<commit_before>var activeGameInstance, activeEngine;
var playersArray;
var game = function(game_id, playerId){
    this.game_id = game_id;
    this.playerId = playerId;
    this.isMasterUser = false;
  }

game.prototype.endGame = function(state) {
    var self = this;
    self.state = state;
    $.ajax({
        type: "POST",
        url: "../endGame.php",
        data: {
            gameId: this.game_id,
            teamAScore: this.state.score.a,
            teamBScore: this.state.score.b
        },
        dataType: 'json',
        success: function(response){
            if(response.isValid){
                activeGameInstance.gameOverModal(self.state);
            }
        },
        error: function(response){
            alert('Something went wrong');
        }
    });
}

game.prototype.gameOverModal = function(state) {
    console.log("appear");
    //whatever with score  state={score: {'a':0,'b':0 },players:{}, started:false, gameId: 0};
	$("#game-over-modal").css("display", "block");
}

game.prototype.redirectToLobby = function() {
    window.location.href="../lobby.php";
}
$('#logout-from-game').on('click', function(){
    logout();
});

function logout()
{
    $.ajax({
        type: "POST",
        url: "../logout.php",
        success: function(response){
            window.location = '../../../home/home.php';
        }
    });
}

game.prototype.getData = function() {
    var self = this;
//use promise chaining to grab data needed to begin game.
$.when(
    $.ajax({
        type: "POST",
        url: "../getTeams.php",
        data: {
            game_id: this.game_id
        }}),
        $.ajax({
            type: "POST",
            url: "../getServer.php",
            data: {
                game_id: this.game_id
            }})
        )
    .done(function(players, serverData){
        var server = JSON.parse(serverData[0]);
        if (server.length==0) { //if the server cannot be loaded here, it's likely it went down or the game is over, redirect to the lobby.
            activeGameInstance.redirectToLobby();
            return;
        }

        self.isMasterUser = (self.playerId==server[0].master_user);
        self.initBoard(JSON.parse(players[0]), server[0].url, server[0].server_name);
        playersArray = activeEngine.paddleDictionary;
    });
}

game.prototype.initBoard = function(gameData, url, serverName) {
    var teamA = _.filter(gameData,function(o){
        return o.team==1});
    var teamB = _.filter(gameData,function(o){
        return o.team==2});
    this.networking = new Networking(serverName,url, gameId, this.onBehavior);
    this.engine = new physicsEngine($("#gameBoard"), teamA, teamB, this.networking, this.isMasterUser);
    activeEngine = this.engine;
    this.addListeners();
}

//Setup listeners for the paddle position slider.  Supported by both touch and mouse.
game.prototype.addListeners = function() {
    //var obj = document.getElementById('slider');
    var self = this;
    window.addEventListener('touchmove', function(event) {
      // If there's exactly one finger inside this element
      if (event.targetTouches.length == 1) {
        var touch = event.targetTouches[0];
        self.engine.moveMyPaddle(self.playerId,touch.pageY);
      }
    }, false);
    window.addEventListener('mousemove', function(event) {
        self.engine.moveMyPaddle(self.playerId,event.pageY-40);
    }, false);
}
game.prototype.getRandomBallStartPosition= function() {
    var rand = Math.floor(Math.random() * 2) + 1
    return (rand==1?.25:-.25); //start with a value of either .25 or -.25, determined randomly.
}
game.prototype.onBehavior = function(name, data) {
    switch (name) {
        case "connect": //occurs on successful handshake with game server
		    console.log("connection");
            var cd = new Countdown($("#countdown"),1,"Go!", activeGameInstance.engine.start);
            cd.beginCountdown();
            $('#game-over-modal').css("display", "none");
            break;
        case "gameOver": //occurs when the server determines the game is over
            activeEngine.stop();
            if (activeGameInstance.isMasterUser)
                activeGameInstance.endGame(data); //data is a json object, contains an 'a' and 'b' property, with the integer score
            else {
                activeGameInstance.gameOverModal(data);
            }

            break;
        case "paddleChange": //occurs when another player changes their paddle position (not your own)
            var paddleData = data; //paddleData is a json object e.g. {'l':0,'p':0 }.  'l' is the location (Y coordinate) of the paddle, 'p' is the player id
            activeEngine.moveOtherPaddle(paddleData.p,paddleData.l);
            break;
        case "stateChange":
            var state = data; //var gameState={score: {'a':0,'b':0 },players:[], started:false};
            $("#status").html("Team A: " + data.score.a + " Team B: " + data.score.b);
            break;
        case "swapBall": //occurs when a team successfully gets a score.  Note that resetball is called immediately after this.
           // var scoreData = data; //scoreData is a json object e.g. {'a':0,'b':0 }.  'a' is the score for team a, 'b' is the score for team b
           // console.log("Score is now: " + JSON.stringify(scoreData))
           // $("#Status").text = "Team A: " + scoreData.a + " Team B: " + scoreData.b;
             //here is an example something we could do when the ball is reset..
            //change the balls's color to red, and move it off the screen, and create a new ball.
           // var ballBody = activeEngine.ballBody; //ballBody is a reference to the ball body from physicsJS
          //  ballBody.state.vel.x = 0;
          //  ballBody.state.vel.y = .5;
          //  ballBody.styles.fillStyle = 'red';
           // ballBody.treatment = 'kinematic';
          //  ballBody.recalc();
          //  ballBody.view = undefined; // re-creates new view on next render
          //  activeEngine.world.render();
          //  activeEngine.removeBall(ballBody);
           // activeEngine.removeBall();
           // var x = activeGameInstance.getRandomBallStartPosition();
           // var y = activeGameInstance.getRandomBallStartPosition();

           // activeEngine.addBall(x,y);
           // setTimeout(function() {

           // },500);
            //use this function to determine the starting x and y vector of the ball

            break;
        case "impact": //occurs whenever the ball hits something, either a paddle, or any of the walls.  This action should update game state for all players.
            if (!activeGameInstance.isMasterUser) {
                activeEngine.adjustState(data);
            }
            break;
        case "score":
            var teamAScore = data.a;
            var teamBScore = data.b;
            $("#status").html("Team A: " + teamAScore + " Team B: " + teamBScore);
           // this.onBehavior("swapBall",null);
            break;
        default:
            break;
    }
}

$(document).ready(function() {
//this stops that "refresh when you swipe down" action from happening
document.body.addEventListener('touchmove', function(event) {
    event.preventDefault();
    }, false);

    let params = (new URL(document.location)).searchParams;
    gameId = parseInt(params.get("gameId"));
    playerId = parseInt(params.get("playerId"));
    activeGameInstance= new game(gameId,playerId);
    activeGameInstance.getData(gameId, playerId);
});
<commit_msg>adding player+color to game board lists<commit_after>var activeGameInstance, activeEngine;
var playersArray;
var game = function(game_id, playerId){
    this.game_id = game_id;
    this.playerId = playerId;
    this.isMasterUser = false;
  }

game.prototype.endGame = function(state) {
    var self = this;
    self.state = state;
    console.log(state);
    console.log('try');
    $.ajax({
        type: "POST",
        url: "../endGame.php",
        data: {
            gameId: this.game_id,
            teamAScore: this.state.score.a,
            teamBScore: this.state.score.b
        },
        dataType: 'json',
        success: function(response){
            if(response.isValid){
                activeGameInstance.gameOverModal(self.state);
            }
        },
        error: function(response){
            alert('Something went wrong');
        }
    });
}

game.prototype.gameOverModal = function(state) {
    //whatever with score  state={score: {'a':0,'b':0 },players:{}, started:false, gameId: 0};
    $("#game-over-modal").css("display", "block");
}

game.prototype.redirectToLobby = function() {
    window.location.href="../lobby.php";
}
$('#logout-from-game').on('click', function(){
    logout();
});

function logout()
{
    $.ajax({
        type: "POST",
        url: "../logout.php",
        success: function(response){
            window.location = '../../../home/home.php';
        }
    });
}

game.prototype.getData = function() {
    var self = this;
//use promise chaining to grab data needed to begin game.
$.when(
    $.ajax({
        type: "POST",
        url: "../getTeams.php",
        data: {
            game_id: this.game_id
        }}),
        $.ajax({
            type: "POST",
            url: "../getServer.php",
            data: {
                game_id: this.game_id
            }})
        )
    .done(function(players, serverData){
        var server = JSON.parse(serverData[0]);
        if (server.length==0) { //if the server cannot be loaded here, it's likely it went down or the game is over, redirect to the lobby.
            activeGameInstance.redirectToLobby();
            return;
        }

        self.isMasterUser = (self.playerId==server[0].master_user);
        self.initBoard(JSON.parse(players[0]), server[0].url, server[0].server_name);
        playersArray = activeEngine.paddleDictionary;

        for(var key in playersArray){

            var player = playersArray[key];
            var color = player.color;
            var name = player.currentPlayerName;
            var team = parseInt(player.team);

            if(team === 1){
                $('#1_table').append("
"+name+"

");
            }else if(team === 2){
                $('#2_table').append("
"+name+"

");
            }
        }
    });
}

game.prototype.initBoard = function(gameData, url, serverName) {
    var teamA = _.filter(gameData,function(o){
        return o.team==1});
    var teamB = _.filter(gameData,function(o){
        return o.team==2});
    this.networking = new Networking(serverName,url, gameId, this.onBehavior);
    this.engine = new physicsEngine($("#gameBoard"), teamA, teamB, this.networking, this.isMasterUser);
    activeEngine = this.engine;
    this.addListeners();
}

//Setup listeners for the paddle position slider.  Supported by both touch and mouse.
game.prototype.addListeners = function() {
    //var obj = document.getElementById('slider');
    var self = this;
    window.addEventListener('touchmove', function(event) {
      // If there's exactly one finger inside this element
      if (event.targetTouches.length == 1) {
        var touch = event.targetTouches[0];
        self.engine.moveMyPaddle(self.playerId,touch.pageY);
      }
    }, false);
    window.addEventListener('mousemove', function(event) {
        self.engine.moveMyPaddle(self.playerId,event.pageY-40);
    }, false);
}
game.prototype.getRandomBallStartPosition= function() {
    var rand = Math.floor(Math.random() * 2) + 1
    return (rand==1?.25:-.25); //start with a value of either .25 or -.25, determined randomly.
}
game.prototype.onBehavior = function(name, data) {
    switch (name) {
        case "connect": //occurs on successful handshake with game server
            console.log("connection");
            var cd = new Countdown($("#countdown"),1,"Go!", activeGameInstance.engine.start);
            cd.beginCountdown();
            $('#game-over-modal').css("display", "none");
            break;
        case "gameOver": //occurs when the server determines the game is over
            activeEngine.stop();
            if (activeGameInstance.isMasterUser)
                activeGameInstance.endGame(data); //data is a json object, contains an 'a' and 'b' property, with the integer score
            else {
                activeGameInstance.gameOverModal(data);
            }

            break;
        case "paddleChange": //occurs when another player changes their paddle position (not your own)
            var paddleData = data; //paddleData is a json object e.g. {'l':0,'p':0 }.  'l' is the location (Y coordinate) of the paddle, 'p' is the player id
            activeEngine.moveOtherPaddle(paddleData.p,paddleData.l);
            break;
        case "stateChange":
            var state = data; //var gameState={score: {'a':0,'b':0 },players:[], started:false};
            $("#status").html("Team A: " + data.score.a + " Team B: " + data.score.b);
            break;
        case "swapBall": //occurs when a team successfully gets a score.  Note that resetball is called immediately after this.
           // var scoreData = data; //scoreData is a json object e.g. {'a':0,'b':0 }.  'a' is the score for team a, 'b' is the score for team b
           // console.log("Score is now: " + JSON.stringify(scoreData))
           // $("#Status").text = "Team A: " + scoreData.a + " Team B: " + scoreData.b;
             //here is an example something we could do when the ball is reset..
            //change the balls's color to red, and move it off the screen, and create a new ball.
           // var ballBody = activeEngine.ballBody; //ballBody is a reference to the ball body from physicsJS
          //  ballBody.state.vel.x = 0;
          //  ballBody.state.vel.y = .5;
          //  ballBody.styles.fillStyle = 'red';
           // ballBody.treatment = 'kinematic';
          //  ballBody.recalc();
          //  ballBody.view = undefined; // re-creates new view on next render
          //  activeEngine.world.render();
          //  activeEngine.removeBall(ballBody);
           // activeEngine.removeBall();
           // var x = activeGameInstance.getRandomBallStartPosition();
           // var y = activeGameInstance.getRandomBallStartPosition();

           // activeEngine.addBall(x,y);
           // setTimeout(function() {

           // },500);
            //use this function to determine the starting x and y vector of the ball

            break;
        case "impact": //occurs whenever the ball hits something, either a paddle, or any of the walls.  This action should update game state for all players.
            if (!activeGameInstance.isMasterUser) {
                activeEngine.adjustState(data);
            }
            break;
        case "score":
            var teamAScore = data.a;
            var teamBScore = data.b;
            $("#status").html("Team A: " + teamAScore + " Team B: " + teamBScore);
           // this.onBehavior("swapBall",null);
            break;
        default:
            break;
    }
}

$(document).ready(function() {
//this stops that "refresh when you swipe down" action from happening
document.body.addEventListener('touchmove', function(event) {
    event.preventDefault();
    }, false);

    let params = (new URL(document.location)).searchParams;
    gameId = parseInt(params.get("gameId"));
    playerId = parseInt(params.get("playerId"));
    activeGameInstance= new game(gameId,playerId);
    activeGameInstance.getData(gameId, playerId);
});
<|endoftext|>


<commit_before>/* Copyright (c) 2012 The Tagspaces Authors. All rights reserved.
 * Use of this source code is governed by a AGPL3 license that
 * can be found in the LICENSE file. */

define([
    'require',
    'exports',
    'module',
    'datatables',
//    'css!datatablescss'
],function(require, exports, module) {
"use strict";

exports.Title = "Search"
exports.ID = "viewSearch";  // ID should be equal to the directory name where the ext. is located
exports.Type =  "view";
exports.Icon = "ui-icon-search";
exports.Version = "1.0";
exports.ManifestVersion = 1;
exports.License = "AGPL";

console.debug("Loading view.search.js");

var viewContainer = undefined;
var viewToolbar = undefined;
var viewFooter = undefined;

var fileTable = undefined;
var viewMode = "files" // tags

exports.init = function init() {
	console.debug("Initializing View "+exports.ID);

    viewContainer = $("#"+exports.ID+"Container");
    viewToolbar = $("#"+exports.ID+"Toolbar");
	viewFooter = $("#"+exports.ID+"Footer");

	viewContainer.empty();
	viewToolbar.empty();
	viewFooter.empty();

    viewToolbar.append($("<button>", {
        text: "ReIndex",
		disabled: true,
        title: "Reindex current favorite folder.",
        id: exports.ID+"ReIndexButton",
    }));

    viewToolbar.append($("", {
    	style: "float: right; margin: 0px; padding: 0px;",
    }).append($("<input>", {
		type: "filter",
		// autocomplete: "off", // Error: cannot call methods on autocomplete prior to initialization; attempted to call method 'off'
        title: "This filter applies to current directory without subdirectories.",
        id: exports.ID+"FilterBox",
    })));

    viewContainer.append($("
", {
		cellpadding: "0",
		cellspacing: "0",
		border: "0",
		style: "width: 100%",
        id: exports.ID+"FileTable",
    }));

    fileTable = $('#'+exports.ID+"FileTable").dataTable( {
        "bJQueryUI": false,
        "bPaginate": false,
        "bLengthChange": false,
        "bFilter": true,
        "bSort": true,
        "bInfo": false,
        "bAutoWidth": false,
        "aoColumns": [
            { "sTitle": "Filename", "sClass": "right" },
            { "sTitle": "Size(bytes)" },
            { "sTitle": "Date Modified" },
            { "sTitle": "Title" },
            { "sTitle": "Tags" },
            { "sTitle": "Ext" },
            { "sTitle": "Path" },
        ],
        "aoColumnDefs": [
            { // Filename column
                "mRender": function ( data, type, row ) { return TagsUI.buttonizeFileName(data) },
                "aTargets": [ 0 ]
            },
            { // Title column
                "mRender": function ( data, type, row ) { return TagsUI.buttonizeTitle(data,row[0]) },
                "aTargets": [ 3 ]
            },
            { // Tags column
                "mRender": function ( data, type, row ) { return TagsUI.generateTagButtons(data,row[5],row[0]) },
                "aTargets": [ 4 ]
            },
            { // Last changed date column
                "mRender": function ( data, type, row ) { return TSAPI.formatDateTime(data, true) },
                "aTargets": [ 2 ]
            },
            { "bVisible": false,  "aTargets": [ 5 ] },
//            { "bSearchable": false,  "aTargets": [ 0 ] },
//            { "sClass": "center", "aTargets": [ 0 ] }
         ]
    } );

    fileTable.fnSetColumnVis(0, false);

    // Disable alerts in datatable
    fileTable.dataTableExt.sErrMode = 'throw';

    // Makes the body of the fileTable selectable
    $("tbody", $(fileTable)).selectable({
      filter: 'tr',
      start: function() {
        console.debug("Start selecting");

        //Hiding all dropdown menus
		$('BODY')
			.find('.dropdown-menu').hide().end()
			.find('[data-dropdown]').removeClass('dropdown-open');

		exports.clearSelectedFiles();
      },
      stop: function(){
        $(".ui-selected", this).each(function(){
            var rowData = fileTable.fnGetData( this );
            // Add the filename which is located in the first column to the list of selected filenames
            UIAPI.selectedFiles.push(rowData[0]);
          });
        console.debug("Selected files: "+UIAPI.selectedFiles);
      }
    })

    // Filter functionality
    $("#"+exports.ID+"FilterBox").keyup(function() {
        fileTable.fnFilter(this.value);
        console.debug("Filter to value: "+this.value);
    });

    $('#'+exports.ID+"FilterBox").wrap('').after($('').click(function() {
        $(this).prev('input').val('').focus();
        fileTable.fnFilter( "" );
    }));

    initButtons();
}

exports.load = function load() {
	console.debug("Loading View "+exports.ID);

    $('#'+exports.ID+"FileTable_wrapper").hide();

    // Purging file table
    fileTable.fnClearTable();

	$( "#"+exports.ID+"ReIndexButton" ).button( "enable" );
	UIAPI.hideLoadingAnimation();
//    $( "#"+exports.ID+"ReIndexButton" ).button( "disable" );
//	IOAPI.createDirectoryIndex(UIAPI.currentPath);
}

var enhanceIndexData = function(index) {
	console.debug("Enhancing directory index...");
    var enhancedIndex = [];
    var tags = undefined;
    var ext = undefined;
    var title = undefined;
    var fileSize = undefined;
    var fileLMDT = undefined;
    var path = undefined;
    for (var i=0; i < index.length; i++) {
        if (index[i].type == "file"){
            // Considering Unix HiddenEntries (. in the beginning of the filename)
            if (TSSETTINGS.Settings["showUnixHiddenEntries"] ||
               (!TSSETTINGS.Settings["showUnixHiddenEntries"] && (index[i].name.indexOf(".") != 0))) {
                 tags = TSAPI.extractTags(index[i].name);
                 title = TSAPI.extractTitle(index[i].name);
                 if(index[i].name.lastIndexOf(".") > 0) {
                     ext = index[i].name.substring(index[i].name.lastIndexOf(".")+1,index[i].name.length);
                 } else {
                     ext = "";
                 }
                 fileSize = index[i].size;
                 fileLMDT = index[i].lmdt;
                 path = index[i].path;
                 if(fileSize == undefined) fileSize = "";
                 if(fileLMDT == undefined) fileLMDT = "";
                 var entry = [index[i].name,fileSize,fileLMDT,title,tags,ext,path];
                 enhancedIndex.push(entry);
            }
        }
    }
    return enhancedIndex;
}

exports.updateIndexData = function updateIndexData(index) {
	console.debug("Updating index data.");

	// Clearing the old data
    fileTable.fnClearTable();

    fileTable.fnAddData( enhanceIndexData(index) );

    fileTable.$('tr').dblclick( function() {
        console.debug("Opening file...");
        var rowData = fileTable.fnGetData( this );

        UIAPI.openFile(rowData[6]);
    } );

    fileTable.$('.fileTitleButton')
        .click( function() {
            selectFile(this, $(this).attr("title"));
        } )
        .dropdown( 'attach' , '#fileMenu' );

    fileTable.$('.extTagButton')
        .click( function() {
        	selectFile(this, $(this).attr("fileName"));
            TagsUI.openTagMenu(this, $(this).attr("tag"), $(this).attr("filename"));
        } )
        .dropdown( 'attach' , '#extensionMenu' );

    fileTable.$('.tagButton')
        .click( function() {
            selectFile(this, $(this).attr("fileName"));
            TagsUI.openTagMenu(this, $(this).attr("tag"), $(this).attr("filename"));
        } )
        .dropdown( 'attach' , '#tagMenu' );

    $('#'+exports.ID+"FileTable_wrapper").show();

    $( "#"+exports.ID+"ReIndexButton" ).button( "enable" );

    UIAPI.hideLoadingAnimation();
}

exports.setFileFilter = function setFileFilter(filter) {
	$( "#"+exports.ID+"FilterBox").val(filter);
	fileTable.fnFilter(filter);
}

exports.clearSelectedFiles = function() {
    UIAPI.selectedFiles = [];
    $('#'+exports.ID+'FileTable tbody tr').each(function(){
        $(this).removeClass('ui-selected');
    });
}

var selectFile = function(tagButton, fileName) {
    exports.clearSelectedFiles();

    $(tagButton).parent().parent().toggleClass("ui-selected");
    UIAPI.currentFilename = fileName;
    UIAPI.selectedFiles.push(UIAPI.currentFilename);
}

var initButtons = function() {

// Initialize file buttons
    $( "#"+exports.ID+"ReIndexButton" ).button({
        text: true,
        icons: {
            primary: "ui-icon-refresh"
        }
    })
    .click(function() {
	    $( "#"+exports.ID+"ReIndexButton" ).button( "disable" );
		IOAPI.createDirectoryIndex(UIAPI.currentPath);
    });

    $( "#clearFilterButton" ).button({
        text: false,
        disabled: false,
        icons: {
            primary: "ui-icon-close"
        }
    })
    .click(function() {
        $( "#filterBox" ).val( "" );
        fileTable.fnFilter( "" );
    });
}

// currently not used
var handleElementActivation = function() {
    console.debug("Entering element activation handler...");

    if (UIAPI.selectedFiles.length > 1) {
        $( "#openFileButton" ).button( "disable" );
        $( "#editFileButton" ).button( "disable" );
        $( "#deleteFileButton" ).button( "disable" );
        $( "#renameFileButton" ).button( "disable" );
    } else if (UIAPI.selectedFiles.length == 1) {
        $( "#openFileButton" ).button( "enable" );
        $( "#editFileButton" ).button( "enable" );
        $( "#deleteFileButton" ).button( "enable" );
        $( "#renameFileButton" ).button( "enable" );
    } else {
        $( "#openFileButton" ).button( "disable" );
        $( "#editFileButton" ).button( "disable" );
        $( "#deleteFileButton" ).button( "disable" );
        $( "#renameFileButton" ).button( "disable" );
    }
}

});<commit_msg>Redisigning the saerch results Disabling the context menu in the search results<commit_after>/* Copyright (c) 2012 The Tagspaces Authors. All rights reserved.
 * Use of this source code is governed by a AGPL3 license that
 * can be found in the LICENSE file. */

define([
    'require',
    'exports',
    'module',
    'datatables',
//    'css!datatablescss'
],function(require, exports, module) {
"use strict";

exports.Title = "Search"
exports.ID = "viewSearch";  // ID should be equal to the directory name where the ext. is located
exports.Type =  "view";
exports.Icon = "ui-icon-search";
exports.Version = "1.0";
exports.ManifestVersion = 1;
exports.License = "AGPL";

console.debug("Loading view.search.js");

var viewContainer = undefined;
var viewToolbar = undefined;
var viewFooter = undefined;

var fileTable = undefined;
var viewMode = "files" // tags

exports.init = function init() {
	console.debug("Initializing View "+exports.ID);

    viewContainer = $("#"+exports.ID+"Container");
    viewToolbar = $("#"+exports.ID+"Toolbar");
	viewFooter = $("#"+exports.ID+"Footer");

	viewContainer.empty();
	viewToolbar.empty();
	viewFooter.empty();

    viewToolbar.append($("<button>", {
        text: "ReIndex",
		disabled: true,
        title: "Reindex current favorite folder.",
        id: exports.ID+"ReIndexButton",
    }));

    viewToolbar.append($("", {
    	style: "float: right; margin: 0px; padding: 0px;",
    }).append($("<input>", {
		type: "filter",
		// autocomplete: "off", // Error: cannot call methods on autocomplete prior to initialization; attempted to call method 'off'
        title: "This filter applies to current directory without subdirectories.",
        id: exports.ID+"FilterBox",
    })));

    viewContainer.append($("
", {
		cellpadding: "0",
		cellspacing: "0",
		border: "0",
		style: "width: 100%",
        id: exports.ID+"FileTable",
    }));

	// Column order in json [title(0),tags(1),fileSize(2),fileLMDT(3),path(4),filename(5),extension(6)];
    fileTable = $('#'+exports.ID+"FileTable").dataTable( {
        "bJQueryUI": false,
        "bPaginate": false,
        "bLengthChange": false,
        "bFilter": true,
        "bSort": true,
        "bInfo": false,
        "bAutoWidth": false,
        "aoColumns": [
            { "sTitle": "Title", "sClass": "right" },
            { "sTitle": "Tags" },
            { "sTitle": "Size(bytes)" },
            { "sTitle": "Date Modified" },
            { "sTitle": "Path" },
        ],
        "aoColumnDefs": [
            { // Title column
                "mRender": function ( data, type, row ) { return TagsUI.buttonizeTitle(data,row[0],row[4]) },
                "aTargets": [ 0 ]
            },
            { // Tags column
                "mRender": function ( data, type, row ) { return TagsUI.generateTagButtons(data,row[6],row[5],row[4]) },
                "aTargets": [ 1 ]
            },
            { // Filesize column
                "mRender": function ( data, type, row ) { return TSAPI.formatFileSize(data) },
                "aTargets": [ 2 ]
            },
            { // Last changed date column
                "mRender": function ( data, type, row ) { return TSAPI.formatDateTime(data, true) },
                "aTargets": [ 3 ]
            },
//            { "bVisible": false,  "aTargets": [ 5 ] },
//            { "bSearchable": false,  "aTargets": [ 0 ] },
//            { "sClass": "center", "aTargets": [ 0 ] }
         ]
    } );

    // Disable alerts in datatable
    fileTable.dataTableExt.sErrMode = 'throw';

    // Makes the body of the fileTable selectable
    $("tbody", $(fileTable)).selectable({
      filter: 'tr',
      start: function() {
        console.debug("Start selecting");

        //Hiding all dropdown menus
		$('BODY')
			.find('.dropdown-menu').hide().end()
			.find('[data-dropdown]').removeClass('dropdown-open');

		exports.clearSelectedFiles();
      },
      stop: function(){
        $(".ui-selected", this).each(function(){
            var rowData = fileTable.fnGetData( this );
            // Add the filename which is located in the first column to the list of selected filenames
            UIAPI.selectedFiles.push(rowData[0]);
          });
        console.debug("Selected files: "+UIAPI.selectedFiles);
      }
    })

    // Filter functionality
    $("#"+exports.ID+"FilterBox").keyup(function() {
        fileTable.fnFilter(this.value);
        console.debug("Filter to value: "+this.value);
    });

    $('#'+exports.ID+"FilterBox").wrap('').after($('').click(function() {
        $(this).prev('input').val('').focus();
        fileTable.fnFilter( "" );
    }));

    initButtons();
}

exports.load = function load() {
	console.debug("Loading View "+exports.ID);

    $('#'+exports.ID+"FileTable_wrapper").hide();

    // Purging file table
    fileTable.fnClearTable();

	$( "#"+exports.ID+"ReIndexButton" ).button( "enable" );
	UIAPI.hideLoadingAnimation();
//    $( "#"+exports.ID+"ReIndexButton" ).button( "disable" );
//	IOAPI.createDirectoryIndex(UIAPI.currentPath);
}

var enhanceIndexData = function(index) {
	console.debug("Enhancing directory index...");
    var enhancedIndex = [];
    var tags = undefined;
    var ext = undefined;
    var title = undefined;
    var fileSize = undefined;
    var fileLMDT = undefined;
    var path = undefined;
    for (var i=0; i < index.length; i++) {
        if (index[i].type == "file"){
            // Considering Unix HiddenEntries (. in the beginning of the filename)
            if (TSSETTINGS.Settings["showUnixHiddenEntries"] ||
               (!TSSETTINGS.Settings["showUnixHiddenEntries"] && (index[i].name.indexOf(".") != 0))) {
                 tags = TSAPI.extractTags(index[i].name);
                 title = TSAPI.extractTitle(index[i].name);
                 if(index[i].name.lastIndexOf(".") > 0) {
                     ext = index[i].name.substring(index[i].name.lastIndexOf(".")+1,index[i].name.length);
                 } else {
                     ext = "";
                 }
                 fileSize = index[i].size;
                 fileLMDT = index[i].lmdt;
                 path = index[i].path;
                 if(fileSize == undefined) fileSize = "";
                 if(fileLMDT == undefined) fileLMDT = "";
                 var entry = [title,tags,fileSize,fileLMDT,path,index[i].name,ext];
                 enhancedIndex.push(entry);
            }
        }
    }
    return enhancedIndex;
}

exports.updateIndexData = function updateIndexData(index) {
	console.debug("Updating index data.");

	// Clearing the old data
    fileTable.fnClearTable();

    fileTable.fnAddData( enhanceIndexData(index) );

    fileTable.$('tr').dblclick( function() {
        console.debug("Opening file...");
        var rowData = fileTable.fnGetData( this );

        UIAPI.openFile(rowData[4]); // 4 is the filePath
    } );

    fileTable.$('.fileTitleButton')
        .click( function() {
            selectFile(this, $(this).attr("title"));
        } )
// TODO Context menu disable until the view.basic and view.search use filepath instead of filename
//        .dropdown( 'attach' , '#fileMenu' );

    fileTable.$('.extTagButton')
        .click( function() {
        	selectFile(this, $(this).attr("fileName"));
            TagsUI.openTagMenu(this, $(this).attr("tag"), $(this).attr("filename"));
        } )
// TODO Context menu disable until the view.basic and view.search use filepath instead of filename
//        .dropdown( 'attach' , '#extensionMenu' );

    fileTable.$('.tagButton')
        .click( function() {
            selectFile(this, $(this).attr("fileName"));
            TagsUI.openTagMenu(this, $(this).attr("tag"), $(this).attr("filename"));
        } )
// TODO Context menu disable until the view.basic and view.search use filepath instead of filename
//        .dropdown( 'attach' , '#tagMenu' );

    $('#'+exports.ID+"FileTable_wrapper").show();

    $( "#"+exports.ID+"ReIndexButton" ).button( "enable" );

    UIAPI.hideLoadingAnimation();
}

exports.setFileFilter = function setFileFilter(filter) {
	$( "#"+exports.ID+"FilterBox").val(filter);
	fileTable.fnFilter(filter);
}

exports.clearSelectedFiles = function() {
    UIAPI.selectedFiles = [];
    $('#'+exports.ID+'FileTable tbody tr').each(function(){
        $(this).removeClass('ui-selected');
    });
}

var selectFile = function(tagButton, fileName) {
    exports.clearSelectedFiles();

    $(tagButton).parent().parent().toggleClass("ui-selected");
    UIAPI.currentFilename = fileName;
    UIAPI.selectedFiles.push(UIAPI.currentFilename);
}

var initButtons = function() {

// Initialize file buttons
    $( "#"+exports.ID+"ReIndexButton" ).button({
        text: true,
        icons: {
            primary: "ui-icon-refresh"
        }
    })
    .click(function() {
	    $( "#"+exports.ID+"ReIndexButton" ).button( "disable" );
		IOAPI.createDirectoryIndex(UIAPI.currentPath);
    });

    $( "#clearFilterButton" ).button({
        text: false,
        disabled: false,
        icons: {
            primary: "ui-icon-close"
        }
    })
    .click(function() {
        $( "#filterBox" ).val( "" );
        fileTable.fnFilter( "" );
    });
}

// currently not used
var handleElementActivation = function() {
    console.debug("Entering element activation handler...");

    if (UIAPI.selectedFiles.length > 1) {
        $( "#openFileButton" ).button( "disable" );
        $( "#editFileButton" ).button( "disable" );
        $( "#deleteFileButton" ).button( "disable" );
        $( "#renameFileButton" ).button( "disable" );
    } else if (UIAPI.selectedFiles.length == 1) {
        $( "#openFileButton" ).button( "enable" );
        $( "#editFileButton" ).button( "enable" );
        $( "#deleteFileButton" ).button( "enable" );
        $( "#renameFileButton" ).button( "enable" );
    } else {
        $( "#openFileButton" ).button( "disable" );
        $( "#editFileButton" ).button( "disable" );
        $( "#deleteFileButton" ).button( "disable" );
        $( "#renameFileButton" ).button( "disable" );
    }
}

});<|endoftext|>


<commit_before>const Commando = require('discord.js-commando')

module.exports =
class Command extends Commando.Command {
  constructor (client, info) {
    info.group = 'rover'
    info.guildOnly = info.guildOnly == null ? true : info.guildOnly
    info.memberName = info.name
    info.argsPromptLimit = 1

    super(client, info)

    this.properName = info.properName
    this.userPermissions = info.userPermissions || ['MANAGE_GUILD']
    this.discordBot = this.client.discordBot
  }

  hasPermission (msg) {
    return this.client.isOwner(msg.author) || !msg.guild || msg.member.hasPermission(this.userPermissions) || msg.member.roles.find(role => role.name === 'RoVer Admin')
  }

  async run (msg, args, pattern) {
    this.server = msg.guild && await this.discordBot.getServer(msg.guild.id)
    return this.fn(msg, args, pattern)
  }
}
<commit_msg>fix missing .cache<commit_after>const Commando = require('discord.js-commando')

module.exports =
class Command extends Commando.Command {
  constructor (client, info) {
    info.group = 'rover'
    info.guildOnly = info.guildOnly == null ? true : info.guildOnly
    info.memberName = info.name
    info.argsPromptLimit = 1

    super(client, info)

    this.properName = info.properName
    this.userPermissions = info.userPermissions || ['MANAGE_GUILD']
    this.discordBot = this.client.discordBot
  }

  hasPermission (msg) {
    return this.client.isOwner(msg.author) || !msg.guild || msg.member.hasPermission(this.userPermissions) || msg.member.roles.cache.find(role => role.name === 'RoVer Admin')
  }

  async run (msg, args, pattern) {
    this.server = msg.guild && await this.discordBot.getServer(msg.guild.id)
    return this.fn(msg, args, pattern)
  }
}
<|endoftext|>


<commit_before>// @flow

import React, { useContext, useMemo } from 'react';
import { TreeStateContext } from './TreeContext';
import { SettingsContext } from '../Settings/SettingsContext';
import TreeFocusedContext from './TreeFocusedContext';
import { StoreContext } from '../context';
import { useSubscription } from '../hooks';
import Store from '../../store';

import styles from './SelectedTreeHighlight.css';

type Data = {|
  startIndex: number,
  stopIndex: number,
|};

export default function SelectedTreeHighlight(_: {||}) {
  const { lineHeight } = useContext(SettingsContext);
  const store = useContext(StoreContext);
  const treeFocused = useContext(TreeFocusedContext);
  const { ownerID, selectedElementID } = useContext(TreeStateContext);

  const subscription = useMemo(
    () => ({
      getCurrentValue: () => {
        if (selectedElementID === null) {
          return null;
        }

        const element = store.getElementByID(selectedElementID);
        if (
          element === null ||
          element.isCollapsed ||
          element.children.length === 0
        ) {
          return null;
        }

        const startIndex = store.getIndexOfElementID(element.children[0]);
        if (startIndex === null) {
          return null;
        }

        let stopIndex = null;
        let current = element;
        while (current !== null) {
          if (current.isCollapsed || current.children.length === 0) {
            // We've found the last/deepest descendant.
            stopIndex = store.getIndexOfElementID(current.id);
            current = null;
          } else {
            const lastChildID = current.children[current.children.length - 1];
            current = store.getElementByID(lastChildID);
          }
        }

        if (stopIndex === null) {
          return null;
        }

        return {
          startIndex,
          stopIndex,
        };
      },
      subscribe: (callback: Function) => {
        store.addListener('mutated', callback);
        return () => {
          store.removeListener('mutated', callback);
        };
      },
    }),
    [selectedElementID, store]
  );
  const data = useSubscription<Data | null, Store>(subscription);

  if (ownerID !== null) {
    return null;
  }

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

  const { startIndex, stopIndex } = data;

  return (
    <div
      className={treeFocused ? styles.Active : styles.Inactive}
      style={{
        position: 'absolute',
        top: `${startIndex * lineHeight - lineHeight / 2}px`,
        height: `${(stopIndex + 1 - startIndex) * lineHeight +
          lineHeight / 2}px`,
      }}
    />
  );
}
<commit_msg>Simplified background highlight style now that corner radius has been removed from selected highlight<commit_after>// @flow

import React, { useContext, useMemo } from 'react';
import { TreeStateContext } from './TreeContext';
import { SettingsContext } from '../Settings/SettingsContext';
import TreeFocusedContext from './TreeFocusedContext';
import { StoreContext } from '../context';
import { useSubscription } from '../hooks';
import Store from '../../store';

import styles from './SelectedTreeHighlight.css';

type Data = {|
  startIndex: number,
  stopIndex: number,
|};

export default function SelectedTreeHighlight(_: {||}) {
  const { lineHeight } = useContext(SettingsContext);
  const store = useContext(StoreContext);
  const treeFocused = useContext(TreeFocusedContext);
  const { ownerID, selectedElementID } = useContext(TreeStateContext);

  const subscription = useMemo(
    () => ({
      getCurrentValue: () => {
        if (selectedElementID === null) {
          return null;
        }

        const element = store.getElementByID(selectedElementID);
        if (
          element === null ||
          element.isCollapsed ||
          element.children.length === 0
        ) {
          return null;
        }

        const startIndex = store.getIndexOfElementID(element.children[0]);
        if (startIndex === null) {
          return null;
        }

        let stopIndex = null;
        let current = element;
        while (current !== null) {
          if (current.isCollapsed || current.children.length === 0) {
            // We've found the last/deepest descendant.
            stopIndex = store.getIndexOfElementID(current.id);
            current = null;
          } else {
            const lastChildID = current.children[current.children.length - 1];
            current = store.getElementByID(lastChildID);
          }
        }

        if (stopIndex === null) {
          return null;
        }

        return {
          startIndex,
          stopIndex,
        };
      },
      subscribe: (callback: Function) => {
        store.addListener('mutated', callback);
        return () => {
          store.removeListener('mutated', callback);
        };
      },
    }),
    [selectedElementID, store]
  );
  const data = useSubscription<Data | null, Store>(subscription);

  if (ownerID !== null) {
    return null;
  }

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

  const { startIndex, stopIndex } = data;

  return (
    <div
      className={treeFocused ? styles.Active : styles.Inactive}
      style={{
        position: 'absolute',
        top: `${startIndex * lineHeight}px`,
        height: `${(stopIndex + 1 - startIndex) * lineHeight}px`,
      }}
    />
  );
}
<|endoftext|>


<commit_before>ScriptLoader.load('Form');
var ComponentParamsForm = new Class({
    Extends: Form,
    initialize: function(el){
        this.parent(el);
    },
    save: function(){
        var result = {};
        if(this.codeEditors.length){
            this.codeEditors.each(function(editor){
                editor.save();
            });
        }

        if (!this.validator.validate()) {
            return false;
        }
        this.form.getElements('input[type=text],input[type=checkbox], select, textarea').each(function(el){
            var value;
            if(el.getProperty('type') == 'checkbox'){
                value = (el.checked)?1:0;
            }
            else {
                value = el.get('value');
            }

            if(el.getProperty('name'))
                result[el.getProperty('name')] = value;
        });

        if(this.richEditors.length){
            this.richEditors.each(function(editor){
                result[editor.hidden.getProperty('name')] = editor.area.innerHTML;
            });
        }

        ModalBox.setReturnValue(result);
        this.close();
    }
});
<commit_msg><commit_after>ScriptLoader.load('Form');
var ComponentParamsForm = new Class({
    Extends: Form,
    initialize: function(el){
        this.parent(el);
        if(this.codeEditors.length){
            this.codeEditors.each(function(editor){
                editor.setValue(editor.getValue().replace('<![CDATA['+"\n", '').replace("\n" + ']]>', ''));
            });
        }
    },
    save: function(){
        var result = {};
        if(this.codeEditors.length){
            this.codeEditors.each(function(editor){
                editor.setValue('<![CDATA[' + "\n" + editor.getValue() + "\n" +']]>');
                editor.save();
            });
        }

        if (!this.validator.validate()) {
            return false;
        }
        this.form.getElements('input[type=text],input[type=checkbox], select, textarea').each(function(el){
            var value;
            if(el.getProperty('type') == 'checkbox'){
                value = (el.checked)?1:0;
            }
            else {
                value = el.get('value');
            }

            if(el.getProperty('name'))
                result[el.getProperty('name')] = value;
        });

        if(this.richEditors.length){
            this.richEditors.each(function(editor){
                result[editor.hidden.getProperty('name')] = editor.area.innerHTML;
            });
        }

        ModalBox.setReturnValue(result);
        this.close();
    }
});
<|endoftext|>


<commit_before>(function(mod) {
  if (typeof exports == "object" && typeof module == "object") // CommonJS
    return mod(require("../lib/infer"), require("../lib/tern"));
  if (typeof define == "function" && define.amd) // AMD
    return define(["../lib/infer", "../lib/tern"], mod);
  mod(tern, tern);
})(function(infer, tern) {
  "use strict";

  function flattenPath(path) {
    if (!/(^|\/)(\.\/|[^\/]+\/\.\.\/)/.test(path)) return path;
    var parts = path.split("/");
    for (var i = 0; i < parts.length; ++i) {
      if (parts[i] == ".") parts.splice(i--, 1);
      else if (i && parts[i] == "..") parts.splice(i-- - 1, 2);
    }
    return parts.join("/");
  }

  function resolveName(name, data) {
    var excl = name.indexOf("!");
    if (excl > -1) name = name.slice(0, excl);

    var opts = data.options;
    var hasExt = /\.js$/.test(name);
    if (hasExt || /^(?:\w+:|\/)/.test(name))
      return name + (hasExt ? "" : ".js");

    var base = opts.baseURL || "";
    if (base && base.charAt(base.length - 1) != "/") base += "/";
    if (opts.paths) {
      var known = opts.paths[name];
      if (known) return flattenPath(base + known + ".js");
      var dir = name.match(/^([^\/]+)(\/.*)$/);
      if (dir) {
        var known = opts.paths[dir[1]];
        if (known) return flattenPath(base + known + dir[2] + ".js");
      }
    }
    return flattenPath(base + name + ".js");
  }

  function getRequire(data) {
    if (!data.require) {
      data.require = new infer.Fn("require", infer.ANull, [infer.cx().str], ["module"], new infer.AVal);
      data.require.computeRet = function(_self, _args, argNodes) {
        if (argNodes.length && argNodes[0].type == "Literal" && typeof argNodes[0].value == "string")
          return getInterface(argNodes[0].value, data);
        return infer.ANull;
      };
    }
    return data.require;
  }

  function getInterface(name, data) {
    if (name == "require") return getRequire(data);
    if (name == "module") return infer.cx().definitions.requirejs.module;

    if (data.options.override && Object.prototype.hasOwnProperty.call(data.options.override, name)) {
      var over = data.options.override[name];
      if (typeof over == "string" && over.charAt(0) == "=") return infer.def.parsePath(over.slice(1));
      if (typeof over == "object") {
        if (data.interfaces[name]) return data.interfaces[name];
        var scope = data.interfaces[name] = new infer.Obj(null, name);
        infer.def.load(over, scope);
        return scope;
      }
      name = over;
    }

    if (!/^(https?:|\/)|\.js$/.test(name))
      name = resolveName(name, data);
    name = flattenPath(name);
    var known = data.interfaces[name];
    if (!known) {
      known = data.interfaces[name] = new infer.AVal;
      data.server.addFile(name);
    }
    return known;
  }

  var EXPORT_OBJ_WEIGHT = 50;

  infer.registerFunction("requireJS", function(_self, args, argNodes) {
    var server = infer.cx().parent, data = server && server._requireJS;
    if (!data || !args.length) return infer.ANull;

    var name = data.currentFile;
    var out = data.interfaces[name];
    if (!out) out = data.interfaces[name] = new infer.AVal;

    var deps = [], fn;
    if (argNodes && args.length > 1) {
      var node = argNodes[args.length == 2 ? 0 : 1];
      if (node.type == "Literal" && typeof node.value == "string") {
        deps.push(getInterface(node.value, data));
      } else if (node.type == "ArrayExpression") for (var i = 0; i < node.elements.length; ++i) {
        var elt = node.elements[i];
        if (elt.type == "Literal" && typeof elt.value == "string") {
          if (elt.value == "exports") {
            var exports = new infer.Obj(true);
            deps.push(exports);
            out.addType(exports, EXPORT_OBJ_WEIGHT);
          } else {
            deps.push(getInterface(elt.value, data));
          }
        }
      }
    } else if (argNodes && args.length == 1 && argNodes[0].type == "FunctionExpression" && argNodes[0].params.length) {
      // Simplified CommonJS call
      var exports = new infer.Obj(true);
      deps.push(getInterface("require", data), exports);
      out.addType(exports, EXPORT_OBJ_WEIGHT);
      fn = args[0];
    }

    if (!fn) {
      fn = args[Math.min(args.length - 1, 2)];
      if (!fn.isEmpty() && !fn.getFunctionType()) fn = null;
    }

    if (fn) fn.propagate(new infer.IsCallee(infer.ANull, deps, null, out));
    else if (args.length) args[0].propagate(out);

    return infer.ANull;
  });

  // Parse simple ObjectExpression AST nodes to their corresponding JavaScript objects.
  function parseExprNode(node) {
    switch (node.type) {
    case "ArrayExpression":
      return node.elements.map(parseExprNode);
    case "Literal":
      return node.value;
    case "ObjectExpression":
      var obj = {};
      node.properties.forEach(function(prop) {
        var key = prop.key.name || prop.key.value;
        obj[key] = parseExprNode(prop.value);
      });
      return obj;
    }
  }

  infer.registerFunction("requireJSConfig", function(_self, _args, argNodes) {
    var server = infer.cx().parent, data = server && server._requireJS;
    if (data && argNodes && argNodes.length && argNodes[0].type == "ObjectExpression") {
      var config = parseExprNode(argNodes[0]);
      for (var key in config) if (config.hasOwnProperty(key)) {
        var value = config[key], exists = data.options[key];
        if (!exists) {
          data.options[key] = value;
        } else if (key == "paths") {
          for (var path in value) if (value.hasOwnProperty(path) && !data.options.paths[path])
            data.options.paths[path] = value[path];
        }
      }
    }
    return infer.ANull;
  });

  tern.registerPlugin("requirejs", function(server, options) {
    server._requireJS = {
      interfaces: Object.create(null),
      options: options || {},
      currentFile: null,
      server: server
    };

    server.on("beforeLoad", function(file) {
      this._requireJS.currentFile = file.name;
    });
    server.on("reset", function() {
      this._requireJS.interfaces = Object.create(null);
      this._requireJS.require = null;
    });
    return {defs: defs};
  });

  var defs = {
    "!name": "requirejs",
    "!define": {
      module: {
        id: "string",
        uri: "string",
        config: "fn() -> ?",
        exports: "?"
      }
    },
    requirejs: {
      "!type": "fn(deps: [string], callback: fn(), errback: fn()) -> !custom:requireJS",
      onError: "fn(err: +Error)",
      load: "fn(context: ?, moduleName: string, url: string)",
      config: "fn(config: ?) -> !custom:requireJSConfig",
      version: "string",
      isBrowser: "bool"
    },
    require: "requirejs",
    define: {
      "!type": "fn(deps: [string], callback: fn()) -> !custom:requireJS",
      amd: {
        jQuery: "bool"
      }
    }
  };
});
<commit_msg>[requirejs plugin] Don't get confused by base paths starting with /<commit_after>(function(mod) {
  if (typeof exports == "object" && typeof module == "object") // CommonJS
    return mod(require("../lib/infer"), require("../lib/tern"));
  if (typeof define == "function" && define.amd) // AMD
    return define(["../lib/infer", "../lib/tern"], mod);
  mod(tern, tern);
})(function(infer, tern) {
  "use strict";

  function flattenPath(path) {
    if (!/(^|\/)(\.\/|[^\/]+\/\.\.\/)/.test(path)) return path;
    var parts = path.split("/");
    for (var i = 0; i < parts.length; ++i) {
      if (parts[i] == "." || !parts[i]) parts.splice(i--, 1);
      else if (i && parts[i] == "..") parts.splice(i-- - 1, 2);
    }
    return parts.join("/");
  }

  function resolveName(name, data) {
    var excl = name.indexOf("!");
    if (excl > -1) name = name.slice(0, excl);

    var opts = data.options;
    var hasExt = /\.js$/.test(name);
    if (hasExt || /^(?:\w+:|\/)/.test(name))
      return name + (hasExt ? "" : ".js");

    var base = opts.baseURL || "";
    if (base && base.charAt(base.length - 1) != "/") base += "/";
    if (opts.paths) {
      var known = opts.paths[name];
      if (known) return flattenPath(base + known + ".js");
      var dir = name.match(/^([^\/]+)(\/.*)$/);
      if (dir) {
        var known = opts.paths[dir[1]];
        if (known) return flattenPath(base + known + dir[2] + ".js");
      }
    }
    return flattenPath(base + name + ".js");
  }

  function getRequire(data) {
    if (!data.require) {
      data.require = new infer.Fn("require", infer.ANull, [infer.cx().str], ["module"], new infer.AVal);
      data.require.computeRet = function(_self, _args, argNodes) {
        if (argNodes.length && argNodes[0].type == "Literal" && typeof argNodes[0].value == "string")
          return getInterface(argNodes[0].value, data);
        return infer.ANull;
      };
    }
    return data.require;
  }

  function getInterface(name, data) {
    if (name == "require") return getRequire(data);
    if (name == "module") return infer.cx().definitions.requirejs.module;

    if (data.options.override && Object.prototype.hasOwnProperty.call(data.options.override, name)) {
      var over = data.options.override[name];
      if (typeof over == "string" && over.charAt(0) == "=") return infer.def.parsePath(over.slice(1));
      if (typeof over == "object") {
        if (data.interfaces[name]) return data.interfaces[name];
        var scope = data.interfaces[name] = new infer.Obj(null, name);
        infer.def.load(over, scope);
        return scope;
      }
      name = over;
    }

    if (!/^(https?:|\/)|\.js$/.test(name))
      name = resolveName(name, data);
    name = flattenPath(name);
    var known = data.interfaces[name];
    if (!known) {
      known = data.interfaces[name] = new infer.AVal;
      data.server.addFile(name);
    }
    return known;
  }

  var EXPORT_OBJ_WEIGHT = 50;

  infer.registerFunction("requireJS", function(_self, args, argNodes) {
    var server = infer.cx().parent, data = server && server._requireJS;
    if (!data || !args.length) return infer.ANull;

    var name = data.currentFile;
    var out = data.interfaces[name];
    if (!out) out = data.interfaces[name] = new infer.AVal;

    var deps = [], fn;
    if (argNodes && args.length > 1) {
      var node = argNodes[args.length == 2 ? 0 : 1];
      if (node.type == "Literal" && typeof node.value == "string") {
        deps.push(getInterface(node.value, data));
      } else if (node.type == "ArrayExpression") for (var i = 0; i < node.elements.length; ++i) {
        var elt = node.elements[i];
        if (elt.type == "Literal" && typeof elt.value == "string") {
          if (elt.value == "exports") {
            var exports = new infer.Obj(true);
            deps.push(exports);
            out.addType(exports, EXPORT_OBJ_WEIGHT);
          } else {
            deps.push(getInterface(elt.value, data));
          }
        }
      }
    } else if (argNodes && args.length == 1 && argNodes[0].type == "FunctionExpression" && argNodes[0].params.length) {
      // Simplified CommonJS call
      var exports = new infer.Obj(true);
      deps.push(getInterface("require", data), exports);
      out.addType(exports, EXPORT_OBJ_WEIGHT);
      fn = args[0];
    }

    if (!fn) {
      fn = args[Math.min(args.length - 1, 2)];
      if (!fn.isEmpty() && !fn.getFunctionType()) fn = null;
    }

    if (fn) fn.propagate(new infer.IsCallee(infer.ANull, deps, null, out));
    else if (args.length) args[0].propagate(out);

    return infer.ANull;
  });

  // Parse simple ObjectExpression AST nodes to their corresponding JavaScript objects.
  function parseExprNode(node) {
    switch (node.type) {
    case "ArrayExpression":
      return node.elements.map(parseExprNode);
    case "Literal":
      return node.value;
    case "ObjectExpression":
      var obj = {};
      node.properties.forEach(function(prop) {
        var key = prop.key.name || prop.key.value;
        obj[key] = parseExprNode(prop.value);
      });
      return obj;
    }
  }

  infer.registerFunction("requireJSConfig", function(_self, _args, argNodes) {
    var server = infer.cx().parent, data = server && server._requireJS;
    if (data && argNodes && argNodes.length && argNodes[0].type == "ObjectExpression") {
      var config = parseExprNode(argNodes[0]);
      for (var key in config) if (config.hasOwnProperty(key)) {
        var value = config[key], exists = data.options[key];
        if (!exists) {
          data.options[key] = value;
        } else if (key == "paths") {
          for (var path in value) if (value.hasOwnProperty(path) && !data.options.paths[path])
            data.options.paths[path] = value[path];
        }
      }
    }
    return infer.ANull;
  });

  tern.registerPlugin("requirejs", function(server, options) {
    server._requireJS = {
      interfaces: Object.create(null),
      options: options || {},
      currentFile: null,
      server: server
    };

    server.on("beforeLoad", function(file) {
      this._requireJS.currentFile = file.name;
    });
    server.on("reset", function() {
      this._requireJS.interfaces = Object.create(null);
      this._requireJS.require = null;
    });
    return {defs: defs};
  });

  var defs = {
    "!name": "requirejs",
    "!define": {
      module: {
        id: "string",
        uri: "string",
        config: "fn() -> ?",
        exports: "?"
      }
    },
    requirejs: {
      "!type": "fn(deps: [string], callback: fn(), errback: fn()) -> !custom:requireJS",
      onError: "fn(err: +Error)",
      load: "fn(context: ?, moduleName: string, url: string)",
      config: "fn(config: ?) -> !custom:requireJSConfig",
      version: "string",
      isBrowser: "bool"
    },
    require: "requirejs",
    define: {
      "!type": "fn(deps: [string], callback: fn()) -> !custom:requireJS",
      amd: {
        jQuery: "bool"
      }
    }
  };
});
<|endoftext|>


<commit_before>var eventId = 'altconf15';

var fs = require('fs');
var path = require('path');

var allDays = {
  "2015-06-08": {
    "id": "alt-day-1",
    "event": eventId,
    "type": "day",
    "label_en": "8th June",
   "date": "2015-06-08"
    // "date": "2015-06-02"
  },
  "2015-06-09": {
    "id": "alt-day-2",
    "event": eventId,
    "type": "day",
    "label_en": "9th June",
   "date": "2015-06-09"
    // "date": "2015-06-03"
  },
  "2015-06-10": {
    "id": "alt-day-3",
    "event": eventId,
    "type": "day",
    "label_en": "10th June",
  "date": "2015-06-10"
    // "date": "2015-06-04"
  },
  "2015-06-11": {
    "id": "alt-day-4",
    "event": eventId,
    "type": "day",
    "label_en": "11th June",
 "date": "2015-06-11"
    // "date": "2015-06-05"
  },
  "2015-06-12": {
    "id": "alt-day-5",
    "event": eventId,
    "type": "day",
    "label_en": "12th June",
   "date": "2015-06-12"
    // "date": "2015-06-06"

  }
};

var allRooms = {
  // "alt-location-lab-1": {
  //   "id": "alt-location-lab-1",
  //   "label_en": "Jillian's A",
  //   "label_de": "Jillian's A",
  //   "is_stage": false,
  //   "floor": 0,
  //   "order_index": 1,
  //   "event": "alt",
  //   "type": "location"
  // },
  // "alt-location-lab-2": {
  //   "id": "alt-location-lab-2",
  //   "label_en": "Jillian's B",
  //   "label_de": "Jillian's B",
  //   "is_stage": false,
  //   "floor": 0,
  //   "order_index": 2,
  //   "event": "alt",
  //   "type": "location"
  // },
  // "alt-location-mainstage": {
  //   "id": "alt-location-mainstage",
  //   "label_en": "Creativity Museum",
  //   "label_de": "Creativity Museum",
  //   "is_stage": true,
  //   "floor": 0,
  //   "order_index": 0,
  //   "event": "alt",
  //   "type": "location",
  // }
};

var allLanguages = {
	'en': { id:'en', label_en:'English' },
};

var allFormats = {
	'discussion': { id:'discussion', label_en:'Discussion' },
	'talk':    { id:'talk',       label_en:'Talk'       },
	'workshop':   { id:'workshop',   label_en:'Workshop'   },
	'action':     { id:'action',     label_en:'Action'     }
}

var allLevels = {
	'beginner':         { id:'beginner',     label_en:'Beginner'     },
	'intermediate':     { id:'intermediate', label_en:'Intermediate' },
	'advanced':         { id:'advanced',     label_en:'Advanced'     }
};

var allTracks = {
  'development': { "color": [207,94,28,1],
                   "id": "development",
                   "label_en": "Development" },
  'general': { "color": [160,160,160,1],
               "id": "general",
               "label_en": "General" },
  'streaming': { "color": [43,81,160,1],
                 "id": "streaming",
                 "label_en": "Streaming" },
  'design': { "color": [43,81,160,1],
                 "id": "design",
                 "label_en": "Design" },
  'community': { "color": [43,81,160,1],
                 "id": "community",
				  "label_en": "Community" }
};

var trackMap = {
  'development':   [
  				],
  'streaming': [
  	 			],
  'design': [
  			],
  'community': [
				]
};

function parseSpeaker(dict) {
	var speaker = dict;

	if (speaker['name'].match(/TBA/)) {
		return null;
	}

	return speaker;
}

function parseSession(dict) {
	var session = dict;

	if (session['title'] == "") {
		return null;
	};

	if (!session['format']) {
		session['format'] = allFormats['talk'];
	}
	if (!session['level']) {
		session['level'] = allLevels['intermediate'];
	}
	if (!session['lang']) {
		session['lang'] = allLanguages['en'];
	}
	if (session['begin'] != null && session['end'] != null) {

		var beginDate = new Date(session['begin']);
		var endDate = new Date(session['end']);
		var month = beginDate.getMonth() + 1;
		var day = beginDate.getDate();
		var key = beginDate.getFullYear() + "-" + (month < 10 ? "0" + month : month) + "-" + (day < 10 ? "0" + day : day);
		session['day'] = allDays[key];
		session['duration'] = (endDate.getTime() - beginDate.getTime()) / 1000.0;

		if (session['location']) {
			allRooms[session['location']['id']] = session['location'];
		}
	}

	if (!session['day']) {
		session['begin'] = null;
		session['end'] = null;
	}

	var speakers = session['speakers'];
	if (speakers) {
		speakers = speakers.filter(function (speaker) {
			return !(speaker['name'].match(/TBA/));
		});
		session['speakers'] = speakers;
	}

	return session;
};

function mkID(string) {
	return eventId + "-" + string.toString().replace(/[^A-Za-z0-9]+/g, '-').toLowerCase();
}

exports.scrape = function (callback) {
	require('../lib/json_requester').get(
		{
			urls: {
				sessions: 'http://altconf.com/schedule/sessions.json',
				speakers: 'http://altconf.com/schedule/speakers.json'
			}
		},
		function (result) {
			var data = [];
			var sessionList  = result.sessions.data;
			var speakerList  = result.speakers.data;

			// Speakers
			// -----------
			speakerList.forEach(function (speakerDict) {
				var speaker = parseSpeaker(speakerDict);

				if (speaker != null) {
					addEntry('speaker', speaker);
				}
			});

			// Sessions
			// -----------
			sessionList.forEach(function (sessionDict) {
				var session = parseSession(sessionDict);

				if (session != null) {
					addEntry('session', session);
				}
			});

			// Additional Data
			// -----------
			alsoAdd('track', allTracks);
			alsoAdd('format', allFormats);
			alsoAdd('level', allLevels);
			alsoAdd('language', allLanguages);
			alsoAdd('day', allDays);
			alsoAdd('location', allRooms);

			// Done
			console.log("Updated dataset with " + data.length + " entries");
			callback(data);
			// -----------------------------

			function addEntry(type, obj) {
				obj.event = eventId;
				obj.type = type;
				data.push(obj);
			}

			function alsoAdd(type, list) {
				Object.keys(list).forEach(function (key) {
					var obj = clone(list[key]);
					obj.event = eventId;
					obj.type = type;
					data.push(obj);
				})
			}

		}
	);
}

function toArray(obj) {
	return Object.keys(obj).map(function (key) { return obj[key] })
}

function parseDay(dateString) {
	if (dateString == '') return false;

	var date = new Date(dateString);
	var day = date.getUTCDate();
	var month = date.getUTCMonth() + 1;
	var year = date.getUTCFullYear();

	var key = year + '-' + (month < 10 ? '0'+month : month) + '-' + (day < 10 ? '0'+day : day);
	var dayDict = allDays[key];

	if (dayDict == undefined) return false;
	return dayDict;
}

function parseDate(text) {
	if (text == '') return false;

	var date = new Date(dateString);
	var day = date.day;
	var month = date.month + 1;
	var year = date.year;
	return new Date(year, month, day, 0, 0, 0, 0);
}

function parseDateTime(date, time) {
	if ((date == '') && (time == '')) return false;

	var dateMatcher = /^(\d+)\.(\d+)\.(\d\d\d\d) /;
	dateMatcher.exec(date);

	var day = RegExp.$1;
	var month = RegExp.$2;
	var year = RegExp.$3;

	var timeMatcher = /(\d+)\:(\d+)/
	timeMatcher.exec(time);
	var hour = RegExp.$1;
	var minute = RegExp.$2;

	// we parse the date stirng to ensure timezone compatibility if run on a computer
	// which is not in CEST as the conference.
	var dateString = year + "-" + month + "-" + day + "T" + hour + ":" + minute + ":" + "00+02:00";

	return new Date(dateString);

	console.log('Unknown date "'+date+'" and time "'+time+'"');
	return false
}

function parseSpeakerLinks(linkUrls, linkLabels) {

	// google+ URLs are so ugly, what parsing them is non trivial, so we ignore them for now
	var linkTypes = { 'github': /^https?\:\/\/github\.com\/(\w+)$/i,
										'twitter': /^https?\:\/\/twitter\.com\/(\w+)$/i,
										'facebook': /^https?\:\/\/facebook\.com\/(\w+)$/i,
										'app.net': /^https?\:\/\/(alpha\.)?app.net\.com\/(\w+)$/i };

	var links = [];

	for (var i = 0; i < linkUrls.length; i++) {
		var linkURL = linkUrls[i];
		var label = linkLabels[i];
		var username = false;
		var service = 'web';

		for (var serviceID in linkTypes) {
			if (linkURL.match(linkTypes[serviceID])) {
				service = serviceID;
				username = RegExp.$1;
			}
		}

		var linkItem = { 'url': linkURL,
										 'title': label,
										 'service': service,
										 'type': 'speaker-link' };
		if (username) linkItem['username'] = username;

		links.push(linkItem);
	}

	return links;
}

function clone(obj) {
	var newObj = {};
	Object.keys(obj).forEach(function (key) {
		newObj[key] = obj[key];
	})
	return newObj;
}<commit_msg>add tracks<commit_after>var eventId = 'altconf15';

var fs = require('fs');
var path = require('path');

var allDays = {
  "2015-06-08": {
    "id": "alt-day-1",
    "event": eventId,
    "type": "day",
    "label_en": "8th June",
   "date": "2015-06-08"
    // "date": "2015-06-02"
  },
  "2015-06-09": {
    "id": "alt-day-2",
    "event": eventId,
    "type": "day",
    "label_en": "9th June",
   "date": "2015-06-09"
    // "date": "2015-06-03"
  },
  "2015-06-10": {
    "id": "alt-day-3",
    "event": eventId,
    "type": "day",
    "label_en": "10th June",
  "date": "2015-06-10"
    // "date": "2015-06-04"
  },
  "2015-06-11": {
    "id": "alt-day-4",
    "event": eventId,
    "type": "day",
    "label_en": "11th June",
 "date": "2015-06-11"
    // "date": "2015-06-05"
  },
  "2015-06-12": {
    "id": "alt-day-5",
    "event": eventId,
    "type": "day",
    "label_en": "12th June",
   "date": "2015-06-12"
    // "date": "2015-06-06"

  }
};

var allRooms = {
  // "alt-location-lab-1": {
  //   "id": "alt-location-lab-1",
  //   "label_en": "Jillian's A",
  //   "label_de": "Jillian's A",
  //   "is_stage": false,
  //   "floor": 0,
  //   "order_index": 1,
  //   "event": "alt",
  //   "type": "location"
  // },
  // "alt-location-lab-2": {
  //   "id": "alt-location-lab-2",
  //   "label_en": "Jillian's B",
  //   "label_de": "Jillian's B",
  //   "is_stage": false,
  //   "floor": 0,
  //   "order_index": 2,
  //   "event": "alt",
  //   "type": "location"
  // },
  // "alt-location-mainstage": {
  //   "id": "alt-location-mainstage",
  //   "label_en": "Creativity Museum",
  //   "label_de": "Creativity Museum",
  //   "is_stage": true,
  //   "floor": 0,
  //   "order_index": 0,
  //   "event": "alt",
  //   "type": "location",
  // }
};

var allLanguages = {
	'en': { id:'en', label_en:'English' },
};

var allFormats = {
	'discussion': { id:'discussion', label_en:'Discussion' },
	'talk':    { id:'talk',       label_en:'Talk'       },
	'workshop':   { id:'workshop',   label_en:'Workshop'   },
	'action':     { id:'action',     label_en:'Action'     }
}

var allLevels = {
	'beginner':         { id:'beginner',     label_en:'Beginner'     },
	'intermediate':     { id:'intermediate', label_en:'Intermediate' },
	'advanced':         { id:'advanced',     label_en:'Advanced'     }
};

var allTracks = {
  // 'development': { "color": [207,94,28,1],
  //                  "id": "development",
  //                  "label_en": "Development" },
  // 'general': { "color": [160,160,160,1],
  //              "id": "general",
  //              "label_en": "General" },
  // 'streaming': { "color": [43,81,160,1],
  //                "id": "streaming",
  //                "label_en": "Streaming" },
  // 'design': { "color": [43,81,160,1],
  //                "id": "design",
  //                "label_en": "Design" },
  // 'community': { "color": [43,81,160,1],
  //                "id": "community",
  // 				  "label_en": "Community" }
};

var trackMap = {
  'development':   [
  				],
  'streaming': [
  	 			],
  'design': [
  			],
  'community': [
				]
};

function parseSpeaker(dict) {
	var speaker = dict;

	if (speaker['name'].match(/TBA/)) {
		return null;
	}

	return speaker;
}

function parseSession(dict) {
	var session = dict;

	if (session['title'] == "") {
		return null;
	};

	if (!session['format']) {
		session['format'] = allFormats['talk'];
	}
	if (!session['level']) {
		session['level'] = allLevels['intermediate'];
	}
	if (!session['lang']) {
		session['lang'] = allLanguages['en'];
	}
	if (session['begin'] != null && session['end'] != null) {

		var beginDate = new Date(session['begin']);
		var endDate = new Date(session['end']);
		var month = beginDate.getMonth() + 1;
		var day = beginDate.getDate();
		var key = beginDate.getFullYear() + "-" + (month < 10 ? "0" + month : month) + "-" + (day < 10 ? "0" + day : day);
		session['day'] = allDays[key];
		session['duration'] = (endDate.getTime() - beginDate.getTime()) / 1000.0;

		if (session['location']) {
			allRooms[session['location']['id']] = session['location'];
		}
	}

	if (session['track']) {
		if (session['track']['id'] != '') {
			allTracks[session['track']['id']] = session['track'];
		}
	}

	if (!session['day']) {
		session['begin'] = null;
		session['end'] = null;
	}

	var speakers = session['speakers'];
	if (speakers) {
		speakers = speakers.filter(function (speaker) {
			return !(speaker['name'].match(/TBA/));
		});
		session['speakers'] = speakers;
	}

	return session;
};

function mkID(string) {
	return eventId + "-" + string.toString().replace(/[^A-Za-z0-9]+/g, '-').toLowerCase();
}

exports.scrape = function (callback) {
	require('../lib/json_requester').get(
		{
			urls: {
				sessions: 'http://altconf.com/schedule/sessions.json',
				speakers: 'http://altconf.com/schedule/speakers.json'
			}
		},
		function (result) {
			var data = [];
			var sessionList  = result.sessions.data;
			var speakerList  = result.speakers.data;

			// Speakers
			// -----------
			speakerList.forEach(function (speakerDict) {
				var speaker = parseSpeaker(speakerDict);

				if (speaker != null) {
					addEntry('speaker', speaker);
				}
			});

			// Sessions
			// -----------
			sessionList.forEach(function (sessionDict) {
				var session = parseSession(sessionDict);

				if (session != null) {
					addEntry('session', session);
				}
			});

			// Additional Data
			// -----------
			alsoAdd('track', allTracks);
			alsoAdd('format', allFormats);
			alsoAdd('level', allLevels);
			alsoAdd('language', allLanguages);
			alsoAdd('day', allDays);
			alsoAdd('location', allRooms);

			// Done
			console.log("Updated dataset with " + data.length + " entries");
			callback(data);
			// -----------------------------

			function addEntry(type, obj) {
				obj.event = eventId;
				obj.type = type;
				data.push(obj);
			}

			function alsoAdd(type, list) {
				Object.keys(list).forEach(function (key) {
					var obj = clone(list[key]);
					obj.event = eventId;
					obj.type = type;
					data.push(obj);
				})
			}

		}
	);
}

function toArray(obj) {
	return Object.keys(obj).map(function (key) { return obj[key] })
}

function parseDay(dateString) {
	if (dateString == '') return false;

	var date = new Date(dateString);
	var day = date.getUTCDate();
	var month = date.getUTCMonth() + 1;
	var year = date.getUTCFullYear();

	var key = year + '-' + (month < 10 ? '0'+month : month) + '-' + (day < 10 ? '0'+day : day);
	var dayDict = allDays[key];

	if (dayDict == undefined) return false;
	return dayDict;
}

function parseDate(text) {
	if (text == '') return false;

	var date = new Date(dateString);
	var day = date.day;
	var month = date.month + 1;
	var year = date.year;
	return new Date(year, month, day, 0, 0, 0, 0);
}

function parseDateTime(date, time) {
	if ((date == '') && (time == '')) return false;

	var dateMatcher = /^(\d+)\.(\d+)\.(\d\d\d\d) /;
	dateMatcher.exec(date);

	var day = RegExp.$1;
	var month = RegExp.$2;
	var year = RegExp.$3;

	var timeMatcher = /(\d+)\:(\d+)/
	timeMatcher.exec(time);
	var hour = RegExp.$1;
	var minute = RegExp.$2;

	// we parse the date stirng to ensure timezone compatibility if run on a computer
	// which is not in CEST as the conference.
	var dateString = year + "-" + month + "-" + day + "T" + hour + ":" + minute + ":" + "00+02:00";

	return new Date(dateString);

	console.log('Unknown date "'+date+'" and time "'+time+'"');
	return false
}

function parseSpeakerLinks(linkUrls, linkLabels) {

	// google+ URLs are so ugly, what parsing them is non trivial, so we ignore them for now
	var linkTypes = { 'github': /^https?\:\/\/github\.com\/(\w+)$/i,
										'twitter': /^https?\:\/\/twitter\.com\/(\w+)$/i,
										'facebook': /^https?\:\/\/facebook\.com\/(\w+)$/i,
										'app.net': /^https?\:\/\/(alpha\.)?app.net\.com\/(\w+)$/i };

	var links = [];

	for (var i = 0; i < linkUrls.length; i++) {
		var linkURL = linkUrls[i];
		var label = linkLabels[i];
		var username = false;
		var service = 'web';

		for (var serviceID in linkTypes) {
			if (linkURL.match(linkTypes[serviceID])) {
				service = serviceID;
				username = RegExp.$1;
			}
		}

		var linkItem = { 'url': linkURL,
										 'title': label,
										 'service': service,
										 'type': 'speaker-link' };
		if (username) linkItem['username'] = username;

		links.push(linkItem);
	}

	return links;
}

function clone(obj) {
	var newObj = {};
	Object.keys(obj).forEach(function (key) {
		newObj[key] = obj[key];
	})
	return newObj;
}<|endoftext|>


<commit_before>Tools = function(self){
  this.bobParse = function(raw){
    var clients = [], data = {type: 'Clients'};
    // exit on null entry
    if ( raw === null ) return;
    for (var cells = raw.replace(/Basic[\r\n\s\ta-z]*Partner ID[\t\s]+/i, '').split(/\t/),
      client = {}, cols = ['Account ID',  'Account Start Date',  'Account Bucket',  'Account Spend',
      'Date of Next Ticket',  'Engaged Status',  'Timezone',  'Welcome Call',  'Keyword Research',
      'Local Profile Tab',  'Obtain or Create Google Logins',  'Create and Verify Google Profile',
      'Obtain Site Access',  'Implement Onsite Edits',  'Create Yahoo Account',  'Create and Verify Yahoo Profile',
      'Create and Verify Bing Profile',  'Install Analytics',  'Company Name',  'Contact Name',  'Website URL',
      'Email Address',  'Phone Number',  'Partner ID',];
      cells.length>0;){
      var keys = Object.keys(client).length;
      if (keys<cols.length-1){
        var param = cols[keys];
        client[param] = cells[0];
        cells.shift();
      } else {
        client.count = keys;
        clients.push(client);
        client = {};
      }
    }
    for (var i=0;i<clients.length;i++){
      var date = clients[i]['Date of Next Ticket'];
      if (data[date] === undefined) data[date] = [];
      data[date].push(clients[i]);
    }
    return data;
  };
  this.todoistExport = function (){
    var view, data,
    taskDate = function(day){
      var days = [new Date(),new Date(),new Date()];
      if (days[0].getDay() == 5) {
        days[1].setDate(days[0].getDate()+3);
        days[2].setDate(days[0].getDate()+4);
      } else if (days[0].getDay() == 4) {
        days[1].setDate(days[0].getDate()+1);
        days[2].setDate(days[0].getDate()+4);
      } else {
        days[1].setDate(days[0].getDate()+1);
        days[2].setDate(days[0].getDate()+2);
      }
      return 'date '+days[day].toDateString().substring(4);
    },
    textarea = document.createElement('textarea'), text = '',
    modal = bootbox.alert({
        size: 'large',
        message: 'placeholder',
        callback: function(){},
    })[0].children[0].children[0].children[0].children[1];
    if (ko.dataFor(window.app) !== undefined){
      view = ko.dataFor(window.app).contentViewModel();
    } else if (ko.dataFor(app) !== undefined){
      view = ko.dataFor(app).contentViewModel();
    }
    if (! view.hasOwnProperty('customersDataTable')){
      modal.remove();
      bootbox.alert('No client data available in active view.
Try running this tool after searching for a client.');
      return 1;
    } else {
      if (typeof(view.customersDataTable) === undefined) {
        console.log('No customersDataTable');
        return;
      } else {
        data = view.customersDataTable.dataSource()[0];
      }
      text += data.CustomerId+' - '+data.Name;
      text += '\n[[NOTE]]: https://launchpad.boostability.com/#customerservice/customersearch/'+data.CustomerId;
      text += '\n...'+data.CustomerId+' Welcome Call [['+taskDate(2)+']]';
      text += '\n......'+data.CustomerId+' 1st Welcome Call [['+taskDate(0)+']]';
      text += '\n......'+data.CustomerId+' 1st Welcome Email [['+taskDate(0)+']]';
      text += '\n......'+data.CustomerId+' 2nd Welcome Call [['+taskDate(1)+']]';
      text += '\n......'+data.CustomerId+' 2nd Welcome Email [['+taskDate(1)+']]';
      text += '\n......'+data.CustomerId+' 3rd Welcome Call [['+taskDate(2)+']]';
      text += '\n......'+data.CustomerId+' 3rd Welcome Email [['+taskDate(2)+']]';
      text += '\n...'+data.CustomerId+' Keyword Research';
      text += '\n...'+data.CustomerId+' Local Profile';
      textarea.value = text;
      modal.parentNode.parentNode.parentNode.style.width = "50em";
      modal.innerHTML = '
'+text+'
';
    }
  };
  this.openClient = function(client) {
    var lp = ko.dataFor(app);
    lp.showManageCustomer(client);
  };
  this.closeClient = function() {
    var buttons = document.getElementsByClassName('close'),
    i = buttons.length - 1;
    if (i >= 1) buttons[i - 1].click();
  };
  this.createElement = function(parent, tag, attributes) {
    var element = parent.appendChild(document.createElement(tag));
    for (var attribute in attributes) {
      if (attributes.hasOwnProperty(attribute)) {
        element[attribute] = attributes[attribute];
      }
    }
    return element;
  };
  this.nextTicket = function(tickets){
    self.Tools.closeClient();
    self.Tools.openClient(tickets[0].CustomerId);
  };
  this.today = function(){
    var date = new Date();
    return (date.getMonth()+1)+'/'+date.getDate()+'/'+date.getFullYear();
  }
  this.httpRequest = function(data){
    var URL = data.url,
    headers = data.headers,
    request = new XMLHttpRequest();
    request.open( "GET", URL, false );
    for (var header in headers) {
      if (headers.hasOwnProperty(header)) {
          request.setRequestHeader(header, headers[header]);
      }
    }
    request.send( null );
    return request.responseText;
  };
  this.getKeywords = (client){
    var activeResponse = this.httpRequest({
      url:'https://launchpad.boostability.com/WebsiteUrlApi/WebsiteUrl_SelectActiveUrls?customerId='+client,
      headers: {
        'Accept': '*/*',
        'Accept-Encoding': 'gzip, deflate, sdch',
        'Accept-Language': 'en-US,en;q=0.8',
        'Cookie': document.cookie,
        'Referer': 'https://launchpad.boostability.com/'},
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36',
        'X-Requested-With': 'XMLHttpRequest',
    }),
    trackingResponse = this.httpRequest({
      url:'https://launchpad.boostability.com/WebsiteKeywordTrackingApi/WebsiteKeywordTracking_Select?customerId='+client,
      headers: {
        'Accept': '*/*',
        'Accept-Encoding': 'gzip, deflate, sdch',
        'Accept-Language': 'en-US,en;q=0.8',
        'Cookie': document.cookie,
        'Referer': 'https://launchpad.boostability.com/'},
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36',
        'X-Requested-With': 'XMLHttpRequest',
    });
    return {active: JSON.parse(activeResponse).Data, tracking: JSON.parse(trackingResponse).Data};
  };
};
<commit_msg>Update tools.js<commit_after>Tools = function(self){
  this.bobParse = function(raw){
    var clients = [], data = {type: 'Clients'};
    // exit on null entry
    if ( raw === null ) return;
    for (var cells = raw.replace(/Basic[\r\n\s\ta-z]*Partner ID[\t\s]+/i, '').split(/\t/),
      client = {}, cols = ['Account ID',  'Account Start Date',  'Account Bucket',  'Account Spend',
      'Date of Next Ticket',  'Engaged Status',  'Timezone',  'Welcome Call',  'Keyword Research',
      'Local Profile Tab',  'Obtain or Create Google Logins',  'Create and Verify Google Profile',
      'Obtain Site Access',  'Implement Onsite Edits',  'Create Yahoo Account',  'Create and Verify Yahoo Profile',
      'Create and Verify Bing Profile',  'Install Analytics',  'Company Name',  'Contact Name',  'Website URL',
      'Email Address',  'Phone Number',  'Partner ID',];
      cells.length>0;){
      var keys = Object.keys(client).length;
      if (keys<cols.length-1){
        var param = cols[keys];
        client[param] = cells[0];
        cells.shift();
      } else {
        client.count = keys;
        clients.push(client);
        client = {};
      }
    }
    for (var i=0;i<clients.length;i++){
      var date = clients[i]['Date of Next Ticket'];
      if (data[date] === undefined) data[date] = [];
      data[date].push(clients[i]);
    }
    return data;
  };
  this.todoistExport = function (){
    var view, data,
    taskDate = function(day){
      var days = [new Date(),new Date(),new Date()];
      if (days[0].getDay() == 5) {
        days[1].setDate(days[0].getDate()+3);
        days[2].setDate(days[0].getDate()+4);
      } else if (days[0].getDay() == 4) {
        days[1].setDate(days[0].getDate()+1);
        days[2].setDate(days[0].getDate()+4);
      } else {
        days[1].setDate(days[0].getDate()+1);
        days[2].setDate(days[0].getDate()+2);
      }
      return 'date '+days[day].toDateString().substring(4);
    },
    textarea = document.createElement('textarea'), text = '',
    modal = bootbox.alert({
        size: 'large',
        message: 'placeholder',
        callback: function(){},
    })[0].children[0].children[0].children[0].children[1];
    if (ko.dataFor(window.app) !== undefined){
      view = ko.dataFor(window.app).contentViewModel();
    } else if (ko.dataFor(app) !== undefined){
      view = ko.dataFor(app).contentViewModel();
    }
    if (! view.hasOwnProperty('customersDataTable')){
      modal.remove();
      bootbox.alert('No client data available in active view.
Try running this tool after searching for a client.');
      return 1;
    } else {
      if (typeof(view.customersDataTable) === undefined) {
        console.log('No customersDataTable');
        return;
      } else {
        data = view.customersDataTable.dataSource()[0];
      }
      text += data.CustomerId+' - '+data.Name;
      text += '\n[[NOTE]]: https://launchpad.boostability.com/#customerservice/customersearch/'+data.CustomerId;
      text += '\n...'+data.CustomerId+' Welcome Call [['+taskDate(2)+']]';
      text += '\n......'+data.CustomerId+' 1st Welcome Call [['+taskDate(0)+']]';
      text += '\n......'+data.CustomerId+' 1st Welcome Email [['+taskDate(0)+']]';
      text += '\n......'+data.CustomerId+' 2nd Welcome Call [['+taskDate(1)+']]';
      text += '\n......'+data.CustomerId+' 2nd Welcome Email [['+taskDate(1)+']]';
      text += '\n......'+data.CustomerId+' 3rd Welcome Call [['+taskDate(2)+']]';
      text += '\n......'+data.CustomerId+' 3rd Welcome Email [['+taskDate(2)+']]';
      text += '\n...'+data.CustomerId+' Keyword Research';
      text += '\n...'+data.CustomerId+' Local Profile';
      textarea.value = text;
      modal.parentNode.parentNode.parentNode.style.width = "50em";
      modal.innerHTML = '
'+text+'
';
    }
  };
  this.openClient = function(client) {
    var lp = ko.dataFor(app);
    lp.showManageCustomer(client);
  };
  this.closeClient = function() {
    var buttons = document.getElementsByClassName('close'),
    i = buttons.length - 1;
    if (i >= 1) buttons[i - 1].click();
  };
  this.createElement = function(parent, tag, attributes) {
    var element = parent.appendChild(document.createElement(tag));
    for (var attribute in attributes) {
      if (attributes.hasOwnProperty(attribute)) {
        element[attribute] = attributes[attribute];
      }
    }
    return element;
  };
  this.nextTicket = function(tickets){
    self.Tools.closeClient();
    self.Tools.openClient(tickets[0].CustomerId);
  };
  this.today = function(){
    var date = new Date();
    return (date.getMonth()+1)+'/'+date.getDate()+'/'+date.getFullYear();
  }
  this.httpRequest = function(data){
    var URL = data.url,
    headers = data.headers,
    request = new XMLHttpRequest();
    request.open( "GET", URL, false );
    for (var header in headers) {
      if (headers.hasOwnProperty(header)) {
          request.setRequestHeader(header, headers[header]);
      }
    }
    request.send( null );
    return request.responseText;
  };
  this.getClient = function(client){
    var response = this.httpRequest({
      url:'https://launchpad.boostability.com/CustomerApi/Customer_Select?customerId='+client,
      headers: {
        'Accept': '*/*',
        'Accept-Encoding': 'gzip, deflate, sdch',
        'Accept-Language': 'en-US,en;q=0.8',
        'Cookie': document.cookie,
        'Referer': 'https://launchpad.boostability.com/',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36',
        'X-Requested-With': 'XMLHttpRequest',
      }
    });
    return JSON.parse(response);
  };
  this.getKeywords = (client){
    var activeResponse = this.httpRequest({
      url:'https://launchpad.boostability.com/WebsiteUrlApi/WebsiteUrl_SelectActiveUrls?customerId='+client,
      headers: {
        'Accept': '*/*',
        'Accept-Encoding': 'gzip, deflate, sdch',
        'Accept-Language': 'en-US,en;q=0.8',
        'Cookie': document.cookie,
        'Referer': 'https://launchpad.boostability.com/',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36',
        'X-Requested-With': 'XMLHttpRequest',
      }
    }),
    trackingResponse = this.httpRequest({
      url:'https://launchpad.boostability.com/WebsiteKeywordTrackingApi/WebsiteKeywordTracking_Select?customerId='+client,
      headers: {
        'Accept': '*/*',
        'Accept-Encoding': 'gzip, deflate, sdch',
        'Accept-Language': 'en-US,en;q=0.8',
        'Cookie': document.cookie,
        'Referer': 'https://launchpad.boostability.com/',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36',
        'X-Requested-With': 'XMLHttpRequest',
      }
    });
    return {active: JSON.parse(activeResponse).Data, tracking: JSON.parse(trackingResponse).Data};
  };
};
<|endoftext|>


<commit_before>import Ember from 'ember';
import jobMixin from 'ember-data-offline/mixins/job';

export default Ember.Object.extend(jobMixin, {
  task() {
    if (this[this.get('method')]){
      return this[this.get('method')].apply(this, this.get('params'));
    }
    return this.get('adapter')[this.get('method')].apply(this.get('adapter'), this.get('params'));
  },

  findAll(store, typeClass, sinceToken) {
    let adapterResp = this.get('adapter').findAll(store, typeClass, sinceToken);
    store.set(`syncLoads.findAll.${typeClass.modelName}`, false);

    adapterResp.then(adapterPayload => {
      store.pushPayload(typeClass.modelName, adapterPayload);

      store.set(`syncLoads.findAll.${typeClass.modelName}`, true);
    });

    return adapterResp;
  },

  find: function(store, typeClass, id, snapshot) {
    let adapterResp = this.get('adapter').find(store, typeClass, id, snapshot);
    store.set(`syncLoads.find.${typeClass.modelName}`, false);

    adapterResp.then(adapterPayload => {
      if (!Ember.isEmpty(adapterPayload)) {
        store.pushPayload(typeClass, adapterPayload);

        store.set(`syncLoads.find.${typeClass.modelName}`, true);
      }
    }).catch(console.log.bind(console));

    return adapterResp;
  },

  findQuery(store, type, query) {
    let adapterResp = this.get('adapter').findQuery(store, type, query);
    store.set(`syncLoads.findQuery.${type.modelName}`, false);

    adapterResp.then(adapterPayload => {
      store.pushPayload(type, adapterPayload);
      store.set(`syncLoads.findQuery.${type.modelName}`, true);
    });

    return adapterResp;
  },

  findMany(store, type, ids, snapshots) {
    let adapterResp = this.get('adapter').findMany(store, type, ids, snapshots);

    adapterResp.then(adapterPayload => {
      store.pushPayload(type, adapterPayload);
    });

    return adapterResp;
  },

  createRecord(store, type, snapshot, fromJob) {
    let adapter = this.get('adapter');
    return adapter.createRecord(store, type, snapshot, fromJob);
  },

  updateRecord(store, type, snapshot, fromJob) {
    let adapter = this.get('adapter');
    return adapter.updateRecord(store, type, snapshot, fromJob);
  },

  deleteRecord(store, type, snapshot, fromJob) {
    let adapter = this.get('adapter');
    return adapter.deleteRecord(store, type, snapshot, fromJob);
  },

});
<commit_msg>try fix<commit_after>import Ember from 'ember';
import jobMixin from 'ember-data-offline/mixins/job';

export default Ember.Object.extend(jobMixin, {
  task() {
    if (this[this.get('method')]){
      return this[this.get('method')].apply(this, this.get('params'));
    }
    return this.get('adapter')[this.get('method')].apply(this.get('adapter'), this.get('params'));
  },

  findAll(store, typeClass, sinceToken) {
    let adapterResp = this.get('adapter').findAll(store, typeClass, sinceToken);
    store.set(`syncLoads.findAll.${typeClass.modelName}`, false);

    adapterResp.then(adapterPayload => {
      store.pushPayload(typeClass, adapterPayload);

      store.set(`syncLoads.findAll.${typeClass.modelName}`, true);
    });

    return adapterResp;
  },

  find: function(store, typeClass, id, snapshot) {
    let adapterResp = this.get('adapter').find(store, typeClass, id, snapshot);
    store.set(`syncLoads.find.${typeClass.modelName}`, false);

    adapterResp.then(adapterPayload => {
      if (!Ember.isEmpty(adapterPayload)) {
        store.pushPayload(typeClass, adapterPayload);

        store.set(`syncLoads.find.${typeClass.modelName}`, true);
      }
    }).catch(console.log.bind(console));

    return adapterResp;
  },

  findQuery(store, type, query) {
    let adapterResp = this.get('adapter').findQuery(store, type, query);
    store.set(`syncLoads.findQuery.${type.modelName}`, false);

    adapterResp.then(adapterPayload => {
      store.pushPayload(type, adapterPayload);
      store.set(`syncLoads.findQuery.${type.modelName}`, true);
    });

    return adapterResp;
  },

  findMany(store, type, ids, snapshots) {
    let adapterResp = this.get('adapter').findMany(store, type, ids, snapshots);

    adapterResp.then(adapterPayload => {
      store.pushPayload(type, adapterPayload);
    });

    return adapterResp;
  },

  createRecord(store, type, snapshot, fromJob) {
    let adapter = this.get('adapter');
    return adapter.createRecord(store, type, snapshot, fromJob);
  },

  updateRecord(store, type, snapshot, fromJob) {
    let adapter = this.get('adapter');
    return adapter.updateRecord(store, type, snapshot, fromJob);
  },

  deleteRecord(store, type, snapshot, fromJob) {
    let adapter = this.get('adapter');
    return adapter.deleteRecord(store, type, snapshot, fromJob);
  },

});
<|endoftext|>


<commit_before>module.exports = function(app, router, logger, proxy) {
    logger.info('module cide');
    var fork = require('child_process').fork;
    var c, fpga;

    router.get('/', function(req, res) {
        res.json({
            cide: '/c/',
            fpgadesign: '/fpga/'
        });
    });

    router.get('/c/start', function(req, res) {
        c = fork('../ArduinoIDE/server.js', [''], {
            cwd: '../ArduinoIDE/'
        });
        res.json({
            message: 'start the c ide!'
        });
    });

    router.get('/c/status', function(req, res) {
        if (c != null) {
            logger.debug(c.connected)
            res.json(c.connected);
        } else {
            res.json(false);
        }
    });

    router.get('/c/stop', function(req, res) {
        if (c != null) {
            c.kill('SIGHUP');
        }
        res.json({
            message: 'stop the c ide!!'
        });
    });

    router.get('/fpga/start', function(req, res) {
        fpga = fork('../FPGAdesigner/server.js', [''], {
            cwd: '../FPGAdesigner/'
        });
        res.json({
            message: 'start the fpga ide!'
        });
    });

    router.get('/fpga/status', function(req, res) {
        if (fpga != null) {
            logger.debug(fpga.connected)
            res.json(fpga.connected);
        } else {
            res.json(false);
        }
    });

    router.get('/fpga/stop', function(req, res) {
        if (fpga != null) {
            fpga.kill('SIGHUP');
        }
        res.json({
            message: 'stop the fpga ide!!'
        });
    });

    app.use('/ide', router);
    app.use('/cide', proxy('localhost:8888'));
}<commit_msg>debug<commit_after>module.exports = function(app, router, logger, proxy) {
    logger.info('module cide');
    var fork = require('child_process').fork;
    var c, fpga;

    router.get('/', function(req, res) {
        res.json({
            cide: '/c/',
            fpgadesign: '/fpga/'
        });
    });

    router.get('/c/start', function(req, res) {
        c = fork('../ArduinoIDE/server.js', [''], {
            cwd: '../ArduinoIDE/'
        });
        res.json({
            message: 'start the c ide!'
        });
    });

    router.get('/c/status', function(req, res) {
        if (c != null) {
            logger.debug(c.connected)
            res.json(c.connected);
        } else {
            res.json(false);
        }
    });

    router.get('/c/stop', function(req, res) {
        if (c != null) {
            c.kill('SIGHUP');
        }
        res.json({
            message: 'stop the c ide!!'
        });
    });

    router.get('/fpga/start', function(req, res) {
        fpga = fork('../FPGAdesigner/server.js', [''], {
            cwd: '../FPGAdesigner/'
        });
        res.json({
            message: 'start the fpga ide!'
        });
    });

    router.get('/fpga/status', function(req, res) {
        if (fpga != null) {
            logger.debug(fpga.connected)
            res.json(fpga.connected);
        } else {
            res.json(false);
        }
    });

    router.get('/fpga/stop', function(req, res) {
        if (fpga != null) {
            fpga.kill('SIGHUP');
        }
        res.json({
            message: 'stop the fpga ide!!'
        });
    });

    app.use('/ide', router);
    app.use('/cide', proxy('localhost:8888', {
        forwardPath: function(req, res) {
            return require('url').parse(req.url).path;
        }
    }));
}<|endoftext|>