<commit_before>const { registerMultiTask } = require("grunt");

/**
 *
 * @param labelContainer
 * @param missionModel
 * @param missionContainer
 * @param navigationModel
 * @param neighborhoodModel
 * @param panoramaContainer
 * @param taskContainer
 * @param mapService
 * @param compass
 * @param tracker
 * @param params
 * @returns {{className: string}}
 * @constructor
 */
function Form (labelContainer, missionModel, missionContainer, navigationModel, neighborhoodModel, panoramaContainer, taskContainer, mapService, compass, tracker, params) {
    var self = this;
    let properties = {
        dataStoreUrl : undefined,
        beaconDataStoreUrl : undefined,
        timeLastQuried : new Date().getTime() // Assuming that Form is created when TaskContainer is created
    };

    missionModel.on("MissionProgress:complete", function (parameters) {
        self.submitData(true);
    });

    /**
     * This method gathers all the data needed for submission.
     * @returns {{}}
     */
    this.compileSubmissionData = function (task) {
        var data = {};

        data.amt_assignment_id = svl.amtAssignmentId;

        var mission = missionContainer.getCurrentMission();
        mission.updateDistanceProgress();
        data.mission = {
            mission_id: mission.getProperty("missionId"),
            distance_progress: Math.min(mission.getProperty("distanceProgress"), mission.getProperty("distance")),
            completed: mission.getProperty("isComplete"),
            audit_task_id: task.getAuditTaskId(),
            skipped: mission.getProperty("skipped")
        };

        data.audit_task = {
            street_edge_id: task.getStreetEdgeId(),
            task_start: task.getTaskStart(),
            audit_task_id: task.getAuditTaskId(),
            completed: task.isComplete(),
            current_lat: navigationModel.getPosition().lat,
            current_lng: navigationModel.getPosition().lng,
            start_point_reversed: task.getProperty("startPointReversed"),
            time_data_last_queried: properties.timeLastQuried
        };

        data.environment = {
            browser: util.getBrowser(),
            browser_version: util.getBrowserVersion(),
            browser_width: $(window).width(),
            browser_height: $(window).height(),
            screen_width: screen.width,
            screen_height: screen.height,
            avail_width: screen.availWidth,              // total width - interface (taskbar)
            avail_height: screen.availHeight,            // total height - interface };
            operating_system: util.getOperatingSystem(),
            language: i18next.language
        };

        data.interactions = tracker.getActions();
        tracker.refresh();

        data.labels = [];
        var labels = labelContainer.getCurrentLabels();
        for(var i = 0, labelLen = labels.length; i < labelLen; i += 1) {
            var label = labels[i];
            var prop = label.getProperties();
            var points = label.getPath().getPoints();
            var labelLatLng = label.toLatLng();
            var tempLabelId = label.getProperty('temporary_label_id');
            var auditTaskId = label.getProperty('audit_task_id');

            // If this label is a new label, get the timestamp of its creation from the corresponding interaction.
            var associatedInteraction = data.interactions.find(interaction =>
                interaction.action === 'LabelingCanvas_FinishLabeling' && interaction.temporary_label_id === tempLabelId
                && interaction.audit_task_id === auditTaskId);
            var timeCreated = associatedInteraction ? associatedInteraction.timestamp : null;

            var temp = {
                deleted : label.isDeleted(),
                label_id : label.getLabelId(),
                label_type : label.getLabelType(),
                photographer_heading : prop.photographerHeading,
                photographer_pitch : prop.photographerPitch,
                panorama_lat: prop.panoramaLat,
                panorama_lng: prop.panoramaLng,
                temporary_label_id: tempLabelId,
                audit_task_id: auditTaskId,
                gsv_panorama_id : prop.panoId,
                label_points : [],
                severity: label.getProperty('severity'),
                temporary_label: label.getProperty('temporaryLabel'),
                tag_ids: label.getProperty('tagIds'),
                description: label.getProperty('description'),
                time_created: timeCreated,
                tutorial: prop.tutorial
            };

            for (var j = 0, pathLen = points.length; j < pathLen; j += 1) {
                var point = points[j],
                    gsvImageCoordinate = point.getGSVImageCoordinate(),
                    pointParam = {
                        sv_image_x : gsvImageCoordinate.x,
                        sv_image_y : gsvImageCoordinate.y,
                        canvas_x: point.originalCanvasCoordinate.x,
                        canvas_y: point.originalCanvasCoordinate.y,
                        heading: point.panoramaPov.heading,
                        pitch: point.panoramaPov.pitch,
                        zoom : point.panoramaPov.zoom,
                        canvas_height : prop.canvasHeight,
                        canvas_width : prop.canvasWidth,
                        alpha_x : prop.canvasDistortionAlphaX,
                        alpha_y : prop.canvasDistortionAlphaY,
                        lat : null,
                        lng : null
                    };

                if (labelLatLng) {
                    pointParam.lat = labelLatLng.lat;
                    pointParam.lng = labelLatLng.lng;
                    pointParam.computation_method = labelLatLng.latLngComputationMethod;
                }
                temp.label_points.push(pointParam);
            }

            data.labels.push(temp)
        }

        // Keep Street View meta data. This is particularly important to keep track of the date when the images were taken (i.e., the date of the accessibility attributes).
        data.gsv_panoramas = [];

        var temp;
        var panoramaData;
        var link;
        var links;
        var panoramas = panoramaContainer.getStagedPanoramas();
        for (var i = 0, panoramaLen = panoramas.length; i < panoramaLen; i++) {
            panoramaData = panoramas[i].data();
            links = [];
            if ("links" in panoramaData) {
                for (j = 0; j < panoramaData.links.length; j++) {
                    link = panoramaData.links[j];
                    links.push({
                        target_gsv_panorama_id: ("pano" in link) ? link.pano : "",
                        yaw_deg: ("heading" in link) ? link.heading : 0.0,
                        description: ("description" in link) ? link.description : ""
                    });
                }
            }
            temp = {
                panorama_id: ("location" in panoramaData && "pano" in panoramaData.location) ? panoramaData.location.pano : "",
                image_date: "imageDate" in panoramaData ? panoramaData.imageDate : "",
                links: links,
                copyright: "copyright" in panoramaData ? panoramaData.copyright : ""
            };
            data.gsv_panoramas.push(temp);
            panoramas[i].setProperty("submitted", true);
        }

        return data;
    };

    this._prepareSkipData = function (issueDescription) {
        var position = navigationModel.getPosition();
        return {
            issue_description: issueDescription,
            lat: position.lat,
            lng: position.lng
        };
    };

    this.skip = function (task, skipReasonLabel) {
        var data = self._prepareSkipData(skipReasonLabel);

        if (skipReasonLabel === "GSVNotAvailable") {
            taskContainer.endTask(task);
            missionContainer.getCurrentMission().pushATaskToTheRoute(task);
            util.misc.reportNoStreetView(task.getStreetEdgeId());
        } else {
            // Set the tasksMissionsOffset so that the mission progress bar remains the same after the jump.
            var currTaskDist = util.math.kilometersToMeters(taskContainer.getCurrentTaskDistance());
            var oldOffset = missionContainer.getTasksMissionsOffset();
            missionContainer.setTasksMissionsOffset(oldOffset + currTaskDist);
        }

        task.eraseFromGoogleMaps();
        self.skipSubmit(data, task);

        // If the jump was clicked in the middle of the beforeJumpTask,
        // reset the beforeJump tracking parameters
        var jumpListenerStatus = mapService.getLabelBeforeJumpListenerStatus();
        if (jumpListenerStatus) {
            mapService.setLabelBeforeJumpListenerStatus(false);
            compass.resetBeforeJump();
            mapService.finishCurrentTaskBeforeJumping();
        }

        taskContainer.getFinishedAndInitNextTask(task);
    };

    /**
     * Submit the data collected so far and move to another location.
     *
     * @param dataIn An object that has issue_description, lat, and lng as fields.
     * @param task
     * @returns {boolean}
     */
    this.skipSubmit = function (dataIn, task) {
        tracker.push('TaskSkip');

        var data = self.compileSubmissionData(task);
        data.incomplete = dataIn;

        self.submit(data, task);
        return false;
    };

    /**
     * Submit the data via an AJAX post request.
     * @param data
     * @param task
     * @param async
     */
    this.submit = function (data, task, async) {
        if (typeof async === "undefined") { async = true; }
        if (data.constructor !== Array) { data = [data]; }

        if ('interactions' in data[0] && data[0].constructor === Array) {
            var action = tracker.create("TaskSubmit");
            data[0].interactions.push(action);
        }

        labelContainer.refresh();

        $.ajax({
            async: async,
            contentType: 'application/json; charset=utf-8',
            url: properties.dataStoreUrl,
            type: 'post',
            data: JSON.stringify(data),
            dataType: 'json',
            success: function (result) {
                if (result) {
                    var taskId = result.audit_task_id;
                    task.setProperty("auditTaskId", taskId);
                    svl.tracker.setAuditTaskID(taskId);

                    // If the back-end says it is time to switch to validations, then do it immediately (mostly to
                    // prevent turkers from modifying JS variables to prevent switching to validation).
                    if (result.switch_to_validation) window.location.replace('/validate');

                    // If a new mission was sent and we aren't in onboarding, create an object for it on the front-end.
                    if (result.mission && !svl.isOnboarding()) missionModel.createAMission(result.mission);

                    properties.timeLastQuried = result.timePerformedQuery;

                    // console.log("timeLastQueried: " + properties.timeLastQuried);
                    // console.log("timePerformedQuery: " + result.timePerformedQuery)
                    if (result.streetEdgeIdsAfterTime > 0) {
                        console.log(result.streetEdgeIdsAfterTime);
                        console.log(result.newStreetEdgePriorities);
                        taskContainer.updateTaskPriorities(result.streetEdgeIdsAfterTime, result.newStreetEdgePriorities);
                    }
                }
            },
            error: function (result) {
                console.error(result);
            }
        });
    };

    properties.dataStoreUrl = params.dataStoreUrl;
    properties.beaconDataStoreUrl = params.beaconDataStoreUrl;

    $(window).on('beforeunload', function () {
        tracker.push("Unload");

        // // April 17, 2019
        // // What we want here is type: 'application/json'. Can't do that quite yet because the
        // // feature has been disabled, but we should switch back when we can.
        //
        // // For now, we send plaintext and the server converts it to actual JSON
        //
        // // Source for fix and ongoing discussion is here:
        // // https://bugs.chromium.org/p/chromium/issues/detail?id=490015
        var task = taskContainer.getCurrentTask();
        var data = [self.compileSubmissionData(task)];
        var jsonData = JSON.stringify(data);
        navigator.sendBeacon(properties.beaconDataStoreUrl, jsonData);
    });

    /**
     * Manually triggers form submission from other functions.
     * @param async     Whether data should be submitted asynchronously or not (if undefined,
     *                  then submits asynchronously by default)
     */
    this.submitData = function (async) {
        if (typeof async === "undefined") { async = true; }
        var task = taskContainer.getCurrentTask();
        var data = self.compileSubmissionData(task);
        self.submit(data, task, async);
    }
}
<commit_msg>fixed bug with not intended line<commit_after>/**
 *
 * @param labelContainer
 * @param missionModel
 * @param missionContainer
 * @param navigationModel
 * @param neighborhoodModel
 * @param panoramaContainer
 * @param taskContainer
 * @param mapService
 * @param compass
 * @param tracker
 * @param params
 * @returns {{className: string}}
 * @constructor
 */
function Form (labelContainer, missionModel, missionContainer, navigationModel, neighborhoodModel, panoramaContainer, taskContainer, mapService, compass, tracker, params) {
    var self = this;
    let properties = {
        dataStoreUrl : undefined,
        beaconDataStoreUrl : undefined,
        timeLastQuried : new Date().getTime() // Assuming that Form is created when TaskContainer is created
    };

    missionModel.on("MissionProgress:complete", function (parameters) {
        self.submitData(true);
    });

    /**
     * This method gathers all the data needed for submission.
     * @returns {{}}
     */
    this.compileSubmissionData = function (task) {
        var data = {};

        data.amt_assignment_id = svl.amtAssignmentId;

        var mission = missionContainer.getCurrentMission();
        mission.updateDistanceProgress();
        data.mission = {
            mission_id: mission.getProperty("missionId"),
            distance_progress: Math.min(mission.getProperty("distanceProgress"), mission.getProperty("distance")),
            completed: mission.getProperty("isComplete"),
            audit_task_id: task.getAuditTaskId(),
            skipped: mission.getProperty("skipped")
        };

        data.audit_task = {
            street_edge_id: task.getStreetEdgeId(),
            task_start: task.getTaskStart(),
            audit_task_id: task.getAuditTaskId(),
            completed: task.isComplete(),
            current_lat: navigationModel.getPosition().lat,
            current_lng: navigationModel.getPosition().lng,
            start_point_reversed: task.getProperty("startPointReversed"),
            time_data_last_queried: properties.timeLastQuried
        };

        data.environment = {
            browser: util.getBrowser(),
            browser_version: util.getBrowserVersion(),
            browser_width: $(window).width(),
            browser_height: $(window).height(),
            screen_width: screen.width,
            screen_height: screen.height,
            avail_width: screen.availWidth,              // total width - interface (taskbar)
            avail_height: screen.availHeight,            // total height - interface };
            operating_system: util.getOperatingSystem(),
            language: i18next.language
        };

        data.interactions = tracker.getActions();
        tracker.refresh();

        data.labels = [];
        var labels = labelContainer.getCurrentLabels();
        for(var i = 0, labelLen = labels.length; i < labelLen; i += 1) {
            var label = labels[i];
            var prop = label.getProperties();
            var points = label.getPath().getPoints();
            var labelLatLng = label.toLatLng();
            var tempLabelId = label.getProperty('temporary_label_id');
            var auditTaskId = label.getProperty('audit_task_id');

            // If this label is a new label, get the timestamp of its creation from the corresponding interaction.
            var associatedInteraction = data.interactions.find(interaction =>
                interaction.action === 'LabelingCanvas_FinishLabeling' && interaction.temporary_label_id === tempLabelId
                && interaction.audit_task_id === auditTaskId);
            var timeCreated = associatedInteraction ? associatedInteraction.timestamp : null;

            var temp = {
                deleted : label.isDeleted(),
                label_id : label.getLabelId(),
                label_type : label.getLabelType(),
                photographer_heading : prop.photographerHeading,
                photographer_pitch : prop.photographerPitch,
                panorama_lat: prop.panoramaLat,
                panorama_lng: prop.panoramaLng,
                temporary_label_id: tempLabelId,
                audit_task_id: auditTaskId,
                gsv_panorama_id : prop.panoId,
                label_points : [],
                severity: label.getProperty('severity'),
                temporary_label: label.getProperty('temporaryLabel'),
                tag_ids: label.getProperty('tagIds'),
                description: label.getProperty('description'),
                time_created: timeCreated,
                tutorial: prop.tutorial
            };

            for (var j = 0, pathLen = points.length; j < pathLen; j += 1) {
                var point = points[j],
                    gsvImageCoordinate = point.getGSVImageCoordinate(),
                    pointParam = {
                        sv_image_x : gsvImageCoordinate.x,
                        sv_image_y : gsvImageCoordinate.y,
                        canvas_x: point.originalCanvasCoordinate.x,
                        canvas_y: point.originalCanvasCoordinate.y,
                        heading: point.panoramaPov.heading,
                        pitch: point.panoramaPov.pitch,
                        zoom : point.panoramaPov.zoom,
                        canvas_height : prop.canvasHeight,
                        canvas_width : prop.canvasWidth,
                        alpha_x : prop.canvasDistortionAlphaX,
                        alpha_y : prop.canvasDistortionAlphaY,
                        lat : null,
                        lng : null
                    };

                if (labelLatLng) {
                    pointParam.lat = labelLatLng.lat;
                    pointParam.lng = labelLatLng.lng;
                    pointParam.computation_method = labelLatLng.latLngComputationMethod;
                }
                temp.label_points.push(pointParam);
            }

            data.labels.push(temp)
        }

        // Keep Street View meta data. This is particularly important to keep track of the date when the images were taken (i.e., the date of the accessibility attributes).
        data.gsv_panoramas = [];

        var temp;
        var panoramaData;
        var link;
        var links;
        var panoramas = panoramaContainer.getStagedPanoramas();
        for (var i = 0, panoramaLen = panoramas.length; i < panoramaLen; i++) {
            panoramaData = panoramas[i].data();
            links = [];
            if ("links" in panoramaData) {
                for (j = 0; j < panoramaData.links.length; j++) {
                    link = panoramaData.links[j];
                    links.push({
                        target_gsv_panorama_id: ("pano" in link) ? link.pano : "",
                        yaw_deg: ("heading" in link) ? link.heading : 0.0,
                        description: ("description" in link) ? link.description : ""
                    });
                }
            }
            temp = {
                panorama_id: ("location" in panoramaData && "pano" in panoramaData.location) ? panoramaData.location.pano : "",
                image_date: "imageDate" in panoramaData ? panoramaData.imageDate : "",
                links: links,
                copyright: "copyright" in panoramaData ? panoramaData.copyright : ""
            };
            data.gsv_panoramas.push(temp);
            panoramas[i].setProperty("submitted", true);
        }

        return data;
    };

    this._prepareSkipData = function (issueDescription) {
        var position = navigationModel.getPosition();
        return {
            issue_description: issueDescription,
            lat: position.lat,
            lng: position.lng
        };
    };

    this.skip = function (task, skipReasonLabel) {
        var data = self._prepareSkipData(skipReasonLabel);

        if (skipReasonLabel === "GSVNotAvailable") {
            taskContainer.endTask(task);
            missionContainer.getCurrentMission().pushATaskToTheRoute(task);
            util.misc.reportNoStreetView(task.getStreetEdgeId());
        } else {
            // Set the tasksMissionsOffset so that the mission progress bar remains the same after the jump.
            var currTaskDist = util.math.kilometersToMeters(taskContainer.getCurrentTaskDistance());
            var oldOffset = missionContainer.getTasksMissionsOffset();
            missionContainer.setTasksMissionsOffset(oldOffset + currTaskDist);
        }

        task.eraseFromGoogleMaps();
        self.skipSubmit(data, task);

        // If the jump was clicked in the middle of the beforeJumpTask,
        // reset the beforeJump tracking parameters
        var jumpListenerStatus = mapService.getLabelBeforeJumpListenerStatus();
        if (jumpListenerStatus) {
            mapService.setLabelBeforeJumpListenerStatus(false);
            compass.resetBeforeJump();
            mapService.finishCurrentTaskBeforeJumping();
        }

        taskContainer.getFinishedAndInitNextTask(task);
    };

    /**
     * Submit the data collected so far and move to another location.
     *
     * @param dataIn An object that has issue_description, lat, and lng as fields.
     * @param task
     * @returns {boolean}
     */
    this.skipSubmit = function (dataIn, task) {
        tracker.push('TaskSkip');

        var data = self.compileSubmissionData(task);
        data.incomplete = dataIn;

        self.submit(data, task);
        return false;
    };

    /**
     * Submit the data via an AJAX post request.
     * @param data
     * @param task
     * @param async
     */
    this.submit = function (data, task, async) {
        if (typeof async === "undefined") { async = true; }
        if (data.constructor !== Array) { data = [data]; }

        if ('interactions' in data[0] && data[0].constructor === Array) {
            var action = tracker.create("TaskSubmit");
            data[0].interactions.push(action);
        }

        labelContainer.refresh();

        $.ajax({
            async: async,
            contentType: 'application/json; charset=utf-8',
            url: properties.dataStoreUrl,
            type: 'post',
            data: JSON.stringify(data),
            dataType: 'json',
            success: function (result) {
                if (result) {
                    var taskId = result.audit_task_id;
                    task.setProperty("auditTaskId", taskId);
                    svl.tracker.setAuditTaskID(taskId);

                    // If the back-end says it is time to switch to validations, then do it immediately (mostly to
                    // prevent turkers from modifying JS variables to prevent switching to validation).
                    if (result.switch_to_validation) window.location.replace('/validate');

                    // If a new mission was sent and we aren't in onboarding, create an object for it on the front-end.
                    if (result.mission && !svl.isOnboarding()) missionModel.createAMission(result.mission);

                    properties.timeLastQuried = result.timePerformedQuery;

                    // console.log("timeLastQueried: " + properties.timeLastQuried);
                    // console.log("timePerformedQuery: " + result.timePerformedQuery)
                    if (result.streetEdgeIdsAfterTime > 0) {
                        console.log(result.streetEdgeIdsAfterTime);
                        console.log(result.newStreetEdgePriorities);
                        taskContainer.updateTaskPriorities(result.streetEdgeIdsAfterTime, result.newStreetEdgePriorities);
                    }
                }
            },
            error: function (result) {
                console.error(result);
            }
        });
    };

    properties.dataStoreUrl = params.dataStoreUrl;
    properties.beaconDataStoreUrl = params.beaconDataStoreUrl;

    $(window).on('beforeunload', function () {
        tracker.push("Unload");

        // // April 17, 2019
        // // What we want here is type: 'application/json'. Can't do that quite yet because the
        // // feature has been disabled, but we should switch back when we can.
        //
        // // For now, we send plaintext and the server converts it to actual JSON
        //
        // // Source for fix and ongoing discussion is here:
        // // https://bugs.chromium.org/p/chromium/issues/detail?id=490015
        var task = taskContainer.getCurrentTask();
        var data = [self.compileSubmissionData(task)];
        var jsonData = JSON.stringify(data);
        navigator.sendBeacon(properties.beaconDataStoreUrl, jsonData);
    });

    /**
     * Manually triggers form submission from other functions.
     * @param async     Whether data should be submitted asynchronously or not (if undefined,
     *                  then submits asynchronously by default)
     */
    this.submitData = function (async) {
        if (typeof async === "undefined") { async = true; }
        var task = taskContainer.getCurrentTask();
        var data = self.compileSubmissionData(task);
        self.submit(data, task, async);
    }
}
<|endoftext|>


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

var webpack = require('webpack');
var AUTOPREFIXER_LOADER = 'autoprefixer-loader?{browsers:[' +
    '"Android 2.3", "Android >= 4", "Chrome >= 20", "Firefox >= 24", ' +
    '"Explorer >= 8", "iOS >= 6", "Opera >= 12", "Safari >= 6"]}';

module.exports = {

    devtool: 'source-map',
    entry: {
        app: './public/app.jsx'
    },
	output:{
        path: path.join(__dirname, '../subschema-gh-pages'),
        filename: 'app.[hash].js'
    },
	target:"web",
    stats: {
        colors: true,
        reasons: true
    },
    module: {
        loaders: [
            {
                test: /\.js(x)?$/,
                excludes: /node_modules/,
                //do this to prevent babel fromt tanslating everything.
                includes: [
                    '~/node_modules/react',
                    '~/node_modules/react-router',
                    '~/node_modules/react-bootstrap',
                    '~/node_modules/subschema-builder'

                ],
                loaders: ['babel-loader?stage=0']
            },
            {test: /\.(png|woff|woff2|eot|ttf|svg)$/, loader: 'url-loader?limit=100000'},
            {test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&minetype=application/font-woff"},
            {test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&minetype=application/octet-stream"},
            {test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file"},
            {test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&minetype=image/svg+xml"},
            // Optionally extract less files
            // or any other compile-to-css language
            {
                test: /\.css$/,
                loader: 'style-loader!css-loader!' + AUTOPREFIXER_LOADER
            },
            {
                test: /\.less$/,
                loader: 'style!css!less-loader'
            }
        ]
    },

    resolve: {
        alias: {
            'subschema': __dirname
        }
    },

    plugins: [

        new webpack.DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify('production')
        }),
		//new webpack.optimize.DedupePlugin(),
        function () {
            this.plugin("done", function (stats) {
                stats = stats.toJson();
                console.error(JSON.stringify({
                    assetsByChunkName: stats.assetsByChunkName
                }));
            });
        }
    ]

};

<commit_msg>Fix demo webpack<commit_after>var path = require('path');

var webpack = require('webpack');
var AUTOPREFIXER_LOADER = 'autoprefixer-loader?{browsers:[' +
    '"Android 2.3", "Android >= 4", "Chrome >= 20", "Firefox >= 24", ' +
    '"Explorer >= 8", "iOS >= 6", "Opera >= 12", "Safari >= 6"]}';

module.exports = {

    devtool: 'source-map',
    entry: {
        app: './public/app.jsx'
    },
	output:{
        path: path.join(__dirname, '../subschema-gh-pages'),
        filename: 'app.[hash].js'
    },
	target:"web",
    stats: {
        colors: true,
        reasons: true
    },
    module: {
        loaders: [
            {
                test: /\.js(x)?$/,
                excludes: /node_modules/,
                //do this to prevent babel fromt tanslating everything.
                includes: [
                    '~/node_modules/react',
                    '~/node_modules/react-router',
                    '~/node_modules/react-bootstrap',
                    '~/node_modules/subschema-builder',
                    '~/node_modules/react-highlight'

                ],
                loaders: ['babel-loader?stage=0']
            },
            {test: /\.(png|woff|woff2|eot|ttf|svg)$/, loader: 'url-loader?limit=100000'},
            {test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&minetype=application/font-woff"},
            {test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&minetype=application/octet-stream"},
            {test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file"},
            {test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&minetype=image/svg+xml"},
            // Optionally extract less files
            // or any other compile-to-css language
            {
                test: /\.css$/,
                loader: 'style-loader!css-loader!' + AUTOPREFIXER_LOADER
            },
            {
                test: /\.less$/,
                loader: 'style!css!less-loader'
            }
        ]
    },

    resolve: {
        alias: {
            'subschema':path.join( __dirname, 'src/index.jsx'),
            'react': path.join(__dirname, '/node_modules/react')
        }
    },

    plugins: [

        new webpack.DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify('production')
        }),
		//new webpack.optimize.DedupePlugin(),
        function () {
            this.plugin("done", function (stats) {
                stats = stats.toJson();
                console.error(JSON.stringify({
                    assetsByChunkName: stats.assetsByChunkName
                }));
            });
        }
    ]

};

<|endoftext|>


<commit_before>/**
 * Platform cattail@cattop.cattail.me Linux3.11.5-1-ARCH@x86_64 GNU/Linux
 * Date 2013-10-23 12:19:43
 * @author zhongchiyu@gmail.com (cattail)
 * @description Instance property could be share accidently when using
 * Javascript's prototype based class inheritance.
 *
 * ## Reference
 * * [coffeescript-class-member](http://stackoverflow.com/questions/8355371/coffeescript-class-members)
 */

// If property is primitive value, it will be fine.
function Klass () {}
Klass.prototype.prop = 0;
Klass.prototype.setProp = function (value) {
  this.prop = value;
};
var obj1 = new Klass();
var obj2 = new Klass();
obj2.setProp(1);
console.log(obj1.prop === 0)
console.log(obj2.prop === 1);

// Problem comes with non-primitive value
function $Set () {}
$Set.prototype.items = [];
$Set.prototype.add = function (item) {
  this.items.push(item);
};
var obj3 = new $Set();
var obj4 = new $Set();
obj4.add(1);
console.log(obj3.items.length === 1);
console.log(obj4.items.length === 1);

// Solution is to move property initialization into constructor
function Set () {
  this.items = [];
}
Set.prototype.add = function (item) {
  this.items.push(item);
};
var obj5 = new Set();
var obj6 = new Set();
obj6.add(1);
console.log(obj5.items.length === 0);
console.log(obj6.items.length === 1);
<commit_msg>seprate different block of snippet<commit_after>/**
 * Platform cattail@cattop.cattail.me Linux3.11.5-1-ARCH@x86_64 GNU/Linux
 * Date 2013-10-23 12:19:43
 * @author zhongchiyu@gmail.com (cattail)
 * @description Instance property could be share accidently when using
 * prototype based class inheritance.
 */

// If property is primitive value, it will be fine.
function Klass () {}
Klass.prototype.prop = 0;
Klass.prototype.setProp = function (value) {
  this.prop = value;
};
var obj1 = new Klass();
var obj2 = new Klass();
obj2.setProp(1);
console.log(obj1.prop === 0)
console.log(obj2.prop === 1);

////////////////////////////////////////
// Problem
////////////////////////////////////////

// Problem comes with non-primitive value
function $Set () {}
$Set.prototype.items = [];
$Set.prototype.add = function (item) {
  this.items.push(item);
};
var obj3 = new $Set();
var obj4 = new $Set();
obj4.add(1);
console.log(obj3.items.length === 1);
console.log(obj4.items.length === 1);

////////////////////////////////////////
// Solution
////////////////////////////////////////

// move property initialization into constructor
function Set () {
  this.items = [];
}
Set.prototype.add = function (item) {
  this.items.push(item);
};
var obj5 = new Set();
var obj6 = new Set();
obj6.add(1);
console.log(obj5.items.length === 0);
console.log(obj6.items.length === 1);

////////////////////////////////////////
// Reference
////////////////////////////////////////

// [coffeescript-class-member](http://stackoverflow.com/questions/8355371/coffeescript-class-members)
<|endoftext|>


<commit_before>const Submission = require('../models/Submission');
const User = require('../models/User');
const Language = require('../models/Language');
const Hexdump = require('hexdump-stream');
const concatStream = require('concat-stream');
const isValidUTF8 = require('utf-8-validate');
const qs = require('querystring');

/*
 * GET /submissions
 */
module.exports.getSubmissions = async (req, res) => {
	const query = {
		contest: req.contest,
	};

	if (req.query.author) {
		const author = await User.findOne({
			email: `${req.query.author}@twitter.com`,
		});
		if (author) {
			query.user = author._id;
		}
	}

	if (req.query.language) {
		const language = await Language.findOne({
			slug: req.query.language,
			contest: req.contest,
		});
		if (language) {
			query.language = language._id;
		}
	}

	const page = parseInt(req.query && req.query.page) || 0;

	if (req.query.status) {
		query.status = req.query.status;
	}

	const submissions = await Submission.find(query)
		.sort({_id: -1})
		.populate('user')
		.populate('language')
		.skip(500 * page)
		.limit(500)
		.exec();

	const totalSubmissions = await Submission.find(query)
		.count()
		.exec();

	const users_id = await Submission.find({contest: req.contest})
		.distinct('user')
		.exec();
	const langs_id = await Submission.find({contest: req.contest})
		.distinct('language')
		.exec();
	const usersRecord = await User.find({_id: {$in: users_id}}).exec();
	const langsRecord = await Language.find({_id: {$in: langs_id}}).exec();
	const users = usersRecord.map((user) => {
		const team = user.team.find((t) => t.contest.equals(req.contest._id));
		const displayName = (team ? `team-${team.value}` : '') + user.name();
		return {email: user.email, displayName};
	}).sort(({displayName: dispA}, {displayName: dispB}) => dispA.localeCompare(dispB));
	const langs = langsRecord.sort(({slug: slugA}, {slug: slugB}) => slugA.localeCompare(slugB));

	res.render('submissions', {
		contest: req.contest,
		title: 'Submissions',
		submissions,
		users,
		langs,
		page,
		query: req.query || {},
		totalPages: Math.ceil(totalSubmissions / 500),
		encode: qs.encode,
	});
};

/*
 * GET /submissions/:submission
 */
module.exports.getSubmission = async (req, res) => {
	const _id = req.params.submission;

	const submission = await Submission.findOne({_id})
		.populate('user')
		.populate('language')
		.populate('contest')
		.exec();

	if (submission === null) {
		res.sendStatus(404);
		return;
	}

	if (submission.contest.id !== req.params.contest) {
		res.redirect(
			`/contests/${submission.contest.id}/submissions/${submission._id}`
		);
		return;
	}

	const {code, isHexdump} = await new Promise((resolve) => {
		// eslint-disable-next-line no-control-regex
		if (
			isValidUTF8(submission.code) &&
			!submission.code
				.toString()
				.match(/[\x00-\x08\x0b\x0c\x0e-\x1F\x7F\x80-\x9F]/)
		) {
			resolve({code: submission.code.toString(), isHexdump: false});
			return;
		}

		const hexdump = new Hexdump();
		const concatter = concatStream((dump) => {
			resolve({code: dump, isHexdump: true});
		});

		hexdump.pipe(concatter);
		hexdump.end(submission.code);
	});

	res.render('submission', {
		contest: req.contest,
		title: `Submission by ${submission.user.name()} (${
			submission.language.slug
		}, ${submission.size} bytes)`,
		submission,
		code,
		isHexdump,
		selfTeam:
			req.user &&
			req.user.getTeam(req.contest) === submission.user.getTeam(req.contest),
	});
};

module.exports.getOldSubmission = async (req, res) => {
	const _id = req.params.submission;

	const submission = await Submission.findOne({_id})
		.populate('contest')
		.exec();

	if (submission === null) {
		res.sendStatus(404);
		return;
	}

	res.redirect(
		`/contests/${submission.contest.id}/submissions/${submission._id}`
	);
};

/*
 * GET /contest/:contest/submissions/:submission/raw
 */
module.exports.getRawSubmission = async (req, res) => {
	const _id = req.params.submission;

	const submission = await Submission.findOne({_id})
		.populate('user')
		.exec();
	const selfTeam =
		req.user &&
		req.user.getTeam(req.contest) === submission.user.getTeam(req.contest);

	if (!selfTeam && !req.contest.isEnded() && !(req.user && req.user.admin)) {
		res.sendStatus(403);
		return;
	}

	if (submission === null) {
		res.sendStatus(404);
		return;
	}

	res.set({
		'Content-Type': 'text/plain',
		'Content-Disposition': 'attachment',
	});

	res.send(submission.code);
};
<commit_msg>submission.js: match git<commit_after>const Submission = require('../models/Submission');
const User = require('../models/User');
const Language = require('../models/Language');
const Hexdump = require('hexdump-stream');
const concatStream = require('concat-stream');
const isValidUTF8 = require('utf-8-validate');
const qs = require('querystring');

/*
 * GET /submissions
 */
module.exports.getSubmissions = async (req, res) => {
	const query = {
		contest: req.contest,
	};

	if (req.query.author) {
		const author = await User.findOne({
			email: `${req.query.author}@twitter.com`,
		});
		if (author) {
			query.user = author._id;
		} else {
                   // TODO : GitHub
                  const author = await User.findOne({
                           email: `${req.query.author}@github.com`,
                  });
                  if (author) {
                           query.user = author._id;
                  }
                }
	}

	if (req.query.language) {
		const language = await Language.findOne({
			slug: req.query.language,
			contest: req.contest,
		});
		if (language) {
			query.language = language._id;
		}
	}

	const page = parseInt(req.query && req.query.page) || 0;

	if (req.query.status) {
		query.status = req.query.status;
	}

	const submissions = await Submission.find(query)
		.sort({_id: -1})
		.populate('user')
		.populate('language')
		.skip(500 * page)
		.limit(500)
		.exec();

	const totalSubmissions = await Submission.find(query)
		.count()
		.exec();

	const users_id = await Submission.find({contest: req.contest})
		.distinct('user')
		.exec();
	const langs_id = await Submission.find({contest: req.contest})
		.distinct('language')
		.exec();
	const usersRecord = await User.find({_id: {$in: users_id}}).exec();
	const langsRecord = await Language.find({_id: {$in: langs_id}}).exec();
	const users = usersRecord.map((user) => {
		const team = user.team.find((t) => t.contest.equals(req.contest._id));
		const displayName = (team ? `team-${team.value}` : '') + user.name();
		return {email: user.email, displayName};
	}).sort(({displayName: dispA}, {displayName: dispB}) => dispA.localeCompare(dispB));
	const langs = langsRecord.sort(({slug: slugA}, {slug: slugB}) => slugA.localeCompare(slugB));

	res.render('submissions', {
		contest: req.contest,
		title: 'Submissions',
		submissions,
		users,
		langs,
		page,
		query: req.query || {},
		totalPages: Math.ceil(totalSubmissions / 500),
		encode: qs.encode,
	});
};

/*
 * GET /submissions/:submission
 */
module.exports.getSubmission = async (req, res) => {
	const _id = req.params.submission;

	const submission = await Submission.findOne({_id})
		.populate('user')
		.populate('language')
		.populate('contest')
		.exec();

	if (submission === null) {
		res.sendStatus(404);
		return;
	}

	if (submission.contest.id !== req.params.contest) {
		res.redirect(
			`/contests/${submission.contest.id}/submissions/${submission._id}`
		);
		return;
	}

	const {code, isHexdump} = await new Promise((resolve) => {
		// eslint-disable-next-line no-control-regex
		if (
			isValidUTF8(submission.code) &&
			!submission.code
				.toString()
				.match(/[\x00-\x08\x0b\x0c\x0e-\x1F\x7F\x80-\x9F]/)
		) {
			resolve({code: submission.code.toString(), isHexdump: false});
			return;
		}

		const hexdump = new Hexdump();
		const concatter = concatStream((dump) => {
			resolve({code: dump, isHexdump: true});
		});

		hexdump.pipe(concatter);
		hexdump.end(submission.code);
	});

	res.render('submission', {
		contest: req.contest,
		title: `Submission by ${submission.user.name()} (${
			submission.language.slug
		}, ${submission.size} bytes)`,
		submission,
		code,
		isHexdump,
		selfTeam:
			req.user &&
			req.user.getTeam(req.contest) === submission.user.getTeam(req.contest),
	});
};

module.exports.getOldSubmission = async (req, res) => {
	const _id = req.params.submission;

	const submission = await Submission.findOne({_id})
		.populate('contest')
		.exec();

	if (submission === null) {
		res.sendStatus(404);
		return;
	}

	res.redirect(
		`/contests/${submission.contest.id}/submissions/${submission._id}`
	);
};

/*
 * GET /contest/:contest/submissions/:submission/raw
 */
module.exports.getRawSubmission = async (req, res) => {
	const _id = req.params.submission;

	const submission = await Submission.findOne({_id})
		.populate('user')
		.exec();
	const selfTeam =
		req.user &&
		req.user.getTeam(req.contest) === submission.user.getTeam(req.contest);

	if (!selfTeam && !req.contest.isEnded() && !(req.user && req.user.admin)) {
		res.sendStatus(403);
		return;
	}

	if (submission === null) {
		res.sendStatus(404);
		return;
	}

	res.set({
		'Content-Type': 'text/plain',
		'Content-Disposition': 'attachment',
	});

	res.send(submission.code);
};
<|endoftext|>


<commit_before>/**
 * Basic functions for the navigation toolbar, used by all top level Python
 * scripts, including undo and redo for the structurer and segmenter.
 * Author: Amir Zeldes
*/

function save(){
    disable_buttons();
    $("#nav_save").addClass("nav_button_inset");
    document.getElementById("timestamp").value = Date();
    document.getElementById("edit_form").submit();

}

function open_segment(){
    if (document.getElementById("dirty").value=="dirty"){
        var r = confirm("You have unsaved work - really leave this page without saving?");
        if (r == false) {
            return;
        }
    }
    document.getElementById("edit_form").action="segment";
    if(document.getElementById("serve_mode").value=="server"){document.getElementById("edit_form").action="segment.py";}
    document.getElementById("edit_form").submit();
}

function open_structure(){
    if (document.getElementById("dirty").value=="dirty"){
        var r = confirm("You have unsaved work - really leave this page without saving?");
        if (r == false) {
            return;
        }
    }
    document.getElementById("edit_form").action="structure";
    if(document.getElementById("serve_mode").value=="server"){document.getElementById("edit_form").action="structure.py";}
    document.getElementById("edit_form").submit();
}

function open_open(){
    if (document.getElementById("dirty").value=="dirty"){
        var r = confirm("You have unsaved work - really leave this page without saving?");
        if (r == false) {
            return;
        }
    }
    if(document.getElementById("serve_mode").value=="server"){
		document.getElementById("edit_form").action="open.py";
	}
	else{
		document.getElementById("edit_form").action="open";
	}
    document.getElementById("edit_form").submit();
}

function open_admin(){
    if (document.getElementById("dirty").value=="dirty"){
        var r = confirm("You have unsaved work - really leave this page without saving?");
        if (r == false) {
            return;
        }
    }
    document.getElementById("edit_form").action="admin";
    if(document.getElementById("serve_mode").value=="server"){document.getElementById("edit_form").action="admin.py";}
    document.getElementById("edit_form").submit();
}

function show_help(){
    if( $(".help")[0].style.display!="block"){
        $(".help")[0].style.display="block";
        $('body, .tab_btn, .tab, .tab button, .doclist, ._jsPlumb_overlay, #segment_canvas, .minibtn, .num_id, .nav_button').toggleClass("blackout");
        $('.tab_btn, .tab, .tab button, .doclist, ._jsPlumb_overlay, #segment_canvas, .minibtn, .num_id, .nav_button').toggleClass("no_events");
    }
    else {
        hide_help();
    }

}

function hide_help(){
    $(".help")[0].style.display="none";
    $('body, .tab_btn, .tab, .tab button, .doclist, ._jsPlumb_overlay, #segment_canvas, .minibtn, .num_id, .nav_button').toggleClass("blackout");
    $('.tab_btn, .tab, .tab button, .doclist, ._jsPlumb_overlay, #segment_canvas, .minibtn, .num_id, .nav_button').toggleClass("no_events");
}

function show_about(){
    if( $(".about")[0].style.display!="block"){
        $(".about")[0].style.display="block";
        $('body, .tab_btn, .tab, .tab button, .doclist, ._jsPlumb_overlay, #segment_canvas, .minibtn, .num_id, .nav_button').toggleClass("blackout");
        $('.tab_btn, .tab, .tab button, .doclist, ._jsPlumb_overlay, #segment_canvas, .minibtn, .num_id, .nav_button').toggleClass("no_events");
    }
    else {
        hide_about();
    }

}

function hide_about(){
    $(".about")[0].style.display="none";
    $('body, .tab_btn, .tab, .tab button, .doclist, ._jsPlumb_overlay, #segment_canvas, .minibtn, .num_id, .nav_button').toggleClass("blackout");
    $('.tab_btn, .tab, .tab button, .doclist, ._jsPlumb_overlay, #segment_canvas, .minibtn, .num_id, .nav_button').toggleClass("no_events");
}

function do_reset(){
    var r = confirm("Really reset this document? All of your annotations will be deleted and the original imported state of this file will be restored!");
    if (r == false) {
        return;
    }
    disable_buttons();
    $("#nav_reset").addClass("nav_button_inset");
    document.getElementById('reset').value='reset';
    document.getElementById('logging').value += 'reset;';
    document.getElementById('edit_form').submit()
}

function do_open(project_doc){
    if (project_doc =="") {alert("No document has been selected!");return;}
    document.getElementById('current_project').value = project_doc.split('/')[0];
    document.getElementById('current_doc').value = project_doc.split('/')[1];
    document.getElementById('edit_form').submit();
}

function do_quickexp(){
    if (document.getElementById("dirty").value=="dirty"){
        var r = confirm("You have unsaved work - really export without saved work? Changes will be omitted.");
        if (r == false) {
            return;
        }
    }
    document.getElementById("quickexp_form").action="quick_export";
    if(document.getElementById("serve_mode").value=="server"){document.getElementById("quickexp_form").action="quick_export.py";}
    document.getElementById("quickexp_form").submit();
}

function do_screenshot(){
    // create a deep copy of the canvas (the root html element of the rst tree)
    // so that we can change and discard it once we're done without affecting
    // the real html elements
    var canvasDivCopy = $("#canvas").clone();
    var offscreenDiv = $('

');
    offscreenDiv.append(canvasDivCopy);
    offscreenDiv.insertAfter($("#canvas"));

    // need to replace svg elements with canvas elements or else they won't show up in html2canvas
    // https://github.com/niklasvh/html2canvas/issues/1179
    var elements = canvasDivCopy.find('svg').map(function() {
        var svg = $(this);
        var canvas = $('<canvas></canvas>').css({position: 'absolute', left:svg.css('left'), top: svg.css('top')});

        svg.replaceWith(canvas);

        // Get the raw SVG string and curate it
        var content = svg.wrap('

').parent().html();
        svg.unwrap();

        canvg(canvas[0], content);

        return {
            svg: svg,
            canvas: canvas
        };
    });

    // remove ui elements that we don't want in the picture
    canvasDivCopy.find("#document_name").remove();
    canvasDivCopy.find("#show-all-signals").remove();
    canvasDivCopy.find(".minibtn").remove();
    canvasDivCopy.find(".rst_rel").replaceWith(function(i, htmlStr) {
        var select = $(htmlStr);
        var text = select.val();
        return '
' + text + '
';
    });

    // workaround for html2canvas bug
    canvasDivCopy.find(".tok").css("font-size", "9pt");

    // since the contents of #inner_canvas are positioned absolutely, it does not
    // scale its width and height automatically to the content. we have to
    // detect this rather crudely: for the width we find the left offsets of
    // EDU's, and for height we use toks
    var width = 100;
    var canvasDivLeftOffset = canvasDivCopy.offset().left;
    canvasDivCopy.find(".edu").each(function() {
        var div = $(this);
        // 16 gives some padding on the right
        var divWidth = (div.offset().left - canvasDivLeftOffset) + div.outerWidth() + 16;
        if (divWidth > width) {
            width = divWidth;
        }
    });

    var height = 100;
    var canvasDivTopOffset = canvasDivCopy.offset().top;
    canvasDivCopy.find(".tok").each(function() {
        var tok = $(this);
        // 100 is an arbitrarily chosen number that worked when toks were highlighted and
        // when they were not highlighted.
        var tokHeight = (tok.offset().top - canvasDivTopOffset) + tok.outerHeight() + 100;
        if (tokHeight > height) {
            height = tokHeight;
        }
    });

    html2canvas(canvasDivCopy[0], {height: height, width: width, scale: 2})
    .then(function(canvas){
        elements.each(function() {
            canvas.replaceWith(this.svg);
        });

        var url = canvas.toDataURL("image/png");

        // use anchor to download it
        var a = document.createElement('a');
        var filename = document.getElementById('current_doc').value.replace(".rs3","");
        a.setAttribute('href', url);
        a.setAttribute('download', filename + ".png");
        a.setAttribute('download', filename + ".png");
        $(a).insertAfter($("#canvas"));
        a.click();

        $(a).remove();
        offscreenDiv.remove();
    });
}

function undo(){

    //document.getElementById("undo_log").value = reorder_undo_log(document.getElementById("undo_log").value);
    if (document.getElementById("undo_log").value =="") {alert("Nothing to undo!");return;}
    document.getElementById("undo_state").value = "undo";
    actions = pop_undo();
    action_array = actions.split("+")
    action_array = action_array.reverse();
    for (action in action_array){
        act(action_array[action]);
    }
    pop_action();
    //recalculate_depth();
    document.getElementById("undo_state").value = "";

}

function pop_undo(){

    undo_log = document.getElementById("undo_log").value;
    myRegexp = /([^;]+);$/g;
    last_action = myRegexp.exec(undo_log);
    document.getElementById("undo_log").value = undo_log.replace(/[^;]+;$/,"");
    if (document.getElementById("undo_log").value==""){
            document.getElementById("dirty").value = "";
    }
    return last_action[1];
}

function append_undo(undo_action){

    // each undo click should correspond to a series of actions ending in a semicolon
    if (document.getElementById("undo_state").value!="undo"){ //only append undo actions if we are not during an undo state
        if (undo_action.length >0){
            if (undo_action.startsWith("+")){//plus appended plus actions should be inserted before the semi-colon
                document.getElementById("undo_log").value = document.getElementById("undo_log").value.replace(/;$/,"");
            }
            document.getElementById("undo_log").value += undo_action;
            if (!(undo_action.endsWith("+"))){ //prepended plus actions should not receive a semicolon
                document.getElementById("undo_log").value += ";";
            }
        }
    }

}

function pop_action(){

    if ($("#action").length >0){
        hidden_action = document.getElementById("action"); //for structure.py script
    }
    else {
        hidden_action = document.getElementById("seg_action"); //for segment.py script
    }

    if (hidden_action.value!=""){
        //put last action into redo
        myRegexp = /([^;]+)$/g;
        last_action = myRegexp.exec(hidden_action.value);
        append_redo(last_action[1]);

        //delete the action from the action field to remove from next save
        hidden_action.value = hidden_action.value.replace(/;?[^;]+$/,"")
    }

}

function modify_undo(find, replace){

    undo_log = document.getElementById("undo_log").value;
    n = undo_log.lastIndexOf(find);
    undo_log = undo_log.slice(0, n) + undo_log.slice(n).replace(find, replace);
    document.getElementById("undo_log").value = undo_log;

}

function redo(){

    if (document.getElementById("redo_log").value =="") {alert("Nothing to redo!");return;}
    document.getElementById("undo_state").value = "redo";
    action = pop_redo();
    act(action);

}

function append_redo(redo_action){

    // each redo click should correspond to an action ending in a semicolon
    if (redo_action.length >0){
        document.getElementById("redo_log").value += redo_action + ";";
    }

}

function pop_redo(){

    redo_log = document.getElementById("redo_log").value;
    myRegexp = /([^;]+);$/g;
    redo_action = myRegexp.exec(redo_log);
    document.getElementById("redo_log").value = redo_log.replace(/[^;]+;$/,"");
    return redo_action[1];

}

function disable_buttons(){
    $(".minibtn").prop("disabled",true);
    $(".nav_button").prop("disabled",true);
}

function enable_buttons(){
    $(".minibtn").prop("disabled",false);
    $(".nav_button").prop("disabled",false);
}

function enable_guidelines(url){
    if ((document.getElementById("current_guidelines").value).length > 1 && document.getElementById("current_guidelines").value != "**current_guidelines**"){
        $("#guidelines").prop("disabled",false);
    }
}

function show_guidelines(){
    window.open(document.getElementById("current_guidelines").value,'_blank');
}
<commit_msg>use relation's display name instead of underlying value<commit_after>/**
 * Basic functions for the navigation toolbar, used by all top level Python
 * scripts, including undo and redo for the structurer and segmenter.
 * Author: Amir Zeldes
*/

function save(){
    disable_buttons();
    $("#nav_save").addClass("nav_button_inset");
    document.getElementById("timestamp").value = Date();
    document.getElementById("edit_form").submit();

}

function open_segment(){
    if (document.getElementById("dirty").value=="dirty"){
        var r = confirm("You have unsaved work - really leave this page without saving?");
        if (r == false) {
            return;
        }
    }
    document.getElementById("edit_form").action="segment";
    if(document.getElementById("serve_mode").value=="server"){document.getElementById("edit_form").action="segment.py";}
    document.getElementById("edit_form").submit();
}

function open_structure(){
    if (document.getElementById("dirty").value=="dirty"){
        var r = confirm("You have unsaved work - really leave this page without saving?");
        if (r == false) {
            return;
        }
    }
    document.getElementById("edit_form").action="structure";
    if(document.getElementById("serve_mode").value=="server"){document.getElementById("edit_form").action="structure.py";}
    document.getElementById("edit_form").submit();
}

function open_open(){
    if (document.getElementById("dirty").value=="dirty"){
        var r = confirm("You have unsaved work - really leave this page without saving?");
        if (r == false) {
            return;
        }
    }
    if(document.getElementById("serve_mode").value=="server"){
		document.getElementById("edit_form").action="open.py";
	}
	else{
		document.getElementById("edit_form").action="open";
	}
    document.getElementById("edit_form").submit();
}

function open_admin(){
    if (document.getElementById("dirty").value=="dirty"){
        var r = confirm("You have unsaved work - really leave this page without saving?");
        if (r == false) {
            return;
        }
    }
    document.getElementById("edit_form").action="admin";
    if(document.getElementById("serve_mode").value=="server"){document.getElementById("edit_form").action="admin.py";}
    document.getElementById("edit_form").submit();
}

function show_help(){
    if( $(".help")[0].style.display!="block"){
        $(".help")[0].style.display="block";
        $('body, .tab_btn, .tab, .tab button, .doclist, ._jsPlumb_overlay, #segment_canvas, .minibtn, .num_id, .nav_button').toggleClass("blackout");
        $('.tab_btn, .tab, .tab button, .doclist, ._jsPlumb_overlay, #segment_canvas, .minibtn, .num_id, .nav_button').toggleClass("no_events");
    }
    else {
        hide_help();
    }

}

function hide_help(){
    $(".help")[0].style.display="none";
    $('body, .tab_btn, .tab, .tab button, .doclist, ._jsPlumb_overlay, #segment_canvas, .minibtn, .num_id, .nav_button').toggleClass("blackout");
    $('.tab_btn, .tab, .tab button, .doclist, ._jsPlumb_overlay, #segment_canvas, .minibtn, .num_id, .nav_button').toggleClass("no_events");
}

function show_about(){
    if( $(".about")[0].style.display!="block"){
        $(".about")[0].style.display="block";
        $('body, .tab_btn, .tab, .tab button, .doclist, ._jsPlumb_overlay, #segment_canvas, .minibtn, .num_id, .nav_button').toggleClass("blackout");
        $('.tab_btn, .tab, .tab button, .doclist, ._jsPlumb_overlay, #segment_canvas, .minibtn, .num_id, .nav_button').toggleClass("no_events");
    }
    else {
        hide_about();
    }

}

function hide_about(){
    $(".about")[0].style.display="none";
    $('body, .tab_btn, .tab, .tab button, .doclist, ._jsPlumb_overlay, #segment_canvas, .minibtn, .num_id, .nav_button').toggleClass("blackout");
    $('.tab_btn, .tab, .tab button, .doclist, ._jsPlumb_overlay, #segment_canvas, .minibtn, .num_id, .nav_button').toggleClass("no_events");
}

function do_reset(){
    var r = confirm("Really reset this document? All of your annotations will be deleted and the original imported state of this file will be restored!");
    if (r == false) {
        return;
    }
    disable_buttons();
    $("#nav_reset").addClass("nav_button_inset");
    document.getElementById('reset').value='reset';
    document.getElementById('logging').value += 'reset;';
    document.getElementById('edit_form').submit()
}

function do_open(project_doc){
    if (project_doc =="") {alert("No document has been selected!");return;}
    document.getElementById('current_project').value = project_doc.split('/')[0];
    document.getElementById('current_doc').value = project_doc.split('/')[1];
    document.getElementById('edit_form').submit();
}

function do_quickexp(){
    if (document.getElementById("dirty").value=="dirty"){
        var r = confirm("You have unsaved work - really export without saved work? Changes will be omitted.");
        if (r == false) {
            return;
        }
    }
    document.getElementById("quickexp_form").action="quick_export";
    if(document.getElementById("serve_mode").value=="server"){document.getElementById("quickexp_form").action="quick_export.py";}
    document.getElementById("quickexp_form").submit();
}

function do_screenshot(){
    // create a deep copy of the canvas (the root html element of the rst tree)
    // so that we can change and discard it once we're done without affecting
    // the real html elements
    var canvasDivCopy = $("#canvas").clone();
    var offscreenDiv = $('

');
    offscreenDiv.append(canvasDivCopy);
    offscreenDiv.insertAfter($("#canvas"));

    // need to replace svg elements with canvas elements or else they won't show up in html2canvas
    // https://github.com/niklasvh/html2canvas/issues/1179
    var elements = canvasDivCopy.find('svg').map(function() {
        var svg = $(this);
        var canvas = $('<canvas></canvas>').css({position: 'absolute', left:svg.css('left'), top: svg.css('top')});

        svg.replaceWith(canvas);

        // Get the raw SVG string and curate it
        var content = svg.wrap('

').parent().html();
        svg.unwrap();

        canvg(canvas[0], content);

        return {
            svg: svg,
            canvas: canvas
        };
    });

    // remove ui elements that we don't want in the picture
    canvasDivCopy.find("#document_name").remove();
    canvasDivCopy.find("#show-all-signals").remove();
    canvasDivCopy.find(".minibtn").remove();
    canvasDivCopy.find(".rst_rel").replaceWith(function(i, htmlStr) {
        var select = $(htmlStr);
        var text = select.find('option:selected').text();
        return '
' + text + '
';
    });

    // workaround for html2canvas bug
    canvasDivCopy.find(".tok").css("font-size", "9pt");

    // since the contents of #inner_canvas are positioned absolutely, it does not
    // scale its width and height automatically to the content. we have to
    // detect this rather crudely: for the width we find the left offsets of
    // EDU's, and for height we use toks
    var width = 100;
    var canvasDivLeftOffset = canvasDivCopy.offset().left;
    canvasDivCopy.find(".edu").each(function() {
        var div = $(this);
        // 16 gives some padding on the right
        var divWidth = (div.offset().left - canvasDivLeftOffset) + div.outerWidth() + 16;
        if (divWidth > width) {
            width = divWidth;
        }
    });

    var height = 100;
    var canvasDivTopOffset = canvasDivCopy.offset().top;
    canvasDivCopy.find(".tok").each(function() {
        var tok = $(this);
        // 100 is an arbitrarily chosen number that worked when toks were highlighted and
        // when they were not highlighted.
        var tokHeight = (tok.offset().top - canvasDivTopOffset) + tok.outerHeight() + 100;
        if (tokHeight > height) {
            height = tokHeight;
        }
    });

    html2canvas(canvasDivCopy[0], {height: height, width: width, scale: 2})
    .then(function(canvas){
        elements.each(function() {
            canvas.replaceWith(this.svg);
        });

        var url = canvas.toDataURL("image/png");

        // use anchor to download it
        var a = document.createElement('a');
        var filename = document.getElementById('current_doc').value.replace(".rs3","");
        a.setAttribute('href', url);
        a.setAttribute('download', filename + ".png");
        a.setAttribute('download', filename + ".png");
        $(a).insertAfter($("#canvas"));
        a.click();

        $(a).remove();
        offscreenDiv.remove();
    });
}

function undo(){

    //document.getElementById("undo_log").value = reorder_undo_log(document.getElementById("undo_log").value);
    if (document.getElementById("undo_log").value =="") {alert("Nothing to undo!");return;}
    document.getElementById("undo_state").value = "undo";
    actions = pop_undo();
    action_array = actions.split("+")
    action_array = action_array.reverse();
    for (action in action_array){
        act(action_array[action]);
    }
    pop_action();
    //recalculate_depth();
    document.getElementById("undo_state").value = "";

}

function pop_undo(){

    undo_log = document.getElementById("undo_log").value;
    myRegexp = /([^;]+);$/g;
    last_action = myRegexp.exec(undo_log);
    document.getElementById("undo_log").value = undo_log.replace(/[^;]+;$/,"");
    if (document.getElementById("undo_log").value==""){
            document.getElementById("dirty").value = "";
    }
    return last_action[1];
}

function append_undo(undo_action){

    // each undo click should correspond to a series of actions ending in a semicolon
    if (document.getElementById("undo_state").value!="undo"){ //only append undo actions if we are not during an undo state
        if (undo_action.length >0){
            if (undo_action.startsWith("+")){//plus appended plus actions should be inserted before the semi-colon
                document.getElementById("undo_log").value = document.getElementById("undo_log").value.replace(/;$/,"");
            }
            document.getElementById("undo_log").value += undo_action;
            if (!(undo_action.endsWith("+"))){ //prepended plus actions should not receive a semicolon
                document.getElementById("undo_log").value += ";";
            }
        }
    }

}

function pop_action(){

    if ($("#action").length >0){
        hidden_action = document.getElementById("action"); //for structure.py script
    }
    else {
        hidden_action = document.getElementById("seg_action"); //for segment.py script
    }

    if (hidden_action.value!=""){
        //put last action into redo
        myRegexp = /([^;]+)$/g;
        last_action = myRegexp.exec(hidden_action.value);
        append_redo(last_action[1]);

        //delete the action from the action field to remove from next save
        hidden_action.value = hidden_action.value.replace(/;?[^;]+$/,"")
    }

}

function modify_undo(find, replace){

    undo_log = document.getElementById("undo_log").value;
    n = undo_log.lastIndexOf(find);
    undo_log = undo_log.slice(0, n) + undo_log.slice(n).replace(find, replace);
    document.getElementById("undo_log").value = undo_log;

}

function redo(){

    if (document.getElementById("redo_log").value =="") {alert("Nothing to redo!");return;}
    document.getElementById("undo_state").value = "redo";
    action = pop_redo();
    act(action);

}

function append_redo(redo_action){

    // each redo click should correspond to an action ending in a semicolon
    if (redo_action.length >0){
        document.getElementById("redo_log").value += redo_action + ";";
    }

}

function pop_redo(){

    redo_log = document.getElementById("redo_log").value;
    myRegexp = /([^;]+);$/g;
    redo_action = myRegexp.exec(redo_log);
    document.getElementById("redo_log").value = redo_log.replace(/[^;]+;$/,"");
    return redo_action[1];

}

function disable_buttons(){
    $(".minibtn").prop("disabled",true);
    $(".nav_button").prop("disabled",true);
}

function enable_buttons(){
    $(".minibtn").prop("disabled",false);
    $(".nav_button").prop("disabled",false);
}

function enable_guidelines(url){
    if ((document.getElementById("current_guidelines").value).length > 1 && document.getElementById("current_guidelines").value != "**current_guidelines**"){
        $("#guidelines").prop("disabled",false);
    }
}

function show_guidelines(){
    window.open(document.getElementById("current_guidelines").value,'_blank');
}
<|endoftext|>


<commit_before>/**
 * @flow
 */

import assert from 'assert'
import React from 'react'
import { Action, merge } from 'microcosm'
import serialize from 'form-serialize'

/* istanbul ignore next */
const identity = n => n
/* istanbul ignore next */
const noop = () => {}

type Props = {
  action: *,
  onOpen: ?Callback,
  onUpdate: ?Callback,
  onError: ?Callback,
  onCancel: ?Callback,
  onDone: ?Callback,
  onSubmit: (event: Event, Action: *) => *,
  confirm: (value?: *, event?: Event) => boolean,
  prepare: (value?: *, event?: Event) => *,
  send: ?Sender,
  serializer: (form: Element) => Object
}

type Context = {
  send: ?Sender
}

class ActionForm extends React.PureComponent<Props> {
  static defaultProps: Props
  static contextTypes: Context

  send: Sender
  form: Element
  onSubmit: *
  assignForm: Element => void

  constructor(props: Props, context: Context) {
    super(props, context)

    this.send = this.props.send || this.context.send
    this.onSubmit = this.onSubmit.bind(this)
  }

  setForm = (el: Element) => {
    this.form = el
  }

  render() {
    let props = merge(this.props, {
      onSubmit: this.onSubmit,
      ref: this.setForm
    })

    // Remove invalid props to prevent React warnings
    delete props.action
    delete props.prepare
    delete props.confirm
    delete props.serializer
    delete props.onOpen
    delete props.onDone
    delete props.onUpdate
    delete props.onCancel
    delete props.onError
    delete props.send

    return React.createElement('form', props)
  }

  onSubmit(event: Event) {
    event.preventDefault()
    this.submit(event)
  }

  submit(event: Event) {
    let form = this.form

    assert(
      form,
      'ActionForm has no form reference and can not submit. This can happen ' +
        'if submit() is called after the parent component has unmounted.'
    )

    let params = this.props.prepare(this.props.serializer(form))
    let action = null

    if (!this.props.confirm(params, event)) {
      return
    }

    if (this.props.action) {
      action = this.send(this.props.action, params)

      if (action && action instanceof Action) {
        action
          .onOpen(this.props.onOpen)
          .onUpdate(this.props.onUpdate)
          .onCancel(this.props.onCancel)
          .onDone(this.props.onDone)
          .onError(this.props.onError)
      }
    }

    this.props.onSubmit(event, action)
  }
}

ActionForm.contextTypes = {
  send: noop
}

ActionForm.defaultProps = {
  action: null,
  onOpen: null,
  onUpdate: null,
  onCancel: null,
  onError: null,
  onDone: null,
  onSubmit: noop,
  prepare: identity,
  confirm: (value, event) => true,
  send: null,
  serializer: form => serialize(form, { hash: true, empty: true })
}

export default ActionForm
<commit_msg>Avoid class inline fields<commit_after>/**
 * @flow
 */

import assert from 'assert'
import React from 'react'
import { Action, merge } from 'microcosm'
import serialize from 'form-serialize'

/* istanbul ignore next */
const identity = n => n
/* istanbul ignore next */
const noop = () => {}

type Props = {
  action: *,
  onOpen: ?Callback,
  onUpdate: ?Callback,
  onError: ?Callback,
  onCancel: ?Callback,
  onDone: ?Callback,
  onSubmit: (event: Event, Action: *) => *,
  confirm: (value?: *, event?: Event) => boolean,
  prepare: (value?: *, event?: Event) => *,
  send: ?Sender,
  serializer: (form: Element) => Object
}

type Context = {
  send: ?Sender
}

class ActionForm extends React.PureComponent<Props> {
  static defaultProps: Props
  static contextTypes: Context

  send: Sender
  form: Element
  onSubmit: *
  setForm: Element => void

  constructor(props: Props, context: Context) {
    super(props, context)

    this.send = this.props.send || this.context.send
    this.onSubmit = this.onSubmit.bind(this)
    this.setForm = this.setForm.bind(this)
  }

  setForm(el: Element) {
    this.form = el
  }

  render() {
    let props = merge(this.props, {
      onSubmit: this.onSubmit,
      ref: this.setForm
    })

    // Remove invalid props to prevent React warnings
    delete props.action
    delete props.prepare
    delete props.confirm
    delete props.serializer
    delete props.onOpen
    delete props.onDone
    delete props.onUpdate
    delete props.onCancel
    delete props.onError
    delete props.send

    return React.createElement('form', props)
  }

  onSubmit(event: Event) {
    event.preventDefault()
    this.submit(event)
  }

  submit(event: Event) {
    let form = this.form

    assert(
      form,
      'ActionForm has no form reference and can not submit. This can happen ' +
        'if submit() is called after the parent component has unmounted.'
    )

    let params = this.props.prepare(this.props.serializer(form))
    let action = null

    if (!this.props.confirm(params, event)) {
      return
    }

    if (this.props.action) {
      action = this.send(this.props.action, params)

      if (action && action instanceof Action) {
        action
          .onOpen(this.props.onOpen)
          .onUpdate(this.props.onUpdate)
          .onCancel(this.props.onCancel)
          .onDone(this.props.onDone)
          .onError(this.props.onError)
      }
    }

    this.props.onSubmit(event, action)
  }
}

ActionForm.contextTypes = {
  send: noop
}

ActionForm.defaultProps = {
  action: null,
  onOpen: null,
  onUpdate: null,
  onCancel: null,
  onError: null,
  onDone: null,
  onSubmit: noop,
  prepare: identity,
  confirm: (value, event) => true,
  send: null,
  serializer: form => serialize(form, { hash: true, empty: true })
}

export default ActionForm
<|endoftext|>


<commit_before>import {
  moduleFor,
  setup,
  test
}
from 'ember-qunit';
import Ember from 'ember';
import TmdbMovie from 'polyflix/models/tmdb-movie';

var movieMock = {
  adult: false,
  backdrop_path: '/8uO0gUM8aNqYLs1OsTBQiXu0fEv.jpg', // jshint ignore:line
  belongs_to_collection: null, // jshint ignore:line
  budget: 63000000,
  genres: [{
    id: 18,
    name: 'Drama'
  }],
  homepage: '',
  id: 550,
  imdb_id: 'tt0137523', // jshint ignore:line
  original_language: 'en', // jshint ignore:line
  original_title: 'Fight Club', // jshint ignore:line
  overview: 'A ticking-time-bomb insomniac and a slippery soap salesman channel primal male aggression into a shocking new form of therapy. Their concept catches on, with underground " fight clubs " forming in every town, until an eccentric gets in the way and ignites an out-of-control spiral toward oblivion.',
  popularity: 3.16634464772838,
  poster_path: '/2lECpi35Hnbpa4y46JX0aY3AWTy.jpg', // jshint ignore:line
  production_companies: [{ // jshint ignore:line
    name: '20th Century Fox',
    id: 25
  }, {
    name: 'Fox 2000 Pictures',
    id: 711
  }, {
    name: 'Regency Enterprises',
    id: 508
  }],
  production_countries: [{ // jshint ignore:line
    iso_3166_1: 'DE', // jshint ignore:line
    name: 'Germany'
  }, {
    iso_3166_1: 'US', // jshint ignore:line
    name: 'United States of America'
  }],
  release_date: '1999-10-14', // jshint ignore:line
  revenue: 100853753,
  runtime: 139,
  spoken_languages: [{ // jshint ignore:line
    iso_639_1: 'en', // jshint ignore:line
    name: 'English'
  }],
  status: 'Released',
  tagline: 'How much can you know about yourself if you\'ve never been in a fight?',
  title: 'Fight Club',
  video: false,
  vote_average: 7.8, // jshint ignore:line
  vote_count: 3286, // jshint ignore:line,
  tmdbConfig: {
    images: {
      base_url: 'http://image.tmdb.org/t/p/', // jshint ignore:line
      secure_base_url: 'https://image.tmdb.org/t/p/', // jshint ignore:line
      backdrop_sizes: ['w300', 'w780', 'w1280', 'original'], // jshint ignore:line
      logo_sizes: ['w45', 'w92', 'w154', 'w185', 'w300', 'w500', 'original'], // jshint ignore:line
      poster_sizes: ['w92', 'w154', 'w185', 'w342', 'w500', 'w780', 'original'], // jshint ignore:line
      profile_sizes: ['w45', 'w185', 'h632', 'original'], // jshint ignore:line
      still_sizes: ['w92', 'w185', 'w300', 'original'] // jshint ignore:line
    }
  }
};
var movie = null;

moduleFor('model:tmdb-movie', {});

test('It creates tmdb-movies', function() {
  Ember.run(function() {
    movie = TmdbMovie.create(movieMock);
  });
  equal(movie.get('title'), 'Fight Club');
});

test('Gets poster URL', function() {
  Ember.run(function() {
    movie = TmdbMovie.create(movieMock);
  });
  equal(movie.get('posterUrl'), 'http://image.tmdb.org/t/p/w185/2lECpi35Hnbpa4y46JX0aY3AWTy.jpg');
});<commit_msg>Add tmdb-movie backdrop URL test<commit_after>import {
  moduleFor,
  setup,
  test
}
from 'ember-qunit';
import Ember from 'ember';
import TmdbMovie from 'polyflix/models/tmdb-movie';

var movieMock = {
  adult: false,
  backdrop_path: '/8uO0gUM8aNqYLs1OsTBQiXu0fEv.jpg', // jshint ignore:line
  belongs_to_collection: null, // jshint ignore:line
  budget: 63000000,
  genres: [{
    id: 18,
    name: 'Drama'
  }],
  homepage: '',
  id: 550,
  imdb_id: 'tt0137523', // jshint ignore:line
  original_language: 'en', // jshint ignore:line
  original_title: 'Fight Club', // jshint ignore:line
  overview: 'A ticking-time-bomb insomniac and a slippery soap salesman channel primal male aggression into a shocking new form of therapy. Their concept catches on, with underground " fight clubs " forming in every town, until an eccentric gets in the way and ignites an out-of-control spiral toward oblivion.',
  popularity: 3.16634464772838,
  poster_path: '/2lECpi35Hnbpa4y46JX0aY3AWTy.jpg', // jshint ignore:line
  production_companies: [{ // jshint ignore:line
    name: '20th Century Fox',
    id: 25
  }, {
    name: 'Fox 2000 Pictures',
    id: 711
  }, {
    name: 'Regency Enterprises',
    id: 508
  }],
  production_countries: [{ // jshint ignore:line
    iso_3166_1: 'DE', // jshint ignore:line
    name: 'Germany'
  }, {
    iso_3166_1: 'US', // jshint ignore:line
    name: 'United States of America'
  }],
  release_date: '1999-10-14', // jshint ignore:line
  revenue: 100853753,
  runtime: 139,
  spoken_languages: [{ // jshint ignore:line
    iso_639_1: 'en', // jshint ignore:line
    name: 'English'
  }],
  status: 'Released',
  tagline: 'How much can you know about yourself if you\'ve never been in a fight?',
  title: 'Fight Club',
  video: false,
  vote_average: 7.8, // jshint ignore:line
  vote_count: 3286, // jshint ignore:line,
  tmdbConfig: {
    images: {
      base_url: 'http://image.tmdb.org/t/p/', // jshint ignore:line
      secure_base_url: 'https://image.tmdb.org/t/p/', // jshint ignore:line
      backdrop_sizes: ['w300', 'w780', 'w1280', 'original'], // jshint ignore:line
      logo_sizes: ['w45', 'w92', 'w154', 'w185', 'w300', 'w500', 'original'], // jshint ignore:line
      poster_sizes: ['w92', 'w154', 'w185', 'w342', 'w500', 'w780', 'original'], // jshint ignore:line
      profile_sizes: ['w45', 'w185', 'h632', 'original'], // jshint ignore:line
      still_sizes: ['w92', 'w185', 'w300', 'original'] // jshint ignore:line
    }
  }
};
var movie = null;

moduleFor('model:tmdb-movie', {});

test('It creates tmdb-movies', function() {
  Ember.run(function() {
    movie = TmdbMovie.create(movieMock);
  });
  equal(movie.get('title'), 'Fight Club');
});

test('Gets poster URL', function() {
  Ember.run(function() {
    movie = TmdbMovie.create(movieMock);
  });
  equal(movie.get('posterUrl'), 'http://image.tmdb.org/t/p/w185/2lECpi35Hnbpa4y46JX0aY3AWTy.jpg');
});

test('Gets backdrop URL', function() {
  Ember.run(function() {
    movie = TmdbMovie.create(movieMock);
  });
  equal(movie.get('backdropUrl'), 'http://image.tmdb.org/t/p/w1280/8uO0gUM8aNqYLs1OsTBQiXu0fEv.jpg');
});<|endoftext|>


<commit_before>'use strict';

var mean = require('meanio');
var rizeAPI = require('../../../../custom/rizers/server/service/rizeAPI');
var utils = require('../../../../custom/rizers/server/lib/utils');
var phantom = require('phantom');
var config = mean.config.clean;

/*
var rizeConfig={
  applicationUrl:config.applicationUrl,
  fbAppID:config.fbAppID,
  applicationName:config.applicationName
}*/
var rizeConfig=config;
var frontEndConfig={
  applicationUrl:config.applicationUrl,
  fbAppID:config.fbAppID,
  applicationName:config.applicationName
}

module.exports = function(System){
  return {
    render:function(req,res){
      //OPTIMIZE: this logic is currently duplicated on the frontend in the linkSafeString filter
      var categories = rizeAPI.getAllCategories();

      for (var i=0; i < categories.length; i++) {
        categories[i].safeName=utils.linkSafeString(categories[i].name);
      }

      if (categories.length > 0) {

        /** facebook/twitter don't obey the meta tag about fragments, so we detect user agent and behave appropriately **/
        /* for FB this is important for regular shares - for Twitter it's so that card detail views show images */
        var userAgent = req.headers['user-agent'];
        if (userAgent.indexOf('facebookexternalhit') >= 0 || userAgent.indexOf('Twitterbot') >= 0) {
          req.query._escaped_fragment_=req.originalUrl;
        }

        if(false && typeof(req.query._escaped_fragment_) !== 'undefined') {
            var translatedURL=config.applicationUrl;
            if (req.query._escaped_fragment_.charAt(0)=="/") {
              translatedURL+=req.query._escaped_fragment_.substr(1);
            } else {
              translatedURL+=req.query._escaped_fragment_;
            }
            var simpleRender=false;
            if (translatedURL.indexOf("/accounts/") != -1 ) {
               var urlArray=translatedURL.split("/");
               if (urlArray.length > 4) {
                  var accountID=urlArray[4];
                  if (accountID != null && accountID != "") {
                    console.log("render simpleSEO for accountID " + accountID);
                    var account = rizeAPI.getOneProfile(accountID);
                    account.profileUrl=translatedURL;
                    simpleRender=true;
                    res.render('rizeSEO',{
                        account:account,
                        rizeConfig:rizeConfig,
                    });
                  }
               }
            }
            if (!simpleRender) {
                console.log('running phantomJS for ' + translatedURL);
                phantom.create(function(ph) {
                  ph.createPage(function(page) {
                    //console.log('opening page ' + translatedURL);
                    page.open(translatedURL, function(status) {
                      page.evaluate((function() {   // jshint ignore:line
                        return document.getElementsByTagName('html')[0].innerHTML;
                      }), function(result) {
                        res.send(result);
                        return ph.exit();
                        //ph._phantom.kill('SIGTERM');
                      });
                    });
                  });
                });
            }
          // If there is no _escaped_fragment_, we return the normal index template.
          } else {
            var animate=false;
            if (req.param('animate')) {
              animate=true;
            }
            var forceDelay=false;
            if (req.param('forceDelay')) {
              forceDelay=true;
            }
            frontEndConfig.forceDelay=forceDelay;
            res.render('index',{
                categories:categories,
                rizeConfigStr:JSON.stringify(frontEndConfig),
                rizeConfig:rizeConfig,
                locals: {config: System.config.clean},
                animate:animate,
                forceDelay:forceDelay
            });
          }
      } else {
        //swig templates are cached.
        //we don't want to render that index view until our categories are ready or our navigation breaks
        res.json({status:'site is reloading'});
      }

    },
    aggregatedList:function(req,res) {
      res.send(res.locals.aggregatedassets);
    }
  };
};
<commit_msg>kill phantom except for fb/twitter crawls<commit_after>'use strict';

var mean = require('meanio');
var rizeAPI = require('../../../../custom/rizers/server/service/rizeAPI');
var utils = require('../../../../custom/rizers/server/lib/utils');
var phantom = require('phantom');
var config = mean.config.clean;

/*
var rizeConfig={
  applicationUrl:config.applicationUrl,
  fbAppID:config.fbAppID,
  applicationName:config.applicationName
}*/
var rizeConfig=config;
var frontEndConfig={
  applicationUrl:config.applicationUrl,
  fbAppID:config.fbAppID,
  applicationName:config.applicationName
}

module.exports = function(System){
  return {
    render:function(req,res){
      //OPTIMIZE: this logic is currently duplicated on the frontend in the linkSafeString filter
      var categories = rizeAPI.getAllCategories();

      for (var i=0; i < categories.length; i++) {
        categories[i].safeName=utils.linkSafeString(categories[i].name);
      }

      if (categories.length > 0) {

        /** facebook/twitter don't obey the meta tag about fragments, so we detect user agent and behave appropriately **/
        /* for FB this is important for regular shares - for Twitter it's so that card detail views show images */
        var userAgent = req.headers['user-agent'];
        if(userAgent.indexOf('facebookexternalhit') >= 0 || userAgent.indexOf('Twitterbot') >= 0) {
            req.query._escaped_fragment_=req.originalUrl;
            var translatedURL=config.applicationUrl;
            if (req.query._escaped_fragment_.charAt(0)=="/") {
              translatedURL+=req.query._escaped_fragment_.substr(1);
            } else {
              translatedURL+=req.query._escaped_fragment_;
            }
            /*
            var simpleRender=false;
            if (translatedURL.indexOf("/accounts/") != -1 ) {
               var urlArray=translatedURL.split("/");
               if (urlArray.length > 4) {
                  var accountID=urlArray[4];
                  if (accountID != null && accountID != "") {
                    console.log("render simpleSEO for accountID " + accountID);
                    var account = rizeAPI.getOneProfile(accountID);
                    account.profileUrl=translatedURL;
                    simpleRender=true;
                    res.render('rizeSEO',{
                        account:account,
                        rizeConfig:rizeConfig,
                    });
                  }
               }
            }
            */
            if (true) {
                console.log('running phantomJS for ' + translatedURL);
                phantom.create(function(ph) {
                  ph.createPage(function(page) {
                    //console.log('opening page ' + translatedURL);
                    page.open(translatedURL, function(status) {
                      page.evaluate((function() {   // jshint ignore:line
                        return document.getElementsByTagName('html')[0].innerHTML;
                      }), function(result) {
                        res.send(result);
                        return ph.exit();
                        //ph._phantom.kill('SIGTERM');
                      });
                    });
                  });
                });
            }
          // If there is no _escaped_fragment_, we return the normal index template.
          } else {
            var animate=false;
            if (req.param('animate')) {
              animate=true;
            }
            var forceDelay=false;
            if (req.param('forceDelay')) {
              forceDelay=true;
            }
            frontEndConfig.forceDelay=forceDelay;
            res.render('index',{
                categories:categories,
                rizeConfigStr:JSON.stringify(frontEndConfig),
                rizeConfig:rizeConfig,
                locals: {config: System.config.clean},
                animate:animate,
                forceDelay:forceDelay
            });
          }
      } else {
        //swig templates are cached.
        //we don't want to render that index view until our categories are ready or our navigation breaks
        res.json({status:'site is reloading'});
      }

    },
    aggregatedList:function(req,res) {
      res.send(res.locals.aggregatedassets);
    }
  };
};
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import withStyles from '../styles/withStyles';
import Typography from '../Typography';

export const styles = theme => ({
  root: {
    flex: '1 1 auto',
    padding: '0 16px',
    '&:first-child': {
      paddingLeft: 0,
    },
  },
  inset: {
    '&:first-child': {
      paddingLeft: theme.spacing.unit * 7,
    },
  },
  dense: {
    fontSize: theme.typography.pxToRem(13),
  },
  text: {}, // Present to allow external customization
  textDense: {
    fontSize: 'inherit',
  },
});

function ListItemText(props, context) {
  const {
    classes,
    className: classNameProp,
    disableTypography,
    inset,
    primary,
    secondary,
    ...other
  } = props;
  const { dense } = context;
  const className = classNames(
    classes.root,
    {
      [classes.dense]: dense,
      [classes.inset]: inset,
    },
    classNameProp,
  );

  return (

      {primary &&
        (disableTypography ? (
          primary
        ) : (
          <Typography
            type="subheading"
            className={classNames(classes.text, { [classes.textDense]: dense })}
          >
            {primary}
          </Typography>
        ))}
      {secondary &&
        (disableTypography ? (
          secondary
        ) : (
          <Typography
            color="secondary"
            type="body1"
            className={classNames(classes.text, { [classes.textDense]: dense })}
          >
            {secondary}
          </Typography>
        ))}

  );
}

ListItemText.propTypes = {
  /**
   * Useful to extend the style applied to components.
   */
  classes: PropTypes.object.isRequired,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * If `true`, the children won't be wrapped by a typography component.
   * For instance, that can be useful to can render an h4 instead of a
   */
  disableTypography: PropTypes.bool,
  /**
   * If `true`, the children will be indented.
   * This should be used if there is no left avatar or left icon.
   */
  inset: PropTypes.bool,
  primary: PropTypes.node,
  secondary: PropTypes.node,
};

ListItemText.defaultProps = {
  disableTypography: false,
  inset: false,
  primary: false,
  secondary: false,
};

ListItemText.contextTypes = {
  dense: PropTypes.bool,
};

export default withStyles(styles, { name: 'MuiListItemText' })(ListItemText);
<commit_msg>[ListItemText] Fix nowrap primary text ellipsis (#9631)<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import withStyles from '../styles/withStyles';
import Typography from '../Typography';

export const styles = theme => ({
  root: {
    flex: '1 1 auto',
    minWidth: 0,
    padding: '0 16px',
    '&:first-child': {
      paddingLeft: 0,
    },
  },
  inset: {
    '&:first-child': {
      paddingLeft: theme.spacing.unit * 7,
    },
  },
  dense: {
    fontSize: theme.typography.pxToRem(13),
  },
  text: {}, // Present to allow external customization
  textDense: {
    fontSize: 'inherit',
  },
});

function ListItemText(props, context) {
  const {
    classes,
    className: classNameProp,
    disableTypography,
    inset,
    primary,
    secondary,
    ...other
  } = props;
  const { dense } = context;
  const className = classNames(
    classes.root,
    {
      [classes.dense]: dense,
      [classes.inset]: inset,
    },
    classNameProp,
  );

  return (

      {primary &&
        (disableTypography ? (
          primary
        ) : (
          <Typography
            type="subheading"
            className={classNames(classes.text, { [classes.textDense]: dense })}
          >
            {primary}
          </Typography>
        ))}
      {secondary &&
        (disableTypography ? (
          secondary
        ) : (
          <Typography
            color="secondary"
            type="body1"
            className={classNames(classes.text, { [classes.textDense]: dense })}
          >
            {secondary}
          </Typography>
        ))}

  );
}

ListItemText.propTypes = {
  /**
   * Useful to extend the style applied to components.
   */
  classes: PropTypes.object.isRequired,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * If `true`, the children won't be wrapped by a typography component.
   * For instance, that can be useful to can render an h4 instead of a
   */
  disableTypography: PropTypes.bool,
  /**
   * If `true`, the children will be indented.
   * This should be used if there is no left avatar or left icon.
   */
  inset: PropTypes.bool,
  primary: PropTypes.node,
  secondary: PropTypes.node,
};

ListItemText.defaultProps = {
  disableTypography: false,
  inset: false,
  primary: false,
  secondary: false,
};

ListItemText.contextTypes = {
  dense: PropTypes.bool,
};

export default withStyles(styles, { name: 'MuiListItemText' })(ListItemText);
<|endoftext|>