<commit_before>
(function() {

    /**
     * A Moveable implementation.
     * @implements{Moveable}
     */
    function ClientMoveable(object, transform, collisionimage) {
    	//TODO: need internal data and transform as well as object?
		//vec3
		this.position = new Array(3);
		this.position[0] = transform.translation.x;
		this.position[1] = transform.translation.y;
		this.position[2] = transform.translation.z;
		//quaternion
		this.orientation = new Array(4);
		this.orientation[0] = transform.rotation;
		this.orientation[1] = transform.rotation;
		this.orientation[2] = transform.rotation;
		this.orientation[3] = transform.rotation;

		//oject
		this.object = object;

		//transform
		this.transform = transform;

		// binary 2d map for collision check
		var img = new Image();
		img.src = "collision.png";//collisionimage;
		var element = document.getElementById("canvas");
		this.context = element.getContext("2d");
		this.context.drawImage(img, 0, 0);
		this.imgWidth = element.width;
		this.imgHeight = element.height;
    };

    var p = ClientMoveable.prototype;

    /**
     * Set the absolute position.
     */
    p.setPosition = function(x,y,z){
		if(this.checkCollision(x, y, z)){
			//alert("collision at x: " + x + " z: " + z);
			return;
		}
    	this.position[0] = x;
		this.position[1] = y;
		this.position[2] = z;

		//object data
		this.transform.translation.set(x,y,z);
    };

	/**
	 * Set the absolute orientation.
	 */
	p.setOrientation = function(x,y,z,s){
		//TODO: set internal data
		//this.orientation[0] = transform.rotation;
		//this.orientation[1] = transform.rotation;
		//this.orientation[2] = transform.rotation;
		//this.orientation[3] = transform.rotation;
		this.transform.rotation.setQuaternion(new XML3DVec3(x,y,z), s);
    };

    /**
     * Translate the object by the given values.
     */
    p.translate = function(x,y,z){
		if(this.checkCollision(x, y, z)){
			//alert("collision at x: " + x + " z: " + z);
			return;
		}
		this.position[0] += x;
		this.position[1] += y;
		this.position[2] += z;

		this.transform.translation.set(this.transform.translation.add(new XML3DVec3(x,y,z)));
    };

    /**
     * Rotate the object by the given values.
     */
    p.rotate = function(){};

    /**
     * Simple Method to check if a given position is allowed as a new position for the object.
     * Returns true if a collision is detected.
     */
    p.checkCollision = function(x,y,z){
		//z coord of the scene is y coord of the map
		if(x<0 || y< 0 || y<0) return true; // its forbidden to move away from the plane
		var checkAtX = x/5*this.imgWidth;
		var checkAtY = z/5*this.imgHeight;
		//TODO: check rotationssymmetrische dingsda, also z achse der szene = -y des bildes?
		var data = this.context.getImageData(checkAtX,checkAtY,1,1).data;
		alert("atX: " + checkAtX + "atY: " + checkAtY + " R " + data[0] + " G " + data[1] + " B " + data[2]);
		return !(data[0] || data[1] || data[2]);
    };

    //export
    XMOT.ClientMoveable = ClientMoveable;
}());
<commit_msg>Cleaned up; removed (useless) internal data<commit_after>
(function() {

    /**
     * A Moveable implementation.
     * @implements{Moveable}
     */
    function ClientMoveable(object, transform, collisionimage) {
		//oject
		this.object = object;

		//transform
		this.transform = transform;

		// binary 2d map for collision check
		var img = new Image();
		img.src = "collision.png";//collisionimage;
		var element = document.getElementById("canvas");
		this.context = element.getContext("2d");
		this.context.drawImage(img, 0, 0);
		this.imgWidth = element.width;
		this.imgHeight = element.height;
    };

    var p = ClientMoveable.prototype;

    /**
     * Set the absolute position.
     */
    p.setPosition = function(x,y,z){
		if(this.checkCollision(x, y, z)){
			return;
		}
		//object data
		this.transform.translation.set(x,y,z);
    };

	/**
	 * Set the absolute orientation.
	 */
	p.setOrientation = function(x,y,z,s){
		this.transform.rotation.setQuaternion(new XML3DVec3(x,y,z), s);
    };

    /**
     * Translate the object by the given values.
     */
    p.translate = function(x,y,z){
		if(this.checkCollision(x, y, z)){
			return;
		}
		this.transform.translation.set(this.transform.translation.add(new XML3DVec3(x,y,z)));
    };

    /**
     * Rotate the object by the given values.
     */
    p.rotate = function(){};

    /**
     * Simple Method to check if a given position is allowed as a new position for the object.
     * Returns true if a collision is detected.
     */
    p.checkCollision = function(x,y,z){
		//z coord of the scene is y coord of the map
		if(x<0 || y< 0 || y<0) return true; // its forbidden to move away from the plane
		var checkAtX = x/5*this.imgWidth;
		var checkAtY = z/5*this.imgHeight;
		//TODO: check rotationssymmetrische dingsda, also z achse der szene = -y des bildes?
		var data = this.context.getImageData(checkAtX,checkAtY,1,1).data;
		alert("atX: " + checkAtX + "atY: " + checkAtY + " R " + data[0] + " G " + data[1] + " B " + data[2]);
		return !(data[0] || data[1] || data[2]);
    };

    //export
    XMOT.ClientMoveable = ClientMoveable;
}());
<|endoftext|>


<commit_before>/* Copyright (c) 2006-2011 by OpenLayers Contributors (see authors.txt for
 * full list of contributors). Published under the Clear BSD license.
 * See http://svn.openlayers.org/trunk/openlayers/license.txt for the
 * full text of the license. */

/**
 * @requires OpenLayers/Format/XML.js
 */

/**
 * Class: OpenLayers.Format.WCSGetCoverage version 1.1.0
 *
 * Inherits from:
 *  - <OpenLayers.Format.XML>
 */
OpenLayers.Format.WCSGetCoverage = OpenLayers.Class(OpenLayers.Format.XML, {

    /**
     * Property: namespaces
     * {Object} Mapping of namespace aliases to namespace URIs.
     */
    namespaces: {
        ows: "http://www.opengis.net/ows/1.1",
        wcs: "http://www.opengis.net/wcs/1.1",
        xlink: "http://www.w3.org/1999/xlink",
        xsi: "http://www.w3.org/2001/XMLSchema-instance"
    },

    /**
     * Property: regExes
     * Compiled regular expressions for manipulating strings.
     */
    regExes: {
        trimSpace: (/^\s*|\s*$/g),
        removeSpace: (/\s*/g),
        splitSpace: (/\s+/),
        trimComma: (/\s*,\s*/g)
    },

    /**
     * Constant: VERSION
     * {String} 1.1.2
     */
    VERSION: "1.1.2",

    /**
     * Property: schemaLocation
     * {String} Schema location
     */
    schemaLocation: "http://www.opengis.net/wcs/1.1 http://schemas.opengis.net/wcs/1.1/wcsGetCoverage.xsd",

    /**
     * Constructor: OpenLayers.Format.WCSGetCoverage
     *
     * Parameters:
     * options - {Object} An optional object whose properties will be set on
     *     this instance.
     */

    /**
     * Method: write
     *
     * Parameters:
     * options - {Object} Optional object.
     *
     * Returns:
     * {String} A WCS GetCoverage request XML string.
     */
    write: function(options) {
        var node = this.writeNode("wcs:GetCoverage", options);
        this.setAttributeNS(
            node, this.namespaces.xsi,
            "xsi:schemaLocation", this.schemaLocation
        );
        return OpenLayers.Format.XML.prototype.write.apply(this, [node]);
    },

    /**
     * Property: writers
     * As a compliment to the readers property, this structure contains public
     *     writing functions grouped by namespace alias and named like the
     *     node names they produce.
     */
    writers: {
        "wcs": {
            "GetCoverage": function(options) {
                var node = this.createElementNSPlus("wcs:GetCoverage", {
                    attributes: {
                        version: options.version || this.VERSION,
                        service: 'WCS'
                    }
                });
                this.writeNode("ows:Identifier", options.identifier, node);
                this.writeNode("wcs:DomainSubset", options.domainSubset, node);
                this.writeNode("wcs:Output", options.output, node);
                return node;
            },
            "DomainSubset": function(domainSubset) {
                var node = this.createElementNSPlus("wcs:DomainSubset", {});
                this.writeNode("ows:BoundingBox", domainSubset.boundingBox, node);
                if (domainSubset.temporalSubset) {
                    this.writeNode("wcs:TemporalSubset", domainSubset.temporalSubset, node);
                }
                return node;
            },
            "TemporalSubset": function(temporalSubset) {
                var node = this.createElementNSPlus("wcs:TemporalSubset", {});
                for (var i=0, len=temporalSubset.timePeriods.length; i<len; ++i) {
                    this.writeNode("wcs:TimePeriod", temporalSubset.timePeriods[i], node);
                }
                return node;
            },
            "TimePeriod": function(timePeriod) {
                var node = this.createElementNSPlus("wcs:TimePeriod", {});
                this.writeNode("wcs:BeginPosition", timePeriod.begin, node);
                this.writeNode("wcs:EndPosition", timePeriod.end, node);
                if (timePeriod.resolution) {
                    this.writeNode("wcs:TimeResolution", timePeriod.resolution, node);
                }
                return node;
            },
            "BeginPosition": function(begin) {
                var node = this.createElementNSPlus("wcs:BeginPosition", {
                    value: begin
                });
                return node;
            },
            "EndPosition": function(end) {
                var node = this.createElementNSPlus("wcs:EndPosition", {
                    value: end
                });
                return node;
            },
            "TimeResolution": function(resolution) {
                var node = this.createElementNSPlus("wcs:TimeResolution", {
                    value: resolution
                });
                return node;
            },
            "Output": function(output) {
                var node = this.createElementNSPlus("wcs:Output", {
                    attributes: {
                        format: output.format,
                        store: output.store
                    }
                });
                if (output.gridCRS) {
                    this.writeNode("wcs:GridCRS", output.gridCRS, node);
                }
                return node;
            },
            "GridCRS": function(gridCRS) {
                var node = this.createElementNSPlus("wcs:GridCRS", {});
                this.writeNode("wcs:GridBaseCRS", gridCRS.baseCRS, node);
                if (gridCRS.type) {
                    this.writeNode("wcs:GridType", gridCRS.type, node);
                }
                if (gridCRS.origin) {
                    this.writeNode("wcs:GridOrigin", gridCRS.origin, node);
                }
                this.writeNode("wcs:GridOffsets", gridCRS.offsets, node);
                if (gridCRS.CS) {
                    this.writeNode("wcs:GridCS", gridCRS.CS, node);
                }
                return node;
            },
            "GridBaseCRS": function(baseCRS) {
                return this.createElementNSPlus("wcs:GridBaseCRS", {
                    value: baseCRS
                });
            },
            "GridOrigin": function(origin) {
                return this.createElementNSPlus("wcs:GridOrigin", {
                    value: origin
                });
            },
            "GridType": function(type) {
                return this.createElementNSPlus("wcs:GridType", {
                    value: type
                });
            },
            "GridOffsets": function(offsets) {
                return this.createElementNSPlus("wcs:GridOffsets", {
                    value: offsets
                });
            },
            "GridCS": function(CS) {
                return this.createElementNSPlus("wcs:GridCS", {
                    value: CS
                });
            }
        },
        "ows": OpenLayers.Format.OWSCommon.v1_1_0.prototype.writers.ows
    },

    CLASS_NAME: "OpenLayers.Format.WCSGetCoverage"

});
<commit_msg>add missing requires<commit_after>/* Copyright (c) 2006-2011 by OpenLayers Contributors (see authors.txt for
 * full list of contributors). Published under the Clear BSD license.
 * See http://svn.openlayers.org/trunk/openlayers/license.txt for the
 * full text of the license. */

/**
 * @requires OpenLayers/Format/XML.js
 * @requires OpenLayers/Format/OWSCommon/v1_1_0.js
 */

/**
 * Class: OpenLayers.Format.WCSGetCoverage version 1.1.0
 *
 * Inherits from:
 *  - <OpenLayers.Format.XML>
 */
OpenLayers.Format.WCSGetCoverage = OpenLayers.Class(OpenLayers.Format.XML, {

    /**
     * Property: namespaces
     * {Object} Mapping of namespace aliases to namespace URIs.
     */
    namespaces: {
        ows: "http://www.opengis.net/ows/1.1",
        wcs: "http://www.opengis.net/wcs/1.1",
        xlink: "http://www.w3.org/1999/xlink",
        xsi: "http://www.w3.org/2001/XMLSchema-instance"
    },

    /**
     * Property: regExes
     * Compiled regular expressions for manipulating strings.
     */
    regExes: {
        trimSpace: (/^\s*|\s*$/g),
        removeSpace: (/\s*/g),
        splitSpace: (/\s+/),
        trimComma: (/\s*,\s*/g)
    },

    /**
     * Constant: VERSION
     * {String} 1.1.2
     */
    VERSION: "1.1.2",

    /**
     * Property: schemaLocation
     * {String} Schema location
     */
    schemaLocation: "http://www.opengis.net/wcs/1.1 http://schemas.opengis.net/wcs/1.1/wcsGetCoverage.xsd",

    /**
     * Constructor: OpenLayers.Format.WCSGetCoverage
     *
     * Parameters:
     * options - {Object} An optional object whose properties will be set on
     *     this instance.
     */

    /**
     * Method: write
     *
     * Parameters:
     * options - {Object} Optional object.
     *
     * Returns:
     * {String} A WCS GetCoverage request XML string.
     */
    write: function(options) {
        var node = this.writeNode("wcs:GetCoverage", options);
        this.setAttributeNS(
            node, this.namespaces.xsi,
            "xsi:schemaLocation", this.schemaLocation
        );
        return OpenLayers.Format.XML.prototype.write.apply(this, [node]);
    },

    /**
     * Property: writers
     * As a compliment to the readers property, this structure contains public
     *     writing functions grouped by namespace alias and named like the
     *     node names they produce.
     */
    writers: {
        "wcs": {
            "GetCoverage": function(options) {
                var node = this.createElementNSPlus("wcs:GetCoverage", {
                    attributes: {
                        version: options.version || this.VERSION,
                        service: 'WCS'
                    }
                });
                this.writeNode("ows:Identifier", options.identifier, node);
                this.writeNode("wcs:DomainSubset", options.domainSubset, node);
                this.writeNode("wcs:Output", options.output, node);
                return node;
            },
            "DomainSubset": function(domainSubset) {
                var node = this.createElementNSPlus("wcs:DomainSubset", {});
                this.writeNode("ows:BoundingBox", domainSubset.boundingBox, node);
                if (domainSubset.temporalSubset) {
                    this.writeNode("wcs:TemporalSubset", domainSubset.temporalSubset, node);
                }
                return node;
            },
            "TemporalSubset": function(temporalSubset) {
                var node = this.createElementNSPlus("wcs:TemporalSubset", {});
                for (var i=0, len=temporalSubset.timePeriods.length; i<len; ++i) {
                    this.writeNode("wcs:TimePeriod", temporalSubset.timePeriods[i], node);
                }
                return node;
            },
            "TimePeriod": function(timePeriod) {
                var node = this.createElementNSPlus("wcs:TimePeriod", {});
                this.writeNode("wcs:BeginPosition", timePeriod.begin, node);
                this.writeNode("wcs:EndPosition", timePeriod.end, node);
                if (timePeriod.resolution) {
                    this.writeNode("wcs:TimeResolution", timePeriod.resolution, node);
                }
                return node;
            },
            "BeginPosition": function(begin) {
                var node = this.createElementNSPlus("wcs:BeginPosition", {
                    value: begin
                });
                return node;
            },
            "EndPosition": function(end) {
                var node = this.createElementNSPlus("wcs:EndPosition", {
                    value: end
                });
                return node;
            },
            "TimeResolution": function(resolution) {
                var node = this.createElementNSPlus("wcs:TimeResolution", {
                    value: resolution
                });
                return node;
            },
            "Output": function(output) {
                var node = this.createElementNSPlus("wcs:Output", {
                    attributes: {
                        format: output.format,
                        store: output.store
                    }
                });
                if (output.gridCRS) {
                    this.writeNode("wcs:GridCRS", output.gridCRS, node);
                }
                return node;
            },
            "GridCRS": function(gridCRS) {
                var node = this.createElementNSPlus("wcs:GridCRS", {});
                this.writeNode("wcs:GridBaseCRS", gridCRS.baseCRS, node);
                if (gridCRS.type) {
                    this.writeNode("wcs:GridType", gridCRS.type, node);
                }
                if (gridCRS.origin) {
                    this.writeNode("wcs:GridOrigin", gridCRS.origin, node);
                }
                this.writeNode("wcs:GridOffsets", gridCRS.offsets, node);
                if (gridCRS.CS) {
                    this.writeNode("wcs:GridCS", gridCRS.CS, node);
                }
                return node;
            },
            "GridBaseCRS": function(baseCRS) {
                return this.createElementNSPlus("wcs:GridBaseCRS", {
                    value: baseCRS
                });
            },
            "GridOrigin": function(origin) {
                return this.createElementNSPlus("wcs:GridOrigin", {
                    value: origin
                });
            },
            "GridType": function(type) {
                return this.createElementNSPlus("wcs:GridType", {
                    value: type
                });
            },
            "GridOffsets": function(offsets) {
                return this.createElementNSPlus("wcs:GridOffsets", {
                    value: offsets
                });
            },
            "GridCS": function(CS) {
                return this.createElementNSPlus("wcs:GridCS", {
                    value: CS
                });
            }
        },
        "ows": OpenLayers.Format.OWSCommon.v1_1_0.prototype.writers.ows
    },

    CLASS_NAME: "OpenLayers.Format.WCSGetCoverage"

});
<|endoftext|>


<commit_before>/**
 * @author: @mreinhardt
 */

const webpack = require('webpack');
const util = require('util');
const debugLog = util.debuglog('@holisticon/angularjs-common/webpack.common');
const path = require('path');
const helpers = require('./helpers');
const appConfig = helpers.getAppConfig();

debugLog('Using following appConfig:', appConfig);

/*
 * Webpack Plugins
 */
const NgAnnotatePlugin = require('ng-annotate-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const TsConfigPathsPlugin = require('awesome-typescript-loader').TsConfigPathsPlugin;
const ForkCheckerPlugin = require('awesome-typescript-loader').ForkCheckerPlugin;

/*
 * Webpack Constants
 */
const METADATA = {
  title: appConfig.title,
  baseUrl: '/',
  isDevServer: helpers.isWebpackDevServer()
};

/*
 * Webpack configuration
 *
 * See: http://webpack.github.io/docs/configuration.html#cli
 */
var config = {

  bail: true,

  /*
   * Static metadata for index.html
   *
   * See: (custom attribute)
   */
  metadata: METADATA,

  /*
   * The entry point for the bundle
   * Our Angular.js app
   *
   * See: http://webpack.github.io/docs/configuration.html#entry
   */
  entry: appConfig.entry,

  resolveLoader: {
    root: appConfig.modulesPath
  },
  /*
   * Options affecting the resolving of modules.
   *
   * See: http://webpack.github.io/docs/configuration.html#resolve
   */
  resolve: {

    /*
     * An array of extensions that should be used to resolve modules.
     *
     * See: http://webpack.github.io/docs/configuration.html#resolve-extensions
     */
    extensions: ['', '.ts', '.js', '.jsx', '.json'],

    // Make sure root is src
    root: appConfig.src,

    alias: {
      angular: path.resolve(appConfig.modulesPath, 'angular/angular.js')
    },

    packageMains: ['webpack', 'browser', 'web', 'browserify', ['jam', 'main'], 'main'],

    // remove other default values
    modulesDirectories: appConfig.modulesDirectories || [appConfig.modulesPath]

  },

  htmlLoader: {
    minimize: true,
    removeAttributeQuotes: false,
    caseSensitive: true,
    customAttrSurround: [
      [/#/, /(?:)/],
      [/\*/, /(?:)/],
      [/\[?\(?/, /(?:)/]
    ],
    customAttrAssign: [/\)?\]?=/]
  },

  /*
   * Options affecting the normal modules.
   *
   * See: http://webpack.github.io/docs/configuration.html#module
   */
  module: {

    noParse: [
      /lie.js/,
      path.resolve(appConfig.modulesPath, 'angular/angular.min.js')
    ],

    /*
     * An array of applied pre and post loaders.
     *
     * See: http://webpack.github.io/docs/configuration.html#module-preloaders-module-postloaders
     */
    preLoaders: [

      /*
       * Tslint loader support for *.ts files
       *
       * See: https://github.com/wbuchwalter/tslint-loader
       */
      {
        test: /\.ts$/,
        loader: 'tslint-loader',
        exclude: [
          /node_modules/,
          /\.(html|css|sass)$/
        ]
      },
      /*
       * Source map loader support for *.js files
       * Extracts SourceMaps for source files that as added as sourceMappingURL comment.
       *
       * See: https://github.com/webpack/source-map-loader
       */
      {
        test: /\.js$/,
        loader: 'source-map-loader'
      }
    ],

    /*
     * An array of automatically applied loaders.
     *
     * IMPORTANT: The loaders here are resolved relative to the resource which they are applied to.
     * This means they are not resolved relative to the configuration file.
     *
     * See: http://webpack.github.io/docs/configuration.html#module-loaders
     */
    loaders: [
      /*
       * Typescript loader support for .ts and Angular 2 async routes via .async.ts
       *
       * See: https://github.com/s-panferov/awesome-typescript-loader
       */
      // note that babel-loader is configured to run after ts-loader
      {
        test: /\.ts$/,
        loaders: ['awesome-typescript-loader', 'angular2-template-loader']
      },
      /*
       *  Babel- and ESLint-Loader
       */
      {
        test: /\.js$/,
        loaders: ['babel-loader', 'eslint-loader'],
        exclude: [/\.(spec|e2e)\.ts$/]
      },
      /*
       * Json loader support for *.json files.
       *
       * See: https://github.com/webpack/json-loader
       */
      {
        test: /\.json$/,
        loader: 'json-loader'
      }, {
        test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'file-loader?mimetype=image/svg+xml'
      }, {
        test: /\.png(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'file-loader?mimetype=image/png'
      }, {
        test: /\.jpeg(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'file-loader?mimetype=image/png'
      }, {
        test: /\.jpg(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'file-loader?mimetype=image/png'
      }, {
        test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'file-loader?mimetype=application/font-woff'
      }, {
        test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'file-loader?mimetype=application/font-woff'
      }, {
        test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'file-loader?mimetype=application/octet-stream'
      }, {
        test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'file-loader'
      },
      // https://github.com/jtangelder/sass-loader#usage
      {
        test: /\.scss$/,
        loaders: ["style", "css", "sass"]
      },
      /*
       * to string and css loader support for *.css files
       * Returns file content as string
       *
       */
      {
        test: /\.css$/,
        loaders: ['to-string-loader', 'css-loader']
      },
      /* Raw loader support for *.html
       * Returns file content as string
       *
       * See: https://github.com/webpack/raw-loader
       */
      {
        test: /\.html$/,
        loader: 'raw-loader'
      },
      {
        test: /\.xml/,
        loader: 'raw-loader'
      },
      /*
       * Exports Angular
       */
      {
        test: /[\/]angular.js$/,
        loader: "exports?angular"
      }
    ]

  },

  /*
   * Add additional plugins to the compiler.
   *
   * See: http://webpack.github.io/docs/configuration.html#plugins
   */
  plugins: [

    /**
     * Advanced typescript path resolution
     *
     * See: https://github.com/s-panferov/awesome-typescript-loader#advanced-path-resolution-in-typescript-20
     */
    new TsConfigPathsPlugin(),

    /*
     * Plugin: ForkCheckerPlugin
     * Description: Do type checking in a separate process, so webpack don't need to wait.
     *
     * See: https://github.com/s-panferov/awesome-typescript-loader#forkchecker-boolean-defaultfalse
     */
    new ForkCheckerPlugin(),

    /*
     * Plugin: OccurenceOrderPlugin
     * Description: Varies the distribution of the ids to get the smallest id length
     * for often used ids.
     *
     * See: https://webpack.github.io/docs/list-of-plugins.html#occurrenceorderplugin
     * See: https://github.com/webpack/docs/wiki/optimization#minimize
     */
    new webpack.optimize.OccurenceOrderPlugin(true),
    new webpack.ProvidePlugin(appConfig.globals || {
        PouchDB: "pouchdb",
        jquery: "jQuery",
        "windows.jQuery": "jquery"
      }),

    /*
     * Plugin: CopyWebpackPlugin
     * Description: Copy files and directories in webpack.
     *
     * Copies project static assets.
     *
     * See: https://www.npmjs.com/package/copy-webpack-plugin
     */
    new CopyWebpackPlugin([{
      from: path.join(appConfig.src, 'images'),
      to: path.join(appConfig.dist, 'images')
    }, {
      from: path.join(appConfig.src, 'views'),
      to: path.join(appConfig.dist, 'views')
    }, {
      from: path.join(appConfig.templates),
      to: path.join(appConfig.dist, appConfig.templates.replace(appConfig.src, ''))
    }, {
      context: path.join(appConfig.src),
      from: '*.*',
      to: path.join(appConfig.dist)
    }, {
      context: path.join(appConfig.gen),
      from: '*.*',
      to: path.join(appConfig.dist)
    }]),
    // annotate angular
    new NgAnnotatePlugin({
      add: true,
      single_quotes: true
    }),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
    }),
    new webpack.NoErrorsPlugin()

  ],

  /*
   * Include polyfills or mocks for various node stuff
   * Description: Node configuration
   *
   * See: https://webpack.github.io/docs/configuration.html#node
   */
  node: {
    global: 'window',
    crypto: 'empty',
    module: false,
    clearImmediate: false,
    setImmediate: false
  }
};

/*
 * Plugin: HtmlWebpackPlugin
 * Description: Simplifies creation of HTML files to serve your webpack bundles.
 * This is especially useful for webpack bundles that include a hash in the filename
 * which changes every compilation.
 *
 * See: https://github.com/ampedandwired/html-webpack-plugin
 */
for (var indexConfig of appConfig.indexFiles) {
  config.plugins.push(new HtmlWebpackPlugin(indexConfig));
}

// add additional settings here
if (appConfig.additionalWebpackOptions) {
  config = webpackMerge(config, appConfig.additionalWebpackOptions);
}
debugLog('Using following webpack common config:', config);
module.exports = config;
<commit_msg>feat(typescript): basic typescript support<commit_after>/**
 * @author: @mreinhardt
 */

const webpack = require('webpack');
const util = require('util');
const debugLog = util.debuglog('@holisticon/angularjs-common/webpack.common');
const path = require('path');
const helpers = require('./helpers');
const appConfig = helpers.getAppConfig();

debugLog('Using following appConfig:', appConfig);

/*
 * Webpack Plugins
 */
const NgAnnotatePlugin = require('ng-annotate-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const TsConfigPathsPlugin = require('awesome-typescript-loader').TsConfigPathsPlugin;
const ForkCheckerPlugin = require('awesome-typescript-loader').ForkCheckerPlugin;

/*
 * Webpack Constants
 */
const METADATA = {
  title: appConfig.title,
  baseUrl: '/',
  isDevServer: helpers.isWebpackDevServer()
};

/*
 * Webpack configuration
 *
 * See: http://webpack.github.io/docs/configuration.html#cli
 */
var config = {

  bail: true,

  /*
   * Static metadata for index.html
   *
   * See: (custom attribute)
   */
  metadata: METADATA,

  /*
   * The entry point for the bundle
   * Our Angular.js app
   *
   * See: http://webpack.github.io/docs/configuration.html#entry
   */
  entry: appConfig.entry,

  resolveLoader: {
    root: appConfig.modulesPath
  },
  /*
   * Options affecting the resolving of modules.
   *
   * See: http://webpack.github.io/docs/configuration.html#resolve
   */
  resolve: {

    /*
     * An array of extensions that should be used to resolve modules.
     *
     * See: http://webpack.github.io/docs/configuration.html#resolve-extensions
     */
    extensions: ['', '.ts', '.js', '.jsx', '.json'],

    // Make sure root is src
    root: appConfig.src,

    alias: {
      angular: path.resolve(appConfig.modulesPath, 'angular/angular.js')
    },

    packageMains: ['webpack', 'browser', 'web', 'browserify', ['jam', 'main'], 'main'],

    // remove other default values
    modulesDirectories: appConfig.modulesDirectories || [appConfig.modulesPath]

  },

  htmlLoader: {
    minimize: true,
    removeAttributeQuotes: false,
    caseSensitive: true,
    customAttrSurround: [
      [/#/, /(?:)/],
      [/\*/, /(?:)/],
      [/\[?\(?/, /(?:)/]
    ],
    customAttrAssign: [/\)?\]?=/]
  },

  /*
   * Options affecting the normal modules.
   *
   * See: http://webpack.github.io/docs/configuration.html#module
   */
  module: {

    noParse: [
      /lie.js/,
      path.resolve(appConfig.modulesPath, 'angular/angular.min.js')
    ],

    /*
     * An array of applied pre and post loaders.
     *
     * See: http://webpack.github.io/docs/configuration.html#module-preloaders-module-postloaders
     */
    preLoaders: [

      /*
       * Tslint loader support for *.ts files
       *
       * See: https://github.com/wbuchwalter/tslint-loader
       */
      {
        test: /\.ts$/,
        loader: 'tslint-loader',
        exclude: [
          /node_modules/,
          /\.(html|css|sass)$/
        ]
      },
      /*
       * Source map loader support for *.js files
       * Extracts SourceMaps for source files that as added as sourceMappingURL comment.
       *
       * See: https://github.com/webpack/source-map-loader
       */
      {
        test: /\.js$/,
        loader: 'source-map-loader'
      }
    ],

    /*
     * An array of automatically applied loaders.
     *
     * IMPORTANT: The loaders here are resolved relative to the resource which they are applied to.
     * This means they are not resolved relative to the configuration file.
     *
     * See: http://webpack.github.io/docs/configuration.html#module-loaders
     */
    loaders: [
      /*
       * Typescript loader support for .ts and Angular 2 async routes via .async.ts
       *
       * See: https://github.com/s-panferov/awesome-typescript-loader
       */
      // note that babel-loader is configured to run after ts-loader
      {
        test: /\.ts$/,
        loaders: ['awesome-typescript-loader', 'angular2-template-loader']
      },
      /*
       *  Babel- and ESLint-Loader
       */
      {
        test: /\.js$/,
        loaders: ['babel-loader', 'eslint-loader'],
        exclude: [/\.(spec|e2e)\.ts$/]
      },
      /*
       * Json loader support for *.json files.
       *
       * See: https://github.com/webpack/json-loader
       */
      {
        test: /\.json$/,
        loader: 'json-loader'
      }, {
        test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'file-loader?mimetype=image/svg+xml'
      }, {
        test: /\.png(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'file-loader?mimetype=image/png'
      }, {
        test: /\.jpeg(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'file-loader?mimetype=image/png'
      }, {
        test: /\.jpg(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'file-loader?mimetype=image/png'
      }, {
        test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'file-loader?mimetype=application/font-woff'
      }, {
        test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'file-loader?mimetype=application/font-woff'
      }, {
        test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'file-loader?mimetype=application/octet-stream'
      }, {
        test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'file-loader'
      },
      // https://github.com/jtangelder/sass-loader#usage
      {
        test: /\.scss$/,
        loaders: ["style", "css", "sass"]
      },
      /*
       * to string and css loader support for *.css files
       * Returns file content as string
       *
       */
      {
        test: /\.css$/,
        loaders: ['to-string-loader', 'css-loader']
      },
      /* Raw loader support for *.html
       * Returns file content as string
       *
       * See: https://github.com/webpack/raw-loader
       */
      {
        test: /\.html$/,
        loader: 'raw-loader'
      },
      {
        test: /\.xml/,
        loader: 'raw-loader'
      },
      /*
       * Exports Angular
       */
      {
        test: /[\/]angular.js$/,
        loader: "exports?angular"
      }
    ]

  },

  /*
   * Add additional plugins to the compiler.
   *
   * See: http://webpack.github.io/docs/configuration.html#plugins
   */
  plugins: [

    /**
     * Advanced typescript path resolution
     *
     * See: https://github.com/s-panferov/awesome-typescript-loader#advanced-path-resolution-in-typescript-20
     */
    new TsConfigPathsPlugin(),

    /*
     * Plugin: ForkCheckerPlugin
     * Description: Do type checking in a separate process, so webpack don't need to wait.
     *
     * See: https://github.com/s-panferov/awesome-typescript-loader#forkchecker-boolean-defaultfalse
     */
    new ForkCheckerPlugin(),

    /*
     * Plugin: OccurenceOrderPlugin
     * Description: Varies the distribution of the ids to get the smallest id length
     * for often used ids.
     *
     * See: https://webpack.github.io/docs/list-of-plugins.html#occurrenceorderplugin
     * See: https://github.com/webpack/docs/wiki/optimization#minimize
     */
    new webpack.optimize.OccurrenceOrderPlugin(true),
    new webpack.ProvidePlugin(appConfig.globals || {
        PouchDB: "pouchdb",
        jquery: "jQuery",
        "windows.jQuery": "jquery"
      }),

    /*
     * Plugin: CopyWebpackPlugin
     * Description: Copy files and directories in webpack.
     *
     * Copies project static assets.
     *
     * See: https://www.npmjs.com/package/copy-webpack-plugin
     */
    new CopyWebpackPlugin([{
      from: path.join(appConfig.src, 'images'),
      to: path.join(appConfig.dist, 'images')
    }, {
      from: path.join(appConfig.src, 'views'),
      to: path.join(appConfig.dist, 'views')
    }, {
      from: path.join(appConfig.templates),
      to: path.join(appConfig.dist, appConfig.templates.replace(appConfig.src, ''))
    }, {
      context: path.join(appConfig.src),
      from: '*.*',
      to: path.join(appConfig.dist)
    }, {
      context: path.join(appConfig.gen),
      from: '*.*',
      to: path.join(appConfig.dist)
    }]),
    // annotate angular
    new NgAnnotatePlugin({
      add: true,
      single_quotes: true
    }),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
    }),
    new webpack.NoErrorsPlugin()

  ],

  /*
   * Include polyfills or mocks for various node stuff
   * Description: Node configuration
   *
   * See: https://webpack.github.io/docs/configuration.html#node
   */
  node: {
    global: 'window',
    crypto: 'empty',
    module: false,
    clearImmediate: false,
    setImmediate: false
  }
};

/*
 * Plugin: HtmlWebpackPlugin
 * Description: Simplifies creation of HTML files to serve your webpack bundles.
 * This is especially useful for webpack bundles that include a hash in the filename
 * which changes every compilation.
 *
 * See: https://github.com/ampedandwired/html-webpack-plugin
 */
for (var indexConfig of appConfig.indexFiles) {
  config.plugins.push(new HtmlWebpackPlugin(indexConfig));
}

// add additional settings here
if (appConfig.additionalWebpackOptions) {
  config = webpackMerge(config, appConfig.additionalWebpackOptions);
}
debugLog('Using following webpack common config:', config);
module.exports = config;
<|endoftext|>


<commit_before>/**
 * Global DB server class.
 */
class DBServer {

    /**
     * Initialise with database options.
     */
    constructor() {
        this.server = null;
        this.options = {
            server: 'tei-viewer',
            version: 3,
            schema: {
                tei: {
                    key: {keyPath: 'id', autoIncrement: true}
                }
            }
        };
    }

    /**
     * Connect to the database.
     */
    connect() {
        var _this = this;
        return new Promise(function(resolve, reject) {
            db.open(_this.options).then(function(server) {
                _this.server = server;
                resolve();
            }).catch(function (err) {
                if (err.type === 'blocked') {
                    oldConnection.close();
                    return err.resume;
                }
                reject(err);
            });
        });
    }

    /**
     * Add a record, ensuring that a connection is established first.
     */
    add(data) {
        var _this = this;

        function addRecord(data) {
            return new Promise(function(resolve, reject) {
                _this.server.tei.add(data).then(function() {
                    resolve();
                }).catch(function (err) {
                    reject(err);
                });
            });
        }

        return new Promise(function(resolve, reject) {
            if (_this.server === null) {
                _this.connect().then(function() {
                    resolve(addRecord(data));
                }).catch(function (err) {
                    reject(err);
                });
            } else {
                resolve(addRecord(data));
            }
        });
    }

    /**
     * Return a record, ensuring that a connection is established first.
     */
    get(id) {
        var _this = this;

        function getRecord(id) {
            return new Promise(function(resolve, reject) {
                _this.server.tei.get(id).then(function(record) {
                    if (typeof record === 'undefined') {
                        reject(new Error('Record not found'));
                    }
                    resolve(record);
                }).catch(function (err) {
                    reject(err);
                });
            });
        }

        return new Promise(function(resolve, reject) {
            if (_this.server === null) {
                _this.connect().then(function() {
                    resolve(getRecord(id));
                }).catch(function (err) {
                    reject(err);
                });
            } else {
                resolve(getRecord(id));
            }
        });
    }

    /**
     * Update a record, ensuring that a connection is established first.
     */
    update(record) {
        var _this = this;

        function updateRecord(record) {
            return new Promise(function(resolve, reject) {
                _this.server.tei.update(record).then(function() {
                    resolve(record);
                }).catch(function (err) {
                    reject(err);
                });
            });
        }

        return new Promise(function(resolve, reject) {
            if (_this.server === null) {
                _this.connect().then(function() {
                    resolve(updateRecord(record));
                }).catch(function (err) {
                    reject(err);
                });
            } else {
                resolve(updateRecord(record));
            }
        });
    }

    /**
     * Return multiple records, ensuring that a connection is established first.
     */
    getAll() {
        var _this = this;

        function getAllRecords(fromRecord, toRecord) {
            return new Promise(function(resolve, reject) {
                _this.server.tei.query()
                                .all()
                                .execute()
                                .then(function(records) {
                                    resolve(records);
                }).catch(function (err) {
                    reject(err);
                });
            });
        }

        return new Promise(function(resolve, reject) {
            if (_this.server === null) {
                _this.connect().then(function() {
                    resolve(getAllRecords());
                }).catch(function (err) {
                    reject(err);
                });
            } else {
                resolve(getAllRecords());
            }
        });
    }

    /**
     * Count records, ensuring that a connection is established first.
     */
    count() {
        var _this = this;

        function countRecords() {
            return new Promise(function(resolve, reject) {
                _this.server.tei.count().then(function (n) {
                    resolve(n);
                }).catch(function (err) {
                    reject(err);
                });
            });
        }

        return new Promise(function(resolve, reject) {
            if (_this.server === null) {
                _this.connect().then(function() {
                    resolve(countRecords());
                }).catch(function (err) {
                    reject(err);
                });
            } else {
                resolve(countRecords());
            }
        });
    }

    /**
     * Clear all records, ensuring that a connection is established first.
     */
    clearAll() {
        var _this = this;

        function clearAllRecords() {
            return new Promise(function(resolve, reject) {
                _this.server.tei.clear().then(function () {
                    resolve();
                }).catch(function (err) {
                    reject(err);
                });
            });
        }

        return new Promise(function(resolve, reject) {
            if (_this.server === null) {
                _this.connect().then(function() {
                    resolve(clearAllRecords());
                }).catch(function (err) {
                    reject(err);
                });
            } else {
                resolve(clearAllRecords());
            }
        });
    }

    /**
     * Remove a record, ensuring that a connection is established first.
     */
    remove(id) {
        var _this = this;

        function removeRecord(id) {
            return new Promise(function(resolve, reject) {
                _this.server.tei.remove(id).then(function(record) {
                    if (typeof record === 'undefined') {
                        reject(new Error('Record not found'));
                    }
                    resolve(record);
                }).catch(function (err) {
                    reject(err);
                });
            });
        }

        return new Promise(function(resolve, reject) {
            if (_this.server === null) {
                _this.connect().then(function() {
                    resolve(removeRecord(id));
                }).catch(function (err) {
                    reject(err);
                });
            } else {
                resolve(removeRecord(id));
            }
        });
    }

}

export default window.dbServer = new DBServer();<commit_msg>Refactor db-server.js<commit_after>/**
 * Database server class.
 */
class DBServer {

    /**
     * Initialise with database options.
     */
    constructor() {
        this.server = null;
        this.options = {
            server: 'tei-viewer',
            version: 3,
            schema: {
                tei: {
                    key: {keyPath: 'id', autoIncrement: true}
                }
            }
        };
    }

    /**
     * Connect to the database.
     */
    connect() {
        var _this = this;
        return new Promise(function(resolve, reject) {
            if (_this.server !== null) {
                resolve();
            }
            db.open(_this.options).then(function(server) {
                _this.server = server;
                resolve();
            }).catch(function (err) {
                if (err.type === 'blocked') {
                    oldConnection.close();
                    return err.resume;
                }
                reject(err);
            });
        });
    }

    /**
     * Add a record.
     */
    add(data) {
        var _this = this;
        return new Promise(function(resolve, reject) {
            _this.connect().then(function() {
                return _this.server.tei.add(data);
            }).then(function() {
                resolve();
            }).catch(function (err) {
                reject(err);
            });
        });
    }

    /**
     * Return a record.
     */
    get(id) {
        var _this = this;
        return new Promise(function(resolve, reject) {
            _this.connect().then(function() {
                return _this.server.tei.get(id);
            }).then(function(record) {
                if (typeof record === 'undefined') {
                    reject(new Error('Record not found'));
                }
                resolve(record);
            }).catch(function (err) {
                reject(err);
            });
        });
    }

    /**
     * Update a record.
     */
    update(record) {
        var _this = this;
        return new Promise(function(resolve, reject) {
            _this.connect().then(function() {
                return _this.server.tei.update(record);
            }).then(function(record) {
                resolve(record);
            }).catch(function (err) {
                reject(err);
            });
        });
    }

    /**
     * Return all records.
     */
    getAll() {
        var _this = this;
        return new Promise(function(resolve, reject) {
            _this.connect().then(function() {
                return _this.server.tei.query().all().execute();
            }).then(function(records) {
                resolve(records);
            }).catch(function (err) {
                reject(err);
            });
        });
    }

    /**
     * Remove a record.
     */
    remove(id) {
        var _this = this;
        return new Promise(function(resolve, reject) {
            _this.connect().then(function() {
                return _this.server.tei.remove(id);
            }).then(function(record) {
                if (typeof record === 'undefined') {
                    reject(new Error('Record not found'));
                }
                resolve(record);
            }).catch(function (err) {
                reject(err);
            });
        });
    }

}

export default window.dbServer = new DBServer();<|endoftext|>


<commit_before>/**
 * Takes care of logs management.
 *  Checks current state of log processing.
 *  Sets watcher on log files.
 *  Processes new logs.
 */
const fs = require('fs');
const tail = require('./tail');
const fileParser = require('./parser').parseFile;
const info = require('./log-info');
const logger = require('../logger');
const validateLine = require('../tools').validateLogLine;

let infoFile = {
    data: []
};

function readFiles(dirName) {
    infoFile = info.getInfo();
    fs.readdir(dirName, (err, fileNames) => {
        if (err) {
            onError(err);
            return;
        }
        logger.verbose("Log files present: " + fileNames.length);

        fileNames.forEach(function(filename) {
            logger.debug(dirName + '/' + filename);
            if (!process.env.ACCESS_LOG_ONLY || filename === 'access.log') {
                if (checkContent(dirName + '/' + filename)) onFileContent(dirName + '/' + filename);
                /*fs.readFile(dirName + '/' + filename, 'utf-8', (err, content) => {
                    if (err) {
                        onError(err);
                        return;
                    }
                    onFileContent(dirName + '/' + filename, content);
                });*/
            }
        });
    });
}

function onError(error) {
    // handle specific listen errors with friendly messages
    logger.error(error);
}

function checkContent(filename) {
    const fd = fs.openSync(filename, 'r');
    const bufferSize = 1024;
    let buffer = new Buffer(bufferSize);

    let read, line, idx;
    read = fs.readSync(fd, buffer, 0, bufferSize, null);
    line = buffer.toString('utf8', 0, read);
    while ((idx = line.indexOf("\n",0)) === -1 ) {
        read = fs.readSync(fd, buffer, 0, bufferSize, null);
        line += buffer.toString('utf8', 0, read);
    }
    line = line.substring(0, idx);
    validateLine(line);
}

function onFileContent(filePath) {
    const filename = filePath.substr(filePath.lastIndexOf('/') + 1);
    let alreadyRead = 0;
    infoFile.data.forEach(function (item) {
        if (item.name === filename) alreadyRead = item.bytesRead;
    });
    // the size of the file in bytes
    const size = fs.statSync(filePath)["size"];
    if (alreadyRead < size) {
        fileParser(filePath, alreadyRead)
            .catch(error => {
                logger.error(error);
            });
        infoFile.data.push({name: filename, bytesRead: size});
        info.setInfo(infoFile);
    } else {
        logger.verbose('File', filename, 'is up to date');
    }
    tail.tailFile(filePath, fs.statSync(filePath)["size"] - size, size, true, (err, filename, data, unsubscribe) => {
        if (err) {
            logger.error(err);
        }});
}

module.exports = readFiles;<commit_msg>file reading hotfix<commit_after>/**
 * Takes care of logs management.
 *  Checks current state of log processing.
 *  Sets watcher on log files.
 *  Processes new logs.
 */
const fs = require('fs');
const tail = require('./tail');
const fileParser = require('./parser').parseFile;
const info = require('./log-info');
const logger = require('../logger');
const validateLine = require('../tools').validateLogLine;

let infoFile = {
    data: []
};

function readFiles(dirName) {
    infoFile = info.getInfo();
    fs.readdir(dirName, (err, fileNames) => {
        if (err) {
            onError(err);
            return;
        }
        logger.verbose("Log files present: " + fileNames.length);

        fileNames.forEach(function(filename) {
            logger.debug(dirName + '/' + filename);
            if (!process.env.ACCESS_LOG_ONLY || filename === 'access.log') {
                /*if (checkContent(dirName + '/' + filename))*/ onFileContent(dirName + '/' + filename);
                /*fs.readFile(dirName + '/' + filename, 'utf-8', (err, content) => {
                    if (err) {
                        onError(err);
                        return;
                    }
                    onFileContent(dirName + '/' + filename, content);
                });*/
            }
        });
    });
}

function onError(error) {
    // handle specific listen errors with friendly messages
    logger.error(error);
}

function checkContent(filename) {
    const fd = fs.openSync(filename, 'r');
    const bufferSize = 1024;
    let buffer = new Buffer(bufferSize);

    let read, line, idx;
    read = fs.readSync(fd, buffer, 0, bufferSize, null);
    line = buffer.toString('utf8', 0, read);
    while ((idx = line.indexOf("\n",0)) === -1 ) {
        read = fs.readSync(fd, buffer, 0, bufferSize, null);
        line += buffer.toString('utf8', 0, read);
    }
    line = line.substring(0, idx);
    validateLine(line);
}

function onFileContent(filePath) {
    const filename = filePath.substr(filePath.lastIndexOf('/') + 1);
    let alreadyRead = 0;
    infoFile.data.forEach(function (item) {
        if (item.name === filename) alreadyRead = item.bytesRead;
    });
    // the size of the file in bytes
    const size = fs.statSync(filePath)["size"];
    if (alreadyRead < size) {
        fileParser(filePath, alreadyRead)
            .catch(error => {
                logger.error(error);
            });
        infoFile.data.push({name: filename, bytesRead: size});
        info.setInfo(infoFile);
    } else {
        logger.verbose('File', filename, 'is up to date');
    }
    tail.tailFile(filePath, fs.statSync(filePath)["size"] - size, size, true, (err, filename, data, unsubscribe) => {
        if (err) {
            logger.error(err);
        }});
}

module.exports = readFiles;<|endoftext|>


<commit_before>import React from 'react';
import { render } from 'react-dom';
import endpoint from './endpoint';
import Logo from './react-components/logo.jsx';
import Footer from './react-components/footer.jsx';
import { oauthLogin } from '../common/appId';
import { isEuCountry, showHideEuElements } from '../common/footer-checks';
import GTM from '../common/gtm';
import { load as loadLang, showBanner } from '../common/lang';
import { moveToDeriv } from '../common/utils/utility';
import { get as getStorage, set as setStorage, remove, getTokenList } from '../common/utils/storageManager';
import { createUrl } from '../common/utils/tools';
import '../common/binary-ui/dropdown';
import BotLanding from './react-components/bot-landing';
import ModalComponent from './react-components/bot-landing/ModalComponent.jsx';

const today = new Date().getTime();
// eslint-disable-next-line one-var
const twentyOneDays = 21,
    fiveMinutes = 300,
    oneMilliSec = 1000,
    oneMinute = 60,
    oneDay = 24;

const elementsPopup = ['.bot-landing-alert-draggable-dialog', '#bot-landing-alert-popup'];
const elements = ['#notification-banner', '#main', '#footer', '#header', '#topbar'];
// eslint-disable-next-line one-var
export const bannerToken = getStorage('setDueDateForBanner');
export const popupToken = getStorage('setPopupToken');

// eslint-disable-next-line arrow-body-style
export const expirationDate = () => {
    return today + oneMilliSec * oneMinute * oneMinute * oneDay * twentyOneDays;
};
// eslint-disable-next-line arrow-body-style
export const setPopupToken = () => {
    return expirationDate() - fiveMinutes;
};
export const calcSetTimeoutValue = setPopupToken() - new Date().getTime();
export const calcSetTimeoutValueBanner = expirationDate() - new Date().getTime();

// eslint-disable-next-line import/prefer-default-export
export const renderPopup = type => {
    render(<ModalComponent />, document.getElementById('bot-landing-alert-popup'));
    // eslint-disable-next-line no-unused-vars
    // eslint-disable-next-line array-callback-return
    elementsPopup.map(elem => {
        if (type === 'open') {
            document.querySelector(elem).classList.add('open');
        } else {
            document.querySelector(elem).classList.remove('open');
        }
    });
};

const checkifBotRunning = () => {
    if (document.getElementById('runButton').style.display === 'none') {
        return true;
    }
    return false;
};

export const setTimeOutBanner = route => {
    let bannerDisplayed;
    if (route === 'index') {
        bannerDisplayed = document.getElementById('bot-landing').classList.contains('hidden');
    }

    // eslint-disable-next-line consistent-return
    setTimeout(() => {
        if ((route === 'index' && !bannerDisplayed) || (route === 'views' && checkifBotRunning())) {
            const getqueryParameter = document.location.search;
            const getDefaultPath = window.location.href.replace('/bot.html', getqueryParameter);
            window.location.replace(getDefaultPath);
            renderBanner();
        } else if ((route === 'index' && bannerDisplayed) || (route === 'views' && checkifBotRunning())) {
            remove('setDueDateForBanner');
            setStorage('setDueDateForBanner', setPopupToken());
            return false;
        }
    }, calcSetTimeoutValueBanner);
};

export const setTimeOutPopup = route => {
    let bannerDisplayed;
    if (route === 'index') {
        bannerDisplayed = document.getElementById('bot-landing').classList.contains('hidden');
    }
    // render popup 5min before user see the page in 3 weeks
    // eslint-disable-next-line consistent-return
    setTimeout(() => {
        if ((route === 'index' && !bannerDisplayed) || (route === 'views' && checkifBotRunning())) {
            renderPopup('open');
        } else if ((route === 'index' && bannerDisplayed) || (route === 'views' && checkifBotRunning())) {
            remove('setPopupToken');
            setStorage('setPopupToken', setPopupToken());
            return false;
        }
    }, calcSetTimeoutValue);
};

const renderBanner = () => {
    render(<ModalComponent />, document.getElementById('bot-landing-alert-popup'));
    render(<BotLanding />, document.getElementById('bot-landing'));
    setStorage('setDueDateForBanner', expirationDate());
    setStorage('setPopupToken', setPopupToken());
    elements.map(elem => document.querySelector(elem).classList.add('hidden'));
    document.getElementById('bot-landing').classList.remove('hidden');
    document.getElementById('bot-main').classList.remove('hidden');
    $('.barspinner').hide();
};

// eslint-disable-next-line consistent-return
const renderElements = () => {
    setTimeOutPopup('index');
    setTimeOutBanner('index');
    $('.barspinner').show();

        if (!bannerToken) {
            if (window.location.href.indexOf('bot.html') === -1) {
            renderBanner();
        }
    }
     else {
        if (today > bannerToken) {
            remove('setDueDateForBanner');
            renderBanner();
            return false;
        }
            if (window.location.href.indexOf('bot.html') === -1) {
        render(<Logo />, document.getElementById('binary-logo'));
        render(<Footer />, document.getElementById('footer'));
        isEuCountry().then(isEu => showHideEuElements(isEu));
        showBanner();
        $('#shop-url').attr(
            'href',
            createUrl({ subdomain: 'shop', path: 'collections/strategies', isNonBotPage: true })
        );
        elements.map(elem => document.querySelector(elem).classList.remove('hidden'));
        document.getElementById('bot-landing').classList.add('hidden');
            }
        document.getElementById('bot-main').classList.remove('hidden');
        $('.barspinner').hide();
    }
};

const loginCheck = () => {
    if (endpoint()) return;
    moveToDeriv();
    loadLang();
    if (bannerToken) {
        if (getTokenList().length) {
            if (!window.location.pathname.includes('/bot.html')) {
                window.location.pathname = `${window.location.pathname.replace(/\/+$/, '')}/bot.html`;
            }
            document.getElementById('bot-main').classList.remove('hidden');
        } else {
            oauthLogin(() => {
                $('.show-on-load').show();
                $('.barspinner').hide();
                renderElements();
                GTM.init();
            });
        }
    } else {
        setTimeout(() => {
            renderBanner();
        }, 2000);
    }
};

loginCheck();
<commit_msg>minor changes<commit_after>import React from 'react';
import { render } from 'react-dom';
import endpoint from './endpoint';
import Logo from './react-components/logo.jsx';
import Footer from './react-components/footer.jsx';
import { oauthLogin } from '../common/appId';
import { isEuCountry, showHideEuElements } from '../common/footer-checks';
import GTM from '../common/gtm';
import { load as loadLang, showBanner } from '../common/lang';
import { moveToDeriv } from '../common/utils/utility';
import { get as getStorage, set as setStorage, remove, getTokenList } from '../common/utils/storageManager';
import { createUrl } from '../common/utils/tools';
import '../common/binary-ui/dropdown';
import BotLanding from './react-components/bot-landing';
import ModalComponent from './react-components/bot-landing/ModalComponent.jsx';

const today = new Date().getTime();
// eslint-disable-next-line one-var
const twentyOneDays = 21,
    fiveMinutes = 300,
    oneMilliSec = 1000,
    oneMinute = 60,
    oneDay = 24;

const elementsPopup = ['.bot-landing-alert-draggable-dialog', '#bot-landing-alert-popup'];
const elements = ['#notification-banner', '#main', '#footer', '#header', '#topbar'];
// eslint-disable-next-line one-var
export const bannerToken = getStorage('setDueDateForBanner');
export const popupToken = getStorage('setPopupToken');

// eslint-disable-next-line arrow-body-style
export const expirationDate = () => {
    return today + oneMilliSec * oneMinute * oneMinute * oneDay * twentyOneDays;
};
// eslint-disable-next-line arrow-body-style
export const setPopupToken = () => {
    return expirationDate() - fiveMinutes;
};
export const calcSetTimeoutValue = setPopupToken() - new Date().getTime();
export const calcSetTimeoutValueBanner = expirationDate() - new Date().getTime();

// eslint-disable-next-line import/prefer-default-export
export const renderPopup = type => {
    render(<ModalComponent />, document.getElementById('bot-landing-alert-popup'));
    // eslint-disable-next-line no-unused-vars
    // eslint-disable-next-line array-callback-return
    elementsPopup.map(elem => {
        if (type === 'open') {
            document.querySelector(elem).classList.add('open');
        } else {
            document.querySelector(elem).classList.remove('open');
        }
    });
};

const checkifBotRunning = () => {
    if (document.getElementById('runButton').style.display === 'none') {
        return true;
    }
    return false;
};

export const setTimeOutBanner = route => {
    let bannerDisplayed;
    if (route === 'index') {
        bannerDisplayed = document.getElementById('bot-landing').classList.contains('hidden');
    }

    // eslint-disable-next-line consistent-return
    setTimeout(() => {
        if ((route === 'index' && !bannerDisplayed) || (route === 'views' && checkifBotRunning())) {
            const getqueryParameter = document.location.search;
            const getDefaultPath = window.location.href.replace('/bot.html', getqueryParameter);
            window.location.replace(getDefaultPath);
            renderBanner();
        } else if ((route === 'index' && bannerDisplayed) || (route === 'views' && checkifBotRunning())) {
            remove('setDueDateForBanner');
            setStorage('setDueDateForBanner', setPopupToken());
            return false;
        }
    }, calcSetTimeoutValueBanner);
};

export const setTimeOutPopup = route => {
    let bannerDisplayed;
    if (route === 'index') {
        bannerDisplayed = document.getElementById('bot-landing').classList.contains('hidden');
    }
    // render popup 5min before user see the page in 3 weeks
    // eslint-disable-next-line consistent-return
    setTimeout(() => {
        if ((route === 'index' && !bannerDisplayed) || (route === 'views' && checkifBotRunning())) {
            renderPopup('open');
        } else if ((route === 'index' && bannerDisplayed) || (route === 'views' && checkifBotRunning())) {
            remove('setPopupToken');
            setStorage('setPopupToken', setPopupToken());
            return false;
        }
    }, calcSetTimeoutValue);
};

const renderBanner = () => {
    render(<ModalComponent />, document.getElementById('bot-landing-alert-popup'));
    render(<BotLanding />, document.getElementById('bot-landing'));
    setStorage('setDueDateForBanner', expirationDate());
    setStorage('setPopupToken', setPopupToken());
    elements.map(elem => document.querySelector(elem).classList.add('hidden'));
    document.getElementById('bot-landing').classList.remove('hidden');
    document.getElementById('bot-main').classList.remove('hidden');
    $('.barspinner').hide();
};

// eslint-disable-next-line consistent-return
const renderElements = () => {
    setTimeOutPopup('index');
    setTimeOutBanner('index');
    $('.barspinner').show();

    if (!bannerToken) {
        if (window.location.href.indexOf('bot.html') === -1) {
            renderBanner();
        }
    }
    else {
        if (today > bannerToken) {
            remove('setDueDateForBanner');
            renderBanner();
            return false;
        }
        if (window.location.href.indexOf('bot.html') === -1) {
            render(<Logo />, document.getElementById('binary-logo'));
            render(<Footer />, document.getElementById('footer'));
            isEuCountry().then(isEu => showHideEuElements(isEu));
            showBanner();
            $('#shop-url').attr(
                'href',
                createUrl({ subdomain: 'shop', path: 'collections/strategies', isNonBotPage: true })
            );
            elements.map(elem => document.querySelector(elem).classList.remove('hidden'));
            document.getElementById('bot-landing').classList.add('hidden');
        }
        document.getElementById('bot-main').classList.remove('hidden');
        $('.barspinner').hide();
    }
};

const loginCheck = () => {
    if (endpoint()) return;
    moveToDeriv();
    loadLang();
    if (bannerToken) {
        if (getTokenList().length) {
            if (!window.location.pathname.includes('/bot.html')) {
                window.location.pathname = `${window.location.pathname.replace(/\/+$/, '')}/bot.html`;
            }
            document.getElementById('bot-main').classList.remove('hidden');
        } else {
            oauthLogin(() => {
                $('.show-on-load').show();
                $('.barspinner').hide();
                renderElements();
                GTM.init();
            });
        }
    } else {
        setTimeout(() => {
            renderBanner();
        }, 2000);
    }
};

loginCheck();
<|endoftext|>


<commit_before>define( [
            'dojo/_base/declare',
            'dojo/_base/array',
            'dojo/_base/Color',
            'dojo/on',
            'JBrowse/View/Track/WiggleBase',
            'JBrowse/View/Track/_YScaleMixin',
            'JBrowse/Util',
            './_Scale'
        ],
        function( declare, array, Color, on, WiggleBase, YScaleMixin, Util, Scale ) {

var XYPlot = declare( [WiggleBase, YScaleMixin],

/**
 * Wiggle track that shows data with an X-Y plot along the reference.
 *
 * @lends JBrowse.View.Track.Wiggle.XYPlot
 * @extends JBrowse.View.Track.WiggleBase
 */
{
    _defaultConfig: function() {
        return Util.deepUpdate(
            dojo.clone( this.inherited(arguments) ),
            {
                style: {
                    pos_color: 'blue',
                    neg_color: 'red',
                    origin_color: '#888',
                    variance_band_color: 'rgba(0,0,0,0.3)'
                }
            }
        );
    },

    _getScaling: function( viewArgs, successCallback, errorCallback ) {

        this._getScalingStats( viewArgs, dojo.hitch(this, function( stats ) {

            //calculate the scaling if necessary
            if( ! this.lastScaling || ! this.lastScaling.sameStats( stats ) ) {

                var scaling = new Scale( this.config, stats );

                // bump minDisplayed to 0 if it is within 0.5% of it
                if( Math.abs( scaling.min / scaling.max ) < 0.005 )
                    scaling.min = 0;

                // update our track y-scale to reflect it
                this.makeYScale({
                    fixBounds: true,
                    min: scaling.min,
                    max: scaling.max
                });

                // and finally adjust the scaling to match the ruler's scale rounding
                scaling.min = this.ruler.scaler.bounds.lower;
                scaling.max = this.ruler.scaler.bounds.upper;
                scaling.range = scaling.max - scaling.min;

                this.lastScaling = scaling;
            }

            successCallback( this.lastScaling );
        }), errorCallback );
    },

    updateStaticElements: function( coords ) {
        this.inherited( arguments );
        this.updateYScaleFromViewDimensions( coords );
    },

    /**
     * Draw a set of features on the canvas.
     * @private
     */
    _drawFeatures: function( scale, leftBase, rightBase, block, canvas, pixels, dataScale ) {
        var context = canvas.getContext('2d');
        var canvasHeight = canvas.height;
        var toY = dojo.hitch( this, function( val ) {
           return canvasHeight * ( 1-dataScale.normalize(val) );
        });
        var originY = toY( dataScale.origin );

        var disableClipMarkers = this.config.disable_clip_markers;

        dojo.forEach( pixels, function(p,i) {
            if (!p)
                return;
            var score = toY(p['score']);
            var f = p['feat'];

            // draw the background color if we are configured to do so
            if( score >= 0 ) {
                var bgColor = this.getConfForFeature('style.bg_color', f );
                if( bgColor ) {
                    context.fillStyle = bgColor;
                    context.fillRect( i, 0, 1, canvasHeight );
                }
            }

            if( score <= canvasHeight || score > originY) { // if the rectangle is visible at all
                if( score <= originY ) {
                    // bar goes upward
                    context.fillStyle = this.getConfForFeature('style.pos_color',f);
                    context.fillRect( i, score, 1, originY-score+1);
                    if( !disableClipMarkers && score < 0 ) { // draw clip marker if necessary
                        context.fillStyle = this.getConfForFeature('style.clip_marker_color',f) || this.getConfForFeature('style.neg_color',f);
                        context.fillRect( i, 0, 1, 3 );

                    }
                }
                else {
                    // bar goes downward
                    context.fillStyle = this.getConfForFeature('style.neg_color',f);
                    context.fillRect( i, originY, 1, score-originY+1 );
                    if( !disableClipMarkers && score >= canvasHeight ) { // draw clip marker if necessary
                        context.fillStyle = this.getConfForFeature('style.clip_marker_color',f) || this.getConfForFeature('style.pos_color',f);
                        context.fillRect( i, canvasHeight-3, 1, 3 );

                    }
                }
            }
        }, this );
    },

    _calculatePixelScores: function( canvasWidth, features, featureRects ) {
        /* A variant of calculatePixelScores that stores the feature used at each pixel.
         * If there are multiple features, use the first one */
        var pixelValues = new Array( canvasWidth );
        dojo.forEach( features, function( f, i ) {
            var store = f.source;
            var fRect = featureRects[i];
            var jEnd = fRect.r;
            var score = f.get('score');
            for( var j = Math.round(fRect.l); j < jEnd; j++ ) {
                if ( pixelValues[j] && pixelValues[j]['lastUsedStore'] == store ) {
                    /* Note: if the feature is from a different store, the condition should fail,
                     *       and we will add to the value, rather than adjusting for overlap */
                    pixelValues[j]['score'] = Math.max( pixelValues[j]['score'], score );
                }
                else if ( pixelValues[j] ) {
                    pixelValues[j]['score'] = pixelValues[j]['score'] + score;
                    pixelValues[j]['lastUsedStore'] = store;
                }
                else {
                    pixelValues[j] = { score: score, lastUsedStore: store, feat: f };
                }
            }
        },this);
        // when done looping through features, forget the store information.
        for (var i=0; i<pixelValues.length; i++) {
            if ( pixelValues[i] ) {
                pixelValues[i] = { score: pixelValues[i]['score'], feat: pixelValues[i]['feat'] };
            }
        }
        return pixelValues;
    },

    /* If it's a boolean track, mask accordingly */
    _maskBySpans: function( scale, leftBase, rightBase, block, canvas, pixels, dataScale, spans ) {
        var context = canvas.getContext('2d');
        var canvasHeight = canvas.height;

        for ( var index in spans ) {
            if (spans.hasOwnProperty(index)) {
                var w = Math.ceil(( spans[index].end   - spans[index].start ) * scale );
                var l = Math.round(( spans[index].start - leftBase ) * scale );
                context.clearRect( l, 0, w, canvasHeight );
            }
        }
        context.globalAlpha = this.config.style.masked_transparancy || 0.2;
        this.config.style.masked_transparancy = context.globalAlpha;
        this._drawFeatures( scale, leftBase, rightBase, block, canvas, pixels, dataScale );
    },

    /**
     * Draw anything needed after the features are drawn.
     */
    _postDraw: function( scale, leftBase, rightBase, block, canvas, features, featureRects, dataScale ) {
        var context = canvas.getContext('2d');
        var canvasHeight = canvas.height;
        var toY = dojo.hitch( this, function( val ) {
           return canvasHeight * (1-dataScale.normalize(val));
        });

        // draw the variance_band if requested
        if( this.config.variance_band ) {
            var bandPositions =
                typeof this.config.variance_band == 'object'
                    ? array.map( this.config.variance_band, function(v) { return parseFloat(v); } ).sort().reverse()
                    : [ 2, 1 ];
            this.getGlobalStats( dojo.hitch( this, function( stats ) {
                if( ('scoreMean' in stats) && ('scoreStdDev' in stats) ) {
                    var drawVarianceBand = function( plusminus, fill, label ) {
                        context.fillStyle = fill;
                        var varTop = toY( stats.scoreMean + plusminus );
                        var varHeight = toY( stats.scoreMean - plusminus ) - varTop;
                        varHeight = Math.max( 1, varHeight );
                        context.fillRect( 0, varTop, canvas.width, varHeight );
                        context.font = '12px sans-serif';
                        if( plusminus > 0 ) {
                            context.fillText( '+'+label, 2, varTop );
                            context.fillText( '-'+label, 2, varTop+varHeight );
                        }
                        else {
                            context.fillText( label, 2, varTop );
                        }
                    };

                    var maxColor = new Color( this.config.style.variance_band_color );
                    var minColor = new Color( this.config.style.variance_band_color );
                    minColor.a /= bandPositions.length;

                    var bandOpacityStep = 1/bandPositions.length;
                    var minOpacity = bandOpacityStep;

                    array.forEach( bandPositions, function( pos,i ) {
                        drawVarianceBand( pos*stats.scoreStdDev,
                                          Color.blendColors( minColor, maxColor, (i+1)/bandPositions.length).toCss(true),
                                          pos+'σ');
                    });
                    drawVarianceBand( 0, 'rgba(255,255,0,0.7)', 'mean' );
                }
            }));
        }

        // draw the origin line if it is not disabled
        var originColor = this.config.style.origin_color;
        if( typeof originColor == 'string' && !{'none':1,'off':1,'no':1,'zero':1}[originColor] ) {
            var originY = toY( dataScale.origin );
            context.fillStyle = originColor;
            context.fillRect( 0, originY, canvas.width, 1 );
        }

    }

});

return XYPlot;
});
<commit_msg>Commit 2/3 - Fix height rendering on the highdpi canvas by making y-coordinates relative to the pixel ratio<commit_after>define( [
            'dojo/_base/declare',
            'dojo/_base/array',
            'dojo/_base/Color',
            'dojo/on',
            'JBrowse/View/Track/WiggleBase',
            'JBrowse/View/Track/_YScaleMixin',
            'JBrowse/Util',
            './_Scale'
        ],
        function( declare, array, Color, on, WiggleBase, YScaleMixin, Util, Scale ) {

var XYPlot = declare( [WiggleBase, YScaleMixin],

/**
 * Wiggle track that shows data with an X-Y plot along the reference.
 *
 * @lends JBrowse.View.Track.Wiggle.XYPlot
 * @extends JBrowse.View.Track.WiggleBase
 */
{
    _defaultConfig: function() {
        return Util.deepUpdate(
            dojo.clone( this.inherited(arguments) ),
            {
                style: {
                    pos_color: 'blue',
                    neg_color: 'red',
                    origin_color: '#888',
                    variance_band_color: 'rgba(0,0,0,0.3)'
                }
            }
        );
    },

    _getScaling: function( viewArgs, successCallback, errorCallback ) {

        this._getScalingStats( viewArgs, dojo.hitch(this, function( stats ) {

            //calculate the scaling if necessary
            if( ! this.lastScaling || ! this.lastScaling.sameStats( stats ) ) {

                var scaling = new Scale( this.config, stats );

                // bump minDisplayed to 0 if it is within 0.5% of it
                if( Math.abs( scaling.min / scaling.max ) < 0.005 )
                    scaling.min = 0;

                // update our track y-scale to reflect it
                this.makeYScale({
                    fixBounds: true,
                    min: scaling.min,
                    max: scaling.max
                });

                // and finally adjust the scaling to match the ruler's scale rounding
                scaling.min = this.ruler.scaler.bounds.lower;
                scaling.max = this.ruler.scaler.bounds.upper;
                scaling.range = scaling.max - scaling.min;

                this.lastScaling = scaling;
            }

            successCallback( this.lastScaling );
        }), errorCallback );
    },

    updateStaticElements: function( coords ) {
        this.inherited( arguments );
        this.updateYScaleFromViewDimensions( coords );
    },

    /**
     * Draw a set of features on the canvas.
     * @private
     */
    _drawFeatures: function( scale, leftBase, rightBase, block, canvas, pixels, dataScale ) {
        var context = canvas.getContext('2d');
        var canvasHeight = canvas.height;
        var devicePixelRatio = window.devicePixelRatio || 1;
        var backingStoreRatio = context.webkitBackingStorePixelRatio ||
                                                context.mozBackingStorePixelRatio ||
                                                context.msBackingStorePixelRatio ||
                                                context.oBackingStorePixelRatio ||
                                                context.backingStorePixelRatio || 1;

        var ratio = devicePixelRatio / backingStoreRatio;
        var toY = dojo.hitch( this, function( val ) {
           return canvasHeight * ( 1-dataScale.normalize(val) ) / ratio;
        });
        var originY = toY( dataScale.origin );

        var disableClipMarkers = this.config.disable_clip_markers;

        dojo.forEach( pixels, function(p,i) {
            if (!p)
                return;
            var score = toY(p['score']);
            var f = p['feat'];

            // draw the background color if we are configured to do so
            if( score >= 0 ) {
                var bgColor = this.getConfForFeature('style.bg_color', f );
                if( bgColor ) {
                    context.fillStyle = bgColor;
                    context.fillRect( i, 0, 1, canvasHeight );
                }
            }

            if( score <= canvasHeight || score > originY) { // if the rectangle is visible at all
                if( score <= originY ) {
                    // bar goes upward
                    context.fillStyle = this.getConfForFeature('style.pos_color',f);
                    context.fillRect( i, score, 1, originY-score+1);
                    if( !disableClipMarkers && score < 0 ) { // draw clip marker if necessary
                        context.fillStyle = this.getConfForFeature('style.clip_marker_color',f) || this.getConfForFeature('style.neg_color',f);
                        context.fillRect( i, 0, 1, 3 );

                    }
                }
                else {
                    // bar goes downward
                    context.fillStyle = this.getConfForFeature('style.neg_color',f);
                    context.fillRect( i, originY, 1, score-originY+1 );
                    if( !disableClipMarkers && score >= canvasHeight ) { // draw clip marker if necessary
                        context.fillStyle = this.getConfForFeature('style.clip_marker_color',f) || this.getConfForFeature('style.pos_color',f);
                        context.fillRect( i, canvasHeight-3, 1, 3 );

                    }
                }
            }
        }, this );
    },

    _calculatePixelScores: function( canvasWidth, features, featureRects ) {
        /* A variant of calculatePixelScores that stores the feature used at each pixel.
         * If there are multiple features, use the first one */
        var pixelValues = new Array( canvasWidth );
        dojo.forEach( features, function( f, i ) {
            var store = f.source;
            var fRect = featureRects[i];
            var jEnd = fRect.r;
            var score = f.get('score');
            for( var j = Math.round(fRect.l); j < jEnd; j++ ) {
                if ( pixelValues[j] && pixelValues[j]['lastUsedStore'] == store ) {
                    /* Note: if the feature is from a different store, the condition should fail,
                     *       and we will add to the value, rather than adjusting for overlap */
                    pixelValues[j]['score'] = Math.max( pixelValues[j]['score'], score );
                }
                else if ( pixelValues[j] ) {
                    pixelValues[j]['score'] = pixelValues[j]['score'] + score;
                    pixelValues[j]['lastUsedStore'] = store;
                }
                else {
                    pixelValues[j] = { score: score, lastUsedStore: store, feat: f };
                }
            }
        },this);
        // when done looping through features, forget the store information.
        for (var i=0; i<pixelValues.length; i++) {
            if ( pixelValues[i] ) {
                pixelValues[i] = { score: pixelValues[i]['score'], feat: pixelValues[i]['feat'] };
            }
        }
        return pixelValues;
    },

    /* If it's a boolean track, mask accordingly */
    _maskBySpans: function( scale, leftBase, rightBase, block, canvas, pixels, dataScale, spans ) {
        var context = canvas.getContext('2d');
        var canvasHeight = canvas.height;

        for ( var index in spans ) {
            if (spans.hasOwnProperty(index)) {
                var w = Math.ceil(( spans[index].end   - spans[index].start ) * scale );
                var l = Math.round(( spans[index].start - leftBase ) * scale );
                context.clearRect( l, 0, w, canvasHeight );
            }
        }
        context.globalAlpha = this.config.style.masked_transparancy || 0.2;
        this.config.style.masked_transparancy = context.globalAlpha;
        this._drawFeatures( scale, leftBase, rightBase, block, canvas, pixels, dataScale );
    },

    /**
     * Draw anything needed after the features are drawn.
     */
    _postDraw: function( scale, leftBase, rightBase, block, canvas, features, featureRects, dataScale ) {
        var context = canvas.getContext('2d');
        var canvasHeight = canvas.height;
        var devicePixelRatio = window.devicePixelRatio || 1;
        var backingStoreRatio = context.webkitBackingStorePixelRatio ||
                                                context.mozBackingStorePixelRatio ||
                                                context.msBackingStorePixelRatio ||
                                                context.oBackingStorePixelRatio ||
                                                context.backingStorePixelRatio || 1;

        var ratio = devicePixelRatio / backingStoreRatio;
        var toY = dojo.hitch( this, function( val ) {
           return canvasHeight * ( 1-dataScale.normalize(val) ) / ratio;
        });

        // draw the variance_band if requested
        if( this.config.variance_band ) {
            var bandPositions =
                typeof this.config.variance_band == 'object'
                    ? array.map( this.config.variance_band, function(v) { return parseFloat(v); } ).sort().reverse()
                    : [ 2, 1 ];
            this.getGlobalStats( dojo.hitch( this, function( stats ) {
                if( ('scoreMean' in stats) && ('scoreStdDev' in stats) ) {
                    var drawVarianceBand = function( plusminus, fill, label ) {
                        context.fillStyle = fill;
                        var varTop = toY( stats.scoreMean + plusminus );
                        var varHeight = toY( stats.scoreMean - plusminus ) - varTop;
                        varHeight = Math.max( 1, varHeight );
                        context.fillRect( 0, varTop, canvas.width, varHeight );
                        context.font = '12px sans-serif';
                        if( plusminus > 0 ) {
                            context.fillText( '+'+label, 2, varTop );
                            context.fillText( '-'+label, 2, varTop+varHeight );
                        }
                        else {
                            context.fillText( label, 2, varTop );
                        }
                    };

                    var maxColor = new Color( this.config.style.variance_band_color );
                    var minColor = new Color( this.config.style.variance_band_color );
                    minColor.a /= bandPositions.length;

                    var bandOpacityStep = 1/bandPositions.length;
                    var minOpacity = bandOpacityStep;

                    array.forEach( bandPositions, function( pos,i ) {
                        drawVarianceBand( pos*stats.scoreStdDev,
                                          Color.blendColors( minColor, maxColor, (i+1)/bandPositions.length).toCss(true),
                                          pos+'σ');
                    });
                    drawVarianceBand( 0, 'rgba(255,255,0,0.7)', 'mean' );
                }
            }));
        }

        // draw the origin line if it is not disabled
        var originColor = this.config.style.origin_color;
        if( typeof originColor == 'string' && !{'none':1,'off':1,'no':1,'zero':1}[originColor] ) {
            var originY = toY( dataScale.origin );
            context.fillStyle = originColor;
            context.fillRect( 0, originY, canvas.width, 1 );
        }

    }

});

return XYPlot;
});
<|endoftext|>


<commit_before>$(function () {

    // Initialize relationship pickers
    $('[data-provides="anomaly.field_type.relationship"]').each(function () {

        var input = $(this);
        var field = input.data('field_name');
        var wrapper = input.closest('.form-group');
        var modal = $('#' + field + '-modal');

        modal.on('click', '[data-entry]', function (e) {

            e.preventDefault();

            wrapper.find('.selected').load('/streams/relationship-field_type/selected/' + $(this).data('key') + '?uploaded=' + $(this).data('entry'), function () {
                modal.modal('hide');
            });

            $('[name="' + field + '"]').val($(this).data('entry'));

            $(wrapper).find('[data-dismiss="relationship"]').removeClass('hidden');
        });

        $(wrapper).on('click', '[data-dismiss="relationship"]', function (e) {

            e.preventDefault();

            $('[name="' + field + '"]').val('');

            wrapper.find('.selected').html('');

            $(this).addClass('hidden');
        });
    });
});
<commit_msg>Making work on subfolder installations<commit_after>$(function () {

    // Initialize relationship pickers
    $('[data-provides="anomaly.field_type.relationship"]').each(function () {

        var input = $(this);
        var field = input.data('field_name');
        var wrapper = input.closest('.form-group');
        var modal = $('#' + field + '-modal');

        modal.on('click', '[data-entry]', function (e) {

            e.preventDefault();

            wrapper.find('.selected').load(REQUEST_ROOT_PATH + '/streams/relationship-field_type/selected/' + $(this).data('key') + '?uploaded=' + $(this).data('entry'), function () {
                modal.modal('hide');
            });

            $('[name="' + field + '"]').val($(this).data('entry'));

            $(wrapper).find('[data-dismiss="relationship"]').removeClass('hidden');
        });

        $(wrapper).on('click', '[data-dismiss="relationship"]', function (e) {

            e.preventDefault();

            $('[name="' + field + '"]').val('');

            wrapper.find('.selected').html('');

            $(this).addClass('hidden');
        });
    });
});
<|endoftext|>


<commit_before>import React from 'react'
import { Link } from 'react-router'
import instagram_logo from '../../assets/instagram_logo.png'
import facebook_logo from '../../assets/facebook_logo.png'
import snapchat_logo from '../../assets/snapchat_logo.png'
import twitter_logo from '../../assets/twitter_logo.png'

class IntroBlock extends React.Component {

  static propTypes = {
    data: React.PropTypes.object,
  }

  render () {

    return (

Facebook

Instagram

Snapchat

Twitter

    )
  }

  // Dan, If not logged in show the Register button, otherwise show the view all photos button
  _renderButton() {
    if ( !this.props.data.user ) {
      return <Link className="f3 fw4 hover-red no-underline black-70 dib pv2 ph3 ba" to="/signup" >Register Now!</Link>
    } else {
      return <Link className="f3 fw4 hover-red no-underline black-70 dib pv2 ph3 ba" to="/Photo" >View all photos</Link>
    }
  }

  _showText() {
    if ( !this.props.data.user ) {
      return
1. Sign-up

    } else {
      return
2. Add photos

    }
  }
}

export default IntroBlock
<commit_msg>comments added<commit_after>import React from 'react'
import { Link } from 'react-router'
import instagram_logo from '../../assets/instagram_logo.png'
import facebook_logo from '../../assets/facebook_logo.png'
import snapchat_logo from '../../assets/snapchat_logo.png'
import twitter_logo from '../../assets/twitter_logo.png'

class IntroBlock extends React.Component {

  static propTypes = {
    data: React.PropTypes.object,
  }

  render () {

    return (

Facebook

              Follow us to get the latest news @farnboroughguide

Instagram

              See some pictures of farnborough @farnboroughguide

Snapchat

              Keep up-to-date with the latest news @fguide

Twitter

              Give us a follow! @fboroguide

    )
  }

  // Dan, If not logged in show the Register button, otherwise show the view all photos button
  _renderButton() {
    if ( !this.props.data.user ) {
      return <Link className="f3 fw4 hover-red no-underline black-70 dib pv2 ph3 ba" to="/signup" >Register Now!</Link>
    } else {
      return <Link className="f3 fw4 hover-red no-underline black-70 dib pv2 ph3 ba" to="/Photo" >View all photos</Link>
    }
  }

  _showText() {
    if ( !this.props.data.user ) {
      return
1. Sign-up

    } else {
      return
2. Add photos

    }
  }
}

export default IntroBlock
<|endoftext|>


<commit_before>var JSM = function ()
{
	this.mainVersion = 0;
	this.subVersion = 43;
};

/**
* Function: RandomNumber
* Description: Generates a random number between two numbers.
* Parameters:
*	from {number} lowest random result
*	to {number} highest random result
* Returns:
*	{number} the result
*/
JSM.RandomNumber = function (from, to)
{
	return Math.random () * (to - from) + from;
};

/**
* Function: RandomInt
* Description: Generates a random integer between two integers.
* Parameters:
*	from {integer} lowest random result
*	to {integer} highest random result
* Returns:
*	{integer} the result
*/
JSM.RandomInt = function (from, to)
{
	return Math.floor ((Math.random () * (to - from + 1)) + from);
};

/**
* Function: RandomBoolean
* Description: Generates a random boolean value.
* Returns:
*	{boolean} the result
*/
JSM.RandomBoolean = function ()
{
	return JSM.RandomInt (0, 1) === 1;
};

/**
* Function: SeededRandomInt
* Description: Generates a random integer between two integers. A seed number can be specified.
* Parameters:
*	from {integer} lowest random result
*	to {integer} highest random result
*	seed {integer} seed value
* Returns:
*	{integer} the result
*/
JSM.SeededRandomInt = function (from, to, seed)
{
    var random = ((seed * 9301 + 49297) % 233280) / 233280;
	return Math.floor ((random * (to - from + 1)) + from);
};

/**
* Function: ValueOrDefault
* Description: Returns the given value, or a default if it is undefined.
* Parameters:
*	val {anything} new value
*	def {anything} default value
* Returns:
*	{anything} the result
*/
JSM.ValueOrDefault = function (val, def)
{
	if (val === undefined || val === null) {
		return def;
	}
	return val;
};

/**
* Function: PrevIndex
* Description: Returns the circular previous index for an array with the given length.
* Parameters:
*	index {integer} the index
*	length {integer} the number of indices
*/
JSM.PrevIndex = function (index, length)
{
	return index > 0 ? index - 1 : length - 1;
};

/**
* Function: NextIndex
* Description: Returns the circular next index for an array with the given length.
* Parameters:
*	index {integer} the index
*	length {integer} the number of indices
*/
JSM.NextIndex = function (index, length)
{
	return index < length - 1 ? index + 1 : 0;
};

/**
* Function: CopyObjectProperties
* Description: Copies one object properties to another object.
* Parameters:
*	source {anything} source object
*	target {anything} target object
*	overwrite {boolean} overwrite existing properties
*/
JSM.CopyObjectProperties = function (source, target, overwrite)
{
	if (source === undefined || source === null ||
		target === undefined || target === null)
	{
		return;
	}

	var property;
	for (property in source) {
		if (source.hasOwnProperty (property)) {
			if (overwrite || target[property] === undefined || target[property] === null) {
				target[property] = source[property];
			}
		}
	}
};

/**
* Function: Message
* Description: Writes a message to the console.
* Parameters:
*	message {string} the message
*/
JSM.Message = function (message)
{
	console.log ('JSModeler: ' + message);
};
<commit_msg>Utility function for access an objects property.<commit_after>var JSM = function ()
{
	this.mainVersion = 0;
	this.subVersion = 43;
};

/**
* Function: RandomNumber
* Description: Generates a random number between two numbers.
* Parameters:
*	from {number} lowest random result
*	to {number} highest random result
* Returns:
*	{number} the result
*/
JSM.RandomNumber = function (from, to)
{
	return Math.random () * (to - from) + from;
};

/**
* Function: RandomInt
* Description: Generates a random integer between two integers.
* Parameters:
*	from {integer} lowest random result
*	to {integer} highest random result
* Returns:
*	{integer} the result
*/
JSM.RandomInt = function (from, to)
{
	return Math.floor ((Math.random () * (to - from + 1)) + from);
};

/**
* Function: RandomBoolean
* Description: Generates a random boolean value.
* Returns:
*	{boolean} the result
*/
JSM.RandomBoolean = function ()
{
	return JSM.RandomInt (0, 1) === 1;
};

/**
* Function: SeededRandomInt
* Description: Generates a random integer between two integers. A seed number can be specified.
* Parameters:
*	from {integer} lowest random result
*	to {integer} highest random result
*	seed {integer} seed value
* Returns:
*	{integer} the result
*/
JSM.SeededRandomInt = function (from, to, seed)
{
    var random = ((seed * 9301 + 49297) % 233280) / 233280;
	return Math.floor ((random * (to - from + 1)) + from);
};

/**
* Function: ValueOrDefault
* Description: Returns the given value, or a default if it is undefined.
* Parameters:
*	val {anything} new value
*	def {anything} default value
* Returns:
*	{anything} the result
*/
JSM.ValueOrDefault = function (val, def)
{
	if (val === undefined || val === null) {
		return def;
	}
	return val;
};

/**
* Function: PrevIndex
* Description: Returns the circular previous index for an array with the given length.
* Parameters:
*	index {integer} the index
*	length {integer} the number of indices
*/
JSM.PrevIndex = function (index, length)
{
	return index > 0 ? index - 1 : length - 1;
};

/**
* Function: NextIndex
* Description: Returns the circular next index for an array with the given length.
* Parameters:
*	index {integer} the index
*	length {integer} the number of indices
*/
JSM.NextIndex = function (index, length)
{
	return index < length - 1 ? index + 1 : 0;
};

/**
* Function: CopyObjectProperties
* Description: Copies one object properties to another object.
* Parameters:
*	source {anything} source object
*	target {anything} target object
*	overwrite {boolean} overwrite existing properties
*/
JSM.CopyObjectProperties = function (source, target, overwrite)
{
	if (source === undefined || source === null ||
		target === undefined || target === null)
	{
		return;
	}

	var property;
	for (property in source) {
		if (source.hasOwnProperty (property)) {
			if (overwrite || target[property] === undefined || target[property] === null) {
				target[property] = source[property];
			}
		}
	}
};

/**
* Function: GetObjectProperty
* Description: Returns the given property of the object. If it doesn't exist, returns the given default value.
* Parameters:
*	object {anything} the object
*	propertyName {string} the name of the property
*	defaultValue {anything} the default value
*/
JSM.GetObjectProperty = function (object, propertyName, defaultValue)
{
	if (object === undefined || object === null) {
		return defaultValue
	}

	var propertyValue = object[propertyName];
	if (propertyValue === undefined || propertyValue === null) {
		return defaultValue;
	}

	return propertyValue;
};

/**
* Function: Message
* Description: Writes a message to the console.
* Parameters:
*	message {string} the message
*/
JSM.Message = function (message)
{
	console.log ('JSModeler: ' + message);
};
<|endoftext|>