<commit_before>'use strict';

angular.module('jmList', ['ngMaterial', 'jmUser', 'jmInput'])

    .directive("jmList", function () {
        return {
            scope: true,
            templateUrl: 'list/list.tpl.html',
            controller: 'jmListController'
        };
    })

    .controller("jmListController", function ($scope, jmDB) {
        $scope.users = [];
        $scope.count = '';
        $scope.lastUpdate = new Date();
        $scope.name = 'McPeak';
        $scope.height = 'auto';
        $scope.showDelete = false;

        var findUser = function (id) {
            for (var i in $scope.users) {
                if ($scope.users[i].id === id) {
                    return $scope.users[i];
                }
            }
        };

        $scope.$root.$on('userRemoved', function () {
            $scope.update(($scope.users.length >=1) ? $scope.users[0] : undefined);
        });

        $scope.update = function (user) {
            $scope.$root.$emit('selectUser', user);
        };

        $scope.$root.$on('refresh', function (event, id) {
            $scope.refresh(id);
        });

        $scope.refresh = function (id) {
            jmDB.queryAll().then(function (data) {
                $scope.count = data.length;
                $scope.users = data;

                if (id) {
                    $scope.update(findUser(id));
                }
            }, function (reason) {
                window.alert('Failed: ' + reason);
            });
        };

        $scope.refresh();
    })

    .directive("jmToolbar", function () {
        return {
            scope: true,
            templateUrl: 'list/toolbar.tpl.html',
            controller: 'jmToolbarController'
        };
    })

    .controller("jmToolbarController", function ($scope, $mdSidenav) {

        $scope.menus = [
            {link: 'https://github.com/jmcpeak/family/issues', label: 'Log an Issue'},
            {link: 'https://github.com/jmcpeak/family', label: 'See the code'},
            {link: 'https://travis-ci.org/jmcpeak/family', label: 'View Builds'}
        ];

        $scope.open = function () {
            $mdSidenav('left').open();
        };

        $scope.close = function () {
            $mdSidenav('left').close();
            // unselect button
        };
    });
<commit_msg>After deleting a user select the first user, first tab<commit_after>'use strict';

angular.module('jmList', ['ngMaterial', 'jmUser', 'jmInput'])

    .directive("jmList", function () {
        return {
            scope: true,
            templateUrl: 'list/list.tpl.html',
            controller: 'jmListController'
        };
    })

    .controller("jmListController", function ($scope, jmDB) {
        $scope.users = [];
        $scope.count = '';
        $scope.lastUpdate = new Date();
        $scope.name = 'McPeak';
        $scope.height = 'auto';
        $scope.showDelete = false;

        var findUser = function (id) {
            for (var i in $scope.users) {
                if ($scope.users[i].id === id) {
                    return $scope.users[i];
                }
            }
        };

        $scope.$root.$on('userRemoved', function () {
            $scope.update(($scope.users.length >= 1) ? $scope.users[0] : undefined);
        });

        $scope.update = function (user) {
            $scope.$root.$emit('selectUser', user);
        };

        $scope.$root.$on('refresh', function (event, id) {
            $scope.refresh(id);
        });

        $scope.refresh = function (id) {
            jmDB.queryAll().then(function (data) {
                $scope.count = data.length;
                $scope.users = data;

                if (id) {
                    $scope.update(findUser(id));
                }
            }, function (reason) {
                window.alert('Failed: ' + reason);
            });
        };

        $scope.refresh();
    })

    .directive("jmToolbar", function () {
        return {
            scope: true,
            templateUrl: 'list/toolbar.tpl.html',
            controller: 'jmToolbarController'
        };
    })

    .controller("jmToolbarController", function ($scope, $mdSidenav) {

        $scope.menus = [
            {link: 'https://github.com/jmcpeak/family/issues', label: 'Log an Issue'},
            {link: 'https://github.com/jmcpeak/family', label: 'See the code'},
            {link: 'https://travis-ci.org/jmcpeak/family', label: 'View Builds'}
        ];

        $scope.open = function () {
            $mdSidenav('left').open();
        };

        $scope.close = function () {
            $mdSidenav('left').close();
            // unselect button
        };
    });
<|endoftext|>


<commit_before>'use strict';
const request = require('request');
const turf = require('@turf/turf');

const geojson_intersect = require('./geojson_intersection.js');
const cql_filter = require('./cql_filter');

function geoportailRequest(options, done) {
    request(options, function(err, response, body) {
        if (err) return done(err);
        if (response.statusCode !== 200) {
            const error = new Error('Géoportail returned an error: ' + response.statusCode);
            error.responseBody = body;
            error.statusCode = response.statusCode;
            return done(error);
        }
        if (options.expectedFormat &&
            response.headers['content-type'] &&
            !response.headers['content-type'].includes(options.expectedFormat)) {
            const error = new Error(`Géoportail returned an unexpected format: ${response.headers['content-type']}. Expected: ${options.expectedFormat}`);
            error.responseBody = body;
            return done(error);
        }
        done(null, body);
    });
}

function parseGeoJSONAndFlip(rawText, done) {
    let result, error;
    try {
        result = JSON.parse(rawText);
    } catch (err) {
        error = err;
    }
    done(error, result);
}

class CadastreClient {

    /**
     * Constructeur avec :
     * apiKey : une clé IGN avec les droits sur BDPARCELLAIRE-VECTEUR_WLD_BDD_WGS84G:divcad et BDPARCELLAIRE-VECTEUR_WLD_BDD_WGS84G:parcelle
     * options :
     * - referer: le referer correspondant à la clée
     * - serviceUrl: url racine du service geoportail
     */
    constructor(apiKey, options) {
        if (!apiKey) throw new Error('Required param: apiKey');
        this.apiKey = apiKey;
        this.referer = options.referer || 'http://localhost';
        this.serviceUrl = options.serviceUrl || 'http://wxs.ign.fr';
    }

    getDefaultOptions() {
        return {
            uri: `${this.serviceUrl}/${this.apiKey}/geoportail/wfs`,
            qs: { version: '2.0.0' },
            headers: {
                Referer: this.referer
            }
        };
    }

    getCapabilities(done) {
        const options = this.getDefaultOptions();
        options.qs.request = 'GetCapabilities';
        geoportailRequest(options, done);
    }

    /**
     * Récupération des communes pour un code département et un code commune
     */
    getDivisions(params, done) {
        const options = this.getDefaultOptions();
        options.qs.request = 'GetFeature';
        options.qs.typename = 'BDPARCELLAIRE-VECTEUR_WLD_BDD_WGS84G:divcad';
        options.qs.outputFormat = 'application/json';
        options.qs.cql_filter = cql_filter(params);
        options.expectedFormat = 'json';

        geoportailRequest(options, function (err, body) {
            if (err) return done(err);
            parseGeoJSONAndFlip(body, done);
        });
    }

    /**
     * Récupération des parcelles
     */
    getParcelles(params, done) {
        const options = this.getDefaultOptions();
        options.qs.request = 'GetFeature';
        options.qs.typename = 'BDPARCELLAIRE-VECTEUR_WLD_BDD_WGS84G:parcelle';
        options.qs.outputFormat = 'application/json';
        options.qs.cql_filter = cql_filter(params);
        options.expectedFormat = 'json';

        geoportailRequest(options, function(err, body) {
            if (err) return done(err);
            parseGeoJSONAndFlip(body, done);
        });
    }

    /* Recuperer les informations du cadastre à partir d'une geometrie
     * le résultat retourne :
     * Informations sur la parcelle
     * Calcul des surfaces et des intersections
     */
    getCadastreFromGeom(feature, done) {
        const geomInitialParams = feature;
        const paramsGeom = {
            geom: feature.geometry
        };
        const options = this.getDefaultOptions();
        options.qs.request = 'GetFeature';
        options.qs.typename = 'BDPARCELLAIRE-VECTEUR_WLD_BDD_WGS84G:parcelle';
        options.qs.outputFormat = 'application/json';
        options.form = {
            cql_filter: cql_filter(paramsGeom)
        };
        options.method = 'POST';
        options.expectedFormat = 'json';

        geoportailRequest(options, function(err, body) {
            if (err) return done(err);
            parseGeoJSONAndFlip(body, function (err, geojson) {
                if (err) return done(err);
                geojson.features.forEach(feature => {
                    feature.properties.surface_intersection = geojson_intersect(feature, geomInitialParams);
                    feature.properties.surface_parcelle = turf.area(feature);
                });
                done(null, geojson);
            });
        });
    }

    /**
     * Récupération des geometries d'une commune
     * Passage en parametre code_insee de la commune
     */
    getCommune(params, done) {
        const options = this.getDefaultOptions();
        options.qs.request = 'GetFeature';
        options.qs.typename = 'BDPARCELLAIRE-VECTEUR_WLD_BDD_WGS84G:commune';
        options.qs.outputFormat = 'application/json';
        options.qs.cql_filter = cql_filter(params);
        options.expectedFormat = 'json';

        geoportailRequest(options, function(err, body) {
            if (err) return done(err);
            parseGeoJSONAndFlip(body, done);
        });
    }

    /**
     * Récupération des localisant
     * Passage en parametre code_insee de la commune et/ou section et/ou numero
     */
    getLocalisant(params, done) {
        const options = this.getDefaultOptions();
        options.qs.request = 'GetFeature';
        options.qs.typename = 'BDPARCELLAIRE-VECTEUR_WLD_BDD_WGS84G:localisant';
        options.qs.outputFormat = 'application/json';
        options.qs.cql_filter = cql_filter(params);
        options.expectedFormat = 'json';

        geoportailRequest(options, function(err, body) {
            if (err) return done(err);
            parseGeoJSONAndFlip(body, done);
        });
    }

}

module.exports = CadastreClient;
<commit_msg>Switch Geoportail API to HTTPS<commit_after>'use strict';
const request = require('request');
const turf = require('@turf/turf');

const geojson_intersect = require('./geojson_intersection.js');
const cql_filter = require('./cql_filter');

function geoportailRequest(options, done) {
    request(options, function(err, response, body) {
        if (err) return done(err);
        if (response.statusCode !== 200) {
            const error = new Error('Géoportail returned an error: ' + response.statusCode);
            error.responseBody = body;
            error.statusCode = response.statusCode;
            return done(error);
        }
        if (options.expectedFormat &&
            response.headers['content-type'] &&
            !response.headers['content-type'].includes(options.expectedFormat)) {
            const error = new Error(`Géoportail returned an unexpected format: ${response.headers['content-type']}. Expected: ${options.expectedFormat}`);
            error.responseBody = body;
            return done(error);
        }
        done(null, body);
    });
}

function parseGeoJSONAndFlip(rawText, done) {
    let result, error;
    try {
        result = JSON.parse(rawText);
    } catch (err) {
        error = err;
    }
    done(error, result);
}

class CadastreClient {

    /**
     * Constructeur avec :
     * apiKey : une clé IGN avec les droits sur BDPARCELLAIRE-VECTEUR_WLD_BDD_WGS84G:divcad et BDPARCELLAIRE-VECTEUR_WLD_BDD_WGS84G:parcelle
     * options :
     * - referer: le referer correspondant à la clée
     * - serviceUrl: url racine du service geoportail
     */
    constructor(apiKey, options) {
        if (!apiKey) throw new Error('Required param: apiKey');
        this.apiKey = apiKey;
        this.referer = options.referer || 'http://localhost';
        this.serviceUrl = options.serviceUrl || 'https://wxs.ign.fr';
    }

    getDefaultOptions() {
        return {
            uri: `${this.serviceUrl}/${this.apiKey}/geoportail/wfs`,
            qs: { version: '2.0.0' },
            headers: {
                Referer: this.referer
            }
        };
    }

    getCapabilities(done) {
        const options = this.getDefaultOptions();
        options.qs.request = 'GetCapabilities';
        geoportailRequest(options, done);
    }

    /**
     * Récupération des communes pour un code département et un code commune
     */
    getDivisions(params, done) {
        const options = this.getDefaultOptions();
        options.qs.request = 'GetFeature';
        options.qs.typename = 'BDPARCELLAIRE-VECTEUR_WLD_BDD_WGS84G:divcad';
        options.qs.outputFormat = 'application/json';
        options.qs.cql_filter = cql_filter(params);
        options.expectedFormat = 'json';

        geoportailRequest(options, function (err, body) {
            if (err) return done(err);
            parseGeoJSONAndFlip(body, done);
        });
    }

    /**
     * Récupération des parcelles
     */
    getParcelles(params, done) {
        const options = this.getDefaultOptions();
        options.qs.request = 'GetFeature';
        options.qs.typename = 'BDPARCELLAIRE-VECTEUR_WLD_BDD_WGS84G:parcelle';
        options.qs.outputFormat = 'application/json';
        options.qs.cql_filter = cql_filter(params);
        options.expectedFormat = 'json';

        geoportailRequest(options, function(err, body) {
            if (err) return done(err);
            parseGeoJSONAndFlip(body, done);
        });
    }

    /* Recuperer les informations du cadastre à partir d'une geometrie
     * le résultat retourne :
     * Informations sur la parcelle
     * Calcul des surfaces et des intersections
     */
    getCadastreFromGeom(feature, done) {
        const geomInitialParams = feature;
        const paramsGeom = {
            geom: feature.geometry
        };
        const options = this.getDefaultOptions();
        options.qs.request = 'GetFeature';
        options.qs.typename = 'BDPARCELLAIRE-VECTEUR_WLD_BDD_WGS84G:parcelle';
        options.qs.outputFormat = 'application/json';
        options.form = {
            cql_filter: cql_filter(paramsGeom)
        };
        options.method = 'POST';
        options.expectedFormat = 'json';

        geoportailRequest(options, function(err, body) {
            if (err) return done(err);
            parseGeoJSONAndFlip(body, function (err, geojson) {
                if (err) return done(err);
                geojson.features.forEach(feature => {
                    feature.properties.surface_intersection = geojson_intersect(feature, geomInitialParams);
                    feature.properties.surface_parcelle = turf.area(feature);
                });
                done(null, geojson);
            });
        });
    }

    /**
     * Récupération des geometries d'une commune
     * Passage en parametre code_insee de la commune
     */
    getCommune(params, done) {
        const options = this.getDefaultOptions();
        options.qs.request = 'GetFeature';
        options.qs.typename = 'BDPARCELLAIRE-VECTEUR_WLD_BDD_WGS84G:commune';
        options.qs.outputFormat = 'application/json';
        options.qs.cql_filter = cql_filter(params);
        options.expectedFormat = 'json';

        geoportailRequest(options, function(err, body) {
            if (err) return done(err);
            parseGeoJSONAndFlip(body, done);
        });
    }

    /**
     * Récupération des localisant
     * Passage en parametre code_insee de la commune et/ou section et/ou numero
     */
    getLocalisant(params, done) {
        const options = this.getDefaultOptions();
        options.qs.request = 'GetFeature';
        options.qs.typename = 'BDPARCELLAIRE-VECTEUR_WLD_BDD_WGS84G:localisant';
        options.qs.outputFormat = 'application/json';
        options.qs.cql_filter = cql_filter(params);
        options.expectedFormat = 'json';

        geoportailRequest(options, function(err, body) {
            if (err) return done(err);
            parseGeoJSONAndFlip(body, done);
        });
    }

}

module.exports = CadastreClient;
<|endoftext|>


<commit_before>"use strict";

var Progress = function (value, type) {
        this.value = value;
        this.type = type;
    };

Progress.prototype = {};

module.exports = Progress;<commit_msg>removing unused progress class<commit_after><|endoftext|>


<commit_before>/*jslint node: true */
/*jshint laxbreak: true */
'use strict';

var d3 = require('d3');
var _ = require('underscore');

var symbolSize = 10,
    gapRegion = 0,
    gapShape = 0,
    dictionary = {
        metal: "diamond",
        site: "chevron",
        binding: "catFace",
        act_site: "circle",
        mod_res: "triangle",
        lipid: "wave",
        carbohyd: "hexagon",
        non_std: "pentagon",
        init_met: "arrow",
        non_ter: "doubleBar",
        non_cons: "doubleBar",
        ca_bind:'rectangle',
        disulfid:'bridge',
        crosslnk:'bridge',
        turn:'rectangle',
        chain:'rectangle',
        mutagen:'rectangle',
        conflict:'rectangle',
        helix:'rectangle',
        repeat:'rectangle',
        region:'rectangle',
        signal:'rectangle',
        peptide:'rectangle',
        strand:'rectangle',
        topo_dom:'rectangle',
        transmem:'rectangle',
        motif:'rectangle',
        domain:'rectangle',
        compbias:'rectangle',
        missense:'variant',//CHECK
        ms_del:'variant',//CHECK
        insdel:'variant',//CHECK
        stop_lost:'variant',//CHECK
        stop_gained:'variant',//CHECK
        init_codon:'variant'//CHECK
    };

var Feature = function() {
    var feature = this;
    return feature;
};

var FeatureFactory = function() {
    return {
        getFeature: function(type, aaWidth, height, length) {
            var feature,
                featureType = dictionary[type.toLowerCase()],
                width = aaWidth * length;
            //0,0 is in the middle, so we first move to the starting of the aa at gapShape,0.
            gapShape = length === 1 ? 0 : width/length/2;
            //again a gap is needed for regions
            gapRegion = aaWidth/2;
            // if the constructor doesn't exist, rectangle is used by default
            if (typeof Feature[featureType] !== 'function') {
                console.log(type + ' doesn\'t exist');
                featureType = 'rectangle';
            }

            Feature[featureType].prototype = new Feature();
            feature = Feature[featureType](width, height, length);

            return feature;
        }
    };
}();

Feature.rectangle = function(width, height) {
    return 'M' + -(gapRegion) + ',0'
            + 'L' + (width-gapRegion) + ',0'
            + 'L' + (width-gapRegion) + ',' + height
            + 'L' + -(gapRegion) + ',' + height
            + 'Z';
};

Feature.bridge = function(width, height, length) {
    if (length !== 1) {
        return 'M' + -(gapRegion) + ',' + height
                + 'L' + -(gapRegion) + ',0'
                + 'L' + (width-gapRegion) + ',0'
                + 'L' + (width-gapRegion) + ',' + height
                + 'L' + (width-gapRegion) + ',2'
                + 'L' + -(gapRegion) + ',2Z';
    } else {
        return 'M' + -(gapRegion) + ',' + height
                + 'L' + -(gapRegion) + ',' + (height/2)
                + 'L0,' + (height/2)
                + 'L0,0'
                + 'L0,' + (height/2)
                + 'L' + (width-gapRegion) + ',' + (height/2)
                + 'L' + (width-gapRegion) + ',' + height
                + 'Z';
    }
};

var getMiddleLine = function(centerx, width) {
    return 'M' + (centerx+gapShape) + ',' + centerx
            + 'L' + (width/2+gapShape) + ',' + centerx
            + 'M' + (-centerx+gapShape) + ',' + centerx
            + 'L' + (-width/2+gapShape) + ',' + centerx;
};

Feature.diamond = function(width, height, length) {
    var centerx = symbolSize/2;
    var shape = 'M' + gapShape + ',0'
            + 'L' + (centerx+gapShape) + ',' + centerx
            + 'L' + gapShape + ',' + symbolSize
            + 'L' + (-centerx+gapShape) + ',' + centerx;
    return length !== 1
        ? shape + 'L' + gapShape + ',0Z' + getMiddleLine(centerx, width)
        : shape + 'Z';
};

Feature.chevron = function(width, height, length) {
    var centerx = symbolSize/2;
    var shape = 'M' + gapShape + ',' + centerx
            + 'L' + (centerx+gapShape) + ',0'
            + 'L' + (centerx+gapShape) +',' + centerx
            + 'L' + gapShape + ',' + symbolSize
            + 'L' + (-centerx+gapShape) + ',' + centerx
            + 'L' + (-centerx+gapShape) + ',0';
    return length !== 1
        ? shape + 'L' + gapShape + ',' + centerx + getMiddleLine(centerx, width) + 'Z'
        : shape + 'Z';
};

Feature.catFace = function(width, height, length) {
    var centerx = symbolSize/2;
    var step = symbolSize/10;
    var shape = 'M' + (-centerx+gapShape) + ',0'
        + 'L' + (-centerx+gapShape) + ',' + (6*step)
        + 'L' + (-2*step+gapShape) + ',' + symbolSize
        + 'L' + (2*step+gapShape) + ',' + symbolSize
        + 'L' + (centerx+gapShape) + ',' + (6*step)
        + 'L' + (centerx+gapShape) + ',0'
        + 'L' + (2*step+gapShape) + ',' + (4*step)
        + 'L' + (-2*step+gapShape) + ',' + (4*step);
    return length !== 1
        ? shape + 'M' + (-centerx+gapShape) + ',0' + getMiddleLine(centerx, width) + 'Z'
        : shape + 'Z';
};

Feature.triangle = function(width, height, length) {
    var centerx = symbolSize/2;
    var shape = 'M' + gapShape + ',0'
                + 'L' + (centerx+gapShape) + ',' + symbolSize
                + 'L' + (-centerx+gapShape) + ',' + symbolSize;
    return length !== 1
        ? shape + 'L' + gapShape + ',0' + getMiddleLine(centerx, width) + 'Z'
        : shape + 'Z';
};

Feature.wave = function(width, height, length) {
    var rx = symbolSize/4;
    var ry = symbolSize/2;
    var shape = 'M' + (-symbolSize/2+gapShape) + ',' + ry
            + "A" + rx + "," + ry + " 0 1,1 " + gapShape + "," + ry
            + "A" + rx + "," + ry + " 0 1,0 " + (symbolSize/2+gapShape) + ',' + ry;
    return length !== 1
        ? shape + getMiddleLine(ry, width) + 'Z'
        : shape + 'Z';
};

var getPolygon = function(N, width, length){
    var r = symbolSize/2;
    var polygon = 'M ';
    for(var i=0; i < N;i++) {
        polygon += (r * Math.cos(2*Math.PI*i/N) + gapShape) + ',' + (r * Math.sin(2*Math.PI*i/N)+r)  + ' ';
    }
    return length !== 1
        ? polygon + ' ' + (r * Math.cos(0) + gapShape) + ',' + (r * Math.sin(0)+r)  + ' ' + getMiddleLine(r, width) + 'Z'
        : polygon + 'Z';
};

Feature.hexagon = function(width, height, length) {
    return getPolygon(6, width, length);
};

Feature.pentagon = function(width, height, length) {
    return getPolygon(5, width, length);
};

Feature.circle = function(width, height, length) {
  var r = Math.sqrt(symbolSize / Math.PI);
  var shape = "M" + gapShape + ",0"
      + "A" + r + "," + r + " 0 1,1 " + gapShape + "," + symbolSize
      + "A" + r + "," + r + " 0 1,1 " + gapShape + ",0";
  return length !== 1
        ? shape + getMiddleLine(symbolSize/2, width) + 'Z'
        : shape + 'Z';
};

Feature.arrow = function(width, height, length) {
    var step = symbolSize/10;
    var shape = 'M' + gapShape + ',0'
        + 'L' + (-step+gapShape) + ',0'
        + 'L' + (-5*step+gapShape) + ',' + (4*step)
        + 'L' + (-step+gapShape) + ',' + height
        + 'L' + gapShape + ',' + height
        + 'L' + (4*step+gapShape) + ',' + (4*step);
    return length !== 1
        ? shape + 'L' + gapShape + ',0' + getMiddleLine(symbolSize/2, width) + 'Z'
        : shape + 'Z';
};

Feature.doubleBar = function(width, height, length) {
    var centerx = symbolSize/2;
    var shape = 'M' + gapShape + ',0'
        + 'L' + (-centerx+gapShape) + ',' + symbolSize
        + 'L' + gapShape + ',' + symbolSize
        + 'L' + (centerx+gapShape) + ',0';
    return length !== 1
        ? shape + 'L' + gapShape + ',0' + getMiddleLine(symbolSize/2, width) + 'Z'
        : shape + 'Z';
};

Feature.variant = function() {
    //TODO
};

module.exports = FeatureFactory;<commit_msg>Add missing feature types.<commit_after>/*jslint node: true */
/*jshint laxbreak: true */
'use strict';

var d3 = require('d3');
var _ = require('underscore');

var symbolSize = 10,
    gapRegion = 0,
    gapShape = 0,
    dictionary = {
        //molecular processing
        chain:'rectangle',
        transit: 'rectangle',
        init_met: "arrow",
        propep: 'rectangle',
        peptide:'rectangle',
        signal:'rectangle',
        //structural
        helix:'rectangle',
        strand:'rectangle',
        turn:'rectangle',
        disulfid:'bridge',
        crosslnk:'bridge',
        //domains & sites
        region:'rectangle',
        coiled: 'rectangle',
        motif:'rectangle',
        repeat:'rectangle',
        ca_bind:'rectangle',
        dna_bind: 'rectangle',
        domain:'rectangle',
        zn_fing: 'rectangle',
        np_bind: 'rectangle',
        metal: "diamond",
        site: "chevron",
        binding: "catFace",
        act_site: "circle",
        //ptms
        mod_res: "triangle",
        lipid: "wave",
        carbohyd: "hexagon",
        //seqInfo
        compbias:'rectangle',
        conflict:'rectangle',
        non_cons: "doubleBar",
        non_ter: "doubleBar",
        unsure: 'rectangle',
        non_std: "pentagon",
        //mutagenesis
        mutagen:'rectangle',
        //topology
        topo_dom:'rectangle',
        transmem:'rectangle',
        intramem:'rectangle',
        //variants
        missense:'variant',//CHECK
        ms_del:'variant',//CHECK
        insdel:'variant',//CHECK
        stop_lost:'variant',//CHECK
        stop_gained:'variant',//CHECK
        init_codon:'variant'//CHECK
    };

var Feature = function() {
    var feature = this;
    return feature;
};

var FeatureFactory = function() {
    return {
        getFeature: function(type, aaWidth, height, length) {
            var feature,
                featureType = dictionary[type.toLowerCase()],
                width = aaWidth * length;
            //0,0 is in the middle, so we first move to the starting of the aa at gapShape,0.
            gapShape = length === 1 ? 0 : width/length/2;
            //again a gap is needed for regions
            gapRegion = aaWidth/2;
            // if the constructor doesn't exist, rectangle is used by default
            if (typeof Feature[featureType] !== 'function') {
                console.log(type + ' doesn\'t exist');
                featureType = 'rectangle';
            }

            Feature[featureType].prototype = new Feature();
            feature = Feature[featureType](width, height, length);

            return feature;
        }
    };
}();

Feature.rectangle = function(width, height) {
    return 'M' + -(gapRegion) + ',0'
            + 'L' + (width-gapRegion) + ',0'
            + 'L' + (width-gapRegion) + ',' + height
            + 'L' + -(gapRegion) + ',' + height
            + 'Z';
};

Feature.bridge = function(width, height, length) {
    if (length !== 1) {
        return 'M' + -(gapRegion) + ',' + height
                + 'L' + -(gapRegion) + ',0'
                + 'L' + (width-gapRegion) + ',0'
                + 'L' + (width-gapRegion) + ',' + height
                + 'L' + (width-gapRegion) + ',2'
                + 'L' + -(gapRegion) + ',2Z';
    } else {
        return 'M' + -(gapRegion) + ',' + height
                + 'L' + -(gapRegion) + ',' + (height/2)
                + 'L0,' + (height/2)
                + 'L0,0'
                + 'L0,' + (height/2)
                + 'L' + (width-gapRegion) + ',' + (height/2)
                + 'L' + (width-gapRegion) + ',' + height
                + 'Z';
    }
};

var getMiddleLine = function(centerx, width) {
    return 'M' + (centerx+gapShape) + ',' + centerx
            + 'L' + (width/2+gapShape) + ',' + centerx
            + 'M' + (-centerx+gapShape) + ',' + centerx
            + 'L' + (-width/2+gapShape) + ',' + centerx;
};

Feature.diamond = function(width, height, length) {
    var centerx = symbolSize/2;
    var shape = 'M' + gapShape + ',0'
            + 'L' + (centerx+gapShape) + ',' + centerx
            + 'L' + gapShape + ',' + symbolSize
            + 'L' + (-centerx+gapShape) + ',' + centerx;
    return length !== 1
        ? shape + 'L' + gapShape + ',0Z' + getMiddleLine(centerx, width)
        : shape + 'Z';
};

Feature.chevron = function(width, height, length) {
    var centerx = symbolSize/2;
    var shape = 'M' + gapShape + ',' + centerx
            + 'L' + (centerx+gapShape) + ',0'
            + 'L' + (centerx+gapShape) +',' + centerx
            + 'L' + gapShape + ',' + symbolSize
            + 'L' + (-centerx+gapShape) + ',' + centerx
            + 'L' + (-centerx+gapShape) + ',0';
    return length !== 1
        ? shape + 'L' + gapShape + ',' + centerx + getMiddleLine(centerx, width) + 'Z'
        : shape + 'Z';
};

Feature.catFace = function(width, height, length) {
    var centerx = symbolSize/2;
    var step = symbolSize/10;
    var shape = 'M' + (-centerx+gapShape) + ',0'
        + 'L' + (-centerx+gapShape) + ',' + (6*step)
        + 'L' + (-2*step+gapShape) + ',' + symbolSize
        + 'L' + (2*step+gapShape) + ',' + symbolSize
        + 'L' + (centerx+gapShape) + ',' + (6*step)
        + 'L' + (centerx+gapShape) + ',0'
        + 'L' + (2*step+gapShape) + ',' + (4*step)
        + 'L' + (-2*step+gapShape) + ',' + (4*step);
    return length !== 1
        ? shape + 'M' + (-centerx+gapShape) + ',0' + getMiddleLine(centerx, width) + 'Z'
        : shape + 'Z';
};

Feature.triangle = function(width, height, length) {
    var centerx = symbolSize/2;
    var shape = 'M' + gapShape + ',0'
                + 'L' + (centerx+gapShape) + ',' + symbolSize
                + 'L' + (-centerx+gapShape) + ',' + symbolSize;
    return length !== 1
        ? shape + 'L' + gapShape + ',0' + getMiddleLine(centerx, width) + 'Z'
        : shape + 'Z';
};

Feature.wave = function(width, height, length) {
    var rx = symbolSize/4;
    var ry = symbolSize/2;
    var shape = 'M' + (-symbolSize/2+gapShape) + ',' + ry
            + "A" + rx + "," + ry + " 0 1,1 " + gapShape + "," + ry
            + "A" + rx + "," + ry + " 0 1,0 " + (symbolSize/2+gapShape) + ',' + ry;
    return length !== 1
        ? shape + getMiddleLine(ry, width) + 'Z'
        : shape + 'Z';
};

var getPolygon = function(N, width, length){
    var r = symbolSize/2;
    var polygon = 'M ';
    for(var i=0; i < N;i++) {
        polygon += (r * Math.cos(2*Math.PI*i/N) + gapShape) + ',' + (r * Math.sin(2*Math.PI*i/N)+r)  + ' ';
    }
    return length !== 1
        ? polygon + ' ' + (r * Math.cos(0) + gapShape) + ',' + (r * Math.sin(0)+r)  + ' ' + getMiddleLine(r, width) + 'Z'
        : polygon + 'Z';
};

Feature.hexagon = function(width, height, length) {
    return getPolygon(6, width, length);
};

Feature.pentagon = function(width, height, length) {
    return getPolygon(5, width, length);
};

Feature.circle = function(width, height, length) {
  var r = Math.sqrt(symbolSize / Math.PI);
  var shape = "M" + gapShape + ",0"
      + "A" + r + "," + r + " 0 1,1 " + gapShape + "," + symbolSize
      + "A" + r + "," + r + " 0 1,1 " + gapShape + ",0";
  return length !== 1
        ? shape + getMiddleLine(symbolSize/2, width) + 'Z'
        : shape + 'Z';
};

Feature.arrow = function(width, height, length) {
    var step = symbolSize/10;
    var shape = 'M' + gapShape + ',0'
        + 'L' + (-step+gapShape) + ',0'
        + 'L' + (-5*step+gapShape) + ',' + (4*step)
        + 'L' + (-step+gapShape) + ',' + height
        + 'L' + gapShape + ',' + height
        + 'L' + (4*step+gapShape) + ',' + (4*step);
    return length !== 1
        ? shape + 'L' + gapShape + ',0' + getMiddleLine(symbolSize/2, width) + 'Z'
        : shape + 'Z';
};

Feature.doubleBar = function(width, height, length) {
    var centerx = symbolSize/2;
    var shape = 'M' + gapShape + ',0'
        + 'L' + (-centerx+gapShape) + ',' + symbolSize
        + 'L' + gapShape + ',' + symbolSize
        + 'L' + (centerx+gapShape) + ',0';
    return length !== 1
        ? shape + 'L' + gapShape + ',0' + getMiddleLine(symbolSize/2, width) + 'Z'
        : shape + 'Z';
};

Feature.variant = function() {
    //TODO
};

module.exports = FeatureFactory;<|endoftext|>


<commit_before>angular.module('mwFormBuilder')
        .service('mwFormUuid', function () {
          function s4() {
            return Math.floor((1 + Math.random()) * 0x10000)
                    .toString(16)
                    .substring(1);
          }
          this.get = function () {
            return s4() + s4() + s4() + s4() + s4() + s4() + s4() + s4();

          };
        }).factory('mwFormClone', ["mwFormUuid", function (mwFormUuid) {
    var service = {};
    var checkedObjects = [];
    function resetIds(obj, root) {
      if (root) {
        checkedObjects = [];
      }
      if (checkedObjects.indexOf(obj) >= 0) {
        return;
      }
      checkedObjects.push(obj);
      if (!obj === Object(obj)) {
        return;
      }

      if (Array.isArray(obj)) {
        obj.forEach(resetIds);
        return;
      }

      for (var property in obj) {
        if (obj.hasOwnProperty(property)) {
          resetIds(obj[property]);
        }
      }

      if (obj.hasOwnProperty('id')) {
        var newId = mwFormUuid.get();
        var oldId = obj.id;
        obj.id = newId;
      }

    }

    service.cloneElement = function (pageElement) {
      var element = {};
      angular.copy(pageElement, element);
      resetIds(element, true);
      return element;
    };

    service.clonePage = function (formPage) {
      var _page = {};
      angular.copy(formPage, _page);
      _page.id = mwFormUuid.get();
      var _elements = [];
      if (Array.isArray(formPage.elements)) {
        for (var i = 0; i < formPage.elements.length; i++) {
          _elements.push(service.cloneElement(formPage.elements[i]));
        }
      }
      _page.elements = _elements;
      return _page;
    };

    service.cloneForm = function (form) {
      var _form = {};
      angular.copy(form, _form);
      var _pages = [];
      if (Array.isArray(form.pages)) {
        for (var i = 0; i < form.pages.length; i++) {
          _pages.push(service.clonePage(form.pages[i]));
        }
      }
      _form.pages = _pages;
      return _form;
    };

    return service;

  }]);

/*    .factory('CollectionsUtil', function(){
 return{
 replaceByEqualObject: function(collection, referenceObjects, equalFn){
 return _.map(collection, function(element){
 var foundRefObj = _.find(referenceObjects, function(refObj){
 if(equalFn){
 return equalFn(element, refObj);
 }else{
 return _.isEqual(element, refObj);
 }
 });
 if(foundRefObj){
 return foundRefObj;
 }else{
 return element;
 }
 });
 },
 isNotEmptyArray: function(object){
 return object && $.isArray(object) && object.length > 0;
 }
 }
 });*/<commit_msg>resetIds on util<commit_after>angular.module('mwFormBuilder')
        .service('mwFormUuid', function () {
          function s4() {
            return Math.floor((1 + Math.random()) * 0x10000)
                    .toString(16)
                    .substring(1);
          }
          this.get = function () {
            return s4() + s4() + s4() + s4() + s4() + s4() + s4() + s4();

          };
        }).factory('mwFormClone', ["mwFormUuid", function (mwFormUuid) {
    var service = {};
    var checkedObjects = [];

    service.resetIds = function (obj, root) {
      if (root) {
        checkedObjects = [];
      }
      if (checkedObjects.indexOf(obj) >= 0) {
        return;
      }
      checkedObjects.push(obj);
      if (!obj === Object(obj)) {
        return;
      }

      if (Array.isArray(obj)) {
        obj.forEach(service.resetIds);
        return;
      }

      for (var property in obj) {
        if (obj.hasOwnProperty(property)) {
          service.resetIds(obj[property]);
        }
      }

      if (obj.hasOwnProperty('id')) {
        var newId = mwFormUuid.get();
        var oldId = obj.id;
        obj.id = newId;
      }
    };

    service.cloneElement = function (pageElement) {
      var element = {};
      angular.copy(pageElement, element);
      service.resetIds(element, true);
      return element;
    };

    service.clonePage = function (formPage) {
      var _page = {};
      angular.copy(formPage, _page);
      _page.id = mwFormUuid.get();
      var _elements = [];
      if (Array.isArray(formPage.elements)) {
        for (var i = 0; i < formPage.elements.length; i++) {
          _elements.push(service.cloneElement(formPage.elements[i]));
        }
      }
      _page.elements = _elements;
      return _page;
    };

    service.cloneForm = function (form) {
      var _form = {};
      angular.copy(form, _form);
      var _pages = [];
      if (Array.isArray(form.pages)) {
        for (var i = 0; i < form.pages.length; i++) {
          _pages.push(service.clonePage(form.pages[i]));
        }
      }
      _form.pages = _pages;
      return _form;
    };

    return service;

  }]);

/*    .factory('CollectionsUtil', function(){
 return{
 replaceByEqualObject: function(collection, referenceObjects, equalFn){
 return _.map(collection, function(element){
 var foundRefObj = _.find(referenceObjects, function(refObj){
 if(equalFn){
 return equalFn(element, refObj);
 }else{
 return _.isEqual(element, refObj);
 }
 });
 if(foundRefObj){
 return foundRefObj;
 }else{
 return element;
 }
 });
 },
 isNotEmptyArray: function(object){
 return object && $.isArray(object) && object.length > 0;
 }
 }
 });*/<|endoftext|>


<commit_before>'use strict';
import React, {PureComponent} from 'react';
import {StyleSheet, Text} from 'react-native';
import withMaterialTheme from '../styles/withMaterialTheme';
import RectRipple from '../touchable/RectRipple';
import elevation from '../styles/elevation';
import * as typo from '../styles/typo';
import {largePrimaryTextShade} from '../styles/wcag';

const defaultHitSlop = {
	top: 6, bottom: 6,
	left: 0, right: 0,
};

class Button extends PureComponent {
	static defaultProps = {
		disabled: false,
	};

	render() {
		const {
			materialTheme,
			disabled,
			text,
			hitSlop,
			onPress,
			onLongPress,
			onAccessibilityTap,
			onMagicTap,
			raised,
			solid: solidOverride,
			primary,
			accent,
			disabledColor: disabledColorOverride,
			tintColor: tintColorOverride,
			style,
		} = this.props;

		let backgroundColor, color;
		if ( raised ) {
			const tintColor = (
				tintColorOverride
				|| (primary && materialTheme.button.tintColor)
				|| (accent && materialTheme.button.accentColor)
			);

			// Raised buttons default to solid when primary, accent, or custom tint colors are passed
			const solid = typeof solidOverride === 'boolean' ? solidOverride : !!tintColor;

			if ( solid ) {
				backgroundColor = (
					(disabled && materialTheme.button.disabledBackground)
					|| tintColor
					|| materialTheme.button.tintColor
				);
				color = disabled
					? materialTheme.button.disabledColor
					: largePrimaryTextShade(backgroundColor);
			} else {
				backgroundColor = (
					(disabled && materialTheme.button.disabledBackground)
					|| materialTheme.palette.container
				);
				color = disabled
					? materialTheme.button.disabledColor
					: tintColor || materialTheme.text.primaryColor;
			}
		} else {
			color = (
				(disabled && (disabledColorOverride || materialTheme.text.disabledColor))
				|| tintColorOverride
				|| (primary && materialTheme.button.tintColor)
				|| (accent && materialTheme.button.accentColor)
				|| materialTheme.text.primaryColor
			);
		}

		return (
			<RectRipple
				pointerEvents='box-only'
				accessibilityComponentType='button'
				accessibilityTraits={disabled ? 'disabled' : 'button'}
				accessibilityLabel={text}
				{...(disabled ? {} : {onPress, onLongPress, onAccessibilityTap, onMagicTap})}
				hitSlop={hitSlop || defaultHitSlop}
				style={[
					styles.base,
					style,
					styles.root,
					raised ? styles.raised : styles.flat,
					raised && !disabled && elevation(2),
					{
						backgroundColor,
					}
				]}>
				<Text
					suppressHighlighting
					numberOfLines={1}
					style={[
						styles.text,
						{
							color,
						}
					]}>
					{text}
				</Text>
			</RectRipple>
		);
	}
}

export default withMaterialTheme(Button);

const styles = StyleSheet.create({
	base: {
		alignSelf: 'flex-start',
	},
	root: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center',
		borderRadius: 2,
		height: 36,
		minWidth: 88,
	},
	flat: {
		paddingHorizontal: 8,
	},
	raised: {
		paddingHorizontal: 16,
	},
	text: {
		...typo.button,
		textAlign: 'center',
		lineHeight: 20,
	},
});
<commit_msg>Drop the usage of `alignSelf: flex-start` in Button<commit_after>'use strict';
import React, {PureComponent} from 'react';
import {StyleSheet, Text} from 'react-native';
import withMaterialTheme from '../styles/withMaterialTheme';
import RectRipple from '../touchable/RectRipple';
import elevation from '../styles/elevation';
import * as typo from '../styles/typo';
import {largePrimaryTextShade} from '../styles/wcag';

const defaultHitSlop = {
	top: 6, bottom: 6,
	left: 0, right: 0,
};

class Button extends PureComponent {
	static defaultProps = {
		disabled: false,
	};

	render() {
		const {
			materialTheme,
			disabled,
			text,
			hitSlop,
			onPress,
			onLongPress,
			onAccessibilityTap,
			onMagicTap,
			raised,
			solid: solidOverride,
			primary,
			accent,
			disabledColor: disabledColorOverride,
			tintColor: tintColorOverride,
			style,
		} = this.props;

		let backgroundColor, color;
		if ( raised ) {
			const tintColor = (
				tintColorOverride
				|| (primary && materialTheme.button.tintColor)
				|| (accent && materialTheme.button.accentColor)
			);

			// Raised buttons default to solid when primary, accent, or custom tint colors are passed
			const solid = typeof solidOverride === 'boolean' ? solidOverride : !!tintColor;

			if ( solid ) {
				backgroundColor = (
					(disabled && materialTheme.button.disabledBackground)
					|| tintColor
					|| materialTheme.button.tintColor
				);
				color = disabled
					? materialTheme.button.disabledColor
					: largePrimaryTextShade(backgroundColor);
			} else {
				backgroundColor = (
					(disabled && materialTheme.button.disabledBackground)
					|| materialTheme.palette.container
				);
				color = disabled
					? materialTheme.button.disabledColor
					: tintColor || materialTheme.text.primaryColor;
			}
		} else {
			color = (
				(disabled && (disabledColorOverride || materialTheme.text.disabledColor))
				|| tintColorOverride
				|| (primary && materialTheme.button.tintColor)
				|| (accent && materialTheme.button.accentColor)
				|| materialTheme.text.primaryColor
			);
		}

		return (
			<RectRipple
				pointerEvents='box-only'
				accessibilityComponentType='button'
				accessibilityTraits={disabled ? 'disabled' : 'button'}
				accessibilityLabel={text}
				{...(disabled ? {} : {onPress, onLongPress, onAccessibilityTap, onMagicTap})}
				hitSlop={hitSlop || defaultHitSlop}
				style={[
					style,
					styles.root,
					raised ? styles.raised : styles.flat,
					raised && !disabled && elevation(2),
					{
						backgroundColor,
					}
				]}>
				<Text
					suppressHighlighting
					numberOfLines={1}
					style={[
						styles.text,
						{
							color,
						}
					]}>
					{text}
				</Text>
			</RectRipple>
		);
	}
}

export default withMaterialTheme(Button);

const styles = StyleSheet.create({
	root: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center',
		borderRadius: 2,
		height: 36,
		minWidth: 88,
	},
	flat: {
		paddingHorizontal: 8,
	},
	raised: {
		paddingHorizontal: 16,
	},
	text: {
		...typo.button,
		textAlign: 'center',
		lineHeight: 20,
	},
});
<|endoftext|>


<commit_before>/*
    Rob Holme

    Functions to highlight user specified fields on a HL7 message.
*/

// load modules
const vscode = require('vscode');
const common = require('./common.js');

// the list of fields to highlight
var fieldSelectionList = [];

//----------------------------------------------------
// Highlight the HL7 field(s) identified by the user
// @param {string} itemLocation - a string identifying the field location (e.g. PID-3)
// @param {object} hl7Schema - An object containing the HL7 schema
// @param {string} backgroundColor - The RGBA colour value identifying the background colour e.g. "rgba(0,255,0,0.3)". If this is not supplied, a default colour will be used.
//
// @returns {object} - returns a hashtable containing all unique segment names (as keys).
function ShowHighlights(itemLocation, hl7Schema, backgroundColor) {
	// the default background colour for highlighted items (if not otherwise specified)
	const defaultBackgroundColour = 'rgba(0,255,0,0.3)'

	// load the message delimiters from the current file
	var delimiters = common.ParseDelimiters();
	// regex to match a segment name and field index
	var itemLocationRegex = new RegExp("^[A-Z]{2}([A-Z]|[0-9])[-]([0-9]{1,3})$", 'i');
	// associative array indexed by segment name, with the field index as a value.
	var locationHashtable = {};
	var highlightBackgroundColour = defaultBackgroundColour;
	var activeEditor = vscode.window.activeTextEditor;
	var fieldLocated = false;
	//	var fieldRegEx = new RegExp("\\" + delimiters.FIELD, "g");
	var text = activeEditor.document.getText();

	// dispose of decorations for previously highlighted fields.
	if (fieldSelectionList.length > 0) {
		currentDecoration.dispose();
		fieldSelectionList = [];
	}

	// return if no location provided by the user, or no active editor
	if ((!itemLocation) || (!activeEditor)) {
		return;
	}

	var currentDoc = activeEditor.document;

	// if a background colour was provided use it, otherwise the default background setting defined in defaultBackgroundColour will apply
	if (backgroundColor) {
		highlightBackgroundColour = backgroundColor
	}

	// create a decorator type that is used to decorate selected fields
	var highlightDecorationType = vscode.window.createTextEditorDecorationType({
		backgroundColor: highlightBackgroundColour
	});

	// Test to see if the user has provided a valid location string, otherwise assume a description has been provided instead
	if (itemLocationRegex.test(itemLocation)) {
		// identify the segment name and field index from the location string
		var segmentName = common.GetSegmentNameFromLocationString(itemLocation).toUpperCase();
		var fieldIndex = parseInt(common.GetFieldIndex(itemLocation), 10);
		// the first field of MSH segments is the field delimiter, adjust index accordingly for MSH fields
		if (segmentName == "MSH") {
			fieldIndex--;
		}
		locationHashtable[segmentName] = [fieldIndex];
	}
	// else assume the user has provided a field description to search for instead of a location.
	else {
		locationHashtable = common.FindLocationFromDescription(itemLocation, hl7Schema);
	}

	fieldSelectionList = AddDecorations(activeEditor, locationHashtable, delimiters.FIELD)
	// warn the user if the field selected does not exist in the message
	if (fieldSelectionList.length < 1) {
		vscode.window.showWarningMessage("A field matching " + itemLocation + " could not be located in the message");
	}

	// apply the decoration to highlight the field.
	activeEditor.setDecorations(highlightDecorationType, fieldSelectionList);
	currentDecoration = highlightDecorationType;
}

//----------------------------------------------------
// Return an array of HL7 location strings that match the fieldDescription parameter.
// The array is indexed with the 3 letter segment name, the value is the field index.
// @param {string} fieldDescription - a string containing a description, or partial description of the field. e.g. "Patient Name"
// @param {object} hl7Schema - An object containing the HL7 schema corresponding to the version of the HL7 message
//
// @return {object} - a hashtable containing HL7 location strings for every field matching the description supplied by the fieldDescription parameter. Includes partial matches.

// MOVED TO COMMON.JS
/*function FindLocationFromDescription(fieldDescription, hl7Schema) {
	var locationHashtable = {};
	var currentDoc = vscode.window.activeTextEditor.document;
	// regex to match the description of the segment provided
	var nameRegEx = new RegExp(fieldDescription, "i");

	// find matching field names for any segment present in the message
	var segmentHash = GetAllSegmentNames(currentDoc);
	for (var key in segmentHash) {
		var segmentDef = hl7Schema[key];
		// ignore segments not present in the hl7 scheme (i.e. custom Z segments)
		if (!(segmentDef === undefined)) {
			fieldIndexArray = [];
			for (var i = 0; i < segmentDef.fields.length; i++) {
				if (nameRegEx.test(segmentDef.fields[i].desc)) {
					// the first field of MSH segments is the field delimiter, adjust index accordingly for MSH fields
					if (key == "MSH") {
						fieldIndexArray.push(i);
					}
					else {
						fieldIndexArray.push(i + 1);
					}
				}
			}
			locationHashtable[key] = fieldIndexArray;
		}
	}
	return locationHashtable;
}
*/

//----------------------------------------------------
//  Locate the position of the fields to highlight, add the highlight decoration to a list
// @param {object} activeEditor - the current vscode editor
// @param {object} locationHashtable - An hashtable containing field locations to highlight. e.g. PID-3
// @param {char} fieldDelimiter - the field delimiter used by the HL7 message. e.g. '|'
//
// @return {object} - returns an array of the decoration objects (background highlighting) for each of the locations identified by the locationHashtable parameter.
function AddDecorations(activeEditor, locationHashtable, fieldDelimiter) {
	var positionOffset = 0;
	var fieldSelectionListToReturn = [];
	var fieldRegEx = new RegExp("\\" + fieldDelimiter, "g");
	// calculate the number of characters at the end of line (<CR>, or <CR><LF>)
	var config = vscode.workspace.getConfiguration();
	var endOfLineLength = config.files.eol.length;

	for (lineIndex = 0; lineIndex < activeEditor.document.lineCount; lineIndex++) {
		var startPos = null;
		var endPos = null;
		var currentLine = activeEditor.document.lineAt(lineIndex).text;
		var fields = currentLine.split(fieldDelimiter);
		if (!(locationHashtable[fields[0].toUpperCase()] === undefined)) {
			var fieldCount = 1;
			// get the location of field delimiter characters
			while (match = fieldRegEx.exec(currentLine)) {
				// if the start position was located in the previous iteration, then this must be the end position
				if (startPos) {
					endPos = activeEditor.document.positionAt(positionOffset + match.index);
					var decoration = { range: new vscode.Range(startPos, endPos) };
					fieldSelectionListToReturn.push(decoration);
					startPos = null;
					endPos = null;
					fieldLocated = true;
				}
				// if this field is in the list of fields to highlight, mark the start position in the message
				if (locationHashtable[fields[0].toUpperCase()].includes(fieldCount)) {
					startPos = activeEditor.document.positionAt(positionOffset + match.index + 1);
				}
				fieldCount++;
			}
			// check to see if the field requested was the last field in the segment (i.e. start of field delimiter found, but no further field delimiters).
			if (startPos) {
				endPos = activeEditor.document.positionAt(positionOffset + currentLine.length);
				var decoration = { range: new vscode.Range(startPos, endPos) };
				fieldSelectionListToReturn.push(decoration);
				fieldLocated = true;
			}
		}
		// the field locations are relative to the current line, so calculate the offset of previous lines to identify the location within the file.
		positionOffset += currentLine.length + endOfLineLength;
	}
	return fieldSelectionListToReturn;
}

exports.ShowHighlights = ShowHighlights;<commit_msg>removed commented out code<commit_after>/*
    Rob Holme

    Functions to highlight user specified fields on a HL7 message.
*/

// load modules
const vscode = require('vscode');
const common = require('./common.js');

// the list of fields to highlight
var fieldSelectionList = [];

//----------------------------------------------------
// Highlight the HL7 field(s) identified by the user
// @param {string} itemLocation - a string identifying the field location (e.g. PID-3)
// @param {object} hl7Schema - An object containing the HL7 schema
// @param {string} backgroundColor - The RGBA colour value identifying the background colour e.g. "rgba(0,255,0,0.3)". If this is not supplied, a default colour will be used.
//
// @returns {object} - returns a hashtable containing all unique segment names (as keys).
function ShowHighlights(itemLocation, hl7Schema, backgroundColor) {
	// the default background colour for highlighted items (if not otherwise specified)
	const defaultBackgroundColour = 'rgba(0,255,0,0.3)'

	// load the message delimiters from the current file
	var delimiters = common.ParseDelimiters();
	// regex to match a segment name and field index
	var itemLocationRegex = new RegExp("^[A-Z]{2}([A-Z]|[0-9])[-]([0-9]{1,3})$", 'i');
	// associative array indexed by segment name, with the field index as a value.
	var locationHashtable = {};
	var highlightBackgroundColour = defaultBackgroundColour;
	var activeEditor = vscode.window.activeTextEditor;
	var fieldLocated = false;
	//	var fieldRegEx = new RegExp("\\" + delimiters.FIELD, "g");
	var text = activeEditor.document.getText();

	// dispose of decorations for previously highlighted fields.
	if (fieldSelectionList.length > 0) {
		currentDecoration.dispose();
		fieldSelectionList = [];
	}

	// return if no location provided by the user, or no active editor
	if ((!itemLocation) || (!activeEditor)) {
		return;
	}

	var currentDoc = activeEditor.document;

	// if a background colour was provided use it, otherwise the default background setting defined in defaultBackgroundColour will apply
	if (backgroundColor) {
		highlightBackgroundColour = backgroundColor
	}

	// create a decorator type that is used to decorate selected fields
	var highlightDecorationType = vscode.window.createTextEditorDecorationType({
		backgroundColor: highlightBackgroundColour
	});

	// Test to see if the user has provided a valid location string, otherwise assume a description has been provided instead
	if (itemLocationRegex.test(itemLocation)) {
		// identify the segment name and field index from the location string
		var segmentName = common.GetSegmentNameFromLocationString(itemLocation).toUpperCase();
		var fieldIndex = parseInt(common.GetFieldIndex(itemLocation), 10);
		// the first field of MSH segments is the field delimiter, adjust index accordingly for MSH fields
		if (segmentName == "MSH") {
			fieldIndex--;
		}
		locationHashtable[segmentName] = [fieldIndex];
	}
	// else assume the user has provided a field description to search for instead of a location.
	else {
		locationHashtable = common.FindLocationFromDescription(itemLocation, hl7Schema);
	}

	fieldSelectionList = AddDecorations(activeEditor, locationHashtable, delimiters.FIELD)
	// warn the user if the field selected does not exist in the message
	if (fieldSelectionList.length < 1) {
		vscode.window.showWarningMessage("A field matching " + itemLocation + " could not be located in the message");
	}

	// apply the decoration to highlight the field.
	activeEditor.setDecorations(highlightDecorationType, fieldSelectionList);
	currentDecoration = highlightDecorationType;
}

//----------------------------------------------------
//  Locate the position of the fields to highlight, add the highlight decoration to a list
// @param {object} activeEditor - the current vscode editor
// @param {object} locationHashtable - An hashtable containing field locations to highlight. e.g. PID-3
// @param {char} fieldDelimiter - the field delimiter used by the HL7 message. e.g. '|'
//
// @return {object} - returns an array of the decoration objects (background highlighting) for each of the locations identified by the locationHashtable parameter.
function AddDecorations(activeEditor, locationHashtable, fieldDelimiter) {
	var positionOffset = 0;
	var fieldSelectionListToReturn = [];
	var fieldRegEx = new RegExp("\\" + fieldDelimiter, "g");
	// calculate the number of characters at the end of line (<CR>, or <CR><LF>)
	var config = vscode.workspace.getConfiguration();
	var endOfLineLength = config.files.eol.length;

	for (lineIndex = 0; lineIndex < activeEditor.document.lineCount; lineIndex++) {
		var startPos = null;
		var endPos = null;
		var currentLine = activeEditor.document.lineAt(lineIndex).text;
		var fields = currentLine.split(fieldDelimiter);
		if (!(locationHashtable[fields[0].toUpperCase()] === undefined)) {
			var fieldCount = 1;
			// get the location of field delimiter characters
			while (match = fieldRegEx.exec(currentLine)) {
				// if the start position was located in the previous iteration, then this must be the end position
				if (startPos) {
					endPos = activeEditor.document.positionAt(positionOffset + match.index);
					var decoration = { range: new vscode.Range(startPos, endPos) };
					fieldSelectionListToReturn.push(decoration);
					startPos = null;
					endPos = null;
					fieldLocated = true;
				}
				// if this field is in the list of fields to highlight, mark the start position in the message
				if (locationHashtable[fields[0].toUpperCase()].includes(fieldCount)) {
					startPos = activeEditor.document.positionAt(positionOffset + match.index + 1);
				}
				fieldCount++;
			}
			// check to see if the field requested was the last field in the segment (i.e. start of field delimiter found, but no further field delimiters).
			if (startPos) {
				endPos = activeEditor.document.positionAt(positionOffset + currentLine.length);
				var decoration = { range: new vscode.Range(startPos, endPos) };
				fieldSelectionListToReturn.push(decoration);
				fieldLocated = true;
			}
		}
		// the field locations are relative to the current line, so calculate the offset of previous lines to identify the location within the file.
		positionOffset += currentLine.length + endOfLineLength;
	}
	return fieldSelectionListToReturn;
}

exports.ShowHighlights = ShowHighlights;<|endoftext|>


<commit_before>define(function() {

  'use strict';

  var _BYTESOURCE = Symbol('byteSource');

  var itemObjectModel = {
    createItem: function(title) {
      var itemElement = document.createElement('SECTION');
      itemElement.classList.add('item');

      itemElement.appendChild(itemElement.titleElement = document.createElement('HEADER'));

      itemElement.titleTextElement = itemElement.titleElement;

      Object.defineProperties(itemElement, this.itemProperties);

      if (title) itemElement.itemTitle = title;

      itemElement.addEventListener('click', clickItem);

      return itemElement;
    },
    itemProperties: {
      itemTitle: {
        get: function() {
          return this.titleTextElement.innerText;
        },
        set: function(text) {
          this.titleTextElement.innerText = text;
        },
        enumerable: true,
      },
      byteSource: {
        get: function() {
          return this[_BYTESOURCE];
        },
        set: function(byteSource) {
          this[_BYTESOURCE] = byteSource;
          if (!byteSource) {
            this.titleElement.innerText = this.titleTextElement.innerText;
            this.titleTextElement = this.titleElement;
          }
          else {
            var link = document.createElement('A');
            link.href = '#';
            link.classList.add('item-download');
            link.download = this.itemTitle.replace(/[\\\/:"<>\*\?\|]/g, '_');
            link.innerText = this.titleTextElement.innerText;
            this.titleElement.innerHTML = '';
            this.titleElement.appendChild(this.titleTextElement = link);
          }
        },
      },
      startAddingItems: {
        value: function() {
          if (!this.classList.contains('has-subitems')) {
            this.classList.add('has-subitems');
            this.appendChild(this.subitemsElement = document.createElement('SECTION'));
            this.subitemsElement.classList.add('subitems');
          }
        },
      },
      addItem: {
        value: function(item) {
          this.startAddingItems();
          this.classList.add('itemizing');
          this.subitemsElement.appendChild(item);
        },
      },
      confirmAllItemsAdded: {
        value: function() {
          this.classList.remove('itemizing');
          this.classList.add('itemized');
        },
      },
    },
  };

  function clickItem(e) {
    e.stopPropagation();
    if (e.target.classList.contains('item-download')) {
      if (e.target.href === '#') {
        e.preventDefault();
        this.byteSource.getURL().then(function(url) {
          e.target.href = url;
          e.target.click();
        });
      }
      return;
    }
    if (this.classList.contains('has-subitems')) {
      if (this.classList.toggle('open')) {
        this.dispatchEvent(new Event(itemObjectModel.EVT_POPULATE));
      }
    }
  }

  Object.defineProperties(itemObjectModel, {
    EVT_POPULATE: {value:'item-populate'},
  });

  return itemObjectModel;

});
<commit_msg>Use classes for handling download link state<commit_after>define(function() {

  'use strict';

  var _BYTESOURCE = Symbol('byteSource');

  var itemObjectModel = {
    createItem: function(title) {
      var itemElement = document.createElement('SECTION');
      itemElement.classList.add('item');

      itemElement.appendChild(itemElement.titleElement = document.createElement('HEADER'));

      itemElement.titleTextElement = itemElement.titleElement;

      Object.defineProperties(itemElement, this.itemProperties);

      if (title) itemElement.itemTitle = title;

      itemElement.addEventListener('click', clickItem);

      return itemElement;
    },
    itemProperties: {
      itemTitle: {
        get: function() {
          return this.titleTextElement.innerText;
        },
        set: function(text) {
          this.titleTextElement.innerText = text;
        },
        enumerable: true,
      },
      byteSource: {
        get: function() {
          return this[_BYTESOURCE];
        },
        set: function(byteSource) {
          this[_BYTESOURCE] = byteSource;
          if (!byteSource) {
            this.titleElement.innerText = this.titleTextElement.innerText;
            this.titleTextElement = this.titleElement;
          }
          else {
            var link = document.createElement('A');
            link.href = '#';
            link.classList.add('item-download');
            link.download = this.itemTitle.replace(/[\\\/:"<>\*\?\|]/g, '_');
            link.innerText = this.titleTextElement.innerText;
            this.titleElement.innerHTML = '';
            this.titleElement.appendChild(this.titleTextElement = link);
          }
        },
      },
      startAddingItems: {
        value: function() {
          if (!this.classList.contains('has-subitems')) {
            this.classList.add('has-subitems');
            this.appendChild(this.subitemsElement = document.createElement('SECTION'));
            this.subitemsElement.classList.add('subitems');
          }
        },
      },
      addItem: {
        value: function(item) {
          this.startAddingItems();
          this.classList.add('itemizing');
          this.subitemsElement.appendChild(item);
        },
      },
      confirmAllItemsAdded: {
        value: function() {
          this.classList.remove('itemizing');
          this.classList.add('itemized');
        },
      },
    },
  };

  function clickItem(e) {
    e.stopPropagation();
    if (e.target.classList.contains('item-download')) {
      if (!e.target.classList.contains('prepared')) {
        e.preventDefault();
        if (!e.target.classList.contains('preparing')) {
          e.target.classList.add('preparing');
          this.byteSource.getURL().then(function(url) {
            e.target.classList.remove('preparing');
            e.target.classList.add('prepared');
            e.target.href = url;
            e.target.click();
          });
        }
      }
      return;
    }
    if (this.classList.contains('has-subitems')) {
      if (this.classList.toggle('open')) {
        this.dispatchEvent(new Event(itemObjectModel.EVT_POPULATE));
      }
    }
  }

  Object.defineProperties(itemObjectModel, {
    EVT_POPULATE: {value:'item-populate'},
  });

  return itemObjectModel;

});
<|endoftext|>


<commit_before>'use strict';
const request = require('request-promise');
const mongoose = require('mongoose');
const stateGen = require('crypto-random-string');
var UserData = mongoose.model('UserData');

require('../../db.js');

// these are credentials that are used for facebook to authorise the login
var credentials = {
    ClientId: process.env.CLIENT_ID,
    ClientSecret: process.env.CLIENT_SECRET,
    state: {
        st: '',
        ds: '',
    },
    redirect_uri: 'http://localhost:8080/fbCode',
};

var access_token, person;

module.exports = async(app) => {

    // this get route redirects the user to facebooks site to handle their login
    app.get('/fb', (req, res) => {
        credentials.state.st = stateGen(20);
        credentials.state.ds = stateGen(20);
        res.redirect(`https://www.facebook.com/v3.1/dialog/oauth?client_id=${credentials.ClientId}&redirect_uri=${credentials.redirect_uri}&state=${JSON.stringify(credentials.state)}`);
    });

    // this route deals with what comes back when facebook redirects back to the site and the application then has to exchange the code returned from the login
    // and the applications credentials in return for an access token which is then used to get the users details
    app.get('/fbCode', (req, res) => {
        var code = req.query.code;
        var err = req.query.error;
        var state = JSON.parse(req.query.state);

        if (state.st !== credentials.state.st && state.ds !== credentials.state.ds) {
            console.log('State does not match up! Error');
            res.writeHead('409');
            res.end('The state did not match up, there may be something intercepting your traffic.');
        }

        if (err !== undefined) console.log(err);

        request.get(`https://graph.facebook.com/v3.1/oauth/access_token?client_id=${credentials.ClientId}&redirect_uri=${credentials.redirect_uri}&client_secret=${credentials.ClientSecret}&code=${code}`).then((body) => {
            var data = JSON.parse(body);
            access_token = data.access_token; // this is the access token retuned

            // this then uses the access token to gain the users details
            request.get(`https://graph.facebook.com/v3.1/me?fields=id%2Cname%2Cpicture&access_token=${access_token}&redirect_uri=http://localhost:8080/`).then(body => {
                person = JSON.parse(body);

                UserData.findOne({_id: person.id}, (err, user) => {
                    if (err) console.log('err: ' + err);

                    console.log('user: ' + user);

                    if (user == null) {
                        var userId = (person.name.replace(/\s/g, '')).toUpperCase() + '#' + stateGen(10).toUpperCase();

                        var userObject = {
                            _id: person.id,
                            name: person.name,
                            meetId: userId,
                            pictureURL: person.picture.data.url,
                            invites: [],
                        };

                        var newUser = new UserData(userObject);

                        newUser.save()
                        .then(savedUser => {
                            console.log('User Saved: ' + savedUser);
                        }).catch(err => {
                            console.log(err);
                        });
                    }
                });
                // SUCCESS CONDITION
            }).catch(e => {
                console.log(e);
            });
        }).catch(e => {
            console.log(e);
        });
    });
};
<commit_msg>relocated the declaration of the userObject<commit_after>'use strict';
const request = require('request-promise');
const mongoose = require('mongoose');
const stateGen = require('crypto-random-string');
var UserData = mongoose.model('UserData');

require('../../db.js');

// these are credentials that are used for facebook to authorise the login
var credentials = {
    ClientId: process.env.CLIENT_ID,
    ClientSecret: process.env.CLIENT_SECRET,
    state: {
        st: '',
        ds: '',
    },
    redirect_uri: 'http://localhost:8080/fbCode',
};

var access_token, person, userObject;

module.exports = async(app) => {

    // this get route redirects the user to facebooks site to handle their login
    app.get('/fb', (req, res) => {
        credentials.state.st = stateGen(20);
        credentials.state.ds = stateGen(20);
        res.redirect(`https://www.facebook.com/v3.1/dialog/oauth?client_id=${credentials.ClientId}&redirect_uri=${credentials.redirect_uri}&state=${JSON.stringify(credentials.state)}`);
    });

    // this route deals with what comes back when facebook redirects back to the site and the application then has to exchange the code returned from the login
    // and the applications credentials in return for an access token which is then used to get the users details
    app.get('/fbCode', (req, res) => {
        var code = req.query.code;
        var err = req.query.error;
        var state = JSON.parse(req.query.state);

        if (state.st !== credentials.state.st && state.ds !== credentials.state.ds) {
            console.log('State does not match up! Error');
            res.writeHead('409');
            res.end('The state did not match up, there may be something intercepting your traffic.');
        }

        if (err !== undefined) console.log(err);

        request.get(`https://graph.facebook.com/v3.1/oauth/access_token?client_id=${credentials.ClientId}&redirect_uri=${credentials.redirect_uri}&client_secret=${credentials.ClientSecret}&code=${code}`).then((body) => {
            var data = JSON.parse(body);
            access_token = data.access_token; // this is the access token retuned

            // this then uses the access token to gain the users details
            request.get(`https://graph.facebook.com/v3.1/me?fields=id%2Cname%2Cpicture&access_token=${access_token}&redirect_uri=http://localhost:8080/`).then(body => {
                person = JSON.parse(body);

                UserData.findOne({_id: person.id}, (err, user) => {
                    if (err) console.log('err: ' + err);

                    console.log('user: ' + user);

                    if (user == null) {
                        var userId = (person.name.replace(/\s/g, '')).toUpperCase() + '#' + stateGen(10).toUpperCase();

                        userObject = {
                            _id: person.id,
                            name: person.name,
                            meetId: userId,
                            pictureURL: person.picture.data.url,
                            invites: [],
                        };

                        var newUser = new UserData(userObject);

                        newUser.save()
                        .then(savedUser => {
                            console.log('User Saved: ' + savedUser);
                        }).catch(err => {
                            console.log(err);
                        });
                    }
                });
                // SUCCESS CONDITION
            }).catch(e => {
                console.log(e);
            });
        }).catch(e => {
            console.log(e);
        });

        res.json(userObject);
        res.end();
    });
};
<|endoftext|>


<commit_before>// Contains a clone of the classic "xeyes" demos.

(function(exports) {
    "use strict";

    function ellipse(ctx, x, y, rx, ry) {
        x -= rx;
        y -= ry;

        var kappa = .5522848;
        var ox = rx * kappa;
        var oy = ry * kappa;
        var xe = x + rx * 2;
        var ye = y + ry * 2;
        var xm = x + rx;
        var ym = y + ry;

        ctx.beginPath();
        ctx.moveTo(x, ym);
        ctx.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
        ctx.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
        ctx.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
        ctx.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
        ctx.closePath();
    }

    var Xeyes = new Class({
        initialize: function(server) {
            var connection = server.connect();
            this._display = connection.display;
            var port = connection.clientPort;
            port.addEventListener("message", function(messageEvent) {
                this._handleEvent(messageEvent.data);
            }.bind(this));

            this._pointerRootX = -1;
            this._pointerRootY = -1;

            this.windowId = this._display.createWindow({ x: 0, y: 0, width: 200, height: 150 });
            this._display.selectInput({ windowId: this.windowId, events: ["Expose", "ConfigureNotify", "MapNotify", "UnmapNotify"] });
            this._display.changeProperty({ windowId: this.windowId, name: "WM_NAME", value: "xeyes.js" });
            this._exposeHandler = new DemoCommon.ExposeHandler(this._draw.bind(this));
        },
        _start: function() {
            this._intervalId = setInterval(function() {
                var pointer = this._display.queryPointer();
                if (pointer.rootX == this._pointerRootX &&
                    pointer.rootY == this._pointerRootY)
                    return;

                this._pointerRootX = pointer.rootX;
                this._pointerRootY = pointer.rootY;
                this._display.invalidateWindow({ windowId: this.windowId });
            }.bind(this), 50);
        },
        _stop: function() {
            clearInterval(this._intervalId);
            this._intervalId = 0;
        },
        _configureNotify: function(event) {
            // Invalidate the entire window when we get resized, as we need
            // to repaint all contents to fit the new size.
            if (event.width !== undefined || event.height !== undefined)
                this._display.invalidateWindow({ windowId: this.windowId });
        },
        handleEvent: function(event) {
            switch(event.type) {
            case "Expose":
                return this._exposeHandler.handleExpose(event);
            case "ConfigureNotify":
                return this._configureNotify(event);
            case "MapNotify":
                return this._start();
            case "UnmapNotify":
                return this._stop();
            }
        },

        _draw: function() {
            var eyeRX = this.width / 4 - 6;
            var eyeRY = this.height / 2 - 6;
            var eyeCenterLX = this.width * (1/4);
            var eyeCenterRX = this.width * (3/4);
            var eyeCenterY = this.height / 2;

            var pupilRX = eyeRX / 4;
            var pupilRY = eyeRY / 4;

            var pointerCoords = this._display.translateCoordinates({ srcWindowId: this._display.rootWindowId,
                                                                     destWindowId: this.windowId,
                                                                     x: this._pointerRootX,
                                                                     y: this._pointerRootY });

            function hypot(x, y) {
                return Math.sqrt(x*x + y*y);
            }

            function getPupilPosition(eyeCenterX) {
                // The max distance away from the center the pupil
                // is allowed to be.
                var maxDistX = eyeRX - pupilRX - 20;
                var maxDistY = eyeRY - pupilRY - 20;

                // Normalize to center of eye.
                var pointerX = pointerCoords.x - eyeCenterX;
                var pointerY = pointerCoords.y - eyeCenterY;

                var distance = hypot(pointerX / maxDistX, pointerY / maxDistY);
                if (distance > 1)
                    distance = 1;

                var angle = Math.atan2(pointerY, pointerX);

                // Pupil position relative to center of eye.
                var pupilX = Math.cos(angle) * distance * maxDistX;
                var pupilY = Math.sin(angle) * distance * maxDistY;

                return { x: pupilX, y: pupilY };
            }

            this._display.drawTo(this.windowId, function(ctx) {
                this._exposeHandler.clip(ctx);

                ctx.fillStyle = '#eeeeec';
                ctx.fillRect(0, 0, this.width, this.height);

                ctx.strokeStyle = '#000000';
                ctx.lineWidth = 10;
                ctx.fillStyle = '#ffffff';

                // scleras
                ellipse(ctx, eyeCenterLX, eyeCenterY, eyeRX, eyeRY);
                ctx.fill();
                ctx.stroke();

                ellipse(ctx, eyeCenterRX, eyeCenterY, eyeRX, eyeRY);
                ctx.fill();
                ctx.stroke();
                // pupils
                ctx.fillStyle = '#000000';

                var pos;

                pos = getPupilPosition(eyeCenterLX);
                ellipse(ctx, eyeCenterLX + pos.x, eyeCenterY + pos.y, pupilRX, pupilRY);
                ctx.fill();

                pos = getPupilPosition(eyeCenterRX);
                ellipse(ctx, eyeCenterRX + pos.x, eyeCenterY + pos.y, pupilRX, pupilRY);
                ctx.fill();
            }.bind(this));
        },
    });

    exports.Xeyes = Xeyes;

})(window);
<commit_msg>xeyes: Simplify code<commit_after>// Contains a clone of the classic "xeyes" demos.

(function(exports) {
    "use strict";

    function ellipse(ctx, rx, ry) {
        var kappa = .5522848;
        var ox = rx * kappa;
        var oy = ry * kappa;

        ctx.beginPath();
        ctx.moveTo(-rx, 0);
        ctx.bezierCurveTo(-rx, -oy, -ox, -ry, 0, -ry);
        ctx.bezierCurveTo(ox, -ry, rx, -oy, rx, 0);
        ctx.bezierCurveTo(rx, oy, ox, ry, 0, ry);
        ctx.bezierCurveTo(-ox, ry, -rx, oy, -rx, 0);
        ctx.closePath();
    }

    var Xeyes = new Class({
        initialize: function(server) {
            var connection = server.connect();
            this._display = connection.display;
            var port = connection.clientPort;
            port.addEventListener("message", function(messageEvent) {
                this._handleEvent(messageEvent.data);
            }.bind(this));

            this._pointerRootX = -1;
            this._pointerRootY = -1;

            this.windowId = this._display.createWindow({ x: 50, y: 50, width: 200, height: 150 });
            this._display.selectInput({ windowId: this.windowId, events: ["Expose", "ConfigureNotify", "MapNotify", "UnmapNotify"] });
            this._display.changeProperty({ windowId: this.windowId, name: "WM_NAME", value: "xeyes.js" });
            this._exposeHandler = new ClientUtil.ExposeHandler(this._draw.bind(this));
        },
        _start: function() {
            this._intervalId = setInterval(function() {
                var pointer = this._display.queryPointer();
                if (pointer.rootX == this._pointerRootX &&
                    pointer.rootY == this._pointerRootY)
                    return;

                this._pointerRootX = pointer.rootX;
                this._pointerRootY = pointer.rootY;
                this._display.invalidateWindow({ windowId: this.windowId });
            }.bind(this), 50);
        },
        _stop: function() {
            clearInterval(this._intervalId);
            this._intervalId = 0;
        },
        _configureNotify: function(event) {
            // Invalidate the entire window when we get resized, as we need
            // to repaint all contents to fit the new size.
            if (event.width !== undefined || event.height !== undefined)
                this._display.invalidateWindow({ windowId: this.windowId });
        },
        _handleEvent: function(event) {
            switch(event.type) {
            case "Expose":
                return this._exposeHandler.handleExpose(event);
            case "ConfigureNotify":
                return this._configureNotify(event);
            case "MapNotify":
                return this._start();
            case "UnmapNotify":
                return this._stop();
            }
        },

        _draw: function() {
            var geom = this._display.getGeometry({ drawableId: this.windowId });
            var width = geom.width, height = geom.height;

            var eyeRX = width / 4 - 6;
            var eyeRY = height / 2 - 6;
            var eyeCenterLX = width * (1/4);
            var eyeCenterRX = width * (3/4);
            var eyeCenterY = height / 2;

            var pupilRX = eyeRX / 4;
            var pupilRY = eyeRY / 4;

            var pointerCoords = this._display.translateCoordinates({ srcWindowId: this._display.rootWindowId,
                                                                     destWindowId: this.windowId,
                                                                     x: this._pointerRootX,
                                                                     y: this._pointerRootY });

            function hypot(x, y) {
                return Math.sqrt(x*x + y*y);
            }

            function getPupilPosition(eyeCenterX) {
                // The max distance away from the center the pupil
                // is allowed to be.
                var maxDistX = eyeRX - pupilRX - 20;
                var maxDistY = eyeRY - pupilRY - 20;

                // Normalize to center of eye.
                var pointerX = pointerCoords.x - eyeCenterX;
                var pointerY = pointerCoords.y - eyeCenterY;

                var distance = hypot(pointerX / maxDistX, pointerY / maxDistY);
                if (distance > 1)
                    distance = 1;

                var angle = Math.atan2(pointerY, pointerX);

                // Pupil position relative to center of eye.
                var pupilX = Math.cos(angle) * distance * maxDistX;
                var pupilY = Math.sin(angle) * distance * maxDistY;

                return { x: pupilX, y: pupilY };
            }

            this._display.drawTo(this.windowId, function(ctx) {
                this._exposeHandler.clip(ctx);

                ctx.fillStyle = 'white';
                ctx.fillRect(0, 0, width, height);

                ctx.strokeStyle = 'black';
                ctx.lineWidth = 6;

                // scleras
                ctx.save();
                ctx.translate(eyeCenterLX, eyeCenterY);
                ellipse(ctx, eyeRX, eyeRY);
                ctx.fill();
                ctx.stroke();
                ctx.restore();

                ctx.save();
                ctx.translate(eyeCenterRX, eyeCenterY);
                ellipse(ctx, eyeRX, eyeRY);
                ctx.fill();
                ctx.stroke();
                ctx.restore();

                // pupils
                ctx.fillStyle = 'black';

                var pos;

                pos = getPupilPosition(eyeCenterLX);
                ctx.save();
                ctx.translate(eyeCenterLX + pos.x, eyeCenterY + pos.y);
                ellipse(ctx, pupilRX, pupilRY);
                ctx.restore();
                ctx.fill();

                pos = getPupilPosition(eyeCenterRX);
                ctx.save();
                ctx.translate(eyeCenterRX + pos.x, eyeCenterY + pos.y);
                ellipse(ctx, pupilRX, pupilRY);
                ctx.restore();
                ctx.fill();
            }.bind(this));
        },
    });

    exports.Xeyes = Xeyes;

})(window);
<|endoftext|>


<commit_before>/**
 * This program is checked with node.js
 */

var onp = require('./onp.js')

var diff = new onp.Diff(process.argv[2], process.argv[3]);
diff.compose();
console.log("editdistance:" + diff.editdistance());
console.log("lcs:" + diff.getlcs());
console.log("ses");

var ses = diff.getses();
for (var i=0;i<ses.length;++i) {
    if (ses[i].t == diff.SES_COMMON) {
        console.log("  " + ses[i].elem);
    } else if (ses[i].t == diff.SES_DELETE) {
        console.log("- " + ses[i].elem);
    } else if (ses[i].t == diff.SES_ADD) {
        console.log("+ " + ses[i].elem);
    }
}
<commit_msg>adjust space<commit_after>/**
 * This program is checked with node.js
 */

var onp = require('./onp.js')

var diff = new onp.Diff(process.argv[2], process.argv[3]);
diff.compose();
console.log("editdistance:" + diff.editdistance());
console.log("lcs:" + diff.getlcs());
console.log("ses");

var ses = diff.getses();
for (var i=0;i<ses.length;++i) {
    if (ses[i].t == diff.SES_COMMON) {
        console.log(" " + ses[i].elem);
    } else if (ses[i].t == diff.SES_DELETE) {
        console.log("-" + ses[i].elem);
    } else if (ses[i].t == diff.SES_ADD) {
        console.log("+" + ses[i].elem);
    }
}
<|endoftext|>


<commit_before>import inquirer from 'inquirer';
import ProgressBar from 'progress';
import { Api, Exp, Logger, NotificationCode, MessageCode } from 'xdl';

import _ from 'lodash';
import log from '../log';
import CommandError from '../CommandError';

import path from 'path';

let _currentRequestID = 0;
let _downloadIsSlowPrompt = false;
let _retryObject = {};

async function action(projectDir, options) {
  let templateType;
  let questions = [];

  let insertPath = path.dirname(projectDir);
  let name = path.basename(projectDir);

  // If the user does not supply a project name, exp prompts the user
  if (projectDir === process.cwd()) {
    questions.push({
      name: 'name',
      message: 'Choose a project name:',
      validate(input) {
        return /^[a-z0-9@.' '\-\_]*$/i.test(input) && input.length > 0;
      },
    });
  }

  if (options.projectType) {
    templateType = options.projectType;
  } else {
    let versions = await Api.versionsAsync();
    let templateIds = _.map(versions.templatesv2, template => template.id);

    questions.push({
      type: 'list',
      name: 'type',
      message: 'Choose a template type:',
      choices: templateIds,
    });
  }

  if (questions.length > 0) {
    var answers = await inquirer.prompt(questions);
    if (answers.name) {
      // If the user supplies a project name, change the insertPath and name
      insertPath = projectDir;
      name = answers.name;
    }
    if (answers.type) {
      templateType = answers.type;
    }
  }

  if (!insertPath || !name) {
    throw new CommandError(
      'PATH_ERROR',
      `Couldn't determine path for new project.`
    );
  }

  // TODO(jim): We will need to update this method later to not force
  // us to strip out the <name> from /path/to/<name> if we don't want
  // to duplicate the folder at creation time. (example: test => test/test)
  await downloadAndExtractTemplate(templateType, insertPath, {
    name,
  });
}

async function downloadAndExtractTemplate(
  templateType,
  projectDir,
  validatedOptions
) {
  _retryObject = { templateType, projectDir, validatedOptions };
  const requestID = _currentRequestID + 1;
  _currentRequestID = requestID;
  let templateDownload = await Exp.downloadTemplateApp(
    templateType,
    projectDir,
    {
      ...validatedOptions,
      progressFunction: progress => {
        const percent = Math.round(progress * 100);
        if (_currentRequestID === requestID) {
          Logger.notifications.info(
            { code: NotificationCode.DOWNLOAD_CLI_PROGRESS },
            percent + '%'
          );
          const bar = new ProgressBar('[:bar] :percent', {
            total: 100,
            complete: '=',
            incomplete: ' ',
          });
          if (!_downloadIsSlowPrompt) {
            bar.tick(percent);
          }
        }
      },
      retryFunction: () => {
        triggerRetryPrompt();
      },
    }
  );

  // Since we cannot cancel the download request, we need a way to ignore all of the requests made except the last one when retrying.
  if (_currentRequestID !== requestID) {
    return;
  }
  let root = await Exp.extractTemplateApp(
    templateDownload.starterAppPath,
    templateDownload.name,
    templateDownload.root
  );
  log(
    `Your project is ready at ${root}. Use "exp start ${root}" to get started.`
  );
  process.exit();
}

async function triggerRetryPrompt() {
  _downloadIsSlowPrompt = true;
  var answer = await inquirer({
    type: 'input',
    name: 'retry',
    message: '\n' + MessageCode.DOWNLOAD_IS_SLOW + '(y/n)',
    validate(val) {
      if (val !== 'y' && val !== 'n') {
        return false;
      }
      return true;
    },
  });

  if (answer.retry === 'n') {
    _downloadIsSlowPrompt = false;
  } else {
    Exp.clearXDLCacheAsync();
    _downloadIsSlowPrompt = false;
    downloadAndExtractTemplate(
      _retryObject.templateType,
      _retryObject.projectDir,
      _retryObject.validatedOptions
    );
  }
}

export default program => {
  program
    .command('init [project-dir]')
    .alias('i')
    .description(
      'Initializes a directory with an example project. Run it without any options and you will be prompted for the name and type.'
    )
    .option(
      '-t, --projectType [type]',
      'Specify what type of template to use. Run without this option to see all choices.'
    )
    .allowNonInteractive()
    .asyncActionProjectDir(action, true /* skipProjectValidation */);
};
<commit_msg>Make XDE use the Chromium HTTP stack with Axios (#1284)<commit_after>import inquirer from 'inquirer';
import ProgressBar from 'progress';
import { Api, Exp, Logger, NotificationCode, MessageCode } from 'xdl';

import _ from 'lodash';
import log from '../log';
import CommandError from '../CommandError';

import path from 'path';

let _currentRequestID = 0;
let _downloadIsSlowPrompt = false;
let _retryObject = {};
let _bar = new ProgressBar('[:bar] :percent', {
  total: 100,
  complete: '=',
  incomplete: ' ',
});

async function action(projectDir, options) {
  let templateType;
  let questions = [];

  let insertPath = path.dirname(projectDir);
  let name = path.basename(projectDir);

  // If the user does not supply a project name, exp prompts the user
  if (projectDir === process.cwd()) {
    questions.push({
      name: 'name',
      message: 'Choose a project name:',
      validate(input) {
        return /^[a-z0-9@.' '\-\_]*$/i.test(input) && input.length > 0;
      },
    });
  }

  if (options.projectType) {
    templateType = options.projectType;
  } else {
    let versions = await Api.versionsAsync();
    let templateIds = _.map(versions.templatesv2, template => template.id);

    questions.push({
      type: 'list',
      name: 'type',
      message: 'Choose a template type:',
      choices: templateIds,
    });
  }

  if (questions.length > 0) {
    var answers = await inquirer.prompt(questions);
    if (answers.name) {
      // If the user supplies a project name, change the insertPath and name
      insertPath = projectDir;
      name = answers.name;
    }
    if (answers.type) {
      templateType = answers.type;
    }
  }

  if (!insertPath || !name) {
    throw new CommandError(
      'PATH_ERROR',
      `Couldn't determine path for new project.`
    );
  }

  // TODO(jim): We will need to update this method later to not force
  // us to strip out the <name> from /path/to/<name> if we don't want
  // to duplicate the folder at creation time. (example: test => test/test)
  await downloadAndExtractTemplate(templateType, insertPath, {
    name,
  });
}

async function downloadAndExtractTemplate(
  templateType,
  projectDir,
  validatedOptions
) {
  _retryObject = { templateType, projectDir, validatedOptions };
  const requestID = _currentRequestID + 1;
  _currentRequestID = requestID;

  let templateDownload = await Exp.downloadTemplateApp(
    templateType,
    projectDir,
    {
      ...validatedOptions,
      progressFunction: progress => {
        if (_currentRequestID === requestID) {
          Logger.notifications.info(
            { code: NotificationCode.DOWNLOAD_CLI_PROGRESS },
            progress + '%'
          );
          if (!_downloadIsSlowPrompt) {
            _bar.tick();
          }
        }
      },
      retryFunction: () => {
        triggerRetryPrompt();
      },
    }
  );

  // Since we cannot cancel the download request, we need a way to ignore all of the requests made except the last one when retrying.
  if (_currentRequestID !== requestID) {
    return;
  }
  let root = await Exp.extractTemplateApp(
    templateDownload.starterAppPath,
    templateDownload.name,
    templateDownload.root
  );
  log(
    `Your project is ready at ${root}. Use "exp start ${root}" to get started.`
  );
  process.exit();
}

async function triggerRetryPrompt() {
  _downloadIsSlowPrompt = true;
  var answer = await inquirer({
    type: 'input',
    name: 'retry',
    message: '\n' + MessageCode.DOWNLOAD_IS_SLOW + '(y/n)',
    validate(val) {
      if (val !== 'y' && val !== 'n') {
        return false;
      }
      return true;
    },
  });

  if (answer.retry === 'n') {
    _downloadIsSlowPrompt = false;
  } else {
    Exp.clearXDLCacheAsync();
    _downloadIsSlowPrompt = false;
    downloadAndExtractTemplate(
      _retryObject.templateType,
      _retryObject.projectDir,
      _retryObject.validatedOptions
    );
  }
}

export default program => {
  program
    .command('init [project-dir]')
    .alias('i')
    .description(
      'Initializes a directory with an example project. Run it without any options and you will be prompted for the name and type.'
    )
    .option(
      '-t, --projectType [type]',
      'Specify what type of template to use. Run without this option to see all choices.'
    )
    .allowNonInteractive()
    .asyncActionProjectDir(action, true /* skipProjectValidation */);
};
<|endoftext|>