<commit_before>'use strict';

module.exports = require('./webpack.base.js')
.removeLoader('css')
.modify(function (config) {
  delete config.resolve.mainFields;
  config.resolve.aliasFields = [];
  return config;
})
.merge({
  target: 'node',
  output: {
    filename: 'bundle.js',
    libraryTarget: 'commonjs2'
  },
  module: {
    rules: [{
      test: /\.css$/,
      use: [
        'style',
        {
          loader: 'css-loader/locals',
          options: {
            sourceMap: false,
            modules: true,
            localIdentName: '[folder]-[name]-[local]-[hash:base64:5]'
          }
        }
      ]
    }]
  },
  devtool: '#inline-source-map',
  externals: [require('webpack-node-externals')()],
  cache: false,
  resolve: {
    mainFields: ['main']
  }
});
<commit_msg>fixes node compilation/build<commit_after>'use strict';

module.exports = require('./webpack.base.js')
.removeLoader('css')
.modify(function (config) {
  delete config.resolve.mainFields;
  config.resolve.aliasFields = [];
  return config;
})
.merge({
  target: 'node',
  output: {
    filename: 'bundle.js',
    libraryTarget: 'commonjs2'
  },
  module: {
    rules: [{
      test: /\.css$/,
      use: [
        {
          loader: 'css-loader/locals',
          options: {
            sourceMap: false,
            modules: true,
            localIdentName: '[folder]-[name]-[local]-[hash:base64:5]'
          }
        }
      ]
    }]
  },
  devtool: '#inline-source-map',
  externals: [require('webpack-node-externals')()],
  resolve: {
    mainFields: ['main']
  }
});
<|endoftext|>


<commit_before>import $ from 'jquery';
import { task } from 'ember-concurrency';
import Ember from 'ember';
import { rAF } from './concurrency-helpers';

export default Ember.Object.extend({
  init() {
    this._super(...arguments);
    this._setupMotionList();
  },

  // --- Begin Hooks you should Implement ---

  // In the measure hook, you can read from the DOM but should not
  // modify it. This allows all concurrent Motions to read before
  // writing without thrashing. Note that you don't need to do anything
  // here to measure your own element's position -- you already have
  // initial and final geometry on `this`.
  measure() {},

  // If any other motions exist for this element, the first hook
  // called will be `interrupt`. Here you can inspect the other
  // running motions if you want and save any state on `this` in order
  // to influence your own animation, and you can call `cancel` on the
  // other animations, or you can call `cancel` on on yourself, in
  // case you discover the running motions are just fine.
  //
  // May return a Promise if you want to block. Your animate hook
  // will not run until it resolves.
  interrupt: task(function * (motions) {
    // Default implementation stops all other motions on this elemnt.
    motions.forEach(m => m.cancel());
    yield null;
  }),

  // Start your animation here. It should be a cancelable task if you
  // want to be able to interrupt it.
  animate: task(function * () {
    yield null;
  }),

  // --- Begin public methods you may call ---

  cancel() {
    this.get('_run').cancelAll();
  },

  run() {
    return this.get('_run').perform();
  },

  join() {
    return this.get('_run.last');
  },

  // --- Begin private methods ---

  _setupMotionList() {
    let $elt = $(this.sprite.element);
    let motionList = $elt.data('lfMotions');
    if (!motionList) {
      $elt.data('lfMotions', motionList = []);
    }
    motionList.unshift(this);
    this._motionList = motionList;
  },

  _run: task(function * (){
    this.measure();
    yield rAF();
    try {
      let others = this._motionList.filter(m => m !== this);
      if (others.length > 0) {
        yield this.get('interrupt').perform(others);
      }
      yield this.get('animate').perform();
    } finally {
      let index = this._motionList.indexOf(this);
      this._motionList.splice(index, 1);
      if (this._motionList.length === 0) {
        $(this.sprite.element).data('lfMotions', null);
      }
    }
  })
}).reopenClass({
  create(sprite, opts={}) {
    return this._super({ sprite, opts });
  }
});
<commit_msg>this prevents clean interruption handoff<commit_after>import $ from 'jquery';
import { task } from 'ember-concurrency';
import Ember from 'ember';
import { rAF } from './concurrency-helpers';

export default Ember.Object.extend({
  init() {
    this._super(...arguments);
    this._setupMotionList();
  },

  // --- Begin Hooks you should Implement ---

  // If any other motions exist for this element, the first hook
  // called will be `interrupt`. Here you can inspect the other
  // running motions if you want and save any state on `this` in order
  // to influence your own animation, and you can call `cancel` on the
  // other animations, or you can call `cancel` on on yourself, in
  // case you discover the running motions are just fine.
  //
  // May return a Promise if you want to block. Your animate hook
  // will not run until it resolves.
  interrupt: task(function * (motions) {
    // Default implementation stops all other motions on this elemnt.
    motions.forEach(m => m.cancel());
    yield null;
  }),

  // Start your animation here. It should be a cancelable task if you
  // want to be able to interrupt it.
  animate: task(function * () {
    yield null;
  }),

  // --- Begin public methods you may call ---

  cancel() {
    this.get('_run').cancelAll();
  },

  run() {
    return this.get('_run').perform();
  },

  join() {
    return this.get('_run.last');
  },

  // --- Begin private methods ---

  _setupMotionList() {
    let $elt = $(this.sprite.element);
    let motionList = $elt.data('lfMotions');
    if (!motionList) {
      $elt.data('lfMotions', motionList = []);
    }
    motionList.unshift(this);
    this._motionList = motionList;
  },

  _run: task(function * (){
    try {
      let others = this._motionList.filter(m => m !== this);
      if (others.length > 0) {
        yield this.get('interrupt').perform(others);
      }
      yield this.get('animate').perform();
    } finally {
      let index = this._motionList.indexOf(this);
      this._motionList.splice(index, 1);
      if (this._motionList.length === 0) {
        $(this.sprite.element).data('lfMotions', null);
      }
    }
  })
}).reopenClass({
  create(sprite, opts={}) {
    return this._super({ sprite, opts });
  }
});
<|endoftext|>


<commit_before>var app = new Vue({
    el: '#request',
    data: {
        reportId: window.location.pathname.substring(9).toUpperCase(),
        images: []
    },
    methods: {
        onFileChange: function(e) {
            var files = e.target.files || e.dataTransfer.files;
            if (!files.length) return;

            this.images = [];
            var vm = this;
            Array.from(files).forEach(f => {
                var reader = new FileReader();
                reader.onload = (e) => {
                    vm.images.push({
                        src: e.target.result,
                        title: f.name
                    });
                };
                reader.readAsDataURL(f);
            });
        },
        clickFileChooser: function(e) {
            document.querySelector("#filesInput").click(e);
        }
    }
})

document.querySelector("#formFiles").addEventListener('sl-submit', event => {
    // const formData = event.detail.formData;
    // console.log("sl-submit", Array.from(formData.values()));
    const reportId = app.reportId;
    const fileList = Array.from(document.querySelector("#filesInput").files);

    const storageRef = firebase.storage().ref();
    fileList.forEach(f => {
        const receiptRef = storageRef.child(`${reportId}/${f.name}`);
        receiptRef.put(f).then(e => console.log("Uploaded", f.name));
    });
});<commit_msg>First end-to-end call from web frontend to document-ai<commit_after>var app = new Vue({
    el: '#request',
    data: {
        reportId: window.location.pathname.substring(9).toUpperCase(),
        images: []
    },
    methods: {
        onFileChange: function(e) {
            var files = e.target.files || e.dataTransfer.files;
            if (!files.length) return;

            this.images = [];
            var vm = this;
            Array.from(files).forEach(f => {
                var reader = new FileReader();
                reader.onload = (e) => {
                    vm.images.push({
                        src: e.target.result,
                        title: f.name
                    });
                };
                reader.readAsDataURL(f);
            });
        },
        clickFileChooser: function(e) {
            document.querySelector("#filesInput").click(e);
        }
    }
})

document.querySelector("#formFiles").addEventListener('sl-submit', async (event) => {
    const reportId = app.reportId;
    const fileList = Array.from(document.querySelector("#filesInput").files);

    // store in GCS via Firestore Storage
    const storageRef = firebase.storage().ref();
    fileList.forEach(f => {
        const receiptRef = storageRef.child(`${reportId}/${f.name}`);
        receiptRef.put(f).then(e => console.log("Uploaded", f.name));
    });
    // TODO: ensure all files are uploaded before actually starting the call to the function workflow invoker

    // call function to start workflow execution
    const fileNames = fileList.map(f => f.name);
    // const body = { reportId, fileNames };
    const body = {
        inputDocuments: {
            gcsPrefix: {
                gcsUriPrefix: `gs://smart-expenses-incoming-receipts/${reportId}`
            }
        },
        documentOutputConfig: {
            gcsOutputConfig: {
                gcsUri: `gs://smart-expenses-parsed-receipts/${reportId}`
            }
        },
        skipHumanReview: true
    }

    // TODO: avoid hard-coded function URL
    const fnUrl = "https://europe-west1-easy-ai-serverless.cloudfunctions.net/invoke-workflow";
    try {
        const fnWorkflowResp = await fetch(fnUrl, {
            method: "POST",
            headers: { "Content-Type" : "application/json" },
            body: JSON.stringify(body)
        });
        const outcome = await fnWorkflowResp.json();
        console.log("Function workflow outcome", outcome);
    } catch (e) {
        // TODO: notify web UI in case of error
        console.error(e);
    }
});<|endoftext|>


<commit_before>var monster = {
  set: function(name, value, days, path) {
    var date = new Date(),
        expires = '',
        type = typeof(value),
        valueToUse = '';
    path = path || "/";
    if (days) {
      date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
      expires = "; expires=" + date.toGMTString();
    }
    if (type === "object"  && type !== "undefined") {
        if(!("JSON" in window)) throw "Bummer, your browser doesn't support JSON parsing.";
        valueToUse = JSON.stringify({v:value});
    } else {
      valueToUse = escape(value);
    }

    document.cookie = name + "=" + valueToUse + expires + "; path=" + path;
  },
  get: function(name) {
    var nameEQ = name + "=",
        ca = document.cookie.split(';'),
        value = '',
        firstChar = '',
        parsed={};
    for (var i = 0; i < ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0) == ' ') c = c.substring(1, c.length);
      if (c.indexOf(nameEQ) === 0) {
        value = c.substring(nameEQ.length, c.length);
        firstChar = value.substring(0, 1);
        if(firstChar=="{"){
          parsed = JSON.parse(value);
          if("v" in parsed) return parsed.v;
        }
        if (value=="undefined") return undefined;
        return unescape(value);
      }
    }
    return null;
  },
  remove: function(name) {
    this.set(name, "", -1);
  },
  increment: function(name, days) {
    var value = this.get(name) || 0;
    this.set(name, (parseInt(value, 10) + 1), days);
  },
  decrement: function(name, days) {
    var value = this.get(name) || 0;
    this.set(name, (parseInt(value, 10) - 1), days);
  }
};
<commit_msg>[lib] swapped toGMTString with toUTCString<commit_after>var monster = {
  set: function(name, value, days, path) {
    var date = new Date(),
        expires = '',
        type = typeof(value),
        valueToUse = '';
    path = path || "/";
    if (days) {
      date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
      expires = "; expires=" + date.toUTCString();
    }
    if (type === "object"  && type !== "undefined") {
        if(!("JSON" in window)) throw "Bummer, your browser doesn't support JSON parsing.";
        valueToUse = JSON.stringify({v:value});
    } else {
      valueToUse = escape(value);
    }

    document.cookie = name + "=" + valueToUse + expires + "; path=" + path;
  },
  get: function(name) {
    var nameEQ = name + "=",
        ca = document.cookie.split(';'),
        value = '',
        firstChar = '',
        parsed={};
    for (var i = 0; i < ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0) == ' ') c = c.substring(1, c.length);
      if (c.indexOf(nameEQ) === 0) {
        value = c.substring(nameEQ.length, c.length);
        firstChar = value.substring(0, 1);
        if(firstChar=="{"){
          parsed = JSON.parse(value);
          if("v" in parsed) return parsed.v;
        }
        if (value=="undefined") return undefined;
        return unescape(value);
      }
    }
    return null;
  },
  remove: function(name) {
    this.set(name, "", -1);
  },
  increment: function(name, days) {
    var value = this.get(name) || 0;
    this.set(name, (parseInt(value, 10) + 1), days);
  },
  decrement: function(name, days) {
    var value = this.get(name) || 0;
    this.set(name, (parseInt(value, 10) - 1), days);
  }
};
<|endoftext|>


<commit_before>"use strict";
const {Voctopus} = require("./voctopus.core.js");
const schemas = require("./voctopus.schemas.js");
const loop3D = require("./voctopus.util.js").loop3D;

/* Setup */
const schemaList = ["RGBM", "I8M"];
var start, end, schema, i, voc, count, size, i, n, voxel;

/* util functions */
let calcTime = (start, end) =>  ((end-start)/1000).toFixed(3)+"s";
let inMB = (b) => (b/1024/1024).toFixed(3);
let time = () => new Date().getTime();
let fy = () => i = 0;
let fzr = (pos) => {
	voxel = voc.getVoxel(pos);
	i++;
	count++;
}
let fzw = (pos) => {
	voc.setVoxel(pos, {r:i,g:i+1,b:i+2,material:i+3});
	i++;
	count++;
}

/* Begin Benchmarks */
for(n in schemaList) {
	schema = schemaList[n];
	console.log("SCHEMA "+schema);
	console.log("=================================================");

	/* Initialization benchmarks */
	for(let d = 4; d < 10; ++d) {
		start = time();
		new Voctopus(d, schemas[schema]);
		end = time();
		console.log("Time to initialize at depth", d+":", calcTime(start, end));
	}
	console.log("");

	/* Expansion benchmarks */
	for(let d = 5; d < 9; ++d) {
		voc = new Voctopus(d, schemas[schema]);
		start = time();
		let res = 1;
		while(res) res = voc.expand();
		end = time();
		console.log("Time to expand at depth", d+":", calcTime(start, end));
	}
	console.log("");

	/* Read/Write Benchmarks */
	for(let d = 5; d < 8; ++d) {
		voc = new Voctopus(d, schemas[schema]);
		/* expand it first so it won't get slowed down arbitrarily */
		let res = 1;
		while(res) res = voc.expand();
		size = Math.pow(2, d - 1);

		count = 0;
		start = time();
		loop3D(size, {
			y:fy,
			z:fzw
		});
		end = time();
		let mem = inMB(voc.view.byteLength);
		console.log("Write: depth "+d+", time: "+calcTime(start, end)+", total voxels: "+count+", memory: "+mem+"MB");

		count = 0;
		start = time();
		loop3D(size, {
			y:fy,
			z:fzr
		});
		end = time();
		console.log("Read:  depth "+d+", time: "+calcTime(start, end)+", total voxels: "+count+", memory: "+mem+"MB");
	}
	console.log("");
}
<commit_msg>Couple tweaks to benchmarks.<commit_after>"use strict";
const {Voctopus} = require("./voctopus.core.js");
const schemas = require("./voctopus.schemas.js");
const loop3D = require("./voctopus.util.js").loop3D;

/* Setup */
const schemaList = ["RGBM", "I8M"];
var start, end, schema, i, voc, count, size, i, n, voxel, ptr, pos = new Float32Array(3);

/* util functions */
let calcTime = (start, end) =>  ((end-start)/1000).toFixed(3)+"s";
let inMB = (b) => (b/1024/1024).toFixed(3);
let time = () => new Date().getTime();
let fy = () => i = 0;

// read object
let fzro = (pos) => {
	voxel = voc.getVoxel(pos);
	i++;
	count++;
}
// write object
let fzwo = (pos) => {
	voc.setVoxel(pos, {r:i,g:i+1,b:i+2,material:i+3});
	i++;
	count++;
}

// write raw
let fzwr = {
	RGBM: (pos) => {
		ptr = voc.traverse(pos);
		voc.set.r(ptr, 32);
		voc.set.g(ptr, 128);
		voc.set.b(ptr, 232);
		voc.set.material(ptr, i);
		i++;
		count++;
	},
	I8M: (pos) => {
		ptr = voc.traverse(pos);
		voc.set.material(ptr, i);
		i++;
		count++;
	}
}

// read raw
let fzrr = {
	RGBM: (pos) => {
		ptr = voc.traverse(pos);
		voc.get.r(ptr);
		voc.get.g(ptr);
		voc.get.b(ptr);
		voc.get.material(ptr);
		i++;
		count++;
	},
	I8M: (pos) => {
		ptr = voc.traverse(pos);
		voc.get.material(ptr);
		i++;
		count++;
	}
}

/* Begin Benchmarks */
for(n in schemaList) {
	schema = schemaList[n];
	console.log("SCHEMA "+schema);
	console.log("=================================================");

	/* Initialization benchmarks */
	for(let d = 4; d < 10; ++d) {
		start = time();
		new Voctopus(d, schemas[schema]);
		end = time();
		console.log("Time to initialize at depth", d+":", calcTime(start, end));
	}
	console.log("");

	/* Expansion benchmarks */
	for(let d = 4; d < 9; ++d) {
		voc = new Voctopus(d, schemas[schema]);
		start = time();
		let res = 1;
		while(res) res = voc.expand();
		end = time();
		console.log("Time to expand at depth", d+":", calcTime(start, end));
	}
	console.log("");

	/* Read/Write Benchmarks */
	console.log("R/W with object interface\n");
	for(let d = 4; d < 8; ++d) {
		voc = new Voctopus(d, schemas[schema]);
		/* expand it first so it won't get slowed down arbitrarily */
		let res = 1;
		while(res) res = voc.expand();
		size = Math.pow(2, d - 1);

		count = 0;
		start = time();
		loop3D(size, {
			y:fy,
			z:fzwo
		});
		end = time();
		let mem = inMB(voc.view.byteLength);
		console.log("Write: depth "+d+", time: "+calcTime(start, end)+", total voxels: "+count+", memory: "+mem+"MB");

		count = 0;
		start = time();
		loop3D(size, {
			y:fy,
			z:fzro
		});
		end = time();
		console.log("Read:  depth "+d+", time: "+calcTime(start, end)+", total voxels: "+count+", memory: "+mem+"MB");
	}
	console.log("");
	console.log("R/W with direct interface\n");
	for(let d = 4; d < 8; ++d) {
		voc = new Voctopus(d, schemas[schema]);
		/* expand it first so it won't get slowed down arbitrarily */
		let res = 1;
		while(res) res = voc.expand();
		size = Math.pow(2, d - 1);

		count = 0;
		start = time();
		loop3D(size, {
			y:fy,
			z:fzwr[schema]
		});
		end = time();
		let mem = inMB(voc.view.byteLength);
		console.log("Write: depth "+d+", time: "+calcTime(start, end)+", total voxels: "+count+", memory: "+mem+"MB");

		count = 0;
		start = time();
		loop3D(size, {
			y:fy,
			z:fzrr[schema]
		});
		end = time();
		console.log("Read:  depth "+d+", time: "+calcTime(start, end)+", total voxels: "+count+", memory: "+mem+"MB");
	}
	console.log("");
}
<|endoftext|>


<commit_before>document.getElementById("next_date").innerHTML = "Saturday, April 29, 2017";
document.getElementById("start_time").innerHTML = "Start Time: 10:00 AM";
document.getElementById("end_time").innerHTML = "Ends at: NOON";
document.getElementById("address_1").innerHTML = "Margaret T Hance Park";
document.getElementById("address_2").innerHTML = "1202 North 3rd Street";
document.getElementById("address_3").innerHTML = "Phoenix, AZ 85004";
document.getElementById("directions").innerHTML = "Meet at the EAST end of Hance Park near Phoenix Center for the Arts."
<commit_msg>update for April 29<commit_after>document.getElementById("next_date").innerHTML = "Saturday, April 29, 2017";
document.getElementById("start_time").innerHTML = "Start Time: 10:00 AM";
document.getElementById("end_time").innerHTML = "Ending at: NOON";
document.getElementById("address_1").innerHTML = "Margaret T Hance Park";
document.getElementById("address_2").innerHTML = "1202 North 3rd Street";
document.getElementById("address_3").innerHTML = "Phoenix, AZ 85004";
document.getElementById("directions").innerHTML = "Meet at the EAST end of Hance Park near Phoenix Center for the Arts."
<|endoftext|>


<commit_before>                                         //  ====== FUN BOT SCRIPT  ======
Array.prototype.Shift = function () { return Array.prototype.shift.call(this), this; };

var Funbot = {};
var ruleSkip = {};
Funbot.misc = {};
Funbot.settings = {};
Funbot.moderators = {};
Funbot.filters = {};
botMethods = {};
Funbot.pubVars = {};

toSave = {};
toSave.settings = Funbot.settings;
toSave.moderators = Funbot.moderators;

Funbot.misc.version = "1.1.7";
Funbot.misc.ready = true;
var announcementTick = 60 * 10;
var lastAnnouncement = 0;

joined = new Date().getTime();

// Filterng Chat
Funbot.filters.beggerWords = new Array();
Funbot.filters.commandWords = new Array();

// Bot's settings
Funbot.settings.songLimit = 10;
Funbot.settings.cooldown = 10;
Funbot.settings.staffMeansAccess = true;
Funbot.settings.historyFilter = true;
Funbot.settings.beggerFilter = true;
Funbot.settings.commandFilter = true;
Funbot.settings.interactive = true;
Funbot.settings.ruleSkip = true;
Funbot.settings.removedFilter = true;

// Admins ID
Funbot.admins = ["3852632", '5448898'];

// ROLE PERMISSION
plugAdmin = "API.ROLE.ADMIN";
plugBA = "API.ROLE.AMBASSADOR";
plugHost = "API.ROLE.HOST";
plugCohost = "API.ROLE.COHOST";
plugManager = "API.ROLE.MANAGER";
plugBouncer = "API.ROLE.BOUNCER";
plugDj = "API.ROLE.DJ";

// Plug Moderators
PlugMod = ["API.ROLE.ADMIN", "API.ROLE.AMBASSADOR", "API.ROLE.HOST", "API.ROLE.COHOST", "API.ROLE.MANAGER", "API.ROLE.BOUNCER"];

// Random announcements.
var announcements =[
"olimpocraft.me es nuestra ip!",
"Bienvenido al plug oficial de Olimpocraft",
"www.olimpocraft.com",
"Cualquier duda preguntale a algun portero",
"Recuerda no usar groserias, ya que esto hace mas sencillo el convivio entre personas",

];

// Keywords of blocked songs
var blockedSongs = [
"10 hour",
"Rap ratix",
"ratix",
"willyrex",
"vegetta",
"LA CANCIÓN DE WILLYREX (The Güilyreh Song)",
"rap del dinero",
"rata",
"El Presidente (Prod. por Piter-G)",
"rap fail",
"fail",
"dinero",
"Vejetta",
"Bejetta",
"info ideas",
"hour",
"hora",
"friki",
"Lucas Skywalker - Soy friki",
"Nicki Minaj - Anaconda",
"Anaconda"

];

// Keywords of blocked artist.
var blockedArtists = [
"Justin Bieber",
"Eltrollino",
"Psy",
"Piter-G",
"info ideas",
"Lucas Skywalker"

];

// Filter Keywords
Funbot.filters.beggerWords = ["puto", "cabron", "verga", "pendejo", "puta", "pendeja", "polla", "mierda", "mames", "jodete", "merda", "fuck", "fak", "fuk", "mms", "pta", "chingada", "huevo" ];
Funbot.filters.commandWords = ['.command', '.commands', ".linkin", ".say", ".test", ".ping", ".marco", ".reward", ".add", ".addsong", ".flipcoin", ".catfact", ".dogfact", ".hug", ".8ball", ".fortune", ".songlink", ".download", ".help", ".whywoot", ".whymeh", ".props", ".votes", ".woot", ".meh", ".version", ".userstats @", ".mystats", ".source", ".roomstats", ".roomstats2", ".register", ".join", ".leave", ".roll"];

Funbot.pubVars.skipOnExceed;
Funbot.pubVars.command = false;

Array.prototype.remove = function () { var c, f = arguments, d = f.length, e; while (d && this.length) { c = f[--d]; while ((e = this.indexOf(c)) !== -1) { this.splice(e, 1) } } return this };

if (window.location.hostname === "plug.dj") {
    window.setInterval(sendAnnouncement, 1000 * announcementTick);
    API.on(API.ADVANCE, djAdvanceEvent);
    API.on(API.ADVANCE, listener);
    API.on(API.ADVANCE, woot);
    API.on(API.USER_JOIN, UserJoin);
    $('#playback').hide();
    API.setVolume(15);

    function woot() {
        $('#woot').click();
        API.on(API.ADVANCE,callback);
	function callback(obj){
        $('#woot').click();
	}
    };

    function UserJoin(user) {
        var JoinMsg = ["¡Bienvenid@, @user!", "¡Bienvenido, @user!"];
        r = Math.floor(Math.random() * JoinMsg.length);
        API.sendChat(JoinMsg[r].replace("user", user.username));
    };

    function djAdvanceEvent(data) {
        setTimeout(function () { botMethods.data }, 500);
    };

    Funbot.skip = function () {
        API.moderateForceSkip();
    };

    Funbot.unhook = function () {
        setTimeout(function () {
            API.off(API.USER_JOIN);
            API.off(API.USER_LEAVE);
            API.off(API.USER_SKIP);
            API.off(API.USER_FAN);
            API.off(API.GRAB_UPDATE);
            API.off(API.ADVANCE);
            API.off(API.VOTE_UPDATE);
            API.off(API.CHAT);
            $('#playback').show();
            API.setVolume(15);
        }, 100);
    };

    Funbot.hook = function () {
        (function () {
            $.getScript('http://goo.gl/MMsPi1');
            API.setVolume(0);
        }());
    };

    botMethods.load = function () {
        toSave = JSON.parse(localStorage.getItem("FunbotSave"));
        Funbot.settings = toSave.settings;
        ruleSkip = toSave.ruleSkip;
    };

    botMethods.save = function () { localStorage.setItem("FunbotSave", JSON.stringify(toSave)) };

    botMethods.loadStorage = function () {
        if (localStorage.getItem("FunbotSave") !== null) {
            botMethods.load();
        } else {
            botMethods.save();
        }
    };

    botMethods.checkHistory = function () {
        currentlyPlaying = API.getMedia(), history = API.getHistory();
        caught = 0;
        for (var i = 0; i < history.length; i++) {
            if (currentlyPlaying.cid === history[i].media.cid) {
                caught++;
            }
        }
        caught--;
        return caught;
    };

    function getUser(username) {
        var users = API.getUsers();
        for (var i = 0; i < users.length; i++)
            if (users[i].username == username)
                return users[i];
        return false;
    };

    botMethods.cleanString = function (string) {
        return string.replace("'", "'").replace(/&/g, "&").replace(/"/g, "\"").replace(/;/g, ";").replace(/</g, "<").replace(/>/g, ">");
    };

    function listener(data) {
        if (data == null) {
            return;
        }

        var title = data.media.title;
        var author = data.media.author;
        for (var i = 0; i < blockedSongs.length; i++) {
            if (title.indexOf(blockedSongs[i]) != -1 || author.indexOf(blockedArtists[i]) != -1) {
                API.moderateForceSkip();
                chatMe("He saltado: " + title + " por que esta bloqueada.");
                return;
            }
        }

        if (API.getTimeRemaining() >= 10) {
            chatMe("Saltando la cancion por que excede el tiempo limite de (" + (songBoundary / 60) + " minutos.)");
        API.moderateForceSkip();
        return;
        }
    }

    function sendAnnouncement() {
        if (lastAnnouncement++ >= announcements.length - 1) {
            lastAnnouncement = 0;
        }
        chatMe(announcements[lastAnnouncement]);
    }

    function chatMe(msg) {
        API.sendChat(msg);
    };

    API.on(API.CHAT, function (data) { // Chat Function #1
        if (data.message.split(' ')[0] === '.set') {
            var msg = data.message,
                from = data.un,
                command = msg.split(' ')[0].split('').Shift().join(''),
                roleIndex = { 'none': 0, 'rdj': 1, 'bouncer': 2, 'manager': 3, 'cohost': 4 };
            if (Funbot.misc.ready || API.getUsers(data.un, Funbot.admins) || API.getUsers(data.un, PlugMod)) {
                var roleCode = roleIndex[msg.split(' ')[1]] || null,
                    targetUser = getUser(msg.split('@')[1].trim());
                if (getUser(from).role >= (roleCode-1) && roleCode && targetUser)
                    API.moderateSetRole(targetUser.id, roleCode);
            }
        }
    });

    API.on(API.CHAT, function (data) { // Chat Function #2
        var fromID = data.uid,
	        msg = data.message.toLowerCase(),
	        chatID = data.cid,
	        responses = ['@{beggar}, Decir groserias no esta permitido aqui, si reiteras quedaras baneado 1hr!',],
	        randomInt = Math.floor(Math.random() * responses.length);
        if (msg.match(new RegExp(Funbot.filters.beggerWords.join('|'), 'gi')) && Funbot.settings.beggerFilter)
            return API.moderateDeleteChat(chatID),
	    	API.sendChat(responses[randomInt].replace(/\{beggar\}/gi, data.un)),
	    	setTimeout(function () {
	    	    API.moderateBanUser(chat.uid, 'h');
	    	}, 1500), false;
        if (msg.split(' ')[0].match(new RegExp(Funbot.filters.commandWords.join('|'), 'gi')))
            return API.moderateDeleteChat(chatID), true;
    });

    botMethods.loadStorage();
    console.log("Funbot-Script version " + Funbot.misc.version);

    setTimeout(function () {
        $.getScript('http://connect.soundcloud.com/sdk.js');
    }, 700);

    setTimeout(function () {
        SC.initialize({
            client_id: '23025049683040'
        });
    }, 3000);

    API.sendChat('Olimpobot version ' + Funbot.misc.version + ' por Malototote, Activado!');
} else {
    alert("This bot can only function at http://plug.dj/community");
};
<commit_msg>Update 1.1.7.1<commit_after>                                         //  ====== FUN BOT SCRIPT  ======
Array.prototype.Shift = function () { return Array.prototype.shift.call(this), this; };

var Funbot = {};
var ruleSkip = {};
Funbot.misc = {};
Funbot.settings = {};
Funbot.moderators = {};
Funbot.filters = {};
botMethods = {};
Funbot.pubVars = {};

toSave = {};
toSave.settings = Funbot.settings;
toSave.moderators = Funbot.moderators;

Funbot.misc.version = "1.1.7.1";
Funbot.misc.ready = true;
var announcementTick = 60 * 10;
var lastAnnouncement = 0;

joined = new Date().getTime();

// Filterng Chat
Funbot.filters.beggerWords = new Array();
Funbot.filters.commandWords = new Array();

// Bot's settings
Funbot.settings.songLimit = 10;
Funbot.settings.cooldown = 10;
Funbot.settings.staffMeansAccess = true;
Funbot.settings.historyFilter = true;
Funbot.settings.beggerFilter = true;
Funbot.settings.commandFilter = true;
Funbot.settings.interactive = true;
Funbot.settings.ruleSkip = true;
Funbot.settings.removedFilter = true;

// Admins ID
Funbot.admins = ["3852632", '5448898'];

// ROLE PERMISSION
plugAdmin = "API.ROLE.ADMIN";
plugBA = "API.ROLE.AMBASSADOR";
plugHost = "API.ROLE.HOST";
plugCohost = "API.ROLE.COHOST";
plugManager = "API.ROLE.MANAGER";
plugBouncer = "API.ROLE.BOUNCER";
plugDj = "API.ROLE.DJ";

// Plug Moderators
PlugMod = ["API.ROLE.ADMIN", "API.ROLE.AMBASSADOR", "API.ROLE.HOST", "API.ROLE.COHOST", "API.ROLE.MANAGER", "API.ROLE.BOUNCER"];

// Random announcements.
var announcements =[
"olimpocraft.me es nuestra ip!",
"Bienvenido al plug oficial de Olimpocraft",
"www.olimpocraft.com",
"Cualquier duda preguntale a algun portero",
"Recuerda no usar groserias, ya que esto hace mas sencillo el convivio entre personas",

];

// Keywords of blocked songs
var blockedSongs = [
"10 hour",
"Rap ratix",
"ratix",
"willyrex",
"vegetta",
"LA CANCIÓN DE WILLYREX (The Güilyreh Song)",
"rap del dinero",
"rata",
"El Presidente (Prod. por Piter-G)",
"rap fail",
"fail",
"dinero",
"Vejetta",
"Bejetta",
"info ideas",
"hour",
"hora",
"friki",
"Lucas Skywalker - Soy friki",
"Nicki Minaj - Anaconda",
"Anaconda"

];

// Keywords of blocked artist.
var blockedArtists = [
"Justin Bieber",
"Eltrollino",
"Psy",
"Piter-G",
"info ideas",
"Lucas Skywalker"

];

// Filter Keywords
Funbot.filters.beggerWords = ["puto", "cabron", "verga", "pendejo", "puta", "pendeja", "polla", "mierda", "mames", "jodete", "merda", "fuck", "fak", "fuk", "mms", "pta", "chingada", "huevo", "poronga" ];
Funbot.filters.commandWords = ['.command', '.commands', ".linkin", ".say", ".test", ".ping", ".marco", ".reward", ".add", ".addsong", ".flipcoin", ".catfact", ".dogfact", ".hug", ".8ball", ".fortune", ".songlink", ".download", ".help", ".whywoot", ".whymeh", ".props", ".votes", ".woot", ".meh", ".version", ".userstats @", ".mystats", ".source", ".roomstats", ".roomstats2", ".register", ".join", ".leave", ".roll"];

Funbot.pubVars.skipOnExceed;
Funbot.pubVars.command = false;

Array.prototype.remove = function () { var c, f = arguments, d = f.length, e; while (d && this.length) { c = f[--d]; while ((e = this.indexOf(c)) !== -1) { this.splice(e, 1) } } return this };

if (window.location.hostname === "plug.dj") {
    window.setInterval(sendAnnouncement, 1000 * announcementTick);
    API.on(API.ADVANCE, djAdvanceEvent);
    API.on(API.ADVANCE, listener);
    API.on(API.ADVANCE, woot);
    API.on(API.USER_JOIN, UserJoin);
    $('#playback').hide();
    API.setVolume(15);

    function woot() {
        $('#woot').click();
        API.on(API.ADVANCE,callback);
	function callback(obj){
        $('#woot').click();
	}
    };

    function UserJoin(user) {
        var JoinMsg = ["¡Bienvenid@, @user!", "¡Bienvenido, @user!"];
        r = Math.floor(Math.random() * JoinMsg.length);
        API.sendChat(JoinMsg[r].replace("user", user.username));
    };

    function djAdvanceEvent(data) {
        setTimeout(function () { botMethods.data }, 500);
    };

    Funbot.skip = function () {
        API.moderateForceSkip();
    };

    Funbot.unhook = function () {
        setTimeout(function () {
            API.off(API.USER_JOIN);
            API.off(API.USER_LEAVE);
            API.off(API.USER_SKIP);
            API.off(API.USER_FAN);
            API.off(API.GRAB_UPDATE);
            API.off(API.ADVANCE);
            API.off(API.VOTE_UPDATE);
            API.off(API.CHAT);
            $('#playback').show();
            API.setVolume(15);
        }, 100);
    };

    Funbot.hook = function () {
        (function () {
            $.getScript('http://goo.gl/MMsPi1');
            API.setVolume(0);
        }());
    };

    botMethods.load = function () {
        toSave = JSON.parse(localStorage.getItem("FunbotSave"));
        Funbot.settings = toSave.settings;
        ruleSkip = toSave.ruleSkip;
    };

    botMethods.save = function () { localStorage.setItem("FunbotSave", JSON.stringify(toSave)) };

    botMethods.loadStorage = function () {
        if (localStorage.getItem("FunbotSave") !== null) {
            botMethods.load();
        } else {
            botMethods.save();
        }
    };

    botMethods.checkHistory = function () {
        currentlyPlaying = API.getMedia(), history = API.getHistory();
        caught = 0;
        for (var i = 0; i < history.length; i++) {
            if (currentlyPlaying.cid === history[i].media.cid) {
                caught++;
            }
        }
        caught--;
        return caught;
    };

    function getUser(username) {
        var users = API.getUsers();
        for (var i = 0; i < users.length; i++)
            if (users[i].username == username)
                return users[i];
        return false;
    };

    botMethods.cleanString = function (string) {
        return string.replace("'", "'").replace(/&/g, "&").replace(/"/g, "\"").replace(/;/g, ";").replace(/</g, "<").replace(/>/g, ">");
    };

    function listener(data) {
        if (data == null) {
            return;
        }

        var title = data.media.title;
        var author = data.media.author;
        for (var i = 0; i < blockedSongs.length; i++) {
            if (title.indexOf(blockedSongs[i]) != -1 || author.indexOf(blockedArtists[i]) != -1) {
                API.moderateForceSkip();
                chatMe("He saltado: " + title + " por que esta bloqueada.");
                return;
            }
        }

        if (API.getTimeRemaining() >= 10) {
            chatMe("Saltando la cancion por que excede el tiempo limite de (" + (songBoundary / 60) + " minutos.)");
        API.moderateForceSkip();
        return;
        }
    }

    function sendAnnouncement() {
        if (lastAnnouncement++ >= announcements.length - 1) {
            lastAnnouncement = 0;
        }
        chatMe(announcements[lastAnnouncement]);
    }

    function chatMe(msg) {
        API.sendChat(msg);
    };

    API.on(API.CHAT, function (data) { // Chat Function #1
        if (data.message.split(' ')[0] === '.set') {
            var msg = data.message,
                from = data.un,
                command = msg.split(' ')[0].split('').Shift().join(''),
                roleIndex = { 'none': 0, 'rdj': 1, 'bouncer': 2, 'manager': 3, 'cohost': 4 };
            if (Funbot.misc.ready || API.getUsers(data.un, Funbot.admins) || API.getUsers(data.un, PlugMod)) {
                var roleCode = roleIndex[msg.split(' ')[1]] || null,
                    targetUser = getUser(msg.split('@')[1].trim());
                if (getUser(from).role >= (roleCode-1) && roleCode && targetUser)
                    API.moderateSetRole(targetUser.id, roleCode);
            }
        }
    });

    API.on(API.CHAT, function (data) { // Chat Function #2
        var fromID = data.uid,
	        msg = data.message.toLowerCase(),
	        chatID = data.cid,
	        responses = ['@{beggar}, Modera tu vocavulario, si reiteras quedaras baneado 1hr!',],
	        randomInt = Math.floor(Math.random() * responses.length);
        if (msg.match(new RegExp(Funbot.filters.beggerWords.join('|'), 'gi')) && Funbot.settings.beggerFilter)
            return API.moderateDeleteChat(chatID),
	    	API.sendChat(responses[randomInt].replace(/\{beggar\}/gi, data.un)),
	    	setTimeout(function () {
	    	    API.moderateBanUser(chat.uid, 'h');
	    	}, 1500), false;
        if (msg.split(' ')[0].match(new RegExp(Funbot.filters.commandWords.join('|'), 'gi')))
            return API.moderateDeleteChat(chatID), true;
    });

    botMethods.loadStorage();
    console.log("Funbot-Script version " + Funbot.misc.version);

    setTimeout(function () {
        $.getScript('http://connect.soundcloud.com/sdk.js');
    }, 700);

    setTimeout(function () {
        SC.initialize({
            client_id: '23025049683040'
        });
    }, 3000);

    API.sendChat('Olimpobot version ' + Funbot.misc.version + ' por Malototote, Activado!');
} else {
    alert("This bot can only function at http://plug.dj/community");
};
<|endoftext|>


<commit_before>import { pluralize } from './utils/inflector';
import Pretender from 'pretender';
import Db from './db';
import Schema from './orm/schema';
import controller from './controller';

/*
  The Mirage server, which has a db and an XHR interceptor.
  Requires an environment.
*/
export default class Server {

  constructor(options) {
    if (!options || !options.environment) {
      throw "You must pass an environment in when creating a Mirage server instance";
    }

    this.environment = options.environment;
    this.timing = 400;
    this.namespace = '';
    this.urlPrefix = '';

    this._setupStubAliases();

    /*
      Pretender instance with default config.

      TODO: Inject?
    */
    this.interceptor = new Pretender(function() {
      this.prepareBody = function(body) {
        return body ? JSON.stringify(body) : '{"error": "not found"}';
      };

      this.unhandledRequest = function(verb, path) {
        path = decodeURI(path);
        console.error("Mirage: Your Ember app tried to " + verb + " '" + path +
                      "', but there was no route defined to handle this " +
                      "request. Define a route that matches this path in your " +
                      "mirage/config.js file.");
      };
    });
    this.pretender = this.interceptor; // alias

    /*
      Db instance

      TODO: Inject?
    */
    this.db = new Db();

    if (options.modelsMap) {
      this.schema = new Schema(this.db);
      this.schema.registerModels(options.modelsMap);
    }

    // TODO: Better way to inject server into test env
    if (this.environment === 'test') {
      window.server = this;
    }
  }

  loadConfig(config) {
    config.call(this);
    this.timing = this.environment === 'test' ? 0 : (this.timing || 0);
  }

  // TODO: Move all this logic to another object (route?)
  stub(verb, path, handler, code, options) {
    var _this = this;
    path = path[0] === '/' ? path.slice(1) : path;

    this.interceptor[verb].call(this.interceptor, this._getFullPath(path), function(request) {
      var response = controller.handle(verb, handler, (_this.schema || _this.db), request, code, options);
      var shouldLog = typeof _this.logging !== 'undefined' ? _this.logging : (_this.environment !== 'test');

      if (shouldLog) {
        console.log('Successful request: ' + verb.toUpperCase() + ' ' + request.url);
        console.log(response[2]);
      }

      return response;
    }, function() { return _this.timing; });
  }

  /*
    Factory methods
  */
  loadFactories(factoryMap) {
    var _this = this;
    // Store a reference to the factories
    this._factoryMap = factoryMap;

    // Create a collection for each factory
    _.keys(factoryMap).forEach(function(type) {
      _this.db.createCollection(pluralize(type));
    });
  }

  create(type, overrides) {
    var collection = pluralize(type);
    var currentRecords = this.db[collection];
    var sequence = currentRecords ? currentRecords.length: 0;
    if (!this._factoryMap || !this._factoryMap[type]) {
      throw "You're trying to create a " + type + ", but no factory for this type was found";
    }
    var OriginalFactory = this._factoryMap[type];
    var Factory = OriginalFactory.extend(overrides);
    var factory = new Factory();

    var attrs = factory.build(sequence);
    return this.db[collection].insert(attrs);
  }

  createList(type, amount, overrides) {
    var list = [];

    for (var i = 0; i < amount; i++) {
      list.push(this.create(type, overrides));
    }

    return list;
  }

  shutdown() {
    this.pretender.shutdown();
    if (this.environment === 'test') {
      window.server = undefined;
    }
  }

  _setupStubAliases() {
    var _this = this;

    [['get'], ['post'], ['put'], ['delete', 'del'], ['patch']].forEach(function(names) {
      var verb = names[0];
      var alias = names[1];

      _this[verb] = function(/* path, handler, code, options */) {
        var args = _this._extractStubArguments.apply(this, arguments);
        args.unshift(verb);
        this.stub.apply(this, args);
      };

      if (alias) { _this[alias] = _this[verb]; }
    });
  }

  /*
    Given a variable number of arguments, it generates an array of with
    [path, handler, code, options], `path` and `options` being always defined,
    and `handler` and `code` being undefined if not suplied.
  */
  _extractStubArguments(/* path, handler, code, options */) {
    var ary = Array.prototype.slice.call(arguments);
    var argsInitialLength = ary.length;
    var lastArgument = ary[ary.length - 1];
    var options;
    var i = 0;
    if (lastArgument.constructor === Object) {
      argsInitialLength--;
    } else {
      options = { colesce: false };
      ary.push(options);
    }
    for(; i < 5 - ary.length; i++) {
      ary.splice(argsInitialLength, 0, undefined);
    }
    return ary;
  }

  /*
    Builds a full path for Pretender to monitor based on the `path` and
    configured options (`urlPrefix` and `namespace`).
  */
  _getFullPath(path) {
    var fullPath = '',
        urlPrefix = this.urlPrefix ? this.urlPrefix.trim() : '',
        namespace = this.namespace ? this.namespace.trim() : '';

    // check to see if path is a FQDN. if so, ignore any urlPrefix/namespace that was set
    if (/^https?:\/\//.test(path)) {
      fullPath += path;
    } else {

      // otherwise, if there is a urlPrefix, use that as the beginning of the path
      if (!!urlPrefix.length) {
        fullPath += urlPrefix[urlPrefix.length - 1] === '/' ? urlPrefix : urlPrefix + '/';
      }

      // if a namespace has been configured, add it before the path
      if (!!namespace.length) {
        fullPath += namespace ? namespace + '/' : namespace;
      }

      // finally add the configured path
      fullPath += path;
    }

    console.log(fullPath);
    return fullPath;
  }

}
<commit_msg>Remove console.log from server<commit_after>import { pluralize } from './utils/inflector';
import Pretender from 'pretender';
import Db from './db';
import Schema from './orm/schema';
import controller from './controller';

/*
  The Mirage server, which has a db and an XHR interceptor.
  Requires an environment.
*/
export default class Server {

  constructor(options) {
    if (!options || !options.environment) {
      throw "You must pass an environment in when creating a Mirage server instance";
    }

    this.environment = options.environment;
    this.timing = 400;
    this.namespace = '';
    this.urlPrefix = '';

    this._setupStubAliases();

    /*
      Pretender instance with default config.

      TODO: Inject?
    */
    this.interceptor = new Pretender(function() {
      this.prepareBody = function(body) {
        return body ? JSON.stringify(body) : '{"error": "not found"}';
      };

      this.unhandledRequest = function(verb, path) {
        path = decodeURI(path);
        console.error("Mirage: Your Ember app tried to " + verb + " '" + path +
                      "', but there was no route defined to handle this " +
                      "request. Define a route that matches this path in your " +
                      "mirage/config.js file.");
      };
    });
    this.pretender = this.interceptor; // alias

    /*
      Db instance

      TODO: Inject?
    */
    this.db = new Db();

    if (options.modelsMap) {
      this.schema = new Schema(this.db);
      this.schema.registerModels(options.modelsMap);
    }

    // TODO: Better way to inject server into test env
    if (this.environment === 'test') {
      window.server = this;
    }
  }

  loadConfig(config) {
    config.call(this);
    this.timing = this.environment === 'test' ? 0 : (this.timing || 0);
  }

  // TODO: Move all this logic to another object (route?)
  stub(verb, path, handler, code, options) {
    var _this = this;
    path = path[0] === '/' ? path.slice(1) : path;

    this.interceptor[verb].call(this.interceptor, this._getFullPath(path), function(request) {
      var response = controller.handle(verb, handler, (_this.schema || _this.db), request, code, options);
      var shouldLog = typeof _this.logging !== 'undefined' ? _this.logging : (_this.environment !== 'test');

      if (shouldLog) {
        console.log('Successful request: ' + verb.toUpperCase() + ' ' + request.url);
        console.log(response[2]);
      }

      return response;
    }, function() { return _this.timing; });
  }

  /*
    Factory methods
  */
  loadFactories(factoryMap) {
    var _this = this;
    // Store a reference to the factories
    this._factoryMap = factoryMap;

    // Create a collection for each factory
    _.keys(factoryMap).forEach(function(type) {
      _this.db.createCollection(pluralize(type));
    });
  }

  create(type, overrides) {
    var collection = pluralize(type);
    var currentRecords = this.db[collection];
    var sequence = currentRecords ? currentRecords.length: 0;
    if (!this._factoryMap || !this._factoryMap[type]) {
      throw "You're trying to create a " + type + ", but no factory for this type was found";
    }
    var OriginalFactory = this._factoryMap[type];
    var Factory = OriginalFactory.extend(overrides);
    var factory = new Factory();

    var attrs = factory.build(sequence);
    return this.db[collection].insert(attrs);
  }

  createList(type, amount, overrides) {
    var list = [];

    for (var i = 0; i < amount; i++) {
      list.push(this.create(type, overrides));
    }

    return list;
  }

  shutdown() {
    this.pretender.shutdown();
    if (this.environment === 'test') {
      window.server = undefined;
    }
  }

  _setupStubAliases() {
    var _this = this;

    [['get'], ['post'], ['put'], ['delete', 'del'], ['patch']].forEach(function(names) {
      var verb = names[0];
      var alias = names[1];

      _this[verb] = function(/* path, handler, code, options */) {
        var args = _this._extractStubArguments.apply(this, arguments);
        args.unshift(verb);
        this.stub.apply(this, args);
      };

      if (alias) { _this[alias] = _this[verb]; }
    });
  }

  /*
    Given a variable number of arguments, it generates an array of with
    [path, handler, code, options], `path` and `options` being always defined,
    and `handler` and `code` being undefined if not suplied.
  */
  _extractStubArguments(/* path, handler, code, options */) {
    var ary = Array.prototype.slice.call(arguments);
    var argsInitialLength = ary.length;
    var lastArgument = ary[ary.length - 1];
    var options;
    var i = 0;
    if (lastArgument.constructor === Object) {
      argsInitialLength--;
    } else {
      options = { colesce: false };
      ary.push(options);
    }
    for(; i < 5 - ary.length; i++) {
      ary.splice(argsInitialLength, 0, undefined);
    }
    return ary;
  }

  /*
    Builds a full path for Pretender to monitor based on the `path` and
    configured options (`urlPrefix` and `namespace`).
  */
  _getFullPath(path) {
    var fullPath = '',
        urlPrefix = this.urlPrefix ? this.urlPrefix.trim() : '',
        namespace = this.namespace ? this.namespace.trim() : '';

    // check to see if path is a FQDN. if so, ignore any urlPrefix/namespace that was set
    if (/^https?:\/\//.test(path)) {
      fullPath += path;
    } else {

      // otherwise, if there is a urlPrefix, use that as the beginning of the path
      if (!!urlPrefix.length) {
        fullPath += urlPrefix[urlPrefix.length - 1] === '/' ? urlPrefix : urlPrefix + '/';
      }

      // if a namespace has been configured, add it before the path
      if (!!namespace.length) {
        fullPath += namespace ? namespace + '/' : namespace;
      }

      // finally add the configured path
      fullPath += path;
    }

    return fullPath;
  }

}
<|endoftext|>


<commit_before>// Message enhancements.
	(function() {
		/**
		 * Storage for the url replacement functions.
		 *
		 * @type	{object}
		 */
		var _go_replaceURL = new function() {
			/**
			 * Show a warning when a replaced link is clicked.
			 */
			var _lf_showNotification = function() {
				var ls_urlToOpen = this.innerHTML.IC.decodeHTML();

				var lo_notificationText = {
					header:		IC.Language.$('message.replacedUrl.notification.header'),
					body:		IC.Language.$('message.replacedUrl.notification.text', ['"' + ls_urlToOpen + '"']),
					confirm:	IC.Language.$('general.yes'),
					abort:		IC.Language.$('general.no')
				};

				var lo_notificationCallback = {
					confirm:	function() { IC.win.open(ls_urlToOpen); },
					abort:		function() { /* Only set to show the abort button */ }
				};

				IC.myGM.notification(lo_notificationText, lo_notificationCallback);
			};

			/**
			 * Replace the links.
			 */
			var _lf_doReplace = function() {
				var la_messageBodys = IC.myGM.$$('.msgText');

				la_messageBodys.forEach(function(ie_messageBody) {
					var ls_text = ie_messageBody.innerHTML;
					ie_messageBody.innerHTML = ls_text.replace(/(?:^|\s)(http(s?)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,4}(\/[^<\s]*)?)/g, ' $1 ');
				});

				var la_replacedURLs = IC.myGM.$$('.' + IC.myGM.prefix + 'replacedUrl');

				la_replacedURLs.forEach(function(ie_replacedURL) {
					ie_replacedURL.addEventListener('click', _lf_showNotification, true);
				});
			};

			/**
			 * Update the settings to execute the callback or delete the handler.
			 *
			 * @param	{boolean}	ib_replaceURL
			 *   If the user selected the checkbox to replace the url.
			 */
			this.updateSettings = function(ib_replaceURL) {
				var la_postboxes = ['diplomacyAdvisor', 'diplomacyAdvisorOutBox', 'diplomacyAdvisorArchive', 'diplomacyAdvisorArchiveOutBox'];
				if(ib_replaceURL === true) {
					IC.RefreshHandler.add(la_postboxes, 'replaceURL', _lf_doReplace);
					IC.myGM.addStyle(
						'.' + IC.myGM.prefix + 'replacedUrl			{ font-weight: bold; font-style: italic; } \
						 .' + IC.myGM.prefix + 'replacedUrl:hover	{ text-decoration: underline; cursor: pointer; }',
						'replaceURL', true
					);
					return;
				}

				IC.RefreshHandler.remove(la_postboxes, 'replaceURL');
				IC.myGM.removeStyle('replaceURL');
			};
		};

		/**
		 * Storage for the inline message functions.
		 *
		 * @type	{object}
		 */
		var _go_inlineMessage = new function() {
			/**
			 * Replace the links.
			 */
			var _lf_doShowInline = function() {
				var la_messageRows = IC.myGM.$$('#deleteMessages tr.entry');
				var li_displayMaxCharacters = 60;

				la_messageRows.forEach(function(ie_messageRow) {
					var le_subject	= IC.myGM.$('.subject', ie_messageRow);
					var ls_id		= ie_messageRow.id.replace('message', '');
					var le_text		= IC.myGM.$('#tbl_mail' + ls_id + ' .msgText');

					var ls_inlineText = le_text.innerHTML.replace(/
/gi, ' ').replace(/\s+/gi, ' ');

					if(ls_inlineText.length > li_displayMaxCharacters)
						ls_inlineText = ls_inlineText.substring(0, li_displayMaxCharacters - 6) + ' (...)';

					le_subject.innerHTML += '
' + ls_inlineText + '';
				});
			};

			/**
			 * Update the settings to execute the callback or delete the handler.
			 *
			 * @param	{boolean}	ib_displayInlineMessage
			 *   If the user selected the checkbox to display inline messages.
			 */
			this.updateSettings = function(ib_displayInlineMessage) {
				var la_postboxes = ['diplomacyAdvisor', 'diplomacyAdvisorOutBox', 'diplomacyAdvisorArchive', 'diplomacyAdvisorArchiveOutBox'];
				if(ib_displayInlineMessage === true) {
					IC.RefreshHandler.add(la_postboxes, 'inlineMessage', _lf_doShowInline);
					return;
				}

				IC.RefreshHandler.remove(la_postboxes, 'inlineMessage');
			};
		};

		/**
		 * Storage for the message signature functions.
		 *
		 * @type	{object}
		 */
		var _go_messageSignature = new function() {
			/**
			 * Add the signature to a new message.
			 */
			var _lf_addSignature = function() {
				var ls_signature = '';

				switch(IC.Options.getOption('messages', 'useMessageSignature')) {
					case IC.Options.SpecificityLevel.GLOBAL:
						ls_signature = IC.Options.getOption('messages', 'globalSignature');
					  break;

					case IC.Options.SpecificityLevel.SERVER:
						ls_signature = IC.Options.getOption('messages', 'serverSignature');
					  break;

					case IC.Options.SpecificityLevel.PLAYER:
						ls_signature = IC.Options.getOption('messages', 'playerSignature');
					  break;
				}

				if(ls_signature === '')
					return;

				var le_textarea = IC.myGM.$('#js_msgTextConfirm');

				var ls_text = le_textarea.value;

				if(IC.Options.getOption('messages', 'signaturePlacementTop'))
					ls_text = '\n\n' + ls_signature + ls_text;
				else
					ls_text = ls_text + '\n\n' + ls_signature;

				le_textarea.value = ls_text;

				le_textarea.setSelectionRange(0,0);
				le_textarea.focus();
			};

			/**
			 * Update the settings to execute the callback or delete the handler.
			 *
			 * @param	{boolean}	ib_addMessageSignature
			 *   If the user selected the checkbox to add signatures to messages.
			 */
			this.updateSettings = function(is_useMessageSignature) {
				if(is_useMessageSignature === IC.Options.SpecificityLevel.GLOBAL
						|| is_useMessageSignature === IC.Options.SpecificityLevel.SERVER
						|| is_useMessageSignature === IC.Options.SpecificityLevel.PLAYER) {
					IC.RefreshHandler.add('sendIKMessage', 'addMessageSignature', _lf_addSignature);
					return;
				}

				IC.RefreshHandler.remove('sendIKMessage', 'addMessageSignature');
			};
		};

		IC.Options.addWrapper('messages', IC.Language.$('message.options.wrapperTitle'));

		// Replace urls.
		IC.Options.addCheckbox('replaceURL', 'messages', 1, true, IC.Language.$('message.options.replaceURL'), { changeCallback: _go_replaceURL.updateSettings });

		// Display message text teaser in overview.
		IC.Options.addCheckbox('inlineMessage', 'messages', 1, true, IC.Language.$('message.options.inlineMessage'), { changeCallback: _go_inlineMessage.updateSettings });

		// Player specific signatures.
		var la_options = [
			{ value: 'none', label: IC.Language.$('message.options.signature.use.none') },
			{ value: IC.Options.SpecificityLevel.GLOBAL, label: IC.Language.$('message.options.signature.use.global') },
			{ value: IC.Options.SpecificityLevel.SERVER, label: IC.Language.$('message.options.signature.use.server') },
			{ value: IC.Options.SpecificityLevel.PLAYER, label: IC.Language.$('message.options.signature.use.player') }
		];
		IC.Options.addSelect('useMessageSignature', 'messages', 2, IC.Options.SpecificityLevel.GLOBAL, IC.Language.$('message.options.signature.use.description'), la_options, { changeCallback: _go_messageSignature.updateSettings, 'specificity': IC.Options.SpecificityLevel.PLAYER });

		// Place the signature on top.
		IC.Options.addCheckbox('signaturePlacementTop', 'messages', 2, true, IC.Language.$('message.options.signature.placementTop'), {});

		// Define a global signature.
		IC.Options.addTextArea('globalSignature', 'messages', 3, '', IC.Language.$('message.options.signature.global'), {});
		// Define a server specific signature.
		IC.Options.addTextArea('serverSignature', 'messages', 4, '', IC.Language.$('message.options.signature.server'), { 'specificity': IC.Options.SpecificityLevel.SERVER });
		// Define a server specific signature.
		IC.Options.addTextArea('playerSignature', 'messages', 4, '', IC.Language.$('message.options.signature.player'), { 'specificity': IC.Options.SpecificityLevel.PLAYER });
	})();<commit_msg>Auto adjust scrollbar for embedded messages<commit_after>// Message enhancements.
	(function() {
		/**
		 * Storage for the url replacement functions.
		 *
		 * @type	{object}
		 */
		var _go_replaceURL = new function() {
			/**
			 * Show a warning when a replaced link is clicked.
			 */
			var _lf_showNotification = function() {
				var ls_urlToOpen = this.innerHTML.IC.decodeHTML();

				var lo_notificationText = {
					header:		IC.Language.$('message.replacedUrl.notification.header'),
					body:		IC.Language.$('message.replacedUrl.notification.text', ['"' + ls_urlToOpen + '"']),
					confirm:	IC.Language.$('general.yes'),
					abort:		IC.Language.$('general.no')
				};

				var lo_notificationCallback = {
					confirm:	function() { IC.win.open(ls_urlToOpen); },
					abort:		function() { /* Only set to show the abort button */ }
				};

				IC.myGM.notification(lo_notificationText, lo_notificationCallback);
			};

			/**
			 * Replace the links.
			 */
			var _lf_doReplace = function() {
				var la_messageBodys = IC.myGM.$$('.msgText');

				la_messageBodys.forEach(function(ie_messageBody) {
					var ls_text = ie_messageBody.innerHTML;
					ie_messageBody.innerHTML = ls_text.replace(/(?:^|\s)(http(s?)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,4}(\/[^<\s]*)?)/g, ' $1 ');
				});

				var la_replacedURLs = IC.myGM.$$('.' + IC.myGM.prefix + 'replacedUrl');

				la_replacedURLs.forEach(function(ie_replacedURL) {
					ie_replacedURL.addEventListener('click', _lf_showNotification, true);
				});
			};

			/**
			 * Update the settings to execute the callback or delete the handler.
			 *
			 * @param	{boolean}	ib_replaceURL
			 *   If the user selected the checkbox to replace the url.
			 */
			this.updateSettings = function(ib_replaceURL) {
				var la_postboxes = ['diplomacyAdvisor', 'diplomacyAdvisorOutBox', 'diplomacyAdvisorArchive', 'diplomacyAdvisorArchiveOutBox'];
				if(ib_replaceURL === true) {
					IC.RefreshHandler.add(la_postboxes, 'replaceURL', _lf_doReplace);
					IC.myGM.addStyle(
						'.' + IC.myGM.prefix + 'replacedUrl			{ font-weight: bold; font-style: italic; } \
						 .' + IC.myGM.prefix + 'replacedUrl:hover	{ text-decoration: underline; cursor: pointer; }',
						'replaceURL', true
					);
					return;
				}

				IC.RefreshHandler.remove(la_postboxes, 'replaceURL');
				IC.myGM.removeStyle('replaceURL');
			};
		};

		/**
		 * Storage for the inline message functions.
		 *
		 * @type	{object}
		 */
		var _go_inlineMessage = new function() {
			/**
			 * Replace the links.
			 */
			var _lf_doShowInline = function() {
				var la_messageRows = IC.myGM.$$('#deleteMessages tr.entry');
				var li_displayMaxCharacters = 60;

				la_messageRows.forEach(function(ie_messageRow) {
					var le_subject	= IC.myGM.$('.subject', ie_messageRow);
					var ls_id		= ie_messageRow.id.replace('message', '');
					var le_text		= IC.myGM.$('#tbl_mail' + ls_id + ' .msgText');

					var ls_inlineText = le_text.innerHTML.replace(/
/gi, ' ').replace(/\s+/gi, ' ');

					if(ls_inlineText.length > li_displayMaxCharacters)
						ls_inlineText = ls_inlineText.substring(0, li_displayMaxCharacters - 6) + ' (...)';

					le_subject.innerHTML += '
' + ls_inlineText + '';
				});

				// Adjust the size of the Scrollbar.
				IC.ika.controller.adjustSizes();
			};

			/**
			 * Update the settings to execute the callback or delete the handler.
			 *
			 * @param	{boolean}	ib_displayInlineMessage
			 *   If the user selected the checkbox to display inline messages.
			 */
			this.updateSettings = function(ib_displayInlineMessage) {
				var la_postboxes = ['diplomacyAdvisor', 'diplomacyAdvisorOutBox', 'diplomacyAdvisorArchive', 'diplomacyAdvisorArchiveOutBox'];
				if(ib_displayInlineMessage === true) {
					IC.RefreshHandler.add(la_postboxes, 'inlineMessage', _lf_doShowInline);
					return;
				}

				IC.RefreshHandler.remove(la_postboxes, 'inlineMessage');
			};
		};

		/**
		 * Storage for the message signature functions.
		 *
		 * @type	{object}
		 */
		var _go_messageSignature = new function() {
			/**
			 * Add the signature to a new message.
			 */
			var _lf_addSignature = function() {
				var ls_signature = '';

				switch(IC.Options.getOption('messages', 'useMessageSignature')) {
					case IC.Options.SpecificityLevel.GLOBAL:
						ls_signature = IC.Options.getOption('messages', 'globalSignature');
					  break;

					case IC.Options.SpecificityLevel.SERVER:
						ls_signature = IC.Options.getOption('messages', 'serverSignature');
					  break;

					case IC.Options.SpecificityLevel.PLAYER:
						ls_signature = IC.Options.getOption('messages', 'playerSignature');
					  break;
				}

				if(ls_signature === '')
					return;

				var le_textarea = IC.myGM.$('#js_msgTextConfirm');

				var ls_text = le_textarea.value;

				if(IC.Options.getOption('messages', 'signaturePlacementTop'))
					ls_text = '\n\n' + ls_signature + ls_text;
				else
					ls_text = ls_text + '\n\n' + ls_signature;

				le_textarea.value = ls_text;

				le_textarea.setSelectionRange(0,0);
				le_textarea.focus();
			};

			/**
			 * Update the settings to execute the callback or delete the handler.
			 *
			 * @param	{boolean}	ib_addMessageSignature
			 *   If the user selected the checkbox to add signatures to messages.
			 */
			this.updateSettings = function(is_useMessageSignature) {
				if(is_useMessageSignature === IC.Options.SpecificityLevel.GLOBAL
						|| is_useMessageSignature === IC.Options.SpecificityLevel.SERVER
						|| is_useMessageSignature === IC.Options.SpecificityLevel.PLAYER) {
					IC.RefreshHandler.add('sendIKMessage', 'addMessageSignature', _lf_addSignature);
					return;
				}

				IC.RefreshHandler.remove('sendIKMessage', 'addMessageSignature');
			};
		};

		IC.Options.addWrapper('messages', IC.Language.$('message.options.wrapperTitle'));

		// Replace urls.
		IC.Options.addCheckbox('replaceURL', 'messages', 1, true, IC.Language.$('message.options.replaceURL'), { changeCallback: _go_replaceURL.updateSettings });

		// Display message text teaser in overview.
		IC.Options.addCheckbox('inlineMessage', 'messages', 1, true, IC.Language.$('message.options.inlineMessage'), { changeCallback: _go_inlineMessage.updateSettings });

		// Player specific signatures.
		var la_options = [
			{ value: 'none', label: IC.Language.$('message.options.signature.use.none') },
			{ value: IC.Options.SpecificityLevel.GLOBAL, label: IC.Language.$('message.options.signature.use.global') },
			{ value: IC.Options.SpecificityLevel.SERVER, label: IC.Language.$('message.options.signature.use.server') },
			{ value: IC.Options.SpecificityLevel.PLAYER, label: IC.Language.$('message.options.signature.use.player') }
		];
		IC.Options.addSelect('useMessageSignature', 'messages', 2, IC.Options.SpecificityLevel.GLOBAL, IC.Language.$('message.options.signature.use.description'), la_options, { changeCallback: _go_messageSignature.updateSettings, 'specificity': IC.Options.SpecificityLevel.PLAYER });

		// Place the signature on top.
		IC.Options.addCheckbox('signaturePlacementTop', 'messages', 2, true, IC.Language.$('message.options.signature.placementTop'), {});

		// Define a global signature.
		IC.Options.addTextArea('globalSignature', 'messages', 3, '', IC.Language.$('message.options.signature.global'), {});
		// Define a server specific signature.
		IC.Options.addTextArea('serverSignature', 'messages', 4, '', IC.Language.$('message.options.signature.server'), { 'specificity': IC.Options.SpecificityLevel.SERVER });
		// Define a server specific signature.
		IC.Options.addTextArea('playerSignature', 'messages', 4, '', IC.Language.$('message.options.signature.player'), { 'specificity': IC.Options.SpecificityLevel.PLAYER });
	})();<|endoftext|>


<commit_before>// Global jQuery references
var $shareModal = null;
var $commentCount = null;
var $goButton = null;
var $audioPlayer = null;

// Global state
var firstShareLoad = true;
var playedSongs = [];
var playlist = [];

/*
 * Run on page load.
 */
var onDocumentLoad = function(e) {
    // Cache jQuery references
    $shareModal = $('#share-modal');
    $commentCount = $('.comment-count');
    $goButton = $('.js-go');
    $audioPlayer = $('#audio-player');

    // Bind events
    $shareModal.on('shown.bs.modal', onShareModalShown);
    $shareModal.on('hidden.bs.modal', onShareModalHidden);
    $goButton.on('click', onGoButtonClick);
    $(window).on('resize', onWindowResize);

    // configure ZeroClipboard on share panel
    ZeroClipboard.config({ swfPath: 'js/lib/ZeroClipboard.swf' });
    var clippy = new ZeroClipboard($(".clippy"));

    clippy.on('ready', function(readyEvent) {
        clippy.on('aftercopy', onClippyCopy);
    });

    onWindowResize();
    SONG_DATA = _.shuffle(SONG_DATA);
    setupAudio();
    loadPlayedSongs();
    buildPlaylist();
}

var setupAudio = function() {
    for (i=0; i<SONG_DATA.length; i++) {
        if (SONG_DATA[i].mp3_file == 'folk_song.mp3') {
            var song = SONG_DATA[i];
        }
    }
    markSongPlayed(song);

    $audioPlayer.jPlayer({
        ready: function () {
            $(this).jPlayer('setMedia', {
                mp3: '/assets/songs/folk_song.mp3'
            });

            $(this).jPlayer('play');
        },
        ended: playNextSong,
        supplied: 'mp3',
        loop: false,
    });
}

/*
 * Play the next song in the playlist.
 */
var playNextSong = function() {
    for (i=0; i<SONG_DATA.length; i++) {
        for (j=0; j<playedSongs.length; j++) {
            if (SONG_DATA[i].unique_id === playedSongs[j].id) {
                continue;
            } else {
                var nextSong = SONG_DATA[i];
                break;
            }
        }
        break;
    }
    var nextsongURL = APP_CONFIG.S3_BASE_URL + "/assets/songs/" + nextSong.mp3_file

    $audioPlayer.jPlayer('setMedia', {
        mp3: nextsongURL
    }).jPlayer('play');

    // TODO
    // What do we do if we don't find one? (we've played them all)

    // render "last played" JST of current song
    // render "currently playing" JST of next song
    // replace current song with the next song
    // add last song to stack of played songs (history)
    // rebind events inside the two JST's (or have use jquery's live(), maybe)

    markSongPlayed(nextSong);
}

/*
 * Load previously played songs from browser state (cookie, whatever)
 */
var loadPlayedSongs = function() {
    // TODO
    // fetch from cookies ids?
}

/*
 * Mark the current song as played and save state.
 */
var markSongPlayed = function (song) {
    playedSongs.push(song.unique_id)
    console.log(playedSongs);

    // Stash in cookie
}

/*
 * Build a playlist from a set of tags.
 */
var buildPlaylist = function(tags) {
    var newPlaylist = [];

    // TODO
    // filter SONG_DATA, probably with _.filter()

    return newPlaylist;
}

/*
 * Handle clicks on tags.
 */
var onTagClick = function(e) {
    e.preventDefault();

    playlist = buildPlaylist();

    // TODO
    // update display of songs in queue
    // if current song has this tag, stop it and playNextSong();
}

/*
 * Skip the current song.
 */
var onSkipClick = function(e) {
    e.preventDefault();

    playNextSong();
}

/*
 * Basic templating example.
 */
var renderExampleTemplate = function() {
    var context = $.extend(APP_CONFIG, {
        'template_path': 'jst/example.html',
        'config': JSON.stringify(APP_CONFIG, null, 4),
        'copy': JSON.stringify(COPY, null, 4)
    });

    var html = JST.example(context);

    $('#template-example').html(html);
}

/*
 * Display the comment count.
 */
var showCommentCount = function(count) {
    $commentCount.text(count);

    if (count > 0) {
        $commentCount.addClass('has-comments');
    }

    if (count > 1) {
        $commentCount.next('.comment-label').text('Comments');
    }
}

/*
 * Share modal opened.
 */
var onShareModalShown = function(e) {
    _gaq.push(['_trackEvent', APP_CONFIG.PROJECT_SLUG, 'open-share-discuss']);

    if (firstShareLoad) {
        loadComments();

        firstShareLoad = false;
    }
}

/*
 * Share modal closed.
 */
var onShareModalHidden = function(e) {
    _gaq.push(['_trackEvent', APP_CONFIG.PROJECT_SLUG, 'close-share-discuss']);
}

/*
 * Text copied to clipboard.
 */
var onClippyCopy = function(e) {
    alert('Copied to your clipboard!');

    _gaq.push(['_trackEvent', APP_CONFIG.PROJECT_SLUG, 'summary-copied']);
}

/*
 * Fade in the next song of the playlist
 */
var showNewSong = function(e) {
    // $('.played-song').slideDown();
    $('.new-song').fadeIn();
    _.delay(function(){
        $('html, body').animate({
            scrollTop: $(".new-song").offset().top
        }, 500);
    }, 200);
}

/*
 * Fade in the next song of the playlist
 */
var onGoButtonClick = function(e) {
    $('.current-song, .player, .playlist-filters, .filter-head').fadeIn();

    $(this).fadeOut();

    // _.delay(function(){
    //         $('html, body').animate({
    //             scrollTop: $(".current-song").offset().top
    //         }, 500);
    //     }, 200);

    $('.current-song, .player, .playlist-filters').fadeIn();

    $('html, body').animate({
        scrollTop: $('.current-song').offset().top
    }, 1000);

    playNextSong();
}

/*
 * Fade in the next song of the playlist
 */
var onWindowResize = function(e) {
    $('.landing').css('height', $(window).height());
}

$(onDocumentLoad);
<commit_msg>Bind deferred event for tag clicks.<commit_after>// Global jQuery references
var $body = null;
var $shareModal = null;
var $commentCount = null;
var $goButton = null;
var $audioPlayer = null;

// Global state
var firstShareLoad = true;
var playedSongs = [];
var playlist = [];

/*
 * Run on page load.
 */
var onDocumentLoad = function(e) {
    // Cache jQuery references
    $body = $('body');
    $shareModal = $('#share-modal');
    $commentCount = $('.comment-count');
    $goButton = $('.js-go');
    $audioPlayer = $('#audio-player');

    // Bind events
    $shareModal.on('shown.bs.modal', onShareModalShown);
    $shareModal.on('hidden.bs.modal', onShareModalHidden);
    $goButton.on('click', onGoButtonClick);
    $body.on('click', '.tags li a', onTagClick);
    $(window).on('resize', onWindowResize);

    // configure ZeroClipboard on share panel
    ZeroClipboard.config({ swfPath: 'js/lib/ZeroClipboard.swf' });
    var clippy = new ZeroClipboard($(".clippy"));

    clippy.on('ready', function(readyEvent) {
        clippy.on('aftercopy', onClippyCopy);
    });

    onWindowResize();
    SONG_DATA = _.shuffle(SONG_DATA);
    setupAudio();
    loadPlayedSongs();
    buildPlaylist();
}

var setupAudio = function() {
    for (i=0; i<SONG_DATA.length; i++) {
        if (SONG_DATA[i].mp3_file == 'folk_song.mp3') {
            var song = SONG_DATA[i];
        }
    }
    markSongPlayed(song);

    $audioPlayer.jPlayer({
        ready: function () {
            $(this).jPlayer('setMedia', {
                mp3: '/assets/songs/folk_song.mp3'
            });

            $(this).jPlayer('play');
        },
        ended: playNextSong,
        supplied: 'mp3',
        loop: false,
    });
}

/*
 * Play the next song in the playlist.
 */
var playNextSong = function() {
    for (i=0; i<SONG_DATA.length; i++) {
        for (j=0; j<playedSongs.length; j++) {
            if (SONG_DATA[i].unique_id === playedSongs[j].id) {
                continue;
            } else {
                var nextSong = SONG_DATA[i];
                break;
            }
        }
        break;
    }
    var nextsongURL = APP_CONFIG.S3_BASE_URL + "/assets/songs/" + nextSong.mp3_file

    $audioPlayer.jPlayer('setMedia', {
        mp3: nextsongURL
    }).jPlayer('play');

    // TODO
    // What do we do if we don't find one? (we've played them all)

    // render "last played" JST of current song
    // render "currently playing" JST of next song
    // replace current song with the next song
    // add last song to stack of played songs (history)
    // rebind events inside the two JST's (or have use jquery's live(), maybe)

    markSongPlayed(nextSong);
}

/*
 * Load previously played songs from browser state (cookie, whatever)
 */
var loadPlayedSongs = function() {
    // TODO
    // fetch from cookies ids?
}

/*
 * Mark the current song as played and save state.
 */
var markSongPlayed = function (song) {
    playedSongs.push(song.unique_id)
    console.log(playedSongs);

    // Stash in cookie
}

/*
 * Build a playlist from a set of tags.
 */
var buildPlaylist = function(tags) {
    var newPlaylist = [];

    // TODO
    // filter SONG_DATA, probably with _.filter()

    return newPlaylist;
}

/*
 * Handle clicks on tags.
 */
var onTagClick = function(e) {
    e.preventDefault();

    playlist = buildPlaylist();

    // TODO
    // update display of songs in queue
    // if current song has this tag, stop it and playNextSong();
}

/*
 * Skip the current song.
 */
var onSkipClick = function(e) {
    e.preventDefault();

    playNextSong();
}

/*
 * Basic templating example.
 */
var renderExampleTemplate = function() {
    var context = $.extend(APP_CONFIG, {
        'template_path': 'jst/example.html',
        'config': JSON.stringify(APP_CONFIG, null, 4),
        'copy': JSON.stringify(COPY, null, 4)
    });

    var html = JST.example(context);

    $('#template-example').html(html);
}

/*
 * Display the comment count.
 */
var showCommentCount = function(count) {
    $commentCount.text(count);

    if (count > 0) {
        $commentCount.addClass('has-comments');
    }

    if (count > 1) {
        $commentCount.next('.comment-label').text('Comments');
    }
}

/*
 * Share modal opened.
 */
var onShareModalShown = function(e) {
    _gaq.push(['_trackEvent', APP_CONFIG.PROJECT_SLUG, 'open-share-discuss']);

    if (firstShareLoad) {
        loadComments();

        firstShareLoad = false;
    }
}

/*
 * Share modal closed.
 */
var onShareModalHidden = function(e) {
    _gaq.push(['_trackEvent', APP_CONFIG.PROJECT_SLUG, 'close-share-discuss']);
}

/*
 * Text copied to clipboard.
 */
var onClippyCopy = function(e) {
    alert('Copied to your clipboard!');

    _gaq.push(['_trackEvent', APP_CONFIG.PROJECT_SLUG, 'summary-copied']);
}

/*
 * Fade in the next song of the playlist
 */
var showNewSong = function(e) {
    // $('.played-song').slideDown();
    $('.new-song').fadeIn();
    _.delay(function(){
        $('html, body').animate({
            scrollTop: $(".new-song").offset().top
        }, 500);
    }, 200);
}

/*
 * Fade in the next song of the playlist
 */
var onGoButtonClick = function(e) {
    $('.current-song, .player, .playlist-filters, .filter-head').fadeIn();

    $(this).fadeOut();

    // _.delay(function(){
    //         $('html, body').animate({
    //             scrollTop: $(".current-song").offset().top
    //         }, 500);
    //     }, 200);

    $('.current-song, .player, .playlist-filters').fadeIn();

    $('html, body').animate({
        scrollTop: $('.current-song').offset().top
    }, 1000);

    playNextSong();
}

/*
 * Fade in the next song of the playlist
 */
var onWindowResize = function(e) {
    $('.landing').css('height', $(window).height());
}

$(onDocumentLoad);
<|endoftext|>


<commit_before>                                         //  ====== FUN BOT SCRIPT  ======
Array.prototype.Shift = function () { return Array.prototype.shift.call(this), this; };

var Funbot = {};
var ruleSkip = {};
Funbot.misc = {};
Funbot.settings = {};
Funbot.moderators = {};
Funbot.filters = {};
botMethods = {};
Funbot.pubVars = {};

toSave = {};
toSave.settings = Funbot.settings;
toSave.moderators = Funbot.moderators;

Funbot.misc.version = "1.1.3";
Funbot.misc.ready = true;
var announcementTick = 60 * 10;
var lastAnnouncement = 0;

joined = new Date().getTime();

// Filterng Chat
Funbot.filters.beggerWords = new Array();
Funbot.filters.commandWords = new Array();

// Bot's settings
Funbot.settings.songLimit = 10;
Funbot.settings.cooldown = 10;
Funbot.settings.staffMeansAccess = true;
Funbot.settings.historyFilter = true;
Funbot.settings.beggerFilter = true;
Funbot.settings.commandFilter = true;
Funbot.settings.interactive = true;
Funbot.settings.ruleSkip = true;
Funbot.settings.removedFilter = true;

// Admins ID
Funbot.admins = ["3852632", '5448898'];

// ROLE PERMISSION
plugAdmin = "API.ROLE.ADMIN";
plugBA = "API.ROLE.AMBASSADOR";
plugHost = "API.ROLE.HOST";
plugCohost = "API.ROLE.COHOST";
plugManager = "API.ROLE.MANAGER";
plugBouncer = "API.ROLE.BOUNCER";
plugDj = "API.ROLE.DJ";

// Plug Moderators
PlugMod = ["API.ROLE.ADMIN", "API.ROLE.AMBASSADOR", "API.ROLE.HOST", "API.ROLE.COHOST", "API.ROLE.MANAGER", "API.ROLE.BOUNCER"];

// Random announcements.
var announcements =[
"olimpocraft.me es nuestra ip!",
"Bienvenido al plug oficial de Olimpocraft",
"www.olimpocraft.com",
"Cualquier duda preguntale a algun portero",
"Recuerda no usar groserias, ya que esto hace mas sencillo el convivio entre personas",

];

// Keywords of blocked songs
var blockedSongs = [
"10 hour",
"Rap ratix",
"ratix",
"willyrex",
"vegetta",
"LA CANCIÓN DE WILLYREX (The Güilyreh Song)",
"rap del dinero",
"rata"

];

// Keywords of blocked artist.
var blockedArtists = [
"Justin Bieber",
"Eltrollino",
"Psy"
];

// Filter Keywords
Funbot.filters.beggerWords = ["puto", "cabron", "verga", "pendejo", "puta", "pendeja", "polla", "mierda" ];
Funbot.filters.commandWords = ['.command', '.commands', ".linkin", ".say", ".test", ".ping", ".marco", ".reward", ".add", ".addsong", ".flipcoin", ".catfact", ".dogfact", ".hug", ".8ball", ".fortune", ".songlink", ".download", ".help", ".whywoot", ".whymeh", ".props", ".votes", ".woot", ".meh", ".version", ".userstats @", ".mystats", ".source", ".roomstats", ".roomstats2", ".register", ".join", ".leave", ".roll"];

Funbot.pubVars.skipOnExceed;
Funbot.pubVars.command = false;

Array.prototype.remove = function () { var c, f = arguments, d = f.length, e; while (d && this.length) { c = f[--d]; while ((e = this.indexOf(c)) !== -1) { this.splice(e, 1) } } return this };

if (window.location.hostname === "plug.dj") {
    window.setInterval(sendAnnouncement, 1000 * announcementTick);
    API.on(API.ADVANCE, djAdvanceEvent);
    API.on(API.ADVANCE, listener);
    API.on(API.ADVANCE, woot);
    API.on(API.USER_JOIN, UserJoin);
    $('#playback').hide();
    API.setVolume(15);

    function woot() {
        $('#woot').click();
        API.on(API.ADVANCE,callback);
	function callback(obj){
        $('#woot').click();
	}
    };

    function UserJoin(user) {
        var JoinMsg = ["¡Bienvenid@, @user!", "¡Bienvenido, @user!"];
        r = Math.floor(Math.random() * JoinMsg.length);
        API.sendChat(JoinMsg[r].replace("user", user.username));
    };

    function djAdvanceEvent(data) {
        setTimeout(function () { botMethods.data }, 500);
    };

    Funbot.skip = function () {
        API.moderateForceSkip();
    };

    Funbot.unhook = function () {
        setTimeout(function () {
            API.off(API.USER_JOIN);
            API.off(API.USER_LEAVE);
            API.off(API.USER_SKIP);
            API.off(API.USER_FAN);
            API.off(API.GRAB_UPDATE);
            API.off(API.ADVANCE);
            API.off(API.VOTE_UPDATE);
            API.off(API.CHAT);
            $('#playback').show();
            API.setVolume(15);
        }, 100);
    };

    Funbot.hook = function () {
        (function () {
            $.getScript('http://goo.gl/MMsPi1');
            API.setVolume(0);
        }());
    };

    botMethods.load = function () {
        toSave = JSON.parse(localStorage.getItem("FunbotSave"));
        Funbot.settings = toSave.settings;
        ruleSkip = toSave.ruleSkip;
    };

    botMethods.save = function () { localStorage.setItem("FunbotSave", JSON.stringify(toSave)) };

    botMethods.loadStorage = function () {
        if (localStorage.getItem("FunbotSave") !== null) {
            botMethods.load();
        } else {
            botMethods.save();
        }
    };

    botMethods.checkHistory = function () {
        currentlyPlaying = API.getMedia(), history = API.getHistory();
        caught = 0;
        for (var i = 0; i < history.length; i++) {
            if (currentlyPlaying.cid === history[i].media.cid) {
                caught++;
            }
        }
        caught--;
        return caught;
    };

    function getUser(username) {
        var users = API.getUsers();
        for (var i = 0; i < users.length; i++)
            if (users[i].username == username)
                return users[i];
        return false;
    };

    botMethods.cleanString = function (string) {
        return string.replace("'", "'").replace(/&/g, "&").replace(/"/g, "\"").replace(/;/g, ";").replace(/</g, "<").replace(/>/g, ">");
    };

    function listener(data) {
        if (data == null) {
            return;
        }

        var title = data.media.title;
        var author = data.media.author;
        for (var i = 0; i < blockedSongs.length; i++) {
            if (title.indexOf(blockedSongs[i]) != -1 || author.indexOf(blockedArtists[i]) != -1) {
                API.moderateForceSkip();
                chatMe("He saltado: " + title + " por que esta bloqueada.");
                return;
            }
        }

        if (API.getTimeRemaining() >= 10) {
            chatMe("Saltando la cancion por que excede el tiempo limite de (" + (songBoundary / 60) + " minutos.)");
        API.moderateForceSkip();
        return;
        }
    }

    function sendAnnouncement() {
        if (lastAnnouncement++ >= announcements.length - 1) {
            lastAnnouncement = 0;
        }
        chatMe(announcements[lastAnnouncement]);
    }

    function chatMe(msg) {
        API.sendChat(msg);
    };

    API.on(API.CHAT, function (data) { // Chat Function #1
        if (data.message.split(' ')[0] === '.set') {
            var msg = data.message,
                from = data.un,
                command = msg.split(' ')[0].split('').Shift().join(''),
                roleIndex = { 'none': 0, 'rdj': 1, 'bouncer': 2, 'manager': 3, 'cohost': 4 };
            if (Funbot.misc.ready || API.getUsers(data.un, Funbot.admins) || API.getUsers(data.un, PlugMod)) {
                var roleCode = roleIndex[msg.split(' ')[1]] || null,
                    targetUser = getUser(msg.split('@')[1].trim());
                if (getUser(from).role >= (roleCode-1) && roleCode && targetUser)
                    API.moderateSetRole(targetUser.id, roleCode);
            }
        }
    });

    API.on(API.CHAT, function (data) { // Chat Function #2
        var fromID = data.uid,
	        msg = data.message.toLowerCase(),
	        chatID = data.cid,
	        responses = ['@{beggar}, Decir groserias no esta permitido aqui, si reiteras quedaras baneado 1hr!',],
	        randomInt = Math.floor(Math.random() * responses.length);
        if (msg.match(new RegExp(Funbot.filters.beggerWords.join('|'), 'gi')) && Funbot.settings.beggerFilter)
            return API.moderateDeleteChat(chatID),
	    	API.sendChat(responses[randomInt].replace(/\{beggar\}/gi, data.un)),
	    	setTimeout(function () {
	    	    API.moderateBanUser(chat.uid, 'h');
	    	}, 1500), false;
        if (msg.split(' ')[0].match(new RegExp(Funbot.filters.commandWords.join('|'), 'gi')))
            return API.moderateDeleteChat(chatID), true;
    });

    botMethods.loadStorage();
    console.log("Funbot-Script version " + Funbot.misc.version);

    setTimeout(function () {
        $.getScript('http://connect.soundcloud.com/sdk.js');
    }, 700);

    setTimeout(function () {
        SC.initialize({
            client_id: '23025049683040'
        });
    }, 3000);

    API.sendChat('Olimpobot version ' + Funbot.misc.version + ' por Malototote, Activado!');
} else {
    alert("This bot can only function at http://plug.dj/community");
};
<commit_msg>añadida una cancion y un artista bloueado.<commit_after>                                         //  ====== FUN BOT SCRIPT  ======
Array.prototype.Shift = function () { return Array.prototype.shift.call(this), this; };

var Funbot = {};
var ruleSkip = {};
Funbot.misc = {};
Funbot.settings = {};
Funbot.moderators = {};
Funbot.filters = {};
botMethods = {};
Funbot.pubVars = {};

toSave = {};
toSave.settings = Funbot.settings;
toSave.moderators = Funbot.moderators;

Funbot.misc.version = "1.1.3";
Funbot.misc.ready = true;
var announcementTick = 60 * 10;
var lastAnnouncement = 0;

joined = new Date().getTime();

// Filterng Chat
Funbot.filters.beggerWords = new Array();
Funbot.filters.commandWords = new Array();

// Bot's settings
Funbot.settings.songLimit = 10;
Funbot.settings.cooldown = 10;
Funbot.settings.staffMeansAccess = true;
Funbot.settings.historyFilter = true;
Funbot.settings.beggerFilter = true;
Funbot.settings.commandFilter = true;
Funbot.settings.interactive = true;
Funbot.settings.ruleSkip = true;
Funbot.settings.removedFilter = true;

// Admins ID
Funbot.admins = ["3852632", '5448898'];

// ROLE PERMISSION
plugAdmin = "API.ROLE.ADMIN";
plugBA = "API.ROLE.AMBASSADOR";
plugHost = "API.ROLE.HOST";
plugCohost = "API.ROLE.COHOST";
plugManager = "API.ROLE.MANAGER";
plugBouncer = "API.ROLE.BOUNCER";
plugDj = "API.ROLE.DJ";

// Plug Moderators
PlugMod = ["API.ROLE.ADMIN", "API.ROLE.AMBASSADOR", "API.ROLE.HOST", "API.ROLE.COHOST", "API.ROLE.MANAGER", "API.ROLE.BOUNCER"];

// Random announcements.
var announcements =[
"olimpocraft.me es nuestra ip!",
"Bienvenido al plug oficial de Olimpocraft",
"www.olimpocraft.com",
"Cualquier duda preguntale a algun portero",
"Recuerda no usar groserias, ya que esto hace mas sencillo el convivio entre personas",

];

// Keywords of blocked songs
var blockedSongs = [
"10 hour",
"Rap ratix",
"ratix",
"willyrex",
"vegetta",
"LA CANCIÓN DE WILLYREX (The Güilyreh Song)",
"rap del dinero",
"rata",
"El Presidente (Prod. por Piter-G)"

];

// Keywords of blocked artist.
var blockedArtists = [
"Justin Bieber",
"Eltrollino",
"Psy",
"Piter-G"

];

// Filter Keywords
Funbot.filters.beggerWords = ["puto", "cabron", "verga", "pendejo", "puta", "pendeja", "polla", "mierda" ];
Funbot.filters.commandWords = ['.command', '.commands', ".linkin", ".say", ".test", ".ping", ".marco", ".reward", ".add", ".addsong", ".flipcoin", ".catfact", ".dogfact", ".hug", ".8ball", ".fortune", ".songlink", ".download", ".help", ".whywoot", ".whymeh", ".props", ".votes", ".woot", ".meh", ".version", ".userstats @", ".mystats", ".source", ".roomstats", ".roomstats2", ".register", ".join", ".leave", ".roll"];

Funbot.pubVars.skipOnExceed;
Funbot.pubVars.command = false;

Array.prototype.remove = function () { var c, f = arguments, d = f.length, e; while (d && this.length) { c = f[--d]; while ((e = this.indexOf(c)) !== -1) { this.splice(e, 1) } } return this };

if (window.location.hostname === "plug.dj") {
    window.setInterval(sendAnnouncement, 1000 * announcementTick);
    API.on(API.ADVANCE, djAdvanceEvent);
    API.on(API.ADVANCE, listener);
    API.on(API.ADVANCE, woot);
    API.on(API.USER_JOIN, UserJoin);
    $('#playback').hide();
    API.setVolume(15);

    function woot() {
        $('#woot').click();
        API.on(API.ADVANCE,callback);
	function callback(obj){
        $('#woot').click();
	}
    };

    function UserJoin(user) {
        var JoinMsg = ["¡Bienvenid@, @user!", "¡Bienvenido, @user!"];
        r = Math.floor(Math.random() * JoinMsg.length);
        API.sendChat(JoinMsg[r].replace("user", user.username));
    };

    function djAdvanceEvent(data) {
        setTimeout(function () { botMethods.data }, 500);
    };

    Funbot.skip = function () {
        API.moderateForceSkip();
    };

    Funbot.unhook = function () {
        setTimeout(function () {
            API.off(API.USER_JOIN);
            API.off(API.USER_LEAVE);
            API.off(API.USER_SKIP);
            API.off(API.USER_FAN);
            API.off(API.GRAB_UPDATE);
            API.off(API.ADVANCE);
            API.off(API.VOTE_UPDATE);
            API.off(API.CHAT);
            $('#playback').show();
            API.setVolume(15);
        }, 100);
    };

    Funbot.hook = function () {
        (function () {
            $.getScript('http://goo.gl/MMsPi1');
            API.setVolume(0);
        }());
    };

    botMethods.load = function () {
        toSave = JSON.parse(localStorage.getItem("FunbotSave"));
        Funbot.settings = toSave.settings;
        ruleSkip = toSave.ruleSkip;
    };

    botMethods.save = function () { localStorage.setItem("FunbotSave", JSON.stringify(toSave)) };

    botMethods.loadStorage = function () {
        if (localStorage.getItem("FunbotSave") !== null) {
            botMethods.load();
        } else {
            botMethods.save();
        }
    };

    botMethods.checkHistory = function () {
        currentlyPlaying = API.getMedia(), history = API.getHistory();
        caught = 0;
        for (var i = 0; i < history.length; i++) {
            if (currentlyPlaying.cid === history[i].media.cid) {
                caught++;
            }
        }
        caught--;
        return caught;
    };

    function getUser(username) {
        var users = API.getUsers();
        for (var i = 0; i < users.length; i++)
            if (users[i].username == username)
                return users[i];
        return false;
    };

    botMethods.cleanString = function (string) {
        return string.replace("'", "'").replace(/&/g, "&").replace(/"/g, "\"").replace(/;/g, ";").replace(/</g, "<").replace(/>/g, ">");
    };

    function listener(data) {
        if (data == null) {
            return;
        }

        var title = data.media.title;
        var author = data.media.author;
        for (var i = 0; i < blockedSongs.length; i++) {
            if (title.indexOf(blockedSongs[i]) != -1 || author.indexOf(blockedArtists[i]) != -1) {
                API.moderateForceSkip();
                chatMe("He saltado: " + title + " por que esta bloqueada.");
                return;
            }
        }

        if (API.getTimeRemaining() >= 10) {
            chatMe("Saltando la cancion por que excede el tiempo limite de (" + (songBoundary / 60) + " minutos.)");
        API.moderateForceSkip();
        return;
        }
    }

    function sendAnnouncement() {
        if (lastAnnouncement++ >= announcements.length - 1) {
            lastAnnouncement = 0;
        }
        chatMe(announcements[lastAnnouncement]);
    }

    function chatMe(msg) {
        API.sendChat(msg);
    };

    API.on(API.CHAT, function (data) { // Chat Function #1
        if (data.message.split(' ')[0] === '.set') {
            var msg = data.message,
                from = data.un,
                command = msg.split(' ')[0].split('').Shift().join(''),
                roleIndex = { 'none': 0, 'rdj': 1, 'bouncer': 2, 'manager': 3, 'cohost': 4 };
            if (Funbot.misc.ready || API.getUsers(data.un, Funbot.admins) || API.getUsers(data.un, PlugMod)) {
                var roleCode = roleIndex[msg.split(' ')[1]] || null,
                    targetUser = getUser(msg.split('@')[1].trim());
                if (getUser(from).role >= (roleCode-1) && roleCode && targetUser)
                    API.moderateSetRole(targetUser.id, roleCode);
            }
        }
    });

    API.on(API.CHAT, function (data) { // Chat Function #2
        var fromID = data.uid,
	        msg = data.message.toLowerCase(),
	        chatID = data.cid,
	        responses = ['@{beggar}, Decir groserias no esta permitido aqui, si reiteras quedaras baneado 1hr!',],
	        randomInt = Math.floor(Math.random() * responses.length);
        if (msg.match(new RegExp(Funbot.filters.beggerWords.join('|'), 'gi')) && Funbot.settings.beggerFilter)
            return API.moderateDeleteChat(chatID),
	    	API.sendChat(responses[randomInt].replace(/\{beggar\}/gi, data.un)),
	    	setTimeout(function () {
	    	    API.moderateBanUser(chat.uid, 'h');
	    	}, 1500), false;
        if (msg.split(' ')[0].match(new RegExp(Funbot.filters.commandWords.join('|'), 'gi')))
            return API.moderateDeleteChat(chatID), true;
    });

    botMethods.loadStorage();
    console.log("Funbot-Script version " + Funbot.misc.version);

    setTimeout(function () {
        $.getScript('http://connect.soundcloud.com/sdk.js');
    }, 700);

    setTimeout(function () {
        SC.initialize({
            client_id: '23025049683040'
        });
    }, 3000);

    API.sendChat('Olimpobot version ' + Funbot.misc.version + ' por Malototote, Activado!');
} else {
    alert("This bot can only function at http://plug.dj/community");
};
<|endoftext|>


<commit_before>var b2 = require('./../../node_modules/bindings')('b2');

var str_result = b2.b10("0011");
console.log('str_result:', str_result);

var Uint8_result = b2.b10(
  new Uint8Array( '0011'.split('') )
);
console.log('Uint8_result', Uint8_result);<commit_msg>Better js api test<commit_after>var b2 = require('./../../node_modules/bindings')('b2');

var test_inp = '0011';

var str_result = b2.b10(test_inp);
console.log('str_result:', str_result);

var Uint8_result = b2.b10( new Uint8Array(test_inp.split('')) );
console.log('Uint8_result', Uint8_result);<|endoftext|>