<commit_before>/*jslint node: true */
"use strict";

if (typeof process === 'object' && typeof process.versions === 'object' && typeof process.versions.node !== 'undefined') { // desktop
	var desktopApp = require('./desktop_app.js');
	var appRootDir = desktopApp.getAppRootDir();
	require('dotenv').config({path: appRootDir + '/.env'});
}

exports.COUNT_WITNESSES = 12;
exports.MAX_WITNESS_LIST_MUTATIONS = 1;
exports.TOTAL_WHITEBYTES = 1e15;
exports.MAJORITY_OF_WITNESSES = (exports.COUNT_WITNESSES%2===0) ? (exports.COUNT_WITNESSES/2+1) : Math.ceil(exports.COUNT_WITNESSES/2);
exports.COUNT_MC_BALLS_FOR_PAID_WITNESSING = 100;

exports.bTestnet = !!process.env.testnet;
console.log('===== testnet = ' + exports.bTestnet);

exports.version = exports.bTestnet ? '2.0t' : '2.0';
exports.alt = exports.bTestnet ? '2' : '1';

exports.supported_versions = exports.bTestnet ? ['1.0t', '2.0t'] : ['1.0', '2.0'];
exports.versionWithoutTimestamp = exports.bTestnet ? '1.0t' : '1.0';

//exports.bTestnet = (exports.alt === '2' && exports.version === '1.0t');

exports.GENESIS_UNIT = exports.bTestnet ? 'TvqutGPz3T4Cs6oiChxFlclY92M2MvCvfXR5/FETato=' : 'oj8yEksX9Ubq7lLc+p6F2uyHUuynugeVq4+ikT67X6E=';
exports.BLACKBYTES_ASSET = exports.bTestnet ? 'LUQu5ik4WLfCrr8OwXezqBa+i3IlZLqxj2itQZQm8WY=' : 'qO2JsiuDMh/j+pqJYZw3u82O71WjCDf0vTNvsnntr8o=';

exports.HASH_LENGTH = 44;
exports.PUBKEY_LENGTH = 44;
exports.SIG_LENGTH = 88;

// anti-spam limits
exports.MAX_AUTHORS_PER_UNIT = 16;
exports.MAX_PARENTS_PER_UNIT = 16;
exports.MAX_MESSAGES_PER_UNIT = 128;
exports.MAX_SPEND_PROOFS_PER_MESSAGE = 128;
exports.MAX_INPUTS_PER_PAYMENT_MESSAGE = 128;
exports.MAX_OUTPUTS_PER_PAYMENT_MESSAGE = 128;
exports.MAX_CHOICES_PER_POLL = 128;
exports.MAX_CHOICE_LENGTH = 64;
exports.MAX_DENOMINATIONS_PER_ASSET_DEFINITION = 64;
exports.MAX_ATTESTORS_PER_ASSET = 64;
exports.MAX_DATA_FEED_NAME_LENGTH = 64;
exports.MAX_DATA_FEED_VALUE_LENGTH = 64;
exports.MAX_AUTHENTIFIER_LENGTH = 4096;
exports.MAX_CAP = 9e15;
exports.MAX_COMPLEXITY = 100;
exports.MAX_UNIT_LENGTH = 5e6;

exports.MAX_PROFILE_FIELD_LENGTH = 50;
exports.MAX_PROFILE_VALUE_LENGTH = 100;

exports.MAX_AA_STRING_LENGTH = 4096;
exports.MAX_STATE_VAR_NAME_LENGTH = 128;
exports.MAX_STATE_VAR_VALUE_LENGTH = 1024;
exports.MAX_OPS = 2000;

exports.TEXTCOIN_CLAIM_FEE = 548;
exports.TEXTCOIN_ASSET_CLAIM_FEE = 750;
exports.TEXTCOIN_ASSET_CLAIM_HEADER_FEE = 391;
exports.TEXTCOIN_ASSET_CLAIM_MESSAGE_FEE = 209;
exports.TEXTCOIN_ASSET_CLAIM_BASE_MSG_FEE = 158;
exports.TEXTCOIN_PRIVATE_ASSET_CLAIM_MESSAGE_FEE = 99;
exports.MIN_BYTES_BOUNCE_FEE = 10000;

exports.minCoreVersion = exports.bTestnet ? '0.3.0' : '0.2.0';
exports.minCoreVersionForFullNodes = exports.bTestnet ? '0.3.0' : '0.2.94';

exports.lastBallStableInParentsUpgradeMci = 1300000;
exports.witnessedLevelMustNotRetreatUpgradeMci = exports.bTestnet ? 684000 : 1400000;
exports.spendUnconfirmedUpgradeMci = exports.bTestnet ? 589000 : 2909000;
exports.branchedMinMcWlUpgradeMci = exports.bTestnet ? 593000 : 2909000;
exports.otherAddressInDefinitionUpgradeMci = exports.bTestnet ? 602000 : 2909000;
exports.attestedInDefinitionUpgradeMci = exports.bTestnet ? 616000 : 2909000;
exports.altBranchByBestParentUpgradeMci = exports.bTestnet ? 642000 : 3009824;
exports.anyDefinitionChangeUpgradeMci = exports.bTestnet ? 855000 : 4229100;
exports.formulaUpgradeMci = exports.bTestnet ? 961000 : Infinity;
exports.witnessedLevelMustNotRetreatFromAllParentsUpgradeMci = exports.bTestnet ? 909000 : Infinity;
exports.timestampUpgradeMci = exports.bTestnet ? 909000 : Infinity;
exports.aaStorageSizeUpgradeMci = exports.bTestnet ? 1024000 : Infinity;

if (process.env.devnet) {
	console.log('===== devnet');
	exports.bDevnet = true;
	exports.version = '2.0dev';
	exports.alt = '3';
	exports.supported_versions = ['1.0dev', '2.0dev'];
	exports.versionWithoutTimestamp = '1.0dev';
	exports.GENESIS_UNIT = 'pLzHaCisvxkfgwyBDzgvZzhPp37ZKnuMOxiI3QwXxqM=';
	exports.BLACKBYTES_ASSET = 'GRzA4D/ElsiwivoUrkCg36s+CoOr6rLsSH2F0EOes64=';

	exports.COUNT_WITNESSES = 1;
	exports.MAJORITY_OF_WITNESSES = (exports.COUNT_WITNESSES%2===0) ? (exports.COUNT_WITNESSES/2+1) : Math.ceil(exports.COUNT_WITNESSES/2);

	exports.lastBallStableInParentsUpgradeMci = 0;
	exports.witnessedLevelMustNotRetreatUpgradeMci = 0;
	exports.spendUnconfirmedUpgradeMci = 0;
	exports.branchedMinMcWlUpgradeMci = 0;
	exports.otherAddressInDefinitionUpgradeMci = 0;
	exports.attestedInDefinitionUpgradeMci = 0;
	exports.altBranchByBestParentUpgradeMci = 0;
	exports.anyDefinitionChangeUpgradeMci = 0;
	exports.formulaUpgradeMci = 0;
	exports.witnessedLevelMustNotRetreatFromAllParentsUpgradeMci = 0;
	exports.timestampUpgradeMci = 0;
	exports.aaStorageSizeUpgradeMci = 0;
}
<commit_msg>delay aaStorageSizeUpgradeMci<commit_after>/*jslint node: true */
"use strict";

if (typeof process === 'object' && typeof process.versions === 'object' && typeof process.versions.node !== 'undefined') { // desktop
	var desktopApp = require('./desktop_app.js');
	var appRootDir = desktopApp.getAppRootDir();
	require('dotenv').config({path: appRootDir + '/.env'});
}

exports.COUNT_WITNESSES = 12;
exports.MAX_WITNESS_LIST_MUTATIONS = 1;
exports.TOTAL_WHITEBYTES = 1e15;
exports.MAJORITY_OF_WITNESSES = (exports.COUNT_WITNESSES%2===0) ? (exports.COUNT_WITNESSES/2+1) : Math.ceil(exports.COUNT_WITNESSES/2);
exports.COUNT_MC_BALLS_FOR_PAID_WITNESSING = 100;

exports.bTestnet = !!process.env.testnet;
console.log('===== testnet = ' + exports.bTestnet);

exports.version = exports.bTestnet ? '2.0t' : '2.0';
exports.alt = exports.bTestnet ? '2' : '1';

exports.supported_versions = exports.bTestnet ? ['1.0t', '2.0t'] : ['1.0', '2.0'];
exports.versionWithoutTimestamp = exports.bTestnet ? '1.0t' : '1.0';

//exports.bTestnet = (exports.alt === '2' && exports.version === '1.0t');

exports.GENESIS_UNIT = exports.bTestnet ? 'TvqutGPz3T4Cs6oiChxFlclY92M2MvCvfXR5/FETato=' : 'oj8yEksX9Ubq7lLc+p6F2uyHUuynugeVq4+ikT67X6E=';
exports.BLACKBYTES_ASSET = exports.bTestnet ? 'LUQu5ik4WLfCrr8OwXezqBa+i3IlZLqxj2itQZQm8WY=' : 'qO2JsiuDMh/j+pqJYZw3u82O71WjCDf0vTNvsnntr8o=';

exports.HASH_LENGTH = 44;
exports.PUBKEY_LENGTH = 44;
exports.SIG_LENGTH = 88;

// anti-spam limits
exports.MAX_AUTHORS_PER_UNIT = 16;
exports.MAX_PARENTS_PER_UNIT = 16;
exports.MAX_MESSAGES_PER_UNIT = 128;
exports.MAX_SPEND_PROOFS_PER_MESSAGE = 128;
exports.MAX_INPUTS_PER_PAYMENT_MESSAGE = 128;
exports.MAX_OUTPUTS_PER_PAYMENT_MESSAGE = 128;
exports.MAX_CHOICES_PER_POLL = 128;
exports.MAX_CHOICE_LENGTH = 64;
exports.MAX_DENOMINATIONS_PER_ASSET_DEFINITION = 64;
exports.MAX_ATTESTORS_PER_ASSET = 64;
exports.MAX_DATA_FEED_NAME_LENGTH = 64;
exports.MAX_DATA_FEED_VALUE_LENGTH = 64;
exports.MAX_AUTHENTIFIER_LENGTH = 4096;
exports.MAX_CAP = 9e15;
exports.MAX_COMPLEXITY = 100;
exports.MAX_UNIT_LENGTH = 5e6;

exports.MAX_PROFILE_FIELD_LENGTH = 50;
exports.MAX_PROFILE_VALUE_LENGTH = 100;

exports.MAX_AA_STRING_LENGTH = 4096;
exports.MAX_STATE_VAR_NAME_LENGTH = 128;
exports.MAX_STATE_VAR_VALUE_LENGTH = 1024;
exports.MAX_OPS = 2000;

exports.TEXTCOIN_CLAIM_FEE = 548;
exports.TEXTCOIN_ASSET_CLAIM_FEE = 750;
exports.TEXTCOIN_ASSET_CLAIM_HEADER_FEE = 391;
exports.TEXTCOIN_ASSET_CLAIM_MESSAGE_FEE = 209;
exports.TEXTCOIN_ASSET_CLAIM_BASE_MSG_FEE = 158;
exports.TEXTCOIN_PRIVATE_ASSET_CLAIM_MESSAGE_FEE = 99;
exports.MIN_BYTES_BOUNCE_FEE = 10000;

exports.minCoreVersion = exports.bTestnet ? '0.3.0' : '0.2.0';
exports.minCoreVersionForFullNodes = exports.bTestnet ? '0.3.0' : '0.2.94';

exports.lastBallStableInParentsUpgradeMci = 1300000;
exports.witnessedLevelMustNotRetreatUpgradeMci = exports.bTestnet ? 684000 : 1400000;
exports.spendUnconfirmedUpgradeMci = exports.bTestnet ? 589000 : 2909000;
exports.branchedMinMcWlUpgradeMci = exports.bTestnet ? 593000 : 2909000;
exports.otherAddressInDefinitionUpgradeMci = exports.bTestnet ? 602000 : 2909000;
exports.attestedInDefinitionUpgradeMci = exports.bTestnet ? 616000 : 2909000;
exports.altBranchByBestParentUpgradeMci = exports.bTestnet ? 642000 : 3009824;
exports.anyDefinitionChangeUpgradeMci = exports.bTestnet ? 855000 : 4229100;
exports.formulaUpgradeMci = exports.bTestnet ? 961000 : Infinity;
exports.witnessedLevelMustNotRetreatFromAllParentsUpgradeMci = exports.bTestnet ? 909000 : Infinity;
exports.timestampUpgradeMci = exports.bTestnet ? 909000 : Infinity;
exports.aaStorageSizeUpgradeMci = exports.bTestnet ? 1034000 : Infinity;

if (process.env.devnet) {
	console.log('===== devnet');
	exports.bDevnet = true;
	exports.version = '2.0dev';
	exports.alt = '3';
	exports.supported_versions = ['1.0dev', '2.0dev'];
	exports.versionWithoutTimestamp = '1.0dev';
	exports.GENESIS_UNIT = 'pLzHaCisvxkfgwyBDzgvZzhPp37ZKnuMOxiI3QwXxqM=';
	exports.BLACKBYTES_ASSET = 'GRzA4D/ElsiwivoUrkCg36s+CoOr6rLsSH2F0EOes64=';

	exports.COUNT_WITNESSES = 1;
	exports.MAJORITY_OF_WITNESSES = (exports.COUNT_WITNESSES%2===0) ? (exports.COUNT_WITNESSES/2+1) : Math.ceil(exports.COUNT_WITNESSES/2);

	exports.lastBallStableInParentsUpgradeMci = 0;
	exports.witnessedLevelMustNotRetreatUpgradeMci = 0;
	exports.spendUnconfirmedUpgradeMci = 0;
	exports.branchedMinMcWlUpgradeMci = 0;
	exports.otherAddressInDefinitionUpgradeMci = 0;
	exports.attestedInDefinitionUpgradeMci = 0;
	exports.altBranchByBestParentUpgradeMci = 0;
	exports.anyDefinitionChangeUpgradeMci = 0;
	exports.formulaUpgradeMci = 0;
	exports.witnessedLevelMustNotRetreatFromAllParentsUpgradeMci = 0;
	exports.timestampUpgradeMci = 0;
	exports.aaStorageSizeUpgradeMci = 0;
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
// The TutTB_Search() function will perform a Google search for us. The two
// parameters that get passed in are the event that triggered this function
// call, and the type of search to perform.
////////////////////////////////////////////////////////////////////////////////
function TutTB_Search(event, type)
{
    // This variable will hold the URL we will browse to
    var URL = "";

    // This variable will tell us whether our search box is empty or not
    var isEmpty = false;

    // Get a handle to our search terms box (the <menulist> element)
    var searchTermsBox = document.getElementById("TutTB-SearchTerms");

    // Get the value in the search terms box, trimming whitespace as necessary
    // See the TutTB_TrimString() function farther down in this file for details
    // on how it works.
    var searchTerms = TutTB_TrimString(searchTermsBox.value);

    if(searchTerms.length == 0) // Is the search terms box empty?
        isEmpty = true;         // If so, set the isEmpty flag to true
    else                        // If not, convert the terms to a URL-safe string
        searchTerms = TutTB_ConvertTermsToURI(searchTerms);

    // Now switch on whatever the incoming type value is
    // If the search box is empty, we simply redirect the user to the appropriate
    // place at the Google website. Otherwise, we search for whatever they entered.

    switch(type)
    {
    // Build up the URL for an image search
    case "aya":
        if(isEmpty) { URL = "http://alfanous.sourceforge.com/"; }
        else        { URL = "http://alfanous.sourceforge.com/index.php?query=" + searchTerms; }
        break;

    }

    // Load the URL in the browser window using the TutTB_LoadURL function
    TutTB_LoadURL(URL);
}

////////////////////////////////////////////////////////////////////////////////
// The TutTB_TrimString() function will trim all leading and trailing whitespace
// from the incoming string, and convert all runs of more than one whitespace
// character into a single space. The altered string gets returned.
////////////////////////////////////////////////////////////////////////////////
function TutTB_TrimString(string)
{
    // If the incoming string is invalid, or nothing was passed in, return empty
    if (!string)
        return "";

    string = string.replace(/^\s+/, ''); // Remove leading whitespace
    string = string.replace(/\s+$/, ''); // Remove trailing whitespace

    // Replace all whitespace runs with a single space
    string = string.replace(/\s+/g, ' ');

    return string; // Return the altered value
}

////////////////////////////////////////////////////////////////////////////////
// The TutTB_ConvertTermsToURI() function converts an incoming string of search
// terms to a safe value for passing into a URL.
////////////////////////////////////////////////////////////////////////////////
function TutTB_ConvertTermsToURI(terms)
{
    // Create an array to hold each search term
    var termArray = new Array();

    // Split up the search term string based on the space character
    termArray = terms.split(" ");

    // Create a variable to hold our resulting URI-safe value
    var result = "";

    // Loop through the search terms
    for(var i=0; i<termArray.length; i++)
    {
        // All search terms (after the first one) are to be separated with a '+'
        if(i > 0)
            result += "+";

        // Encode each search term, using the built-in Firefox function
        // encodeURIComponent().
        result += encodeURIComponent(termArray[i]);
    }

    return result; // Return the result
}

////////////////////////////////////////////////////////////////////////////////
// The TutTB_LoadURL() function loads the specified URL in the browser.
////////////////////////////////////////////////////////////////////////////////
function TutTB_LoadURL(url)
{
    // Set the browser window's location to the incoming URL
    window._content.document.location = url;

    // Make sure that we get the focus
    window.content.focus();
}

////////////////////////////////////////////////////////////////////////////////
// The TutTB_KeyHandler() function checks to see if the key that was pressed
// is the [Enter] key. If it is, a web search is performed.
////////////////////////////////////////////////////////////////////////////////
function TutTB_KeyHandler(event)
{
    // Was the key that was pressed [ENTER]? If so, perform a web search.
    if(event.keyCode == event.DOM_VK_RETURN)
        TutTB_Search(event, 'aya');
}

////////////////////////////////////////////////////////////////////////////////
// The TutTB_Populate() function places dynamically generated menu items inside
// our toolbar's search box drop-down menu. Although this sample isn't very
// practical, it is provided as an example of how dynamic menu population works.
////////////////////////////////////////////////////////////////////////////////
function TutTB_Populate()
{
    // Get the menupopup element that we will be working with
    var menu = document.getElementById("TutTB-SearchTermsMenu");

    // Remove all of the items currently in the popup menu
    for(var i=menu.childNodes.length - 1; i >= 0; i--)
    {
        menu.removeChild(menu.childNodes.item(i));
    }

    // Specify how many items we should add to the menu
    var numItemsToAdd = 10;

    tempItem.setAttribute("label", "الحمد لله رب العالمين");
    for(var i=0; i<numItemsToAdd; i++)
    {
        // Create a new menu item to be added
        var tempItem = document.createElement("menuitem");

        // Set the new menu item's label
        //tempItem.setAttribute("label", "Dynamic Item Number " + (i+1));

        // Add the item to our menu
        menu.appendChild(tempItem);
    }
}
<commit_msg>Update interfaces/toolbars/firefox/chrome/content/alfanoustoolbar.js<commit_after>/*
    alfanoustoolbar.js file
	created on Sunday, August 05th, 2012 at 13:00
	by SMAHI Zakaria
	zakaria08esi@gmail.com
*/

	function AlfanousTB_Search(event, type)
	{

		/*
			AlfanousTB_Search function
			This function performs a search in alfanous
			if the SearchBox is empty it loads the alfanous default URL (HomePage)
		*/

		var URL = ""; // using this variable to holding on the URL

		var isEmpty = false; // is the SearchBox Empty or not? initially is false we suppose that the user will search for a word

		// Get a handle to our search terms box (the <menulist> element)

		var searchTermsBox = document.getElementById("AlfanousTB-SearchTerms");

		// Get the value in the search terms box, trimming whitespace as necessary using the AlfanousTB_TrimString() function
		// See farther down in this file for details on how it works.

		var searchTerms = AlfanousTB_TrimString(searchTermsBox.value);

		if(searchTerms.length == 0) // Is the search terms box empty?
		isEmpty = true;             // If so, set the isEmpty flag to true
		else                        // If not, convert the terms to a URL-safe string
		searchTerms = AlfanousTB_ConvertTermsToURI(searchTerms);

		// Now switch on whatever the incoming type value is
		// If the search box is empty, we simply redirect the user to alfanous homepage
		// if not perform a full search.

		switch(type)
		{

			// Build up the URL
			case "word":
			if(isEmpty) { URL = "http://alfanous.org/"; }
			else        { URL = "http://alfanous.org/?search=" + searchTerms; }
			break;

		}

		// Load the URL in the browser window using the TutTB_LoadURL function
		AlfanousTB_LoadURL(URL);

	}

	function AlfanousTB_TrimString(string)
	{

		/*
			AlfanousTB_TrimString function
			This function trims all leading and trailing whitespace from the incoming string and convert them into one
			whitespace; the new string is returned
		*/

		// If the incoming string is invalid, or nothing was passed in, return empty
		if (!string)
		return "";

		string = string.replace(/^\s+/, ''); // Remove leading whitespace
		string = string.replace(/\s+$/, ''); // Remove trailing whitespace

		// Replace all whitespace runs with a single space
		string = string.replace(/\s+/g, ' ');

		return string; // Return the altered value

	}

	function AlfanousTB_ConvertTermsToURI(terms)
	{

		/*
			AlfanousTB_ConvertTermsToURI
			This function converts an incoming string of search terms
			to a safe value for passing into a URL
		*/

		// Create an array to hold each search term
		var termArray = new Array();

		// Split up the search term string based on the space character
		termArray = terms.split(" ");

		// Create a variable to hold our resulting URI-safe value
		var result = "";

		// Loop through the search terms
		for(var i=0; i<termArray.length; i++)
		{

			// All search terms (after the first one) are to be separated with a '+'
			if(i > 0)
			result += "+";

			// Encode each search term, using the built-in Firefox function
			// encodeURIComponent().
			result += encodeURIComponent(termArray[i]);
		}

		return result; // Return the result

	}

	function AlfanousTB_LoadURL(url)
	{

		/*
			AlfanousTB_LoadURL
			This function loads the specified URL in the browser
		*/
var win = Components.classes['@mozilla.org/appshell/window-mediator;1'].getService(Components.interfaces.nsIWindowMediator).getMostRecentWindow('navigator:browser');
win.openUILinkIn(url, 'current');
	}

	function AlfanousTB_KeyHandler(event)
	{

		/*
			AlfanousTB_KeyHandler
			This function checks if the [enter] button was pressed
			if yes; it loads the AlfanousTB_Search function and as parameters the text in SearchBox
		*/

		// Was the key that was pressed [ENTER]? If so, perform a web search.
		if(event.keyCode == event.DOM_VK_RETURN)
		AlfanousTB_Search(event, 'word');

	}

	function AlfanousTB_Populate()
	{

		/*
			AlfanousTB_Populate
			This function generates automatically menu item inside the SearchBox drop-down menu
			As a historic searchs; te number of Items to Add is 10
		*/

		// Get the menupopup element that we will be working with
		var menu = document.getElementById("AlfanousTB-SearchTermsMenu");

		// Remove all of the items currently in the popup menu
		for(var i=menu.childNodes.length - 1; i >= 0; i--)
		{
			menu.removeChild(menu.childNodes.item(i));
		}

		// Specify how many items we should add to the menu
		var numItemsToAdd = 10;

		tempItem.setAttribute("label", "الحمد لله رب العالمين");
		for(var i=0; i<numItemsToAdd; i++)
		{
			// Create a new menu item to be added
			var tempItem = document.createElement("menuitem");

			// Set the new menu item's label
			//tempItem.setAttribute("label", "Dynamic Item Number " + (i+1));

			// Add the item to our menu
			menu.appendChild(tempItem);
		}

	}

<|endoftext|>


<commit_before>'use strict';

module.exports = TileContainer;

function TileContainer(data) {
    let tileForm = 'square'; //square, hexagonal, triangular
    let stackElementRadius = 5;

    this.setTileForm = function(value) {
        tileForm = value;
    };

    this.setStackElementRadius = function(value) {
        stackElementRadius = value;
    };

    this.transformToFrontend = function(slotIndex) {
        return {
            tileForm: tileForm,
            stackElementRadius: stackElementRadius
        }
    };

    this.setTileForm(data.tileForm);
    this.setStackElementRadius(data.stackElementRadius);
}<commit_msg>tileContainer_v1: added height and spacing for better placement of the contained tiles<commit_after>'use strict';

module.exports = TileContainer;

function TileContainer(data) {
    let tileForm = 'square'; //square, hexagonal, triangular
    let stackElementRadius = 5;
    let stackElementHeight = 0.2;
    let stackElementSpacing = 0.2;

    this.setTileForm = function(value) {
        tileForm = value;
    };

    this.setStackElementRadius = function(value) {
        stackElementRadius = value;
    };

    this.setStackElementHeight = function(value) {
        stackElementHeight = value;
    };

    this.setStackElementSpacing = function(value) {
        stackElementSpacing = value;
    };

    this.transformToFrontend = function(slotIndex) {
        return {
            tileForm: tileForm,
            stackElementRadius: stackElementRadius,
            stackElementHeight: stackElementHeight,
            stackElementSpacing: stackElementSpacing
        }
    };

    this.setTileForm(data.tileForm);
    this.setStackElementRadius(data.stackElementRadius);
    this.setStackElementHeight(data.stackElementHeight);
    this.setStackElementSpacing(data.stackElementSpacing);
}<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 airbug inc. http://airbug.com
 *
 * bugpack may be freely distributed under the MIT license.
 */

//-------------------------------------------------------------------------------
// Requires
//-------------------------------------------------------------------------------

var buildbug            = require("buildbug");

//-------------------------------------------------------------------------------
// Simplify References
//-------------------------------------------------------------------------------

var buildProject        = buildbug.buildProject;
var buildProperties     = buildbug.buildProperties;
var buildScript         = buildbug.buildScript;
var buildTarget         = buildbug.buildTarget;
var enableModule        = buildbug.enableModule;
var parallel            = buildbug.parallel;
var series              = buildbug.series;
var targetTask          = buildbug.targetTask;

//-------------------------------------------------------------------------------
// Enable Modules
//-------------------------------------------------------------------------------

var aws                 = enableModule("aws");
var bugpack             = enableModule('bugpack');
var bugunit             = enableModule('bugunit');
var core                = enableModule('core');
var lintbug             = enableModule("lintbug");
var nodejs              = enableModule('nodejs');
var uglifyjs            = enableModule("uglifyjs");

//-------------------------------------------------------------------------------
// Values
//-------------------------------------------------------------------------------

var name                = "bugpack";
var version             = "0.2.1";

//-------------------------------------------------------------------------------
// Declare Properties
//-------------------------------------------------------------------------------

buildProperties({
    name: name,
    version: version
});

buildProperties({
    node: {
        packageJson: {
            name: "{{name}}",
            version: "{{version}}",
            description: "Package manager and loader to help make browser and node js package loading consistent and easier",
            main: "./lib/BugPackApi.js",
            author: "Brian Neisler <brian@airbug.com>",
            repository: {
                type: "git",
                url: "https://github.com/airbug/bugpack.git"
            },
            bugs: {
                url: "https://github.com/airbug/bugpack/issues"
            },
            licenses: [
                {
                    type : "MIT",
                    url : "https://raw.githubusercontent.com/airbug/bugpack/master/LICENSE"
                }
            ]
        },
        sourcePaths: [
            "./libraries/bugpack/js/src",
            "./projects/bugpack-node/js/src"
        ],
        readmePath: "./README.md"
    },
    web: {
        name: "{{name}}",
        version: "{{version}}",
        sourcePaths: [
            "./projects/bugpack-client/js/src/SimpleRequire.js",
            "./libraries/bugpack/js/src/BugPackFix.js",
            "./libraries/bugpack/js/src/BugPackKey.js",
            "./libraries/bugpack/js/src/BugPackPackage.js",
            "./libraries/bugpack/js/src/BugPackLibrary.js",
            "./projects/bugpack-client/js/src/BugPackSource.js",
            "./libraries/bugpack/js/src/BugPackSourceProcessor.js",
            "./projects/bugpack-client/js/src/BugPackRegistryEntry.js",
            "./projects/bugpack-client/js/src/BugPackRegistry.js",
            "./projects/bugpack-client/js/src/BugPackRegistryFile.js",
            "./projects/bugpack-client/js/src/BugPackContext.js",
            "./projects/bugpack-client/js/src/BugPackApi.js"
        ],
        outputFile: "{{distPath}}/{{web.name}}-{{web.version}}.js",
        outputMinFile: "{{distPath}}/{{web.name}}-{{web.version}}.min.js"
    },
    lint: {
        targetPaths: [
            "."
        ],
        ignorePatterns: [
            ".*\\.buildbug$",
            ".*\\.bugunit$",
            ".*\\.git$",
            ".*node_modules$"
        ]
    }
});

//-------------------------------------------------------------------------------
// BuildTargets
//-------------------------------------------------------------------------------

// Clean BuildTarget
//-------------------------------------------------------------------------------

buildTarget("clean").buildFlow(
    targetTask("clean")
);

// Local BuildTarget
//-------------------------------------------------------------------------------

buildTarget("local").buildFlow(

    series([
        targetTask("clean"),
        targetTask('lint', {
            properties: {
                targetPaths: buildProject.getProperty("lint.targetPaths"),
                ignores: buildProject.getProperty("lint.ignorePatterns"),
                lintTasks: [
                    "cleanupExtraSpacingAtEndOfLines",
                    "ensureNewLineEnding",
                    "indentEqualSignsForPreClassVars",
                    "orderBugpackRequires",
                    "orderRequireAnnotations",
                    "updateCopyright"
                ]
            }
        }),
        parallel([
            series([
                targetTask("createNodePackage", {
                    properties: {
                        packageJson: buildProject.getProperty("node.packageJson"),
                        packagePaths: {
                            "./": [buildProject.getProperty("node.readmePath")],
                            "./lib": buildProject.getProperty("node.sourcePaths")
                        }
                    }
                }),
                targetTask("packNodePackage", {
                    properties: {
                        packageName: "{{node.packageJson.name}}",
                        packageVersion: "{{node.packageJson.version}}"
                    }
                }),
                targetTask("s3PutFile", {
                    init: function(task, buildProject, properties) {
                        var packedNodePackage = nodejs.findPackedNodePackage(buildProject.getProperty("node.packageJson.name"),
                            buildProject.getProperty("node.packageJson.version"));
                        task.updateProperties({
                            file: packedNodePackage.getFilePath(),
                            options: {
                                acl: 'public-read',
                                encrypt: true
                            }
                        });
                    },
                    properties: {
                        bucket: "{{local-bucket}}"
                    }
                })
            ]),
            series([
                targetTask("concat", {
                    properties: {
                        sources: buildProject.getProperty("web.sourcePaths"),
                        outputFile: "{{web.outputFile}}"
                    }
                }),
                parallel([
                    targetTask("s3PutFile", {
                        properties: {
                            file:  "{{web.outputFile}}",
                            options: {
                                acl: 'public-read',
                                gzip: true
                            },
                            bucket: "{{local-bucket}}"
                        }
                    }),
                    series([
                        targetTask("uglifyjsMinify", {
                            properties: {
                                sources: ["{{web.outputFile}}"],
                                outputFile: "{{web.outputMinFile}}"
                            }
                        }),
                        targetTask("s3PutFile", {
                            properties: {
                                file:  "{{web.outputMinFile}}",
                                options: {
                                    acl: 'public-read',
                                    gzip: true
                                },
                                bucket: "{{local-bucket}}"
                            }
                        })
                    ])
                ])
            ])
        ])
    ])
).makeDefault();

// Prod BuildTarget
//-------------------------------------------------------------------------------

buildTarget("prod").buildFlow(
    series([
        targetTask("clean"),
        targetTask('lint', {
            properties: {
                targetPaths: buildProject.getProperty("lint.targetPaths"),
                ignores: buildProject.getProperty("lint.ignorePatterns"),
                lintTasks: [
                    "cleanupExtraSpacingAtEndOfLines",
                    "ensureNewLineEnding",
                    "indentEqualSignsForPreClassVars",
                    "orderBugpackRequires",
                    "orderRequireAnnotations",
                    "updateCopyright"
                ]
            }
        }),
        parallel([
            series([
                targetTask("createNodePackage", {
                    properties: {
                        packageJson: buildProject.getProperty("node.packageJson"),
                        packagePaths: {
                            "./": [buildProject.getProperty("node.readmePath")],
                            "./lib": buildProject.getProperty("node.sourcePaths")
                        }
                    }
                }),
                targetTask("packNodePackage", {
                    properties: {
                        packageName: "{{node.packageJson.name}}",
                        packageVersion: "{{node.packageJson.version}}"
                    }
                }),
                targetTask("s3PutFile", {
                    init: function(task, buildProject, properties) {
                        var packedNodePackage = nodejs.findPackedNodePackage(buildProject.getProperty("node.packageJson.name"),
                            buildProject.getProperty("node.packageJson.version"));
                        task.updateProperties({
                            file: packedNodePackage.getFilePath(),
                            options: {
                                acl: 'public-read',
                                encrypt: true
                            }
                        });
                    },
                    properties: {
                        bucket: "{{public-bucket}}"
                    }
                }),
                targetTask('npmConfigSet', {
                    properties: {
                        config: buildProject.getProperty("npmConfig")
                    }
                }),
                targetTask('npmAddUser'),
                targetTask('publishNodePackage', {
                    properties: {
                        packageName: "{{node.packageJson.name}}",
                        packageVersion: "{{node.packageJson.version}}"
                    }
                })
            ]),
            series([
                targetTask("concat", {
                    properties: {
                        sources: buildProject.getProperty("web.sourcePaths"),
                        outputFile: "{{web.outputFile}}"
                    }
                }),
                parallel([
                    targetTask("s3PutFile", {
                        properties: {
                            file:  "{{web.outputFile}}",
                            options: {
                                acl: 'public-read',
                                gzip: true,
                                cacheControl: "max-age=31536000, public"
                            },
                            bucket: "{{public-bucket}}"
                        }
                    }),
                    series([
                        targetTask("uglifyjsMinify", {
                            properties: {
                                sources: ["{{web.outputFile}}"],
                                outputFile: "{{web.outputMinFile}}"
                            }
                        }),
                        targetTask("s3PutFile", {
                            properties: {
                                file:  "{{web.outputMinFile}}",
                                options: {
                                    acl: 'public-read',
                                    gzip: true,
                                    cacheControl: "max-age=31536000, public"
                                },
                                bucket: "{{public-bucket}}"
                            }
                        })
                    ])
                ])
            ])
        ])
    ])
);

//-------------------------------------------------------------------------------
// Build Scripts
//-------------------------------------------------------------------------------

buildScript({
    dependencies: [
        "bugcore",
        "bugflow",
        "bugfs"
    ],
    script: "./lintbug.js"
});
<commit_msg>Fix buildbug script for bugpack<commit_after>/*
 * Copyright (c) 2014 airbug inc. http://airbug.com
 *
 * bugpack may be freely distributed under the MIT license.
 */

//-------------------------------------------------------------------------------
// Requires
//-------------------------------------------------------------------------------

var buildbug            = require("buildbug");

//-------------------------------------------------------------------------------
// Simplify References
//-------------------------------------------------------------------------------

var buildProject        = buildbug.buildProject;
var buildProperties     = buildbug.buildProperties;
var buildScript         = buildbug.buildScript;
var buildTarget         = buildbug.buildTarget;
var enableModule        = buildbug.enableModule;
var parallel            = buildbug.parallel;
var series              = buildbug.series;
var targetTask          = buildbug.targetTask;

//-------------------------------------------------------------------------------
// Enable Modules
//-------------------------------------------------------------------------------

var aws                 = enableModule("aws");
var bugpack             = enableModule('bugpack');
var bugunit             = enableModule('bugunit');
var core                = enableModule('core');
var lintbug             = enableModule("lintbug");
var nodejs              = enableModule('nodejs');
var uglifyjs            = enableModule("uglifyjs");

//-------------------------------------------------------------------------------
// Values
//-------------------------------------------------------------------------------

var name                = "bugpack";
var version             = "0.2.1";

//-------------------------------------------------------------------------------
// Declare Properties
//-------------------------------------------------------------------------------

buildProperties({
    name: name,
    version: version
});

buildProperties({
    node: {
        packageJson: {
            name: "{{name}}",
            version: "{{version}}",
            description: "Package manager and loader to help make browser and node js package loading consistent and easier",
            main: "./lib/BugPackApi.js",
            author: "Brian Neisler <brian@airbug.com>",
            repository: {
                type: "git",
                url: "https://github.com/airbug/bugpack.git"
            },
            bugs: {
                url: "https://github.com/airbug/bugpack/issues"
            },
            licenses: [
                {
                    type : "MIT",
                    url : "https://raw.githubusercontent.com/airbug/bugpack/master/LICENSE"
                }
            ]
        },
        sourcePaths: [
            "./libraries/bugpack/js/src",
            "./projects/bugpack-node/js/src"
        ],
        readmePath: "./README.md"
    },
    web: {
        name: "{{name}}",
        version: "{{version}}",
        sourcePaths: [
            "./projects/bugpack-client/js/src/SimpleRequire.js",
            "./libraries/bugpack/js/src/BugPackFix.js",
            "./libraries/bugpack/js/src/BugPackKey.js",
            "./libraries/bugpack/js/src/BugPackPackage.js",
            "./libraries/bugpack/js/src/BugPackLibrary.js",
            "./projects/bugpack-client/js/src/BugPackSource.js",
            "./libraries/bugpack/js/src/BugPackSourceProcessor.js",
            "./projects/bugpack-client/js/src/BugPackRegistryEntry.js",
            "./projects/bugpack-client/js/src/BugPackRegistry.js",
            "./projects/bugpack-client/js/src/BugPackRegistryFile.js",
            "./projects/bugpack-client/js/src/BugPackContext.js",
            "./projects/bugpack-client/js/src/BugPackApi.js"
        ],
        outputFile: "{{distPath}}/{{web.name}}-{{web.version}}.js",
        outputMinFile: "{{distPath}}/{{web.name}}-{{web.version}}.min.js"
    },
    lint: {
        targetPaths: [
            "."
        ],
        ignorePatterns: [
            ".*\\.buildbug$",
            ".*\\.bugunit$",
            ".*\\.git$",
            ".*node_modules$"
        ]
    }
});

//-------------------------------------------------------------------------------
// BuildTargets
//-------------------------------------------------------------------------------

// Clean BuildTarget
//-------------------------------------------------------------------------------

buildTarget("clean").buildFlow(
    targetTask("clean")
);

// Local BuildTarget
//-------------------------------------------------------------------------------

buildTarget("local").buildFlow(

    series([
        targetTask("clean"),
        targetTask('lint', {
            properties: {
                targetPaths: buildProject.getProperty("lint.targetPaths"),
                ignores: buildProject.getProperty("lint.ignorePatterns"),
                lintTasks: [
                    "cleanupExtraSpacingAtEndOfLines",
                    "ensureNewLineEnding",
                    "indentEqualSignsForPreClassVars",
                    "orderBugpackRequires",
                    "orderRequireAnnotations",
                    "updateCopyright"
                ]
            }
        }),
        parallel([
            series([
                targetTask("createNodePackage", {
                    properties: {
                        packageJson: buildProject.getProperty("node.packageJson"),
                        packagePaths: {
                            "./": [buildProject.getProperty("node.readmePath")],
                            "./lib": buildProject.getProperty("node.sourcePaths")
                        }
                    }
                }),
                targetTask("packNodePackage", {
                    properties: {
                        packageName: "{{node.packageJson.name}}",
                        packageVersion: "{{node.packageJson.version}}"
                    }
                }),
                targetTask("s3PutFile", {
                    init: function(task, buildProject, properties) {
                        var packedNodePackage = nodejs.findPackedNodePackage(buildProject.getProperty("node.packageJson.name"),
                            buildProject.getProperty("node.packageJson.version"));
                        task.updateProperties({
                            file: packedNodePackage.getFilePath(),
                            options: {
                                acl: 'public-read',
                                encrypt: true
                            }
                        });
                    },
                    properties: {
                        bucket: "{{local-bucket}}"
                    }
                })
            ]),
            series([
                targetTask("concat", {
                    properties: {
                        sources: buildProject.getProperty("web.sourcePaths"),
                        outputFile: "{{web.outputFile}}"
                    }
                }),
                parallel([
                    targetTask("s3PutFile", {
                        properties: {
                            file:  "{{web.outputFile}}",
                            options: {
                                acl: 'public-read',
                                gzip: true
                            },
                            bucket: "{{local-bucket}}"
                        }
                    }),
                    series([
                        targetTask("uglifyjsMinify", {
                            properties: {
                                sources: ["{{web.outputFile}}"],
                                outputFile: "{{web.outputMinFile}}"
                            }
                        }),
                        targetTask("s3PutFile", {
                            properties: {
                                file:  "{{web.outputMinFile}}",
                                options: {
                                    acl: 'public-read',
                                    gzip: true
                                },
                                bucket: "{{local-bucket}}"
                            }
                        })
                    ])
                ])
            ])
        ])
    ])
).makeDefault();

// Prod BuildTarget
//-------------------------------------------------------------------------------

buildTarget("prod").buildFlow(
    series([
        targetTask("clean"),
        targetTask('lint', {
            properties: {
                targetPaths: buildProject.getProperty("lint.targetPaths"),
                ignores: buildProject.getProperty("lint.ignorePatterns"),
                lintTasks: [
                    "cleanupExtraSpacingAtEndOfLines",
                    "ensureNewLineEnding",
                    "indentEqualSignsForPreClassVars",
                    "orderBugpackRequires",
                    "orderRequireAnnotations",
                    "updateCopyright"
                ]
            }
        }),
        parallel([
            series([
                targetTask("createNodePackage", {
                    properties: {
                        packageJson: buildProject.getProperty("node.packageJson"),
                        packagePaths: {
                            "./": [buildProject.getProperty("node.readmePath")],
                            "./lib": buildProject.getProperty("node.sourcePaths")
                        }
                    }
                }),
                targetTask("packNodePackage", {
                    properties: {
                        packageName: "{{node.packageJson.name}}",
                        packageVersion: "{{node.packageJson.version}}"
                    }
                }),
                targetTask("s3PutFile", {
                    init: function(task, buildProject, properties) {
                        var packedNodePackage = nodejs.findPackedNodePackage(buildProject.getProperty("node.packageJson.name"),
                            buildProject.getProperty("node.packageJson.version"));
                        task.updateProperties({
                            file: packedNodePackage.getFilePath(),
                            options: {
                                acl: 'public-read',
                                encrypt: true
                            }
                        });
                    },
                    properties: {
                        bucket: "{{public-bucket}}"
                    }
                }),
                targetTask('publishNodePackage', {
                    properties: {
                        packageName: "{{node.packageJson.name}}",
                        packageVersion: "{{node.packageJson.version}}"
                    }
                })
            ]),
            series([
                targetTask("concat", {
                    properties: {
                        sources: buildProject.getProperty("web.sourcePaths"),
                        outputFile: "{{web.outputFile}}"
                    }
                }),
                parallel([
                    targetTask("s3PutFile", {
                        properties: {
                            file:  "{{web.outputFile}}",
                            options: {
                                acl: 'public-read',
                                gzip: true,
                                cacheControl: "max-age=31536000, public"
                            },
                            bucket: "{{public-bucket}}"
                        }
                    }),
                    series([
                        targetTask("uglifyjsMinify", {
                            properties: {
                                sources: ["{{web.outputFile}}"],
                                outputFile: "{{web.outputMinFile}}"
                            }
                        }),
                        targetTask("s3PutFile", {
                            properties: {
                                file:  "{{web.outputMinFile}}",
                                options: {
                                    acl: 'public-read',
                                    gzip: true,
                                    cacheControl: "max-age=31536000, public"
                                },
                                bucket: "{{public-bucket}}"
                            }
                        })
                    ])
                ])
            ])
        ])
    ])
);

//-------------------------------------------------------------------------------
// Build Scripts
//-------------------------------------------------------------------------------

buildScript({
    dependencies: [
        "bugcore",
        "bugflow",
        "bugfs"
    ],
    script: "./lintbug.js"
});
<|endoftext|>


<commit_before>// ==UserScript==
// @name         autoscroll
// @namespace    autoscroll
// @version      1.16
// @description  autoscroller to be used with https://facebook.tracking.exposed, This userscript works with TamperMoneky extension.
// @author       Claudio Agosti @_vecna
// @match        https://www.facebook.com/*
// @connect      autoscroll
// @grant        GM_setValue
// @grant        GM_getValue
// @require      https://cdnjs.cloudflare.com/ajax/libs/lodash-compat/3.10.2/lodash.min.js
// @require      https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js
// ==/UserScript==

var SCROLL_TIMES = 30;
var AWAITSECS = 5;
var fixedH = 800;

var plan = [
    "08:01",
    "16:01",
    "23:55"
];

function timeline(reference) {

    if(!reference) {
        var s = GM_getValue("scrolling");

        if(s && moment(s).add(50, 's').isBefore(moment())) {
            console.log("a previous scroll interrupted?");
        }

        if(s && moment(s).add(50, 's').isAfter(moment())) {
            return;
        }

        console.log("setting GM_setValue 'scrolling'", moment().format() );
        GM_setValue("scrolling", moment().format());

        reference = {
            counter: 0,
            y: 0,
        };
    }

    if(reference.counter === SCROLL_TIMES) {
        var s = GM_getValue("scrolling");
        console.log("Timeline counter reach", SCROLL_TIMES);
        if(s) {
            console.log(s, "'scrolling': is present, -> doTheNext, removing GM_[scrolling]", s);
            GM_setValue("scrolling", null);
            return _.delay(doTheNext, 1);
        } else {
            console.log("GM_[scrolling] is null", s, "killed ramification");
        }
    } else {
        reference.counter += 1;
        reference.y = reference.counter * fixedH;
        GM_setValue("scrolling", moment().format());

        console.log("scrolling", reference.counter, "at",
                  moment().format("HH:mm:ss"), "a the Y", reference.y);

        scrollTo(0, reference.y);

        return _.delay(timeline, AWAITSECS * 1000, reference);
    }
}

function doTheNext() {

    /* this is not anymore timezone robust, it is intended to be run in the right place */
    var next = null;
    _.each(plan, function(t) {

		var hour = _.parseInt(t.split(':')[0]);
		var minute = _.parseInt(t.split(':')[1]);

        var target = moment().startOf('day').add(hour, 'h').add(minute, 'm');

        if(!next && moment().isBefore( target ) ) {
            console.log("The next refresh will be at", t);
            next = moment.duration(target - moment()).asSeconds();
        }
    });

    if(!next) {
        console.log("strange condition before midnight, check in 1 hour");
        GM_setValue("refresh", true);
        return _.delay(doTheNext, 3600 * 1000);
    } else {
        console.log("Setting the next timeline in", next, "seconds");
        GM_setValue("refresh", true);
        return _.delay(cleanAndReload, next * 1000);
    }
};

function cleanAndReload() {
    GM_setValue("scrolling", null);
    // this value 'refresh' is not used because remain dirty in case a browser restart
    GM_setValue("refresh", null);
    location.reload();
};

(function() {

    var s = GM_getValue("scrolling");

    if( s && moment(s).add(50, 's').isBefore(moment())) {
        console.log("Considering the diff of",
                moment.duration(moment() - moment(s)).humanize(), "...");
        timeline();
    }
    else if(!s) {
        var r = GM_getValue("refresh");
        console.log("beginning tampermonkey, scrolling", s, "refresh", r);
        timeline();
    } else
        console.log("Nope, recorded is", moment(s).format("HH:mm:ss"), "now is:", moment().format("HH:mm:ss"));
})();
<commit_msg>version 1.17 autoscroll with 7 access per day<commit_after>// ==UserScript==
// @name         autoscroll
// @namespace    autoscroll
// @version      1.17
// @description  autoscroller to be used with https://facebook.tracking.exposed, This userscript works with TamperMoneky extension.
// @author       Claudio Agosti @_vecna
// @match        https://www.facebook.com/*
// @connect      autoscroll
// @grant        GM_setValue
// @grant        GM_getValue
// @require      https://cdnjs.cloudflare.com/ajax/libs/lodash-compat/3.10.2/lodash.min.js
// @require      https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js
// ==/UserScript==

var SCROLL_TIMES = 30;
var AWAITSECS = 5;
var fixedH = 800;

var plan = [
    "08:01",
    "10:01",
    "12:01",
    "14:01",
    "16:01",
    "18:01",
    "20:01"
];

function timeline(reference) {

    if(!reference) {
        var s = GM_getValue("scrolling");

        if(s && moment(s).add(50, 's').isBefore(moment())) {
            console.log("a previous scroll interrupted?");
        }

        if(s && moment(s).add(50, 's').isAfter(moment())) {
            return;
        }

        console.log("setting GM_setValue 'scrolling'", moment().format() );
        GM_setValue("scrolling", moment().format());

        reference = {
            counter: 0,
            y: 0,
        };
    }

    if(reference.counter === SCROLL_TIMES) {
        var s = GM_getValue("scrolling");
        console.log("Timeline counter reach", SCROLL_TIMES);
        if(s) {
            console.log(s, "'scrolling': is present, -> doTheNext, removing GM_[scrolling]", s);
            GM_setValue("scrolling", null);
            return _.delay(doTheNext, 1);
        } else {
            console.log("GM_[scrolling] is null", s, "killed ramification");
        }
    } else {
        reference.counter += 1;
        reference.y = reference.counter * fixedH;
        GM_setValue("scrolling", moment().format());

        console.log("scrolling", reference.counter, "at",
                  moment().format("HH:mm:ss"), "a the Y", reference.y);

        scrollTo(0, reference.y);

        return _.delay(timeline, AWAITSECS * 1000, reference);
    }
}

function doTheNext() {

    /* this is not anymore timezone robust, it is intended to be run in the right place */
    var next = null;
    _.each(plan, function(t) {

		var hour = _.parseInt(t.split(':')[0]);
		var minute = _.parseInt(t.split(':')[1]);

        var target = moment().startOf('day').add(hour, 'h').add(minute, 'm');

        if(!next && moment().isBefore( target ) ) {
            console.log("The next refresh will be at", t);
            next = moment.duration(target - moment()).asSeconds();
        }
    });

    if(!next) {
        console.log("strange condition before midnight, check in 1 hour");
        GM_setValue("refresh", true);
        return _.delay(doTheNext, 3600 * 1000);
    } else {
        console.log("Setting the next timeline in", next, "seconds");
        GM_setValue("refresh", true);
        return _.delay(cleanAndReload, next * 1000);
    }
};

function cleanAndReload() {
    GM_setValue("scrolling", null);
    // this value 'refresh' is not used because remain dirty in case a browser restart
    GM_setValue("refresh", null);
    location.reload();
};

(function() {

    var s = GM_getValue("scrolling");

    if( s && moment(s).add(50, 's').isBefore(moment())) {
        console.log("Considering the diff of",
                moment.duration(moment() - moment(s)).humanize(), "...");
        timeline();
    }
    else if(!s) {
        var r = GM_getValue("refresh");
        console.log("beginning tampermonkey, scrolling", s, "refresh", r);
        timeline();
    } else
        console.log("Nope, recorded is", moment(s).format("HH:mm:ss"), "now is:", moment().format("HH:mm:ss"));
})();
<|endoftext|>


<commit_before>// Write an HTTP server that receives only POST requests and converts incoming POST body characters
// to upper-case and returns it to the client.

// Your server should listen on the port provided by the first argument to your program.

'use strict';

var http = require('http');
var fs = require('fs');
var qs = require('querystring');

var port = process.argv[2];

var parseInput = function(input){
    var allContent = '';
    for (var key in input) {
        if (input.hasOwnProperty(key)) {
            allContent += key.toUpperCase();
            //value is input[key]
        }
    }
    return allContent;
};

var server = http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});

    if(req.method === 'POST'){
        req.on('data', function(chunk) {
            var formInput = qs.parse(chunk.toString());
            res.write(parseInput(formInput));
        });
    }

    req.on('end', function(){
        res.end();
    });
});
server.listen(port, '127.0.0.1');

console.log('Server running at http://127.0.0.1:/' + port);

//the form server is just there to help create the POSTS to be able to test the application
var helperFormPath = '12-program-helper-form.html';
var formServerPort = 9090;
if(port === formServerPort){
    formServerPort ++;
}

var formServer = http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    var stream = fs.createReadStream(helperFormPath);

    stream.on('data', function(chunk) {
        var replaceContentActionInForm = chunk.toString();
        replaceContentActionInForm = replaceContentActionInForm.replace('${actionPath}', 'http://127.0.0.1:' + port);
        res.write(replaceContentActionInForm);
    });

    stream.on('end', function(){
        res.end();
    });
});

formServer.listen(formServerPort, '127.0.0.1');
console.log('Form server running at http://127.0.0.1:/' + formServerPort);
<commit_msg>changed typo<commit_after>// Write an HTTP server that receives only POST requests and converts incoming POST body characters
// to upper-case and returns it to the client.

// Your server should listen on the port provided by the first argument to your program.

'use strict';

var http = require('http');
var fs = require('fs');
var qs = require('querystring');

var port = process.argv[2];

var parseInput = function(input){
    var allContent = '';
    for (var key in input) {
        if (input.hasOwnProperty(key)) {
            allContent += key.toUpperCase();
            //suppose you want the content? input[key].toUpperCase() + '\n'
        }
    }
    return allContent;
};

var server = http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});

    if(req.method === 'POST'){
        req.on('data', function(chunk) {
            var formInput = qs.parse(chunk.toString());
            res.write(parseInput(formInput));
        });
    }

    req.on('end', function(){
        res.end();
    });
});
server.listen(port, '127.0.0.1');

console.log('Server running at http://127.0.0.1:/' + port);

//the form server is just there to help create the POSTS to be able to test the application
var helperFormPath = '12-program-helper-form.html';
var formServerPort = 9090;
if(port === formServerPort){
    formServerPort ++;
}

var formServer = http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    var stream = fs.createReadStream(helperFormPath);

    stream.on('data', function(chunk) {
        var replaceContentActionInForm = chunk.toString();
        replaceContentActionInForm = replaceContentActionInForm.replace('${actionPath}', 'http://127.0.0.1:' + port);
        res.write(replaceContentActionInForm);
    });

    stream.on('end', function(){
        res.end();
    });
});

formServer.listen(formServerPort, '127.0.0.1');
console.log('Form server running at http://127.0.0.1:/' + formServerPort);
<|endoftext|>


<commit_before>/// <reference path="../../Core/Collections/DependencyObjectCollection.js"/>
/// CODE
/// <reference path="KeyFrame.js"/>
/// <reference path="Animation.js"/>

//#region KeyFrameCollection
var KeyFrameCollection = Nullstone.Create("KeyFrameCollection", DependencyObjectCollection);

KeyFrameCollection.Instance.Init = function () {
    this.Init$DependencyObjectCollection();
    this._Resolved = false;
    this._SortedList = [];
};

KeyFrameCollection.Instance.GetKeyFrameForTime = function (t, prevFrameRef) {
    /// <param name="t" type="TimeSpan"></param>
    /// <param name="prevFrameRef" type="Object"></param>
    var currentKeyFrame = null;
    var previousKeyFrame = null;
    var i;

    if (this._SortedList.length == 0) {
        prevFrameRef.Value = null;
        return null;
    }

    var keyFrame;
    var valuePropd;
    // Crawl forward to figure out what segment to use (this assumes the list is sorted)
    for (i = 0; i < this._SortedList.length; i++) {
        keyFrame = this._SortedList[i];
        var keyEndTime = keyFrame._ResolvedKeyTime;
        if (keyEndTime.CompareTo(t) >= 0 || (i + 1) >= this._SortedList.length)
            break;
    }

    // Crawl backward to find first non-null frame
    for (; i >= 0; i--) {
        keyFrame = this._SortedList[i];
        valuePropd = keyFrame.GetDependencyProperty("Value");
        if (keyFrame._GetValue(valuePropd) !== undefined) {
            currentKeyFrame = keyFrame;
            break;
        }
    }

    // Crawl backward some more to find first non-null prev frame
    for (i--; i >= 0; i--) {
        keyFrame = this._SortedList[i];
        valuePropd = keyFrame.GetDependencyProperty("Value");
        if (keyFrame._GetValue(valuePropd) !== undefined) {
            previousKeyFrame = keyFrame;
            break;
        }
    }

    prevFrameRef.Value = previousKeyFrame;
    return currentKeyFrame;
};

KeyFrameCollection.Instance.Clear = function () {
    this._Resolved = false;
    //Clear sorted
    this.Clear$DependencyObjectCollection();
};

KeyFrameCollection.Instance.AddedToCollection = function (value, error) {
    if (!this.AddedToCollection$DependencyObjectCollection(value, error))
        return false;
    this._Resolved = false;
    return true;
};
KeyFrameCollection.Instance.RemovedFromCollection = function (value, isValueSafe) {
    this.RemovedFromCollection$DependencyObjectCollection(value, isValueSafe);
    this._Resolved = false;
};

KeyFrameCollection.Instance._OnSubPropertyChanged = function (propd, sender, args) {
    if (args.Property.Name === "KeyTime")
        this._Resolved = false;
    this._OnSubPropertyChanged$DependencyObjectCollection(propd, sender, args);
};

/// http://msdn2.microsoft.com/en-us/library/ms742524.aspx (Bottom of page)
KeyFrameCollection.ResolveKeyFrames = function (animation, coll) {
    /// <param name="animation" type="Animation"></param>
    /// <param name="coll" type="KeyFrameCollection"></param>
    if (coll._Resolved)
        return;
    coll._Resolved = true;

    var totalInterpolationTime;
    var hasTimeSpanKeyFrame = false;
    var highestKeyTimeTimeSpan = 0;
    var keyFrame;
    var value;
    var count = coll.GetCount();

    var i;
    for (i = 0; i < count; i++) {
        value = coll.GetValueAt(i);
        keyFrame = Nullstone.As(value, KeyFrame);
        keyFrame._ResolvedTime = 0;
        keyFrame._Resolved = false;
    }

    var keyTime;
    // resolve TimeSpan keyframes
    for (i = 0; i < count; i++) {
        value = coll.GetValueAt(i);
        keyFrame = Nullstone.As(value, KeyFrame);
        keyTime = keyFrame.GetKeyTime();
        if (keyTime.HasTimeSpan()) {
            hasTimeSpanKeyFrame = true;
            var ts = keyTime.GetTimeSpan();
            if (ts.CompareTo(highestKeyTimeTimeSpan) > 0)
                highestKeyTimeTimeSpan = ts;
            keyFrame._ResolvedKeyTime = ts;
            keyFrame._Resolved = true;
        }
    }

    // calculate total animation interpolation time
    var d = animation.GetDuration();
    if (d.HasTimeSpan()) {
        totalInterpolationTime = d.GetTimeSpan();
    } else if (hasTimeSpanKeyFrame) {
        totalInterpolationTime = highestKeyTimeTimeSpan;
    } else {
        totalInterpolationTime = new TimeSpan(TimeSpan._TicksPerSecond);
    }

    // use the total interpolation time to resolve percent keytime keyframes
    for (i = 0; i < count; i++) {
        value = coll.GetValueAt(i);
        keyFrame = Nullstone.As(value, KeyFrame);
        keyTime = keyFrame.GetKeyTime();
        if (keyTime.HasPercent()) {
            keyFrame._ResolvedTime = totalInterpolationTime.Multiply(keyTime.GetPercent())
            keyFrame._Resolved = true;
        }
    }

    // if the last frame is KeyTime Uniform or Paced, resolve it to be equal to the total interpolation time
    if (count > 0) {
        value = coll.GetValueAt(count - 1);
        keyFrame = Nullstone.As(value, KeyFrame);
        keyTime = keyFrame.GetKeyTime();
        if (keyTime.IsPaced() || keyTime.IsUniform()) {
            keyFrame._ResolvedKeyTime = totalInterpolationTime;
            keyFrame._Resolved = true;
        }
    }

    /* if the first frame is KeyTime Paced:
    **   1. if there is only 1 frame, its KeyTime is the total interpolation time.
    **   2. if there is more than 1 frame, its KeyTime is 0.
    **
    ** note 1 is handled in the above block so we only have to
    ** handle 2 here.
    */
    if (count > 0) {
        value = coll.GetValueAt(count - 1);
        keyFrame = Nullstone.As(value, KeyFrame);
        keyTime = keyFrame.GetKeyTime();
        if (!keyFrame._Resolved && keyTime.IsPaced()) {
            keyFrame._ResolvedKeyTime = new TimeSpan(0);
            keyFrame._Resolved = true;
        }
    }

    // XXX resolve remaining KeyTime::Uniform frames

    // XXX resolve frames with unspecified keytimes -- is this possible?  is the default keytime NULL?  it seems to be Uniform?

    // XXX resolve remaining KeyTime::Paced frames */

    this._SortedList = [];
    for (i = 0; i < count; i++) {
        value = coll.GetValueAt(i);
        keyFrame = Nullstone.As(value, KeyFrame);
        this._SortedList.push(keyFrame);
    }
    this._SortedList.sort(KeyFrame.Comparer);
};

Nullstone.FinishCreate(KeyFrameCollection);
//#endregion<commit_msg>Fixed bug introduced in previous commit.<commit_after>/// <reference path="../../Core/Collections/DependencyObjectCollection.js"/>
/// CODE
/// <reference path="KeyFrame.js"/>
/// <reference path="Animation.js"/>

//#region KeyFrameCollection
var KeyFrameCollection = Nullstone.Create("KeyFrameCollection", DependencyObjectCollection);

KeyFrameCollection.Instance.Init = function () {
    this.Init$DependencyObjectCollection();
    this._Resolved = false;
    this._SortedList = [];
};

KeyFrameCollection.Instance.GetKeyFrameForTime = function (t, prevFrameRef) {
    /// <param name="t" type="TimeSpan"></param>
    /// <param name="prevFrameRef" type="Object"></param>
    var currentKeyFrame = null;
    var previousKeyFrame = null;
    var i;

    if (this._SortedList.length == 0) {
        prevFrameRef.Value = null;
        return null;
    }

    var keyFrame;
    var valuePropd;
    // Crawl forward to figure out what segment to use (this assumes the list is sorted)
    for (i = 0; i < this._SortedList.length; i++) {
        keyFrame = this._SortedList[i];
        var keyEndTime = keyFrame._ResolvedKeyTime;
        if (keyEndTime.CompareTo(t) >= 0 || (i + 1) >= this._SortedList.length)
            break;
    }

    // Crawl backward to find first non-null frame
    for (; i >= 0; i--) {
        keyFrame = this._SortedList[i];
        valuePropd = keyFrame.GetDependencyProperty("Value");
        if (keyFrame._GetValue(valuePropd) !== undefined) {
            currentKeyFrame = keyFrame;
            break;
        }
    }

    // Crawl backward some more to find first non-null prev frame
    for (i--; i >= 0; i--) {
        keyFrame = this._SortedList[i];
        valuePropd = keyFrame.GetDependencyProperty("Value");
        if (keyFrame._GetValue(valuePropd) !== undefined) {
            previousKeyFrame = keyFrame;
            break;
        }
    }

    prevFrameRef.Value = previousKeyFrame;
    return currentKeyFrame;
};

KeyFrameCollection.Instance.Clear = function () {
    this._Resolved = false;
    //Clear sorted
    this.Clear$DependencyObjectCollection();
};

KeyFrameCollection.Instance.AddedToCollection = function (value, error) {
    if (!this.AddedToCollection$DependencyObjectCollection(value, error))
        return false;
    this._Resolved = false;
    return true;
};
KeyFrameCollection.Instance.RemovedFromCollection = function (value, isValueSafe) {
    this.RemovedFromCollection$DependencyObjectCollection(value, isValueSafe);
    this._Resolved = false;
};

KeyFrameCollection.Instance._OnSubPropertyChanged = function (propd, sender, args) {
    if (args.Property.Name === "KeyTime")
        this._Resolved = false;
    this._OnSubPropertyChanged$DependencyObjectCollection(propd, sender, args);
};

/// http://msdn2.microsoft.com/en-us/library/ms742524.aspx (Bottom of page)
KeyFrameCollection.ResolveKeyFrames = function (animation, coll) {
    /// <param name="animation" type="Animation"></param>
    /// <param name="coll" type="KeyFrameCollection"></param>
    if (coll._Resolved)
        return;
    coll._Resolved = true;

    var totalInterpolationTime;
    var hasTimeSpanKeyFrame = false;
    var highestKeyTimeTimeSpan = 0;
    var keyFrame;
    var value;
    var count = coll.GetCount();

    var i;
    for (i = 0; i < count; i++) {
        value = coll.GetValueAt(i);
        keyFrame = Nullstone.As(value, KeyFrame);
        keyFrame._ResolvedTime = 0;
        keyFrame._Resolved = false;
    }

    var keyTime;
    // resolve TimeSpan keyframes
    for (i = 0; i < count; i++) {
        value = coll.GetValueAt(i);
        keyFrame = Nullstone.As(value, KeyFrame);
        keyTime = keyFrame.GetKeyTime();
        if (keyTime.HasTimeSpan()) {
            hasTimeSpanKeyFrame = true;
            var ts = keyTime.GetTimeSpan();
            if (ts.CompareTo(highestKeyTimeTimeSpan) > 0)
                highestKeyTimeTimeSpan = ts;
            keyFrame._ResolvedKeyTime = ts;
            keyFrame._Resolved = true;
        }
    }

    // calculate total animation interpolation time
    var d = animation._GetValue(Timeline.DurationProperty);
    if (d.HasTimeSpan()) {
        totalInterpolationTime = d.GetTimeSpan();
    } else if (hasTimeSpanKeyFrame) {
        totalInterpolationTime = highestKeyTimeTimeSpan;
    } else {
        totalInterpolationTime = new TimeSpan(TimeSpan._TicksPerSecond);
    }

    // use the total interpolation time to resolve percent keytime keyframes
    for (i = 0; i < count; i++) {
        value = coll.GetValueAt(i);
        keyFrame = Nullstone.As(value, KeyFrame);
        keyTime = keyFrame.GetKeyTime();
        if (keyTime.HasPercent()) {
            keyFrame._ResolvedTime = totalInterpolationTime.Multiply(keyTime.GetPercent())
            keyFrame._Resolved = true;
        }
    }

    // if the last frame is KeyTime Uniform or Paced, resolve it to be equal to the total interpolation time
    if (count > 0) {
        value = coll.GetValueAt(count - 1);
        keyFrame = Nullstone.As(value, KeyFrame);
        keyTime = keyFrame.GetKeyTime();
        if (keyTime.IsPaced() || keyTime.IsUniform()) {
            keyFrame._ResolvedKeyTime = totalInterpolationTime;
            keyFrame._Resolved = true;
        }
    }

    /* if the first frame is KeyTime Paced:
    **   1. if there is only 1 frame, its KeyTime is the total interpolation time.
    **   2. if there is more than 1 frame, its KeyTime is 0.
    **
    ** note 1 is handled in the above block so we only have to
    ** handle 2 here.
    */
    if (count > 0) {
        value = coll.GetValueAt(count - 1);
        keyFrame = Nullstone.As(value, KeyFrame);
        keyTime = keyFrame.GetKeyTime();
        if (!keyFrame._Resolved && keyTime.IsPaced()) {
            keyFrame._ResolvedKeyTime = new TimeSpan(0);
            keyFrame._Resolved = true;
        }
    }

    // XXX resolve remaining KeyTime::Uniform frames

    // XXX resolve frames with unspecified keytimes -- is this possible?  is the default keytime NULL?  it seems to be Uniform?

    // XXX resolve remaining KeyTime::Paced frames */

    this._SortedList = [];
    for (i = 0; i < count; i++) {
        value = coll.GetValueAt(i);
        keyFrame = Nullstone.As(value, KeyFrame);
        this._SortedList.push(keyFrame);
    }
    this._SortedList.sort(KeyFrame.Comparer);
};

Nullstone.FinishCreate(KeyFrameCollection);
//#endregion<|endoftext|>


<commit_before>/**
 * Movim Javascript Template functions

 * Look at the comments for help.
 */

var MovimTpl = {
    dragged : false,
    moving : false,
    percent : false,
    init : function() {
        if(document.getElementById('back') != null)
            MovimUtils.hideElement(document.getElementById('back'));
    },
    append : function(selector, html) {
        target = document.querySelector(selector);
        if(target) {
            target.insertAdjacentHTML('beforeend', html);
        }
    },
    back : function() {
        // If the context menu is shown
        var cm = document.querySelector('ul.context_menu');
        if(cm != null && cm.className.includes('shown')) {
            MovimTpl.toggleContextMenu(document);
            // If a drawer is shown
        } else if(Drawer.filled()) {
            Drawer.clear();
            // If a dialog box is shown
        } else if(Dialog.filled()) {
            Dialog.clear();
            // If the menu is shown
        } else if(MovimUtils.hasClass('body > nav', 'active')) {
            MovimUtils.removeClass('body > nav', 'active');
            // If the panel is shown
        } else if(MovimTpl.isPanel()) {
            MovimTpl.hidePanel();
            window.history.back();
        } else {
            history.back();
        }
    },
    fill : function(selector, html) {
        target = document.querySelector(selector);
        if(target) {
            target.innerHTML = html;
        }
    },
    hideContextMenu : function() {
        MovimUtils.removeClass('ul.context_menu', 'shown');
    },
    hideMenu: function() {
        MovimUtils.removeClass('body > nav', 'active');
    },
    showPanel: function() {
        MovimUtils.addClass('main section', 'enabled');
        MovimTpl.scrollPanelTop();
    },
    hidePanel: function() {
        MovimUtils.removeClass('main section', 'enabled');
    },
    isPanel: function() {
        return MovimUtils.hasClass('main section', 'enabled');
    },
    isPanelScrolled: function() {
        var selector = document.querySelector('main section > div:first-child:nth-last-child(2) ~ div div');

        if(selector != null) {
            return (selector.scrollHeight - Math.floor(selector.scrollTop) <= selector.clientHeight + 3);
        }
    },
    prepend: function(selector, html) {
        target = document.querySelector(selector);
        if(target) {
            target.insertAdjacentHTML('afterbegin', html);
        }
    },
    remove: function(selector) {
        target = document.querySelector(selector);
        if(target)
            target.parentNode.removeChild(target);
    },
    replace: function (selector, html) {
        target = document.querySelector(selector);
        if(target) {
            var div = document.createElement('div');
            div.innerHTML = html;
            var element = div.firstChild;
            replacedNode = target.parentNode.replaceChild(element, target);
        }
    },
    scrollPanel : function() {
        var selector = document.querySelector('main section > div:first-child:nth-last-child(2) ~ div div');

        if(selector != null) {
            selector.scrollTop = selector.scrollHeight;
        }
    },
    scrollPanelTop : function() {
        var selector = document.querySelector('main section > div:first-child:nth-last-child(2) ~ div');

        if(selector != null) {
            selector.scrollTop = 0;
        }
    },
    toggleActionButton : function() {
        MovimUtils.toggleClass('.button.action', 'active');
    },
    toggleContextMenu : function(e) {
        var element = 'ul.context_menu';
        var classname = 'shown';

        if(document.querySelector(element) == null) {
            return;
        }

        if(document.querySelector('.show_context_menu').contains(e.target)) {
            MovimUtils.addClass(element, classname);
            return;
        }

        //if(!document.querySelector(element).contains(e.target))
        MovimUtils.removeClass(element, classname);
    },
    toggleMenu : function() {
        MovimUtils.toggleClass('body > nav', 'active');
    },
    touchEvents: function() {
        nav = document.querySelector('body > nav');

        document.body.addEventListener('touchstart', function(event) {
            startX = event.targetTouches[0].pageX;

            if(
            (
                startX < 25 ||
                (nav.classList.contains('active') && startX > document.body.clientWidth - 25)
            )
            && MovimTpl.dragged == false) {
                nav.classList.add('moving');
                MovimTpl.dragged = true;
            }
        }, true);

        document.body.addEventListener('touchmove', function(event) {
            moveX = event.targetTouches[0].pageX;

            if(MovimTpl.dragged) {
                event.preventDefault();
                event.stopPropagation();

                position = moveX - document.body.clientWidth;

                MovimTpl.percent = 1 - Math.abs(moveX) / Math.abs(document.body.clientWidth);
                nav.style.transform = 'matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, '+position+', 0, 0, 1)';
            }
        }, true);

        document.body.addEventListener('touchend', function(event) {
            nav.style.transform = '';

            if(MovimTpl.dragged) {
                nav.classList.remove('moving');

                if(!nav.classList.contains('active')
                && MovimTpl.percent < 0.80) {
                    nav.classList.add('active');
                } else if(MovimTpl.percent > 0.20) {
                    nav.classList.remove('active');
                }
            }

            MovimTpl.dragged = false;
        }, true);
    }
};

movim_add_onload(function() {
    MovimTpl.init();
    MovimTpl.touchEvents();
    document.body.addEventListener('click', MovimTpl.toggleContextMenu, false);
});
<commit_msg>Smaller catch area to slide the nav bar<commit_after>/**
 * Movim Javascript Template functions

 * Look at the comments for help.
 */

var MovimTpl = {
    dragged : false,
    moving : false,
    percent : false,
    init : function() {
        if(document.getElementById('back') != null)
            MovimUtils.hideElement(document.getElementById('back'));
    },
    append : function(selector, html) {
        target = document.querySelector(selector);
        if(target) {
            target.insertAdjacentHTML('beforeend', html);
        }
    },
    back : function() {
        // If the context menu is shown
        var cm = document.querySelector('ul.context_menu');
        if(cm != null && cm.className.includes('shown')) {
            MovimTpl.toggleContextMenu(document);
            // If a drawer is shown
        } else if(Drawer.filled()) {
            Drawer.clear();
            // If a dialog box is shown
        } else if(Dialog.filled()) {
            Dialog.clear();
            // If the menu is shown
        } else if(MovimUtils.hasClass('body > nav', 'active')) {
            MovimUtils.removeClass('body > nav', 'active');
            // If the panel is shown
        } else if(MovimTpl.isPanel()) {
            MovimTpl.hidePanel();
            window.history.back();
        } else {
            history.back();
        }
    },
    fill : function(selector, html) {
        target = document.querySelector(selector);
        if(target) {
            target.innerHTML = html;
        }
    },
    hideContextMenu : function() {
        MovimUtils.removeClass('ul.context_menu', 'shown');
    },
    hideMenu: function() {
        MovimUtils.removeClass('body > nav', 'active');
    },
    showPanel: function() {
        MovimUtils.addClass('main section', 'enabled');
        MovimTpl.scrollPanelTop();
    },
    hidePanel: function() {
        MovimUtils.removeClass('main section', 'enabled');
    },
    isPanel: function() {
        return MovimUtils.hasClass('main section', 'enabled');
    },
    isPanelScrolled: function() {
        var selector = document.querySelector('main section > div:first-child:nth-last-child(2) ~ div div');

        if(selector != null) {
            return (selector.scrollHeight - Math.floor(selector.scrollTop) <= selector.clientHeight + 3);
        }
    },
    prepend: function(selector, html) {
        target = document.querySelector(selector);
        if(target) {
            target.insertAdjacentHTML('afterbegin', html);
        }
    },
    remove: function(selector) {
        target = document.querySelector(selector);
        if(target)
            target.parentNode.removeChild(target);
    },
    replace: function (selector, html) {
        target = document.querySelector(selector);
        if(target) {
            var div = document.createElement('div');
            div.innerHTML = html;
            var element = div.firstChild;
            replacedNode = target.parentNode.replaceChild(element, target);
        }
    },
    scrollPanel : function() {
        var selector = document.querySelector('main section > div:first-child:nth-last-child(2) ~ div div');

        if(selector != null) {
            selector.scrollTop = selector.scrollHeight;
        }
    },
    scrollPanelTop : function() {
        var selector = document.querySelector('main section > div:first-child:nth-last-child(2) ~ div');

        if(selector != null) {
            selector.scrollTop = 0;
        }
    },
    toggleActionButton : function() {
        MovimUtils.toggleClass('.button.action', 'active');
    },
    toggleContextMenu : function(e) {
        var element = 'ul.context_menu';
        var classname = 'shown';

        if(document.querySelector(element) == null) {
            return;
        }

        if(document.querySelector('.show_context_menu').contains(e.target)) {
            MovimUtils.addClass(element, classname);
            return;
        }

        //if(!document.querySelector(element).contains(e.target))
        MovimUtils.removeClass(element, classname);
    },
    toggleMenu : function() {
        MovimUtils.toggleClass('body > nav', 'active');
    },
    touchEvents: function() {
        nav = document.querySelector('body > nav');

        document.body.addEventListener('touchstart', function(event) {
            startX = event.targetTouches[0].pageX;

            if(
            (
                startX < 5 ||
                (nav.classList.contains('active') && startX > document.body.clientWidth - 25)
            )
            && MovimTpl.dragged == false) {
                nav.classList.add('moving');
                MovimTpl.dragged = true;
            }
        }, true);

        document.body.addEventListener('touchmove', function(event) {
            moveX = event.targetTouches[0].pageX;

            if(MovimTpl.dragged) {
                event.preventDefault();
                event.stopPropagation();

                position = moveX - document.body.clientWidth;

                MovimTpl.percent = 1 - Math.abs(moveX) / Math.abs(document.body.clientWidth);
                nav.style.transform = 'matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, '+position+', 0, 0, 1)';
            }
        }, true);

        document.body.addEventListener('touchend', function(event) {
            nav.style.transform = '';

            if(MovimTpl.dragged) {
                nav.classList.remove('moving');

                if(!nav.classList.contains('active')
                && MovimTpl.percent < 0.80) {
                    nav.classList.add('active');
                } else if(MovimTpl.percent > 0.20) {
                    nav.classList.remove('active');
                }
            }

            MovimTpl.dragged = false;
        }, true);
    }
};

movim_add_onload(function() {
    MovimTpl.init();
    MovimTpl.touchEvents();
    document.body.addEventListener('click', MovimTpl.toggleContextMenu, false);
});
<|endoftext|>


<commit_before>#!/usr/bin/env node

/**
 * `tail` source files listed in app/config.js.
 *
 * Usage:
 * - To use config/config.js source list: app/tail.js
 * - To use external source list: app/tail.js path/to/config.js
 *
 * process.send() is occasionally used to coordinate flow with test scripts.
 */

'use strict';

(function() {
  var program = require('commander');
  program
    .option('-c, --config <file>', '/path/to/config.js', null)
    .option('-t, --test <#>', 'Exit after # expected lines for unit tests', Number, 0)
    .option('-q, --quiet', false)
    .parse(process.argv);

  require(__dirname + '/modules/diana.js');
  var spawn = require('child_process').spawn,
      config = diana.getConfig(program.config),
      parsers = diana.requireModule('parsers/parsers'),
      procLog = diana.createUtilogger('tail.js');

  // To support maximum line count for --test.
  var lineCount = 0;

  /**
   * Configure the monitor.
   */
  var Monitor = function(source) {
    // Log source attribute object from config/app.js 'sources' list.
    this.source = _.clone(source);

    // ChildProcess object.
    this.tail = null;

    if (!program.quiet) {
      this.log = diana.createUtilogger(this.source.path);
    }
  };

  /**
   * Start a new `tail` instance and attach event handlers.
   */
  Monitor.prototype.start = function() {
    this.log('spawning tail');

    this.tail = spawn('tail', ['--bytes=0', '-F', this.source.path]);

    var monitor = this;

    this.tail.stdout.on('data', function(data) {
      var lines = data.toString().replace(/\n$/, '').split("\n");
      lineCount += lines.length;

      parsers.parseAndInsert({source: monitor.source, lines: lines}, function() {
        // Support maximum line count for --test.
        if (program.test > 0 && lineCount >= program.test) {
          process.exit();
        }
      }, true);
    });

    this.tail.on('exit', function(code, signal) {
      monitor.log("tail exited with code %d, signal %s", code, signal);

      // Auto-restart.
      monitor.start();

      if (program.test) {
        process.send('MONITOR_RESTART');
      }
    });

    // Kill `tail` before parent process exits.
    var killTail = function() {
      process.removeListener('END_MONITOR', killTail);
      if (monitor.tail) {
        monitor.log('killing ...');
        monitor.tail.kill('SIGKILL');
        monitor.log('killed');
        monitor.tail = null;
      }

      if (program.test) {
        if (!process.listeners('END_MONITOR').length) {
          process.send('MONITORS_ENDED');
        }
      }
    };
    process.on('END_MONITOR', killTail);

    this.log('pid %d', this.tail.pid);
  };

  /**
   * Send a formatted message to stdout. Prepend the timestamp and source path.
   *
   * Accepts util.format() arguments.
   */
  Monitor.prototype.log = function() {
    if (program.quiet) {
      return;
    }
    this.log.apply(null, arguments);
  };

  /**
   * Seed initial `tail` set based on config/app.js 'sources' list.
   */
  var startAllMonitors = function() {
    _.each(config.sources, function(source) {
      (new Monitor(source)).start();
    });
  };

  /**
   * Trigger monitors to clean up their `tail` instances.
   */
  var endAllMonitors = function() {
    process.emit('END_MONITOR');
  };
  process.on('exit', endAllMonitors);
  process.on('SIGINT', function() {
    procLog('SIGINT received');
    process.exit();
  });
  process.on('SIGTERM', function() {
    procLog('SIGTERM received');
    process.exit();
  });
  process.on('uncaughtException', function(err) {
    procLog('uncaught exception: %s', err.stack ? err.stack : '');
    process.exit();
  });

  // Test mode -- wait until instructed by parent process.
  if (program.test) {
    process.on('message', function(message) {
      if ('START_TEST' == message) {
        startAllMonitors();
        process.send('MONITORS_STARTED');
      }
    });
  // Normal mode -- start immediately.
  } else {
    startAllMonitors();
  }
})();
<commit_msg>Add --verbose to tail.js<commit_after>#!/usr/bin/env node

/**
 * `tail` source files listed in app/config.js.
 *
 * Usage:
 * - To use config/config.js source list: app/tail.js
 * - To use external source list: app/tail.js path/to/config.js
 *
 * process.send() is occasionally used to coordinate flow with test scripts.
 */

'use strict';

(function() {
  var program = require('commander');
  program
    .option('-c, --config <file>', '/path/to/config.js', null)
    .option('-t, --test <#>', 'Exit after # expected lines for unit tests', Number, 0)
    .option('-q, --quiet')
    .option('-v, --verbose')
    .parse(process.argv);

  require(__dirname + '/modules/diana.js');
  var spawn = require('child_process').spawn,
      config = diana.getConfig(program.config),
      parsers = diana.requireModule('parsers/parsers'),
      procLog = diana.createUtilogger('tail.js');

  // To support maximum line count for --test.
  var lineCount = 0;

  /**
   * Configure the monitor.
   */
  var Monitor = function(source) {
    // Log source attribute object from config/app.js 'sources' list.
    this.source = _.clone(source);

    // ChildProcess object.
    this.tail = null;

    if (!program.quiet) {
      this.log = diana.createUtilogger(this.source.path);
    }
  };

  /**
   * Start a new `tail` instance and attach event handlers.
   */
  Monitor.prototype.start = function() {
    this.log('spawning tail');

    this.tail = spawn('tail', ['--bytes=0', '-F', this.source.path]);

    var monitor = this;

    this.tail.stdout.on('data', function(data) {
      var lines = data.toString().replace(/\n$/, '').split("\n");
      lineCount += lines.length;

      if (program.verbose) {
        monitor.log('data=[%s] length={%d]', data.toString(), lines.length);
      }

      parsers.parseAndInsert({source: monitor.source, lines: lines}, function() {
        // Support maximum line count for --test.
        if (program.test > 0 && lineCount >= program.test) {
          process.exit();
        }
      }, true);
    });

    this.tail.on('exit', function(code, signal) {
      monitor.log("tail exited with code %d, signal %s", code, signal);

      // Auto-restart.
      monitor.start();

      if (program.test) {
        process.send('MONITOR_RESTART');
      }
    });

    // Kill `tail` before parent process exits.
    var killTail = function() {
      process.removeListener('END_MONITOR', killTail);
      if (monitor.tail) {
        monitor.log('killing ...');
        monitor.tail.kill('SIGKILL');
        monitor.log('killed');
        monitor.tail = null;
      }

      if (program.test) {
        if (!process.listeners('END_MONITOR').length) {
          process.send('MONITORS_ENDED');
        }
      }
    };
    process.on('END_MONITOR', killTail);

    this.log('pid %d', this.tail.pid);
  };

  /**
   * Send a formatted message to stdout. Prepend the timestamp and source path.
   *
   * Accepts util.format() arguments.
   */
  Monitor.prototype.log = function() {
    if (program.quiet) {
      return;
    }
    this.log.apply(null, arguments);
  };

  /**
   * Seed initial `tail` set based on config/app.js 'sources' list.
   */
  var startAllMonitors = function() {
    _.each(config.sources, function(source) {
      (new Monitor(source)).start();
    });
  };

  /**
   * Trigger monitors to clean up their `tail` instances.
   */
  var endAllMonitors = function() {
    process.emit('END_MONITOR');
  };
  process.on('exit', endAllMonitors);
  process.on('SIGINT', function() {
    procLog('SIGINT received');
    process.exit();
  });
  process.on('SIGTERM', function() {
    procLog('SIGTERM received');
    process.exit();
  });
  process.on('uncaughtException', function(err) {
    procLog('uncaught exception: %s', err.stack ? err.stack : '');
    process.exit();
  });

  // Test mode -- wait until instructed by parent process.
  if (program.test) {
    process.on('message', function(message) {
      if ('START_TEST' == message) {
        startAllMonitors();
        process.send('MONITORS_STARTED');
      }
    });
  // Normal mode -- start immediately.
  } else {
    startAllMonitors();
  }
})();
<|endoftext|>