<commit_before>// GLOBAL VARS
var socket;

var type;
var stats;
var URL = window.URL ? window.URL : window.webkitURL;

//----------------------------------------------------------------------------------------------------------------
// ON READY, SETUP SOCKET!
//----------------------------------------------------------------------------------------------------------------

$(document).ready( function() {
	setupSocket();

	document.getElementById("brow").textContent = " " + BrowserDetect.browser + " "
		+ BrowserDetect.version +" " + BrowserDetect.OS +" ";

	stats = new Stats();
	stats.setMode( 0 ); // 0: fps, 1: ms

	// Align top-left
	stats.domElement.style.position = 'absolute';
	stats.domElement.style.right = '0px';
	stats.domElement.style.top = '0px';

	document.body.appendChild( stats.domElement );

	stats.begin();

});

//----------------------------------------------------------------------------------------------------------------
// WS:ON OPEN
//----------------------------------------------------------------------------------------------------------------
function onOpen(){
	document.getElementById("wslm_statustd").style.backgroundColor = "#40ff40";
	document.getElementById("wslm_statustd").textContent = " websocket connection opened ";
}

//----------------------------------------------------------------------------------------------------------------
// WS: ON CLOSE
//----------------------------------------------------------------------------------------------------------------
function onClose(){
	document.getElementById("wslm_statustd").style.backgroundColor = "#ff4040";
	document.getElementById("wslm_statustd").textContent = " websocket connection CLOSED ";
}

//----------------------------------------------------------------------------------------------------------------
// WS: ON MESSAGE
//----------------------------------------------------------------------------------------------------------------

var prevBlob;
function onMessage( messageEvent ){
    stats.end();
    if (messageEvent.data instanceof Blob) {
      URL.revokeObjectURL(prevBlob);
      prevBlob = URL.createObjectURL(messageEvent.data);
      // just set image.src to the blob URL, then you're all good!
      $("#loadintome").attr("src",prevBlob);
	}
    stats.begin();
}

//----------------------------------------------------------------------------------------------------------------
// setup web socket
//----------------------------------------------------------------------------------------------------------------

function setupSocket(){
	// setup!
	socket = new WebSocket( get_appropriate_ws_url());
	socket.binaryType = "arraybuffer";

	// open
	try {
		socket.onopen 		= onOpen;
		socket.onmessage 	= onMessage;
		socket.onclose 	 	= onClose;
	} catch(exception) {
		alert('Error' + exception);
	}
}<commit_msg>Fixed blob example 2<commit_after>// GLOBAL VARS
var socket;

var type;
var stats;
var URL = window.URL ? window.URL : window.webkitURL;

//----------------------------------------------------------------------------------------------------------------
// ON READY, SETUP SOCKET!
//----------------------------------------------------------------------------------------------------------------

$(document).ready( function() {
	setupSocket();

	document.getElementById("brow").textContent = " " + BrowserDetect.browser + " "
		+ BrowserDetect.version +" " + BrowserDetect.OS +" ";

	stats = new Stats();
	stats.setMode( 0 ); // 0: fps, 1: ms

	// Align top-left
	stats.domElement.style.position = 'absolute';
	stats.domElement.style.right = '0px';
	stats.domElement.style.top = '0px';

	document.body.appendChild( stats.domElement );

	stats.begin();

});

//----------------------------------------------------------------------------------------------------------------
// WS:ON OPEN
//----------------------------------------------------------------------------------------------------------------
function onOpen(){
	document.getElementById("wslm_statustd").style.backgroundColor = "#40ff40";
	document.getElementById("wslm_statustd").textContent = " websocket connection opened ";
}

//----------------------------------------------------------------------------------------------------------------
// WS: ON CLOSE
//----------------------------------------------------------------------------------------------------------------
function onClose(){
	document.getElementById("wslm_statustd").style.backgroundColor = "#ff4040";
	document.getElementById("wslm_statustd").textContent = " websocket connection CLOSED ";
}

//----------------------------------------------------------------------------------------------------------------
// WS: ON MESSAGE
//----------------------------------------------------------------------------------------------------------------

var prevBlob;
function onMessage( messageEvent ){
    stats.end();
    if (messageEvent.data instanceof Blob) {
      URL.revokeObjectURL(prevBlob);
      prevBlob = URL.createObjectURL(messageEvent.data);
      // just set image.src to the blob URL, then you're all good!
      $("#loadintome").attr("src",prevBlob);
	}
    stats.begin();
}

//----------------------------------------------------------------------------------------------------------------
// setup web socket
//----------------------------------------------------------------------------------------------------------------

function setupSocket(){
	// setup!
	socket = new WebSocket( get_appropriate_ws_url());
	socket.binaryType = "blob";

	// open
	try {
		socket.onopen 		= onOpen;
		socket.onmessage 	= onMessage;
		socket.onclose 	 	= onClose;
	} catch(exception) {
		alert('Error' + exception);
	}
}
<|endoftext|>


<commit_before>import { accessSync, constants } from 'fs';
import { normalize } from 'path';

const BaseFileLoader = Jymfony.Component.Config.Loader.FileLoader;
const GlobResource = Jymfony.Component.Config.Resource.GlobResource;
const ChildDefinition = Jymfony.Component.DependencyInjection.ChildDefinition;

/**
 * FileLoader is the abstract class used by all built-in loaders that are file based.
 *
 * @abstract
 * @memberOf Jymfony.Component.DependencyInjection.Loader
 */
export default class FileLoader extends BaseFileLoader {
    /**
     * Constructor.
     *
     * @param {Jymfony.Component.DependencyInjection.ContainerBuilder} container
     * @param {Jymfony.Component.Config.FileLocatorInterface} locator
     */
    __construct(container, locator) {
        /**
         * @type {Jymfony.Component.DependencyInjection.ContainerBuilder}
         *
         * @protected
         */
        this._container = container;

        /**
         * @type {boolean}
         *
         * @protected
         */
        this._isLoadingInstanceof = false;

        /**
         * @type {Object.<string, *>}
         *
         * @protected
         */
        this._instanceof = {};

        super.__construct(locator);
    }

    /**
     * Registers a set of classes as services using autoloader for discovery.
     *
     * @param {Jymfony.Component.DependencyInjection.Definition} prototype A definition to use as template
     * @param {string} namespace The namespace prefix of classes in the scanned directory
     * @param {string} resource The directory to look for classes, glob-patterns allowed
     * @param {string|string[]|null} exclude A globbed path of files to exclude or an array of globbed paths of files to exclude
     *
     * @protected
     */
    _registerClasses(prototype, namespace, resource, exclude = null) {
        if (! namespace.endsWith('.')) {
            throw new InvalidArgumentException(__jymfony.sprintf('Namespace prefix must end with a ".": %s.', namespace));
        }

        if (null === exclude || undefined === exclude) {
            exclude = [];
        }

        const classes = this._findClasses(namespace, resource, isArray(exclude) ? exclude : [ exclude ]);

        // Prepare for deep cloning
        const serializedPrototype = __jymfony.serialize(prototype);
        const interfaces = [];
        const singlyImplemented = {};

        for (const [ Class, errorMessage ] of __jymfony.getEntries(classes)) {
            const reflectionClass = new ReflectionClass(Class);
            if (reflectionClass.isInterface) {
                interfaces.push(Class);
            } else {
                const definition = __jymfony.unserialize(serializedPrototype);
                this._setDefinition(Class, definition);
                if (null !== errorMessage) {
                    definition.addError(errorMessage);

                    continue;
                }

                for (const IF of reflectionClass.interfaces) {
                    singlyImplemented[IF.name] = undefined !== singlyImplemented[IF] ? false : Class;
                }
            }
        }

        for (const IF of interfaces) {
            if (!! singlyImplemented[IF]) {
                this._container.setAlias(IF, singlyImplemented[IF]).setPublic(false);
            }
        }
    }

    /**
     * Registers a definition in the container with its instanceof-conditionals.
     *
     * @param {string} id
     * @param {Jymfony.Component.DependencyInjection.Definition} definition
     *
     * @protected
     */
    _setDefinition(id, definition) {
        if (this._isLoadingInstanceof) {
            if (! (definition instanceof ChildDefinition)) {
                throw new InvalidArgumentException(__jymfony.sprintf('Invalid type definition "%s": ChildDefinition expected, "%s" given.', id, ReflectionClass.getClassName(definition)));
            }

            this._instanceof[id] = definition;
        } else {
            this._container.setDefinition(id, definition instanceof ChildDefinition ? definition : definition.setInstanceofConditionals(this._instanceof));
        }
    }

    /**
     * Finds classes into a namespace.
     *
     * @param {string} namespace
     * @param {string} pattern
     * @param {string[]} excludePatterns
     *
     * @returns {Object.<string, string | null>}
     *
     * @private
     */
    _findClasses(namespace, pattern, excludePatterns) {
        const parameterBag = this._container.parameterBag;

        const excludePaths = [];
        let excludePrefix = null;
        excludePatterns = parameterBag.unescapeValue(parameterBag.resolveValue(excludePatterns));
        for (const excludePattern of excludePatterns) {
            const resource = this._glob(excludePattern, true, false, true);
            for (const path of resource) {
                if (null === excludePrefix) {
                    excludePrefix = resource.prefix;
                }

                // Normalize Windows slashes
                excludePaths.push(normalize(path));
            }
        }

        pattern = parameterBag.unescapeValue(parameterBag.resolveValue(pattern));
        const classes = {};
        const extRegexp = /\.js$/;
        let prefixLen = null;
        const resource = this._glob(pattern, true, false, false, excludePaths);
        for (const path of resource) {
            if (null === prefixLen) {
                prefixLen = resource.prefix.length;

                if (excludePrefix && ! excludePrefix.startsWith(resource.prefix)) {
                    throw new InvalidArgumentException(__jymfony.sprintf('Invalid "exclude" pattern when importing classes for "%s": make sure your "exclude" pattern is a subset of the "resource" pattern (%s)', namespace, pattern));
                }
            }

            if (excludePaths.includes(normalize(path))) {
                continue;
            }

            const m = path.match(extRegexp);
            if (null === m) {
                continue;
            }

            try {
                accessSync(path, constants.R_OK);
            } catch (e) {
                continue;
            }

            const Class = namespace + __jymfony.ltrim(path.substr(prefixLen, path.length - prefixLen - m[0].length).replace(/[/\\]/g, '.'), '.');
            let r = null;

            try {
                r = this._container.getReflectionClass(Class);
            } catch (e) {
                if (! (e instanceof ReflectionException)) {
                    throw e;
                }

                classes[Class] = __jymfony.sprintf('While discovering services from namespace "%s", an error was thrown when processing the class "%s": "%s".', namespace, Class, e.message);
                continue;
            }

            // Check to make sure the expected class exists
            if (! r) {
                throw new InvalidArgumentException(__jymfony.sprintf('Expected to find class "%s" in file "%s" while importing services from resource "%s", but it was not found! Check the namespace prefix used with the resource.', Class, path, pattern));
            }

            if (! r.isTrait) {
                classes[Class] = null;
            }
        }

        // Track only for new & removed files
        if (resource instanceof GlobResource) {
            this._container.addResource(resource);
        } else {
            for (const path of resource) {
                this._container.fileExists(path, false);
            }
        }

        return classes;
    }
}
<commit_msg>[DependencyInjection] do not throw if class is not found in file while loading services from namespace<commit_after>import { accessSync, constants } from 'fs';
import { normalize } from 'path';

const BaseFileLoader = Jymfony.Component.Config.Loader.FileLoader;
const GlobResource = Jymfony.Component.Config.Resource.GlobResource;
const ChildDefinition = Jymfony.Component.DependencyInjection.ChildDefinition;

/**
 * FileLoader is the abstract class used by all built-in loaders that are file based.
 *
 * @abstract
 * @memberOf Jymfony.Component.DependencyInjection.Loader
 */
export default class FileLoader extends BaseFileLoader {
    /**
     * Constructor.
     *
     * @param {Jymfony.Component.DependencyInjection.ContainerBuilder} container
     * @param {Jymfony.Component.Config.FileLocatorInterface} locator
     */
    __construct(container, locator) {
        /**
         * @type {Jymfony.Component.DependencyInjection.ContainerBuilder}
         *
         * @protected
         */
        this._container = container;

        /**
         * @type {boolean}
         *
         * @protected
         */
        this._isLoadingInstanceof = false;

        /**
         * @type {Object.<string, *>}
         *
         * @protected
         */
        this._instanceof = {};

        super.__construct(locator);
    }

    /**
     * Registers a set of classes as services using autoloader for discovery.
     *
     * @param {Jymfony.Component.DependencyInjection.Definition} prototype A definition to use as template
     * @param {string} namespace The namespace prefix of classes in the scanned directory
     * @param {string} resource The directory to look for classes, glob-patterns allowed
     * @param {string|string[]|null} exclude A globbed path of files to exclude or an array of globbed paths of files to exclude
     *
     * @protected
     */
    _registerClasses(prototype, namespace, resource, exclude = null) {
        if (! namespace.endsWith('.')) {
            throw new InvalidArgumentException(__jymfony.sprintf('Namespace prefix must end with a ".": %s.', namespace));
        }

        if (null === exclude || undefined === exclude) {
            exclude = [];
        }

        const classes = this._findClasses(namespace, resource, isArray(exclude) ? exclude : [ exclude ]);

        // Prepare for deep cloning
        const serializedPrototype = __jymfony.serialize(prototype);
        const interfaces = [];
        const singlyImplemented = {};

        for (const [ Class, errorMessage ] of __jymfony.getEntries(classes)) {
            const reflectionClass = errorMessage ? null : new ReflectionClass(Class);
            if (reflectionClass && reflectionClass.isInterface) {
                interfaces.push(Class);
            } else {
                const definition = __jymfony.unserialize(serializedPrototype);
                this._setDefinition(Class, definition);
                if (null !== errorMessage) {
                    definition.addError(errorMessage);

                    continue;
                }

                if (reflectionClass) {
                    for (const IF of reflectionClass.interfaces) {
                        singlyImplemented[IF.name] = undefined !== singlyImplemented[IF] ? false : Class;
                    }
                }
            }
        }

        for (const IF of interfaces) {
            if (!! singlyImplemented[IF]) {
                this._container.setAlias(IF, singlyImplemented[IF]).setPublic(false);
            }
        }
    }

    /**
     * Registers a definition in the container with its instanceof-conditionals.
     *
     * @param {string} id
     * @param {Jymfony.Component.DependencyInjection.Definition} definition
     *
     * @protected
     */
    _setDefinition(id, definition) {
        if (this._isLoadingInstanceof) {
            if (! (definition instanceof ChildDefinition)) {
                throw new InvalidArgumentException(__jymfony.sprintf('Invalid type definition "%s": ChildDefinition expected, "%s" given.', id, ReflectionClass.getClassName(definition)));
            }

            this._instanceof[id] = definition;
        } else {
            this._container.setDefinition(id, definition instanceof ChildDefinition ? definition : definition.setInstanceofConditionals(this._instanceof));
        }
    }

    /**
     * Finds classes into a namespace.
     *
     * @param {string} namespace
     * @param {string} pattern
     * @param {string[]} excludePatterns
     *
     * @returns {Object.<string, string | null>}
     *
     * @private
     */
    _findClasses(namespace, pattern, excludePatterns) {
        const parameterBag = this._container.parameterBag;

        const excludePaths = [];
        let excludePrefix = null;
        excludePatterns = parameterBag.unescapeValue(parameterBag.resolveValue(excludePatterns));
        for (const excludePattern of excludePatterns) {
            const resource = this._glob(excludePattern, true, false, true);
            for (const path of resource) {
                if (null === excludePrefix) {
                    excludePrefix = resource.prefix;
                }

                // Normalize Windows slashes
                excludePaths.push(normalize(path));
            }
        }

        pattern = parameterBag.unescapeValue(parameterBag.resolveValue(pattern));
        const classes = {};
        const extRegexp = /\.js$/;
        let prefixLen = null;
        const resource = this._glob(pattern, true, false, false, excludePaths);
        for (const path of resource) {
            if (null === prefixLen) {
                prefixLen = resource.prefix.length;

                if (excludePrefix && ! excludePrefix.startsWith(resource.prefix)) {
                    throw new InvalidArgumentException(__jymfony.sprintf('Invalid "exclude" pattern when importing classes for "%s": make sure your "exclude" pattern is a subset of the "resource" pattern (%s)', namespace, pattern));
                }
            }

            if (excludePaths.includes(normalize(path))) {
                continue;
            }

            const m = path.match(extRegexp);
            if (null === m) {
                continue;
            }

            try {
                accessSync(path, constants.R_OK);
            } catch (e) {
                continue;
            }

            const Class = namespace + __jymfony.ltrim(path.substr(prefixLen, path.length - prefixLen - m[0].length).replace(/[/\\]/g, '.'), '.');
            let r = null;

            try {
                r = this._container.getReflectionClass(Class);
            } catch (e) {
                if (! (e instanceof ReflectionException)) {
                    throw e;
                }

                classes[Class] = __jymfony.sprintf('While discovering services from namespace "%s", an error was thrown when processing the class "%s": "%s".', namespace, Class, e.message);
                continue;
            }

            // Check to make sure the expected class exists
            if (! r) {
                classes[Class] = __jymfony.sprintf('Expected to find class "%s" in file "%s" while importing services from resource "%s", but it was not found! Check the namespace prefix used with the resource.', Class, path, pattern);
                continue;
            }

            if (! r.isTrait) {
                classes[Class] = null;
            }
        }

        // Track only for new & removed files
        if (resource instanceof GlobResource) {
            this._container.addResource(resource);
        } else {
            for (const path of resource) {
                this._container.fileExists(path, false);
            }
        }

        return classes;
    }
}
<|endoftext|>


<commit_before>'use strict';

var parse = require('csv-parse');
var fs    = require('fs');

var lobFactory = require('../../lib/index.js');
var Lob        = new lobFactory('YOUR_API_KEY');
var input      = fs.readFileSync(__dirname + '/input.csv', { encoding: 'utf-8' });
var frontHtml  = fs.readFileSync(__dirname + '/postcard_front.html', { encoding: 'utf-8' });
var backHtml   = fs.readFileSync(__dirname + '/postcard_back.html', { encoding: 'utf-8' });

parse(input, function (err, rows) {
  if (err) {
    return console.log(err);
  }
  for (var i = 0, l = rows.length; i < l; i++) {
    var row = rows[i];
    Lob.postcards.create({
      to: {
        name: row[5],
        address_line1: row[6],
        address_line2: row[7],
        address_city: row[8],
        address_state: row[9],
        address_zip: row[10],
        address_country: row[11]
      },
      from: {
        name: 'Lob',
        address_line1: '123 Main Street',
        address_city: 'San Francisco',
        address_state: 'CA',
        address_zip: '94185',
        address_country: 'US'
      },
      size: '4x6',
      front: frontHtml,
      back: backHtml,
      merge_variables: {
        background_image: row[1],
        background_color: row[2],
        name: row[0],
        car: row[3],
        mileage: row[4]
      }
    }, function (err, postcard) {
      if (err) {
        return console.log(err);
      }
      console.log('Postcard to ' + postcard.to.name + ' sent! View it here: ' + postcard.url);
    })
  }
});
<commit_msg>Add Metadata<commit_after>'use strict';

var parse = require('csv-parse');
var fs    = require('fs');

var lobFactory = require('../../lib/index.js');
var Lob        = new lobFactory('YOUR_API_KEY');
var input      = fs.readFileSync(__dirname + '/input.csv', { encoding: 'utf-8' });
var frontHtml  = fs.readFileSync(__dirname + '/postcard_front.html', { encoding: 'utf-8' });
var backHtml   = fs.readFileSync(__dirname + '/postcard_back.html', { encoding: 'utf-8' });

parse(input, function (err, rows) {
  if (err) {
    return console.log(err);
  }
  for (var i = 0, l = rows.length; i < l; i++) {
    var row = rows[i];
    Lob.postcards.create({
      to: {
        name: row[5],
        address_line1: row[6],
        address_line2: row[7],
        address_city: row[8],
        address_state: row[9],
        address_zip: row[10],
        address_country: row[11]
      },
      from: {
        name: 'Lob',
        address_line1: '123 Main Street',
        address_city: 'San Francisco',
        address_state: 'CA',
        address_zip: '94185',
        address_country: 'US'
      },
      size: '4x6',
      front: frontHtml,
      back: backHtml,
      merge_variables: {
        background_image: row[1],
        background_color: row[2],
        name: row[0],
        car: row[3],
        mileage: row[4]
      },
      metadata: {
        name: row[0],
        customer_id: "customer_123",
        campaign: "Example Campaign"
      }
    }, function (err, postcard) {
      if (err) {
        return console.log(err);
      }
      console.log('Postcard to ' + postcard.to.name + ' sent! View it here: ' + postcard.url);
    })
  }
});
<|endoftext|>


<commit_before>window.responsiveChild = function(config){
    var parentWidth;
    var id;
    var settings = {
        renderCallback: null,
        id:null,
        xdomain: '*',
        polling: 0
    };
    for (var key in config) { settings[key] = config[key]; }

    /*
    * Extract a querystring parameter from the URL.
    */
    var getParameterByName = function(name) {
        name = name.replace(/[\[]/, '\\\[').replace(/[\]]/, '\\\]');

        var regex = new RegExp("[\\?&]" + name + '=([^&#]*)');
        var results = regex.exec(location.search);;

        return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, " "));
    };

    /*
    * Verify that the message came from a trustworthy domaine
    */
    var isSafeMessage = function(e) {
        if (settings.xdomain !== '*') {
            var regex = new RegExp(settings.xdomain + '$');

            if (!e.origin.match(regex)) {
                // Not the origin we're listening for
                return;
            }
        }

        return true;
    };

    /*
    * Process a new message from parent frame.
    */
    var processMessage = function(e) {
        if (!isSafeMessage(e)) {
            return;
        }

        // Parent sent width
        var match = e.data.match(/^responsive-parent-(\w+)-(\d+)$/);

        if (!match || match.length !== 3) {
            // Not the message we're listening for
            return;
        }

        id = match[1];
        var width = parseInt(match[2]);

        if (width != parentWidth) {
            parentWidth = width;

            if (settings.renderCallback) {
                settings.renderCallback(width);
            }

            sendHeightToParent();
        }
    };

    /*
    * Transmit the current iframe height to the parent.
    */
    var sendHeightToParent = function() {
        var height = document.getElementsByTagName('body')[0].offsetHeight.toString();
        window.top.postMessage('responsive-child-' + id + '-'+ height, '*');
    };

    window.addEventListener('message', processMessage, false);

    id = getParameterByName('childId');

    // Initial width is sent as querystring parameter
    var width = parseInt(getParameterByName('initialWidth'));

    if (settings.renderCallback) {
        settings.renderCallback(width);
    }

    sendHeightToParent();

    if (settings.polling) {
        window.setInterval(sendHeightToParent, settings.polling);
    }

}

window.responsiveParent = function(config) {
    var elements = document.querySelectorAll('div[data-iframe-target]');
    var settings = { xdomain: '*' };

    for (var key in config) { settings[key] = config[key]; }

    var constructIframe = function(el) {
        // Calculate its width.
        var width = el.offsetWidth.toString();

        var node = document.createElement("iframe");

        var url = el.getAttribute('data-iframe-target');
        var id = el.getAttribute('id');

        if (url.indexOf('?') < 0) {
            url += '?';
        } else {
            url += '&';
        }

        // Send the initial width as a querystring parameter.
        node.src = url + 'initialWidth=' + width + '&childId=' + id;

        // Super not-dry way to set attrs on our iFrame.
        node.setAttribute('width', '100%');
        node.setAttribute('scrolling', 'no');
        node.setAttribute('marginheight', '0');
        node.setAttribute('frameborder', '0');
        el.appendChild(node);

        // Do our magic on screen resize.
        window.addEventListener('resize', function(e) {
            sendWidthToChild(el);
        });
    }

    /*
    * Verify that the message came from a trustworthy domain.
    */
    var isSafeMessage = function(e) {
        if (settings.xdomain !== '*') {
            var regex = new RegExp(settings.xdomain + '$');

            if (!e.origin.match(regex)) {
                // Not the origin we're listening for
                return;
            }
        }

        return true;
    }

    /*
    * Process a new message from a child iframe.
    */
    var processMessage = function(e) {
        if (!isSafeMessage(e)) {
            return;
        }

        // Child sent height
        var match = e.data.match(/^responsive-child-(\w+)-(\d+)$/);

        if (!match || match.length !== 3) {
            return false;
        }

        var childId = match[1];
        var height = parseInt(match[2]);

        elements = document.querySelectorAll('div[data-iframe-target]');

        for (var i=0; i<elements.length; i++){
            el = elements[i];
            if (el.getAttribute('id') == childId) {
                el.getElementsByTagName('iframe')[0].setAttribute('height', height + 'px');
            }
        }
    }

    /*
    * Transmit the current iframe width to the child.
    */
    function sendWidthToChild(el) {
        var width = el.offsetWidth.toString();
        el.getElementsByTagName('iframe')[0].contentWindow.postMessage('responsive-parent-' + el.getAttribute('id') + '-' + width, '*');
    }

    window.addEventListener('message', processMessage, false);

    for (var i=0; i<elements.length; i++){
        constructIframe(elements[i]);
    }

};<commit_msg>Remove duplicate library.<commit_after><|endoftext|>


<commit_before>import React from 'react';
import { shallow, mount } from 'enzyme';

import QueryBuilder from './QueryBuilder';

describe('<QueryBuilder />', () => {

    it('should exist', () => {
        expect(QueryBuilder).to.exist;
    });

    describe('when rendered', () => {
        it('should render the root RuleGroup', () => {
            const dom = shallow(<QueryBuilder />);
            expect(dom.find('RuleGroup')).to.have.length(1);
        });

        it('should show the list of combinators in the RuleGroup', () => {
            const dom = mount(<QueryBuilder />);
            const options = dom.find('select option');
            expect(options).to.have.length(2); // and, or
        });

    });

    describe('when initial query is provided', () => {
        let dom;

        beforeEach(() => {
            const fields = [
                { name: 'firstName', label: 'First Name' },
                { name: 'lastName', label: 'Last Name' },
                { name: 'age', label: 'Age' },
            ];

            const query = {
                combinator: 'and',
                id: '111',
                rules: [
                    {
                        id: '222',
                        field: 'firstName',
                        value: 'Test',
                        operator: '='
                    }
                ]
            };

            dom = mount(<QueryBuilder query={query} fields={fields} />);
        });

        afterEach(() => {
            if (dom) {
                dom.unmount();
            }
        });

        it('should contain a <Rule />', () => {

            const rule = dom.find('Rule');
            expect(rule).to.have.length(1);
        });

        it('should have the Rule with the correct props', () => {
            const rule = dom.find('Rule');

            expect(rule.props().field).to.equal('firstName');
            expect(rule.props().value).to.equal('Test');
            expect(rule.props().operator).to.equal('=');
        });

        it('should have a select control with the provided fields', () => {
            const rule = dom.find('Rule');

            expect(rule.find('.rule-fields option')).to.have.length(3);
        });

        it('should have a field selector with the correct field', () => {
            const rule = dom.find('Rule');

            expect(rule.find('.rule-fields select').props().value).to.equal('firstName');
        });

        it('should have an operator selector with the correct operator', () => {
            const rule = dom.find('Rule');

            expect(rule.find('.rule-operators select').props().value).to.equal('=');
        });

        it('should have an input control with the correct value', () => {
            const rule = dom.find('Rule');

            expect(rule.find('input').props().value).to.equal('Test');
        });

        it('should accept new props and update query and schema.fields', ()=>{
            const newFields = [
                { name: 'domainName', label: 'Domain Name' },
                { name: 'ownerName', label: 'Owner Name' },

            ];

            const newQuery = {
                combinator: 'and',
                id: '111',
                rules: [
                    {
                        id: '222',
                        field: 'domainName',
                        value: 'www.example.com',
                        operator: '='
                    }
                ]
            };

        dom.setProps({
            query: newQuery,
            fields: newFields
        });

        const rule = dom.find('Rule');
        expect(rule.find('.rule-fields select').props().value).to.equal('domainName');

    });
});

    describe('when initial operators are provided', () => {

        let dom;
        beforeEach(() => {
            const operators = [
                { name: 'null', label: 'Custom Is Null' },
                { name: 'notNull', label: 'Is Not Null' },
                { name: 'in', label: 'In' },
                { name: 'notIn', label: 'Not In' },
            ];

            const fields = [
                { name: 'firstName', label: 'First Name' },
                { name: 'lastName', label: 'Last Name' },
                { name: 'age', label: 'Age' },
            ];

            const query = {
                combinator: 'and',
                id: '111',
                rules: [
                    {
                        id: '222',
                        field: 'firstName',
                        value: 'Test',
                        operator: '='
                    }
                ]
            };

            dom = mount(<QueryBuilder operators={operators}
                                      fields={fields}
                                      query={query} />);
        });

        it('should use the given operators', () => {
            const operatorOptions = dom.find('Rule').find('.rule-operators option');

            expect(operatorOptions.length).to.equal(4);
        });

        it('should match the label of the first operator', () => {
            const operatorOption = dom.find('Rule').find('.rule-operators option').first();

            expect(operatorOption.text()).to.equal('Custom Is Null');
        });
    });

    describe('when calculating the level of a rule', function () {
        let dom;
        beforeEach(() => {
            const fields = [
                { name: 'firstName', label: 'First Name' },
                { name: 'lastName', label: 'Last Name' },
                { name: 'age', label: 'Age' },
            ];
            const query = {
                combinator: 'and',
                id: '111',
                rules: [{
                    id: '222',
                    field: 'firstName',
                    value: 'Test',
                    operator: '='
                }, {
                    id: '333',
                    field: 'firstName',
                    value: 'Test',
                    operator: '='
                }, {
                    combinator: 'and',
                    id: '444',
                    rules: [{
                        id: '555',
                        field: 'firstName',
                        value: 'Test',
                        operator: '='
                    }]
                }]
            };

            dom = mount(<QueryBuilder query={query} fields={fields} />);
        });

        it('should be 0 for the top level', function () {
            expect(dom.state('schema').getLevel('111')).to.equal(0);
            expect(dom.state('schema').getLevel('222')).to.equal(0);
            expect(dom.state('schema').getLevel('333')).to.equal(0);
        });

        it('should be 1 for the second level', function () {
            expect(dom.state('schema').getLevel('444')).to.equal(1);
            expect(dom.state('schema').getLevel('555')).to.equal(1);
        });

        it('should handle an invalid id', function () {
            expect(dom.state('schema').getLevel('546')).to.equal(-1);
        });
    });
});
<commit_msg>Better coverage?<commit_after>import React from 'react';
import { shallow, mount } from 'enzyme';

import QueryBuilder from './QueryBuilder';

describe('<QueryBuilder />', () => {

    it('should exist', () => {
        expect(QueryBuilder).to.exist;
    });

    describe('when rendered', () => {
        it('should render the root RuleGroup', () => {
            const dom = shallow(<QueryBuilder />);
            expect(dom.find('RuleGroup')).to.have.length(1);
        });

        it('should show the list of combinators in the RuleGroup', () => {
            const dom = mount(<QueryBuilder />);
            const options = dom.find('select option');
            expect(options).to.have.length(2); // and, or
        });

    });

    describe('when initial query is provided', () => {
        let dom;

        beforeEach(() => {
            const fields = [
                { name: 'firstName', label: 'First Name' },
                { name: 'lastName', label: 'Last Name' },
                { name: 'age', label: 'Age' },
            ];

            const query = {
                combinator: 'and',
                id: '111',
                rules: [
                    {
                        id: '222',
                        field: 'firstName',
                        value: 'Test',
                        operator: '='
                    }
                ]
            };

            dom = mount(<QueryBuilder query={query} fields={fields} />);
        });

        afterEach(() => {
            if (dom) {
                dom.unmount();
            }
        });

        it('should contain a <Rule />', () => {

            const rule = dom.find('Rule');
            expect(rule).to.have.length(1);
        });

        it('should have the Rule with the correct props', () => {
            const rule = dom.find('Rule');

            expect(rule.props().field).to.equal('firstName');
            expect(rule.props().value).to.equal('Test');
            expect(rule.props().operator).to.equal('=');
        });

        it('should have a select control with the provided fields', () => {
            const rule = dom.find('Rule');

            expect(rule.find('.rule-fields option')).to.have.length(3);
        });

        it('should have a field selector with the correct field', () => {
            const rule = dom.find('Rule');

            expect(rule.find('.rule-fields select').props().value).to.equal('firstName');
        });

        it('should have an operator selector with the correct operator', () => {
            const rule = dom.find('Rule');

            expect(rule.find('.rule-operators select').props().value).to.equal('=');
        });

        it('should have an input control with the correct value', () => {
            const rule = dom.find('Rule');

            expect(rule.find('input').props().value).to.equal('Test');
        });

        it('should accept new props (query and fields) and update query and schema.fields', ()=>{
            const newFields = [
                { name: 'domainName', label: 'Domain Name' },
                { name: 'ownerName', label: 'Owner Name' },

            ];

            const newQuery = {
                combinator: 'and',
                id: '111',
                rules: [
                    {
                        id: '222',
                        field: 'domainName',
                        value: 'www.example.com',
                        operator: '='
                    }
                ]
            };

        dom.setProps({
            query: newQuery,
            fields: newFields
        });

        let fieldstate = dom.state('schema');

        expect(fieldstate.fields).to.equal(newFields);
        expect(dom.state('root')).to.equal(newQuery);

        const rule = dom.find('Rule');
        expect(rule.find('.rule-fields select').props().value).to.equal('domainName');
        expect(rule.find('input').props().value).to.equal('www.example.com');

    });

});

    describe('when initial operators are provided', () => {

        let dom;
        beforeEach(() => {
            const operators = [
                { name: 'null', label: 'Custom Is Null' },
                { name: 'notNull', label: 'Is Not Null' },
                { name: 'in', label: 'In' },
                { name: 'notIn', label: 'Not In' },
            ];

            const fields = [
                { name: 'firstName', label: 'First Name' },
                { name: 'lastName', label: 'Last Name' },
                { name: 'age', label: 'Age' },
            ];

            const query = {
                combinator: 'and',
                id: '111',
                rules: [
                    {
                        id: '222',
                        field: 'firstName',
                        value: 'Test',
                        operator: '='
                    }
                ]
            };

            dom = mount(<QueryBuilder operators={operators}
                                      fields={fields}
                                      query={query} />);
        });

        it('should use the given operators', () => {
            const operatorOptions = dom.find('Rule').find('.rule-operators option');

            expect(operatorOptions.length).to.equal(4);
        });

        it('should match the label of the first operator', () => {
            const operatorOption = dom.find('Rule').find('.rule-operators option').first();

            expect(operatorOption.text()).to.equal('Custom Is Null');
        });
    });

    describe('when calculating the level of a rule', function () {
        let dom;
        beforeEach(() => {
            const fields = [
                { name: 'firstName', label: 'First Name' },
                { name: 'lastName', label: 'Last Name' },
                { name: 'age', label: 'Age' },
            ];
            const query = {
                combinator: 'and',
                id: '111',
                rules: [{
                    id: '222',
                    field: 'firstName',
                    value: 'Test',
                    operator: '='
                }, {
                    id: '333',
                    field: 'firstName',
                    value: 'Test',
                    operator: '='
                }, {
                    combinator: 'and',
                    id: '444',
                    rules: [{
                        id: '555',
                        field: 'firstName',
                        value: 'Test',
                        operator: '='
                    }]
                }]
            };

            dom = mount(<QueryBuilder query={query} fields={fields} />);
        });

        it('should be 0 for the top level', function () {
            expect(dom.state('schema').getLevel('111')).to.equal(0);
            expect(dom.state('schema').getLevel('222')).to.equal(0);
            expect(dom.state('schema').getLevel('333')).to.equal(0);
        });

        it('should be 1 for the second level', function () {
            expect(dom.state('schema').getLevel('444')).to.equal(1);
            expect(dom.state('schema').getLevel('555')).to.equal(1);
        });

        it('should handle an invalid id', function () {
            expect(dom.state('schema').getLevel('546')).to.equal(-1);
        });
    });
});
<|endoftext|>


<commit_before>var system = require('system');

var JQuery_js_Filename = 'jquery-2.1.0.js';
var Client_js_Filename = 'dom-code.js';

var casper_options = {
	userAgent: 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)',
	// verbose: true,
	logLevel: 'debug',
	pageSettings:
	{
		loadImages: false,
		loadPlugins: false
	},
	clientScripts: [
		// JQuery_js_Filename
		// , Client_js_Filename
	]
};

var casper = require('casper').create(casper_options);
var xpath = require('casper').selectXPath;
var utils = require('utils');
var fs = require('fs');

var logger = require('logger');
var parsing = require('parsing');

require('utils-casper')(casper, logger);

//=====================================================================
//=====================================================================
//
//  ┬┌┐┌┌┬┐┬┌─┐┬  ┬┌─┐┌─┐┌┬┐┬┌─┐┌┐┌
//  ││││ │ │├─┤│  │┌─┘├─┤ │ ││ ││││
//  ┴┘└┘ ┴ ┴┴ ┴┴─┘┴└─┘┴ ┴ ┴ ┴└─┘┘└┘
//
//=====================================================================
//=====================================================================

//=====================================================================
// Log the startup.
logger.LogMessage('Casper Status: ');
casper.status(true);
logger.LogMessage("Casper CLI passed args:");
utils.dump(casper.cli.args);
logger.LogMessage("Casper CLI passed options:");
utils.dump(casper.cli.options);

//=====================================================================
// Parse the command line.
var subverse_name = '';
if(casper.cli.has('subverse'))
{
	subverse_name = casper.cli.get('subverse');
	logger.LogMessage('Using the subverse [' + subverse_name + '].');
}
else
{
	logger.LogMessage('Error: No subverse specified.');
	process.exit(1);
}

var take_snapshots = casper.cli.has('snapshots');

//=====================================================================
// Start with front page of the subverse.
var start_url = 'https://voat.co/v/' + subverse_name;

logger.LogMessage("Scrape starting at [" + start_url + "].");
casper.start(start_url);

//=====================================================================
// Identify the output folder.
var output_folder = 'subverse-' + subverse_name;
if(!fs.exists(output_folder))
{
	logger.LogMessage('Error: Output folder does not exist [' + output_folder + '].');
	process.exit(1);
}

//=====================================================================
//=====================================================================
//
//  ╔╦╗┌─┐┬┌┐┌  ╔═╗─┐ ┬┌─┐┌─┐┬ ┬┌┬┐┬┌─┐┌┐┌
//  ║║║├─┤││││  ║╣ ┌┴┬┘├┤ │  │ │ │ ││ ││││
//  ╩ ╩┴ ┴┴┘└┘  ╚═╝┴ └─└─┘└─┘└─┘ ┴ ┴└─┘┘└┘
//
//=====================================================================
//=====================================================================

//=====================================================================
// Read the submission index file.
var filename = output_folder + '/submission-index.json';
if(!fs.exists(filename))
{
	logger.LogMessage('Error: Submission index file does not exist [' + filename + '].');
	process.exit(1);
}
var content = fs.read(filename);
var submission_index_entries = JSON.parse(content);

//=====================================================================
function ClickToDeath(selector)
{
	casper.waitForSelector(selector,
		function OnResource()
		{
			if(casper.exists(selector))
			{
				logger.LogMessage('ClickToDeath [' + selector + ']');
				casper.click(selector);
				// casper.wait(2000, ClickToDeath(selector));
				ClickToDeath(selector);
			}
		},
		function OnTimeout()
		{},
		5000);

	return;
}

//=====================================================================
// Iterate through the submission index and scrape each submission page.
casper.eachThen(
	submission_index_entries,
	function ScrapeSubmissionPage(iteration)
	{
		var submission_index_entry = iteration.data;
		logger.LogMessage('==========================================');
		logger.LogMessage('Processing next submission.');
		logger.LogMessage(JSON.stringify(submission_index_entry, undefined, '    '));

		this.thenOpen(
			submission_index_entry.submission_url,
			function ScrapeSubmission()
			{
				ClickToDeath('a#loadmorebutton');
				// ClickToDeath('a.inline-loadcomments-btn');
				// this.wait(2000, ClickToDeath(this, 'a#loadmorebutton'));

				this.then(function()
				{
					var submission_id = casper.GetAttributeValue('div.submission', 'data-fullname', '');
					if(submission_id == '')
					{
						submission_id = casper.GetAttributeValue('div.submission', 'id', '');
						submission_id = parsing.Parse_GetTextAfter(submission_id, 'submissionid-');
					}

					logger.LogMessage('Scraping submission ' + submission_id + ' in subverse [' + subverse_name + '].');
					if(take_snapshots)
					{
						var snapshot_filename = output_folder + '/' + submission_id + '.jpg';
						this.capture(snapshot_filename);
						logger.LogMessage('Saved snapshot to [' + snapshot_filename + '].');
					}

					// Scrape the submission.
					var submission = {};
					submission.submission_id = submission_id;
					submission.title = casper.GetAttributeValue('a.title', 'title', '');
					submission.timestamp = casper.GetAttributeValue('div.submission time', 'datetime', '');
					submission.username = casper.GetAttributeValue('div.submission span.userattrs a', 'data-username', '');
					submission.submission_text = casper.GetElementText('div.submission textarea');
					submission.submission_link = casper.GetAttributeValue('div.submission a.title', 'href', '');
					submission.vote_score = casper.GetElementText('div.submission div.score.unvoted');
					submission.comment_count = casper.GetElementText('div.submission a.comments');
					submission.comment_count = parsing.Parse_GetTextBefore(submission.comment_count, ' comment');

					logger.LogMessage(JSON.stringify(submission, undefined, '    '));

					// Get the comments.
					submission.comments = [];
					var comment_ids = casper.getElementsAttribute('div.child.comment div.noncollapsed', 'id');
					comment_ids.forEach(function(comment_id)
					{
						logger.LogMessage('Scraping comment ' + comment_id + '.');

						var comment = {};
						comment.comment_id = comment_id;
						comment.parent_comment_id = '';
						comment.submission_id = submission.submission_id;

						var selector = "[id='" + comment_id + "']";

						comment.timestamp = casper.GetAttributeValue(selector + ' p.tagline time', 'datetime', '');
						comment.username = casper.GetAttributeValue(selector + ' p.tagline a.author', 'data-username', '');
						comment.up_votes = casper.GetElementText(selector + ' p.tagline span.score.likes span.number');
						comment.down_votes = casper.GetElementText(selector + ' span.score.dislikes span.number');
						comment.vote_score = casper.GetElementText(selector + ' span.score.unvoted span.number');
						comment.comment_text = casper.GetElementText(selector + ' textarea.commenttextarea');

						if(casper.exists(selector + ' ul li a'))
						{
							var infos = casper.getElementsInfo(selector + ' ul li a');
							// logger.LogMessage(JSON.stringify(infos, undefined, 4));
							infos.forEach(function(info)
							{
								if(info.text == 'parent')
								{
									var ids = info.attributes.href.split('/');
									if(ids.length > 0)
									{
										comment.parent_comment_id = ids[ids.length - 1];
									}
								}
							});
						}
						submission.comments.push(comment);
					});
					logger.LogMessage('Scraped ' + submission.comments.length + ' comments.');

					// Write the submission to a file.
					var content = JSON.stringify(submission, undefined, 4);
					var filename = output_folder + '/' + submission.submission_id + '.json';
					logger.LogMessage('Writing submission file [' + filename + '].');
					fs.write(filename, content, 'w');

					return;
				});

			});

		return;
	}
);

//=====================================================================
//=====================================================================
//
//  ┌─┐┬ ┬┬ ┬┌┬┐┌┬┐┌─┐┬ ┬┌┐┌
//  └─┐├─┤│ │ │  │││ │││││││
//  └─┘┴ ┴└─┘ ┴ ─┴┘└─┘└┴┘┘└┘
//
//=====================================================================
//=====================================================================

casper.then(
	function BeforeExit()
	{
		logger.LogMessage("Scraping is finished.");
	}
);

casper.run();
<commit_msg>alpha<commit_after>var system = require('system');

var JQuery_js_Filename = 'jquery-2.1.0.js';
var Client_js_Filename = 'dom-code.js';

var casper_options = {
	userAgent: 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)',
	// verbose: true,
	logLevel: 'debug',
	pageSettings:
	{
		loadImages: false,
		loadPlugins: false
	},
	clientScripts: [
		// JQuery_js_Filename
		// , Client_js_Filename
	]
};

var casper = require('casper').create(casper_options);
var xpath = require('casper').selectXPath;
var utils = require('utils');
var fs = require('fs');

var logger = require('logger');
var parsing = require('parsing');

require('utils-casper')(casper, logger);

//=====================================================================
//=====================================================================
//
//  ┬┌┐┌┌┬┐┬┌─┐┬  ┬┌─┐┌─┐┌┬┐┬┌─┐┌┐┌
//  ││││ │ │├─┤│  │┌─┘├─┤ │ ││ ││││
//  ┴┘└┘ ┴ ┴┴ ┴┴─┘┴└─┘┴ ┴ ┴ ┴└─┘┘└┘
//
//=====================================================================
//=====================================================================

//=====================================================================
// Log the startup.
logger.LogMessage('Casper Status: ');
casper.status(true);
logger.LogMessage("Casper CLI passed args:");
utils.dump(casper.cli.args);
logger.LogMessage("Casper CLI passed options:");
utils.dump(casper.cli.options);

//=====================================================================
// Parse the command line.
var subverse_name = '';
if(casper.cli.has('subverse'))
{
	subverse_name = casper.cli.get('subverse');
	logger.LogMessage('Using the subverse [' + subverse_name + '].');
}
else
{
	logger.LogMessage('Error: No subverse specified.');
	process.exit(1);
}

var take_snapshots = casper.cli.has('snapshots');

//=====================================================================
// Start with front page of the subverse.
var start_url = 'https://voat.co/v/' + subverse_name;

logger.LogMessage("Scrape starting at [" + start_url + "].");
casper.start(start_url);

//=====================================================================
// Identify the output folder.
var output_folder = 'subverse-' + subverse_name;
if(!fs.exists(output_folder))
{
	logger.LogMessage('Error: Output folder does not exist [' + output_folder + '].');
	process.exit(1);
}

//=====================================================================
var log_debug_objects = false;

//=====================================================================
//=====================================================================
//
//  ╔╦╗┌─┐┬┌┐┌  ╔═╗─┐ ┬┌─┐┌─┐┬ ┬┌┬┐┬┌─┐┌┐┌
//  ║║║├─┤││││  ║╣ ┌┴┬┘├┤ │  │ │ │ ││ ││││
//  ╩ ╩┴ ┴┴┘└┘  ╚═╝┴ └─└─┘└─┘└─┘ ┴ ┴└─┘┘└┘
//
//=====================================================================
//=====================================================================

//=====================================================================
// Read the submission index file.
var filename = output_folder + '/submission-index.json';
if(!fs.exists(filename))
{
	logger.LogMessage('Error: Submission index file does not exist [' + filename + '].');
	process.exit(1);
}
var content = fs.read(filename);
var submission_index_entries = JSON.parse(content);

//=====================================================================
function ClickToDeath(selector)
{
	casper.waitForSelector(selector,
		function OnResource()
		{
			if(casper.exists(selector))
			{
				logger.LogMessage('ClickToDeath [' + selector + ']');
				casper.click(selector);
				// casper.wait(2000, ClickToDeath(selector));
				ClickToDeath(selector);
			}
		},
		function OnTimeout()
		{},
		5000);

	return;
}

var submission_count = submission_index_entries.length;
var submission_number = 0;

//=====================================================================
// Iterate through the submission index and scrape each submission page.
casper.eachThen(
	submission_index_entries,
	function ScrapeSubmissionPage(iteration)
	{
		var submission_index_entry = iteration.data;
		submission_number++;
		logger.LogMessage('==========================================');
		logger.LogMessage('Processing submission ' + submission_number + ' of ' + submission_count + '.');
		if(log_debug_objects)
		{
			logger.LogMessage(JSON.stringify(submission_index_entry, undefined, '    '));
		}

		this.thenOpen(
			submission_index_entry.submission_url,
			function ScrapeSubmission()
			{
				ClickToDeath('a#loadmorebutton');
				// ClickToDeath('a.inline-loadcomments-btn');
				// this.wait(2000, ClickToDeath(this, 'a#loadmorebutton'));

				this.then(function()
				{
					var submission_id = casper.GetAttributeValue('div.submission', 'data-fullname', '');
					if(submission_id == '')
					{
						submission_id = casper.GetAttributeValue('div.submission', 'id', '');
						submission_id = parsing.Parse_GetTextAfter(submission_id, 'submissionid-');
					}

					logger.LogMessage('Scraping submission ' + submission_id + ' in subverse [' + subverse_name + '].');
					if(take_snapshots)
					{
						var snapshot_filename = output_folder + '/' + submission_id + '.jpg';
						this.capture(snapshot_filename);
						logger.LogMessage('Saved snapshot to [' + snapshot_filename + '].');
					}

					// Scrape the submission.
					var submission = {};
					submission.submission_id = submission_id;
					submission.title = casper.GetAttributeValue('a.title', 'title', '');
					submission.timestamp = casper.GetAttributeValue('div.submission time', 'datetime', '');
					submission.username = casper.GetAttributeValue('div.submission span.userattrs a', 'data-username', '');
					submission.submission_text = casper.GetElementText('div.submission textarea');
					submission.submission_link = casper.GetAttributeValue('div.submission a.title', 'href', '');
					submission.vote_score = casper.GetElementText('div.submission div.score.unvoted');
					submission.comment_count = casper.GetElementText('div.submission a.comments');
					submission.comment_count = parsing.Parse_GetTextBefore(submission.comment_count, ' comment');

					if(log_debug_objects)
					{
						logger.LogMessage(JSON.stringify(submission, undefined, '    '));
					}

					// Get the comments.
					submission.comments = [];
					var comment_ids = casper.getElementsAttribute('div.child.comment div.noncollapsed', 'id');
					comment_ids.forEach(function(comment_id)
					{
						logger.LogMessage('Scraping comment ' + comment_id + '.');

						var comment = {};
						comment.comment_id = comment_id;
						comment.parent_comment_id = '';
						comment.submission_id = submission.submission_id;

						var selector = "[id='" + comment_id + "']";

						comment.timestamp = casper.GetAttributeValue(selector + ' p.tagline time', 'datetime', '');
						comment.username = casper.GetAttributeValue(selector + ' p.tagline a.author', 'data-username', '');
						comment.up_votes = casper.GetElementText(selector + ' p.tagline span.score.likes span.number');
						comment.down_votes = casper.GetElementText(selector + ' span.score.dislikes span.number');
						comment.vote_score = casper.GetElementText(selector + ' span.score.unvoted span.number');
						comment.comment_text = casper.GetElementText(selector + ' textarea.commenttextarea');

						if(casper.exists(selector + ' ul li a'))
						{
							var infos = casper.getElementsInfo(selector + ' ul li a');
							// logger.LogMessage(JSON.stringify(infos, undefined, 4));
							infos.forEach(function(info)
							{
								if(info.text == 'parent')
								{
									var ids = info.attributes.href.split('/');
									if(ids.length > 0)
									{
										comment.parent_comment_id = ids[ids.length - 1];
									}
								}
							});
						}
						submission.comments.push(comment);
					});
					logger.LogMessage('Scraped ' + submission.comments.length + ' comments.');

					// Write the submission to a file.
					var content = JSON.stringify(submission, undefined, 4);
					var filename = output_folder + '/' + submission.submission_id + '.json';
					logger.LogMessage('Writing submission file [' + filename + '].');
					fs.write(filename, content, 'w');

					return;
				});

			});

		return;
	}
);

//=====================================================================
//=====================================================================
//
//  ┌─┐┬ ┬┬ ┬┌┬┐┌┬┐┌─┐┬ ┬┌┐┌
//  └─┐├─┤│ │ │  │││ │││││││
//  └─┘┴ ┴└─┘ ┴ ─┴┘└─┘└┴┘┘└┘
//
//=====================================================================
//=====================================================================

casper.then(
	function BeforeExit()
	{
		logger.LogMessage("Scraping is finished.");
	}
);

casper.run();
<|endoftext|>


<commit_before>/*global ODSA */
// Written by Mohammed Farghally and Cliff Shaffer
// Quick Sort Best Case
$(document).ready(function() {
  "use strict";
  var av_name = "QuickSortBestCaseCON";
  // Load the config object with interpreter and code created by odsaUtils.js
  var config = ODSA.UTILS.loadConfig({av_name: av_name}),
      interpret = config.interpreter;      // get the interpreter
  var av = new JSAV(av_name);

  // Slide 1
  av.umsg(interpret("Slide 1"));
  av.displayInit();

  // Slide 2
  av.umsg(interpret("Slide 2"));
  av.g.rect(100, 5, 400, 30);
  av.label("$n$",  {top: "-18px", left: "300px"}).addClass("mediumLabel");
  av.step();

  // Slide 3
  av.umsg(interpret("Slide 3"));
  av.g.rect(100, 80, 400, 30);
  av.g.rect(290, 80, 10, 30);
  av.label("|--------  $< A[pivot]$  --------|",  {top: "35px", left: "105px"}).addClass("mediumLabel2");
  av.label("|---------  $> A[pivot]$  ---------|",  {top: "35px", left: "310px"}).addClass("mediumLabel2");
  av.label("pivot",  {top: "75px", left: "281px"}).addClass("smallLabel rotated");
  av.label("$\\frac{n}{2}$",  {top: "62px", left: "190px"}).addClass("mediumLabel");
  av.label("$\\frac{n}{2}$",  {top: "62px", left: "390px"}).addClass("mediumLabel");
  av.label("$\\theta(n)$",  {top: "62px", left: "600px"}).addClass("mediumLabel");
  av.step();

  // Slide 4
  av.umsg(interpret("Slide 4"));
  av.g.rect(80, 160, 200, 30);
  av.g.rect(320, 160, 200, 30);
  av.g.rect(175, 160, 10, 30);
  av.g.rect(415, 160, 10, 30);
  av.label("pivot",  {top: "155px", left: "166px"}).addClass("smallLabel rotated");
  av.label("pivot",  {top: "155px", left: "406px"}).addClass("smallLabel rotated");
  av.label("$\\frac{n}{4}$",  {top: "142px", left: "120px"}).addClass("mediumLabel");
  av.label("$\\frac{n}{4}$",  {top: "142px", left: "220px"}).addClass("mediumLabel");
  av.label("$\\frac{n}{4}$",  {top: "142px", left: "360px"}).addClass("mediumLabel");
  av.label("$\\frac{n}{4}$",  {top: "142px", left: "460px"}).addClass("mediumLabel");
  av.label("$\\theta(n)$",  {top: "142px", left: "600px"}).addClass("mediumLabel");
  av.step();

  // Slide 5
  av.umsg(interpret("Slide 5"));
  av.g.rect(60, 240, 100, 30);
  av.g.rect(180, 240, 100, 30);
  av.g.rect(320, 240, 100, 30);
  av.g.rect(440, 240, 100, 30);
  av.g.rect(105, 240, 10, 30);
  av.g.rect(225, 240, 10, 30);
  av.g.rect(365, 240, 10, 30);
  av.g.rect(485, 240, 10, 30);
  av.label("pivot",  {top: "235px", left: "96px"}).addClass("smallLabel rotated");
  av.label("pivot",  {top: "235px", left: "216px"}).addClass("smallLabel rotated");
  av.label("pivot",  {top: "235px", left: "356px"}).addClass("smallLabel rotated");
  av.label("pivot",  {top: "235px", left: "476px"}).addClass("smallLabel rotated");
  av.label("$\\frac{n}{8}$",  {top: "222px", left: "75px"}).addClass("mediumLabel");
  av.label("$\\frac{n}{8}$",  {top: "222px", left: "130px"}).addClass("mediumLabel");
  av.label("$\\frac{n}{8}$",  {top: "222px", left: "195px"}).addClass("mediumLabel");
  av.label("$\\frac{n}{8}$",  {top: "222px", left: "250px"}).addClass("mediumLabel");
  av.label("$\\frac{n}{8}$",  {top: "222px", left: "330px"}).addClass("mediumLabel");
  av.label("$\\frac{n}{8}$",  {top: "222px", left: "390px"}).addClass("mediumLabel");
  av.label("$\\frac{n}{8}$",  {top: "222px", left: "450px"}).addClass("mediumLabel");
  av.label("$\\frac{n}{8}$",  {top: "222px", left: "510px"}).addClass("mediumLabel");
  av.label("$\\theta(n)$",  {top: "222px", left: "600px"}).addClass("mediumLabel");
  av.step();

  // Slide 6
  av.umsg(interpret("Slide 6"));
  av.label("...",  {top: "235px", left: "105px"}).addClass("largeLabel rotated");
  av.label("...",  {top: "235px", left: "225px"}).addClass("largeLabel rotated");
  av.label("...",  {top: "235px", left: "365px"}).addClass("largeLabel rotated");
  av.label("...",  {top: "235px", left: "485px"}).addClass("largeLabel rotated");
  av.label("...",  {top: "235px", left: "610px"}).addClass("largeLabel rotated");
  av.g.rect(40, 320, 30, 30);
  av.g.rect(80, 320, 30, 30);
  av.label(".....................................",  {top: "270px", left: "120px"}).addClass("largeLabel");
  av.g.rect(500, 320, 30, 30);
  av.g.rect(540, 320, 30, 30);
  av.label("$1$",  {top: "302px", left: "50px"}).addClass("mediumLabel");
  av.label("$1$",  {top: "302px", left: "90px"}).addClass("mediumLabel");
  av.label("$1$",  {top: "302px", left: "510px"}).addClass("mediumLabel");
  av.label("$1$",  {top: "302px", left: "550px"}).addClass("mediumLabel");
  av.label("$\\theta(n)$",  {top: "302px", left: "600px"}).addClass("mediumLabel");
  av.step();

  // Slide 7
  av.umsg(interpret("Slide 7"));
  av.label("|------------------ $\\log{n}$------------------|",
  {top: "195px", left: "550px"}).css({"font-size": "16px", "text-align": "center"}).addClass("rotated");
  av.recorded();
});
<commit_msg>Adjusting labels<commit_after>/*global ODSA */
// Written by Mohammed Farghally and Cliff Shaffer
// Quick Sort Best Case
$(document).ready(function() {
  "use strict";
  var av_name = "QuickSortBestCaseCON";
  // Load the config object with interpreter and code created by odsaUtils.js
  var config = ODSA.UTILS.loadConfig({av_name: av_name}),
      interpret = config.interpreter;      // get the interpreter
  var av = new JSAV(av_name);

  // Slide 1
  av.umsg(interpret("Slide 1"));
  av.displayInit();

  // Slide 2
  av.umsg(interpret("Slide 2"));
  av.g.rect(100, 5, 400, 30);
  av.label("$n$",  {top: "-5px", left: "300px"}).addClass("mediumLabel");
  av.step();

  // Slide 3
  av.umsg(interpret("Slide 3"));
  av.g.rect(100, 80, 400, 30);
  av.g.rect(290, 80, 10, 30);
  av.label("|--------  $< A[pivot]$  --------|",  {top: "35px", left: "105px"}).addClass("mediumLabel2");
  av.label("|---------  $> A[pivot]$  ---------|",  {top: "35px", left: "310px"}).addClass("mediumLabel2");
  av.label("pivot",  {top: "75px", left: "281px"}).addClass("smallLabel rotated");
  av.label("$\\frac{n}{2}$",  {top: "70px", left: "190px"}).addClass("mediumLabel");
  av.label("$\\frac{n}{2}$",  {top: "70px", left: "390px"}).addClass("mediumLabel");
  av.label("$\\theta(n)$",  {top: "70px", left: "600px"}).addClass("mediumLabel");
  av.step();

  // Slide 4
  av.umsg(interpret("Slide 4"));
  av.g.rect(80, 160, 200, 30);
  av.g.rect(320, 160, 200, 30);
  av.g.rect(175, 160, 10, 30);
  av.g.rect(415, 160, 10, 30);
  av.label("pivot",  {top: "155px", left: "166px"}).addClass("smallLabel rotated");
  av.label("pivot",  {top: "155px", left: "406px"}).addClass("smallLabel rotated");
  av.label("$\\frac{n}{4}$",  {top: "150px", left: "120px"}).addClass("mediumLabel");
  av.label("$\\frac{n}{4}$",  {top: "150px", left: "220px"}).addClass("mediumLabel");
  av.label("$\\frac{n}{4}$",  {top: "150px", left: "360px"}).addClass("mediumLabel");
  av.label("$\\frac{n}{4}$",  {top: "150px", left: "460px"}).addClass("mediumLabel");
  av.label("$\\theta(n)$",  {top: "150px", left: "600px"}).addClass("mediumLabel");
  av.step();

  // Slide 5
  av.umsg(interpret("Slide 5"));
  av.g.rect(60, 240, 100, 30);
  av.g.rect(180, 240, 100, 30);
  av.g.rect(320, 240, 100, 30);
  av.g.rect(440, 240, 100, 30);
  av.g.rect(105, 240, 10, 30);
  av.g.rect(225, 240, 10, 30);
  av.g.rect(365, 240, 10, 30);
  av.g.rect(485, 240, 10, 30);
  av.label("pivot",  {top: "235px", left: "96px"}).addClass("smallLabel rotated");
  av.label("pivot",  {top: "235px", left: "216px"}).addClass("smallLabel rotated");
  av.label("pivot",  {top: "235px", left: "356px"}).addClass("smallLabel rotated");
  av.label("pivot",  {top: "235px", left: "476px"}).addClass("smallLabel rotated");
  av.label("$\\frac{n}{8}$",  {top: "230px", left: "75px"}).addClass("mediumLabel");
  av.label("$\\frac{n}{8}$",  {top: "230px", left: "130px"}).addClass("mediumLabel");
  av.label("$\\frac{n}{8}$",  {top: "230px", left: "195px"}).addClass("mediumLabel");
  av.label("$\\frac{n}{8}$",  {top: "230px", left: "250px"}).addClass("mediumLabel");
  av.label("$\\frac{n}{8}$",  {top: "230px", left: "330px"}).addClass("mediumLabel");
  av.label("$\\frac{n}{8}$",  {top: "230px", left: "390px"}).addClass("mediumLabel");
  av.label("$\\frac{n}{8}$",  {top: "230px", left: "450px"}).addClass("mediumLabel");
  av.label("$\\frac{n}{8}$",  {top: "230px", left: "510px"}).addClass("mediumLabel");
  av.label("$\\theta(n)$",  {top: "230px", left: "600px"}).addClass("mediumLabel");
  av.step();

  // Slide 6
  av.umsg(interpret("Slide 6"));
  av.label("...",  {top: "235px", left: "105px"}).addClass("largeLabel rotated");
  av.label("...",  {top: "235px", left: "225px"}).addClass("largeLabel rotated");
  av.label("...",  {top: "235px", left: "365px"}).addClass("largeLabel rotated");
  av.label("...",  {top: "235px", left: "485px"}).addClass("largeLabel rotated");
  av.label("...",  {top: "235px", left: "610px"}).addClass("largeLabel rotated");
  av.g.rect(40, 320, 30, 30);
  av.g.rect(80, 320, 30, 30);
  av.label("......................................................................",  {top: "300px", left: "120px"}).addClass("largeLabel");
  av.g.rect(500, 320, 30, 30);
  av.g.rect(540, 320, 30, 30);
  av.label("$1$",  {top: "310px", left: "50px"}).addClass("mediumLabel");
  av.label("$1$",  {top: "310px", left: "90px"}).addClass("mediumLabel");
  av.label("$1$",  {top: "310px", left: "510px"}).addClass("mediumLabel");
  av.label("$1$",  {top: "310px", left: "550px"}).addClass("mediumLabel");
  av.label("$\\theta(n)$",  {top: "310px", left: "600px"}).addClass("mediumLabel");
  av.step();

  // Slide 7
  av.umsg(interpret("Slide 7"));
  av.label("|----------------- $\\log{n}$-----------------|",
  {top: "195px", left: "550px"}).css({"font-size": "16px", "text-align": "center"}).addClass("rotated");
  av.recorded();
});
<|endoftext|>


<commit_before>var _gulp   = require('gulp');
var _rename = require('gulp-rename');
//var _core = require('./vendor/spryker/zed-package/gulpfile');

var _del    = require('del');

var _dirCore = 'vendor/spryker/zed-package/src/ProjectA/Zed';
var _dirProj = 'src/Pyz/Zed';
var _dirPub  = 'static/public/Zed/bundles';

var _dirStatPub = '/Static/Public';

function _changeDest(path) {
	path.dirname = path.dirname.replace(_dirStatPub, '');
}

_gulp.task('clean-css', function(done) {
	_del(_dirPub + '/*/styles', done);
});

_gulp.task('clean-js', function(done) {
	_del(_dirPub + '/*/scripts', done);
});

_gulp.task('clean-images', function(done) {
	_del(_dirPub + '/*/images', done);
});

_gulp.task('clean-fonts', function(done) {
	_del(_dirPub + '/*/fonts', done);
});

_gulp.task('copy-css', ['clean-css'], function() {
	return _gulp.src([
		_dirCore + '/*/Static/Public/styles/**/*.css',
		_dirPub  + '/*/Static/Public/styles/**/*.css'
	])
		.pipe(_rename(_changeDest))
		.pipe(_gulp.dest(_dirPub));
});

_gulp.task('copy-js', ['clean-js'], function() {
	return _gulp.src([
		_dirCore + '/*/Static/Public/scripts/**/*.js',
		_dirProj + '/*/Static/Public/scripts/**/*.js'
	])
		.pipe(_rename(_changeDest))
		.pipe(_gulp.dest(_dirPub));
});

_gulp.task('copy-images', ['clean-images'], function() {
	return _gulp.src([
		_dirCore + '/*/Static/Public/images/**/*.{svg,png,jpeg,gif}',
		_dirProj + '/*/Static/Public/images/**/*.{svg,png,jpeg,gif}'
	])
		.pipe(_rename(_changeDest))
		.pipe(_gulp.dest(_dirPub));
});

_gulp.task('copy-fonts', ['clean-fonts'], function() {
	return _gulp.src([
		_dirCore + '/*/Static/Public/fonts/**/*.{svg,woff,otf,ttf,eot}',
		_dirProj + '/*/Static/Public/fonts/**/*.{svg,woff,otf,ttf,eot}'
	])
		.pipe(_rename(_changeDest))
		.pipe(_gulp.dest(_dirPub));
});

_gulp.task('watcher', ['dev'], function() {
	_gulp.watch([
		_dirCore + '/*/Static/Public/*/styles/**/*.css',
		_dirProj + '/*/Static/Public/*/styles/**/*.css'
	], ['clean-css', 'copy-css']);

	_gulp.watch([
		_dirCore + '/*/Static/Public/*/scripts/**/*.js',
		_dirProj + '/*/Static/Public/*/scripts/**/*.js'
	],['clean-js', 'copy-js']);

	_gulp.watch([
		_dirCore + '/*/Static/Public/*/images/**/*.{svg,png,jpeg,gif}',
		_dirProj + '/*/Static/Public/*/images/**/*.{svg,png,jpeg,gif}'
	], ['clean-images', 'copy-images']);

	_gulp.watch([
		_dirCore + '/*/Static/Public/*/fonts/**/*.{svg,woff,otf,ttf,eot}',
		_dirProj + '/*/Static/Public/*/fonts/**/*.{svg,woff,otf,ttf,eot}'
	], ['clean-fonts', 'copy-fonts']);
});

_gulp.task('dev', [
	'clean-css',
	'clean-js',
	'clean-images',
	'clean-fonts',
	'copy-css',
	'copy-js',
	'copy-images',
	'copy-fonts'
]);

_gulp.task('dist', [
	'clean-css',
	'clean-js',
	'clean-images',
	'clean-fonts',
	'copy-css',
	'copy-js',
	'copy-images',
	'copy-fonts'
]);

_gulp.task('default', [
	'dist'
]);<commit_msg>#429 Added Zed gulpfile<commit_after>var _gulp   = require('gulp');
var _rename = require('gulp-rename');
//var _core = require('./vendor/spryker/zed-package/gulpfile');

var _path   = require('path');
var _del    = require('del');

var _dirCore = 'vendor/spryker/zed-package/src/ProjectA/Zed';
var _dirProj = 'src/Pyz/Zed';
var _dirPub  = 'static/public/Zed/bundles';

var _dirStatPub = '/Static/Public';

function _buildSource(type) {
	var source = {
		'css'    : 'styles/**/*.css',
		'js'     : 'scripts/**/*.js',
		'images' : 'images/**/*.{svg,png,jpeg,gif}',
		'fonts'  : 'fonts/**/*.{svg,woff,otf,ttf,eot}'
	};

	return [
		_path.join(_dirCore, '*', _dirStatPub, source[type]),
		_path.join(_dirProj, '*', _dirStatPub, source[type])
	];
}

function _changeDest(path) {
	path.dirname = path.dirname.replace(_dirStatPub, '');
}

function _copy(type) {
	return _gulp.src(_buildSource(type))
		.pipe(_rename(_changeDest))
		.pipe(_gulp.dest(_dirPub));
}

_gulp.task('clean-css', function(done) {
	_del(_dirPub + '/*/styles', done);
});

_gulp.task('clean-js', function(done) {
	_del(_dirPub + '/*/scripts', done);
});

_gulp.task('clean-images', function(done) {
	_del(_dirPub + '/*/images', done);
});

_gulp.task('clean-fonts', function(done) {
	_del(_dirPub + '/*/fonts', done);
});

_gulp.task('copy-css', ['clean-css'], function() {
	return _copy('css');
});

_gulp.task('copy-js', ['clean-js'], function() {
	return _copy('js');
});

_gulp.task('copy-images', ['clean-images'], function() {
	return _copy('images');
});

_gulp.task('copy-fonts', ['clean-fonts'], function() {
	return _copy('fonts');
});

_gulp.task('watcher', ['dev'], function() {
	_gulp.watch([
		_dirCore + '/*/Static/Public/*/styles/**/*.css',
		_dirProj + '/*/Static/Public/*/styles/**/*.css'
	], ['clean-css', 'copy-css']);

	_gulp.watch([
		_dirCore + '/*/Static/Public/*/scripts/**/*.js',
		_dirProj + '/*/Static/Public/*/scripts/**/*.js'
	],['clean-js', 'copy-js']);

	_gulp.watch([
		_dirCore + '/*/Static/Public/*/images/**/*.{svg,png,jpeg,gif}',
		_dirProj + '/*/Static/Public/*/images/**/*.{svg,png,jpeg,gif}'
	], ['clean-images', 'copy-images']);

	_gulp.watch([
		_dirCore + '/*/Static/Public/*/fonts/**/*.{svg,woff,otf,ttf,eot}',
		_dirProj + '/*/Static/Public/*/fonts/**/*.{svg,woff,otf,ttf,eot}'
	], ['clean-fonts', 'copy-fonts']);
});

_gulp.task('dev', [
	'clean-css',
	'clean-js',
	'clean-images',
	'clean-fonts',
	'copy-css',
	'copy-js',
	'copy-images',
	'copy-fonts'
]);

_gulp.task('dist', [
	'clean-css',
	'clean-js',
	'clean-images',
	'clean-fonts',
	'copy-css',
	'copy-js',
	'copy-images',
	'copy-fonts'
]);

_gulp.task('default', [
	'dist'
]);<|endoftext|>


<commit_before>var config = {

    // UTC timezone offset for your stores location
    timezone: '-0500',

    // Enter your shipping cutoff deadline in 24 hour format
    deadline: {
        hour: 16,
        minute: 0
    },

    // Name of estimated shipping method
    shipMethodName: 'Fixed Rate Shipping',

    // This is to make sure we only show transit info if an item is in stock!
    stockSelector  : 'p.availability',  // selector for element that notifies stock status
    inStockText    : 'in-stock',        // in stock text
    // inStockText : true,              // use this if you want to show for all items

    // If you want to estimate delivery dates enter estimated lead time for each state in days
    leadtime: {
        'Alabama': 2,
        'Alaska': 6,
        'Arizona': 5,
        'Arkansas': 2,
        'California': 5,
        'Colorado': 4,
        'Connnecticut': 3,
        'Delaware': 3,
        'Florida': 1,
        'Georgia': 2,
        'Hawaii': 7,
        'Idaho': 5,
        'Illinois': 3,
        'Indiana': 2,
        'Iowa': 3,
        'Kansas': 3,
        'Kentucky': 2,
        'Louisiana': 2,
        'Maine': 3,
        'Maryland': 3,
        'Massachusetts': 3,
        'Michigan': 3,
        'Minnesota': 3,
        'Mississippi': 2,
        'Missouri': 3,
        'Montana': 5,
        'Nebraska': 4,
        'Nevada': 5,
        'New Hampshire': 3,
        'New Jersey': 3,
        'New Mexico': 4,
        'New York': 4,
        'North Carolina': 2,
        'North Dakota': 5,
        'Ohio': 2,
        'Oklahoma': 3,
        'Oregon': 5,
        'Pennsylvania': 3,
        'Rhode Island': 3,
        'South Carolina': 2,
        'South Dakota': 4,
        'Tennessee': 2,
        'Texas': 3,
        'Utah': 5,
        'Vermont': 3,
        'Virginia': 2,
        'Washington': 5,
        'West Virginia': 2,
        'Wisconsin': 3,
        'Wyoming': 5
    }
};

function isWeekday(moment) {
    return (moment.day() !== 0 && moment.day() !== 7) ? true : false;
}

function shipDay(deadline) {
    return (moment().zone(config.timezone).isSame(deadline, "d")) ? "Today" : deadline.format("dddd");
}

function shippingDeadline(hour, minute) {
    var deadline = moment().zone(config.timezone).hour(hour).minute(minute).second(0);
    if (moment().zone(config.timezone).hour() >= deadline.hour() && isWeekday(moment().zone(config.timezone))) {
        deadline.add('h', 24);
    }
    if (!isWeekday(deadline)) {
        return (deadline.day() === 0) ? deadline.add('h', 24) : deadline.add('h', 48);
    } else {
        return deadline;
    }
}

function timeUntilDeadline(deadline) {
    var minutesTill = Math.abs(moment().zone(config.timezone).diff(deadline, 'm'));
    for(var hoursTill = 0; minutesTill >= 60; hoursTill++) {
        minutesTill -= 60;
    }
    return { 'hours': hoursTill, 'minutes': minutesTill };
}

function projectedDeliveryDate(deliveryTime, state) {
    return deliveryTime.add('d', config.leadtime[state]).format("dddd, MMM Do");
}

jQuery(document).ready(function($) {
    if ($(config.stockSelector).text() == config.inStockText || config.inStockText === true) {
        var deadline = shippingDeadline(config.deadline.hour, config.deadline.minute);
        var timeLeft = timeUntilDeadline(deadline);

        $("#ship-time").html('Order within ' + timeLeft.hours + ' hrs ' + timeLeft.minutes + ' mins to ship ' + shipDay(deadline) + '');

        $.get("http://ipinfo.io", function(data){;}, "jsonp")
        .then(function(data) {
            if (data.country == "US") {
                $("#delivery-date").html('Est Delivery: ' + projectedDeliveryDate(deadline, data.region) + '
 to ' + data.region + ' via ' + config.shipMethodName  + '');
            }
        });
    }
});
<commit_msg>make sure state isnt null<commit_after>var config = {

    // UTC timezone offset for your stores location
    timezone: '-0500',

    // Enter your shipping cutoff deadline in 24 hour format
    deadline: {
        hour: 16,
        minute: 0
    },

    // Name of estimated shipping method
    shipMethodName: 'Fixed Rate Shipping',

    // This is to make sure we only show transit info if an item is in stock!
    stockSelector  : 'p.availability',  // selector for element that notifies stock status
    inStockText    : 'in-stock',        // in stock text
    // inStockText : true,              // use this if you want to show for all items

    // If you want to estimate delivery dates enter estimated lead time for each state in days
    leadtime: {
        'Alabama': 2,
        'Alaska': 6,
        'Arizona': 5,
        'Arkansas': 2,
        'California': 5,
        'Colorado': 4,
        'Connnecticut': 3,
        'Delaware': 3,
        'Florida': 1,
        'Georgia': 2,
        'Hawaii': 7,
        'Idaho': 5,
        'Illinois': 3,
        'Indiana': 2,
        'Iowa': 3,
        'Kansas': 3,
        'Kentucky': 2,
        'Louisiana': 2,
        'Maine': 3,
        'Maryland': 3,
        'Massachusetts': 3,
        'Michigan': 3,
        'Minnesota': 3,
        'Mississippi': 2,
        'Missouri': 3,
        'Montana': 5,
        'Nebraska': 4,
        'Nevada': 5,
        'New Hampshire': 3,
        'New Jersey': 3,
        'New Mexico': 4,
        'New York': 4,
        'North Carolina': 2,
        'North Dakota': 5,
        'Ohio': 2,
        'Oklahoma': 3,
        'Oregon': 5,
        'Pennsylvania': 3,
        'Rhode Island': 3,
        'South Carolina': 2,
        'South Dakota': 4,
        'Tennessee': 2,
        'Texas': 3,
        'Utah': 5,
        'Vermont': 3,
        'Virginia': 2,
        'Washington': 5,
        'West Virginia': 2,
        'Wisconsin': 3,
        'Wyoming': 5
    }
};

function isWeekday(moment) {
    return (moment.day() !== 0 && moment.day() !== 7) ? true : false;
}

function shipDay(deadline) {
    return (moment().zone(config.timezone).isSame(deadline, "d")) ? "Today" : deadline.format("dddd");
}

function shippingDeadline(hour, minute) {
    var deadline = moment().zone(config.timezone).hour(hour).minute(minute).second(0);
    if (moment().zone(config.timezone).hour() >= deadline.hour() && isWeekday(moment().zone(config.timezone))) {
        deadline.add('h', 24);
    }
    if (!isWeekday(deadline)) {
        return (deadline.day() === 0) ? deadline.add('h', 24) : deadline.add('h', 48);
    } else {
        return deadline;
    }
}

function timeUntilDeadline(deadline) {
    var minutesTill = Math.abs(moment().zone(config.timezone).diff(deadline, 'm'));
    for(var hoursTill = 0; minutesTill >= 60; hoursTill++) {
        minutesTill -= 60;
    }
    return { 'hours': hoursTill, 'minutes': minutesTill };
}

function projectedDeliveryDate(deliveryTime, state) {
    return deliveryTime.add('d', config.leadtime[state]).format("dddd, MMM Do");
}

jQuery(document).ready(function($) {
    if ($(config.stockSelector).text() == config.inStockText || config.inStockText === true) {
        var deadline = shippingDeadline(config.deadline.hour, config.deadline.minute);
        var timeLeft = timeUntilDeadline(deadline);

        $("#ship-time").html('Order within ' + timeLeft.hours + ' hrs ' + timeLeft.minutes + ' mins to ship ' + shipDay(deadline) + '');

        $.get("http://ipinfo.io", function(data){;}, "jsonp")
        .then(function(data) {
            if (data.country == "US" && data.region != null) {
                $("#delivery-date").html('Est Delivery: ' + projectedDeliveryDate(deadline, data.region) + '
 to ' + data.region + ' via ' + config.shipMethodName  + '');
            }
        });
    }
});
<|endoftext|>


<commit_before>import React, { cloneElement, Component, PropTypes } from 'react';
import styles from 'remotedev-app/lib/styles';
import enhance from 'remotedev-app/lib/hoc';
import DevTools from 'remotedev-app/lib/containers/DevTools';
import MonitorSelector from 'remotedev-app/lib/components/MonitorSelector';
import Instances from 'remotedev-app/lib/components/Instances';
import Button from 'remotedev-app/lib/components/Button';
import DispatcherButton from 'remotedev-app/lib/components/buttons/DispatcherButton';
import SliderButton from 'remotedev-app/lib/components/buttons/SliderButton';
import ImportButton from 'remotedev-app/lib/components/buttons/ImportButton';
import ExportButton from 'remotedev-app/lib/components/buttons/ExportButton';
import TestGenerator from 'remotedev-app/lib/components/TestGenerator';
import SettingsIcon from 'react-icons/lib/md/settings';
import LeftIcon from 'react-icons/lib/md/border-left';
import RightIcon from 'react-icons/lib/md/border-right';
import BottomIcon from 'react-icons/lib/md/border-bottom';
import RemoteIcon from 'react-icons/lib/go/radio-tower';

const monitorPosition = location.hash;

let monitor;
let selectedTemplate;
let testTemplates;

// Electron: Not supported some chrome.* API
if (chrome.storage.local) {
  chrome.storage.local.get({
    ['monitor' + monitorPosition]: 'InspectorMonitor',
    'test-templates': null,
    'test-templates-sel': null
  }, options => {
    monitor = options['monitor' + monitorPosition];
    selectedTemplate = options['test-templates-sel'];
    testTemplates = options['test-templates'];
  });
} else {
  monitor = localStorage.getItem('monitor' + monitorPosition]) || 'InspectorMonitor';
  selectedTemplate = localStorage.getItem('test-templates-sel');
  testTemplates = localStorage.getItem('test-templates');
}

@enhance
export default class App extends Component {
  static propTypes = {
    store: PropTypes.object
  };

  state = {
    monitor,
    instance: 'auto',
    dispatcherIsOpen: false,
    sliderIsOpen: false
  };

  componentWillMount() {
    this.testComponent = (
      <TestGenerator
        testTemplates={testTemplates} selectedTemplate={selectedTemplate} useCodemirror
      />
    );
  }

  handleSelectMonitor = (event, index, value) => {
    this.setState({ monitor: value });

    // Electron: Not supported some chrome.* API
    if (chrome.storage.local) {
      chrome.storage.local.set({ ['monitor' + monitorPosition]: value });
    } else {
      localStorage.setItem('monitor' + monitorPosition, value);
    }
  };

  handleSelectInstance = (event, index, value) => {
    this.setState({ instance: value });
    this.props.store.setInstance(value);
  };

  openWindow = (position) => {
    chrome.runtime.sendMessage({ type: 'OPEN', position });
  };

  toggleDispatcher = () => {
    this.setState({ dispatcherIsOpen: !this.state.dispatcherIsOpen });
  };

  toggleSlider = () => {
    this.setState({ sliderIsOpen: !this.state.sliderIsOpen });
  };

  render() {
    const { store } = this.props;
    const instances = store.instances;
    const { instance, monitor } = this.state;
    const onElectron = navigator.userAgent.indexOf('Electron') !== -1;
    return (

            <MonitorSelector selected={this.state.monitor} onSelect={this.handleSelectMonitor}/>
            {instances &&
              <Instances instances={instances} onSelect={this.handleSelectInstance} selected={instance} />
            }

        <DevTools
          monitor={monitor}
          store={store}
          testComponent={this.testComponent}
          key={`${monitor}-${instance}`}
        />
        {this.state.sliderIsOpen &&

          <DevTools monitor="SliderMonitor" store={store} key={`Slider-${instance}`} />

}
        {this.state.dispatcherIsOpen &&
          <DevTools monitor="DispatchMonitor"
            store={store} dispatchFn={store.dispatch}
            key={`Dispatch-${instance}`}
          />
        }

          {!onElectron && monitorPosition !== 'left' &&
            <Button
              Icon={LeftIcon}
              onClick={() => { this.openWindow('left'); }}
            />
          }
          {!onElectron && monitorPosition !== 'right' &&
            <Button
              Icon={RightIcon}
              onClick={() => { this.openWindow('right'); }}
            />
          }
          {!onElectron && monitorPosition !== 'bottom' &&
            <Button
              Icon={BottomIcon}
              onClick={() => { this.openWindow('bottom'); }}
            />
          }
          <DispatcherButton
            dispatcherIsOpen={this.state.dispatcherIsOpen} onClick={this.toggleDispatcher}
          />
          <SliderButton isOpen={this.state.sliderIsOpen} onClick={this.toggleSlider} />
          <ImportButton importState={store.liftedStore.importState} />
          <ExportButton exportState={store.liftedStore.getState} />
          {!onElectron &&
            <Button
              Icon={RemoteIcon}
              onClick={() => { this.openWindow('remote'); }}
            >Remote</Button>
          }
          {chrome.runtime.openOptionsPage &&
            <Button
              Icon={SettingsIcon}
              onClick={() => { chrome.runtime.openOptionsPage(); }}
            >Settings</Button>
          }

    );
  }
}
<commit_msg>Fix eslint error. Closes #150<commit_after>import React, { cloneElement, Component, PropTypes } from 'react';
import styles from 'remotedev-app/lib/styles';
import enhance from 'remotedev-app/lib/hoc';
import DevTools from 'remotedev-app/lib/containers/DevTools';
import MonitorSelector from 'remotedev-app/lib/components/MonitorSelector';
import Instances from 'remotedev-app/lib/components/Instances';
import Button from 'remotedev-app/lib/components/Button';
import DispatcherButton from 'remotedev-app/lib/components/buttons/DispatcherButton';
import SliderButton from 'remotedev-app/lib/components/buttons/SliderButton';
import ImportButton from 'remotedev-app/lib/components/buttons/ImportButton';
import ExportButton from 'remotedev-app/lib/components/buttons/ExportButton';
import TestGenerator from 'remotedev-app/lib/components/TestGenerator';
import SettingsIcon from 'react-icons/lib/md/settings';
import LeftIcon from 'react-icons/lib/md/border-left';
import RightIcon from 'react-icons/lib/md/border-right';
import BottomIcon from 'react-icons/lib/md/border-bottom';
import RemoteIcon from 'react-icons/lib/go/radio-tower';

const monitorPosition = location.hash;

let initialMonitor;
let selectedTemplate;
let testTemplates;

// Electron: Not supported some chrome.* API
if (chrome.storage.local) {
  chrome.storage.local.get({
    ['monitor' + monitorPosition]: 'InspectorMonitor',
    'test-templates': null,
    'test-templates-sel': null
  }, options => {
    initialMonitor = options['monitor' + monitorPosition];
    selectedTemplate = options['test-templates-sel'];
    testTemplates = options['test-templates'];
  });
} else {
  initialMonitor = localStorage.getItem('monitor' + monitorPosition) || 'InspectorMonitor';
  selectedTemplate = localStorage.getItem('test-templates-sel');
  testTemplates = localStorage.getItem('test-templates');
}

@enhance
export default class App extends Component {
  static propTypes = {
    store: PropTypes.object
  };

  state = {
    monitor: initialMonitor,
    instance: 'auto',
    dispatcherIsOpen: false,
    sliderIsOpen: false
  };

  componentWillMount() {
    this.testComponent = (
      <TestGenerator
        testTemplates={testTemplates} selectedTemplate={selectedTemplate} useCodemirror
      />
    );
  }

  handleSelectMonitor = (event, index, value) => {
    this.setState({ monitor: value });

    // Electron: Not supported some chrome.* API
    if (chrome.storage.local) {
      chrome.storage.local.set({ ['monitor' + monitorPosition]: value });
    } else {
      localStorage.setItem('monitor' + monitorPosition, value);
    }
  };

  handleSelectInstance = (event, index, value) => {
    this.setState({ instance: value });
    this.props.store.setInstance(value);
  };

  openWindow = (position) => {
    chrome.runtime.sendMessage({ type: 'OPEN', position });
  };

  toggleDispatcher = () => {
    this.setState({ dispatcherIsOpen: !this.state.dispatcherIsOpen });
  };

  toggleSlider = () => {
    this.setState({ sliderIsOpen: !this.state.sliderIsOpen });
  };

  render() {
    const { store } = this.props;
    const instances = store.instances;
    const { instance, monitor } = this.state;
    const onElectron = navigator.userAgent.indexOf('Electron') !== -1;
    return (

            <MonitorSelector selected={this.state.monitor} onSelect={this.handleSelectMonitor}/>
            {instances &&
              <Instances instances={instances} onSelect={this.handleSelectInstance} selected={instance} />
            }

        <DevTools
          monitor={monitor}
          store={store}
          testComponent={this.testComponent}
          key={`${monitor}-${instance}`}
        />
        {this.state.sliderIsOpen &&

          <DevTools monitor="SliderMonitor" store={store} key={`Slider-${instance}`} />

}
        {this.state.dispatcherIsOpen &&
          <DevTools monitor="DispatchMonitor"
            store={store} dispatchFn={store.dispatch}
            key={`Dispatch-${instance}`}
          />
        }

          {!onElectron && monitorPosition !== 'left' &&
            <Button
              Icon={LeftIcon}
              onClick={() => { this.openWindow('left'); }}
            />
          }
          {!onElectron && monitorPosition !== 'right' &&
            <Button
              Icon={RightIcon}
              onClick={() => { this.openWindow('right'); }}
            />
          }
          {!onElectron && monitorPosition !== 'bottom' &&
            <Button
              Icon={BottomIcon}
              onClick={() => { this.openWindow('bottom'); }}
            />
          }
          <DispatcherButton
            dispatcherIsOpen={this.state.dispatcherIsOpen} onClick={this.toggleDispatcher}
          />
          <SliderButton isOpen={this.state.sliderIsOpen} onClick={this.toggleSlider} />
          <ImportButton importState={store.liftedStore.importState} />
          <ExportButton exportState={store.liftedStore.getState} />
          {!onElectron &&
            <Button
              Icon={RemoteIcon}
              onClick={() => { this.openWindow('remote'); }}
            >Remote</Button>
          }
          {chrome.runtime.openOptionsPage &&
            <Button
              Icon={SettingsIcon}
              onClick={() => { chrome.runtime.openOptionsPage(); }}
            >Settings</Button>
          }

    );
  }
}
<|endoftext|>