<commit_before>const FileException = Jymfony.Component.HttpFoundation.File.Exception.FileException;
const File = Jymfony.Component.HttpFoundation.File.File;
const Response = Jymfony.Component.HttpFoundation.Response;

/**
 * Represents an HTTP response delivering a file.
 *
 * @memberOf Jymfony.Component.HttpFoundation
 */
class BinaryFileResponse extends Response {
    /**
     * Constructor.
     *
     * @param {Jymfony.Component.HttpFoundation.File.File|string} file
     * @param {int} [status = Jymfony.Component.HttpFoundation.Response.HTTP_OK]
     * @param {Object} [headers = {}]
     * @param {boolean} [isPublic = true]
     * @param {string} [contentDisposition = null]
     * @param {boolean} [autoEtag = false]
     * @param {boolean} [autoLastModified = true]
     */
    __construct(file, status = __self.HTTP_OK, headers = {}, isPublic = true, contentDisposition = null, autoEtag = false, autoLastModified = true) {
        super.__construct('', status, headers);

        if (isPublic) {
            this.setPublic();
        }

        return this.setFile(file, contentDisposition, autoEtag, autoLastModified);
    }

    /**
     * @inheritdoc
     */
    set content(content) {
        super.content = content;
    }

    /**
     * @inheritdoc
     */
    get content() {
        return (res) => {
            const stream = this._file.content;
            const p = new Promise(((resolve, reject) => {
                stream.on('end', resolve);
                stream.on('error', reject);
            }));

            stream.pipe(res, { end: false });
            return p;
        };
    }

    /**
     * @inheritdoc
     *
     * @param {Jymfony.Component.HttpFoundation.Request} request
     */
    prepare(request) {
        if (! this.headers.has('Content-Type')) {
            this.headers.set('Content-Type', this._file.getMimeType() || 'application/octet-stream');
        }

        if ('HTTP/1.0' !== request.server.get('SERVER_PROTOCOL')) {
            this.protocolVersion = '1.1';
        }

        this._ensureIEOverSSLCompatibility(request);
        const fileSize = this._file.size;

        if (false === fileSize) {
            return this;
        }

        this.headers.set('Content-Length', fileSize);

        return this;
    }

    /**
     * Sets the file to stream.
     *
     * @param {Jymfony.Component.HttpFoundation.File.File|string} file
     * @param {string} contentDisposition
     * @param {boolean} autoEtag
     * @param {boolean} autoLastModified
     *
     * @returns {Promise<Jymfony.Component.HttpFoundation.BinaryFileResponse>}
     *
     * @throws {Jymfony.Component.HttpFoundation.File.Exception.FileException}
     */
    async setFile(file, contentDisposition = null, autoEtag = false, autoLastModified = true) {
        if (! (file instanceof File)) {
            file = new File(file.toString());
        }

        if (! file.isReadable) {
            throw new FileException('File must be readable');
        }

        /**
         * @type {Jymfony.Component.HttpFoundation.File.File}
         * @private
         */
        this._file = file;

        if (autoEtag) {
            await this.setAutoEtag();
        }

        if (autoLastModified) {
            this.setAutoLastModified();
        }

        if (contentDisposition) {
            this.setContentDisposition(contentDisposition);
        }

        return this;
    }

    /**
     * Automatically sets the ETag header according to the checksum of the file.
     *
     * @returns {Promise<Jymfony.Component.HttpFoundation.BinaryFileResponse>}
     */
    async setAutoEtag() {
        const p = new Promise((resolve, reject) => {
            const hash = crypto.createHash('sha256');
            const stream = this._file.content;

            stream.on('error', err => reject(err));
            stream.on('data', chunk => hash.update(chunk));
            stream.on('end', () => resolve(hash.digest('base64')));
        });

        this.setEtag(await p);

        return this;
    }

    /**
     * Automatically sets the Last-Modified header according the file modification date.
     *
     * @returns {Jymfony.Component.HttpFoundation.BinaryFileResponse}
     */
    setAutoLastModified() {
        this.lastModified = this._file.modificationTime.timestamp;

        return this;
    }

    /**
     * Sets the Content-Disposition header with the given filename.
     *
     * @param {string} disposition ResponseHeaderBag::DISPOSITION_INLINE or ResponseHeaderBag::DISPOSITION_ATTACHMENT
     * @param {string} filename Optionally use this UTF-8 encoded filename instead of the real name of the file
     * @param {string} filenameFallback A fallback filename, containing only ASCII characters. Defaults to an automatically encoded filename
     *
     * @returns {Jymfony.Component.HttpFoundation.BinaryFileResponse}
     */
    setContentDisposition(disposition, filename = '', filenameFallback = '') {
        if ('' === filename) {
            filename = this._file.fileName;
        }

        if ('' === filenameFallback && (! filename.match(/^[\x20-\x7e]*$/) || -1 !== filename.indexOf('%'))) {
            filenameFallback = filename.replace(/([^\x20-\x7e]|%)/g, '_');
        }

        const dispositionHeader = this.headers.makeDisposition(disposition, filename, filenameFallback);
        this.headers.set('Content-Disposition', dispositionHeader);

        return this;
    }
}

module.exports = BinaryFileResponse;
<commit_msg>[HttpFoundation] make _file property protected in BinaryFileResponse<commit_after>const FileException = Jymfony.Component.HttpFoundation.File.Exception.FileException;
const File = Jymfony.Component.HttpFoundation.File.File;
const Response = Jymfony.Component.HttpFoundation.Response;

/**
 * Represents an HTTP response delivering a file.
 *
 * @memberOf Jymfony.Component.HttpFoundation
 */
class BinaryFileResponse extends Response {
    /**
     * Constructor.
     *
     * @param {Jymfony.Component.HttpFoundation.File.File|string} file
     * @param {int} [status = Jymfony.Component.HttpFoundation.Response.HTTP_OK]
     * @param {Object} [headers = {}]
     * @param {boolean} [isPublic = true]
     * @param {string} [contentDisposition = null]
     * @param {boolean} [autoEtag = false]
     * @param {boolean} [autoLastModified = true]
     */
    __construct(file, status = __self.HTTP_OK, headers = {}, isPublic = true, contentDisposition = null, autoEtag = false, autoLastModified = true) {
        super.__construct('', status, headers);

        if (isPublic) {
            this.setPublic();
        }

        return this.setFile(file, contentDisposition, autoEtag, autoLastModified);
    }

    /**
     * @inheritdoc
     */
    set content(content) {
        super.content = content;
    }

    /**
     * @inheritdoc
     */
    get content() {
        return (res) => {
            const stream = this._file.content;
            const p = new Promise(((resolve, reject) => {
                stream.on('end', resolve);
                stream.on('error', reject);
            }));

            stream.pipe(res, { end: false });
            return p;
        };
    }

    /**
     * @inheritdoc
     *
     * @param {Jymfony.Component.HttpFoundation.Request} request
     */
    prepare(request) {
        if (! this.headers.has('Content-Type')) {
            this.headers.set('Content-Type', this._file.getMimeType() || 'application/octet-stream');
        }

        if ('HTTP/1.0' !== request.server.get('SERVER_PROTOCOL')) {
            this.protocolVersion = '1.1';
        }

        this._ensureIEOverSSLCompatibility(request);
        const fileSize = this._file.size;

        if (false === fileSize) {
            return this;
        }

        this.headers.set('Content-Length', fileSize);

        return this;
    }

    /**
     * Sets the file to stream.
     *
     * @param {Jymfony.Component.HttpFoundation.File.File|string} file
     * @param {string} contentDisposition
     * @param {boolean} autoEtag
     * @param {boolean} autoLastModified
     *
     * @returns {Promise<Jymfony.Component.HttpFoundation.BinaryFileResponse>}
     *
     * @throws {Jymfony.Component.HttpFoundation.File.Exception.FileException}
     */
    async setFile(file, contentDisposition = null, autoEtag = false, autoLastModified = true) {
        if (! (file instanceof File)) {
            file = new File(file.toString());
        }

        if (! file.isReadable) {
            throw new FileException('File must be readable');
        }

        /**
         * @type {Jymfony.Component.HttpFoundation.File.File}
         *
         * @protected
         */
        this._file = file;

        if (autoEtag) {
            await this.setAutoEtag();
        }

        if (autoLastModified) {
            this.setAutoLastModified();
        }

        if (contentDisposition) {
            this.setContentDisposition(contentDisposition);
        }

        return this;
    }

    /**
     * Automatically sets the ETag header according to the checksum of the file.
     *
     * @returns {Promise<Jymfony.Component.HttpFoundation.BinaryFileResponse>}
     */
    async setAutoEtag() {
        const p = new Promise((resolve, reject) => {
            const hash = crypto.createHash('sha256');
            const stream = this._file.content;

            stream.on('error', err => reject(err));
            stream.on('data', chunk => hash.update(chunk));
            stream.on('end', () => resolve(hash.digest('base64')));
        });

        this.setEtag(await p);

        return this;
    }

    /**
     * Automatically sets the Last-Modified header according the file modification date.
     *
     * @returns {Jymfony.Component.HttpFoundation.BinaryFileResponse}
     */
    setAutoLastModified() {
        this.lastModified = this._file.modificationTime.timestamp;

        return this;
    }

    /**
     * Sets the Content-Disposition header with the given filename.
     *
     * @param {string} disposition ResponseHeaderBag::DISPOSITION_INLINE or ResponseHeaderBag::DISPOSITION_ATTACHMENT
     * @param {string} filename Optionally use this UTF-8 encoded filename instead of the real name of the file
     * @param {string} filenameFallback A fallback filename, containing only ASCII characters. Defaults to an automatically encoded filename
     *
     * @returns {Jymfony.Component.HttpFoundation.BinaryFileResponse}
     */
    setContentDisposition(disposition, filename = '', filenameFallback = '') {
        if ('' === filename) {
            filename = this._file.fileName;
        }

        if ('' === filenameFallback && (! filename.match(/^[\x20-\x7e]*$/) || -1 !== filename.indexOf('%'))) {
            filenameFallback = filename.replace(/([^\x20-\x7e]|%)/g, '_');
        }

        const dispositionHeader = this.headers.makeDisposition(disposition, filename, filenameFallback);
        this.headers.set('Content-Disposition', dispositionHeader);

        return this;
    }
}

module.exports = BinaryFileResponse;
<|endoftext|>


<commit_before>export default `
03-10-2017 - Added in Mastery tracking and suggestions, along with updating the Maintainer and Configuration sections (by anomoly)
24-09-2017 - Added additional Windwalker spells / cooldowns along with a simple Hit Combo track (by anomoly)
22-07-2017 - Added basic Windwalker Monk support. (by AttilioLH)
`;
<commit_msg>[Windwalker] Updated Changelog<commit_after>export default `
14-10-2017 - Updated Cast Efficiency - should now track all spells individually correct, but tierbonuses and Serenity CDR is not accounted for (by Juko)
13-10-2017 - Added Combo Breaker tracking and suggestions (by Juko)
03-10-2017 - Added in Mastery tracking and suggestions, along with updating the Maintainer and Configuration sections (by anomoly)
24-09-2017 - Added additional Windwalker spells / cooldowns along with a simple Hit Combo track (by anomoly)
22-07-2017 - Added basic Windwalker Monk support. (by AttilioLH)
`;
<|endoftext|>


<commit_before>/*global defineSuite*/
defineSuite([
         'Core/EllipseGeometry',
         'Core/Cartesian3',
         'Core/Cartographic',
         'Core/Ellipsoid',
         'Core/VertexFormat'
     ], function(
             EllipseGeometry,
         Cartesian3,
         Cartographic,
         Ellipsoid,
         VertexFormat) {
    "use strict";
    /*global jasmine,describe,xdescribe,it,xit,expect,beforeEach,afterEach,beforeAll,afterAll,spyOn,runs,waits,waitsFor*/

    it('throws without a center', function() {
        expect(function() {
            return new EllipseGeometry({
                semiMajorAxis : 1.0,
                semiMinorAxis : 1.0
            });
        }).toThrow();
    });

    it('throws without a semiMajorAxis', function() {
        expect(function() {
            return new EllipseGeometry({
                center : Ellipsoid.WGS84.cartographicToCartesian(new Cartographic()),
                semiMinorAxis : 1.0
            });
        }).toThrow();
    });

    it('throws without a semiMinorAxis', function() {
        expect(function() {
            return new EllipseGeometry({
                center : Ellipsoid.WGS84.cartographicToCartesian(new Cartographic()),
                semiMajorAxis : 1.0
            });
        }).toThrow();
    });

    it('throws with a negative axis', function() {
        expect(function() {
            return new EllipseGeometry({
                center : Ellipsoid.WGS84.cartographicToCartesian(new Cartographic()),
                semiMajorAxis : 1.0,
                semiMinorAxis : -1.0
            });
        }).toThrow();
    });

    it('throws with a negative granularity', function() {
        expect(function() {
            return new EllipseGeometry({
                center : Ellipsoid.WGS84.cartographicToCartesian(new Cartographic()),
                semiMajorAxis : 1.0,
                semiMinorAxis : 1.0,
                granularity : -1.0
            });
        }).toThrow();
    });

    it('computes positions', function() {
        var ellipsoid = Ellipsoid.WGS84;
        var m = new EllipseGeometry({
            vertexFormat : VertexFormat.POSITION_ONLY,
            ellipsoid : ellipsoid,
            center : ellipsoid.cartographicToCartesian(new Cartographic()),
            granularity : 0.75,
            semiMajorAxis : 1.0,
            semiMinorAxis : 1.0
        });

        expect(m.attributes.position.values.length).toEqual(3 * 24);
        expect(m.indices.length).toEqual(3 * 34);
        expect(m.boundingSphere.radius).toEqual(1);
    });

    it('compute all vertex attributes', function() {
        var ellipsoid = Ellipsoid.WGS84;
        var m = new EllipseGeometry({
            vertexFormat : VertexFormat.ALL,
            ellipsoid : ellipsoid,
            center : ellipsoid.cartographicToCartesian(new Cartographic()),
            granularity : 0.75,
            semiMajorAxis : 1.0,
            semiMinorAxis : 1.0
        });

        expect(m.attributes.position.values.length).toEqual(3 * 24);
        expect(m.attributes.st.values.length).toEqual(2 * 24);
        expect(m.attributes.normal.values.length).toEqual(3 * 24);
        expect(m.attributes.tangent.values.length).toEqual(3 * 24);
        expect(m.attributes.binormal.values.length).toEqual(3 * 24);
        expect(m.indices.length).toEqual(3 * 34);
    });
});
<commit_msg>tests<commit_after>/*global defineSuite*/
defineSuite([
         'Core/EllipseGeometry',
         'Core/Cartesian3',
         'Core/Cartographic',
         'Core/Ellipsoid',
         'Core/VertexFormat'
     ], function(
             EllipseGeometry,
         Cartesian3,
         Cartographic,
         Ellipsoid,
         VertexFormat) {
    "use strict";
    /*global jasmine,describe,xdescribe,it,xit,expect,beforeEach,afterEach,beforeAll,afterAll,spyOn,runs,waits,waitsFor*/

    it('throws without a center', function() {
        expect(function() {
            return new EllipseGeometry({
                semiMajorAxis : 1.0,
                semiMinorAxis : 1.0
            });
        }).toThrow();
    });

    it('throws without a semiMajorAxis', function() {
        expect(function() {
            return new EllipseGeometry({
                center : Ellipsoid.WGS84.cartographicToCartesian(new Cartographic()),
                semiMinorAxis : 1.0
            });
        }).toThrow();
    });

    it('throws without a semiMinorAxis', function() {
        expect(function() {
            return new EllipseGeometry({
                center : Ellipsoid.WGS84.cartographicToCartesian(new Cartographic()),
                semiMajorAxis : 1.0
            });
        }).toThrow();
    });

    it('throws with a negative axis', function() {
        expect(function() {
            return new EllipseGeometry({
                center : Ellipsoid.WGS84.cartographicToCartesian(new Cartographic()),
                semiMajorAxis : 1.0,
                semiMinorAxis : -1.0
            });
        }).toThrow();
    });

    it('throws with a negative granularity', function() {
        expect(function() {
            return new EllipseGeometry({
                center : Ellipsoid.WGS84.cartographicToCartesian(new Cartographic()),
                semiMajorAxis : 1.0,
                semiMinorAxis : 1.0,
                granularity : -1.0
            });
        }).toThrow();
    });

    it('computes positions', function() {
        var ellipsoid = Ellipsoid.WGS84;
        var m = new EllipseGeometry({
            vertexFormat : VertexFormat.POSITION_ONLY,
            ellipsoid : ellipsoid,
            center : ellipsoid.cartographicToCartesian(new Cartographic()),
            granularity : 0.75,
            semiMajorAxis : 1.0,
            semiMinorAxis : 1.0
        });

        expect(m.attributes.position.values.length).toEqual(3 * 24);
        expect(m.indices.length).toEqual(3 * 34);
        expect(m.boundingSphere.radius).toEqual(1);
    });

    it('compute all vertex attributes', function() {
        var ellipsoid = Ellipsoid.WGS84;
        var m = new EllipseGeometry({
            vertexFormat : VertexFormat.ALL,
            ellipsoid : ellipsoid,
            center : ellipsoid.cartographicToCartesian(new Cartographic()),
            granularity : 0.75,
            semiMajorAxis : 1.0,
            semiMinorAxis : 1.0
        });

        expect(m.attributes.position.values.length).toEqual(3 * 24);
        expect(m.attributes.st.values.length).toEqual(2 * 24);
        expect(m.attributes.normal.values.length).toEqual(3 * 24);
        expect(m.attributes.tangent.values.length).toEqual(3 * 24);
        expect(m.attributes.binormal.values.length).toEqual(3 * 24);
        expect(m.indices.length).toEqual(3 * 34);
    });

    it('computes positions extruded', function() {
        var ellipsoid = Ellipsoid.WGS84;
        var m = new EllipseGeometry({
            vertexFormat : VertexFormat.POSITION_ONLY,
            ellipsoid : ellipsoid,
            center : ellipsoid.cartographicToCartesian(new Cartographic()),
            granularity : 0.75,
            semiMajorAxis : 1.0,
            semiMinorAxis : 1.0,
            extrudedHeight: 50000
        });

        expect(m.attributes.position.values.length).toEqual(3 * (24 + 10) * 2);
        expect(m.indices.length).toEqual(3 * (34 + 10) * 2);
    });

    it('compute all vertex attributes extruded', function() {
        var ellipsoid = Ellipsoid.WGS84;
        var m = new EllipseGeometry({
            vertexFormat : VertexFormat.ALL,
            ellipsoid : ellipsoid,
            center : ellipsoid.cartographicToCartesian(new Cartographic()),
            granularity : 0.75,
            semiMajorAxis : 1.0,
            semiMinorAxis : 1.0,
            extrudedHeight: 50000
        });

        expect(m.attributes.position.values.length).toEqual(3 * (24 + 10) * 2);
        expect(m.attributes.st.values.length).toEqual(2 * (24 + 10) * 2);
        expect(m.attributes.normal.values.length).toEqual(3 * (24 + 10) * 2);
        expect(m.attributes.tangent.values.length).toEqual(3 * (24 + 10) * 2);
        expect(m.attributes.binormal.values.length).toEqual(3 * (24 + 10) * 2);
        expect(m.indices.length).toEqual(3 * (34 + 10) * 2);
    });
});
<|endoftext|>


<commit_before>casper.test.begin('Page loads without error', 7, function suite (test) {

	casper.start('example/index.html', function() {
		/* 1 */
	    test.assertTitle('WebGL Heatmap Leaflet Plugin', 'title is correct');
	    /* 2 */
	    test.assertExists('#mapid', 'mapid exists');
	    /* 3 */
	    test.assertEvalEquals(function () {
		    return L.version;
	    }, '1.0.3', 'leaflet version is correct');

	    /* 4 */
	    test.assertEvalEquals(function () {
	    	window.meters = L.webGLHeatmap({
				    size: 50,
				    units: 'm',
				    alphaRange: 0.4
				});
	    	meters.setData( dataPoints );
	    	map.addLayer(meters);
		    return meters._scalem( L.latLng(meters.data[0]) );
	    }, 2, 'meters scale is correct');

   	    /* 5 */
   	    test.assertEvalEquals(function () {
   	    	map.setZoom(14);
   		    return meters._scalem( L.latLng(meters.data[0]) );
   	    }, 8, 'meters scale is correct after zoom');

	    /* 5 */
	    test.assertEvalEquals(function () {
	    	window.pixels = L.webGLHeatmap({
				    size: 50,
				    units: 'px',
				    alphaRange: 0.5
				});
	    	pixels.setData( dataPoints );
	    	map.addLayer(pixels);
		    return pixels._scalepx( L.latLng(pixels.data[0]) );
	    }, 50, 'pixel scale is correct');

   	    /* 5 */
   	    test.assertEvalEquals(function () {
   	    	map.setZoom(4);
   		    return pixels._scalepx( L.latLng(pixels.data[0]) );
   	    }, 50, 'pixel scale is correct after zoom');
	});

	casper.on("page.error", function(msg, trace) {
		if (msg === 'WebGL not supported') {
			// we know
			return;
		}
		this.echo("Error: " + msg, "ERROR");
	});

	casper.test.on("fail", function(failure) {
	    failure.message = "Message : " + failure.message + "\nLine : "+ failure.line + "\nCode : " + failure.lineContents;
	});

	casper.run(function () {
		test.done();
	});
});
<commit_msg>testing fixing casperjs<commit_after>casper.test.begin('Page loads without error', 7, function suite(test) {

    casper.on('page.initialized', function() {
        this.evaluate(function() {
            var isFunction = function(o) {
                return typeof o == 'function';
            };

            var bind,
                slice = [].slice,
                proto = Function.prototype,
                featureMap;

            featureMap = {
                'function-bind': 'bind'
            };

            function has(feature) {
                var prop = featureMap[feature];
                return isFunction(proto[prop]);
            }

            // check for missing features
            if (!has('function-bind')) {
                // adapted from Mozilla Developer Network example at
                // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind
                bind = function bind(obj) {
                    var args = slice.call(arguments, 1),
                        self = this,
                        nop = function() {},
                        bound = function() {
                            return self.apply(this instanceof nop ? this : (obj || {}), args.concat(slice.call(arguments)));
                        };
                    nop.prototype = this.prototype || {}; // Firefox cries sometimes if prototype is undefined
                    bound.prototype = new nop();
                    return bound;
                };
                proto.bind = bind;
            }
        });
    });

    casper.start('example/index.html', function() {
        /* 1 */
        test.assertTitle('WebGL Heatmap Leaflet Plugin', 'title is correct');
        /* 2 */
        test.assertExists('#mapid', 'mapid exists');
        /* 3 */
        test.assertEvalEquals(function() {
            return L.version;
        }, '1.0.3', 'leaflet version is correct');

        /* 4 */
        test.assertEvalEquals(function() {
            window.meters = L.webGLHeatmap({
                size: 50,
                units: 'm',
                alphaRange: 0.4
            });
            meters.setData(dataPoints);
            map.addLayer(meters);
            return meters._scalem(L.latLng(meters.data[0]));
        }, 2, 'meters scale is correct');

        /* 5 */
        test.assertEvalEquals(function() {
            map.setZoom(14);
            return meters._scalem(L.latLng(meters.data[0]));
        }, 8, 'meters scale is correct after zoom');

        /* 5 */
        test.assertEvalEquals(function() {
            window.pixels = L.webGLHeatmap({
                size: 50,
                units: 'px',
                alphaRange: 0.5
            });
            pixels.setData(dataPoints);
            map.addLayer(pixels);
            return pixels._scalepx(L.latLng(pixels.data[0]));
        }, 50, 'pixel scale is correct');

        /* 5 */
        test.assertEvalEquals(function() {
            map.setZoom(4);
            return pixels._scalepx(L.latLng(pixels.data[0]));
        }, 50, 'pixel scale is correct after zoom');
    });

    casper.on("page.error", function(msg, trace) {
        if (msg === 'WebGL not supported') {
            // we know
            return;
        }
        this.echo("Error: " + msg, "ERROR");
    });

    casper.test.on("fail", function(failure) {
        failure.message = "Message : " + failure.message + "\nLine : " + failure.line + "\nCode : " + failure.lineContents;
    });

    casper.run(function() {
        test.done();
    });
});
<|endoftext|>


<commit_before>var eventId = 'altconf15';

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

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

  }
};

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

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

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

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

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

var allTrackColors = {
	'default': [43,81,160,1]
};

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

function parseSpeaker(dict) {
	var speaker = dict;

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

	return speaker;
}

function parseSession(dict) {
	var session = dict;

	if (session['title'] == "") {
		return null;
	};
	if (session['id'] == null || session['id'] == undefined || session['id'].trim() == "") {
		return null;
	}

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

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

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

	if (session['track']) {
		if (session['track']['id'] != '') {
			allTracks[session['track']['id']] = session['track'];
		} else {
			allTracks['WWDC'] = {"id": "WWDC", "label_en": "WWDC", "color": [108, 108, 108, 1]}
			session['track'] = allTracks['WWDC'];
		}
	}

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

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

	return session;
};

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

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

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

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

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

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

			// Additional Data
			// -----------
			var index = 0;
			for (var key in allRooms) {
				var value = allRooms[key];
				value['order_index'] = index;
				index++;
			}

			for (var key in allTracks) {
				var value = allTracks[key];
				var color = allTrackColors[key];
				if (!color) {
					color = allTrackColors['default'];
				}
				value['color'] = color;
			}

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

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

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

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

		}
	);
}

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

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

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

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

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

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

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

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

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

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

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

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

	return new Date(dateString);

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

function parseSpeakerLinks(linkUrls, linkLabels) {

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

	var links = [];

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

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

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

		links.push(linkItem);
	}

	return links;
}

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

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

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

  }
};

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

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

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

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

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

var allTrackColors = {
	'default': [43,81,160,1]
};

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

function parseSpeaker(dict) {
	var speaker = dict;

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

	return speaker;
}

function parseTrack(value) {
	if (value['label_en'].match(/Engineering \(has code\) - Advanced Level/i)) {
		value['label_en'] = "Engineering (Advanced)";
	} else if (value['label_en'].match(/Engineering \(has code\) - Beginner level/i)) {
		value['label_en'] = "Engineering (Beginner)";
	}
	var color = allTrackColors[value['id']];
	if (!color) {
		color = allTrackColors['default'];
	}
	value['color'] = color;

	if (value['id'] != '') {
		allTracks[value['id']] = value;
	} else {
		allTracks['WWDC'] = {"id": "WWDC", "label_en": "WWDC", "color": [108, 108, 108, 1]}
		value = allTracks['WWDC'];
	}

	console.log(value);
	return value;
}

function parseSession(dict) {
	var session = dict;

	if (session['title'] == "") {
		return null;
	};
	if (session['id'] == null || session['id'] == undefined || session['id'].trim() == "") {
		return null;
	}

	if (!session['format']) {
		session['format'] = allFormats['talk'];
	}

	if (!session['lang']) {
		session['lang'] = allLanguages['en'];
	}
	if (session['begin'] != null && session['end'] != null) {

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

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

	if (session['track']) {
		session['track'] = parseTrack(session['track']);
	}
	if (!session['level']) {
		session['level'] = allLevels['intermediate'];
		if (session['track']['label_en'] &&
			session['track']['label_en'].match(/Beginner/))
		{
				session['level'] = 	allLevels['beginner'];

		} else if (session['track']['label_en'] &&
			session['track']['label_en'].match(/Advanced/))
		{
				session['level'] = 	allLevels['advanced'];
		}
	}

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

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

	return session;
};

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

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

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

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

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

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

			// Additional Data
			// -----------
			var index = 0;
			for (var key in allRooms) {
				var value = allRooms[key];
				value['order_index'] = index;
				index++;
			}

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

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

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

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

		}
	);
}

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

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

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

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

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

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

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

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

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

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

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

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

	return new Date(dateString);

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

function parseSpeakerLinks(linkUrls, linkLabels) {

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

	var links = [];

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

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

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

		links.push(linkItem);
	}

	return links;
}

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


<commit_before>/*
 * Script that generates a random question. Parameter should
 * be a list of integers that refer to indeces in the CSV file
 * over which the user would like to be tested.
 */
function QuestionGenerator(list) {

  // The array of questions
  var musicSnippets = makeMusicSnippets(list);

  function makeMusicSnippets(array) {
    var ms = [];
    for (var i = 0; i < array.length; i++) {
      console.log(data[list[i]][0] + " " + data[list[i]][1]);
      ms.push(new MusicSnippet(data[list[i]][2], data[list[i]][0],
        data[list[i]][1]));
    }
    return ms;
  }

  /*
   * Picks a random MusicSnippet from the array.
   */
  this.getNextQuestion = function() {
    return musicSnippets[Math.floor(Math.random() * musicSnippets.length)];
  }

  /*
   * Picks a random sonority from the user's list of selected
   * sonorities. When called, sets the answer for this question.
   * Also initializes type.
   */
  function selectRandomSonority(sonorities) {
    var i = Math.floor(Math.random() * sonorities.length);
    type = sonorities[i].type1;
    return sonorities[i].type2;
  }

}
<commit_msg>removed an extraneous method from QuestionGenerator<commit_after>/*
 * Script that generates a random question. Parameter should
 * be a list of integers that refer to indeces in the CSV file
 * over which the user would like to be tested.
 */
function QuestionGenerator(list) {

  // The array of questions
  var musicSnippets = makeMusicSnippets(list);

  function makeMusicSnippets(array) {
    var ms = [];
    for (var i = 0; i < array.length; i++) {
      console.log(data[list[i]][0] + " " + data[list[i]][1]);
      ms.push(new MusicSnippet(data[list[i]][2], data[list[i]][0],
        data[list[i]][1]));
    }
    return ms;
  }

  /*
   * Picks a random MusicSnippet from the array.
   */
  this.getNextQuestion = function() {
    return musicSnippets[Math.floor(Math.random() * musicSnippets.length)];
  }
}
<|endoftext|>


<commit_before>angular.module('ssHome').controller('HomeCtrl', function($scope, ssYoutubeFeed) {

    ssYoutubeFeed.getRecent(3).then(function(videos) {
        $scope.videos = videos;
    });

    $scope.contacts = [
        {
            id: 1694010657,
            name: 'Securitas Protector',
            title: 'Alliance Exec.'
        },
        {
            id: 92940230,
            name: 'Xeron Vann',
            title: 'Diplomacy Director'
        },
        {
            id: 335025985,
            name: 'Ganja Lotus',
            title: 'Military Director'
        },
		{
            id: 93670403,
            name: 'Gav Davies',
            title: 'Co. Military Director'
        },
        {
            id: 618402478,
            name: 'Reuben Blackfeather',
            title: 'IT Director'
        }
    ];

    $scope.corporations = [
        {
            id: 98007439,
            name: 'Ethereal Vengeance'
        },
        {
            id: 98019237,
            name: 'Gallente Volunteer Defense Forces'
        },
        {
            id: 98161636,
            name: 'Physics Says No'
        },
        {
            id: 98041262,
            name: 'Community against Justice'
        },
        {
            id: 851230678,
            name: 'The New Era'
        },
        {
            id: 555073675,
            name: 'The Green Cross'
        },
		{
			id: 98020221,
			name: 'Shattered Void'
		},
        {
            id: 692190945,
            name: 'Shinigami Miners'
        },
        {
            id: 98097817,
            name: 'Concordiat'
        },
        {
            id: 98127611,
            name: 'Quantum Reality R n D'
        },
        {
            id: 98285822,
            name: 'Anime Masters'
        },
        {
            id: 98124232,
            name: 'Caveat Emptor Technologies LP'
        },
        {
            id: 98309567,
            name: 'Aerospace Fencing'
        },
        {
            id: 98197104,
            name: 'Concordiat Industries'
        },
        {
            id: 98189045,
            name: 'Pax Capital'
        },
        {
            id: 98319878,
            name: 'Only Fools and Horses'
        },
        {
            id: 98320400,
            name: 'Discharging Demeanor Solutions'
        },
        {
            id: 98339677,
            name: 'The Contract Bureau'
        }
    ];

});<commit_msg>Update HomeCtrl.js<commit_after>angular.module('ssHome').controller('HomeCtrl', function($scope, ssYoutubeFeed) {

    ssYoutubeFeed.getRecent(3).then(function(videos) {
        $scope.videos = videos;
    });

    $scope.contacts = [
        {
            id: 1694010657,
            name: 'Securitas Protector',
            title: 'Alliance Exec.'
        },
        {
            id: 92988604,
            name: 'Aben Sokoln',
            title: '2nd in command'
        },
        {
            id: 92940230,
            name: 'Xeron Vann',
            title: 'Diplomacy Director'
        },
        {
            id: 92507729,
            name: 'Dex Thiesant',
            title: 'IT Director'
        }
    ];

    $scope.corporations = [
        {
            id: 98041262,
            name: 'Community against Justice'
        },
        {
            id: 851230678,
            name: 'The New Era'
        },
        {
            id: 555073675,
            name: 'The Green Cross'
        },
        {
            id: 692190945,
            name: 'Shinigami Miners'
        },
        {
            id: 98097817,
            name: 'Concordiat'
        },
        {
            id: 98189045,
            name: 'Pax Capital'
        }
    ];

});
<|endoftext|>


<commit_before>/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */
/* eslint no-console: "off" */
/* eslint global-require: "off" */
/* eslint no-param-reassign: "off" */

const getOutput = require('./get-output');
const fs = require('./utils/fs-extra');
const { COLOR_PROPS, ICON_PROPS, ROUTER_PROPS, ACTIONS_PROPS } = require('./ts-extend-props');

const extendMap = {
  colorProps: COLOR_PROPS,
  iconProps: ICON_PROPS,
  routerProps: ROUTER_PROPS,
  actionsProps: ACTIONS_PROPS,
};

function generateComponentEvents(fileContent) {
  if (!fileContent.includes('emits: [')) return '';
  let events;
  fileContent.replace(/emits: \[([^\]]*)\]/, (str, eventsString) => {
    events = eventsString
      .split(',')
      .map((ev) => ev.replace(/'/g, '').trim())
      .filter((ev) => !!ev);
  });
  if (events && events.length) {
    return [
      `(${events.map((ev) => `"${ev}"`).join(' | ')})[]`,
      `${events.map((ev) => `"${ev}"`).join(' | ')}`,
    ].join(',\n  ');
  }
  return '';
}

function generateComponentProps(fileContent) {
  // eslint-disable-next-line
  let propsContent = fileContent.match(/props\:\ {([^ъ]*)},\n  (emits|setup)/g);
  if (propsContent && propsContent[0]) {
    propsContent = propsContent[0]
      .replace('props: {', '')
      .replace('},\n  emits', '')
      .replace('},\n  setup', '');
  }
  if (!propsContent) {
    return '';
  }
  const props = [];
  const extendWith = [];
  (propsContent.match(/\.\.\.([a-zA-Z]*)/g) || []).forEach((prop) => {
    extendWith.push(prop.replace('...', ''));
  });

  const getType = (str) => {
    if (str.includes('['))
      str = str
        // eslint-disable-next-line
        .replace(/[\[\]]*/g, '')
        .split(', ')
        .map((t) => t.replace(',', ''));
    else if (str.includes(',')) str = str.replace(',', '');
    return str;
  };

  // eslint-disable-next-line
  propsContent.replace(/\n    ([a-zA-Z0-9]*): ([\[\], a-zA-Z0-9]*)/g, (str, name, type) => {
    if (!type) return;
    props.push({ name, type: getType(type) });
  });

  // eslint-disable-next-line
  propsContent.replace(/\n    ([a-zA-Z0-9]*): {([^ъ^\}]*)}/g, (str1, name, typeObj) => {
    const prop = { name };
    // eslint-disable-next-line
    typeObj.replace(/type: ([\[\], a-zA-Z0-9]*)/, (str2, typeStr) => {
      prop.type = getType(typeStr);
    });
    if (typeObj.includes('default: ')) {
      prop.default = typeObj.split('default: ')[1].replace(',\n', '').trim();
    }
    props.push(prop);
  });

  const toVueType = (type) => {
    if (type === 'string') return 'String';
    if (type === 'boolean') return 'Boolean';
    if (type === 'number') return 'Number';
    if (type === 'any') return 'Object';
    return '';
  };

  extendWith.forEach((extendGroup) => {
    extendMap[extendGroup]
      .trim()
      .split('\n')
      .forEach((propsRow) => {
        // eslint-disable-next-line
        let [name, type] = propsRow.replace(/;/, '').split('?: ');
        if (type.includes(' | ')) {
          type = type.split(' | ').map(toVueType);
        } else {
          type = toVueType(type);
        }
        props.push({ name, type });
      });
  });

  const getVueType = ({ type }) => {
    const plainType = (t) => {
      if (t === 'String') return 'StringConstructor';
      if (t === 'Boolean') return 'BooleanConstructor';
      if (t === 'Number') return 'NumberConstructor';
      if (t === 'Function') return 'FunctionConstructor';
      if (t === 'Object') return 'ObjectConstructor';
      if (t === 'Array') return 'ArrayConstructor';
      return 'any';
    };
    if (typeof type === 'string') {
      return plainType(type);
    }
    return `PropType<${type.map(plainType).join(' | ')}>`;
  };

  const getVueDefault = (prop) => {
    if ('default' in prop) {
      const value = prop.default;
      if (value.includes("'")) return 'string';
      if (value === 'true' || value === 'false') return 'boolean';
      if (!Number.isNaN(parseFloat(value))) return 'number';
      return `${prop.default}`;
    }
    return '';
  };

  return props
    .map((prop) => {
      const defaultValue = getVueDefault(prop);
      return `
    ${prop.name}: {
      type: ${getVueType(prop)};${defaultValue ? `\n      default: ${defaultValue};` : ''}
    }`;
    })
    .join(',\n');
}

function generateComponentTypings(componentName, fileContent) {
  if (componentName.includes('Swiper') || componentName.includes('Skeleton')) return fileContent;
  return `
import { ComponentOptionsMixin, DefineComponent, PropType } from 'vue';
// IMPORTS

declare const ${componentName}: DefineComponent<
  {
    // PROPS
  },
  () => JSX.Element,
  unknown,
  {},
  {},
  ComponentOptionsMixin,
  ComponentOptionsMixin,
  // EVENTS
>;

export default ${componentName};
  `
    .replace('// IMPORTS', '')
    .replace('// PROPS', generateComponentProps(fileContent))
    .replace('// EVENTS', generateComponentEvents(fileContent));
}

function buildTypings(cb) {
  const output = `${getOutput()}/vue`;

  const files = fs.readdirSync('src/vue/components').filter((file) => file.indexOf('.d.ts') < 0);
  const componentImports = [];
  const componentExports = [];

  files.forEach((fileName) => {
    const componentName = fileName
      .replace('.vue', '')
      .split('-')
      .map((word) => word[0].toUpperCase() + word.substr(1))
      .join('');
    const fileBase = fileName.replace('.vue', '');
    componentImports.push(`import f7${componentName} from './components/${fileBase}';`);
    componentExports.push(`f7${componentName}`);

    const typingsContent = generateComponentTypings(
      componentName,
      fs.readFileSync(`src/vue/components/${fileName}`, 'utf-8'),
    );

    fs.writeFileSync(`${output}/components/${fileBase}/${fileBase}.d.ts`, typingsContent);
  });

  const mainTypings = fs
    .readFileSync('src/vue/framework7-vue.d.ts', 'utf-8')
    .replace('// IMPORT_COMPONENTS', componentImports.join('\n'))
    .replace('// EXPORT_COMPONENTS', `export { ${componentExports.join(', ')} }`);

  fs.writeFileSync(`${output}/framework7-vue.d.ts`, mainTypings);

  if (cb) cb();
}

module.exports = buildTypings;
<commit_msg>fix(vue): fix vue typings for Swiper and Skeleton Elements<commit_after>/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */
/* eslint no-console: "off" */
/* eslint global-require: "off" */
/* eslint no-param-reassign: "off" */

const getOutput = require('./get-output');
const fs = require('./utils/fs-extra');
const { COLOR_PROPS, ICON_PROPS, ROUTER_PROPS, ACTIONS_PROPS } = require('./ts-extend-props');

const extendMap = {
  colorProps: COLOR_PROPS,
  iconProps: ICON_PROPS,
  routerProps: ROUTER_PROPS,
  actionsProps: ACTIONS_PROPS,
};

function generateComponentEvents(fileContent) {
  if (!fileContent.includes('emits: [')) return '';
  let events;
  fileContent.replace(/emits: \[([^\]]*)\]/, (str, eventsString) => {
    events = eventsString
      .split(',')
      .map((ev) => ev.replace(/'/g, '').trim())
      .filter((ev) => !!ev);
  });
  if (events && events.length) {
    return [
      `(${events.map((ev) => `"${ev}"`).join(' | ')})[]`,
      `${events.map((ev) => `"${ev}"`).join(' | ')}`,
    ].join(',\n  ');
  }
  return '';
}

function generateComponentProps(fileContent) {
  // eslint-disable-next-line
  let propsContent = fileContent.match(/props\:\ {([^ъ]*)},\n  (emits|setup)/g);
  if (propsContent && propsContent[0]) {
    propsContent = propsContent[0]
      .replace('props: {', '')
      .replace('},\n  emits', '')
      .replace('},\n  setup', '');
  }
  if (!propsContent) {
    return '';
  }
  const props = [];
  const extendWith = [];
  (propsContent.match(/\.\.\.([a-zA-Z]*)/g) || []).forEach((prop) => {
    extendWith.push(prop.replace('...', ''));
  });

  const getType = (str) => {
    if (str.includes('['))
      str = str
        // eslint-disable-next-line
        .replace(/[\[\]]*/g, '')
        .split(', ')
        .map((t) => t.replace(',', ''));
    else if (str.includes(',')) str = str.replace(',', '');
    return str;
  };

  // eslint-disable-next-line
  propsContent.replace(/\n    ([a-zA-Z0-9]*): ([\[\], a-zA-Z0-9]*)/g, (str, name, type) => {
    if (!type) return;
    props.push({ name, type: getType(type) });
  });

  // eslint-disable-next-line
  propsContent.replace(/\n    ([a-zA-Z0-9]*): {([^ъ^\}]*)}/g, (str1, name, typeObj) => {
    const prop = { name };
    // eslint-disable-next-line
    typeObj.replace(/type: ([\[\], a-zA-Z0-9]*)/, (str2, typeStr) => {
      prop.type = getType(typeStr);
    });
    if (typeObj.includes('default: ')) {
      prop.default = typeObj.split('default: ')[1].replace(',\n', '').trim();
    }
    props.push(prop);
  });

  const toVueType = (type) => {
    if (type === 'string') return 'String';
    if (type === 'boolean') return 'Boolean';
    if (type === 'number') return 'Number';
    if (type === 'any') return 'Object';
    return '';
  };

  extendWith.forEach((extendGroup) => {
    extendMap[extendGroup]
      .trim()
      .split('\n')
      .forEach((propsRow) => {
        // eslint-disable-next-line
        let [name, type] = propsRow.replace(/;/, '').split('?: ');
        if (type.includes(' | ')) {
          type = type.split(' | ').map(toVueType);
        } else {
          type = toVueType(type);
        }
        props.push({ name, type });
      });
  });

  const getVueType = ({ type }) => {
    const plainType = (t) => {
      if (t === 'String') return 'StringConstructor';
      if (t === 'Boolean') return 'BooleanConstructor';
      if (t === 'Number') return 'NumberConstructor';
      if (t === 'Function') return 'FunctionConstructor';
      if (t === 'Object') return 'ObjectConstructor';
      if (t === 'Array') return 'ArrayConstructor';
      return 'any';
    };
    if (typeof type === 'string') {
      return plainType(type);
    }
    return `PropType<${type.map(plainType).join(' | ')}>`;
  };

  const getVueDefault = (prop) => {
    if ('default' in prop) {
      const value = prop.default;
      if (value.includes("'")) return 'string';
      if (value === 'true' || value === 'false') return 'boolean';
      if (!Number.isNaN(parseFloat(value))) return 'number';
      return `${prop.default}`;
    }
    return '';
  };

  return props
    .map((prop) => {
      const defaultValue = getVueDefault(prop);
      return `
    ${prop.name}: {
      type: ${getVueType(prop)};${defaultValue ? `\n      default: ${defaultValue};` : ''}
    }`;
    })
    .join(',\n');
}

function generateComponentTypings(componentName, fileContent) {
  if (componentName.includes('Swiper') || componentName.includes('Skeleton')) {
    return fileContent.replace('<script>', '').replace('</script>', '');
  }

  return `
import { ComponentOptionsMixin, DefineComponent, PropType } from 'vue';
// IMPORTS

declare const ${componentName}: DefineComponent<
  {
    // PROPS
  },
  () => JSX.Element,
  unknown,
  {},
  {},
  ComponentOptionsMixin,
  ComponentOptionsMixin,
  // EVENTS
>;

export default ${componentName};
  `
    .replace('// IMPORTS', '')
    .replace('// PROPS', generateComponentProps(fileContent))
    .replace('// EVENTS', generateComponentEvents(fileContent));
}

function buildTypings(cb) {
  const output = `${getOutput()}/vue`;

  const files = fs.readdirSync('src/vue/components').filter((file) => file.indexOf('.d.ts') < 0);
  const componentImports = [];
  const componentExports = [];

  files.forEach((fileName) => {
    const componentName = fileName
      .replace('.vue', '')
      .split('-')
      .map((word) => word[0].toUpperCase() + word.substr(1))
      .join('');
    const fileBase = fileName.replace('.vue', '');
    componentImports.push(`import f7${componentName} from './components/${fileBase}';`);
    componentExports.push(`f7${componentName}`);

    const typingsContent = generateComponentTypings(
      componentName,
      fs.readFileSync(`src/vue/components/${fileName}`, 'utf-8'),
    );

    fs.writeFileSync(`${output}/components/${fileBase}/${fileBase}.d.ts`, typingsContent);
  });

  const mainTypings = fs
    .readFileSync('src/vue/framework7-vue.d.ts', 'utf-8')
    .replace('// IMPORT_COMPONENTS', componentImports.join('\n'))
    .replace('// EXPORT_COMPONENTS', `export { ${componentExports.join(', ')} }`);

  fs.writeFileSync(`${output}/framework7-vue.d.ts`, mainTypings);

  if (cb) cb();
}

module.exports = buildTypings;
<|endoftext|>


<commit_before>#!/usr/bin/env node
const {readdirSync: readDir} = require('fs');
const {rm, exec} = require('shelljs');
const {last, each} = require('lodash');

const {log} = console;

const prefix = '../src/client/assets/images/coins';
const output = '../build/client/images/coins';

const files = readDir('../src/client/assets/images/coins').filter((f) => last(f.split('.')) === 'svg');

log('Exporting image files to 14px png.');
each(files, (image) => {
  log(`Exporting ${image}`);
  const name = image.split('.svg')[0];
  exec(`node ../node_modules/.bin/svgexport ${prefix}/${image} ${output}/${name}-14.png 14:`);
});
<commit_msg>Change output<commit_after>#!/usr/bin/env node
const {readdirSync: readDir} = require('fs');
const {rm, exec} = require('shelljs');
const {last, each} = require('lodash');

const {log} = console;

const prefix = '../src/client/assets/images/coins';
const output = '../src/client/assets/images/coins';

const files = readDir('../src/client/assets/images/coins').filter((f) => last(f.split('.')) === 'svg');

log('Exporting image files to 14px png.');
each(files, (image) => {
  log(`Exporting ${image}`);
  const name = image.split('.svg')[0];
  exec(`node ../node_modules/.bin/svgexport ${prefix}/${image} ${output}/${name}-14.png 14:`);
});
<|endoftext|>


<commit_before>var defaultFilterList = [
  {
    name: "Default - China",
    isEnabled: true,
    isEditable: false,
    activePage: null,
    rules: [
      {
        src: "ajax.googleapis.com/ajax/*",
        dest: "http://ajax.useso.com/ajax/*",
      },
      {
        src: "fonts.googleapis.com/*",
        dest: "http://fonts.useso.com/*",
      },
      {
        src: "https://*fastly.net*",
        dest: "http://*fastly.net*",
      },
      {
        src: "*google.com*",
        dest: "",
      },
      {
        src: "*googleapis.*",
        dest: "",
      },
      {
        src: "*googlecode.*",
        dest: "",
      },
      {
        src: "*facebook.*",
        dest: "",
      },
      {
        src: "*twitter.*",
        dest: "",
      },
      {
        src: "*youtube.*",
        dest: "",
      },
      {
        src: "*youtu.be*",
        dest: "",
      },
    ]
  }
];
<commit_msg>Edit default list to avoid violations of content security policy<commit_after>var defaultFilterList = [
  {
    name: "Default - China",
    isEnabled: true,
    isEditable: false,
    activePage: null,
    rules: [
      {
        src: "ajax.googleapis.com/ajax/*",
        dest: "cdnjs.cloudflare.com/ajax/*",
      },
      {
        src: "fonts.googleapis.com/*",
        dest: "fonts.useso.com/*",
      },
      {
        src: "https://*fastly.net*",
        dest: "http://*fastly.net*",
      },
      {
        src: "*google.com*",
        dest: "",
      },
      {
        src: "*googleapis.*",
        dest: "",
      },
      {
        src: "*googlecode.*",
        dest: "",
      },
      {
        src: "*facebook.*",
        dest: "",
      },
      {
        src: "*twitter.*",
        dest: "",
      },
      {
        src: "*youtube.*",
        dest: "",
      },
      {
        src: "*youtu.be*",
        dest: "",
      },
    ]
  }
];
<|endoftext|>


<commit_before>import path from 'path';
import glob from 'glob-promise';
import fsp from 'fs-promise';
import yargs from 'yargs';
import _ from 'lodash';

const argv = yargs
  .usage('Usage: generate_constant.js source')
  .demand(1, 'must provide source')
  .argv;

main(argv._[0]).catch(e => console.error(e.stack));

async function main(pattern) {
  const files = await glob(pattern);
  for (let file of files) {
    const fp = path.join(process.cwd(), file);
    const dir = path.dirname(fp);
    const dest = path.join(dir, `${path.basename(fp, path.extname(fp))}.py`);
    const content = require(fp);
    await processBody(content, fp, dest);
  }
}

async function processBody(content, src, dest) {
  const fd = await fsp.open(dest, 'w');
  const emit = (...argv) => fsp.write(fd, ...argv);
  await emitBanner(emit, src);
  for (const [name, val] of _.toPairs(content)) {
    if (typeof val === 'object' && val.__exportToPython === false) {
      continue;
    }
    await emitVariable(emit, name, val);
  }
  await fsp.close(fd);
}

async function emitBanner(emit, srcFilePath) {
  const relativePath = path.relative('', srcFilePath);
  await emit(`
    """
    !!! WARNING !!!
    This file is auto-generated from \`${relativePath}\`.
    Don't edit directly, otherwise it will be overwritten.
    Run \`npm run generate:constant\` to update this file.
    """
  `.split('\n').map(l => l.trim()).join('\n'));
  await emit('\n');
}

async function emitVariable(emit, name, v) {
  await emit(`${name} = `);
  await emitLiteralOrObject(emit, v);
  await emit(`\n\n`);
}

async function emitLiteralOrObject(emit, v) {
  if (typeof v === 'number') {
    await emit(String(v));
    return;
  }
  if (typeof v === 'boolean') {
    await emit(_.capitalize(String(v)));
    return;
  }
  if (typeof v === 'string') {
    await emit(JSON.stringify(v));
    return;
  }
  if (Array.isArray(v)) {
    await emit('[');
    for (let item of v) {
      await emitLiteralOrObject(emit, item);
    }
    await emit(']');
    return;
  }
  if (v instanceof Object) {
    const { __intKey, ...val } = v;
    await emit('{\n');
    for (const [ name, item ] of _.entries(val)) {
      if (__intKey) {
        await emit(`${name}: `);
      } else {
        await emit(`${JSON.stringify(name)}: `);
      }
      await emitLiteralOrObject(emit, item);
      await emit(',\n');
    }
    await emit('}');
    return;
  }
  // null / undefined / cannot recognize
  await emit('Null');
}
<commit_msg>emit OrderedDict<commit_after>import path from 'path';
import glob from 'glob-promise';
import fsp from 'fs-promise';
import yargs from 'yargs';
import _ from 'lodash';

const argv = yargs
  .usage('Usage: generate_constant.js source')
  .demand(1, 'must provide source')
  .argv;

main(argv._[0]).catch(e => console.error(e.stack));

async function main(pattern) {
  const files = await glob(pattern);
  for (let file of files) {
    const fp = path.join(process.cwd(), file);
    const dir = path.dirname(fp);
    const dest = path.join(dir, `${path.basename(fp, path.extname(fp))}.py`);
    const content = require(fp);
    await processBody(content, fp, dest);
  }
}

async function processBody(content, src, dest) {
  const fd = await fsp.open(dest, 'w');
  const emit = (...argv) => fsp.write(fd, ...argv);
  await emitBanner(emit, src);
  for (const [name, val] of _.toPairs(content)) {
    if (typeof val === 'object' && val.__exportToPython === false) {
      continue;
    }
    await emitVariable(emit, name, val);
  }
  await fsp.close(fd);
}

async function emitBanner(emit, srcFilePath) {
  const relativePath = path.relative('', srcFilePath);
  await emit(`
    """
    !!! WARNING !!!
    This file is auto-generated from \`${relativePath}\`.
    Don't edit directly, otherwise it will be overwritten.
    Run \`npm run generate:constant\` to update this file.
    """

    import collections
  `.split('\n').map(l => l.trim()).join('\n'));
  await emit('\n');
}

async function emitVariable(emit, name, v) {
  await emit(`${name} = `);
  await emitLiteralOrObject(emit, v);
  await emit(`\n\n`);
}

async function emitLiteralOrObject(emit, v) {
  if (typeof v === 'number') {
    await emit(String(v));
    return;
  }
  if (typeof v === 'boolean') {
    await emit(_.capitalize(String(v)));
    return;
  }
  if (typeof v === 'string') {
    await emit(JSON.stringify(v));
    return;
  }
  if (Array.isArray(v)) {
    await emit('[');
    for (let item of v) {
      await emitLiteralOrObject(emit, item);
      await emit(',');
    }
    await emit(']');
    return;
  }
  if (v instanceof Object) {
    const { __intKey, ...val } = v;
    await emit('collections.OrderedDict([\n');
    for (const [ name, item ] of _.entries(val)) {
      await emit('(')
      if (__intKey) {
        await emit(name);
      } else {
        await emit(JSON.stringify(name));
      }
      await emit(', ');
      await emitLiteralOrObject(emit, item);
      await emit('),\n');
    }
    await emit('])');
    return;
  }
  // null / undefined / cannot recognize
  await emit('Null');
}
<|endoftext|>


<commit_before>if (typeof JSON !== 'object') {
    JSON = {};
}
(function () {
    'use strict';
    function f(n) {
        return n < 10 ? '0' + n : n;
    }

    if (typeof Date.prototype.toJSON !== 'function') {
        Date.prototype.toJSON = function (key) {
            return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' +
                f(this.getUTCMonth() + 1) + '-' +
                f(this.getUTCDate()) + 'T' +
                f(this.getUTCHours()) + ':' +
                f(this.getUTCMinutes()) + ':' +
                f(this.getUTCSeconds()) + 'Z' : null;
        };
        String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (key) {
            return this.valueOf();
        };
    }
    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = {'\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\\': '\\\\'}, rep;

    function quote(string) {
        escapable.lastIndex = 0;
        return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
            var c = meta[a];
            return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
        }) + '"' : '"' + string + '"';
    }

    function str(key, holder) {
        var i, k, v, length, mind = gap, partial, value = holder[key];
        if (value && typeof value === 'object' && typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }
        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }
        switch (typeof value) {
            case'string':
                return quote(value);
            case'number':
                return isFinite(value) ? String(value) : 'null';
            case'boolean':
            case'null':
                return String(value);
            case'object':
                if (!value) {
                    return'null';
                }
                gap += indent;
                partial = [];
                if (Object.prototype.toString.apply(value) === '[object Array]') {
                    length = value.length;
                    for (i = 0; i < length; i += 1) {
                        partial[i] = str(i, value) || 'null';
                    }
                    v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']';
                    gap = mind;
                    return v;
                }
                if (rep && typeof rep === 'object') {
                    length = rep.length;
                    for (i = 0; i < length; i += 1) {
                        if (typeof rep[i] === 'string') {
                            k = rep[i];
                            v = str(k, value);
                            if (v) {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
                } else {
                    for (k in value) {
                        if (Object.prototype.hasOwnProperty.call(value, k)) {
                            v = str(k, value);
                            if (v) {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
                }
                v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}';
                gap = mind;
                return v;
        }
    }

    if (typeof JSON.stringify !== 'function') {
        JSON.stringify = function (value, replacer, space) {
            var i;
            gap = '';
            indent = '';
            if (typeof space === 'number') {
                for (i = 0; i < space; i += 1) {
                    indent += ' ';
                }
            } else if (typeof space === 'string') {
                indent = space;
            }
            rep = replacer;
            if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) {
                throw new Error('JSON.stringify');
            }
            return str('', {'': value});
        };
    }
    if (typeof JSON.parse !== 'function') {
        JSON.parse = function (text, reviver) {
            var j;

            function walk(holder, key) {
                var k, v, value = holder[key];
                if (value && typeof value === 'object') {
                    for (k in value) {
                        if (Object.prototype.hasOwnProperty.call(value, k)) {
                            v = walk(value, k);
                            if (v !== undefined) {
                                value[k] = v;
                            } else {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }

            text = String(text);
            cx.lastIndex = 0;
            if (cx.test(text)) {
                text = text.replace(cx, function (a) {
                    return'\\u' +
                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }
            if (/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
                j = eval('(' + text + ')');
                return typeof reviver === 'function' ? walk({'': j}, '') : j;
            }
            throw new SyntaxError('JSON.parse');
        };
    }
}());

var _expectedIndex = 0,//expected index of next command
    _actualIndex=0,//actual index of next command by reading commandPath
    _exp,//expression to be eval'ed
    _result;

var Log = (function () {
    var forceFlush = [],
        N = 16384,
        i = N;
    while (i--) {
        forceFlush[i] = "*";
    }
    forceFlush = forceFlush.join('');

    function log_json(object, flush)
    {
        UIALogger.logMessage("OUTPUT_JSON:\n"+JSON.stringify(object)+"\nEND_OUTPUT");
        if (flush) {
            UIALogger.logMessage(forceFlush);
        }
    }

    return {
        result: function (status, data, flush) {
            log_json({"status": status, "value": data, "index":_actualIndex}, flush)
        },
        output: function (msg, flush) {
            log_json({"output": msg,"last_index":_actualIndex}, flush);
        }
    };
})();

function findAlertViewText(alert) {
    if (!alert) {
        return false;
    }
    var txt = alert.name(),
        txts;
    if (txt == null) {
        txts = alert.staticTexts();
        if (txts != null && txts.length > 0) {
            txt = txts[0].name();
        }
    }
    return txt;
}

function isLocationPrompt(alert) {
    var exps = [
            ["OK", /vil bruge din aktuelle placering/],
            ["OK", /Would Like to Use Your Current Location/],
            ["Ja", /Darf (?:.)+ Ihren aktuellen Ort verwenden/],
            ["OK", /Would Like to Send You Notifications/],
            ["Allow", /access your location/],
            ["OK", /Would Like to Access Your Photos/],
            ["OK", /Would Like to Access Your Contacts/],
            ["OK", /запрашивает разрешение на использование Ващей текущей пгеопозиции/]
        ],
        ans, exp,
        txt;

    txt = findAlertViewText(alert);
    Log.output({"output":"alert: "+txt}, true);
    for (var i = 0; i < exps.length; i++) {
        ans = exps[i][0];
        exp = exps[i][1];
        if (exp.test(txt)) {
            return ans;
        }
    }
    return false;
}

UIATarget.onAlert = function (alert) {
    Log.output({"output":"on alert"}, true);
    var target = UIATarget.localTarget();
    target.pushTimeout(10);
    function attemptTouchOKOnLocation(retry_count) {
        retry_count = retry_count || 0;
        if (retry_count >= 5) {
            Log.output("Maxed out retry (5) - unable to dismiss location dialog.");
            return;
        }
        try {
            var answer = isLocationPrompt(alert);
            if (answer) {
                alert.buttons()[answer].tap();
            }
        }
        catch (e) {
            Log.output("Exception while trying to touch alert dialog. Retrying...");
            if (e && typeof e.toString == 'function') {
                Log.output(e.toString());
            }
            target.delay(1);
            attemptTouchOKOnLocation(retry_count + 1);
        }
    }

    attemptTouchOKOnLocation(0);
    target.popTimeout();
    return true;
};

var target = null,
    failureMessage = null,
    preferences = null,
    __calabashRequest = "__calabashRequest",
    __calabashResponse = "__calabashResponse",
    _sanitize = function(val) {
        if (typeof val === 'undefined' || val === null || val instanceof UIAElementNil) {
            return ":nil";
        }
        if (typeof val === 'string' || val instanceof String) {
            return val;
        }
        var arrVal = null, i, N;
        if (val instanceof Array || val instanceof UIAElementArray) {
            arrVal = [];
            for (i=0,N=val.length;i<N;i++) {
                arrVal[i] = _sanitize(val[i]);
            }
            return arrVal;
        }
        if (val instanceof UIAElement) {
            return val.toString();
        }
        var objVal = null, p;
        if (typeof val == 'object') {
            objVal = {};
            for (p in val) {
                objVal[p] = _sanitize(val[p]);
            }
            return objVal;
        }
        return val;
    },
    _response = function(response) {
        var sanitized = _sanitize(response),
            i = 0,
            MAX_TRIES=120,
            res;

        for (i=0; i<MAX_TRIES; i+=1) {
            UIALogger.logMessage("Write result...");
            target.frontMostApp().preferencesValueForKey(__calabashResponse);
            UIALogger.logMessage("Last response..."+__calabashResponse);
            target.frontMostApp().setPreferencesValueForKey(sanitized, __calabashResponse);
            res = target.frontMostApp().preferencesValueForKey(__calabashResponse);
            UIALogger.logMessage("Next response..."+__calabashResponse);
            if (res && res['index'] == sanitized['index']) {
                UIALogger.logMessage("Storage succeeded: "+ res['index']);
                return;
            } else {
                UIALogger.logMessage("Storage failed: "+ res + " Retrying...");
                target.delay(0.2);
            }
        }
        throw new Error("Unable to write to preferences");

    },
    _success = function(result,index) {

        _response({"status":'success', "value":result, "index": index});

    },
    _failure = function(err, index) {
        _response({"status":'error',
                   "value":err.toString(),
                   "backtrace":(err.stack ? err.stack.toString() : ""),
                   "index":index});
    },
    _resetCalabashPreferences = function () {
        //Implementation is weird but reading pref values seems to have side effects
        //also deleting a key seemed to require writing 0 and then null :)
        var app = UIATarget.localTarget().frontMostApp();
        app.preferencesValueForKey(__calabashRequest);
        app.preferencesValueForKey(__calabashResponse);
        app.setPreferencesValueForKey(0, __calabashResponse);
        app.setPreferencesValueForKey(null, __calabashResponse);
        app.setPreferencesValueForKey(0, __calabashRequest);
        app.setPreferencesValueForKey(null, __calabashRequest);
    };

_resetCalabashPreferences();
Log.result('success',true,true);
target = UIATarget.localTarget();
while (true) {
    try {
        preferences = target.frontMostApp().preferencesValueForKey(__calabashRequest);
    } catch (e) {
        Log.output("Unable to read preferences..."+ e.toString());
        target.delay(0.5);
        continue;
    }

    if (!preferences) {
        target.delay(0.2);
        continue;
    }

    _actualIndex = preferences['index'];
    if (!isNaN(_actualIndex) && _actualIndex >= _expectedIndex) {
        UIATarget.localTarget().frontMostApp().setPreferencesValueForKey(null, __calabashResponse);
        _exp = preferences['command'];
        UIALogger.logMessage("index " + _actualIndex + " is command: "+ _exp);
        try {
            if (_exp == 'break;') {
                _success("OK", _actualIndex);
                break;
            }
            _result = eval(_exp);
            UIALogger.logMessage("Success: "+ _result);
            _success(_result, _actualIndex);
        }
        catch(err) {
            failureMessage = "Failure: "+ err.toString() + "  " + (err.stack ? err.stack.toString() : "");
            Log.output({"output":failureMessage}, true);
            _failure(err, _actualIndex);
        }
    }
    else {//likely old command is lingering...
        continue;
    }
    _expectedIndex = Math.max(_actualIndex+1, _expectedIndex+1);
    target.delay(0.1);
}
<commit_msg>Log the right object<commit_after>if (typeof JSON !== 'object') {
    JSON = {};
}
(function () {
    'use strict';
    function f(n) {
        return n < 10 ? '0' + n : n;
    }

    if (typeof Date.prototype.toJSON !== 'function') {
        Date.prototype.toJSON = function (key) {
            return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' +
                f(this.getUTCMonth() + 1) + '-' +
                f(this.getUTCDate()) + 'T' +
                f(this.getUTCHours()) + ':' +
                f(this.getUTCMinutes()) + ':' +
                f(this.getUTCSeconds()) + 'Z' : null;
        };
        String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (key) {
            return this.valueOf();
        };
    }
    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = {'\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\\': '\\\\'}, rep;

    function quote(string) {
        escapable.lastIndex = 0;
        return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
            var c = meta[a];
            return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
        }) + '"' : '"' + string + '"';
    }

    function str(key, holder) {
        var i, k, v, length, mind = gap, partial, value = holder[key];
        if (value && typeof value === 'object' && typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }
        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }
        switch (typeof value) {
            case'string':
                return quote(value);
            case'number':
                return isFinite(value) ? String(value) : 'null';
            case'boolean':
            case'null':
                return String(value);
            case'object':
                if (!value) {
                    return'null';
                }
                gap += indent;
                partial = [];
                if (Object.prototype.toString.apply(value) === '[object Array]') {
                    length = value.length;
                    for (i = 0; i < length; i += 1) {
                        partial[i] = str(i, value) || 'null';
                    }
                    v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']';
                    gap = mind;
                    return v;
                }
                if (rep && typeof rep === 'object') {
                    length = rep.length;
                    for (i = 0; i < length; i += 1) {
                        if (typeof rep[i] === 'string') {
                            k = rep[i];
                            v = str(k, value);
                            if (v) {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
                } else {
                    for (k in value) {
                        if (Object.prototype.hasOwnProperty.call(value, k)) {
                            v = str(k, value);
                            if (v) {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
                }
                v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}';
                gap = mind;
                return v;
        }
    }

    if (typeof JSON.stringify !== 'function') {
        JSON.stringify = function (value, replacer, space) {
            var i;
            gap = '';
            indent = '';
            if (typeof space === 'number') {
                for (i = 0; i < space; i += 1) {
                    indent += ' ';
                }
            } else if (typeof space === 'string') {
                indent = space;
            }
            rep = replacer;
            if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) {
                throw new Error('JSON.stringify');
            }
            return str('', {'': value});
        };
    }
    if (typeof JSON.parse !== 'function') {
        JSON.parse = function (text, reviver) {
            var j;

            function walk(holder, key) {
                var k, v, value = holder[key];
                if (value && typeof value === 'object') {
                    for (k in value) {
                        if (Object.prototype.hasOwnProperty.call(value, k)) {
                            v = walk(value, k);
                            if (v !== undefined) {
                                value[k] = v;
                            } else {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }

            text = String(text);
            cx.lastIndex = 0;
            if (cx.test(text)) {
                text = text.replace(cx, function (a) {
                    return'\\u' +
                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }
            if (/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
                j = eval('(' + text + ')');
                return typeof reviver === 'function' ? walk({'': j}, '') : j;
            }
            throw new SyntaxError('JSON.parse');
        };
    }
}());

var _expectedIndex = 0,//expected index of next command
    _actualIndex=0,//actual index of next command by reading commandPath
    _exp,//expression to be eval'ed
    _result;

var Log = (function () {
    var forceFlush = [],
        N = 16384,
        i = N;
    while (i--) {
        forceFlush[i] = "*";
    }
    forceFlush = forceFlush.join('');

    function log_json(object, flush)
    {
        UIALogger.logMessage("OUTPUT_JSON:\n"+JSON.stringify(object)+"\nEND_OUTPUT");
        if (flush) {
            UIALogger.logMessage(forceFlush);
        }
    }

    return {
        result: function (status, data, flush) {
            log_json({"status": status, "value": data, "index":_actualIndex}, flush)
        },
        output: function (msg, flush) {
            log_json({"output": msg,"last_index":_actualIndex}, flush);
        }
    };
})();

function findAlertViewText(alert) {
    if (!alert) {
        return false;
    }
    var txt = alert.name(),
        txts;
    if (txt == null) {
        txts = alert.staticTexts();
        if (txts != null && txts.length > 0) {
            txt = txts[0].name();
        }
    }
    return txt;
}

function isLocationPrompt(alert) {
    var exps = [
            ["OK", /vil bruge din aktuelle placering/],
            ["OK", /Would Like to Use Your Current Location/],
            ["Ja", /Darf (?:.)+ Ihren aktuellen Ort verwenden/],
            ["OK", /Would Like to Send You Notifications/],
            ["Allow", /access your location/],
            ["OK", /Would Like to Access Your Photos/],
            ["OK", /Would Like to Access Your Contacts/],
            ["OK", /запрашивает разрешение на использование Ващей текущей пгеопозиции/]
        ],
        ans, exp,
        txt;

    txt = findAlertViewText(alert);
    Log.output({"output":"alert: "+txt}, true);
    for (var i = 0; i < exps.length; i++) {
        ans = exps[i][0];
        exp = exps[i][1];
        if (exp.test(txt)) {
            return ans;
        }
    }
    return false;
}

UIATarget.onAlert = function (alert) {
    Log.output({"output":"on alert"}, true);
    var target = UIATarget.localTarget();
    target.pushTimeout(10);
    function attemptTouchOKOnLocation(retry_count) {
        retry_count = retry_count || 0;
        if (retry_count >= 5) {
            Log.output("Maxed out retry (5) - unable to dismiss location dialog.");
            return;
        }
        try {
            var answer = isLocationPrompt(alert);
            if (answer) {
                alert.buttons()[answer].tap();
            }
        }
        catch (e) {
            Log.output("Exception while trying to touch alert dialog. Retrying...");
            if (e && typeof e.toString == 'function') {
                Log.output(e.toString());
            }
            target.delay(1);
            attemptTouchOKOnLocation(retry_count + 1);
        }
    }

    attemptTouchOKOnLocation(0);
    target.popTimeout();
    return true;
};

var target = null,
    failureMessage = null,
    preferences = null,
    __calabashRequest = "__calabashRequest",
    __calabashResponse = "__calabashResponse",
    _sanitize = function(val) {
        if (typeof val === 'undefined' || val === null || val instanceof UIAElementNil) {
            return ":nil";
        }
        if (typeof val === 'string' || val instanceof String) {
            return val;
        }
        var arrVal = null, i, N;
        if (val instanceof Array || val instanceof UIAElementArray) {
            arrVal = [];
            for (i=0,N=val.length;i<N;i++) {
                arrVal[i] = _sanitize(val[i]);
            }
            return arrVal;
        }
        if (val instanceof UIAElement) {
            return val.toString();
        }
        var objVal = null, p;
        if (typeof val == 'object') {
            objVal = {};
            for (p in val) {
                objVal[p] = _sanitize(val[p]);
            }
            return objVal;
        }
        return val;
    },
    _response = function(response) {
        var sanitized = _sanitize(response),
            i = 0,
            MAX_TRIES=120,
            res,
            tmp;

        for (i=0; i<MAX_TRIES; i+=1) {
            UIALogger.logMessage("Write result...");
            tmp = target.frontMostApp().preferencesValueForKey(__calabashResponse);
            UIALogger.logMessage("Last response..."+tmp);
            target.frontMostApp().setPreferencesValueForKey(sanitized, __calabashResponse);
            res = target.frontMostApp().preferencesValueForKey(__calabashResponse);
            UIALogger.logMessage("Next response..."+res);
            if (res && res['index'] == sanitized['index']) {
                UIALogger.logMessage("Storage succeeded: "+ res['index']);
                return;
            } else {
                UIALogger.logMessage("Storage failed: "+ res + " Retrying...");
                target.delay(0.2);
            }
        }
        throw new Error("Unable to write to preferences");

    },
    _success = function(result,index) {

        _response({"status":'success', "value":result, "index": index});

    },
    _failure = function(err, index) {
        _response({"status":'error',
                   "value":err.toString(),
                   "backtrace":(err.stack ? err.stack.toString() : ""),
                   "index":index});
    },
    _resetCalabashPreferences = function () {
        //Implementation is weird but reading pref values seems to have side effects
        //also deleting a key seemed to require writing 0 and then null :)
        var app = UIATarget.localTarget().frontMostApp();
        app.preferencesValueForKey(__calabashRequest);
        app.preferencesValueForKey(__calabashResponse);
        app.setPreferencesValueForKey(0, __calabashResponse);
        app.setPreferencesValueForKey(null, __calabashResponse);
        app.setPreferencesValueForKey(0, __calabashRequest);
        app.setPreferencesValueForKey(null, __calabashRequest);
    };

_resetCalabashPreferences();
Log.result('success',true,true);
target = UIATarget.localTarget();
while (true) {
    try {
        preferences = target.frontMostApp().preferencesValueForKey(__calabashRequest);
    } catch (e) {
        Log.output("Unable to read preferences..."+ e.toString());
        target.delay(0.5);
        continue;
    }

    if (!preferences) {
        target.delay(0.2);
        continue;
    }

    _actualIndex = preferences['index'];
    if (!isNaN(_actualIndex) && _actualIndex >= _expectedIndex) {
        UIATarget.localTarget().frontMostApp().setPreferencesValueForKey(null, __calabashResponse);
        _exp = preferences['command'];
        UIALogger.logMessage("index " + _actualIndex + " is command: "+ _exp);
        try {
            if (_exp == 'break;') {
                _success("OK", _actualIndex);
                break;
            }
            _result = eval(_exp);
            UIALogger.logMessage("Success: "+ _result);
            _success(_result, _actualIndex);
        }
        catch(err) {
            failureMessage = "Failure: "+ err.toString() + "  " + (err.stack ? err.stack.toString() : "");
            Log.output({"output":failureMessage}, true);
            _failure(err, _actualIndex);
        }
    }
    else {//likely old command is lingering...
        continue;
    }
    _expectedIndex = Math.max(_actualIndex+1, _expectedIndex+1);
    target.delay(0.1);
}
<|endoftext|>


<commit_before>function sequence() {
  var executionQueue = Array.prototype.concat.apply([], arguments);

  return function() {
    var result = executionQueue.shift().apply(null, arguments);

    if (executionQueue.length) {
      executionQueue[0] = executionQueue[0].bind(null, result);
    }

    return executionQueue.length ? sequence.apply(null, executionQueue) : result;
  }
}<commit_msg>comment added<commit_after>function sequence() {
  var executionQueue = Array.prototype.concat.apply([], arguments);

  return function() {
    var result = executionQueue.shift().apply(null, arguments);

    if (executionQueue.length) {

      // only context free/fixed functions are supported
      executionQueue[0] = executionQueue[0].bind(null, result);
    }

    return executionQueue.length ? sequence.apply(null, executionQueue) : result;
  }
}<|endoftext|>