<commit_before>// Global variable to store the active tab url
var activeTabUrl = "";

// Global variable that stores the amount of time spent by the user on facebook.com and twitter.com
var totalTimeOnWebsites;

// Global variable to track whether the user is active or not
var isUserActive;

// Stores the current date or the days that have passed since the UTC till today
var today;

// Stores the name of the key that stores the data for the current date
var todayStorageName;

// An array of strings that hold the domain names of the websites that are supposed to be checked
var websitesToTrack;

var isFirstRun = false;

// Returns the current website being used
function getActiveWebsite() {
    return extractDomain(activeTabUrl);
}

// Returns whether the user is active right now or not
function isUserActiveNow() {
    return isUserActive;
}

// Will check if this is the first time the extension has been run, if yes then sets the timeSpentOnWebsites to 0
chrome.runtime.onInstalled.addListener(function(details){
    if(details.reason == "install"){
        isFirstRun = true;
        // Initialize the data objec that is to be placed in the localStorage
        var data = {};

        // Assign initial values to the variables
        today = numDaysSinceUTC();
        todayStorageName = "timeData" + numDaysSinceUTC();
        totalTimeOnWebsites = 0;
        websitesToTrack = ["twitter.com", "facebook.com", "plus.google.com"];

        // Store the values in the localStorage
        data[todayStorageName] = totalTimeOnWebsites;
        data["today"] = numDaysSinceUTC();
        data["trackData"] = JSON.stringify(websitesToTrack);
        data["sitesLocked"] = false;
        chrome.storage.local.set(data, function(){});
    }
});

// Detect for change in storage and update the variables
chrome.storage.onChanged.addListener(function(){
    // update the websites to track variable
    chrome.storage.local.get("trackData", function(result){
        websitesToTrack = JSON.parse(result.trackData);
    });
});

startUp();

// Do all the startup tasks
function startUp() {
    //Initialize the totalTimeOnWebsites variable to the data gained from the local storage of the user
    chrome.storage.local.get(null, function(result){
        totalTimeOnWebsites = result["timeData" + numDaysSinceUTC()];
        today = result["today"];
        websitesToTrack = JSON.parse(result.trackData);
    });
    // Updating the ActiveTabUrl during initialization
    updateActiveTabUrl();

    // Register Events
    registerEvents(); // This one is important better left untouched

    // Setting isUserActive as true while starting up
    isUserActive = true;

    updateData();
    // Setting up the listener that will check if a new day is there
    setInterval(function(){
    if(isNewDay()){
        updateData();
      }
    }, 1000);

}

function updateData(){
    totalTimeOnWebsites = 0;
    var newStorageName = "timeData" + numDaysSinceUTC();
    var newData = {};
    newData[newStorageName] = totalTimeOnWebsites;
    todayStorageName = newStorageName;
    today = numDaysSinceUTC();
    newData["today"] = numDaysSinceUTC();
    chrome.storage.local.set(newData, function(){});
}

function registerEvents() {
    // Registering for onActivated event
    // This is fired when the active tab changes
    chrome.tabs.onActivated.addListener(function(activeInfo) {
        updateActiveTabUrl();
    });

    // Registering for onChanged event
    // This is fired when the url of a tab changes
    chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
        updateActiveTabUrl();
    });

    // Registering for onFocusChanged event
    // This is fired when the active chrome window is changed.
    chrome.windows.onFocusChanged.addListener(function(windowId) {
        // This happens if all the windows are out of focus
        // Using this condition to infer that the user is inactive
        if (windowId === chrome.windows.WINDOW_ID_NONE) {
            isUserActive = false;
        } else {
            isUserActive = true;
        }
        updateActiveTabUrl();
    });

    // Registering for an interval of 1s
    window.setInterval(intervalListener, 1000); // Keeps listening to the current events
}

// Listener for the timer
function intervalListener() {
    updateTotalTime();
}

/*
* Function : updateTotalTime()
* -----------------------------
* Updates the total time spent on the watched website(s).
*/
function updateTotalTime() {
    var currDomain = getActiveWebsite();
    if(isUserActiveNow() && isWatchedWebsite(currDomain)){
        totalTimeOnWebsites += 1;
    }
}

/*
* Function : isWatchedWebsite(domain name of the website)
* -------------------------------------------------------
* I know its a really bad programming style right now but first I have to get
* it to work.
* The function returns true if the current domain name is facebook or twitter and
* false otherwise
*/
function isWatchedWebsite(domainName){
    return ($.inArray(domainName, websitesToTrack) > -1);
}

// Returns the last time when the timeMap has been refresehed
function getLastRefreshTime() {
    return lastRefreshTimeStamp;
}

// Finds the current tab in the current window
// Updates the activeTabUrl global variable
function updateActiveTabUrl() {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { // The argument of the call back function is an array of tabs
        if (tabs.length < 1) { // If there are no tabs in the window, how the fuck is that possible ? let us see
            activeTabUrl = null;
        } else {
            activeTabUrl = tabs[0].url;
        }
    });
}

/*
* Function  : extractDomain(url of the website)
* Usage : currentDomain = extractDomain("http://www.google.com/gmail/")
* ----------------------------------------------------------------------
* Extracts the domain name of the website and returns it as a string.
* E.g. extractDomain("http://www.google.com/gmail/") would return "google.com"
*/
function extractDomain(str) {
    // Removing the protocol and www prefixes
    var strList = str.split(":\/\/");
    if (strList.length > 1) {
        str = strList[1];
    } else {
        str = strList[0];
    }
    str = str.replace(/www\./g,'');

    // Extracting the domain name from full URL
    var domainName = str.split('\/')[0];
    return domainName;
}

/*
* Function : getTimeOnTwitter()
* -------------------------------
* Returns the amount of time in seconds spent on
* the website www.twitter.com and www.facebook.com
*/

function getTimeOnFbTwitter(){
    return totalTimeOnWebsites;
}

/*
* Function : numDaysSinceUTC()
* var numDaysSinceUTC = currentDate();
* ------------------------------------
* Returns the number of days that have passed since
* January 1 1970, used in the process of checking
* days that have passed
*/
function numDaysSinceUTC(){
    var NUM_MILI_IN_A_DAY = 86400000;
    var today = new Date();
    var utcMili = Date.UTC(today.getFullYear(), today.getMonth(), today.getDate()); // miliseconds since UTC
    return (utcMili/ NUM_MILI_IN_A_DAY);
}

/*
* Function : isNewDay()
* -----------------------
* Checks if a new day is dawned upon us,
*/

function isNewDay(){
    return (numDaysSinceUTC() - today >= 1);
}

function todayTimeData(){
    return todayStorageName;
}

<commit_msg>JSON error removed<commit_after>// Global variable to store the active tab url
var activeTabUrl = "";

// Global variable that stores the amount of time spent by the user on facebook.com and twitter.com
var totalTimeOnWebsites;

// Global variable to track whether the user is active or not
var isUserActive;

// Stores the current date or the days that have passed since the UTC till today
var today;

// Stores the name of the key that stores the data for the current date
var todayStorageName;

// An array of strings that hold the domain names of the websites that are supposed to be checked
var websitesToTrack;

var isFirstRun = false;

// Returns the current website being used
function getActiveWebsite() {
    return extractDomain(activeTabUrl);
}

// Returns whether the user is active right now or not
function isUserActiveNow() {
    return isUserActive;
}

// Will check if this is the first time the extension has been run, if yes then sets the timeSpentOnWebsites to 0
chrome.runtime.onInstalled.addListener(function(details){
    if(details.reason == "install"){
        isFirstRun = true;
        // Initialize the data objec that is to be placed in the localStorage
        var data = {};

        // Assign initial values to the variables
        today = numDaysSinceUTC();
        todayStorageName = "timeData" + numDaysSinceUTC();
        totalTimeOnWebsites = 0;
        websitesToTrack = ["twitter.com", "facebook.com", "plus.google.com"];

        // Store the values in the localStorage
        data[todayStorageName] = totalTimeOnWebsites;
        data["today"] = numDaysSinceUTC();
        data["trackData"] = JSON.stringify(websitesToTrack);
        data["sitesLocked"] = false;
        chrome.storage.local.set(data, function(){});
    }
});

// Detect for change in storage and update the variables
chrome.storage.onChanged.addListener(function(){
    // update the websites to track variable
    chrome.storage.local.get("trackData", function(result){
        websitesToTrack = JSON.parse(result.trackData);
    });
});

startUp();

// Do all the startup tasks
function startUp() {
    //Initialize the totalTimeOnWebsites variable to the data gained from the local storage of the user
    chrome.storage.local.get(null, function(result){
        totalTimeOnWebsites = result["timeData" + numDaysSinceUTC()];
        today = result["today"];
        websitesToTrack = (result.trackData);
    });
    // Updating the ActiveTabUrl during initialization
    updateActiveTabUrl();

    // Register Events
    registerEvents(); // This one is important better left untouched

    // Setting isUserActive as true while starting up
    isUserActive = true;

    updateData();
    // Setting up the listener that will check if a new day is there
    setInterval(function(){
    if(isNewDay()){
        updateData();
      }
    }, 1000);

}

function updateData(){
    totalTimeOnWebsites = 0;
    var newStorageName = "timeData" + numDaysSinceUTC();
    var newData = {};
    newData[newStorageName] = totalTimeOnWebsites;
    todayStorageName = newStorageName;
    today = numDaysSinceUTC();
    newData["today"] = numDaysSinceUTC();
    chrome.storage.local.set(newData, function(){});
}

function registerEvents() {
    // Registering for onActivated event
    // This is fired when the active tab changes
    chrome.tabs.onActivated.addListener(function(activeInfo) {
        updateActiveTabUrl();
    });

    // Registering for onChanged event
    // This is fired when the url of a tab changes
    chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
        updateActiveTabUrl();
    });

    // Registering for onFocusChanged event
    // This is fired when the active chrome window is changed.
    chrome.windows.onFocusChanged.addListener(function(windowId) {
        // This happens if all the windows are out of focus
        // Using this condition to infer that the user is inactive
        if (windowId === chrome.windows.WINDOW_ID_NONE) {
            isUserActive = false;
        } else {
            isUserActive = true;
        }
        updateActiveTabUrl();
    });

    // Registering for an interval of 1s
    window.setInterval(intervalListener, 1000); // Keeps listening to the current events
}

// Listener for the timer
function intervalListener() {
    updateTotalTime();
}

/*
* Function : updateTotalTime()
* -----------------------------
* Updates the total time spent on the watched website(s).
*/
function updateTotalTime() {
    var currDomain = getActiveWebsite();
    if(isUserActiveNow() && isWatchedWebsite(currDomain)){
        totalTimeOnWebsites += 1;
    }
}

/*
* Function : isWatchedWebsite(domain name of the website)
* -------------------------------------------------------
* I know its a really bad programming style right now but first I have to get
* it to work.
* The function returns true if the current domain name is facebook or twitter and
* false otherwise
*/
function isWatchedWebsite(domainName){
    return ($.inArray(domainName, websitesToTrack) > -1);
}

// Returns the last time when the timeMap has been refresehed
function getLastRefreshTime() {
    return lastRefreshTimeStamp;
}

// Finds the current tab in the current window
// Updates the activeTabUrl global variable
function updateActiveTabUrl() {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { // The argument of the call back function is an array of tabs
        if (tabs.length < 1) { // If there are no tabs in the window, how the fuck is that possible ? let us see
            activeTabUrl = null;
        } else {
            activeTabUrl = tabs[0].url;
        }
    });
}

/*
* Function  : extractDomain(url of the website)
* Usage : currentDomain = extractDomain("http://www.google.com/gmail/")
* ----------------------------------------------------------------------
* Extracts the domain name of the website and returns it as a string.
* E.g. extractDomain("http://www.google.com/gmail/") would return "google.com"
*/
function extractDomain(str) {
    // Removing the protocol and www prefixes
    var strList = str.split(":\/\/");
    if (strList.length > 1) {
        str = strList[1];
    } else {
        str = strList[0];
    }
    str = str.replace(/www\./g,'');

    // Extracting the domain name from full URL
    var domainName = str.split('\/')[0];
    return domainName;
}

/*
* Function : getTimeOnTwitter()
* -------------------------------
* Returns the amount of time in seconds spent on
* the website www.twitter.com and www.facebook.com
*/

function getTimeOnFbTwitter(){
    return totalTimeOnWebsites;
}

/*
* Function : numDaysSinceUTC()
* var numDaysSinceUTC = currentDate();
* ------------------------------------
* Returns the number of days that have passed since
* January 1 1970, used in the process of checking
* days that have passed
*/
function numDaysSinceUTC(){
    var NUM_MILI_IN_A_DAY = 86400000;
    var today = new Date();
    var utcMili = Date.UTC(today.getFullYear(), today.getMonth(), today.getDate()); // miliseconds since UTC
    return (utcMili/ NUM_MILI_IN_A_DAY);
}

/*
* Function : isNewDay()
* -----------------------
* Checks if a new day is dawned upon us,
*/

function isNewDay(){
    return (numDaysSinceUTC() - today >= 1);
}

function todayTimeData(){
    return todayStorageName;
}

<|endoftext|>


<commit_before>'use strict';

//  ---------------------------------------------------------------------------

const hitbtc = require ('./hitbtc.js');

// ---------------------------------------------------------------------------

module.exports = class bitcoincom extends hitbtc {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'bitcoincom',
            'name': 'bitcoin.com',
            'countries': [ 'KN' ],
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/97296144-514fa300-1861-11eb-952b-3d55d492200b.jpg',
                'api': {
                    'public': 'https://api.exchange.bitcoin.com',
                    'private': 'https://api.exchange.bitcoin.com',
                    'ws': 'wss://api.exchange.bitcoin.com/api/2/ws',
                },
                'www': 'https://exchange.bitcoin.com',
                'doc': 'https://api.exchange.bitcoin.com/api/2/explore',
                'fees': 'https://exchange.bitcoin.com/fees-and-limits',
                'referral': 'https://exchange.bitcoin.com/referral/da948b21d6c92d69',
            },
            'fees': {
                'trading': {
                    'maker': 0.15 / 100,
                    'taker': 0.2 / 100,
                },
            },

        });
    }
};
<commit_msg>bitcoincom linting empty line<commit_after>'use strict';

//  ---------------------------------------------------------------------------

const hitbtc = require ('./hitbtc.js');

// ---------------------------------------------------------------------------

module.exports = class bitcoincom extends hitbtc {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'bitcoincom',
            'name': 'bitcoin.com',
            'countries': [ 'KN' ],
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/97296144-514fa300-1861-11eb-952b-3d55d492200b.jpg',
                'api': {
                    'public': 'https://api.exchange.bitcoin.com',
                    'private': 'https://api.exchange.bitcoin.com',
                    'ws': 'wss://api.exchange.bitcoin.com/api/2/ws',
                },
                'www': 'https://exchange.bitcoin.com',
                'doc': 'https://api.exchange.bitcoin.com/api/2/explore',
                'fees': 'https://exchange.bitcoin.com/fees-and-limits',
                'referral': 'https://exchange.bitcoin.com/referral/da948b21d6c92d69',
            },
            'fees': {
                'trading': {
                    'maker': 0.15 / 100,
                    'taker': 0.2 / 100,
                },
            },
        });
    }
};
<|endoftext|>


<commit_before>'use strict';

const GitHubApi = require("github");

class GitHubApiClient {
  constructor() {
    this.github = new GitHubApi({
      debug: !!process.env.DEBUG,
      timeout: 5000
    });

    const AUTH_TOKEN = process.env.GITHUB_AUTH_TOKEN;

    if (AUTH_TOKEN) {
      this.github.authenticate({type: "oauth", token: AUTH_TOKEN});
    }

    this.getPullRequests = this.getPullRequests.bind(this);
    this.getAllPullRequests = this.getAllPullRequests.bind(this);
  }

  getPullRequests(author) {
    return this.github.search.issues({q: `type:pr+state:open+author:${author}`});
  }

  async getAllPullRequests(authors) {
    return await Promise.all(authors.map(this.getPullRequests));
  }
}

module.exports = GitHubApiClient;
<commit_msg>Add fuction to detect team<commit_after>'use strict';

const GitHubApi = require("github");

class GitHubApiClient {
  constructor() {
    this.github = new GitHubApi({
      debug: !!process.env.DEBUG,
      timeout: 5000
    });

    const AUTH_TOKEN = process.env.GITHUB_AUTH_TOKEN;

    if (AUTH_TOKEN) {
      this.github.authenticate({type: "oauth", token: AUTH_TOKEN});
    }

    this.getPullRequests = this.getPullRequests.bind(this);
    this.getAllPullRequests = this.getAllPullRequests.bind(this);
  }

  getPullRequests(author) {
    return this.github.search.issues({q: `type:pr+state:open+author:${author}`});
  }

  async getAllPullRequests(authors) {
    return await Promise.all(authors.map(this.getPullRequests));
  }

  isTeam(author) {
    !!author.match(/^.+\/.+$/)
  }
}

module.exports = GitHubApiClient;
<|endoftext|>


<commit_before>/*

Jappix - An open social platform
These are the connection JS script for Jappix

-------------------------------------------------

License: AGPL
Author: Vanaryon
Last revision: 29/08/11

*/

// Does the user login
var CURRENT_SESSION = false;

function doLogin(lNick, lServer, lPass, lResource, lPriority, lRemember) {
	try {
		// We remove the not completed class to avoid problems
		$('#home .loginer input').removeClass('please-complete');

		// We add the login wait div
		showGeneralWait();

		// We define the http binding parameters
		oArgs = new Object();

		if(HOST_BOSH_MAIN)
			oArgs.httpbase = HOST_BOSH_MAIN;
		else
			oArgs.httpbase = HOST_BOSH;

		// We create the new http-binding connection
		con = new JSJaCHttpBindingConnection(oArgs);

		// And we handle everything that happen
		setupCon(con);

		// Generate a resource
		var random_resource = getDB('session', 'resource');

		if(!random_resource)
			random_resource = lResource + ' (' + (new Date()).getTime() + ')';

		// We retrieve what the user typed in the login inputs
		oArgs = new Object();
		oArgs.domain = trim(lServer);
		oArgs.username = trim(lNick);
		oArgs.resource = random_resource;
		oArgs.pass = lPass;
		oArgs.secure = true;
		oArgs.xmllang = XML_LANG;

		// Store the resource (for reconnection)
		setDB('session', 'resource', random_resource);

		// Generate a session XML to be stored
		session_xml = '<session><stored>true</stored><domain>' + lServer.htmlEnc() + '</domain><username>' + lNick.htmlEnc() + '</username><resource>' + lResource.htmlEnc() + '</resource><password>' + lPass.htmlEnc() + '</password><priority>' + lPriority.htmlEnc() + '</priority></session>';

		// Save the session parameters (for reconnect if network issue)
		CURRENT_SESSION = session_xml;

		// Remember me?
		if(lRemember)
			setDB('remember', 'session', 1);

		// We store the infos of the user into the data-base
		setDB('priority', 1, lPriority);

		// We connect !
		con.connect(oArgs);

		// Change the page title
		pageTitle('wait');

		logThis('Jappix is connecting...', 3);
	}

	catch(e) {
		// Logs errors
		logThis('Error while logging in: ' + e, 1);

		// Reset Jappix
		destroyTalkPage();

		// Open an unknown error
		openThisError(2);
	}

	finally {
		return false;
	}
}

// Handles the user registration
function handleRegistered() {
	logThis('A new account has been registered.', 3);

	// We remove the waiting image
	removeGeneralWait();

	// Reset the title
	pageTitle('home');

	// We show the success information
	$('#home .registerer .success').fadeIn('fast');

	// We quit the session
	logout();
}

// Does the user registration
function doRegister(username, domain, pass) {
	logThis('Trying to register an account...', 3);

	try {
		// We define the http binding parameters
		oArgs = new Object();

		if(HOST_BOSH_MAIN)
			oArgs.httpbase = HOST_BOSH_MAIN;
		else
			oArgs.httpbase = HOST_BOSH;

		// We create the new http-binding connection
		con = new JSJaCHttpBindingConnection(oArgs);

		// We setup the connection !
		con.registerHandler('onconnect', handleRegistered);
		con.registerHandler('onerror', handleError);

		// We retrieve what the user typed in the register inputs
		oArgs = new Object();
		oArgs.domain = trim(domain);
		oArgs.username = trim(username);
		oArgs.resource = JAPPIX_RESOURCE + ' Register (' + (new Date()).getTime() + ')';
		oArgs.pass = pass;
		oArgs.register = true;
		oArgs.secure = true;
		oArgs.xmllang = XML_LANG;

		con.connect(oArgs);

		// We change the registered information text
		$('#home .homediv.registerer').append(
			'
' +
				_e("You have been registered, here is your XMPP address:") + ' ' + con.username.htmlEnc() + '@' + con.domain.htmlEnc() + ' - ' + _e("Login") + '' +
			'
'
		);

		// Login link
		$('#home .homediv.registerer .success a').click(function() {
			return doLogin(con.username, con.domain, con.pass, con.resource, '10', false);
		});

		// Show the waiting image
		showGeneralWait();

		// Change the page title
		pageTitle('wait');
	}

	catch(e) {
		// Logs errors
		logThis(e, 1);
	}

	finally {
		return false;
	}
}

// Does the user anonymous login
function doAnonymous() {
	logThis('Trying to login anonymously...', 3);

	var aPath = '#home .anonymouser ';
	var room = $(aPath + '.room').val();
	var nick = $(aPath + '.nick').val();

	// If the form is correctly completed
	if(room && nick) {
		// We remove the not completed class to avoid problems
		$('#home .anonymouser input').removeClass('please-complete');

		// Redirect the user to the anonymous room
		window.location.href = JAPPIX_LOCATION + '?r=' + room + '&n=' + nick;
	}

	// We check if the form is entirely completed
	else {
		$(aPath + 'input[type=text]').each(function() {
			var select = $(this);

			if(!select.val())
				$(document).oneTime(10, function() {
					select.addClass('please-complete').focus();
				});
			else
				select.removeClass('please-complete');
		});
	}

	return false;
}

// Handles the user connected event
var CONNECTED = false;

function handleConnected() {
	logThis('Jappix is now connected.', 3);

	// Connection markers
	CONNECTED = true;
	RECONNECT_TRY = 0;
	RECONNECT_TIMER = 0;

	// We hide the home page
	$('#home').hide();

	// Not resumed?
	if(!RESUME) {
		// Remember the session?
		if(getDB('remember', 'session'))
			setPersistent('session', 1, CURRENT_SESSION);

		// We show the chatting app.
		createTalkPage();

		// We reset the homepage
		switchHome('default');

		// We get all the other things
		getEverything();

		// Set last activity stamp
		LAST_ACTIVITY = getTimeStamp();
	}

	// Resumed
	else {
		// Send our presence
		presenceSend();

		// Change the title
		updateTitle();
	}

	// Remove the waiting item
	removeGeneralWait();
}

// Handles the user disconnected event
function handleDisconnected() {
	logThis('Jappix is now disconnected.', 3);

	// Normal disconnection
	if(!CURRENT_SESSION && !CONNECTED)
		destroyTalkPage();
}

// Setups the normal connection
function setupCon(con) {
	// We setup all the necessary handlers for the connection
	con.registerHandler('message', handleMessage);
	con.registerHandler('presence', handlePresence);
	con.registerHandler('iq', handleIQ);
	con.registerHandler('onconnect', handleConnected);
	con.registerHandler('onerror', handleError);
	con.registerHandler('ondisconnect', handleDisconnected);
}

// Logouts from the server
function logout() {
	// We are not connected
	if(!isConnected())
		return false;

	// Disconnect from the XMPP server
	con.disconnect();

	logThis('Jappix is disconnecting...', 3);
}

// Terminates a session
function terminate() {
	if(!isConnected())
		return;

	// Clear temporary session storage
	resetConMarkers();

	// Show the waiting item (useful if BOSH is sloooow)
	showGeneralWait();

	// Change the page title
	pageTitle('wait');

	// Disconnect from the XMPP server
	logout();
}

// Quitss a session
function quit() {
	if(!isConnected())
		return;

	// We show the waiting image
	showGeneralWait();

	// Change the page title
	pageTitle('wait');

	// We disconnect from the XMPP server
	logout();
}

// Creates the reconnect pane
var RECONNECT_TRY = 0;
var RECONNECT_TIMER = 0;

function createReconnect(mode) {
	logThis('This is not a normal disconnection, show the reconnect pane...', 1);

	// Reconnect pane not yet displayed?
	if(!exists('#reconnect')) {
		// Blur the focused input/textarea/select
		$('input, select, textarea').blur();

		// Create the HTML code
		var html = '
' +
				'
' +
					_e("Due to a network issue, you were disconnected. What do you want to do now?");

		// Can we cancel reconnection?
		if(mode == 'normal')
			html += '' + _e("Cancel") + '';

		html += '' + _e("Reconnect") + '' +
			'

';

		// Append the code
		$('body').append(html);

		// Click events
		if(mode == 'normal')
			$('#reconnect a.finish.cancel').click(function() {
				return cancelReconnect();
			});

		$('#reconnect a.finish.reconnect').click(function() {
			return acceptReconnect(mode);
		});

		// Try to reconnect automatically after a while
		if(RECONNECT_TRY < 5)
			RECONNECT_TIMER = 5 + (5 * RECONNECT_TRY);
		else
			RECONNECT_TIMER = 120;

		// Change the try number
		RECONNECT_TRY++;

		// Fire the event!
		$('#reconnect a.finish.reconnect').everyTime('1s', function() {
			// We can reconnect!
			if(RECONNECT_TIMER == 0)
				return acceptReconnect(mode);

			// Button text
			if(RECONNECT_TIMER <= 10)
				$(this).text(_e("Reconnect") + ' (' + RECONNECT_TIMER + ')');

			// Remove 1 second
			RECONNECT_TIMER--;
		});

		// Page title
		updateTitle();
	}
}

// Reconnects the user if he was disconnected (network issue)
var RESUME = false;

function acceptReconnect(mode) {
	logThis('Trying to reconnect the user...', 3);

	// Resume marker
	RESUME = true;

	// Show waiting item
	showGeneralWait();

	// Reset some various stuffs
	var groupchats = '#page-engine .page-engine-chan[data-type=groupchat]';
	$(groupchats + ' .list .role').hide();
	$(groupchats + ' .one-group, ' + groupchats + ' .list .user').remove();
	$(groupchats).attr('data-initial', 'false');

	// Stop the timer
	$('#reconnect a.finish.reconnect').stopTime();

	// Remove the reconnect pane
	$('#reconnect').remove();

	// Try to login again
	if(mode == 'normal')
		loginFromSession(XMLFromString(CURRENT_SESSION));
	else if(mode == 'anonymous')
		anonymousLogin(HOST_ANONYMOUS);

	return false;
}

// Cancel the reconnection of user account (network issue)
function cancelReconnect() {
	logThis('User has canceled automatic reconnection...', 3);

	// Stop the timer
	$('#reconnect a.finish.reconnect').stopTime();

	// Remove the reconnect pane
	$('#reconnect').remove();

	// Destroy the talk page
	destroyTalkPage();

	// Renitialize the previous session parameters
	resetConMarkers();

	return false;
}

// Clears session reminder database
function clearLastSession() {
	// Clear temporary storage
	resetConMarkers();

	// Clear persistent storage
	if($(XMLFromString(getPersistent('session', 1))).find('stored').text() == 'true')
		removePersistent('session', 1);
}

// Resets the connection markers
function resetConMarkers() {
	CURRENT_SESSION = false;
	CONNECTED = false;
	RESUME = false;
	RECONNECT_TRY = 0;
	RECONNECT_TIMER = 0;
}

// Logins from a saved session
function loginFromSession(data) {
	// Select the data
	var session = $(data);

	// Fire the login event
	doLogin(
		session.find('username').text(),
		session.find('domain').text(),
		session.find('password').text(),
		session.find('resource').text(),
		session.find('priority').text(),
		false
	);
}

// Quits a session normally
function normalQuit() {
	// Reset our database
	clearLastSession();

	// We quit the current session
	quit();

	// We show an info
	openThisInfo(3);

	return false;
}

// Gets all the users stuffs
function getEverything() {
	getFeatures();
	getRoster();
	listPrivacy();
	getStorage(NS_ROSTERNOTES);
}

// Plugin launcher
function launchConnection() {
	// Logouts when Jappix is closed
	$(window).bind('beforeunload', terminate);

	// Nothing to do when anonymous!
	if(isAnonymous())
		return;

	// Try to resume a stored session, if not anonymous
	var session = XMLFromString(getPersistent('session', 1));

	if($(session).find('stored').text() == 'true') {
		// Hide the homepage
		$('#home').hide();

		// Show the waiting icon
		showGeneralWait();

		// Login!
		loginFromSession(session);

		logThis('Saved session found, resuming it...', 3);
	}

	// Not connected, maybe a XMPP link is submitted?
	else if((parent.location.hash != '#OK') && LINK_VARS['x']) {
		switchHome('loginer');

		logThis('A XMPP link is set, switch to login page.', 3);
	}
}

// Launch this plugin!
$(document).ready(launchConnection);
<commit_msg>Allow connection callbacks function on function doLogin<commit_after>/*

Jappix - An open social platform
These are the connection JS script for Jappix

-------------------------------------------------

License: AGPL
Author: Vanaryon
Last revision: 29/08/11

*/

// Does the user login
var CURRENT_SESSION = false;

function doLogin(lNick, lServer, lPass, lResource, lPriority, lRemember,loginOpts) {
	try {
		// get optionnal conn handlers
		oextend = loginOpts || {};

		// We remove the not completed class to avoid problems
		$('#home .loginer input').removeClass('please-complete');

		// We add the login wait div
		showGeneralWait();

		// We define the http binding parameters
		oArgs = new Object();

		if(HOST_BOSH_MAIN)
			oArgs.httpbase = HOST_BOSH_MAIN;
		else
			oArgs.httpbase = HOST_BOSH;

		// We create the new http-binding connection
		con = new JSJaCHttpBindingConnection(oArgs);

		// And we handle everything that happen
		setupCon(con,oExtend);

		// Generate a resource
		var random_resource = getDB('session', 'resource');

		if(!random_resource)
			random_resource = lResource + ' (' + (new Date()).getTime() + ')';

		// We retrieve what the user typed in the login inputs
		oArgs = new Object();
		oArgs.domain = trim(lServer);
		oArgs.username = trim(lNick);
		oArgs.resource = random_resource;
		oArgs.pass = lPass;
		oArgs.secure = true;
		oArgs.xmllang = XML_LANG;

		// Store the resource (for reconnection)
		setDB('session', 'resource', random_resource);

		// Generate a session XML to be stored
		session_xml = '<session><stored>true</stored><domain>' + lServer.htmlEnc() + '</domain><username>' + lNick.htmlEnc() + '</username><resource>' + lResource.htmlEnc() + '</resource><password>' + lPass.htmlEnc() + '</password><priority>' + lPriority.htmlEnc() + '</priority></session>';

		// Save the session parameters (for reconnect if network issue)
		CURRENT_SESSION = session_xml;

		// Remember me?
		if(lRemember)
			setDB('remember', 'session', 1);

		// We store the infos of the user into the data-base
		setDB('priority', 1, lPriority);

		// We connect !
		con.connect(oArgs);

		// Change the page title
		pageTitle('wait');

		logThis('Jappix is connecting...', 3);
	}

	catch(e) {
		// Logs errors
		logThis('Error while logging in: ' + e, 1);

		// Reset Jappix
		destroyTalkPage();

		// Open an unknown error
		openThisError(2);
	}

	finally {
		return false;
	}
}

// Handles the user registration
function handleRegistered() {
	logThis('A new account has been registered.', 3);

	// We remove the waiting image
	removeGeneralWait();

	// Reset the title
	pageTitle('home');

	// We show the success information
	$('#home .registerer .success').fadeIn('fast');

	// We quit the session
	logout();
}

// Does the user registration
function doRegister(username, domain, pass) {
	logThis('Trying to register an account...', 3);

	try {
		// We define the http binding parameters
		oArgs = new Object();

		if(HOST_BOSH_MAIN)
			oArgs.httpbase = HOST_BOSH_MAIN;
		else
			oArgs.httpbase = HOST_BOSH;

		// We create the new http-binding connection
		con = new JSJaCHttpBindingConnection(oArgs);

		// We setup the connection !
		con.registerHandler('onconnect', handleRegistered);
		con.registerHandler('onerror', handleError);

		// We retrieve what the user typed in the register inputs
		oArgs = new Object();
		oArgs.domain = trim(domain);
		oArgs.username = trim(username);
		oArgs.resource = JAPPIX_RESOURCE + ' Register (' + (new Date()).getTime() + ')';
		oArgs.pass = pass;
		oArgs.register = true;
		oArgs.secure = true;
		oArgs.xmllang = XML_LANG;

		con.connect(oArgs);

		// We change the registered information text
		$('#home .homediv.registerer').append(
			'
' +
				_e("You have been registered, here is your XMPP address:") + ' ' + con.username.htmlEnc() + '@' + con.domain.htmlEnc() + ' - ' + _e("Login") + '' +
			'
'
		);

		// Login link
		$('#home .homediv.registerer .success a').click(function() {
			return doLogin(con.username, con.domain, con.pass, con.resource, '10', false);
		});

		// Show the waiting image
		showGeneralWait();

		// Change the page title
		pageTitle('wait');
	}

	catch(e) {
		// Logs errors
		logThis(e, 1);
	}

	finally {
		return false;
	}
}

// Does the user anonymous login
function doAnonymous() {
	logThis('Trying to login anonymously...', 3);

	var aPath = '#home .anonymouser ';
	var room = $(aPath + '.room').val();
	var nick = $(aPath + '.nick').val();

	// If the form is correctly completed
	if(room && nick) {
		// We remove the not completed class to avoid problems
		$('#home .anonymouser input').removeClass('please-complete');

		// Redirect the user to the anonymous room
		window.location.href = JAPPIX_LOCATION + '?r=' + room + '&n=' + nick;
	}

	// We check if the form is entirely completed
	else {
		$(aPath + 'input[type=text]').each(function() {
			var select = $(this);

			if(!select.val())
				$(document).oneTime(10, function() {
					select.addClass('please-complete').focus();
				});
			else
				select.removeClass('please-complete');
		});
	}

	return false;
}

// Handles the user connected event
var CONNECTED = false;

function handleConnected() {
	logThis('Jappix is now connected.', 3);

	// Connection markers
	CONNECTED = true;
	RECONNECT_TRY = 0;
	RECONNECT_TIMER = 0;

	// We hide the home page
	$('#home').hide();

	// Not resumed?
	if(!RESUME) {
		// Remember the session?
		if(getDB('remember', 'session'))
			setPersistent('session', 1, CURRENT_SESSION);

		// We show the chatting app.
		createTalkPage();

		// We reset the homepage
		switchHome('default');

		// We get all the other things
		getEverything();

		// Set last activity stamp
		LAST_ACTIVITY = getTimeStamp();
	}

	// Resumed
	else {
		// Send our presence
		presenceSend();

		// Change the title
		updateTitle();
	}

	// Remove the waiting item
	removeGeneralWait();
}

// Handles the user disconnected event
function handleDisconnected() {
	logThis('Jappix is now disconnected.', 3);

	// Normal disconnection
	if(!CURRENT_SESSION && !CONNECTED)
		destroyTalkPage();
}

// Setups the normal connection
function setupCon(con,oExtend) {
	// We setup all the necessary handlers for the connection
	con.registerHandler('message', handleMessage);
	con.registerHandler('presence', handlePresence);
	con.registerHandler('iq', handleIQ);
	con.registerHandler('onconnect', handleConnected);
	con.registerHandler('onerror', handleError);
	con.registerHandler('ondisconnect', handleDisconnected);
	oExtend = oExtend||{};
	jQuery.each(oExtend,function(keywd,funct) {
	  con.registerHandler(keywd, funct);
	});
}

// Logouts from the server
function logout() {
	// We are not connected
	if(!isConnected())
		return false;

	// Disconnect from the XMPP server
	con.disconnect();

	logThis('Jappix is disconnecting...', 3);
}

// Terminates a session
function terminate() {
	if(!isConnected())
		return;

	// Clear temporary session storage
	resetConMarkers();

	// Show the waiting item (useful if BOSH is sloooow)
	showGeneralWait();

	// Change the page title
	pageTitle('wait');

	// Disconnect from the XMPP server
	logout();
}

// Quitss a session
function quit() {
	if(!isConnected())
		return;

	// We show the waiting image
	showGeneralWait();

	// Change the page title
	pageTitle('wait');

	// We disconnect from the XMPP server
	logout();
}

// Creates the reconnect pane
var RECONNECT_TRY = 0;
var RECONNECT_TIMER = 0;

function createReconnect(mode) {
	logThis('This is not a normal disconnection, show the reconnect pane...', 1);

	// Reconnect pane not yet displayed?
	if(!exists('#reconnect')) {
		// Blur the focused input/textarea/select
		$('input, select, textarea').blur();

		// Create the HTML code
		var html = '
' +
				'
' +
					_e("Due to a network issue, you were disconnected. What do you want to do now?");

		// Can we cancel reconnection?
		if(mode == 'normal')
			html += '' + _e("Cancel") + '';

		html += '' + _e("Reconnect") + '' +
			'

';

		// Append the code
		$('body').append(html);

		// Click events
		if(mode == 'normal')
			$('#reconnect a.finish.cancel').click(function() {
				return cancelReconnect();
			});

		$('#reconnect a.finish.reconnect').click(function() {
			return acceptReconnect(mode);
		});

		// Try to reconnect automatically after a while
		if(RECONNECT_TRY < 5)
			RECONNECT_TIMER = 5 + (5 * RECONNECT_TRY);
		else
			RECONNECT_TIMER = 120;

		// Change the try number
		RECONNECT_TRY++;

		// Fire the event!
		$('#reconnect a.finish.reconnect').everyTime('1s', function() {
			// We can reconnect!
			if(RECONNECT_TIMER == 0)
				return acceptReconnect(mode);

			// Button text
			if(RECONNECT_TIMER <= 10)
				$(this).text(_e("Reconnect") + ' (' + RECONNECT_TIMER + ')');

			// Remove 1 second
			RECONNECT_TIMER--;
		});

		// Page title
		updateTitle();
	}
}

// Reconnects the user if he was disconnected (network issue)
var RESUME = false;

function acceptReconnect(mode) {
	logThis('Trying to reconnect the user...', 3);

	// Resume marker
	RESUME = true;

	// Show waiting item
	showGeneralWait();

	// Reset some various stuffs
	var groupchats = '#page-engine .page-engine-chan[data-type=groupchat]';
	$(groupchats + ' .list .role').hide();
	$(groupchats + ' .one-group, ' + groupchats + ' .list .user').remove();
	$(groupchats).attr('data-initial', 'false');

	// Stop the timer
	$('#reconnect a.finish.reconnect').stopTime();

	// Remove the reconnect pane
	$('#reconnect').remove();

	// Try to login again
	if(mode == 'normal')
		loginFromSession(XMLFromString(CURRENT_SESSION));
	else if(mode == 'anonymous')
		anonymousLogin(HOST_ANONYMOUS);

	return false;
}

// Cancel the reconnection of user account (network issue)
function cancelReconnect() {
	logThis('User has canceled automatic reconnection...', 3);

	// Stop the timer
	$('#reconnect a.finish.reconnect').stopTime();

	// Remove the reconnect pane
	$('#reconnect').remove();

	// Destroy the talk page
	destroyTalkPage();

	// Renitialize the previous session parameters
	resetConMarkers();

	return false;
}

// Clears session reminder database
function clearLastSession() {
	// Clear temporary storage
	resetConMarkers();

	// Clear persistent storage
	if($(XMLFromString(getPersistent('session', 1))).find('stored').text() == 'true')
		removePersistent('session', 1);
}

// Resets the connection markers
function resetConMarkers() {
	CURRENT_SESSION = false;
	CONNECTED = false;
	RESUME = false;
	RECONNECT_TRY = 0;
	RECONNECT_TIMER = 0;
}

// Logins from a saved session
function loginFromSession(data) {
	// Select the data
	var session = $(data);

	// Fire the login event
	doLogin(
		session.find('username').text(),
		session.find('domain').text(),
		session.find('password').text(),
		session.find('resource').text(),
		session.find('priority').text(),
		false
	);
}

// Quits a session normally
function normalQuit() {
	// Reset our database
	clearLastSession();

	// We quit the current session
	quit();

	// We show an info
	openThisInfo(3);

	return false;
}

// Gets all the users stuffs
function getEverything() {
	getFeatures();
	getRoster();
	listPrivacy();
	getStorage(NS_ROSTERNOTES);
}

// Plugin launcher
function launchConnection() {
	// Logouts when Jappix is closed
	$(window).bind('beforeunload', terminate);

	// Nothing to do when anonymous!
	if(isAnonymous())
		return;

	// Try to resume a stored session, if not anonymous
	var session = XMLFromString(getPersistent('session', 1));

	if($(session).find('stored').text() == 'true') {
		// Hide the homepage
		$('#home').hide();

		// Show the waiting icon
		showGeneralWait();

		// Login!
		loginFromSession(session);

		logThis('Saved session found, resuming it...', 3);
	}

	// Not connected, maybe a XMPP link is submitted?
	else if((parent.location.hash != '#OK') && LINK_VARS['x']) {
		switchHome('loginer');

		logThis('A XMPP link is set, switch to login page.', 3);
	}
}

// Launch this plugin!
$(document).ready(launchConnection);
<|endoftext|>


<commit_before>/**
 * Theme Customizer enhancements for a better user experience.
 *
 * Contains handlers to make Theme Customizer preview reload changes asynchronously.
 */

( function( $ ) {
	// Site title and description.
	wp.customize( 'blogname', function( value ) {
		value.bind( function( to ) {
			$( '.site-title a' ).text( to );
		} );
	} );
	wp.customize( 'blogdescription', function( value ) {
		value.bind( function( to ) {
			$( '.site-description' ).text( to );
		} );
	} );
	// Header text color.
	wp.customize( 'header_textcolor', function( value ) {
		value.bind( function( to ) {
			if ( 'blank' === to ) {
				$( '.site-title, .site-description' ).css( {
					'clip': 'rect(1px, 1px, 1px, 1px)',
					'position': 'absolute'
				} );
			} else {
				$( '.site-title, .site-description' ).css( {
					'clip': 'auto',
					'color': to,
					'position': 'relative'
				} );
			}
		} );
	} );
} )( jQuery );
<commit_msg>This fixes the header text color link (blogname) to also update the same way as the blogdescription<commit_after>/**
 * Theme Customizer enhancements for a better user experience.
 *
 * Contains handlers to make Theme Customizer preview reload changes asynchronously.
 */

( function( $ ) {
	// Site title and description.
	wp.customize( 'blogname', function( value ) {
		value.bind( function( to ) {
			$( '.site-title a' ).text( to );
		} );
	} );
	wp.customize( 'blogdescription', function( value ) {
		value.bind( function( to ) {
			$( '.site-description' ).text( to );
		} );
	} );
	// Header text color.
	wp.customize( 'header_textcolor', function( value ) {
		value.bind( function( to ) {
			if ( 'blank' === to ) {
				$( '.site-title, .site-description' ).css( {
					'clip': 'rect(1px, 1px, 1px, 1px)',
					'position': 'absolute'
				} );
			} else {
				$( '.site-title a, .site-description' ).css( {
					'clip': 'auto',
					'color': to,
					'position': 'relative'
				} );
			}
		} );
	} );
} )( jQuery );
<|endoftext|>


<commit_before>var margin = {top: 20, right: 20, bottom: 30, left: 140},
  width = 760 - margin.left - margin.right,
  height = 500 - margin.top - margin.bottom;

var color = d3.scale.category20();

var force = d3.layout.force()
    .charge(-80)
    .linkDistance(200)
    .friction(0.9)
    .size([width, height]);

var forceSvg = d3.select("div#chord_chart").append("svg")
    .attr("width", width)
    .attr("height", height);

var forceListSvg = d3.select('div#force_list').append('svg')
    .attr('width', 200)
    .attr('height', 500)
    .append('g')
      .attr("transform", "translate(" + margin.right + "," + margin.top + ")");;

var node_drag = d3.behavior.drag()
    .on("dragstart", dragstart)
    .on("drag", dragmove)
    .on("dragend", dragend);
    function dragstart(d, i) {
        force.stop() // stops the force auto positioning before you start dragging
    }
    function dragmove(d, i) {
        d.px += d3.event.dx;
        d.py += d3.event.dy;
        d.x += d3.event.dx;
        d.y += d3.event.dy;
    }
    function dragend(d, i) {
        d.fixed = true; // of course set the node to fixed so the force doesn't include the node in its auto positioning stuff
        force.resume();
    }
    function releasenode(d) {
        d.fixed = false; // of course set the node to fixed so the force doesn't include the node in its auto positioning stuff
        //force.resume();
    };

d3.csv("cooccurrenceMatrixData.csv", function(data){

  selectedList = ['pm','school','mandarin','up','chinese','strike','new',
  'bomb','blast','attack','die'];
  data1 = $.map(data, function(element){
    return ($.inArray(element.word1,selectedList)>-1?element:null);
  });
  data = $.map(data1, function(element){
    return ($.inArray(element.word2,selectedList)>-1?element:null);
  });

  graphDict = {};
  graphDict['nodes'] = [];
  graphDict['links'] = [];
  entrylist = [];
  for (i=0; i<data.length; i++){
    if ($.inArray(data[i].word1, entrylist) < 0){
      dict = {};
      dict['name'] = data[i].word1
      dict['group'] = 0
      graphDict['nodes'].push(dict)
      entrylist.push(data[i].word1);
    };
    if ($.inArray(data[i].word2, entrylist) < 0){
      dict = {};
      dict['name'] = data[i].word2
      dict['group'] = 0
      graphDict['nodes'].push(dict)
      entrylist.push(data[i].word2);
    };
    dict = {};
    dict['source'] = entrylist.indexOf(data[i].word1);
    dict['target'] = entrylist.indexOf(data[i].word2);
    dict['value'] = +data[i].size
    graphDict['links'].push(dict);

  };
  var term_label = forceListSvg.selectAll('.force_item')
        .data(entrylist)
        .enter()
      .append('text')
        .attr('class', 'force_item')
        .attr("x", 10)
        .attr("y", function(d,i){ return i+1+"em"; })
        .style("text-anchor", "middle")
        .style("font-size", "15px")
        .style("fill", "#53565A")
        .transition()
        .duration(750)
        //.style('fill', function(d){ return line_color(d.term); })
        .text(function(d){ return d; });

  drawGraph(graphDict);

  function drawGraph(graph){
    force
      .nodes(graph.nodes)
      .links(graph.links)
      .start();

    var graphMin = d3.min(graph.links, function(d){ return d.size; });
    var graphMax = d3.max(graph.links, function(d){ return d.size; });

    var fill = d3.scale.ordinal()
        .domain([graphMin, graphMax])
        .range(["#f7fcfd","#e5f5f9","#ccece6","#99d8c9","#66c2a4",
          "#41ae76","#238b45","#006d2c","#00441b"]);

    var div = d3.select('div#chord_chart').append('div')
            .attr('class', 'tooltip')
            .style('opacity', 0);

    var link = forceSvg.selectAll(".link")
        .data(graph.links)
      .enter().append("line")
        .attr("class", "link")
        .style('stroke-width', 1)
        .style('stroke', function(d){ return fill(d.value); });
        //.style("stroke-width", function(d) { return Math.sqrt(d.value); });

    var node = forceSvg.selectAll(".node")
        .data(graph.nodes)
      .enter().append("circle")
        .attr("class", "node")
        .attr("r", 5)
        .style("fill", function(d) { return color(d.group); })
        .on('dblclick', releasenode)
        .on('click', connectedNodes)
        .call(node_drag);
        //.call(force.drag);

    node
        .on('mouseover', function(d,i,j){
            d3.select(this).transition().duration(600)
              .attr('r', 8).style('opacity', 1);
            div.transition()
              .duration(500)
              .style('opacity', 1);
            div.html(d.name)
              .style('left', '300px')
              .style('top', '10px');
              //.style('left', (d3.event.pageX) + 10 + "px")
              //.style('top', (d3.event.pageY) + 2 + "px")
              //.style('color', line_color(used_data[j].term));
        })
        .on('mouseout', function(d){
            d3.select(this).transition().duration(600)
              .attr('r', 5).style('opacity', 1);
            div.transition()
              .duration(500)
              .style('opacity', 0);
        });

    node.append("title")
        .text(function(d) { return d.name; });

    force.on("tick", function() {
      link.attr("x1", function(d) { return d.source.x; })
          .attr("y1", function(d) { return d.source.y; })
          .attr("x2", function(d) { return d.target.x; })
          .attr("y2", function(d) { return d.target.y; });

      node.attr("cx", function(d) { return d.x; })
          .attr("cy", function(d) { return d.y; });
    });

/*
    var k = 0;
    while ((force.alpha() > 1e-2) && (k < 150)) {
        force.tick(),
        k = k + 1;
    }
*/
    //Toggle stores whether the highlighting is on
  var toggle = 0;

  //Create an array logging what is connected to what
  var linkedByIndex = {};
  for (i = 0; i < graph.nodes.length; i++) {
      linkedByIndex[i + "," + i] = 1;
  };
  graph.links.forEach(function (d) {
      linkedByIndex[d.source.index + "," + d.target.index] = 1;
  });

  //This function looks up whether a pair are neighbours
  function neighboring(a, b) {
      return linkedByIndex[a.index + "," + b.index];
  }

  function connectedNodes() {

    if (toggle == 0) {
        //Reduce the opacity of all but the neighbouring nodes
        d = d3.select(this).node().__data__;
        node.style("opacity", function (o) {
            return neighboring(d, o) | neighboring(o, d) ? 1 : 0.1;
        });

        link.style("opacity", function (o) {
            return d.index==o.source.index | d.index==o.target.index ? 1 : 0.1;
        });

        //Reduce the op

        toggle = 1;
    } else {
        //Put them back to opacity=1
        node.style("opacity", 1);
        link.style("opacity", 1);
        toggle = 0;
    }

  }
  }

});

/*
d3.json("newsGraph.json", function(error, graph) {
  testGraph = JSON.parse(JSON.stringify(graph))

  selectedList = ['up','police','china','labor','union'];
  selectedData1 = $.map(testGraph.nodes, function(element){
      return ($.inArray(element.name,selectedList)>-1?element:null);
    });

  selectedData2 = $.map(testGraph.links, function(element){
      return ($.inArray(element['name1'],selectedList)>-1?element:null);
    });

  selectedData3 = $.map(selectedData2, function(element){
      return ($.inArray(element.name2,selectedList)>-1?element:null);
    });

  new_graph = {};
  new_graph['nodes'] = graph.nodes;
  new_graph['links'] = selectedData3;

  //drawGraph(graph, selectedData1, selectedData3);
  drawGraph(graph);

});
*/

<commit_msg>update data<commit_after>var margin = {top: 20, right: 20, bottom: 30, left: 140},
  width = 760 - margin.left - margin.right,
  height = 500 - margin.top - margin.bottom;

var color = d3.scale.category20();

var force = d3.layout.force()
    .charge(-80)
    .linkDistance(200)
    .friction(0.9)
    .size([width, height]);

var forceSvg = d3.select("div#chord_chart").append("svg")
    .attr("width", width)
    .attr("height", height);

var forceListSvg = d3.select('div#force_list').append('svg')
    .attr('width', 200)
    .attr('height', 500)
    .append('g')
      .attr("transform", "translate(" + margin.right + "," + margin.top + ")");;

var node_drag = d3.behavior.drag()
    .on("dragstart", dragstart)
    .on("drag", dragmove)
    .on("dragend", dragend);
    function dragstart(d, i) {
        force.stop() // stops the force auto positioning before you start dragging
    }
    function dragmove(d, i) {
        d.px += d3.event.dx;
        d.py += d3.event.dy;
        d.x += d3.event.dx;
        d.y += d3.event.dy;
    }
    function dragend(d, i) {
        d.fixed = true; // of course set the node to fixed so the force doesn't include the node in its auto positioning stuff
        force.resume();
    }
    function releasenode(d) {
        d.fixed = false; // of course set the node to fixed so the force doesn't include the node in its auto positioning stuff
        //force.resume();
    };

d3.csv("cooccurrenceMatrixData.csv", function(data){

  totallist = [];
  for (i=0; i<data.length; i++){
    if ($.inArray(data[i].word1, totallist) < 0){
      totallist.push(data[i].word1);
    }
    if ($.inArray(data[i].word2, totallist) < 0){
      totallist.push(data[i].word2);
    }
  }

  selectedList = ['pm','school','mandarin','up','chinese','strike','new',
  'bomb','blast','attack','die'];
  data1 = $.map(data, function(element){
    return ($.inArray(element.word1,selectedList)>-1?element:null);
  });
  data = $.map(data1, function(element){
    return ($.inArray(element.word2,selectedList)>-1?element:null);
  });

  graphDict = {};
  graphDict['nodes'] = [];
  graphDict['links'] = [];
  entrylist = [];
  for (i=0; i<data.length; i++){
    if ($.inArray(data[i].word1, entrylist) < 0){
      dict = {};
      dict['name'] = data[i].word1
      dict['group'] = 0
      graphDict['nodes'].push(dict)
      entrylist.push(data[i].word1);
    };
    if ($.inArray(data[i].word2, entrylist) < 0){
      dict = {};
      dict['name'] = data[i].word2
      dict['group'] = 0
      graphDict['nodes'].push(dict)
      entrylist.push(data[i].word2);
    };
    dict = {};
    dict['source'] = entrylist.indexOf(data[i].word1);
    dict['target'] = entrylist.indexOf(data[i].word2);
    dict['value'] = +data[i].size
    graphDict['links'].push(dict);

  };
  var term_label = forceListSvg.selectAll('.force_item')
        .data(totallist)
        .enter()
      .append('text')
        .attr('class', 'force_item')
        .attr("x", 50)
        .attr("y", function(d,i){ return i+1+"em"; })
        .style("text-anchor", "middle")
        .style("font-size", "15px")
        .style("fill", "#53565A")
        .transition()
        .duration(750)
        //.style('fill', function(d){ return line_color(d.term); })
        .text(function(d){ return d; });

  drawGraph(graphDict);

  function drawGraph(graph){
    force
      .nodes(graph.nodes)
      .links(graph.links)
      .start();

    var graphMin = d3.min(graph.links, function(d){ return d.size; });
    var graphMax = d3.max(graph.links, function(d){ return d.size; });

    var fill = d3.scale.ordinal()
        .domain([graphMin, graphMax])
        .range(["#f7fcfd","#e5f5f9","#ccece6","#99d8c9","#66c2a4",
          "#41ae76","#238b45","#006d2c","#00441b"]);

    var div = d3.select('div#chord_chart').append('div')
            .attr('class', 'tooltip')
            .style('opacity', 0);

    var link = forceSvg.selectAll(".link")
        .data(graph.links)
      .enter().append("line")
        .attr("class", "link")
        .style('stroke-width', 1)
        .style('stroke', function(d){ return fill(d.value); });
        //.style("stroke-width", function(d) { return Math.sqrt(d.value); });

    var node = forceSvg.selectAll(".node")
        .data(graph.nodes)
      .enter().append("circle")
        .attr("class", "node")
        .attr("r", 5)
        .style("fill", function(d) { return color(d.group); })
        .on('dblclick', releasenode)
        .on('click', connectedNodes)
        .call(node_drag);
        //.call(force.drag);

    node
        .on('mouseover', function(d,i,j){
            d3.select(this).transition().duration(600)
              .attr('r', 8).style('opacity', 1);
            div.transition()
              .duration(500)
              .style('opacity', 1);
            div.html(d.name)
              .style('left', '300px')
              .style('top', '10px');
              //.style('left', (d3.event.pageX) + 10 + "px")
              //.style('top', (d3.event.pageY) + 2 + "px")
              //.style('color', line_color(used_data[j].term));
        })
        .on('mouseout', function(d){
            d3.select(this).transition().duration(600)
              .attr('r', 5).style('opacity', 1);
            div.transition()
              .duration(500)
              .style('opacity', 0);
        });

    node.append("title")
        .text(function(d) { return d.name; });

    force.on("tick", function() {
      link.attr("x1", function(d) { return d.source.x; })
          .attr("y1", function(d) { return d.source.y; })
          .attr("x2", function(d) { return d.target.x; })
          .attr("y2", function(d) { return d.target.y; });

      node.attr("cx", function(d) { return d.x; })
          .attr("cy", function(d) { return d.y; });
    });

/*
    var k = 0;
    while ((force.alpha() > 1e-2) && (k < 150)) {
        force.tick(),
        k = k + 1;
    }
*/
    //Toggle stores whether the highlighting is on
  var toggle = 0;

  //Create an array logging what is connected to what
  var linkedByIndex = {};
  for (i = 0; i < graph.nodes.length; i++) {
      linkedByIndex[i + "," + i] = 1;
  };
  graph.links.forEach(function (d) {
      linkedByIndex[d.source.index + "," + d.target.index] = 1;
  });

  //This function looks up whether a pair are neighbours
  function neighboring(a, b) {
      return linkedByIndex[a.index + "," + b.index];
  }

  function connectedNodes() {

    if (toggle == 0) {
        //Reduce the opacity of all but the neighbouring nodes
        d = d3.select(this).node().__data__;
        node.style("opacity", function (o) {
            return neighboring(d, o) | neighboring(o, d) ? 1 : 0.1;
        });

        link.style("opacity", function (o) {
            return d.index==o.source.index | d.index==o.target.index ? 1 : 0.1;
        });

        //Reduce the op

        toggle = 1;
    } else {
        //Put them back to opacity=1
        node.style("opacity", 1);
        link.style("opacity", 1);
        toggle = 0;
    }

  }
  }

});

/*
d3.json("newsGraph.json", function(error, graph) {
  testGraph = JSON.parse(JSON.stringify(graph))

  selectedList = ['up','police','china','labor','union'];
  selectedData1 = $.map(testGraph.nodes, function(element){
      return ($.inArray(element.name,selectedList)>-1?element:null);
    });

  selectedData2 = $.map(testGraph.links, function(element){
      return ($.inArray(element['name1'],selectedList)>-1?element:null);
    });

  selectedData3 = $.map(selectedData2, function(element){
      return ($.inArray(element.name2,selectedList)>-1?element:null);
    });

  new_graph = {};
  new_graph['nodes'] = graph.nodes;
  new_graph['links'] = selectedData3;

  //drawGraph(graph, selectedData1, selectedData3);
  drawGraph(graph);

});
*/

<|endoftext|>


<commit_before>/*!
 * Start Bootstrap - Freelancer Bootstrap Theme (http://startbootstrap.com)
 * Code licensed under the Apache License v2.0.
 * For details, see http://www.apache.org/licenses/LICENSE-2.0.
 */

// jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
    $('.page-scroll a').bind('click', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top
        }, 1500, 'easeInOutExpo');
        event.preventDefault();
    });
});

// Highlight the top nav as scrolling occurs
$('body').scrollspy({
    target: '.navbar-fixed-top'
})

// Closes the Responsive Menu on Menu Item Click
$('.navbar-collapse ul li a').click(function() {
    $('.navbar-toggle:visible').click();
});<commit_msg>[update] navigation header menu to scroll page<commit_after>/*!
 * Start Bootstrap - Freelancer Bootstrap Theme (http://startbootstrap.com)
 * Code licensed under the Apache License v2.0.
 * For details, see http://www.apache.org/licenses/LICENSE-2.0.
 */

// jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
    $('.page-scroll a').bind('click', function(event) {
        var $anchor = $(this);
        // MODIFIED FOR ANIBAL
        var sumAllcomponentHeader = parseInt($('nav').css("padding-top"));
        sumAllcomponentHeader += parseInt($('nav').css("padding-bottom"));
        sumAllcomponentHeader += parseInt($('nav').css("margin-top"));
        sumAllcomponentHeader += parseInt($('nav').css("margin-bottom"));

        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top - sumAllcomponentHeader
        }, 1500, 'easeInOutExpo');
        event.preventDefault();
    });
});

// Highlight the top nav as scrolling occurs
$('body').scrollspy({
    target: '.navbar-fixed-top'
})

// Closes the Responsive Menu on Menu Item Click
$('.navbar-collapse ul li a').click(function() {
    $('.navbar-toggle:visible').click();
});<|endoftext|>


<commit_before>/**
 * ownCloud - spreedme
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Leon <leon@struktur.de>
 * @copyright Leon 2015
 */

// This file is loaded in ownCloud context

(function($, OC) {
$(document).ready(function() {

	if (window.parent !== window) {
		$("body").addClass("in-iframe");

		var sharedConfig = $.parseJSON($("#sharedconfig").html());
		var ALLOWED_PARTNERS = sharedConfig.allowed_partners.split(",");

		var postMessageAPI = new PostMessageAPI({
			allowedPartners: ALLOWED_PARTNERS,
			parent: window.parent
		});
	}

	var currentRoom = "";
	var baseUrl = OC.generateUrl('/apps/spreedme');
	var roomUpdated = function(room) {
		currentRoom = room;
	};
	var requestTP = function(userid, expiration, cb_success, cb_error) {
		if (userid.length < 1) {
			alert("Please enter a valid name to invite");
			return;
		}
		if (expiration.length < 1 || expiration < 1 || parseInt(expiration, 10) != expiration) {
			alert("Please enter a valid expiration date");
			return;
		}
		if (expiration > (new Date().getTime() / 1000) + (60 * 60 * 24)) {
			var response = confirm("Do you really want to generate a Temporary Passwords which is valid for more than 1 day?");
			if (!response) {
				return;
			}
		}

		var data = {
			userid: userid,
			expiration: expiration
		};
		$.ajax({
			url: baseUrl + '/api/v1/admin/tp',
			type: 'POST',
			data: $.param(data)
		}).done(function (response) {
			if (response.success === true) {
				cb_success(response.tp);
			} else {
				cb_error(response.error);
			}
		}).fail(function (response, code) {
			console.log(response, code);
		});
	};

	var useridField = $("form input[name=userid]");
	var expirationField = $("form input[name=expiration]");
	$("form input[type=submit]").click(function(e) {
		e.preventDefault();

		requestTP(useridField.val(), Math.round(new Date(expirationField.datetimepicker("getDate")).getTime() / 1000), function(tp) {
			$("[name=temporarypassword]")
				.attr("value", tp)
				.click(function() {
					$(this).select();
				});
			$("[name=temporarypasswordurl]")
				.attr("value", document.location.origin + baseUrl + "?tp=" + window.encodeURIComponent(tp) + (currentRoom === "" ? "" : "#" + window.encodeURIComponent(currentRoom)))
				.click(function() {
					$(this).select();
				});

			$("body")
				.removeClass("failure")
				.addClass("success");
		}, function(error) {
			$("#errorcode").text(error);

			$("body")
				.removeClass("success")
				.addClass("failure");
		});
	});

	expirationField.datetimepicker({
		oneLine: true,
		minDate: new Date(),
		controlType: "select"
	});
	var date = new Date((new Date()).getTime() + (1000 * 60 * 60 * 2)); // Add 2 hours
	expirationField.datetimepicker("setDate", date);

	if (postMessageAPI) {
		postMessageAPI.bind(function(event) {
			switch (event.data.type) {
			case "roomChanged":
				roomUpdated(event.data.message.room);
				break;
			default:
				console.log("Got unsupported message type", event.data.type);
			}
		});

		postMessageAPI.post({
			type: "init"
		});
	}

});
})(jQuery, OC);
<commit_msg>Fix typo<commit_after>/**
 * ownCloud - spreedme
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Leon <leon@struktur.de>
 * @copyright Leon 2015
 */

// This file is loaded in ownCloud context

(function($, OC) {
$(document).ready(function() {

	if (window.parent !== window) {
		$("body").addClass("in-iframe");

		var sharedConfig = $.parseJSON($("#sharedconfig").html());
		var ALLOWED_PARTNERS = sharedConfig.allowed_partners.split(",");

		var postMessageAPI = new PostMessageAPI({
			allowedPartners: ALLOWED_PARTNERS,
			parent: window.parent
		});
	}

	var currentRoom = "";
	var baseUrl = OC.generateUrl('/apps/spreedme');
	var roomUpdated = function(room) {
		currentRoom = room;
	};
	var requestTP = function(userid, expiration, cb_success, cb_error) {
		if (userid.length < 1) {
			alert("Please enter a valid name to invite");
			return;
		}
		if (expiration.length < 1 || expiration < 1 || parseInt(expiration, 10) != expiration) {
			alert("Please enter a valid expiration date");
			return;
		}
		if (expiration > (new Date().getTime() / 1000) + (60 * 60 * 24)) {
			var response = confirm("Do you really want to generate a Temporary Password which is valid for more than 1 day?");
			if (!response) {
				return;
			}
		}

		var data = {
			userid: userid,
			expiration: expiration
		};
		$.ajax({
			url: baseUrl + '/api/v1/admin/tp',
			type: 'POST',
			data: $.param(data)
		}).done(function (response) {
			if (response.success === true) {
				cb_success(response.tp);
			} else {
				cb_error(response.error);
			}
		}).fail(function (response, code) {
			console.log(response, code);
		});
	};

	var useridField = $("form input[name=userid]");
	var expirationField = $("form input[name=expiration]");
	$("form input[type=submit]").click(function(e) {
		e.preventDefault();

		requestTP(useridField.val(), Math.round(new Date(expirationField.datetimepicker("getDate")).getTime() / 1000), function(tp) {
			$("[name=temporarypassword]")
				.attr("value", tp)
				.click(function() {
					$(this).select();
				});
			$("[name=temporarypasswordurl]")
				.attr("value", document.location.origin + baseUrl + "?tp=" + window.encodeURIComponent(tp) + (currentRoom === "" ? "" : "#" + window.encodeURIComponent(currentRoom)))
				.click(function() {
					$(this).select();
				});

			$("body")
				.removeClass("failure")
				.addClass("success");
		}, function(error) {
			$("#errorcode").text(error);

			$("body")
				.removeClass("success")
				.addClass("failure");
		});
	});

	expirationField.datetimepicker({
		oneLine: true,
		minDate: new Date(),
		controlType: "select"
	});
	var date = new Date((new Date()).getTime() + (1000 * 60 * 60 * 2)); // Add 2 hours
	expirationField.datetimepicker("setDate", date);

	if (postMessageAPI) {
		postMessageAPI.bind(function(event) {
			switch (event.data.type) {
			case "roomChanged":
				roomUpdated(event.data.message.room);
				break;
			default:
				console.log("Got unsupported message type", event.data.type);
			}
		});

		postMessageAPI.post({
			type: "init"
		});
	}

});
})(jQuery, OC);
<|endoftext|>


<commit_before>define(["js/html/HtmlElement", "underscore", "moment"], function (HtmlElement, _, moment) {
        var radioNameCache = {};

        return HtmlElement.inherit("js.html.Input", {
            $classAttributes: ['updateOnEvent','checked'],
            defaults: {
                type: 'text',
                checked: false,
                updateOnEvent: 'keyup'
            },
            _commitChangedAttributes: function(attributes){
                if(this.$.type === 'radio'){

                    if(attributes.name){

                        if (this.$previousAttributes.name) {
                            delete radioNameCache[this.$previousAttributes.name][this.$cid];
                        }

                        radioNameCache[attributes.name] = radioNameCache[attributes.name] || {};
                        radioNameCache[attributes.name][this.$cid] = this;
                    }

                }
                this.callBase();
            },
            _renderEnabled: function(enabled){
                if(enabled){
                    this.$el.removeAttribute("disabled");
                }else{
                    this.$el.setAttribute("disabled","disabled");
                }
            },
            _renderValue: function (value) {
                if(value === null || value === undefined){
                    value = "";
                }
                if(String(value) !== this.$el.value){
                    if(this.$.type === "date"){
                        if(value instanceof Date){
                            value = moment(value).format("YYYY-MM-DD");
                        }
                    }

                    this.$el.value = value;
                }
            },
            _commitChecked: function(checked){
                // sync shadow dom
                if (checked && this.$.type === "radio") {
                    var cache = radioNameCache[this.$.name];
                    for (var id in cache) {
                        if (cache.hasOwnProperty(id)) {
                            if (cache[id] !== this) {
                                cache[id].set('checked', false);
                            }
                        }
                    }
                }
            },
            _renderChecked: function (checked) {
                this.$el.checked = checked;
            },
            _transformValue: function(value){
                if(this.$.type === "number"){
                    if(value === ""){
                        return null;
                    }
                    value = parseInt(value);
                    if (isNaN(value)) {
                        value = this.$.value;
                    }
                } else if(this.$.type === "date"){
                    try{
                        value = value !== "" ? new Date(value) : null;
                    }catch(e){
                        this.log("Invalid Date","warn");
                        value = this.$.value;
                    }
                }

                return value;
            },
            _bindDomEvents: function () {

                var self = this;
                if (_.include(["text","password","date","number"], this.$.type)) {
                    if(this.$.type === "date" || this.$.type === "number"){
                        this.$.updateOnEvent = "change";
                    }
                    this.bindDomEvent(this.$.updateOnEvent, function (e) {
                        self.set('value', self._transformValue(self.$el.value));
                    });

                } else if (this.$.type === "checkbox" || this.$.type === "radio") {
                    this.bindDomEvent('click', function (e) {
                        self.set('checked', self.$el.checked);
                    });
                }

                this.callBase();
            }
        });
    }
);<commit_msg>fixed attribute deletion<commit_after>define(["js/html/HtmlElement", "underscore", "moment"], function (HtmlElement, _, moment) {
        var radioNameCache = {};

        return HtmlElement.inherit("js.html.Input", {
            $classAttributes: ['updateOnEvent','checked'],
            defaults: {
                type: 'text',
                checked: false,
                updateOnEvent: 'keyup'
            },
            _commitChangedAttributes: function(attributes){
                if(this.$.type === 'radio'){

                    if(attributes.name){

                        if (this.$previousAttributes.name && radioNameCache[this.$previousAttributes.name]) {
                            delete radioNameCache[this.$previousAttributes.name][this.$cid];
                        }

                        radioNameCache[attributes.name] = radioNameCache[attributes.name] || {};
                        radioNameCache[attributes.name][this.$cid] = this;
                    }

                }
                this.callBase();
            },
            _renderEnabled: function(enabled){
                if(enabled){
                    this.$el.removeAttribute("disabled");
                }else{
                    this.$el.setAttribute("disabled","disabled");
                }
            },
            _renderValue: function (value) {
                if(value === null || value === undefined){
                    value = "";
                }
                if(String(value) !== this.$el.value){
                    if(this.$.type === "date"){
                        if(value instanceof Date){
                            value = moment(value).format("YYYY-MM-DD");
                        }
                    }

                    this.$el.value = value;
                }
            },
            _commitChecked: function(checked){
                // sync shadow dom
                if (checked && this.$.type === "radio") {
                    var cache = radioNameCache[this.$.name];
                    for (var id in cache) {
                        if (cache.hasOwnProperty(id)) {
                            if (cache[id] !== this) {
                                cache[id].set('checked', false);
                            }
                        }
                    }
                }
            },
            _renderChecked: function (checked) {
                this.$el.checked = checked;
            },
            _transformValue: function(value){
                if(this.$.type === "number"){
                    if(value === ""){
                        return null;
                    }
                    value = parseInt(value);
                    if (isNaN(value)) {
                        value = this.$.value;
                    }
                } else if(this.$.type === "date"){
                    try{
                        value = value !== "" ? new Date(value) : null;
                    }catch(e){
                        this.log("Invalid Date","warn");
                        value = this.$.value;
                    }
                }

                return value;
            },
            _bindDomEvents: function () {

                var self = this;
                if (_.include(["text","password","date","number"], this.$.type)) {
                    if(this.$.type === "date" || this.$.type === "number"){
                        this.$.updateOnEvent = "change";
                    }
                    this.bindDomEvent(this.$.updateOnEvent, function (e) {
                        self.set('value', self._transformValue(self.$el.value));
                    });

                } else if (this.$.type === "checkbox" || this.$.type === "radio") {
                    this.bindDomEvent('click', function (e) {
                        self.set('checked', self.$el.checked);
                    });
                }

                this.callBase();
            }
        });
    }
);<|endoftext|>


<commit_before>/*!
 * jqTerminal
 * Copyright 2013, 2014 Federico Caminiti
 * Released under the BSD-2-Clause license
 * http://opensource.org/licenses/BSD-2-Clause
 */

var Terminal = function (user, prompt,container) {

		// Private variables.
		var _hostAndPrompt = '';
		var _user = "user";
		var _containerId = '';
		var _promptSymbol = '';
		var _eraseLimit;
		var _self;
		var _filesInDirectory = [{name:"hello.txt",mimeType:"text/plain",content:"Hola, mundo!.",permissions:"rw-r--r--",type:1,owner:_user,size:1,date:"18 Oct 16:45"}];
		var _consoleCommands = [];

		// Gets the commands that was typed into the console.
		function getCommandInput()
		{
			var lastLine = $(".console").val().split('\n')[$(".console").val().split('\n').length-1];
			command = lastLine.split(_promptSymbol)[1];
			return command;
		}

		// Inserts a new line in the console.
		function _insertNewLine()
		{
			 $(".console").val($(".console").val() + '\n' + _hostAndPrompt);
			  // Set the limit for erasing the conosole to the beginning of the newline.
			 _eraseLimit = $(".console").val().length;
		}

		// Clear the console.
		function _clearConsole()
		{
			$(".console").val("" + _hostAndPrompt);
			_eraseLimit = _hostAndPrompt.length;
		}

		// Writes the given text on the console.
		function _write(text)
		{
		  $(".console").val($(".console").val() + text);
		}

		// Executes a given command.
		function executeCommand(command,arguments)
		{
			var commandPos = $.inArray(command, $.map(_consoleCommands,function(item,index){ return item.name;}));
			if( commandPos != -1)
			{
				_consoleCommands[commandPos].run(arguments,_self);
			}
			else
			{
				 $(".console").val($(".console").val() + "\n");
				_write("bash: " + command + ": command not found");
			}
		}

		// Handles the click event.
		function handleClick(event)
		{
			if($(".console")[0].selectionStart  <= _eraseLimit || $(".console")[0].selectionEnd <= _eraseLimit)
			{
				$(".console")[0].selectionStart = _eraseLimit;
				$(".console")[0].selectionEnd = _eraseLimit;
			}
		}

		/*
		Handles the keypress events to prevent the user to erase the command prompt.
		Relevant keys/events:

		8  - Backspace.
		13 - Enter.
		36 - Init key.
		37 - Arrow back.
		38 - Arrow up.
		39 - Arrow forward (this case is not being handled).
		40 - Arrow down.
		46 - Supress key.

		*/
		function handleKeydown(event)
		{

			console.log(event.which);

			switch(event.which)
			{
				case 13:
					 handleEnterKey(event);
					break;
				case 36:
					handleInitKey();
				case 46:
					preventPromptErasing(true);
				case 8:
				case 37:
					preventPromptErasing(false);
					break;
				case 38:
				case 40:
					event.preventDefault();
					break;
				default:
					// As of now, nothing is done in this case.
					break;
			}
		}

		// Handles the init key.
		function handleInitKey()
		{
		  event.preventDefault();
		  $(".console")[0].selectionStart = _eraseLimit;
		  $(".console")[0].selectionEnd = _eraseLimit;
		}

		// Handles the enter key.
		function handleEnterKey(event)
		{
		   event.preventDefault(); // Do not insert a newline. Instead, let us handle the event.
		   var commandQuery = getCommandInput().trim();
		   if(commandQuery != "")
		   {
			  var splitCommand = commandQuery.split(" ");
			  executeCommand(splitCommand[0],splitCommand);
		   }

		  if(splitCommand[0].indexOf("clear") == -1)
		  {
			 _insertNewLine();
		  }

		  return false;
		}

		// Prevents the user from deleting the command prompt.
		function preventPromptErasing(deleteKeyPressed)
		{

			if($(".console")[0].selectionStart  < _eraseLimit || $(".console")[0].selectionEnd < _eraseLimit || (!deleteKeyPressed && $(".console")[0].selectionStart  == _eraseLimit || $(".console")[0].selectionEnd == _eraseLimit))
			{
				event.preventDefault();
				$(".console")[0].selectionStart = _eraseLimit;
				$(".console")[0].selectionEnd = _eraseLimit;
			}
		}

	// Initialize the console and all of its relevant variables.
	function doInitialize()
	{
		// Initialize variables
		_promptSymbol = prompt;
		_hostAndPrompt = user + prompt;
		_containerId = container;
		_self = this;
		var con = $("<textarea class=\"console\" spellcheck=\"false\">");
		con.val(_hostAndPrompt);
		_eraseLimit = _hostAndPrompt.length;
		con.keydown(function( event ) { handleKeydown(event);});

		// Initialize the conosle and place it inside its container.
		var term = $("<textarea class=\"console\" spellcheck=\"false\">");
		term.val(_hostAndPrompt);
		term.keydown(function( event ) { handleKeydown(event);});
		$("#" + _containerId).append(term);
		$("#" + _containerId).click(function (event) {handleClick(event);});
	}

	/*
		Adds a command:

		A command should have, at least the following sections:
		- name (the name of the command).
		- man  (a description of what it does).
		- run  (the code that executes when the console runs the command).
	*/
	function addCommand(command)
	{
		if(command.name !== undefined && command.man !== undefined && command.run !== undefined)
		{
			_consoleCommands.push(command);
		}
	}

	// Removes the console from its container.
	function doDestroy()
	{
		$("#" + _containerId).remove();
	}

	return {
		initialize: doInitialize,
		clear: _clearConsole,
		write: _write,
		files: _filesInDirectory,
		commands: _consoleCommands,
		addCommand:addCommand,
		destroy: doDestroy
	};
};
<commit_msg>FIX: undefined object when inputing empty line<commit_after>/*!
 * jqTerminal
 * Copyright 2013, 2014 Federico Caminiti
 * Released under the BSD-2-Clause license
 * http://opensource.org/licenses/BSD-2-Clause
 */

var Terminal = function (user, prompt,container) {

		// Private variables.
		var _hostAndPrompt = '';
		var _user = "user";
		var _containerId = '';
		var _promptSymbol = '';
		var _eraseLimit;
		var _self;
		var _filesInDirectory = [{name:"hello.txt",mimeType:"text/plain",content:"Hola, mundo!.",permissions:"rw-r--r--",type:1,owner:_user,size:1,date:"18 Oct 16:45"}];
		var _consoleCommands = [];

		// Gets the commands that was typed into the console.
		function getCommandInput()
		{
			var lastLine = $(".console").val().split('\n')[$(".console").val().split('\n').length-1];
			command = lastLine.split(_promptSymbol)[1];
			return command;
		}

		// Inserts a new line in the console.
		function _insertNewLine()
		{
			 $(".console").val($(".console").val() + '\n' + _hostAndPrompt);
			  // Set the limit for erasing the conosole to the beginning of the newline.
			 _eraseLimit = $(".console").val().length;
		}

		// Clear the console.
		function _clearConsole()
		{
			$(".console").val("" + _hostAndPrompt);
			_eraseLimit = _hostAndPrompt.length;
		}

		// Writes the given text on the console.
		function _write(text)
		{
		  $(".console").val($(".console").val() + text);
		}

		// Executes a given command.
		function executeCommand(command,arguments)
		{
			var commandPos = $.inArray(command, $.map(_consoleCommands,function(item,index){ return item.name;}));
			if( commandPos != -1)
			{
				_consoleCommands[commandPos].run(arguments,_self);
			}
			else
			{
				 $(".console").val($(".console").val() + "\n");
				_write("bash: " + command + ": command not found");
			}
		}

		// Handles the click event.
		function handleClick(event)
		{
			if($(".console")[0].selectionStart  <= _eraseLimit || $(".console")[0].selectionEnd <= _eraseLimit)
			{
				$(".console")[0].selectionStart = _eraseLimit;
				$(".console")[0].selectionEnd = _eraseLimit;
			}
		}

		/*
		Handles the keypress events to prevent the user to erase the command prompt.
		Relevant keys/events:

		8  - Backspace.
		13 - Enter.
		36 - Init key.
		37 - Arrow back.
		38 - Arrow up.
		39 - Arrow forward (this case is not being handled).
		40 - Arrow down.
		46 - Supress key.

		*/
		function handleKeydown(event)
		{

			console.log(event.which);

			switch(event.which)
			{
				case 13:
					 handleEnterKey(event);
					break;
				case 36:
					handleInitKey();
				case 46:
					preventPromptErasing(true);
				case 8:
				case 37:
					preventPromptErasing(false);
					break;
				case 38:
				case 40:
					event.preventDefault();
					break;
				default:
					// As of now, nothing is done in this case.
					break;
			}
		}

		// Handles the init key.
		function handleInitKey()
		{
		  event.preventDefault();
		  $(".console")[0].selectionStart = _eraseLimit;
		  $(".console")[0].selectionEnd = _eraseLimit;
		}

		// Handles the enter key.
		function handleEnterKey(event)
		{
		   event.preventDefault(); // Do not insert a newline. Instead, let us handle the event.
		   var commandQuery = getCommandInput().trim();
		   var splitCommand;
		   if(commandQuery != "")
		   {
			  splitCommand = commandQuery.split(" ");
			  executeCommand(splitCommand[0],splitCommand);
		   } else {
			  splitCommand = [commandQuery];
		   }

		  if(splitCommand[0].indexOf("clear") == -1)
		  {
			 _insertNewLine();
		  }

		  return false;
		}

		// Prevents the user from deleting the command prompt.
		function preventPromptErasing(deleteKeyPressed)
		{

			if($(".console")[0].selectionStart  < _eraseLimit || $(".console")[0].selectionEnd < _eraseLimit || (!deleteKeyPressed && $(".console")[0].selectionStart  == _eraseLimit || $(".console")[0].selectionEnd == _eraseLimit))
			{
				event.preventDefault();
				$(".console")[0].selectionStart = _eraseLimit;
				$(".console")[0].selectionEnd = _eraseLimit;
			}
		}

	// Initialize the console and all of its relevant variables.
	function doInitialize()
	{
		// Initialize variables
		_promptSymbol = prompt;
		_hostAndPrompt = user + prompt;
		_containerId = container;
		_self = this;
		var con = $("<textarea class=\"console\" spellcheck=\"false\">");
		con.val(_hostAndPrompt);
		_eraseLimit = _hostAndPrompt.length;
		con.keydown(function( event ) { handleKeydown(event);});

		// Initialize the conosle and place it inside its container.
		var term = $("<textarea class=\"console\" spellcheck=\"false\">");
		term.val(_hostAndPrompt);
		term.keydown(function( event ) { handleKeydown(event);});
		$("#" + _containerId).append(term);
		$("#" + _containerId).click(function (event) {handleClick(event);});
	}

	/*
		Adds a command:

		A command should have, at least the following sections:
		- name (the name of the command).
		- man  (a description of what it does).
		- run  (the code that executes when the console runs the command).
	*/
	function addCommand(command)
	{
		if(command.name !== undefined && command.man !== undefined && command.run !== undefined)
		{
			_consoleCommands.push(command);
		}
	}

	// Removes the console from its container.
	function doDestroy()
	{
		$("#" + _containerId).remove();
	}

	return {
		initialize: doInitialize,
		clear: _clearConsole,
		write: _write,
		files: _filesInDirectory,
		commands: _consoleCommands,
		addCommand:addCommand,
		destroy: doDestroy
	};
};
<|endoftext|>


<commit_before>/*function jquerytest(){
  var ww = $(window).width();
  if(ww<0){
    alert("This window is impossibly small");
  }else{
    alert("This is a jquery test.  Would you like your " + ww + " pixel window washed?");
  }
  return ww;
};

*/
var logo = $('.site-avatar');
function tw(){
	  TweenMax.to(logo, 2.3, {
		display:'block',
		position:'relative',
		'z-index':4,
		left:'100%',
		ease: Power4.ease
		})

}
$('.site-info').click( function() {

  tw();
});
<commit_msg>Update jquerytest.js<commit_after>/*function jquerytest(){
  var ww = $(window).width();
  if(ww<0){
    alert("This window is impossibly small");
  }else{
    alert("This is a jquery test.  Would you like your " + ww + " pixel window washed?");
  }
  return ww;
};

*/
var logo = $('.site-avatar');
function tw(){
	  TweenMax.to(logo, 2.3, {
		display:'block',
		position:'relative',
		'z-index':4,
		left:'100%',
		 ease: Power0.easeNone
		})

}
$('.site-info').click( function() {

  tw();
});
<|endoftext|>


<commit_before>/*
  The main mappt application.

  the main application contains the ability to search, and will
  provide facilities to spawn several viewers for the user to
  manipulate. This application will also contain the panels for
  performing search queries.

  Dependencies:
  - mappt-viewer.js
  - mappt-panel.js
  - underscore.js
  - jquery
  - jquery.ui
  - jquery.localstorage
  - jquery.mousewheel
  - jquery.mobile

*/

var Mappt_Main_Image_Path = "./floorPlans_svg/";
var Mappt_Main_Data_Path = "./floorPlans_data/";

Mappt = function(context_id, context_width, context_height) {
    this.context_id = context_id;

    //the width wnd height of the context
    this.context_width = context_width;
    this.context_height = context_height;

    //contains the list of maps and their respective data for each map
    // to consider traversal. From this, we can construct the routes
    // for each map, and perform search queries.
    this.mapData = null;
    return this;
}

Mappt.prototype.init = function() {
    var mappt = this;
    return this;
}

//Used to set the data set for our maps within the mappt application
Mappt.prototype.setData = function(data) {
    //produce an object that stores our map data
    this.mapData = [];
    this.mapData = _.map(data, function(elem) {
	var mapObject = {};
	mapObject.name = elem.name;
	mapObject.mapName = elem.mapName;
	mapObject.dataName = elem.dataName;
	mapObject.routeData = this.getJSON(Mappt_Main_Data_Path + mapObject.dataName);
	return mapObject;
    }.bind(this));

    return this;
}

//get the full route between two areas in two different maps. This
//depends on the entrance info list having populated values to
//traverse between the two maps.

//The first version will allow traversal between two related maps
//stored within the entrance info list.
Mappt.prototype.getFullRoute = function(firstID, firstMapName,
					secondID, secondMapName) {
    //get the map corresponding to our first point
    var firstMap = _.find(this.mapData, function(elem) {
	return elem.mapName == firstMapName;
    });

    //get the map corresponding to the second point
    var secondMap = _.find(this.mapData, function(elem) {
	return elem.mapName == secondMapName;
    });

    //grab our points
    var firstPoint = _.find(firstMap.routeData.PointInfoList, function(elem) {
	return elem.id == firstID;
    });
    var secondPoint = _.find(secondMap.routeData.PointInfoList, function(elem) {
	return elem.id == secondID;
    });

    //try and see if there is a relationship between the two maps through the entrance nodes
    //we only traverse from the first node to the second node
    var firstEntranceList = firstMap.routeData.EntranceInfoList;
    var entranceRelations = _.filter(firstEntranceList, function(elem) {
	return elem.secondURL == secondMapName;
    });

    //from our first to our first entrances, form least costs and grab the one with the least cost
    var partialRouteList = _.map(entranceRelations, function(elem) {
	var partial = getRoute_djikstra(firstID, elem.first, firstMap.routeData);
	//fill our partial route with more useful information
	//the ID to the entrance of the building we want to enter
	partial.first = elem.first;
	//the ID to the node on the other side of the entrance within the other map
	partial.second = elem.second;
	return partial;
    }.bind(this));

    //get our minimum least cost
    var firstPartialRoute = _.min(partialRouteList, function(elem) {
	return (elem.totalCost);
    });

    //now that we have a partial route, we can take it's second value
    //and form the rest of the way to our destination
    var secondPartialRoute = getRoute_djikstra(firstPartialRoute.second, secondID, secondMap.routeData);

    //form a better representation for our data
    var fullRoute = [];
    //our first path
    fullRoute.push({
	name: firstMap.name,
	mapName: firstMap.mapName,
	path: firstPartialRoute.data,
    });
    //our second path
    fullRoute.push({
	name: secondMap.name,
	mapName: secondMap.mapName,
	path: secondPartialRoute.data,
    });
    return fullRoute;
}

Mappt.prototype.getJSON = function(dataURL) {
    //set our data up within the viewer
    var theData;

    //make sure it's an async call
    $.ajaxSetup({
	async: false
    });

    if(UrlExists(dataURL)) {
    //we didn't find it in local storage, so we're going to check the server
	jQuery.getJSON(dataURL, function(data) {
	    theData = data;
	    log("loading map data from remote...", dataURL);
	}.bind(this));
    }
    else {
	log(dataURL, " does not exist");
    }
    return theData;
}

//create the search list and produce a hashtable that allows you to
//easily traverse. The search is produced from the descriptors
//describing the nodes.
MapptViewer.prototype.createSearchList = function() {
    var searchList = {};
    //grab the map data for each map
    _.map(this.mapData, function(elemMap) {
	//traverse through the map's route data points
	_.map(elemMap.dataRoute.PointInfoList, function(elemPoint) {
	    //grab all of the descriptors and figure out what makes this particular point unique
	});//END _.map(elemMap.dataRoute.PointInfoList, ...
    });//END _.map(this.mapData, ...

}
<commit_msg>added the creation of viewers<commit_after>/*
  The main mappt application.

  the main application contains the ability to search, and will
  provide facilities to spawn several viewers for the user to
  manipulate. This application will also contain the panels for
  performing search queries.

  Dependencies:
  - mappt-viewer.js
  - mappt-panel.js
  - underscore.js
  - jquery
  - jquery.ui
  - jquery.localstorage
  - jquery.mousewheel
  - jquery.mobile

*/

var Mappt_Main_Image_Path = "./floorPlans_svg/";
var Mappt_Main_Data_Path = "./floorPlans_data/";

Mappt = function(context_id, context_width, context_height) {
    this.context_id = context_id;

    //the width wnd height of the context
    this.context_width = context_width;
    this.context_height = context_height;

    //contains the list of maps and their respective data for each map
    // to consider traversal. From this, we can construct the routes
    // for each map, and perform search queries.
    this.mapData = null;
    return this;
}

Mappt.prototype.init = function() {
    var mappt = this;

    this.contextObj = $("#" + this.context_id);
    (this.contextObj.length) || log("Given ID doesn't exist");

    return this;
}

//Used to set the data set for our maps within the mappt application
Mappt.prototype.setData = function(data) {
    //produce an object that stores our map data
    this.mapData = [];
    this.mapData = _.map(data, function(elem) {
	var mapObject = {};
	mapObject.name = elem.name;
	mapObject.mapName = elem.mapName;
	mapObject.dataName = elem.dataName;
	mapObject.routeData = this.getJSON(Mappt_Main_Data_Path + mapObject.dataName);
	return mapObject;
    }.bind(this));

    return this;
}

//get the full route between two areas in two different maps. This
//depends on the entrance info list having populated values to
//traverse between the two maps.

//The first version will allow traversal between two related maps
//stored within the entrance info list.
Mappt.prototype.getFullRoute = function(firstID, firstMapName,
					secondID, secondMapName) {
    //get the map corresponding to our first point
    var firstMap = _.find(this.mapData, function(elem) {
	return elem.mapName == firstMapName;
    });

    //get the map corresponding to the second point
    var secondMap = _.find(this.mapData, function(elem) {
	return elem.mapName == secondMapName;
    });

    //grab our points
    var firstPoint = _.find(firstMap.routeData.PointInfoList, function(elem) {
	return elem.id == firstID;
    });
    var secondPoint = _.find(secondMap.routeData.PointInfoList, function(elem) {
	return elem.id == secondID;
    });

    //try and see if there is a relationship between the two maps through the entrance nodes
    //we only traverse from the first node to the second node
    var firstEntranceList = firstMap.routeData.EntranceInfoList;
    var entranceRelations = _.filter(firstEntranceList, function(elem) {
	return elem.secondURL == secondMapName;
    });

    //from our first to our first entrances, form least costs and grab the one with the least cost
    var partialRouteList = _.map(entranceRelations, function(elem) {
	var partial = getRoute_djikstra(firstID, elem.first, firstMap.routeData);
	//fill our partial route with more useful information
	//the ID to the entrance of the building we want to enter
	partial.first = elem.first;
	//the ID to the node on the other side of the entrance within the other map
	partial.second = elem.second;
	return partial;
    }.bind(this));

    //get our minimum least cost
    var firstPartialRoute = _.min(partialRouteList, function(elem) {
	return (elem.totalCost);
    });

    //now that we have a partial route, we can take it's second value
    //and form the rest of the way to our destination
    var secondPartialRoute = getRoute_djikstra(firstPartialRoute.second, secondID, secondMap.routeData);

    //form a better representation for our data
    var fullRoute = [];
    //our first path
    fullRoute.push({
	name: firstMap.name,
	mapName: firstMap.mapName,
	path: firstPartialRoute.data,
    });
    //our second path
    fullRoute.push({
	name: secondMap.name,
	mapName: secondMap.mapName,
	path: secondPartialRoute.data,
    });
    return fullRoute;
}

Mappt.prototype.getJSON = function(dataURL) {
    //set our data up within the viewer
    var theData;

    //make sure it's an async call
    $.ajaxSetup({
	async: false
    });

    if(UrlExists(dataURL)) {
    //we didn't find it in local storage, so we're going to check the server
	jQuery.getJSON(dataURL, function(data) {
	    theData = data;
	    log("loading map data from remote...", dataURL);
	}.bind(this));
    }
    else {
	log(dataURL, " does not exist");
    }
    return theData;
}

Mappt.prototype.createViewer = function(viewer_context_id, viewer_width, viewer_height) {
    var newViewerObj = document.createElement("div");
    newViewerObj.setAttribute("id", viewer_context_id);
    $(this.contextObj).append(newViewerObj);
    console.log(viewer_context_id);
    //instantiate our viewer
    var mapptViewer = new MapptViewer(viewer_context_id, viewer_width, viewer_height);
    return mapptViewer;
}

//create the search list and produce a hashtable that allows you to
//easily traverse. The search is produced from the descriptors
//describing the nodes.
Mappt.prototype.createSearchList = function() {
    var searchList = {};
    //grab the map data for each map
    _.map(this.mapData, function(elemMap) {
	//traverse through the map's route data points
	_.map(elemMap.dataRoute.PointInfoList, function(elemPoint) {
	    //grab all of the descriptors and figure out what makes this particular point unique
	});//END _.map(elemMap.dataRoute.PointInfoList, ...
    });//END _.map(this.mapData, ...

}
<|endoftext|>