<commit_before>angular.module('app.services', [])

    .service('AppService', function ($http, $rootScope, $window, Utility) {

        var GRAPH_API_EMAIL = "https://graph.facebook.com/v2.5/me";

        var apigClient;

        function getApigClient() {
            if (apigClient == null) {
                //$window.location.reload("#/login");
            }

            return apigClient;
        }

        getApigClient();

        var syncClient;

        this.facebookGetEmail = function (token) {
            $rootScope.$broadcast('loading:show');

            var response = $http({
                method: 'GET',
                url: GRAPH_API_EMAIL,
                params: {
                    access_token: token,
                    fields: 'email',
                    format: 'json'
                }
            });

            $rootScope.$broadcast('loading:hide');

            return response;
        };

        this.awsCognitoCachedLogin = function (successCallback, failureCallback) {
            apigClient = apigClientFactory.newClient({
                accessKey: Utility.getAccessKey(),
                secretKey: Utility.getSecretKey(),
                sessionToken: Utility.getSessionToken()
            });

            getApigClient().yawnGet({
                    'events': JSON.stringify([
                        {
                            'operation': "list",
                            'payload': {}
                        }
                    ])
                }, '', '')
                .then(successCallback)
                .catch(failureCallback);
        };

        this.awsCognitoLogin = function (token, email, successCallback, failureCallback) {
            $rootScope.$broadcast('loading:show');

            try {
                AWS.config.region = 'us-east-1';
                AWS.config.credentials = new AWS.CognitoIdentityCredentials({
                    IdentityPoolId: 'us-east-1:cb9e6ded-d4d8-4f07-85cc-47ea011c8c53',
                    RoleArn: 'arn:aws:iam::990005713460:role/Cognito_NewsMuteAuth_Role',
                    Logins: {
                        'graph.facebook.com': token
                    },
                    RoleSessionName: 'web'
                });

                AWS.config.credentials.get(function () {
                    syncClient = new AWS.CognitoSyncManager();

                    console.log(syncClient.getIdentityId());

                    var cognitoidentity = new AWS.CognitoIdentity(AWS.config.credentials);

                    var accessKey;
                    var secretKey;
                    var sessionToken;

                    cognitoidentity.getCredentialsForIdentity(
                        {
                            IdentityId: syncClient.getIdentityId(),
                            Logins: {
                                'graph.facebook.com': token
                            }
                        }, function (err, data) {
                            if (!err) {
                                console.log(data);
                                accessKey = data.Credentials.AccessKeyId;
                                secretKey = data.Credentials.SecretKey;
                                sessionToken = data.Credentials.SessionToken;

                                apigClient = apigClientFactory.newClient({
                                    accessKey: accessKey,
                                    secretKey: secretKey,
                                    sessionToken: sessionToken
                                });

                                Utility.setAccessKey(accessKey);
                                Utility.setSecretKey(secretKey);
                                Utility.setSessionToken(sessionToken);

                                $rootScope.$broadcast('loading:hide');

                                successCallback(data);
                            } else {
                                console.log(err, err.stack);

                                $rootScope.$broadcast('loading:hide');

                                failureCallback(err);
                            }
                        });

                    syncClient.openOrCreateDataset('humanId', function (err, dataset) {
                        dataset.put('v1', email, function (err, record) {
                            dataset.synchronize({
                                onSuccess: function (data, newRecords) {
                                    console.log(data);
                                    console.log(newRecords);
                                    console.log("Cognito Sync humanId Complete:onSuccess");
                                },
                                onFailure: function (err) {
                                    console.log(err);
                                    console.log("Cognito Sync humanId Complete:onFailure");
                                },
                                onConflict: function (dataset, conflicts, callback) {
                                    //http://docs.aws.amazon.com/cognito/latest/developerguide/handling-callbacks.html
                                    console.log(dataset);
                                    console.log(conflicts);
                                    var resolved = [];
                                    for (var i = 0; i < conflicts.length; i++) {
                                        resolved.push(conflicts[i].resolveWithValue(conflicts[i].getLocalRecord().getValue()));
                                    }
                                    dataset.resolve(resolved, function () {
                                        console.log("Cognito Sync humanId Complete:onConflict");
                                        return callback(true);
                                    });
                                },
                                onDatasetDeleted: function (dataset, datasetName, callback) {
                                    console.log(dataset);
                                    console.log(datasetName);
                                    console.log("Cognito Sync humanId Complete:onDatasetDeleted");
                                },
                                onDatasetMerged: function (dataset, datasetNames, callback) {
                                    console.log(dataset);
                                    console.log(datasetNames);
                                    console.log("Cognito Sync humanId Complete:onDatasetMerged");
                                }
                            });
                        });
                    });

                    syncClient.openOrCreateDataset('syncTime', function (err, dataset) {
                        dataset.remove('v1', function (err, record) {
                            dataset.put('v1', (new Date).getTime(), function (err, record) {
                                dataset.synchronize({
                                    onSuccess: function (data, newRecords) {
                                        console.log(data);
                                        console.log(newRecords);
                                        console.log("Cognito Sync syncTime Complete");
                                    }
                                });
                            });
                        });
                    });
                });
            } catch (e) {
                alert(e.message);
            }
        };

        this.subscribeFeed = function (username, url) {
            return getApigClient().stalkPost({}, {
                'events': JSON.stringify([
                    {
                        'operation': "create",
                        'payload': [url]
                    }
                ])
            }, {});
        };

        this.unsubscribeFeed = function (username, url, successCallback, failureCallback) {
            return getApigClient().stalkPost({}, {
                'events': JSON.stringify([
                    {
                        'operation': "delete",
                        'payload': [url]
                    }
                ])
            }, {})
                .then(successCallback)
                .catch(failureCallback);
        };

        this.newsFeed = function () {
            var response = getApigClient().yawnGet({
                'events': JSON.stringify([
                    {
                        'operation': "list",
                        'payload': {}
                    }
                ])
            }, '', '');

            return new ParseYawnGet().rootObject(response);
        };

        this.muteNews = function (username, url, successCallback, failureCallback) {
            getApigClient().yawnPost({}, {
                    'events': JSON.stringify([
                        {
                            'operation': "delete",
                            'payload': [url]
                        }
                    ])
                }, {})
                .then(successCallback)
                .catch(failureCallback);
        };

        this.shareNews = function (username, url) {
            getApigClient().screamPost({}, {
                'events': JSON.stringify([
                    {
                        'operation': "create",
                        'payload': [url]
                    }
                ])
            }, {});
        };

        this.getUserLocation = function () {

            return $http({
                method: 'GET',
                url: "http://ipinfo.io"
            });
        };

        this.superfriend = function (friendsEmailArray, successCallback, failureCallback) {
            getApigClient().superfriendPost({}, {
                    'events': JSON.stringify([
                        {
                            'operation': "create",
                            'payload': friendsEmailArray
                        }
                    ])
                }, {})
                .then(successCallback)
                .catch(failureCallback);
        };

        this.syncTime = function () {
            if (syncClient != undefined) {
                syncClient.openOrCreateDataset('syncTime', function (err, dataset) {
                    dataset.remove('v1', function (err, record) {
                        dataset.put('v1', (new Date).getTime(), function (err, record) {
                            dataset.synchronize({
                                onSuccess: function (data, newRecords) {
                                    console.log(data);
                                    console.log(newRecords);
                                    console.log("Cognito Sync syncTime Complete");
                                }
                            });
                        });
                    });
                });
            } else {
                AWS.config.region = 'us-east-1';
                AWS.config.credentials = new AWS.CognitoIdentityCredentials({
                    IdentityPoolId: 'us-east-1:cb9e6ded-d4d8-4f07-85cc-47ea011c8c53',
                    RoleArn: 'arn:aws:iam::990005713460:role/Cognito_NewsMuteAuth_Role',
                    Logins: {
                        'graph.facebook.com': Utility.getToken()
                    },
                    RoleSessionName: 'web'
                });

                AWS.config.credentials.get(function () {
                    "use strict";
                    syncClient = new AWS.CognitoSyncManager();
                    syncClient.openOrCreateDataset('syncTime', function (err, dataset) {
                        dataset.remove('v1', function (err, record) {
                            dataset.put('v1', (new Date).getTime(), function (err, record) {
                                dataset.synchronize({
                                    onSuccess: function (data, newRecords) {
                                        console.log(data);
                                        console.log(newRecords);
                                        console.log("Cognito Sync syncTime Complete");
                                    }
                                });
                            });
                        });
                    });
                });
            }
        }
    });
<commit_msg>Path and session related fixes/improvements<commit_after>angular.module('app.services', [])

    .service('AppService', function ($http, $rootScope, $location, Utility) {

        var GRAPH_API_EMAIL = "https://graph.facebook.com/v2.5/me";

        var apigClient;

        function getApigClient() {
            if (apigClient == null && $location.path() != '#/login') {
                $location.path("#/login");
            }

            return apigClient;
        }

        var syncClient;

        this.facebookGetEmail = function (token) {
            $rootScope.$broadcast('loading:show');

            var response = $http({
                method: 'GET',
                url: GRAPH_API_EMAIL,
                params: {
                    access_token: token,
                    fields: 'email',
                    format: 'json'
                }
            });

            $rootScope.$broadcast('loading:hide');

            return response;
        };

        this.awsCognitoCachedLogin = function (successCallback, failureCallback) {
            apigClient = apigClientFactory.newClient({
                accessKey: Utility.getAccessKey(),
                secretKey: Utility.getSecretKey(),
                sessionToken: Utility.getSessionToken()
            });

            getApigClient().yawnGet({
                    'events': JSON.stringify([
                        {
                            'operation': "list",
                            'payload': {}
                        }
                    ])
                }, '', '')
                .then(successCallback)
                .catch(failureCallback);
        };

        this.awsCognitoLogin = function (token, email, successCallback, failureCallback) {
            $rootScope.$broadcast('loading:show');

            try {
                AWS.config.region = 'us-east-1';
                AWS.config.credentials = new AWS.CognitoIdentityCredentials({
                    IdentityPoolId: 'us-east-1:cb9e6ded-d4d8-4f07-85cc-47ea011c8c53',
                    RoleArn: 'arn:aws:iam::990005713460:role/Cognito_NewsMuteAuth_Role',
                    Logins: {
                        'graph.facebook.com': token
                    },
                    RoleSessionName: 'web'
                });

                AWS.config.credentials.get(function () {
                    syncClient = new AWS.CognitoSyncManager();

                    console.log(syncClient.getIdentityId());

                    var cognitoidentity = new AWS.CognitoIdentity(AWS.config.credentials);

                    var accessKey;
                    var secretKey;
                    var sessionToken;

                    cognitoidentity.getCredentialsForIdentity(
                        {
                            IdentityId: syncClient.getIdentityId(),
                            Logins: {
                                'graph.facebook.com': token
                            }
                        }, function (err, data) {
                            if (!err) {
                                console.log(data);
                                accessKey = data.Credentials.AccessKeyId;
                                secretKey = data.Credentials.SecretKey;
                                sessionToken = data.Credentials.SessionToken;

                                apigClient = apigClientFactory.newClient({
                                    accessKey: accessKey,
                                    secretKey: secretKey,
                                    sessionToken: sessionToken
                                });

                                Utility.setAccessKey(accessKey);
                                Utility.setSecretKey(secretKey);
                                Utility.setSessionToken(sessionToken);

                                $rootScope.$broadcast('loading:hide');

                                successCallback(data);
                            } else {
                                console.log(err, err.stack);

                                $rootScope.$broadcast('loading:hide');

                                failureCallback(err);
                            }
                        });

                    syncClient.openOrCreateDataset('humanId', function (err, dataset) {
                        dataset.put('v1', email, function (err, record) {
                            dataset.synchronize({
                                onSuccess: function (data, newRecords) {
                                    console.log(data);
                                    console.log(newRecords);
                                    console.log("Cognito Sync humanId Complete:onSuccess");
                                },
                                onFailure: function (err) {
                                    console.log(err);
                                    console.log("Cognito Sync humanId Complete:onFailure");
                                },
                                onConflict: function (dataset, conflicts, callback) {
                                    //http://docs.aws.amazon.com/cognito/latest/developerguide/handling-callbacks.html
                                    console.log(dataset);
                                    console.log(conflicts);
                                    var resolved = [];
                                    for (var i = 0; i < conflicts.length; i++) {
                                        resolved.push(conflicts[i].resolveWithValue(conflicts[i].getLocalRecord().getValue()));
                                    }
                                    dataset.resolve(resolved, function () {
                                        console.log("Cognito Sync humanId Complete:onConflict");
                                        return callback(true);
                                    });
                                },
                                onDatasetDeleted: function (dataset, datasetName, callback) {
                                    console.log(dataset);
                                    console.log(datasetName);
                                    console.log("Cognito Sync humanId Complete:onDatasetDeleted");
                                },
                                onDatasetMerged: function (dataset, datasetNames, callback) {
                                    console.log(dataset);
                                    console.log(datasetNames);
                                    console.log("Cognito Sync humanId Complete:onDatasetMerged");
                                }
                            });
                        });
                    });

                    syncClient.openOrCreateDataset('syncTime', function (err, dataset) {
                        dataset.remove('v1', function (err, record) {
                            dataset.put('v1', (new Date).getTime(), function (err, record) {
                                dataset.synchronize({
                                    onSuccess: function (data, newRecords) {
                                        console.log(data);
                                        console.log(newRecords);
                                        console.log("Cognito Sync syncTime Complete");
                                    }
                                });
                            });
                        });
                    });
                });
            } catch (e) {
                alert(e.message);
            }
        };

        this.subscribeFeed = function (username, url) {
            return getApigClient().stalkPost({}, {
                'events': JSON.stringify([
                    {
                        'operation': "create",
                        'payload': [url]
                    }
                ])
            }, {});
        };

        this.unsubscribeFeed = function (username, url, successCallback, failureCallback) {
            return getApigClient().stalkPost({}, {
                    'events': JSON.stringify([
                        {
                            'operation': "delete",
                            'payload': [url]
                        }
                    ])
                }, {})
                .then(successCallback)
                .catch(failureCallback);
        };

        this.newsFeed = function () {
            var response = getApigClient().yawnGet({
                'events': JSON.stringify([
                    {
                        'operation': "list",
                        'payload': {}
                    }
                ])
            }, '', '');

            return new ParseYawnGet().rootObject(response);
        };

        this.muteNews = function (username, url, successCallback, failureCallback) {
            getApigClient().yawnPost({}, {
                    'events': JSON.stringify([
                        {
                            'operation': "delete",
                            'payload': [url]
                        }
                    ])
                }, {})
                .then(successCallback)
                .catch(failureCallback);
        };

        this.shareNews = function (username, url) {
            getApigClient().screamPost({}, {
                'events': JSON.stringify([
                    {
                        'operation': "create",
                        'payload': [url]
                    }
                ])
            }, {});
        };

        this.getUserLocation = function () {

            return $http({
                method: 'GET',
                url: "http://ipinfo.io"
            });
        };

        this.superfriend = function (friendsEmailArray, successCallback, failureCallback) {
            getApigClient().superfriendPost({}, {
                    'events': JSON.stringify([
                        {
                            'operation': "create",
                            'payload': friendsEmailArray
                        }
                    ])
                }, {})
                .then(successCallback)
                .catch(failureCallback);
        };

        this.syncTime = function () {
            if (syncClient != undefined) {
                syncClient.openOrCreateDataset('syncTime', function (err, dataset) {
                    dataset.remove('v1', function (err, record) {
                        dataset.put('v1', (new Date).getTime(), function (err, record) {
                            dataset.synchronize({
                                onSuccess: function (data, newRecords) {
                                    console.log(data);
                                    console.log(newRecords);
                                    console.log("Cognito Sync syncTime Complete");
                                }
                            });
                        });
                    });
                });
            } else {
                AWS.config.region = 'us-east-1';
                AWS.config.credentials = new AWS.CognitoIdentityCredentials({
                    IdentityPoolId: 'us-east-1:cb9e6ded-d4d8-4f07-85cc-47ea011c8c53',
                    RoleArn: 'arn:aws:iam::990005713460:role/Cognito_NewsMuteAuth_Role',
                    Logins: {
                        'graph.facebook.com': Utility.getToken()
                    },
                    RoleSessionName: 'web'
                });

                AWS.config.credentials.get(function () {
                    "use strict";
                    syncClient = new AWS.CognitoSyncManager();
                    syncClient.openOrCreateDataset('syncTime', function (err, dataset) {
                        dataset.remove('v1', function (err, record) {
                            dataset.put('v1', (new Date).getTime(), function (err, record) {
                                dataset.synchronize({
                                    onSuccess: function (data, newRecords) {
                                        console.log(data);
                                        console.log(newRecords);
                                        console.log("Cognito Sync syncTime Complete");
                                    }
                                });
                            });
                        });
                    });
                });
            }
        }
    });
<|endoftext|>


<commit_before>'use strict';

const elem = {};

function loadOptions(){
    browser.storage.local.get(settingsDefault).then(function(result){
        Object.keys(settingsDefault).forEach(function(key){
            elem[key][elem[key].de_val] = result[key];
        });
        refreshIcon();
        saveOptions();
    });
}

function saveOptions(){
    let settings = {};
    Object.keys(settingsDefault).forEach(function(key){
        settings[key] = elem[key][elem[key].de_val];
    });
    browser.storage.local.set(settings);
    disableSave();
}

function resetOptions(){
    Object.keys(settingsDefault).forEach(function(key){
        elem[key][elem[key].de_val] = settingsDefault[key];
    });
    refreshIcon();
    enableSave();
}

function refreshIcon(){
    elem.iconDisplay.style.backgroundImage = elem.icon.value;
}

function fileInputListener(){
    let reader = new FileReader();
    reader.readAsDataURL(elem.fileInput.files[0]);
    reader.onload = function(){
        if (reader.result.length > 2097152) {
            console.log(reader.result.length); //TODO add proper error message
            return;
        }
        elem.icon.value = 'url("' + reader.result + '")';
        refreshIcon();
    };
}

function disableSave(){
    elem.save.disabled = true;
}
function enableSave(){
    elem.save.disabled = false;
}

function refreshFolders(){

}
function listenFolderKey(event){
    event.target.parentNode.querySelector('.keyCode').value = event.keyCode;
}
function addNewFolder(){
    let newFolder = elem.container.querySelector('tr[data-num="0"]').cloneNode(true); //TODO put hidden blank template elsewhere
    let folders = document.querySelectorAll('.folder');
    let newFolderNum = Number(folders[folders.length - 1].dataset.num) + 1;

    newFolder.dataset.num = newFolderNum;
    let deleteBtn = newFolder.querySelector('.deleteFolder');
    deleteBtn.dataset.num = newFolderNum;
    deleteBtn.addEventListener('click', deleteFolder);
    newFolder.querySelector('span').innerHTML = '';
    elem.container.insertBefore(newFolder, elem.addFolderContainer);
}
function deleteFolder(event){
    document.querySelector('tr[data-num="' + event.target.dataset.num + '"]').remove();
}

function initSelectors(){
    let settingsElems = Object.keys(settingsDefault),
        otherElems = ['container', 'addFolder', 'addFolderContainer', 'save', 'reset', 'iconDisplay', 'fileInput'];

    settingsElems.forEach(function(name){
        elem[name] = document.querySelector('#' + name);
        elem[name].de_val = elem[name].type === 'checkbox' ? 'checked' : 'value';
    });
    otherElems.forEach(function(name){
        elem[name] = document.querySelector('#' + name);
    });

    elem.foldersList = [];
}

function init(){
    initSelectors();

    elem.fileInput.addEventListener('change', fileInputListener);
    elem.save.addEventListener('click', saveOptions);
    elem.reset.addEventListener('click', resetOptions);
    elem.addFolder.addEventListener('click', addNewFolder);
    document.querySelectorAll('select, input').forEach(function(elem){
        elem.addEventListener('input', enableSave);
    });

    disableSave();
    loadOptions();
}

document.addEventListener('DOMContentLoaded', init);
<commit_msg>sketches for folders settings saving<commit_after>'use strict';

const elem = {};

/*
-------------------- Generic functions --------------------
*/
function loadOptions(){
    browser.storage.local.get(settingsDefault).then(function(result){
        Object.keys(settingsDefault).forEach(function(key){
            elem[key][elem[key].de_val] = result[key];
        });
        refreshIcon();
        saveOptions();
    });
}

function saveOptions(){
    let settings = {};
    Object.keys(settingsDefault).forEach(function(key){
        settings[key] = elem[key][elem[key].de_val];
    });
    browser.storage.local.set(settings);
    disableSave();
}

function resetOptions(){
    Object.keys(settingsDefault).forEach(function(key){
        elem[key][elem[key].de_val] = settingsDefault[key];
    });
    refreshIcon();
    enableSave();
}

function disableSave(){
    elem.save.disabled = true;
}

function enableSave(){
    elem.save.disabled = false;
}

/*
-------------------- Icon --------------------
*/
function refreshIcon(){
    elem.iconDisplay.style.backgroundImage = elem.icon.value;
}

function fileInputListener(){
    let reader = new FileReader();
    reader.readAsDataURL(elem.fileInput.files[0]);
    reader.onload = function(){
        if (reader.result.length > 2097152) {
            console.log(reader.result.length); //TODO add proper error message
            return;
        }
        elem.icon.value = 'url("' + reader.result + '")';
        refreshIcon();
    };
}

/*
-------------------- Custom Directories --------------------
*/
function refreshFolders(){
    elem.folders.forEach(function(folder){

    });
}

function listenFolderKey(event){
    event.target.parentNode.querySelector('.keyCode').value = event.keyCode;
}

function addNewFolder(folderSettings = null){
    let newFolder = elem.container.querySelector('tr[data-num="0"]').cloneNode(true); //TODO put hidden blank template elsewhere
    let folders = document.querySelectorAll('.folder');
    let newFolderNum = Number(folders[folders.length - 1].dataset.num) + 1;

    newFolder.dataset.num = newFolderNum;
    let deleteBtn = newFolder.querySelector('.deleteFolder');
    deleteBtn.dataset.num = newFolderNum;
    deleteBtn.addEventListener('click', deleteFolder);
    newFolder.querySelector('span').innerHTML = '';
    if (folderSettings) {
    	fillFolder(newFolder, folderSettings);
    }
    elem.container.insertBefore(newFolder, elem.addFolderContainer);
}

function fillFolder(folderElem, folderSettings){
    folderElem.querySelector('.key').value      = folderSettings.key;
    folderElem.querySelector('.keyCode').value  = folderSettings.keyCode;
    folderElem.querySelector('.modifier').value = folderSettings.modifier;
    folderElem.querySelector('.path').value     = folderSettings.path;
}

function deleteFolder(event){
    document.querySelector('tr[data-num="' + event.target.dataset.num + '"]').remove();
}
function buildFolderSettings(folderElem){
    return {
        key     : folderElem.querySelector('.key'),
        keyCode : folderElem.querySelector('.keyCode'),
        modifier: folderElem.querySelector('.modifier'),
        path    : folderElem.querySelector('.path')
    };
}

/*
-------------------- Initialization --------------------
*/
function initSelectors(){
    let settingsElems = Object.keys(settingsDefault),
        otherElems = ['container', 'addFolder', 'addFolderContainer', 'save', 'reset', 'iconDisplay', 'fileInput'];

    settingsElems.forEach(function(name){
        elem[name] = document.querySelector('#' + name);
        elem[name].de_val = elem[name].type === 'checkbox' ? 'checked' : 'value';
    });
    otherElems.forEach(function(name){
        elem[name] = document.querySelector('#' + name);
    });

    elem.foldersList = [];
}

function init(){
    initSelectors();

    elem.fileInput.addEventListener('change', fileInputListener);
    elem.save.addEventListener('click', saveOptions);
    elem.reset.addEventListener('click', resetOptions);
    elem.addFolder.addEventListener('click', addNewFolder);
    document.querySelectorAll('select, input').forEach(function(elem){
        elem.addEventListener('input', enableSave);
    });

    disableSave();
    loadOptions();
}

document.addEventListener('DOMContentLoaded', init);
<|endoftext|>


<commit_before>window.SETTINGS = {
	'embedlyKey': 'dev', // insert your Embedly API key here
	'options': {
		'platform': {
			'default': 'facebook',
			'choices': {
				'facebook': { w: '1200', h: '627' },
				'twitter': { w: '1024', h: '512' },
				'instagram': {w: 640, h: 640 }
			}
		},
		'font': {
			'default': 'helvetica',
			'choices': {
				'helvetica': 'Helvetica, Arial, sans-serif',
				'georgia': 'Georgia, Times New Roman, serif'
			}
		}
	},
	'imageHelper': function(src) {
		// do some regex to tweak img src (ex. pull down better img quality)
		return src.replace(/960w|585w/, '1920w');
	}
};<commit_msg>settings<commit_after>window.SETTINGS = {
	'embedlyKey': 'dev', // insert your Embedly API key here
	'options': {
		'platform': {
			'default': 'facebook',
			'choices': {
				'facebook': { w: 1200, h: 627 },
				'twitter': { w: 1024, h: 512 },
				'instagram': {w: 640, h: 640 }
			}
		},
		'font': {
			'default': 'helvetica',
			'choices': {
				'helvetica': 'Helvetica, Arial, sans-serif',
				'georgia': 'Georgia, Times New Roman, serif'
			}
		}
	},
	'imageHelper': function(src) {
		// do some regex to tweak img src (ex. pull down better img quality)
		return src.replace(/960w|585w/, '1920w');
	}
};<|endoftext|>


<commit_before>export default {
    rows: 8,
    cols: 8,
    baseScore: 100,
    numJewelTypes: 7,
};
<commit_msg>Allow accessing jewelSize from settings object<commit_after>import { $ } from 'util/dom';

export default {
    rows: 8,
    cols: 8,
    baseScore: 100,
    numJewelTypes: 7,
    // element changes size based on screen size
    jewelSize: $('jewel-proto').getBoundingClientRect().width
};
<|endoftext|>


<commit_before>/* global angular:true, document:true */
angular.module('bgDirectives', [])
    .directive('bgSplitter', function()
    {
        return {
            restrict: 'E',
            require: '?^bgPane',
            replace: true,
            transclude: true,
            scope: {
                orientation: '@',
                pos: '@',
                size: '@'
        },
        template: '

',
        controllerAs: 'bgSplitterCtrl',
        controller: ['$scope', function(scope)
        {
            var self = this;
            this.scope = scope;
            this.panes = [];

            this.addPane = function(pane)
            {
                if (self.panes.length > 1)
                {
                   throw 'splitters can only have two panes';
                }
                self.panes.push(pane);
                return self.panes.length;
            };

            this.getStyleRule = function(selectorPattern)
            {
                if(typeof selectorPattern == 'string')
                {
                    selectorPattern = new RegExp(selectorPattern);
                }
                var sheets = document.styleSheets;
                for (var i = 0, l = sheets.length; i < l; i++)
                {
                    var sheet = sheets[i];
                    if( !sheet.cssRules )
                    {
                        continue;
                    }
                    for (var j = 0, cssRulesLen = sheet.cssRules.length; j < cssRulesLen; j++)
                    {
                        var rule = sheet.cssRules[j];
                        if(!rule.selectorText)
                        {
                            continue;
                        }
                        var selectors = rule.selectorText.split(',');
                        for(var k = 0, selectorsLen = sheet.cssRules.length; k < selectorsLen; k++)
                        {
                            if(selectorPattern.test(selectors[j]))
                            {
                                return rule.style;
                            }
                        }
                    }
                }
                return null;
            };

            var orientation = this.scope.orientation;
            var isVertical = this.scope.isVertical = orientation == 'vertical';

            // get the size of the splitter from the pane2 border and its hitzone from split-handler
            var borderStyle = this.getStyleRule('\\.split-panes\\.'+ orientation +'\\s*>\\s*\\.split-pane2\\b') || {};
            var border = (isVertical? borderStyle['border-left']: borderStyle['border-top']) || '';
            var sizePx = border.split(' ')[0];
            var splitterSize = parseInt(sizePx.substring(0, sizePx.indexOf('px')));

            // adjust handler size
            if (scope.size)
            {
                splitterSize = Number(scope.size);
            }

            scope.splitterSize = splitterSize;
        }],
        link: {
            pre: function preLink(scope, element, attrs, bgPane)
            {
                function calcSizes(width, height)
                {
                    scope.width = width;
                    scope.height = height;

                    scope.paneSizes = [];
                    var range = scope.isVertical ? width : height;
                    var val = 0;

                    var pos = scope.pos || "50%";

                    if (pos.indexOf('%') != -1)
                    {
                        // handle percent
                        var posStr = pos.substring(0, pos.indexOf('%'));
                        var fraction = Number(posStr) / 100;

                        val = range * fraction | 0;
                        val = val < 0 ? range + val - scope.splitterSize : val;
                    }
                    else
                    {
                        // handle pixels
                        var pixels = parseInt(pos);
                        val = pixels < 0 ? range + pixels - scope.splitterSize: pixels;
                    }

                    if (scope.isVertical)
                    {
                        scope.paneSizes.push([val, height], [width - val, height]);
                        scope.startX = val;
                    }
                    else
                    {
                        scope.paneSizes.push([width, val], [width, height - val]);
                        scope.startY = val;
                    }
                }

                // calculate the width and height of each pane
                var width;
                var height;
                if (bgPane)
                {
                    width = bgPane.scope.paneSize[0];
                    height = bgPane.scope.paneSize[1];
                    calcSizes(width, height);
                }
                else
                {
                    var bounds = element[0].getBoundingClientRect();
                    width = bounds.right - bounds.left;
                    height = bounds.bottom - bounds.top;
                    calcSizes(width, height);
                }
            },
            post: function postLink (scope, element)
            {
                var self = scope.bgSplitterCtrl;

                var handler = angular.element('

');
                var pane1 = self.panes[0];
                var pane2 = self.panes[1];
                var pane1Min = pane1.minSize || 0;
                var pane2Min = pane2.minSize || 0;
                var drag = false;

                pane1.elem.after(handler);

                function resize (ev)
                {
                    if (!drag) return;

                    var bounds = element[0].getBoundingClientRect();
                    var pos = 0;

                    if (scope.isVertical)
                    {
                        var width = bounds.right - bounds.left;
                        pos = ev.clientX - bounds.left;

                        if (pos < pane1Min) pos = pane1Min;
                        if (width - pos < pane2Min) pos = width - pane2Min;

                        handler.css('left', pos + 'px');
                        pane1.elem.css('width', pos + 'px');
                        pane2.elem.css('left', pos + 'px');

                    } else {
                        var height = bounds.bottom - bounds.top;
                        pos = ev.clientY - bounds.top;

                        if (pos < pane1Min) pos = pane1Min;
                        if (height - pos < pane2Min) pos = height - pane2Min;

                        handler.css('top', pos + 'px');
                        pane1.elem.css('height', pos + 'px');
                        pane2.elem.css('top', pos + 'px');
                    }
                }

                element.bind('mousemove', resize);

                handler.bind('mousedown', function (ev) {
                    ev.preventDefault();
                    drag = true;
                });

                // Use .addEventListener() instead of JQuery-lite's .bind() so we get mouseup before anything eats it.
                document.addEventListener('mouseup', function () {
                    drag = false;
                }, true);

                // adjust the splitter size
                if (scope.size)
                {
                    if (scope.isVertical)
                    {
                        pane2.elem[0].style['border-left-width'] = scope.splitterSize + 'px';
                    }
                    else
                    {
                        pane2.elem[0].style['border-top-width'] = scope.splitterSize + 'px';
                    }
                }

                var splitterStyle = self.getStyleRule('.split-panes.'+ scope.orientation +' > .split-handler') || {};
                var ssSizePx = (scope.isVertical ? splitterStyle.width : splitterStyle.height) || '';
                var splitterHitSize = parseInt(ssSizePx.substring(0, ssSizePx.indexOf('px')));

                if (splitterHitSize < scope.splitterSize)
                {
                    splitterHitSize = scope.splitterSize;
                    if (scope.isVertical)
                    {
                        handler[0].style.width = splitterHitSize + 'px';
                    }
                    else
                    {
                        handler[0].style.height = splitterHitSize + 'px';
                    }
                }

                // initialize splitter and pane positions
                if (scope.isVertical)
                {
                    var startX = scope.startX;
                    if (startX < pane1Min) return;
                    if (scope.width - startX < pane2Min) return;

                    handler.css('left', startX + 'px');
                    pane1.elem.css('width', startX + 'px');
                    pane2.elem.css('left', startX + 'px');

                } else {
                    var startY = scope.startY;
                    if (startY < pane1Min) return;
                    if (scope.height - startY < pane2Min) return;

                    handler.css('top', startY + 'px');
                    pane1.elem.css('height', startY + 'px');
                    pane2.elem.css('top', startY + 'px');
                }
            }// end postLink
        }
    };
  })
  .directive('bgPane', function () {
      return {
            restrict: 'E',
            require: '^bgSplitter',
            replace: true,
            transclude: true,
            scope: {
                minSize: '='
            },
            template: '

',
            controllerAs: 'bgPaneCtrl',
            controller: ['$scope', function(scope)
            {
                this.scope = scope;
            }],
            link: {
                pre: function preLink(scope, element, attrs, bgSplitter)
                {
                    var self = scope.bgPaneCtrl;

                    // get dimensions from bgSplitter
                    self.elem = element;
                    self.id = attrs.id;
                    scope.index = bgSplitter.addPane(self);
                    scope.paneSize = bgSplitter.scope.paneSizes[scope.index - 1];
                }
            }
        };
    });
<commit_msg>Moved stylesheet parsing into a separate service, and other fixes.<commit_after>/* global angular:true */
angular.module('bgDirectives', [])
    .service('bgSplitterStyles', ['$document', '$q', function($document, $q)
    {
        var styleRules = {
            horizontal: {
                splitter: {},
                border: {}
            },
            vertical: {
                splitter: {},
                border: {}
            }
        };

        var rulesLoadedPromise = $q(function(resolve)
        {
            // Wait until stylesheets have loaded before attempting to parse them.
            $document.on('load', function()
            {
                var styleRulePatterns = {
                    horizontal: {
                        splitter: /\.split-panes\.horizontal\s*>\s*\.split-handler\b/,
                        border: /\.split-panes\.horizontal\s*>\s*\.split-pane2\b/
                    },
                    vertical: {
                        splitter: /\.split-panes\.vertical\s*>\s*\.split-handler\b/,
                        border: /\.split-panes\.vertical\s*>\s*\.split-pane2\b/
                    }
                };

                // Iterate over the rules in each stylesheet, finding ones that match splitters and borders.
                var sheets = $document[0].styleSheets;
                for(var i = 0, l = sheets.length; i < l; i++)
                {
                    var sheet = sheets[i];
                    if(!sheet.cssRules)
                    {
                        continue;
                    }
                    for(var j = 0, cssRulesLen = sheet.cssRules.length; j < cssRulesLen; j++)
                    {
                        var rule = sheet.cssRules[j];
                        if(!rule.selectorText)
                        {
                            continue;
                        }
                        var selectors = rule.selectorText.split(',');
                        for(var k = 0, selectorsLen = sheet.cssRules.length; k < selectorsLen; k++)
                        {
                            var selector = selectors[j];
                            if(styleRulePatterns.horizontal.splitter.test(selector))
                                { styleRulePatterns.horizontal.splitter = rule.style; }
                            else if(styleRulePatterns.horizontal.border.test(selector))
                                { styleRulePatterns.horizontal.border = rule.style; }
                            else if(styleRulePatterns.vertical.splitter.test(selector))
                                { styleRulePatterns.vertical.splitter = rule.style; }
                            else if(styleRulePatterns.vertical.border.test(selector))
                                { styleRulePatterns.vertical.border = rule.style; }
                        }
                    }
                }

                resolve(styleRules);
            });
        });

        return {
            // The loaded style rules, or placeholder objects if styles haven't finished loading yet
            rules: styleRules,

            // A promise for when style rules have finished loading
            loaded: rulesLoadedPromise
        };
    }])

    .directive('bgSplitter', ['$document', 'bgSplitterStyles', function($document, styles)
    {
        return {
            restrict: 'E',
            require: '?^bgPane',
            replace: true,
            transclude: true,
            scope: {
                orientation: '@',
                pos: '@',
                size: '@'
        },
        template: '

',
        controllerAs: 'bgSplitterCtrl',
        controller: ['$scope', function(scope)
        {
            var self = this;
            this.scope = scope;
            this.panes = [];

            this.addPane = function(pane)
            {
                if (self.panes.length > 1)
                {
                   throw 'splitters can only have two panes';
                }
                self.panes.push(pane);
                return self.panes.length;
            };

            var orientation = this.scope.orientation;
            var isVertical = this.scope.isVertical = orientation == 'vertical';

            function onStyleChange(rules)
            {
                // get the size of the splitter from the pane2 border and its hitzone from split-handler
                var borderStyle = rules[orientation].border;
                var border = (isVertical? borderStyle['border-left']: borderStyle['border-top']) || '';
                var sizePx = border.split(' ')[0];
                var splitterSize = parseInt(sizePx.substring(0, sizePx.indexOf('px')));

                // adjust handler size
                if (scope.size)
                {
                    splitterSize = Number(scope.size);
                }

                scope.splitterSize = splitterSize;
            }

            styles.loaded.then(onStyleChange);
            onStyleChange(styles.rules);
        }],
        link: {
            pre: function preLink(scope, element, attrs, bgPane)
            {
                function calcSizes(width, height)
                {
                    scope.width = width;
                    scope.height = height;

                    scope.paneSizes = [];
                    var range = scope.isVertical ? width : height;
                    var val = 0;

                    var pos = scope.pos || "50%";

                    if (pos.indexOf('%') != -1)
                    {
                        // handle percent
                        var posStr = pos.substring(0, pos.indexOf('%'));
                        var fraction = Number(posStr) / 100;

                        val = range * fraction | 0;
                        val = val < 0 ? range + val - scope.splitterSize : val;
                    }
                    else
                    {
                        // handle pixels
                        var pixels = parseInt(pos);
                        val = pixels < 0 ? range + pixels - scope.splitterSize: pixels;
                    }

                    if (scope.isVertical)
                    {
                        scope.paneSizes.push([val, height], [width - val, height]);
                        scope.startX = val;
                    }
                    else
                    {
                        scope.paneSizes.push([width, val], [width, height - val]);
                        scope.startY = val;
                    }
                }

                // calculate the width and height of each pane
                var width;
                var height;
                if (bgPane)
                {
                    width = bgPane.scope.paneSize[0];
                    height = bgPane.scope.paneSize[1];
                    calcSizes(width, height);
                }
                else
                {
                    var bounds = element[0].getBoundingClientRect();
                    width = bounds.right - bounds.left;
                    height = bounds.bottom - bounds.top;
                    calcSizes(width, height);
                }
            },
            post: function postLink (scope, element)
            {
                var self = scope.bgSplitterCtrl;

                var handler = angular.element('

');
                var pane1 = self.panes[0];
                var pane2 = self.panes[1];
                var pane1Min = pane1.minSize || 0;
                var pane2Min = pane2.minSize || 0;
                var drag = false;

                pane1.elem.after(handler);

                function resize (ev)
                {
                    if (!drag) return;

                    var bounds = element[0].getBoundingClientRect();
                    var pos = 0;

                    if (scope.isVertical)
                    {
                        var width = bounds.right - bounds.left;
                        pos = ev.clientX - bounds.left;

                        if (pos < pane1Min) pos = pane1Min;
                        if (width - pos < pane2Min) pos = width - pane2Min;

                        handler.css('left', pos + 'px');
                        pane1.elem.css('width', pos + 'px');
                        pane2.elem.css('left', pos + 'px');

                    } else {
                        var height = bounds.bottom - bounds.top;
                        pos = ev.clientY - bounds.top;

                        if (pos < pane1Min) pos = pane1Min;
                        if (height - pos < pane2Min) pos = height - pane2Min;

                        handler.css('top', pos + 'px');
                        pane1.elem.css('height', pos + 'px');
                        pane2.elem.css('top', pos + 'px');
                    }
                }

                element.bind('mousemove', resize);

                handler.bind('mousedown', function (ev) {
                    ev.preventDefault();
                    drag = true;
                });

                // Use .addEventListener() instead of JQuery-lite's .bind() so we get mouseup before anything eats it.
                $document[0].addEventListener('mouseup', function () {
                    drag = false;
                }, true);

                // adjust the splitter size
                if (scope.size)
                {
                    if (scope.isVertical)
                    {
                        pane2.elem[0].style['border-left-width'] = scope.splitterSize + 'px';
                    }
                    else
                    {
                        pane2.elem[0].style['border-top-width'] = scope.splitterSize + 'px';
                    }
                }

                function onStyleChange(rules)
                {
                    var splitterStyle = rules[scope.orientation].border;

                    var ssSizePx = (scope.isVertical ? splitterStyle.width : splitterStyle.height) || '';
                    var splitterHitSize = parseInt(ssSizePx.substring(0, ssSizePx.indexOf('px')));

                    if (splitterHitSize < scope.splitterSize)
                    {
                        splitterHitSize = scope.splitterSize;
                        if (scope.isVertical)
                        {
                            handler[0].style.width = splitterHitSize + 'px';
                        }
                        else
                        {
                            handler[0].style.height = splitterHitSize + 'px';
                        }
                    }

                    // initialize splitter and pane positions
                    if (scope.isVertical)
                    {
                        var startX = scope.startX;
                        if (startX < pane1Min) return;
                        if (scope.width - startX < pane2Min) return;

                        handler.css('left', startX + 'px');
                        pane1.elem.css('width', startX + 'px');
                        pane2.elem.css('left', startX + 'px');

                    } else {
                        var startY = scope.startY;
                        if (startY < pane1Min) return;
                        if (scope.height - startY < pane2Min) return;

                        handler.css('top', startY + 'px');
                        pane1.elem.css('height', startY + 'px');
                        pane2.elem.css('top', startY + 'px');
                    }
                }

                styles.loaded.then(onStyleChange);
                onStyleChange(styles.rules);
            }// end postLink
        }
    };
  }])
  .directive('bgPane', function () {
      return {
            restrict: 'E',
            require: '^bgSplitter',
            replace: true,
            transclude: true,
            scope: {
                minSize: '='
            },
            template: '

',
            controllerAs: 'bgPaneCtrl',
            controller: ['$scope', function(scope)
            {
                this.scope = scope;
            }],
            link: {
                pre: function preLink(scope, element, attrs, bgSplitter)
                {
                    var self = scope.bgPaneCtrl;

                    // get dimensions from bgSplitter
                    self.elem = element;
                    self.id = attrs.id;
                    scope.index = bgSplitter.addPane(self);
                    scope.paneSize = bgSplitter.scope.paneSizes[scope.index - 1];
                }
            }
        };
    });
<|endoftext|>


<commit_before>GIT_USER = "lut4rp";

Terminal = Class.create({
    initialize: function (user) {
	this.user = user;
	this.commands = new Hash;
    },
    connection: function (data) {
	this.userdata = data
	$("terminal_console").update("Welcome to ~\/github\/"+this.userdata.user.login+"<\/a>\/
Type \`help\` to get a list of commands.

");
	this.loc = "~/github/"+this.userdata.user.login;
	$("terminal_folder").update(this.loc+"$><\/span>");
	$("terminal_input").show().activate().value = "";
	this.addDefaultCommands();
    },
    changeLoc: function (loc) {
	this.loc = "~/github/"+this.userdata.user.login+loc;
	$("terminal_folder").update(this.loc+"$><\/span>");
    },
    addData: function (element) {
	$("terminal_console").insert({bottom: element});
    },
    addDefaultCommands: function () {
	this.commands.set('whois',{help:'Gives you information about the user.',exec: function () {
	    var company = git.userdata.user.company ? git.userdata.user.company:"No Company";
	    var name = git.userdata.user.name ? git.userdata.user.name:git.userdata.user.login;
	    var blog = git.userdata.user.blog ? git.userdata.user.blog:"No Blog"
		var url  = git.userdata.user.blog ? git.userdata.user.blog:"#"
		    var whois = new Element('div',{class:'info'}).update(name+", "+company+" ("+git.userdata.user.login+") \t "+blog+"<\/a>
 "+git.userdata.user.email+"<\/a>");
	    git.addData(whois);
	}});

	this.commands.set('open', {help:'Opens the page of the current user or the repository.', exec: function () {
	    var where = git.loc.split("/");
	    if (where.length == 3){
		var ref = window.open("http://github.com/"+git.userdata.user.login);
		var emp = new Element("div");
		git.addData(emp);
	    } else {
		var ref = window.open("http://github.com/"+git.userdata.user.login+"/"+where[3]);
		var emp = new Element("div");
		git.addData(emp);
	    }
	}});

	this.commands.set('gitk', {help:'Shows the network graph of the repository you are in.', exec: function () {
	    var where = git.loc.split("/");
	    var message;
	    if (where.length === 3) {
		message = "Can run \'gitk\' on the user";
	    } else {
		var ref = window.open("http://github.com/"+git.userdata.user.login+"/"+where[3]+"/network");
		message = "";
	    };
	    var emp = new Element('div').update(message);
	    git.addData(emp);
	}});

	this.commands.set('help',{help:'Helps those who cant help themselves.', exec: function () {
	    var list = "
";
	    git.commands.keys().sort().each(function (el) {
		list += "
"+el+"<\/td>"+git.commands.get(el).help+"<\/td><\/tr>";
	    });
	    list += "<\/table>";
	    var helpTable = new Element('div').update(list);
	    git.addData(helpTable);
	}});

	this.commands.set('ls',{help:'Lists all the repositories by this user.', exec: function () {
	    var repos = git.userdata.user.repositories;
	    var repEl = new Element('div', {class: 'ls-list'});
	    var list = "
";
	    repos.each(function (el) {
		list += "
"+el.name+"<\/td>"+el.url+"<\/a><\/td><\/tr>"
	    });
	    list += "<\/table>"
	    repEl.update(list);
	    git.addData(repEl);
	}});

	this.commands.set('cd', {help:'should be followed by the name of a repository, to enter it.', exec: function (repo) {
	    repo = repo.reduce();
	    var repos = new Array;
	    git.userdata.user.repositories.each(function (el) {
		repos.push(el.name);
	    });
	    if (repos.indexOf(repo) === -1) {
		if (repo == ".."){
		    git.changeLoc("");
		    var emp = new Element("div");
		    git.addData(emp);
		} else {
		    var noR = new Element("div", {class:'red'}).update("No such repository!");
		    git.addData(noR);
		}
	    } else {
		git.changeLoc("/"+repo);
		var emp = new Element("div");
		git.addData(emp);
	    }

	}});

	this.commands.set('clear',{help:'Clears the scree', exec: function () {
	    $("terminal_console").update();
	}});

	this.commands.set('git', {help:'

log<\/b>: Gives a list of all the recent commits.<\/li>
diff<\/b>: Followed by the SHA1 of the commit gives the changes made in the commit.<\/li><\/ul>', exec: function(command){
	    commands = command.reduce();
	    if (commands == "log") {
		var where = git.loc.split("/");
		if (where.length == 3){
		    var emp = new Element("div").update("Cant run git log here. Enter a repository to run it.");
		    git.addData(emp);
		} else {
		    git.getData('http://github.com/api/v1/json/'+git.userdata.user.login+'/'+where[3]+'/commits/master',"git.commands.get('git').log")
		    $("terminal_console").setStyle({textDecoration:'blink'});
		}
	    }
	    if(command[0] == "diff"){
		var where = git.loc.split("/");
		if (where.length == 3) {
		    var emp = new Element("div").update("Cant run git here here. Enter a repository to run it.");
		    git.addData(emp);
		} else {
		    git.getData('http://github.com/api/v1/json/'+git.userdata.user.login+'/'+where[3]+'/commit/'+command[1],"git.commands.get('git').diff")
		    $("terminal_console").setStyle({textDecoration:'blink'});
		}
	    }
	},
				  log: function (data) {
				      $("terminal_console").setStyle({textDecoration:'none'});
				      var log = ""
					  data.commits.each(function (el) {
					      log += "
";
					      log += "commit <\/a>"+el.id;
					      log += "
Author: "+el.author.name+" ["+el.author.email+"]<\/a>";
					      log += "
Date: "+el.committed_date;
					      log += "
"+el.message+"<\/blockquote>";
					      log += "<\/div>";
					  });
				      var logEl = new Element('div').update(log);
				      git.addData(logEl);
				      Effect.ScrollTo("the_end");
				  },
				  diff: function (data) {
				      $("terminal_console").setStyle({textDecoration:'none'});
				      console.log(data);
				      var commit = "
";
				      commit += "
"+data.commit.message+"<\/blockquote>";
				      commit += "commit "+data.commit.id+"<\/a>";
				      commit += "
Modified:";
				      data.commit.modified.each(function (el) {
					  commit += "
*"+el.filename;
				      });

				      commit += "
Added:";
				      data.commit.added.each(function(el) {
					  commit += "
+"+el.filename;
				      });
				      commit += "
Removed:";
				      data.commit.removed.each(function (el) {
					  commit += "
-"+el.filename+"<\/del>";
				      });
				      commit+= "<\/span>";
				      commit +=  "<\/div>";
				      var commitEl = new Element('div').update(commit);
				      git.addData(commitEl);
				  }
				 });
    },
    exec: function (command) {
	var comEl = new Element('span', {class:'com'});
	comEl.update(""+ this.loc +">" + command);
	this.addData(comEl);

	if (command.include(" ")) {
	    var param = command.split(" ");
	    command = param[0];
	    param = param.without(command);
	};

	var com = (this.commands.get(command));

	if (!com) {
	    this.addData("
No such command
");
	} else {
	    com.exec(param);
	}

	$("terminal_input").value = "";
	Effect.ScrollTo("the_end");
    },
    getData: function (url,callback) {
	var sc = new Element('script', {src:url+"?callback="+callback});
	console.log(sc);
	$(document.body).insert(sc);
    },
});

    git = new Terminal(GIT_USER);

    document.observe('dom:loaded', function (e) {
	var sc = new Element('script', {src:'http://github.com/api/v1/json/'+GIT_USER+'?callback=initTerm'});
	$(document.body).insert(sc);

	$("term_in").observe('submit', function (e) {
	    e.stop();
	    git.exec($F("terminal_input"));
	});

    });

    initTerm = function (data) {
	git.connection(data);
    };
<commit_msg>Fixed issue #1: small typo<commit_after>GIT_USER = "lut4rp";

Terminal = Class.create({
    initialize: function (user) {
	this.user = user;
	this.commands = new Hash;
    },
    connection: function (data) {
	this.userdata = data
	$("terminal_console").update("Welcome to ~\/github\/"+this.userdata.user.login+"<\/a>\/
Type \`help\` to get a list of commands.

");
	this.loc = "~/github/"+this.userdata.user.login;
	$("terminal_folder").update(this.loc+"$><\/span>");
	$("terminal_input").show().activate().value = "";
	this.addDefaultCommands();
    },
    changeLoc: function (loc) {
	this.loc = "~/github/"+this.userdata.user.login+loc;
	$("terminal_folder").update(this.loc+"$><\/span>");
    },
    addData: function (element) {
	$("terminal_console").insert({bottom: element});
    },
    addDefaultCommands: function () {
	this.commands.set('whois',{help:'Gives you information about the user.',exec: function () {
	    var company = git.userdata.user.company ? git.userdata.user.company:"No Company";
	    var name = git.userdata.user.name ? git.userdata.user.name:git.userdata.user.login;
	    var blog = git.userdata.user.blog ? git.userdata.user.blog:"No Blog"
		var url  = git.userdata.user.blog ? git.userdata.user.blog:"#"
		    var whois = new Element('div',{class:'info'}).update(name+", "+company+" ("+git.userdata.user.login+") \t "+blog+"<\/a>
 "+git.userdata.user.email+"<\/a>");
	    git.addData(whois);
	}});

	this.commands.set('open', {help:'Opens the page of the current user or the repository.', exec: function () {
	    var where = git.loc.split("/");
	    if (where.length == 3){
		var ref = window.open("http://github.com/"+git.userdata.user.login);
		var emp = new Element("div");
		git.addData(emp);
	    } else {
		var ref = window.open("http://github.com/"+git.userdata.user.login+"/"+where[3]);
		var emp = new Element("div");
		git.addData(emp);
	    }
	}});

	this.commands.set('gitk', {help:'Shows the network graph of the repository you are in.', exec: function () {
	    var where = git.loc.split("/");
	    var message;
	    if (where.length === 3) {
		message = "Can run \'gitk\' on the user";
	    } else {
		var ref = window.open("http://github.com/"+git.userdata.user.login+"/"+where[3]+"/network");
		message = "";
	    };
	    var emp = new Element('div').update(message);
	    git.addData(emp);
	}});

	this.commands.set('help',{help:'Helps those who cant help themselves.', exec: function () {
	    var list = "
";
	    git.commands.keys().sort().each(function (el) {
		list += "
"+el+"<\/td>"+git.commands.get(el).help+"<\/td><\/tr>";
	    });
	    list += "<\/table>";
	    var helpTable = new Element('div').update(list);
	    git.addData(helpTable);
	}});

	this.commands.set('ls',{help:'Lists all the repositories by this user.', exec: function () {
	    var repos = git.userdata.user.repositories;
	    var repEl = new Element('div', {class: 'ls-list'});
	    var list = "
";
	    repos.each(function (el) {
		list += "
"+el.name+"<\/td>"+el.url+"<\/a><\/td><\/tr>"
	    });
	    list += "<\/table>"
	    repEl.update(list);
	    git.addData(repEl);
	}});

	this.commands.set('cd', {help:'should be followed by the name of a repository, to enter it.', exec: function (repo) {
	    repo = repo.reduce();
	    var repos = new Array;
	    git.userdata.user.repositories.each(function (el) {
		repos.push(el.name);
	    });
	    if (repos.indexOf(repo) === -1) {
		if (repo == ".."){
		    git.changeLoc("");
		    var emp = new Element("div");
		    git.addData(emp);
		} else {
		    var noR = new Element("div", {class:'red'}).update("No such repository!");
		    git.addData(noR);
		}
	    } else {
		git.changeLoc("/"+repo);
		var emp = new Element("div");
		git.addData(emp);
	    }

	}});

	this.commands.set('clear',{help:'Clears the screen', exec: function () {
	    $("terminal_console").update();
	}});

	this.commands.set('git', {help:'

log<\/b>: Gives a list of all the recent commits.<\/li>
diff<\/b>: Followed by the SHA1 of the commit gives the changes made in the commit.<\/li><\/ul>', exec: function(command){
	    commands = command.reduce();
	    if (commands == "log") {
		var where = git.loc.split("/");
		if (where.length == 3){
		    var emp = new Element("div").update("Cant run git log here. Enter a repository to run it.");
		    git.addData(emp);
		} else {
		    git.getData('http://github.com/api/v1/json/'+git.userdata.user.login+'/'+where[3]+'/commits/master',"git.commands.get('git').log")
		    $("terminal_console").setStyle({textDecoration:'blink'});
		}
	    }
	    if(command[0] == "diff"){
		var where = git.loc.split("/");
		if (where.length == 3) {
		    var emp = new Element("div").update("Cant run git here here. Enter a repository to run it.");
		    git.addData(emp);
		} else {
		    git.getData('http://github.com/api/v1/json/'+git.userdata.user.login+'/'+where[3]+'/commit/'+command[1],"git.commands.get('git').diff")
		    $("terminal_console").setStyle({textDecoration:'blink'});
		}
	    }
	},
				  log: function (data) {
				      $("terminal_console").setStyle({textDecoration:'none'});
				      var log = ""
					  data.commits.each(function (el) {
					      log += "
";
					      log += "commit <\/a>"+el.id;
					      log += "
Author: "+el.author.name+" ["+el.author.email+"]<\/a>";
					      log += "
Date: "+el.committed_date;
					      log += "
"+el.message+"<\/blockquote>";
					      log += "<\/div>";
					  });
				      var logEl = new Element('div').update(log);
				      git.addData(logEl);
				      Effect.ScrollTo("the_end");
				  },
				  diff: function (data) {
				      $("terminal_console").setStyle({textDecoration:'none'});
				      console.log(data);
				      var commit = "
";
				      commit += "
"+data.commit.message+"<\/blockquote>";
				      commit += "commit "+data.commit.id+"<\/a>";
				      commit += "
Modified:";
				      data.commit.modified.each(function (el) {
					  commit += "
*"+el.filename;
				      });

				      commit += "
Added:";
				      data.commit.added.each(function(el) {
					  commit += "
+"+el.filename;
				      });
				      commit += "
Removed:";
				      data.commit.removed.each(function (el) {
					  commit += "
-"+el.filename+"<\/del>";
				      });
				      commit+= "<\/span>";
				      commit +=  "<\/div>";
				      var commitEl = new Element('div').update(commit);
				      git.addData(commitEl);
				  }
				 });
    },
    exec: function (command) {
	var comEl = new Element('span', {class:'com'});
	comEl.update(""+ this.loc +">" + command);
	this.addData(comEl);

	if (command.include(" ")) {
	    var param = command.split(" ");
	    command = param[0];
	    param = param.without(command);
	};

	var com = (this.commands.get(command));

	if (!com) {
	    this.addData("
No such command
");
	} else {
	    com.exec(param);
	}

	$("terminal_input").value = "";
	Effect.ScrollTo("the_end");
    },
    getData: function (url,callback) {
	var sc = new Element('script', {src:url+"?callback="+callback});
	console.log(sc);
	$(document.body).insert(sc);
    },
});

    git = new Terminal(GIT_USER);

    document.observe('dom:loaded', function (e) {
	var sc = new Element('script', {src:'http://github.com/api/v1/json/'+GIT_USER+'?callback=initTerm'});
	$(document.body).insert(sc);

	$("term_in").observe('submit', function (e) {
	    e.stop();
	    git.exec($F("terminal_input"));
	});

    });

    initTerm = function (data) {
	git.connection(data);
    };
<|endoftext|>


<commit_before>"use strict";
(function() {
  var readyCount = 0;
  var tickInterval = 100;
  var tickIntervalContainer = null;
  var currentPass = "";
  var passInput = null;
  var tripInput = null;

  var suffix = "H.";
  var saltTable =
  ".............................................../0123456789ABCDEF" +
	"GABCDEFGHIJKLMNOPQRSTUVWXYZabcdefabcdefghijklmnopqrstuvwxyz....." +
	"................................................................" +
	"................................................................";

  function sjisEncode(pass) {
    var conv = "";
    var char = null;
    for (var i = 0; i < pass.length; i++) {
      char = window.sjisconv[pass[i]];
      if (char === undefined) {
        char = "?";
      }
      conv += char;
    }
    return conv;
  }

  function htmlEntitiesEncode(pass) {
    return pass.replace("&", "&").replace(">", ">").replace("<", "<").replace('"', """);
  }

  function makeTripcode(pass) {
    pass = htmlEntitiesEncode(pass);
    if (pass.length > 8) {
      pass = pass.substr(0, 8);
    }
    pass = sjisEncode();
    if (!pass) {
      return "";
    }
    var salt = "";
    for (var i = 1; i < 3; i++) {
      salt += saltTable[(pass + suffix).charCodeAt(i) % 256];
    }
    return window.Javacrypt.crypt(salt, pass)[0].substring(3);
  }

  function listenTick() {
    currentPass = passInput.value;
    if (!currentPass) {
      tripInput.value = "";
      return;
    }
    if (currentPass.length > 8) {
      currentPass = currentPass.substr(0, 8);
    }
    tripInput.value = makeTripcode(currentPass);
  }

  function startListening() {
    passInput = document.getElementById("pass");
    tripInput = document.getElementById("trip");
    tickIntervalContainer = setInterval(listenTick, tickInterval);
  }

  function onSjisconvDone() {
    document.removeEventListener("sjisconvDone", onSjisconvDone);
    if (++readyCount > 2) {
      startListening();
    }
  }

  function onJavacryptDone() {
    document.removeEventListener("sjisconvDone", onJavacryptDone);
    if (++readyCount > 2) {
      startListening();
    }
  }

  function onDOMContentLoaded() {
    document.removeEventListener("DOMContentLoaded", onDOMContentLoaded);
    if (++readyCount > 2) {
      startListening();
    }
  }

  document.addEventListener("sjisconvDone", onSjisconvDone);
  document.addEventListener("javacryptDone", onJavacryptDone);
  document.addEventListener("DOMContentLoaded", onDOMContentLoaded);
}).call(this);
<commit_msg>Update tripcode.js<commit_after>"use strict";
(function() {
  var readyCount = 0;
  var tickInterval = 100;
  var tickIntervalContainer = null;
  var currentPass = "";
  var passInput = null;
  var tripInput = null;

  var suffix = "H.";
  var saltTable =
  ".............................................../0123456789ABCDEF" +
  "GABCDEFGHIJKLMNOPQRSTUVWXYZabcdefabcdefghijklmnopqrstuvwxyz....." +
  "................................................................" +
  "................................................................";

  function sjisEncode(pass) {
    var conv = "";
    var char = null;
    for (var i = 0; i < pass.length; i++) {
      char = window.sjisconv[pass[i]];
      if (char === undefined) {
        char = "?";
      }
      conv += char;
    }
    return conv;
  }

  function htmlEntitiesEncode(pass) {
    return pass.replace("&", "&").replace(">", ">").replace("<", "<").replace('"', """);
  }

  function makeTripcode(pass) {
    pass = htmlEntitiesEncode(pass);
    if (pass.length > 8) {
      pass = pass.substr(0, 8);
    }
    pass = sjisEncode(pass);
    if (!pass) {
      return "";
    }
    var salt = "";
    for (var i = 1; i < 3; i++) {
      salt += saltTable[(pass + suffix).charCodeAt(i) % 256];
    }
    return window.Javacrypt.crypt(salt, pass)[0].substring(3);
  }

  function listenTick() {
    currentPass = passInput.value;
    if (!currentPass) {
      tripInput.value = "";
      return;
    }
    if (currentPass.length > 8) {
      currentPass = currentPass.substr(0, 8);
    }
    tripInput.value = makeTripcode(currentPass);
  }

  function startListening() {
    passInput = document.getElementById("pass");
    tripInput = document.getElementById("trip");
    tickIntervalContainer = setInterval(listenTick, tickInterval);
  }

  function onSjisconvDone() {
    document.removeEventListener("sjisconvDone", onSjisconvDone);
    if (++readyCount > 2) {
      startListening();
    }
  }

  function onJavacryptDone() {
    document.removeEventListener("sjisconvDone", onJavacryptDone);
    if (++readyCount > 2) {
      startListening();
    }
  }

  function onDOMContentLoaded() {
    document.removeEventListener("DOMContentLoaded", onDOMContentLoaded);
    if (++readyCount > 2) {
      startListening();
    }
  }

  document.addEventListener("sjisconvDone", onSjisconvDone);
  document.addEventListener("javacryptDone", onJavacryptDone);
  document.addEventListener("DOMContentLoaded", onDOMContentLoaded);
}).call(this);
<|endoftext|>


<commit_before>"use strict";
(function() {
  var readyCount = 0;
  var tickInterval = 100;
  var tickIntervalContainer = null;
  var currentPass = "";
  var passInput = null;
  var tripInput = null;

  var suffix = "H.";
  var saltTable =
  ".............................................../0123456789ABCDEF" +
	"GABCDEFGHIJKLMNOPQRSTUVWXYZabcdefabcdefghijklmnopqrstuvwxyz....." +
	"................................................................" +
	"................................................................";

  function sjisEncode(pass) {
    var conv = "";
    var char = null;
    for (var i = 0; i < pass.length; i++) {
      char = window.sjisconv[pass[i]];
      if (char === undefined) {
        char = "?";
      }
      conv += char;
    }
    return conv;
  }

  function htmlEntitiesEncode(pass) {
    return pass.replace("&", "&").replace(">", ">").replace("<", "<").replace('"', """);
  }

  function makeTripcode(pass) {
    pass = sjisEncode(htmlEntitiesEncode(pass));
    if (!pass) {
      return "";
    }
    var salt = "";
    for (var i = 1; i < 3; i++) {
      salt += salt_table[(pass + suffix).charCodeAt(i) % 256];
    }
    return window.javacrypt.crypt(salt, pass)[0].substring(3);
  }

  function listenTick() {
    currentPass = passInput.value;
    if (!currentPass) {
      tripInput.value = "";
      return;
    }
    if (currentPass.length > 8) {
      currentPass = currentPass.substr(0, 8);
    }
    tripInput.value = makeTripcode(currentPass);
  }

  function startListening() {
    passInput = document.getElementById("pass");
    tripInput = document.getElementById("trip");
    tickIntervalContainer = setInterval(listenTick, tickInterval);
  }

  function onSjisconvDone() {
    document.removeEventListener("sjisconvDone", onSjisconvDone);
    if (++readyCount > 1) {
      startListening();
    }
  }

  function onDOMContentLoaded() {
    document.removeEventListener("DOMContentLoaded", onDOMContentLoaded);
    if (++readyCount > 1) {
      startListening();
    }
  }

  document.addEventListener("sjisconvDone", onSjisconvDone);
  document.addEventListener("DOMContentLoaded", onDOMContentLoaded);
}).call(this);
<commit_msg>Update tripcode.js<commit_after>"use strict";
(function() {
  var readyCount = 0;
  var tickInterval = 100;
  var tickIntervalContainer = null;
  var currentPass = "";
  var passInput = null;
  var tripInput = null;

  var suffix = "H.";
  var saltTable =
  ".............................................../0123456789ABCDEF" +
	"GABCDEFGHIJKLMNOPQRSTUVWXYZabcdefabcdefghijklmnopqrstuvwxyz....." +
	"................................................................" +
	"................................................................";

  function sjisEncode(pass) {
    var conv = "";
    var char = null;
    for (var i = 0; i < pass.length; i++) {
      char = window.sjisconv[pass[i]];
      if (char === undefined) {
        char = "?";
      }
      conv += char;
    }
    return conv;
  }

  function htmlEntitiesEncode(pass) {
    return pass.replace("&", "&").replace(">", ">").replace("<", "<").replace('"', """);
  }

  function makeTripcode(pass) {
    pass = sjisEncode(htmlEntitiesEncode(pass));
    if (!pass) {
      return "";
    }
    var salt = "";
    for (var i = 1; i < 3; i++) {
      salt += salt_table[(pass + suffix).charCodeAt(i) % 256];
    }
    return window.Javacrypt.crypt(salt, pass)[0].substring(3);
  }

  function listenTick() {
    currentPass = passInput.value;
    if (!currentPass) {
      tripInput.value = "";
      return;
    }
    if (currentPass.length > 8) {
      currentPass = currentPass.substr(0, 8);
    }
    tripInput.value = makeTripcode(currentPass);
  }

  function startListening() {
    passInput = document.getElementById("pass");
    tripInput = document.getElementById("trip");
    tickIntervalContainer = setInterval(listenTick, tickInterval);
  }

  function onSjisconvDone() {
    document.removeEventListener("sjisconvDone", onSjisconvDone);
    if (++readyCount > 2) {
      startListening();
    }
  }

  function onJavacryptDone() {
    document.removeEventListener("sjisconvDone", onJavacryptDone);
    if (++readyCount > 2) {
      startListening();
    }
  }

  function onDOMContentLoaded() {
    document.removeEventListener("DOMContentLoaded", onDOMContentLoaded);
    if (++readyCount > 2) {
      startListening();
    }
  }

  document.addEventListener("sjisconvDone", onSjisconvDone);
  document.addEventListener("javacryptDone", onJavacryptDone);
  document.addEventListener("DOMContentLoaded", onDOMContentLoaded);
}).call(this);
<|endoftext|>


<commit_before>/**
 * Created by amanu on 7/30/15.
 *
 * Each uploader will be a table,
 * each row will represent an image upload task
 * each task can be saved, or deleted
 * after image is uploaded, image some id is received, and after
 *
 * Needed Components,
 *  a table,
 *  a row
 *  a data for additional columns
 *
 */
(function ($) {

    window.UploaderConfig = {
        max: 4,
        placeHolder: "../images/placeholder",
        addButtonClass: 'btn btn-sm btn-success uploader-add',
        addButtonText: '',
        saveAllButtonClass: 'btn btn-sm btn-primary',
        saveAllButtonText: '',
        removeAllButtonClass: 'btn btn-sm btn-danger',
        removeAllButtonText: '',
        saveButtonClass: 'btn btn-sm btn-primary',
        saveButtonText: '',
        removeButtonClass: 'btn btn-sm btn-danger',
        removeButtonText: '',
        uploaderClass: 'table table-striped table-condensed',
        commandRowClass: '',
        imageRowClass: '',
        imageContainerClass: '',
        loadingImage: '

',
        imageClass: 'img-responsive img-thumbnail',
        inputContainerClass: 'input-group input-group-sm',
        textInputClass: 'input-sm',
        numberInputClass: 'input-sm',
        fileInputClass: '',
        longTextInputClass: '',
        set: function (settings) {
        },
        uploaders: [],
        done: function (uploader_id, task_id) {
            console.log([uploader_id, task_id]);
            if (typeof this.uploaders[uploader_id] != 'undefined'
                && typeof this.uploaders[uploader_id].tasks[task_id] != 'undefined') {

                var task = this.uploaders[uploader_id].tasks[task_id];
                task.done();

            }
        }
    };

    $.fn.uploader = function (settings) {
        var $element = $(this);
        var uc = UploaderConfig;
        UploaderConfig.$element = $element;

        var Uploader = {
            $element: $element,
            $table: null,
            $commandRow: null,
            settings: {url: 'upload.html'},
            tasks: [], //TODO: Add a task scheduling and starting mechanism
            rowCount: 0,

            addToQueue: function ($row) {
                var task = {$row: $row};
                task.done = function () {
                    console.log(this.$row)
                    Uploader.doneUploading(this.$row);
                };
                Uploader.tasks.push(task);
                Uploader.uploadImage(task);
            },
            uploadImage: function (task) {
                var files = task.$row
                    .find('td:first-child input[type=file]').prop('files');

                if (typeof FormData == 'function') {

                    var formData = new FormData();
                    formData.append('upload', files[0]);

                    $.ajax({
                        method: 'POST',
                        url: 'upload.html',
                        contentType: false,
                        processData: false,
                        data: formData,
                        success: function (e) {
                            $('body').append(e).children(":last-child").remove();
                        }
                    })
                } else {
                    var $iframe = Uploader.createIframe(task.$row);

                    var $form = $iframe.contents().find('body')
                        .append('<form method="post" enctype="multipart/form-data" ></form>')
                        .children(':last-child')
                        .attr('action', Uploader.settings.url);
                    $form
                        .append('<input type="file" name="upload"/>')
                        .children(':last-child')
                        .prop('files', files);
                    $form.submit(function (e) {
                        console.log(e.target)
                    }).submit();
                }
            },
            createIframe: function ($row) {
                this.rowCount++;
                return $row
                    .find('td:first-child')
                    .append('

')
                    .children(':last-child')
                    .attr('id', 'progress_' + this.rowCount)
                    .end()
                    .append('')
                    .children(':last-child')
                    .attr('name', 'image_frame_' + this.rowCount)
                    .attr('id', 'image_frame_' + this.rowCount);
            },
            fileSelected: function ($row) {
                Uploader.addToQueue($row);
            },
            cancelUpload: function () {
            },
            doneUploading: function ($row) {
                $row.remove();
            },
            saveUpload: function () {
            },
            addRow: function () {

                //Creating the row,
                var $newRow = Uploader.$table.find('.uploader-command-row')
                    .after('
')
                    .next('tr');

                //add the columns needed
                $newRow
                    .append('')
                    .children(':last-child')
                    .append('
')
                    .children(':last-child')
                    .append(uc.loadingImage)
                    .end()
                    .append('<input type="file" class="hide"/>')
                    .end()
                    .append('')
                    .children(':last-child')
                    .append('  ')
                    .children(':last-child')
                    .addClass(uc.saveButtonClass)
                    .append(uc.saveButtonText)
                    .attr('disabled', true)
                    .end()
                    .append('')
                    .children(':last-child')
                    .addClass(uc.removeButtonClass)
                    .append(uc.removeButtonText);

                if (Uploader.settings.inputs) {
                    for (c in Uploader.settings.inputs) {
                        var input = Uploader.settings.inputs[c]

                        switch (input.type) {
                            case 'text':
                                var $input = $newRow
                                    .append('')
                                    .children(':last-child')
                                    .append('
')
                                    .children(':last-child')
                                    .addClass(uc.inputContainerClass)
                                    .append('<input type="text"/>')
                                    .children(':last-child')
                                    .addClass(uc.textInputClass);

                                break;
                        }

                        $input.attr('id', input.name)
                        $input.attr('name', input.name)
                        if ($.isFunction(input.callback)) {
                            input.callback($input);
                        }
                    }
                }

                //create the handlers

                //remove handler
                $newRow.find('.uploader-remove').click(this.removeRow);

                //when file is selected, que the image upload
                $newRow.find('input[type=file]').change(function () {
                    Uploader.fileSelected($newRow)
                }).click();

                //save handler
                $newRow.find('.save').click(function () {
                    //saveUpload();
                });

                //execute preparations

                return false;
            },
            removeRow: function () {
                //cancelUpload();
                $newRow.remove();
                return false;
            },

            construct: function () {
                //create the table
                var $table = $element
                    .append('
')
                    .children(':last-child')
                    .addClass(uc.uploaderClass)
                    .append('
')
                    .children(':last-child');

                this.$element = $element;
                this.$table = $table;

                //create the command row
                var $commandRow = $table.append('
').children(':last-child');
                $commandRow.addClass(uc.commandRowClass);
                $commandRow.addClass('uploader-command-row');

                this.$commandRow = $commandRow;

                //command buttons
                $commandRow
                    .append('')
                    .children(':last-child')
                    .css({width: '200px'})
                    .append('' + uc.addButtonText + '  ')
                    .children(':last-child').addClass(uc.addButtonClass)
                    .end()
                    .append('' + uc.saveAllButtonText + '  ')
                    .children(':last-child').addClass(uc.saveAllButtonClass)
                    .end()
                    .append('' + uc.removeAllButtonText + '  ')
                    .children(':last-child').addClass(uc.removeAllButtonClass)
                    .end();

                var $add = $commandRow.find('.uploader-add');
                var $saveAll = $commandRow.find('.uploader-save-all');
                var $removeAll = $commandRow.find('.uploader-remove-all');
                var rowCount = 0;

                $add.click(this.addRow);

                $saveAll.click(function () {
                    //Go around clicking all save buttons
                    $table.find('.uploader-save').click();
                });

                UploaderConfig.uploaders.push(Uploader);
            }

        };

        Uploader.construct();
        return $(this);
    };

    $(document).ready(function () {
        //create and attach an Uploader to the body
        $('body').first().uploader(
            {
                inputs: [{
                    name: 'description', type: 'text', callback: function ($element) {
                        console.log($element);
                    }
                }]
            });

    })

}(jQuery));

<commit_msg>Added extra parameters so that the response from server has a correct callback.<commit_after>/**
 * Created by amanu on 7/30/15.
 *
 * Each uploader will be a table,
 * each row will represent an image upload task
 * each task can be saved, or deleted
 * after image is uploaded, image some id is received, and after
 *
 * Needed Components,
 *  a table,
 *  a row
 *  a data for additional columns
 *
 */
(function ($) {

    window.UploaderConfig = {
        max: 4,
        placeHolder: "../images/placeholder",
        addButtonClass: 'btn btn-sm btn-success uploader-add',
        addButtonText: '',
        saveAllButtonClass: 'btn btn-sm btn-primary',
        saveAllButtonText: '',
        removeAllButtonClass: 'btn btn-sm btn-danger',
        removeAllButtonText: '',
        saveButtonClass: 'btn btn-sm btn-primary',
        saveButtonText: '',
        removeButtonClass: 'btn btn-sm btn-danger',
        removeButtonText: '',
        uploaderClass: 'table table-striped table-condensed',
        commandRowClass: '',
        imageRowClass: '',
        imageContainerClass: '',
        loadingImage: '

',
        imageClass: 'img-responsive img-thumbnail',
        inputContainerClass: 'input-group input-group-sm',
        textInputClass: 'input-sm',
        numberInputClass: 'input-sm',
        fileInputClass: '',
        longTextInputClass: '',
        set: function (settings) {
        },
        uploaders: [],
        done: function (uploader_id, task_id) {

            if (typeof this.uploaders[uploader_id] != 'undefined'
                && typeof this.uploaders[uploader_id].tasks[task_id] != 'undefined') {

                var task = this.uploaders[uploader_id].tasks[task_id];
                task.done();

            }
        }
    };

    $.fn.uploader = function (settings) {
        var $element = $(this);
        var uc = UploaderConfig;
        UploaderConfig.$element = $element;

        var Uploader = {
            $element: $element,
            $table: null,
            $commandRow: null,
            settings: settings,
            tasks: [], //TODO: Add a task scheduling and starting mechanism
            rowCount: 0,

            addToQueue: function ($row) {
                var task = {$row: $row};
                task.done = function () {
                    Uploader.doneUploading(this.$row);
                };
                Uploader.tasks.push(task);
                Uploader.uploadImage(task);
            },
            uploadImage: function (task) {
                var files = task.$row
                    .find('td:first-child input[type=file]').prop('files');

                if (typeof FormData == 'function') {

                    var formData = new FormData();
                    formData.append('upload', files[0]);
                    formData.append('uploader', 0);
                    formData.append('task', Uploader.rowCount - 1);
                    formData.append('callback', 'window.UploaderConfig.done');
                    formData.append('ajax', true);

                    $.ajax({
                        method: 'POST',
                        url: Uploader.settings.url,
                        contentType: false,
                        processData: false,
                        data: formData,
                        success: function (e, f) {
                            //append the response to the body, then remove it
                            $('body').append('


<commit_before>WorldMap = function(_parentElement, _data, _metaData, _eventHandler){

  this.parentElement = _parentElement;
  this.data = _data;
  this.metaData = _metaData;
  this.eventHandler = _eventHandler;
  this.displayData = [];

  this.initVis();
}

WorldMap.prototype.initVis = function(){

  var that = this;

  this.map =  new Datamap({
    element: document.getElementById("worldmap"),
    projection: "mercator",
    arcConfig: {
      strokeColor: "#00BFFF",
      strokeWidth: 1,
      arcSharpness: 1.4,
      animationSpeed: 600
    }
  });

  this.wrangleData();

  this.updateVis();
}

WorldMap.prototype.wrangleData= function(_filterFunction){
  this.displayData = this.filterAndAggregate(_filterFunction);
}

WorldMap.prototype.filterAndAggregate = function(_filter){

    var filter = _filter || function(){return true;}

    var that = this;

    return this.data;

}

WorldMap.prototype.updateVis = function(){
  this.map.arc(this.data);

  /*this.map.arc([
    {
        origin: {
            latitude: 30.194444,
            longitude: -97.67
        },
        destination: {
            latitude: 25.793333,
            longitude: -80.290556
        },
        test: {test2: "abc"},
        options: {
          strokeWidth: 0.2,
  greatArc: true
        }
    },
    {
        origin: {
            latitude: 39.861667,
            longitude: -104.673056
        },
        destination: {
            latitude: 35.877778,
            longitude: -78.7875
        }
    }
]);*/
}

WorldMap.prototype.onSelectionChange= function (ranges){
}

// HELPERS

<commit_msg>put arcs on map<commit_after>WorldMap = function(_parentElement, _data, _metaData, _eventHandler){

  this.parentElement = _parentElement;
  this.data = _data;
  this.metaData = _metaData;
  this.eventHandler = _eventHandler;
  this.displayData = [];

  this.initVis();
}

WorldMap.prototype.initVis = function(){

  var that = this;

  this.map =  new Datamap({
    element: document.getElementById("worldmap"),
    projection: "mercator",
    arcConfig: {
      strokeColor: "#00BFFF",
      strokeWidth: 1,
      arcSharpness: 1.4,
      animationSpeed: 600
    }
  });

  this.wrangleData(/*function(d) { return d.origin.country == "Germany" || d.destination.country == "Germany" }*/);

  this.updateVis();
}

WorldMap.prototype.wrangleData= function(_filterFunction){
  this.displayData = this.filterAndAggregate(_filterFunction);
  debugger;
}

WorldMap.prototype.filterAndAggregate = function(_filter){

    var filter = _filter || function(){return true;}

    var that = this;

    return this.data.filter(function(d) {
      return filter(d);
    });

}

WorldMap.prototype.updateVis = function(){
  this.map.arc(this.data);

  /*this.map.arc([
    {
        origin: {
            latitude: 30.194444,
            longitude: -97.67
        },
        destination: {
            latitude: 25.793333,
            longitude: -80.290556
        },
        test: {test2: "abc"},
        options: {
          strokeWidth: 0.2,
  greatArc: true
        }
    },
    {
        origin: {
            latitude: 39.861667,
            longitude: -104.673056
        },
        destination: {
            latitude: 35.877778,
            longitude: -78.7875
        }
    }
]);*/
}

WorldMap.prototype.onSelectionChange= function (ranges){
}

// HELPERS

<|endoftext|>