<commit_before>var rendererOptions = { draggable: true };
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var directionsService = new google.maps.DirectionsService();
var elevator;
var map;
var chart;
var polyline;
var currentPosition;
//assign defalut position
var currentLatitude = 37.783478;
var currentLongitude = -122.409093;
var path;
var content;
var res;

// Load the Visualization API and the columnchart package.
google.load('visualization', '1', {packages: ['columnchart']});

var setupMap = function(content){
  currentPosition = new google.maps.LatLng( currentLatitude, currentLongitude );

  var options = {
    map: map,
    position: currentPosition
  };

  if (content != undefined){
    options.content = content;
    var infowindow = new google.maps.InfoWindow(options);
  }

  map.setCenter(currentPosition);
  directionsDisplay.setMap(map);
  elevator = new google.maps.ElevationService();
  calcRoute();

  //add listner for the route change
  google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
    res = directionsDisplay.getDirections();
    path = res.routes[0].overview_path;
    computeTotalDistance(res);
    drawChart(res);
  });
};

// ====================TO DISPLAY INFO DIV==========================

var computeTotalDistance = function(result) {
  var total = 0;
  var myroute = result.routes[0];
  for (var i = 0; i < myroute.legs.length; i++) {
    total += myroute.legs[i].distance.value;
  }
  total = total / 1000.0;
  document.getElementById('total').innerHTML = total;
};

var calcDifficulty = function(elevations){
  var difficulty = 0;
  for(var i = 0; i < elevations.length - 1; i++){
    //calculate the elevation change
    var ele = elevations[i+1].elevation - elevations[i].elevation;
    // calculate the distance
    var disB = elevations[i+1].location.B - elevations[i].location.B;
    var disK = elevations[i+1].location.k - elevations[i].location.k;
    if(disB < 0){ disB *= -1; }
    if(disK < 0){ disK *= -1; }
    var dis = Math.sqrt( Math.pow( disB, 2 ) + Math.pow( disK, 2 ) );
    //devide elevation by distance (if it is a uphill, maltiple by 2)
    var dif = ele/dis;
    dif = (dif > 0) ? dif * 2 : dif * -1;
    difficulty += dif;
  };
  difficulty =Math.round(difficulty / 1000) / 100;

  $('.difficulty').html(difficulty);
};

function drawChart(response) {

  // Create a new chart in the elevation_chart DIV.
  chart = new google.visualization.ColumnChart(document.getElementById('elevation_chart'));

  // Create a PathElevationRequest object using this array.
  // Ask for 256 samples along that path.
  var pathRequest = {
    'path': path,
    'samples': 256
  }

  // Initiate the path request.
  elevator.getElevationAlongPath(pathRequest, plotElevation);
}

// Takes an array of ElevationResult objects
// and plots the elevation profile on a Visualization API ColumnChart.
var plotElevation = function(results, status) {
  if (status != google.maps.ElevationStatus.OK) {
    return;
  }
  var elevations = results;

  // Extract the elevation samples from the returned results
  // and store them in an array of LatLngs.
  var elevationPath = [];
  for (var i = 0; i < results.length; i++) {
    elevationPath.push(elevations[i].location);
  }

  // Extract the data from which to populate the chart.
  // Because the samples are equidistant, the 'Sample'
  // column here does double duty as distance along the
  // X axis.
  var data = new google.visualization.DataTable();
  data.addColumn('string', 'Sample');
  data.addColumn('number', 'Elevation');
  for (var i = 0; i < results.length; i++) {
    data.addRow(['', elevations[i].elevation]);
  }

  // Draw the chart using the data within its DIV.
  document.getElementById('elevation_chart').style.display = 'block';
  chart.draw(data, {
    height: 150,
    legend: 'none',
    titleY: 'Elevation (m)'
  });

  //culculate the dificulty
  calcDifficulty(elevations);
};

var getRequest = function(currentPo, destPo, wayPtArr){
  var request = {
    origin: currentPo,
    destination: destPo,
    waypoints: wayPtArr,
    optimizeWaypoints: true,
    travelMode: google.maps.TravelMode.WALKING,
    avoidHighways: true,
    avoidTolls: true
  }
  return request;
};

var calcRoute = function() {
  var destination = new google.maps.LatLng(currentLatitude, currentLongitude+0.02);
  var request = getRequest(currentPosition, destination);
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
      drawChart(response);
    }
  });
};

// =======================TO SHOW THE SAVED ROUTES=============================

var loadMap = function(runningRoute){
  var rr = fix(runningRoute);
  directionsDisplay.setDirections(rr);
};

//fixes the saved route object when user clicks on the saved route
var fix = function(obj){
  var bounds = obj.routes[0].bounds;
  var sw = new google.maps.LatLng(parseFloat(bounds.Ea.j), parseFloat(bounds.va.j));
  var ne = new google.maps.LatLng(parseFloat(bounds.Ea.k), parseFloat(bounds.va.k));
  obj.routes[0].bounds = new google.maps.LatLngBounds(sw, ne);
  var legs = obj.routes[0].legs;
  for(var kk = 0; kk < legs.length; kk++){
    var steps = obj.routes[0].legs[kk].steps;
    var waypoint = legs[kk].via_waypoint;
    var waypoints = legs[kk].via_waypoints;
    for(var j = 0; j < waypoints.length; j++){
      waypoint[j].location = new google.maps.LatLng(parseFloat(waypoint[j].location.k), parseFloat(waypoint[j].location.B));
      waypoint[j].location = new google.maps.LatLng(parseFloat(waypoint[j].location.k), parseFloat(waypoint[j].location.B));
      waypoints[j] = new google.maps.LatLng(parseFloat(waypoints[j].k), parseFloat(waypoints[j].B));
      waypoints[j] = new google.maps.LatLng(parseFloat(waypoints[j].k), parseFloat(waypoints[j].B));

    }
    for(var j = 0; j < steps.length; j++){
      var path = steps[j].path;
      var lat_lngs = steps[j].lat_lngs;
      for(var i = 0; i < path.length; i++){
          path[i] = new google.maps.LatLng(parseFloat(path[i].k), parseFloat(path[i].B));
          lat_lngs[i] = new google.maps.LatLng(parseFloat(lat_lngs[i].k), parseFloat(lat_lngs[i].B));
      }
    }
    legs[kk].start_location = new google.maps.LatLng(parseFloat(legs[kk].start_location.k), parseFloat(legs[kk].start_location.B));
    legs[kk].end_location = new google.maps.LatLng(parseFloat(legs[kk].end_location.k), parseFloat(legs[kk].end_location.B));
  }
  var op = obj.routes[0].overview_path;
  for(var i = 0; i < op.length; i++){
    op[i] = new google.maps.LatLng(parseFloat(op[i].k), parseFloat(op[i].B));
  }
  return obj;
};

// ===========TO INITIALIZE WHEN THE WINDOW IS LOADED===============

google.maps.event.addDomListener(window, 'load', initialize);

var initialize = function() {
  map = new google.maps.Map(document.getElementById('map-canvas'));

  if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      currentLatitude = position.coords.latitude;
      currentLongitude = position.coords.longitude;
      setupMap();
    }, function() {
      //if getting geolocation info failed.
      content = 'Error: The Geolocation service failed.';
      setupMap(content);
    });
  }else{
    // Browser doesn't support Geolocation
    content = 'Error: Your browser doesn\'t support geolocation.';
    setupMap(content);
  }
};

// ============TO SHOW THE ACTIVE BUTTON IN NAV BAR ===================

$(document).ready(function(){
  //add savedRoute link active class when loaded
  $('.navbar-nav li:nth-child(2)').addClass('active');
  //toggle active class in navbar, when one of the buttons are clicked.
  $('.navbar-nav').on('click', 'li', function(){
    $('.navbar-nav').children().removeClass('active');
    $(this).addClass('active');
  });
});

<commit_msg>(refactor) move blocks to proper places<commit_after>var rendererOptions = { draggable: true };
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var directionsService = new google.maps.DirectionsService();
var elevator;
var map;
var chart;
var polyline;
var currentPosition;
//assign defalut position
var currentLatitude = 37.783478;
var currentLongitude = -122.409093;
var path;
var content;
var res;

// Load the Visualization API and the columnchart package.
google.load('visualization', '1', {packages: ['columnchart']});

//=================FUNCTIONS TO USE WHEN INITIALIZE=======================

var setupMap = function(content){
  currentPosition = new google.maps.LatLng( currentLatitude, currentLongitude );

  var options = {
    map: map,
    position: currentPosition
  };

  if (content != undefined){
    options.content = content;
    var infowindow = new google.maps.InfoWindow(options);
  }

  map.setCenter(currentPosition);
  directionsDisplay.setMap(map);
  elevator = new google.maps.ElevationService();
  calcRoute();

  //add listner for the route change
  google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
    res = directionsDisplay.getDirections();
    path = res.routes[0].overview_path;
    computeTotalDistance(res);
    drawChart(res);
  });
};

var getRequest = function(currentPo, destPo, wayPtArr){
  var request = {
    origin: currentPo,
    destination: destPo,
    waypoints: wayPtArr,
    optimizeWaypoints: true,
    travelMode: google.maps.TravelMode.WALKING,
    avoidHighways: true,
    avoidTolls: true
  }
  return request;
};

var calcRoute = function() {
  var destination = new google.maps.LatLng(currentLatitude, currentLongitude+0.02);
  var request = getRequest(currentPosition, destination);
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
      drawChart(response);
    }
  });
};

// ====================TO DISPLAY INFO DIV==========================

var computeTotalDistance = function(result) {
  var total = 0;
  var myroute = result.routes[0];
  for (var i = 0; i < myroute.legs.length; i++) {
    total += myroute.legs[i].distance.value;
  }
  total = total / 1000.0;
  $('#total').html(total);
};

var calcDifficulty = function(elevations){
  var difficulty = 0;
  for(var i = 0; i < elevations.length - 1; i++){
    //calculate the elevation change
    var ele = elevations[i+1].elevation - elevations[i].elevation;
    // calculate the distance
    var disB = elevations[i+1].location.B - elevations[i].location.B;
    var disK = elevations[i+1].location.k - elevations[i].location.k;
    if(disB < 0){ disB *= -1; }
    if(disK < 0){ disK *= -1; }
    var dis = Math.sqrt( Math.pow( disB, 2 ) + Math.pow( disK, 2 ) );
    //devide elevation by distance (if it is a uphill, maltiple by 2)
    var dif = ele/dis;
    dif = (dif > 0) ? dif * 2 : dif * -1;
    difficulty += dif;
  };
  difficulty =Math.round(difficulty / 1000) / 100;

  $('.difficulty').html(difficulty);
};

function drawChart(response) {
  // Create a new chart in the elevation_chart DIV.
  chart = new google.visualization.ColumnChart(document.getElementById('elevation_chart'));

  // Create a PathElevationRequest object using this array.
  // Ask for 256 samples along that path.
  var pathRequest = {
    'path': path,
    'samples': 256
  }

  // Initiate the path request.
  elevator.getElevationAlongPath(pathRequest, plotElevation);
};

// Takes an array of ElevationResult objects
// and plots the elevation profile on a Visualization API ColumnChart.
var plotElevation = function(results, status) {
  if (status != google.maps.ElevationStatus.OK) {
    return;
  }
  var elevations = results;

  // Extract the elevation samples from the returned results
  // and store them in an array of LatLngs.
  var elevationPath = [];
  for (var i = 0; i < results.length; i++) {
    elevationPath.push(elevations[i].location);
  }

  // Extract the data from which to populate the chart.
  // Because the samples are equidistant, the 'Sample'
  // column here does double duty as distance along the
  // X axis.
  var data = new google.visualization.DataTable();
  data.addColumn('string', 'Sample');
  data.addColumn('number', 'Elevation');
  for (var i = 0; i < results.length; i++) {
    data.addRow(['', elevations[i].elevation]);
  }

  // Draw the chart using the data within its DIV.
  document.getElementById('elevation_chart').style.display = 'block';
  chart.draw(data, {
    height: 150,
    legend: 'none',
    titleY: 'Elevation (m)'
  });

  //culculate the dificulty
  calcDifficulty(elevations);
};

// =======================TO SHOW THE SAVED ROUTES=============================

var loadMap = function(runningRoute){
  var rr = fix(runningRoute);
  directionsDisplay.setDirections(rr);
};

//fixes the saved route object when user clicks on the saved route
var fix = function(obj){
  var bounds = obj.routes[0].bounds;
  var sw = new google.maps.LatLng(parseFloat(bounds.Ea.j), parseFloat(bounds.va.j));
  var ne = new google.maps.LatLng(parseFloat(bounds.Ea.k), parseFloat(bounds.va.k));
  obj.routes[0].bounds = new google.maps.LatLngBounds(sw, ne);
  var legs = obj.routes[0].legs;
  for(var kk = 0; kk < legs.length; kk++){
    var steps = obj.routes[0].legs[kk].steps;
    var waypoint = legs[kk].via_waypoint;
    var waypoints = legs[kk].via_waypoints;
    for(var j = 0; j < waypoints.length; j++){
      waypoint[j].location = new google.maps.LatLng(parseFloat(waypoint[j].location.k), parseFloat(waypoint[j].location.B));
      waypoint[j].location = new google.maps.LatLng(parseFloat(waypoint[j].location.k), parseFloat(waypoint[j].location.B));
      waypoints[j] = new google.maps.LatLng(parseFloat(waypoints[j].k), parseFloat(waypoints[j].B));
      waypoints[j] = new google.maps.LatLng(parseFloat(waypoints[j].k), parseFloat(waypoints[j].B));

    }
    for(var j = 0; j < steps.length; j++){
      var path = steps[j].path;
      var lat_lngs = steps[j].lat_lngs;
      for(var i = 0; i < path.length; i++){
          path[i] = new google.maps.LatLng(parseFloat(path[i].k), parseFloat(path[i].B));
          lat_lngs[i] = new google.maps.LatLng(parseFloat(lat_lngs[i].k), parseFloat(lat_lngs[i].B));
      }
    }
    legs[kk].start_location = new google.maps.LatLng(parseFloat(legs[kk].start_location.k), parseFloat(legs[kk].start_location.B));
    legs[kk].end_location = new google.maps.LatLng(parseFloat(legs[kk].end_location.k), parseFloat(legs[kk].end_location.B));
  }
  var op = obj.routes[0].overview_path;
  for(var i = 0; i < op.length; i++){
    op[i] = new google.maps.LatLng(parseFloat(op[i].k), parseFloat(op[i].B));
  }
  return obj;
};

// ===========TO INITIALIZE WHEN THE WINDOW IS LOADED===============

google.maps.event.addDomListener(window, 'load', initialize);

var initialize = function() {
  map = new google.maps.Map(document.getElementById('map-canvas'));

  if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      currentLatitude = position.coords.latitude;
      currentLongitude = position.coords.longitude;
      setupMap();
    }, function() {
      //if getting geolocation info failed.
      content = 'Error: The Geolocation service failed.';
      setupMap(content);
    });
  }else{
    // Browser doesn't support Geolocation
    content = 'Error: Your browser doesn\'t support geolocation.';
    setupMap(content);
  }
};

// ============TO SHOW THE ACTIVE BUTTON IN NAV BAR ===================

$(document).ready(function(){
  //add savedRoute link active class when loaded
  $('.navbar-nav li:nth-child(2)').addClass('active');
  //toggle active class in navbar, when one of the buttons are clicked.
  $('.navbar-nav').on('click', 'li', function(){
    $('.navbar-nav').children().removeClass('active');
    $(this).addClass('active');
  });
});

<|endoftext|>


<commit_before>const CUSTOM_PROPERTY_REGEX = /^--/;
const DEFAULT_STYLES = document.createElement("div").style;
const PREFIXES = ["Webkit", "Moz", "ms"];
const propertyNameCache = {};
// DOM properties that should NOT have "px" added when numeric
const IS_NON_DIMENSIONAL = /acit|ex(?:s|g|n|p|$)|rph|ows|mnc|ntw|ine[ch]|zoo|^ord/i;

/**
 * Returns the normalized (like vendor-prefixed) name of the given CSS property
 *
 * @param {string} name
 * @return {string}
 */
function normalizeName (name)
{
    if (propertyNameCache[name])
    {
        return propertyNameCache[name];
    }

    // if the property already exists, just use it
    if (name in DEFAULT_STYLES)
    {
        return name;
    }

    const capitalizedName = name[0].toUpperCase() + name.slice(1);

    for (let i = 0; i < PREFIXES.length; i++)
    {
        const prefixedName = `${PREFIXES[i]}${capitalizedName}`;

        if (prefixedName in DEFAULT_STYLES)
        {
            propertyNameCache[name] = prefixedName;
            return prefixedName;
        }
    }

    propertyNameCache[name] = name;
    return name;
}

/**
 * Sets all styles on the element
 *
 * @param {HTMLElement|HTMLElement[]} elements
 * @param {Object} styles
 */
export function setCss (elements, styles)
{
    elements = Array.isArray(elements) ? elements : [elements];

    for (let i = 0; i < elements.length; i++)
    {
        const element = elements[i];
        const style = element.style;

        for (let key in styles)
        {
            if (!styles.hasOwnProperty(key))
            {
                continue;
            }

            // add "px" to all numbers of dimensional values
            const value = typeof styles[key] === "number" && false === IS_NON_DIMENSIONAL.test(key)
                ? `${styles[key]}px`
                : styles[key];

            if (CUSTOM_PROPERTY_REGEX.test(element))
            {
                style.setProperty(key, value);
            }
            else
            {
                key = normalizeName(key);
                style[key] = value;
            }
        }
    }
}
<commit_msg>Use „property“ as correct name in CSS code<commit_after>const CUSTOM_PROPERTY_REGEX = /^--/;
const DEFAULT_STYLES = document.createElement("div").style;
const VENDOR_PREFIXES = ["Webkit", "Moz", "ms"];
const propertyNameCache = {};
// DOM properties that should NOT have "px" added when numeric
const IS_NON_DIMENSIONAL = /acit|ex(?:s|g|n|p|$)|rph|ows|mnc|ntw|ine[ch]|zoo|^ord/i;

/**
 * Returns the normalized (like vendor-prefixed) name of the given CSS property
 *
 * @param {string} property
 * @return {string}
 */
function normalizeProperty (property)
{
    if (propertyNameCache[property])
    {
        return propertyNameCache[property];
    }

    // if the property already exists, just use it
    if (property in DEFAULT_STYLES)
    {
        return property;
    }

    const capitalized = property[0].toUpperCase() + property.slice(1);

    for (let i = 0; i < VENDOR_PREFIXES.length; i++)
    {
        const prefixedName = `${VENDOR_PREFIXES[i]}${capitalized}`;

        if (prefixedName in DEFAULT_STYLES)
        {
            propertyNameCache[property] = prefixedName;
            return prefixedName;
        }
    }

    propertyNameCache[property] = property;
    return property;
}

/**
 * Sets all styles on the element
 *
 * @param {HTMLElement|HTMLElement[]} elements
 * @param {Object} styles
 */
export function setCss (elements, styles)
{
    elements = Array.isArray(elements) ? elements : [elements];

    for (let i = 0; i < elements.length; i++)
    {
        const element = elements[i];
        const style = element.style;

        for (let property in styles)
        {
            if (!styles.hasOwnProperty(property))
            {
                continue;
            }

            // add "px" to all numbers of dimensional values
            const value = typeof styles[property] === "number" && false === IS_NON_DIMENSIONAL.test(property)
                ? `${styles[property]}px`
                : styles[property];

            if (CUSTOM_PROPERTY_REGEX.test(element))
            {
                style.setProperty(property, value);
            }
            else
            {
                property = normalizeProperty(property);
                style[property] = value;
            }
        }
    }
}
<|endoftext|>


<commit_before>import * as core from '../../core';
import { default as Mesh } from '../Mesh';

/**
 * Renderer dedicated to meshes.
 *
 * @class
 * @private
 * @memberof PIXI
 */
export default class MeshSpriteRenderer
{
    /**
     * @param {PIXI.CanvasRenderer} renderer - The renderer this downport works for
     */
    constructor(renderer)
    {
        this.renderer = renderer;
    }

    /**
     * Renders the Mesh
     *
     * @param {PIXI.mesh.Mesh} mesh - the Mesh to render
     */
    render(mesh)
    {
        const renderer = this.renderer;
        const context = renderer.context;

        const transform = mesh.worldTransform;
        const res = renderer.resolution;

        if (renderer.roundPixels)
        {
            context.setTransform(
                transform.a * res,
                transform.b * res,
                transform.c * res,
                transform.d * res,
                (transform.tx * res) | 0,
                (transform.ty * res) | 0
            );
        }
        else
        {
            context.setTransform(
                transform.a * res,
                transform.b * res,
                transform.c * res,
                transform.d * res,
                transform.tx * res,
                transform.ty * res
            );
        }

        renderer.setBlendMode(mesh.blendMode);

        if (mesh.drawMode === Mesh.DRAW_MODES.TRIANGLE_MESH)
        {
            this._renderTriangleMesh(mesh);
        }
        else
        {
            this._renderTriangles(mesh);
        }
    }

    /**
     * Draws the object in Triangle Mesh mode
     *
     * @private
     * @param {PIXI.mesh.Mesh} mesh - the Mesh to render
     */
    _renderTriangleMesh(mesh)
    {
        // draw triangles!!
        const length = mesh.vertices.length / 2;

        for (let i = 0; i < length - 2; i++)
        {
            // draw some triangles!
            const index = i * 2;

            this._renderDrawTriangle(mesh, index, (index + 2), (index + 4));
        }
    }

    /**
     * Draws the object in triangle mode using canvas
     *
     * @private
     * @param {PIXI.mesh.Mesh} mesh - the current mesh
     */
    _renderTriangles(mesh)
    {
        // draw triangles!!
        const indices = mesh.indices;
        const length = indices.length;

        for (let i = 0; i < length; i += 3)
        {
            // draw some triangles!
            const index0 = indices[i] * 2;
            const index1 = indices[i + 1] * 2;
            const index2 = indices[i + 2] * 2;

            this._renderDrawTriangle(mesh, index0, index1, index2);
        }
    }

    /**
     * Draws one of the triangles that from the Mesh
     *
     * @private
     * @param {PIXI.mesh.Mesh} mesh - the current mesh
     * @param {number} index0 - the index of the first vertex
     * @param {number} index1 - the index of the second vertex
     * @param {number} index2 - the index of the third vertex
     */
    _renderDrawTriangle(mesh, index0, index1, index2)
    {
        const context = this.renderer.context;
        const uvs = mesh.uvs;
        const vertices = mesh.vertices;
        const texture = mesh._texture;

        if (!texture.valid)
        {
            return;
        }

        const base = texture.baseTexture;
        const textureSource = base.source;
        const textureWidth = base.width;
        const textureHeight = base.height;

        let u0;
        let u1;
        let u2;
        let v0;
        let v1;
        let v2;

        if (mesh.uploadUvTransform)
        {
            const ut = mesh._uvTransform.mapCoord;

            u0 = ((uvs[index0] * ut.a) + (uvs[index0 + 1] * ut.c) + ut.tx) * base.width;
            u1 = ((uvs[index1] * ut.a) + (uvs[index1 + 1] * ut.c) + ut.tx) * base.width;
            u2 = ((uvs[index2] * ut.a) + (uvs[index2 + 1] * ut.c) + ut.tx) * base.width;
            v0 = ((uvs[index0] * ut.b) + (uvs[index0 + 1] * ut.d) + ut.ty) * base.height;
            v1 = ((uvs[index1] * ut.b) + (uvs[index1 + 1] * ut.d) + ut.ty) * base.height;
            v2 = ((uvs[index2] * ut.b) + (uvs[index2 + 1] * ut.d) + ut.ty) * base.height;
        }
        else
        {
            u0 = uvs[index0] * base.width;
            u1 = uvs[index1] * base.width;
            u2 = uvs[index2] * base.width;
            v0 = uvs[index0 + 1] * base.height;
            v1 = uvs[index1 + 1] * base.height;
            v2 = uvs[index2 + 1] * base.height;
        }

        let x0 = vertices[index0];
        let x1 = vertices[index1];
        let x2 = vertices[index2];
        let y0 = vertices[index0 + 1];
        let y1 = vertices[index1 + 1];
        let y2 = vertices[index2 + 1];

        if (mesh.canvasPadding > 0)
        {
            const paddingX = mesh.canvasPadding / mesh.worldTransform.a;
            const paddingY = mesh.canvasPadding / mesh.worldTransform.d;
            const centerX = (x0 + x1 + x2) / 3;
            const centerY = (y0 + y1 + y2) / 3;

            let normX = x0 - centerX;
            let normY = y0 - centerY;

            let dist = Math.sqrt((normX * normX) + (normY * normY));

            x0 = centerX + ((normX / dist) * (dist + paddingX));
            y0 = centerY + ((normY / dist) * (dist + paddingY));

            //

            normX = x1 - centerX;
            normY = y1 - centerY;

            dist = Math.sqrt((normX * normX) + (normY * normY));
            x1 = centerX + ((normX / dist) * (dist + paddingX));
            y1 = centerY + ((normY / dist) * (dist + paddingY));

            normX = x2 - centerX;
            normY = y2 - centerY;

            dist = Math.sqrt((normX * normX) + (normY * normY));
            x2 = centerX + ((normX / dist) * (dist + paddingX));
            y2 = centerY + ((normY / dist) * (dist + paddingY));
        }

        context.save();
        context.beginPath();

        context.moveTo(x0, y0);
        context.lineTo(x1, y1);
        context.lineTo(x2, y2);

        context.closePath();

        context.clip();

        // Compute matrix transform
        const delta = (u0 * v1) + (v0 * u2) + (u1 * v2) - (v1 * u2) - (v0 * u1) - (u0 * v2);
        const deltaA = (x0 * v1) + (v0 * x2) + (x1 * v2) - (v1 * x2) - (v0 * x1) - (x0 * v2);
        const deltaB = (u0 * x1) + (x0 * u2) + (u1 * x2) - (x1 * u2) - (x0 * u1) - (u0 * x2);
        const deltaC = (u0 * v1 * x2) + (v0 * x1 * u2) + (x0 * u1 * v2) - (x0 * v1 * u2) - (v0 * u1 * x2) - (u0 * x1 * v2);
        const deltaD = (y0 * v1) + (v0 * y2) + (y1 * v2) - (v1 * y2) - (v0 * y1) - (y0 * v2);
        const deltaE = (u0 * y1) + (y0 * u2) + (u1 * y2) - (y1 * u2) - (y0 * u1) - (u0 * y2);
        const deltaF = (u0 * v1 * y2) + (v0 * y1 * u2) + (y0 * u1 * v2) - (y0 * v1 * u2) - (v0 * u1 * y2) - (u0 * y1 * v2);

        context.transform(
            deltaA / delta,
            deltaD / delta,
            deltaB / delta,
            deltaE / delta,
            deltaC / delta,
            deltaF / delta
        );

        context.drawImage(
            textureSource,
            0,
            0,
            textureWidth * base.resolution,
            textureHeight * base.resolution,
            0,
            0,
            textureWidth,
            textureHeight
        );

        context.restore();
        this.renderer.invalidateBlendMode();
    }

    /**
     * Renders a flat Mesh
     *
     * @private
     * @param {PIXI.mesh.Mesh} mesh - The Mesh to render
     */
    renderMeshFlat(mesh)
    {
        const context = this.renderer.context;
        const vertices = mesh.vertices;
        const length = vertices.length / 2;

        // this.count++;

        context.beginPath();

        for (let i = 1; i < length - 2; ++i)
        {
            // draw some triangles!
            const index = i * 2;

            const x0 = vertices[index];
            const y0 = vertices[index + 1];

            const x1 = vertices[index + 2];
            const y1 = vertices[index + 3];

            const x2 = vertices[index + 4];
            const y2 = vertices[index + 5];

            context.moveTo(x0, y0);
            context.lineTo(x1, y1);
            context.lineTo(x2, y2);
        }

        context.fillStyle = '#FF0000';
        context.fill();
        context.closePath();
    }

    /**
     * destroy the the renderer.
     *
     */
    destroy()
    {
        this.renderer = null;
    }
}

core.CanvasRenderer.registerPlugin('mesh', MeshSpriteRenderer);
<commit_msg>Canvas mesh alpha. Fix for #4534 (#4535)<commit_after>import * as core from '../../core';
import { default as Mesh } from '../Mesh';

/**
 * Renderer dedicated to meshes.
 *
 * @class
 * @private
 * @memberof PIXI
 */
export default class MeshSpriteRenderer
{
    /**
     * @param {PIXI.CanvasRenderer} renderer - The renderer this downport works for
     */
    constructor(renderer)
    {
        this.renderer = renderer;
    }

    /**
     * Renders the Mesh
     *
     * @param {PIXI.mesh.Mesh} mesh - the Mesh to render
     */
    render(mesh)
    {
        const renderer = this.renderer;
        const context = renderer.context;

        const transform = mesh.worldTransform;
        const res = renderer.resolution;

        if (renderer.roundPixels)
        {
            context.setTransform(
                transform.a * res,
                transform.b * res,
                transform.c * res,
                transform.d * res,
                (transform.tx * res) | 0,
                (transform.ty * res) | 0
            );
        }
        else
        {
            context.setTransform(
                transform.a * res,
                transform.b * res,
                transform.c * res,
                transform.d * res,
                transform.tx * res,
                transform.ty * res
            );
        }

        renderer.context.globalAlpha = mesh.worldAlpha;
        renderer.setBlendMode(mesh.blendMode);

        if (mesh.drawMode === Mesh.DRAW_MODES.TRIANGLE_MESH)
        {
            this._renderTriangleMesh(mesh);
        }
        else
        {
            this._renderTriangles(mesh);
        }
    }

    /**
     * Draws the object in Triangle Mesh mode
     *
     * @private
     * @param {PIXI.mesh.Mesh} mesh - the Mesh to render
     */
    _renderTriangleMesh(mesh)
    {
        // draw triangles!!
        const length = mesh.vertices.length / 2;

        for (let i = 0; i < length - 2; i++)
        {
            // draw some triangles!
            const index = i * 2;

            this._renderDrawTriangle(mesh, index, (index + 2), (index + 4));
        }
    }

    /**
     * Draws the object in triangle mode using canvas
     *
     * @private
     * @param {PIXI.mesh.Mesh} mesh - the current mesh
     */
    _renderTriangles(mesh)
    {
        // draw triangles!!
        const indices = mesh.indices;
        const length = indices.length;

        for (let i = 0; i < length; i += 3)
        {
            // draw some triangles!
            const index0 = indices[i] * 2;
            const index1 = indices[i + 1] * 2;
            const index2 = indices[i + 2] * 2;

            this._renderDrawTriangle(mesh, index0, index1, index2);
        }
    }

    /**
     * Draws one of the triangles that from the Mesh
     *
     * @private
     * @param {PIXI.mesh.Mesh} mesh - the current mesh
     * @param {number} index0 - the index of the first vertex
     * @param {number} index1 - the index of the second vertex
     * @param {number} index2 - the index of the third vertex
     */
    _renderDrawTriangle(mesh, index0, index1, index2)
    {
        const context = this.renderer.context;
        const uvs = mesh.uvs;
        const vertices = mesh.vertices;
        const texture = mesh._texture;

        if (!texture.valid)
        {
            return;
        }

        const base = texture.baseTexture;
        const textureSource = base.source;
        const textureWidth = base.width;
        const textureHeight = base.height;

        let u0;
        let u1;
        let u2;
        let v0;
        let v1;
        let v2;

        if (mesh.uploadUvTransform)
        {
            const ut = mesh._uvTransform.mapCoord;

            u0 = ((uvs[index0] * ut.a) + (uvs[index0 + 1] * ut.c) + ut.tx) * base.width;
            u1 = ((uvs[index1] * ut.a) + (uvs[index1 + 1] * ut.c) + ut.tx) * base.width;
            u2 = ((uvs[index2] * ut.a) + (uvs[index2 + 1] * ut.c) + ut.tx) * base.width;
            v0 = ((uvs[index0] * ut.b) + (uvs[index0 + 1] * ut.d) + ut.ty) * base.height;
            v1 = ((uvs[index1] * ut.b) + (uvs[index1 + 1] * ut.d) + ut.ty) * base.height;
            v2 = ((uvs[index2] * ut.b) + (uvs[index2 + 1] * ut.d) + ut.ty) * base.height;
        }
        else
        {
            u0 = uvs[index0] * base.width;
            u1 = uvs[index1] * base.width;
            u2 = uvs[index2] * base.width;
            v0 = uvs[index0 + 1] * base.height;
            v1 = uvs[index1 + 1] * base.height;
            v2 = uvs[index2 + 1] * base.height;
        }

        let x0 = vertices[index0];
        let x1 = vertices[index1];
        let x2 = vertices[index2];
        let y0 = vertices[index0 + 1];
        let y1 = vertices[index1 + 1];
        let y2 = vertices[index2 + 1];

        if (mesh.canvasPadding > 0)
        {
            const paddingX = mesh.canvasPadding / mesh.worldTransform.a;
            const paddingY = mesh.canvasPadding / mesh.worldTransform.d;
            const centerX = (x0 + x1 + x2) / 3;
            const centerY = (y0 + y1 + y2) / 3;

            let normX = x0 - centerX;
            let normY = y0 - centerY;

            let dist = Math.sqrt((normX * normX) + (normY * normY));

            x0 = centerX + ((normX / dist) * (dist + paddingX));
            y0 = centerY + ((normY / dist) * (dist + paddingY));

            //

            normX = x1 - centerX;
            normY = y1 - centerY;

            dist = Math.sqrt((normX * normX) + (normY * normY));
            x1 = centerX + ((normX / dist) * (dist + paddingX));
            y1 = centerY + ((normY / dist) * (dist + paddingY));

            normX = x2 - centerX;
            normY = y2 - centerY;

            dist = Math.sqrt((normX * normX) + (normY * normY));
            x2 = centerX + ((normX / dist) * (dist + paddingX));
            y2 = centerY + ((normY / dist) * (dist + paddingY));
        }

        context.save();
        context.beginPath();

        context.moveTo(x0, y0);
        context.lineTo(x1, y1);
        context.lineTo(x2, y2);

        context.closePath();

        context.clip();

        // Compute matrix transform
        const delta = (u0 * v1) + (v0 * u2) + (u1 * v2) - (v1 * u2) - (v0 * u1) - (u0 * v2);
        const deltaA = (x0 * v1) + (v0 * x2) + (x1 * v2) - (v1 * x2) - (v0 * x1) - (x0 * v2);
        const deltaB = (u0 * x1) + (x0 * u2) + (u1 * x2) - (x1 * u2) - (x0 * u1) - (u0 * x2);
        const deltaC = (u0 * v1 * x2) + (v0 * x1 * u2) + (x0 * u1 * v2) - (x0 * v1 * u2) - (v0 * u1 * x2) - (u0 * x1 * v2);
        const deltaD = (y0 * v1) + (v0 * y2) + (y1 * v2) - (v1 * y2) - (v0 * y1) - (y0 * v2);
        const deltaE = (u0 * y1) + (y0 * u2) + (u1 * y2) - (y1 * u2) - (y0 * u1) - (u0 * y2);
        const deltaF = (u0 * v1 * y2) + (v0 * y1 * u2) + (y0 * u1 * v2) - (y0 * v1 * u2) - (v0 * u1 * y2) - (u0 * y1 * v2);

        context.transform(
            deltaA / delta,
            deltaD / delta,
            deltaB / delta,
            deltaE / delta,
            deltaC / delta,
            deltaF / delta
        );

        context.drawImage(
            textureSource,
            0,
            0,
            textureWidth * base.resolution,
            textureHeight * base.resolution,
            0,
            0,
            textureWidth,
            textureHeight
        );

        context.restore();
        this.renderer.invalidateBlendMode();
    }

    /**
     * Renders a flat Mesh
     *
     * @private
     * @param {PIXI.mesh.Mesh} mesh - The Mesh to render
     */
    renderMeshFlat(mesh)
    {
        const context = this.renderer.context;
        const vertices = mesh.vertices;
        const length = vertices.length / 2;

        // this.count++;

        context.beginPath();

        for (let i = 1; i < length - 2; ++i)
        {
            // draw some triangles!
            const index = i * 2;

            const x0 = vertices[index];
            const y0 = vertices[index + 1];

            const x1 = vertices[index + 2];
            const y1 = vertices[index + 3];

            const x2 = vertices[index + 4];
            const y2 = vertices[index + 5];

            context.moveTo(x0, y0);
            context.lineTo(x1, y1);
            context.lineTo(x2, y2);
        }

        context.fillStyle = '#FF0000';
        context.fill();
        context.closePath();
    }

    /**
     * destroy the the renderer.
     *
     */
    destroy()
    {
        this.renderer = null;
    }
}

core.CanvasRenderer.registerPlugin('mesh', MeshSpriteRenderer);
<|endoftext|>


<commit_before>describe('Test Suite for Data Source plugin', function() {
    var appSetup = null,
        appConf = null;

    var mapModule = null,
        plugin = null,
        pluginDiv = null,
        localization = null,
        selectedLayers = [];

    before(function() {
        // startup the oskari application with publisher bundle, 2 test layers and signed in user
        appSetup = getStartupSequence([
            'openlayers-default-theme',
            'mapfull',
            'divmanazer'
        ]);

        var mapfullConf = getConfigForMapfull();

        mapfullConf.conf.plugins.push({
            "id": "Oskari.mapframework.bundle.mapmodule.plugin.DataSourcePlugin"
        });
        // add some test layers
        mapfullConf.conf.layers.push({
            "type": "wmslayer",
            "id": "34",
            "metaType": "test",
            "orgName" : "Test organization",
            "dataUrl_uuid" : "testuuid",
            "name": "Test layer 1",
            "wmsName": "testlayer",
            "type": "wmslayer",
            "wmsUrl": "http://dummyUrl"
        });
        mapfullConf.conf.layers.push({
            "type": "wmslayer",
            "id": "35",
            "metaType": "test",
            "name": "Test layer 2",
            "orgName" : "Test organization",
            "wmsName": "testlayer",
            "type": "wmslayer",
            "permissions" : {
                "publish" : "publication_permission_ok"
            },
            "wmsUrl": "http://dummyUrl"
        });
        appConf = {
            "mapfull" : mapfullConf
        };
    });

    var startApplication = function(done) {
        //setup HTML
        jQuery("body").html(getDefaultHTML());
        // startup Oskari
        setupOskari(appSetup, appConf, function() {
            sandbox = Oskari.$("sandbox");
			mapModule = sandbox.findRegisteredModuleInstance('MainMapModule');
            plugin = mapModule.getPluginInstance('DataSourcePlugin');
            localization = mapModule.getLocalization('plugin')['DataSourcePlugin'];
            pluginDiv = jQuery('div.oskari-datasource');
            done();
        });
    };

    describe('should have', function() {

        before(function(done) {
            startApplication(done);
        });

        after(function() {
            teardown();
        });

        it("plugin setup correctly", function() {
            expect(plugin.getName()).to.be('MainMapModuleDataSourcePlugin');
        });

        it("an UI", function() {
            expect(pluginDiv.length).to.be(1);
        });

        it("a link in the UI", function() {
            var link = pluginDiv.find('a');
            expect(link.length).to.be(1);
        });

        it("a dialog open from the link", function() {
            var linkSpy = sinon.spy(plugin, '_openDialog');
            var link = pluginDiv.find('a');
            link.click();
            expect(linkSpy.callCount).to.be(1);
        });
    });

    describe('should display popup', function() {

        var dialogContent = null;

        before(function(done) {
            startApplication(function() {
                selectedLayers = addLayers(mapModule, [34,35]);

                var link = pluginDiv.find('a');
                link.click();
                dialogContent = jQuery('div.divmanazerpopup');

                done();
            });

        });

        after(function() {
            teardown();
        });

        it("with heading", function() {
            var heading = dialogContent.find("h3:contains('" + localization.popup.title + "')");
            expect(heading.length).to.be(1);
        });

        it("with 3 selected layers", function() {
            expect(selectedLayers.length).to.be(3);
        });

        it("with organization heading matching selected layers listing", function() {

            var heading = dialogContent.find("b:contains('" + selectedLayers[1].getOrganizationName() + "')");
            expect(heading.length).to.be(1);
        });

        it("with 3 layers listed", function() {
            var items = dialogContent.find("li");
            expect(items.length).to.be(3);
        });

        it("with 1 metadata link", function() {
            var items = dialogContent.find("div.icon-info");
            expect(items.length).to.be(1);
        });

    });
});<commit_msg>[AL-900] more specific layer testing<commit_after>describe('Test Suite for Data Source plugin', function() {
    var appSetup = null,
        appConf = null;

    var mapModule = null,
        plugin = null,
        pluginDiv = null,
        localization = null,
        selectedLayers = [];

    before(function() {
        // startup the oskari application with publisher bundle, 2 test layers and signed in user
        appSetup = getStartupSequence([
            'openlayers-default-theme',
            'mapfull',
            'divmanazer'
        ]);

        var mapfullConf = getConfigForMapfull();

        mapfullConf.conf.plugins.push({
            "id": "Oskari.mapframework.bundle.mapmodule.plugin.DataSourcePlugin"
        });
        // add some test layers
        mapfullConf.conf.layers.push({
            "type": "wmslayer",
            "id": "34",
            "metaType": "test",
            "orgName" : "Test organization",
            "dataUrl_uuid" : "testuuid",
            "name": "Test layer 1",
            "wmsName": "testlayer",
            "type": "wmslayer",
            "wmsUrl": "http://dummyUrl"
        });
        mapfullConf.conf.layers.push({
            "type": "wmslayer",
            "id": "35",
            "metaType": "test",
            "name": "Test layer 2",
            "orgName" : "Test organization",
            "wmsName": "testlayer",
            "type": "wmslayer",
            "permissions" : {
                "publish" : "publication_permission_ok"
            },
            "wmsUrl": "http://dummyUrl"
        });
        appConf = {
            "mapfull" : mapfullConf
        };
    });

    var startApplication = function(done) {
        //setup HTML
        jQuery("body").html(getDefaultHTML());
        // startup Oskari
        setupOskari(appSetup, appConf, function() {
            sandbox = Oskari.$("sandbox");
			mapModule = sandbox.findRegisteredModuleInstance('MainMapModule');
            plugin = mapModule.getPluginInstance('DataSourcePlugin');
            localization = mapModule.getLocalization('plugin')['DataSourcePlugin'];
            pluginDiv = jQuery('div.oskari-datasource');
            done();
        });
    };

    describe('should have', function() {

        before(function(done) {
            startApplication(done);
        });

        after(function() {
            teardown();
        });

        it("plugin setup correctly", function() {
            expect(plugin.getName()).to.be('MainMapModuleDataSourcePlugin');
        });

        it("an UI", function() {
            expect(pluginDiv.length).to.be(1);
        });

        it("a link in the UI", function() {
            var link = pluginDiv.find('a');
            expect(link.length).to.be(1);
        });

        it("a dialog open from the link", function() {
            var linkSpy = sinon.spy(plugin, '_openDialog');
            var link = pluginDiv.find('a');
            link.click();
            expect(linkSpy.callCount).to.be(1);
        });
    });

    describe('should display popup', function() {

        var dialogContent = null;

        before(function(done) {
            startApplication(function() {
                selectedLayers = addLayers(mapModule, [34,35]);

                var link = pluginDiv.find('a');
                link.click();
                dialogContent = jQuery('div.divmanazerpopup');

                done();
            });

        });

        after(function() {
            teardown();
        });

        it("with heading", function() {
            var heading = dialogContent.find("h3:contains('" + localization.popup.title + "')");
            expect(heading.length).to.be(1);
        });

        it("with 3 selected layers", function() {
            expect(selectedLayers.length).to.be(3);
        });

        it("with organization heading matching test layer organization", function() {
            var testLayer34 = sandbox.findMapLayerFromSelectedMapLayers(34);
            var heading = dialogContent.find("b:contains('" + testLayer34.getOrganizationName() + "')");
            expect(heading.length).to.be(1);
        });

        it("with 3 layers listed", function() {
            var items = dialogContent.find("li");
            expect(items.length).to.be(3);
        });

        it("with 1 metadata link", function() {
            var items = dialogContent.find("div.icon-info");
            expect(items.length).to.be(1);
        });

    });
});<|endoftext|>


<commit_before>/*!
* jQuery Sticky Alert v0.1.4
* https://github.com/tlongren/jquery-sticky-alert
*
* Released under the MIT license.
* http://jquery.org/license
*
* Date: November 16, 2016
*/
(function($){

  $.fn.extend({

    stickyalert: function(options) {

      var defaults = {
          barColor: '#222',
          barFontColor: '#FFF',
          barFontSize: '1.1rem',
          barText: 'I like bass and car audio :)',
          barTextLink: 'https://www.longren.io/',
          cookieRememberDays: '2'
      };

      var options = $.extend(defaults, options);

      return this.each(function() {

          if (document.cookie.indexOf("jqsa") >= 0) {

            $('.alert-box').remove();

        }

        else {
          // show the alert
          var alertBar = '
' + options.barText + '✖
';
          var parent_id = $(this).closest("div").prop("id");
          setTimeout(function () {
            $("#" + parent_id).append(alertBar);
          }, options.displayDelay);

          $(".alert-box").delegate("a.close", "click", function(event) {

            event.preventDefault();

            $(this).closest(".alert-box").fadeOut(function(event){

              $(this).remove();

              // set a new cookie
              if (options.cookieRememberDays === 0) {

                // do nothing

              }

              else {

                var hidefor =  60 * 60 * 24 * options.cookieRememberDays;

                document.cookie = "jqsa=closed;max-age=" + hidefor;

              }

            });

          });

        }

      });

    }

  });

})(jQuery);<commit_msg>💄 Uhh, indentation.<commit_after>/*!
* jQuery Sticky Alert v0.1.4
* https://github.com/tlongren/jquery-sticky-alert
*
* Copyright 2016 Tyler Longren
* Released under the MIT license.
* http://jquery.org/license
*
* Date: November 16, 2016
*/
(function($){

  $.fn.extend({

    stickyalert: function(options) {

      var defaults = {
        barColor: '#222', // alert background color
        barFontColor: '#FFF', // text font color
        barFontSize: '1.1rem', // text font size
        barText: 'I like bass and car audio :)', // the text to display, linked with barTextLink
        barTextLink: 'https://www.longren.io/', // url for anchor
        cookieRememberDays: '2', // in days
        displayDelay: '3000' // in milliseconds, 3 second default
      };

      var options = $.extend(defaults, options);

      return this.each(function() {

        if (document.cookie.indexOf("jqsa") >= 0) {

          $('.alert-box').remove();

        }

        else {
          // show the alert
          var alertBar = '
' + options.barText + '✖
';
          var parent_id = $(this).closest("div").prop("id");
          setTimeout(function () {
            $("#" + parent_id).append(alertBar);
          }, options.displayDelay);

          // close the alert
          $(".alert-box").delegate("a.close", "click", function(event) {
            event.preventDefault();
            $(this).closest(".alert-box").fadeOut(function(event){
              $(this).remove();
              // set a new cookie
              if (options.cookieRememberDays === 0) {
                // do nothing
              }

              else {
                var hidefor =  60 * 60 * 24 * options.cookieRememberDays;
                document.cookie = "jqsa=closed;max-age=" + hidefor;
              }
            }, 'slow');
          });
        }
      });
    }
  });
})(jQuery);<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Link, Route } from 'react-router-dom';
import styled from 'styled-components';
import {
  SideHome,
  SideHomeActive,
  SideUpload,
  SideUploadActive,
  FlassLogo
} from './images';
import color from '../../../css/base/colors.scss';
import './Drawer.scss';

const FlassMark = styled.div`
  font-family: ArialRoundedMT;
  font-size: 3rem;
  font-weight: bold;
  text-align: center;
  color: ${color['light-navy']};
  padding-top: 2rem;
  padding-bottom: 2rem;
  width: 1.625rem;
`;

const FlassLogoImg = styled.img`
  width: 100%;
`;

const FlassMenu = styled(Link)`
  display: block;
  position: relative;
  width: 100%;
  height: 7rem;
  text-align: center;
  padding: 1rem 0;
`;

const FlassMenuImage = styled.img`
  max-height: 100%;
  max-width: 100%;
  width: 17px;
  height: auto;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
`;

const ClickLine = styled.div`
  width: 5px;
  height: 100%;
  border-radius: 100px;
  background-color: ${color['light-navy']};
  float: right;
`;

const propTypes = {
};

const defaultProps = {
};

class Drawer extends Component {
  render() {
    return (

        <Link to="/">
          <FlassMark>
            <FlassLogoImg srcSet={ FlassLogo } alt="Flass logo" />
          </FlassMark>
        </Link>
        <Route
          path="/home"
          children={({ match }) =>
            (
              <FlassMenu
                to="/home" >
                <FlassMenuImage alt="" width="17" src={ match ? SideHomeActive : SideHome } />
                {match && <ClickLine />}
              </FlassMenu>
            )} />
        <Route
          path="/upload"
          children={({ match }) =>
            (
              <FlassMenu
                to="/upload" >
                <FlassMenuImage alt="" width="17" src={ match ? SideUploadActive : SideUpload } />
                {match && <ClickLine />}
              </FlassMenu>
            )} />

    );
  }
}

Drawer.propTypes = propTypes;
Drawer.defaultProps = defaultProps;

export default Drawer;
<commit_msg>Flass 로고 css<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Link, Route } from 'react-router-dom';
import styled from 'styled-components';
import {
  SideHome,
  SideHomeActive,
  SideUpload,
  SideUploadActive,
  FlassLogo
} from './images';
import color from '../../../css/base/colors.scss';
import './Drawer.scss';

const FlassMark = styled.div`
  display: flex;
  padding-top: 2.8125rem;
  padding-bottom: 3rem;
`;

const FlassLogoImg = styled.img`
  margin: auto;
`;

const FlassMenu = styled(Link)`
  display: block;
  position: relative;
  width: 100%;
  height: 7rem;
  text-align: center;
  padding: 1rem 0;
`;

const FlassMenuImage = styled.img`
  max-height: 100%;
  max-width: 100%;
  width: 17px;
  height: auto;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
`;

const ClickLine = styled.div`
  width: 5px;
  height: 100%;
  border-radius: 100px;
  background-color: ${color['light-navy']};
  float: right;
`;

const propTypes = {
};

const defaultProps = {
};

class Drawer extends Component {
  render() {
    return (

        <Link to="/">
          <FlassMark>
            <FlassLogoImg srcSet={ FlassLogo } alt="Flass logo" />
          </FlassMark>
        </Link>
        <Route
          path="/home"
          children={({ match }) =>
            (
              <FlassMenu
                to="/home" >
                <FlassMenuImage alt="" width="17" src={ match ? SideHomeActive : SideHome } />
                {match && <ClickLine />}
              </FlassMenu>
            )} />
        <Route
          path="/upload"
          children={({ match }) =>
            (
              <FlassMenu
                to="/upload" >
                <FlassMenuImage alt="" width="17" src={ match ? SideUploadActive : SideUpload } />
                {match && <ClickLine />}
              </FlassMenu>
            )} />

    );
  }
}

Drawer.propTypes = propTypes;
Drawer.defaultProps = defaultProps;

export default Drawer;
<|endoftext|>


<commit_before>import FBSDK, { LoginManager } from 'react-native-fbsdk';
const { LoginButton, AccessToken, ShareDialog } = FBSDK;

export default facebookActions = {

    facebookAction: () => {
      return {
        type: 'IS_AUTHENTICATED',
        payload: AccessToken.getCurrentAccessToken()
        .then((data) => {
          console.log('facebook data change to became payload', data)
          return data
        })
        .catch((err) => {
          console.log(err);
        })
      }
    }
}
<commit_msg>facebook action for log in<commit_after>import FBSDK, { LoginManager } from 'react-native-fbsdk';
const { LoginButton, AccessToken, ShareDialog } = FBSDK;

export default facebookActions = {

    facebookAction: () => {
      return function(dispatch) {
        AccessToken.getCurrentAccessToken()
          .then((data) => {
            console.log('facebook data change to became payload', data)
            dispatch({type: 'IS_AUTHENTICATED', payload: data});
          })
          .catch((err) => {
            console.log('Error: ', err);
          })
      }
    }
}
<|endoftext|>


<commit_before>'use strict';

theToolController
  .controller('MemberController', function ($scope, $http, $routeParams, $sce, $location, MemberFactory) {
    $scope.getClassFromKind = function(participation) {
      if(!participation) { return "nope"; }
      if(!participation.kind) { return "sponsor"; }
      var kind = participation.kind.toLowerCase();

      if(kind.indexOf("bronze") != -1) { return "bronze"; }
      else if(kind.indexOf("prata") != -1) { return "silver"; }
      else { return "sponsor"; }
    }

    MemberFactory.Member.get({id: $routeParams.id}, function(response) {
      if($routeParams.id == "me") {
        var newPath = "/member/"+response.id;
        console.log("going to", newPath);
        $location.path(newPath);
      }
      $scope.member = response;
    });

    MemberFactory.Companies.getAll({id: $routeParams.id}, function(response) {
      $scope.companies = response;
    });
  });<commit_msg>fixing members<commit_after>'use strict';

theToolController
  .controller('MemberController', function ($scope, $http, $routeParams, $sce, $location, MemberFactory, CompanyFactory) {
    $scope.getClassFromKind = function(participation) {
      if(!participation) { return "nope"; }
      if(!participation.kind) { return "sponsor"; }
      var kind = participation.kind.toLowerCase();

      if(kind.indexOf("bronze") != -1) { return "bronze"; }
      else if(kind.indexOf("prata") != -1) { return "silver"; }
      else { return "sponsor"; }
    }

    MemberFactory.Member.get({id: $routeParams.id}, function(response) {
      if($routeParams.id == "me") {
        var newPath = "/member/"+response.id;
        console.log("going to", newPath);
        $location.path(newPath);
      }
      $scope.member = response;
    });

    CompanyFactory.Member.getAll({id: $routeParams.id}, function(response) {
      $scope.companies = response;
    });
  });<|endoftext|>


<commit_before>/* --------------------------------------------------------------------------- */
window.iNN = function (param, value) {
    if (param === null || param === undefined || param === false) {
        return null;
    } else {
        if (typeof(param) != 'object') {
            return value;
        } else {
            return param[value];
        } // end if
    } // end if
}; // end function "iNN"
/* --------------------------------------------------------------------------- */
window.arr2str = function (arr, limit, level, fields, i) {
    if (level === undefined) {level = 0;} // end if
    if (i === undefined) {i=''};
    //----------
    level++;
    if (limit !== undefined && level > limit) {return '';} // end if
    //----------
    var result='';
    //----------
    for (var k in arr) {
        if (fields !== undefined && fields.indexOf(k) == -1) {continue;} // end if
        //----------
        var value = arr[k];
        //----------
        result += ''+i+k+': ';
        if (typeof(value) == 'object') {
            if (AZ.isObject(value)) {
                result += '#'+AZ.getID(value)+'\n';
            } else {
                result += arr2str(value, limit, level, fields, i+'    ');
            } // end if
        } else if (typeof(value) == 'function') {
            result += 'function(...)\n';
        } else {
            result += value+'\n';
        }
    } // end for
    //----------
    return result;
}; // end function "arr2str"
/* --------------------------------------------------------------------------- */
window.add_arr2arr = function (_arr, _values) {
    for (var x=0; x<_values.length; x++) {
        if (_arr.indexOf(_values[x]) == -1) {_arr.push(_values[x]);} // end if
    } // end for
}; // end function "add_arr2arr"
/* --------------------------------------------------------------------------- */
window.arr2arr = function (from) {
    var result = {};
    //----------
    for (var k in from) {
        result[k] = from[k];
    } // end for
    //----------
    return result;
}; // end function "arr2arr"
/* --------------------------------------------------------------------------- */
window.any2arr = function (_param, _add_null) {
    //----------
    if (_param === undefined) {
        _param = (_add_null == false ? [] : [null]);

    } else if (_param === null) {
        _param = (_add_null == false ? [] : [null]);

    } else if (typeof(_param) == 'string') {
        _param = (_param.trim() == '' && _add_null == false) ? [] : [_param];

    } else if (typeof(_param) == 'number') {
        _param = [_param];

    } else if (typeof(_param) == 'object') {
        if (_param.length === undefined) {
            _param = [_param];

        //} else if (AZ.isObject(_param) === true) {
        //    _param = [_param];

        }// end if
    } // end if
    //----------
    return _param;
}; // end function "any2arr"
/* --------------------------------------------------------------------------- */
/* ё2е("ёлка") — Возвращает слово, где Ё заменено на Е. */
window.ё2е = function (word) {
    return word.replace('ё', 'е');
}; // end function "ё2е"
/* --------------------------------------------------------------------------- */
window.length2symbol = function (_list) {
    //----------
    var value = typeof(_list) == 'number' ? _list : _list.length;
    //----------
    if (value == 0) {
        return 'N';
    } else if (value < 2) {
        return 'S';
    } else if (value > 1) {
        return 'P';
    } else {
        return null;
    } // end if
    //----------
}; // end function "any2arr"
/* --------------------------------------------------------------------------- */
window.object2table = function (data, result, fields, level, max, elem1) {
    // Начальная инициализация данных
        if (level == undefined)  {level = 0;} // end if
        //----------
        if (fields == undefined) {
            fields = [];
            for (var k in data)  {fields.push(k);} // end for
        } // end if
        //----------
        if (max == undefined)    {max = fields.length-1;} // end if
        //----------
        if (elem1 == undefined)  {elem1 = {};} // end if
        if (result == undefined) {result = [];} // end if
    //----------
    var field = fields[level];
    var value = data[field];
    //----------
    if (value === null || typeof(value) != 'object' || value.length === undefined) {
        value = [value];
    } // end if
    //----------
    var elem2 = {};
    for (var k in elem1) {elem2[k] = elem1[k];} // end for
    //----------
    for (var x=0; x<value.length; x++) {
        var value2 = value[x];
        //----------
        elem2[field] = value2;
        //----------
        if (level == max) {
            var elem3 = {};
            for (var k in elem2) {elem3[k] = elem2[k];} // end for
            result.push(elem3);
        } else {
            object2table(data, result, fields, level+1, max, elem2);
        } // end if
    } // end for
    //----------
} // end function "next_level"
//----------
window.text2html = function (_text) {
    //----------
    _text = _text.replace(/^\s+/gm, '\n');
    _text = markdown.makeHtml(_text);
    _text = typograph.execute(_text);
    //----------
    return _text;
    //----------
}; // end function "text2html"
/* --------------------------------------------------------------------------- */
window.param2data = function (_param, _data) {
    var result = {};
    //----------
    if (_param !== undefined) {
        if (typeof(_param) == 'object' && _param != null) {
            for (var k in _param) {
                result[k] = _param[k];
            } // end for
        } else {
            result['параметр'] = _param;
        } // end if
    } // end if
    //----------
    if (_data !== undefined) {
        for (var k in _data) {
            result[k] = _data[k];
        } // end for
    } // end if
    //----------
    return result;
}; // end function "iNN"
/* --------------------------------------------------------------------------- */

<commit_msg>Az: checkFuncDuration function<commit_after>/* --------------------------------------------------------------------------- */
window.iNN = function (param, value) {
    if (param === null || param === undefined || param === false) {
        return null;
    } else {
        if (typeof(param) != 'object') {
            return value;
        } else {
            return param[value];
        } // end if
    } // end if
}; // end function "iNN"
/* --------------------------------------------------------------------------- */
window.arr2str = function (arr, limit, level, fields, i) {
    if (level === undefined) {level = 0;} // end if
    if (i === undefined) {i=''};
    //----------
    level++;
    if (limit !== undefined && level > limit) {return '';} // end if
    //----------
    var result='';
    //----------
    for (var k in arr) {
        if (fields !== undefined && fields.indexOf(k) == -1) {continue;} // end if
        //----------
        var value = arr[k];
        //----------
        result += ''+i+k+': ';
        if (typeof(value) == 'object') {
            if (AZ.isObject(value)) {
                result += '#'+AZ.getID(value)+'\n';
            } else {
                result += arr2str(value, limit, level, fields, i+'    ');
            } // end if
        } else if (typeof(value) == 'function') {
            result += 'function(...)\n';
        } else {
            result += value+'\n';
        }
    } // end for
    //----------
    return result;
}; // end function "arr2str"
/* --------------------------------------------------------------------------- */
window.add_arr2arr = function (_arr, _values) {
    for (var x=0; x<_values.length; x++) {
        if (_arr.indexOf(_values[x]) == -1) {_arr.push(_values[x]);} // end if
    } // end for
}; // end function "add_arr2arr"
/* --------------------------------------------------------------------------- */
window.arr2arr = function (from) {
    var result = {};
    //----------
    for (var k in from) {
        result[k] = from[k];
    } // end for
    //----------
    return result;
}; // end function "arr2arr"
/* --------------------------------------------------------------------------- */
window.any2arr = function (_param, _add_null) {
    //----------
    if (_param === undefined) {
        _param = (_add_null == false ? [] : [null]);

    } else if (_param === null) {
        _param = (_add_null == false ? [] : [null]);

    } else if (typeof(_param) == 'string') {
        _param = (_param.trim() == '' && _add_null == false) ? [] : [_param];

    } else if (typeof(_param) == 'number') {
        _param = [_param];

    } else if (typeof(_param) == 'object') {
        if (_param.length === undefined) {
            _param = [_param];

        //} else if (AZ.isObject(_param) === true) {
        //    _param = [_param];

        }// end if
    } // end if
    //----------
    return _param;
}; // end function "any2arr"
/* --------------------------------------------------------------------------- */
/* ё2е("ёлка") — Возвращает слово, где Ё заменено на Е. */
window.ё2е = function (word) {
    return word.replace('ё', 'е');
}; // end function "ё2е"
/* --------------------------------------------------------------------------- */
window.length2symbol = function (_list) {
    //----------
    var value = typeof(_list) == 'number' ? _list : _list.length;
    //----------
    if (value == 0) {
        return 'N';
    } else if (value < 2) {
        return 'S';
    } else if (value > 1) {
        return 'P';
    } else {
        return null;
    } // end if
    //----------
}; // end function "any2arr"
/* --------------------------------------------------------------------------- */
window.object2table = function (data, result, fields, level, max, elem1) {
    // Начальная инициализация данных
        if (level == undefined)  {level = 0;} // end if
        //----------
        if (fields == undefined) {
            fields = [];
            for (var k in data)  {fields.push(k);} // end for
        } // end if
        //----------
        if (max == undefined)    {max = fields.length-1;} // end if
        //----------
        if (elem1 == undefined)  {elem1 = {};} // end if
        if (result == undefined) {result = [];} // end if
    //----------
    var field = fields[level];
    var value = data[field];
    //----------
    if (value === null || typeof(value) != 'object' || value.length === undefined) {
        value = [value];
    } // end if
    //----------
    var elem2 = {};
    for (var k in elem1) {elem2[k] = elem1[k];} // end for
    //----------
    for (var x=0; x<value.length; x++) {
        var value2 = value[x];
        //----------
        elem2[field] = value2;
        //----------
        if (level == max) {
            var elem3 = {};
            for (var k in elem2) {elem3[k] = elem2[k];} // end for
            result.push(elem3);
        } else {
            object2table(data, result, fields, level+1, max, elem2);
        } // end if
    } // end for
    //----------
} // end function "next_level"
//----------
window.text2html = function (_text) {
    //----------
    _text = _text.replace(/^\s+/gm, '\n');
    _text = markdown.makeHtml(_text);
    _text = typograph.execute(_text);
    //----------
    return _text;
    //----------
}; // end function "text2html"
/* --------------------------------------------------------------------------- */
window.param2data = function (_param, _data) {
    var result = {};
    //----------
    if (_param !== undefined) {
        if (typeof(_param) == 'object' && _param != null) {
            for (var k in _param) {
                result[k] = _param[k];
            } // end for
        } else {
            result['параметр'] = _param;
        } // end if
    } // end if
    //----------
    if (_data !== undefined) {
        for (var k in _data) {
            result[k] = _data[k];
        } // end for
    } // end if
    //----------
    return result;
}; // end function "iNN"
/* --------------------------------------------------------------------------- */

window.checkFuncDuration = function (func) {
    var start = new Date().getTime(),
        finish;

    func();
    finish = new Date().getTime();
    console.log(func.name + ' выполнилась за ' + (finish - start) + ' миллисекунд.')
};
<|endoftext|>


<commit_before><commit_msg>Create 211. Add and Search Word - Data structure design.js<commit_after><|endoftext|>


<commit_before>// @flow
import React from "react";

// $FlowFixMe: our flow config isn't picking up modules that package separate .js.flow files
import JSONTransform from "@nteract/transforms/lib/json";
// $FlowFixMe: our flow config isn't picking up modules that package separate .js.flow files
import HTML from "@nteract/transforms/lib/html";
// $FlowFixMe: our flow config isn't picking up modules that package separate .js.flow files
import Text from "@nteract/transforms/lib/text";

// $FlowFixMe: our flow config isn't picking up modules that package separate .js.flow files
import Editor from "@nteract/notebook-preview/lib/editor";

const HokeyTable = props =>

          {props.columnNames.map(column =>

              {column.name}

          )}

        {props.rows.map((row, idx) =>

            {row.map((item, colIdx) =>

                {item}

            )}

        )}

;

const UnsupportedResult = props =>

UNSUPPORTED ZEPPELIN RESULT

      Post an issue to{" "}

        commuter
      {" "}
      to let us know about it

    <JSONTransform data={props.result} />

;

const Result = props => {
  if (!props.result || props.result.msg === "") {
    return null;
  }
  if (!props.result.msg) {
    return <UnsupportedResult result={props.result} />;
  }

  switch (props.result.type) {
    case "HTML":
      return ;
    case "TEXT":
      return <Text data={props.result.msg} />;
    case "TABLE":
      if (!props.result.columnNames || !props.result.rows) {
        return <UnsupportedResult result={props.result} />;
      }
      return (
        <HokeyTable
          columnNames={props.result.columnNames}
          rows={props.result.rows}
        />
      );
    default:
      return <UnsupportedResult result={props.result} />;
  }
};

const whichLanguage = source => {
  if (/^%md/.test(source)) {
    return "markdown";
  }

  if (/^%sql/.test(source)) {
    return "text/x-hive";
  }

  if (/^%pig/.test(source)) {
    return "pig";
  }

  if (
    /^%spark\.pyspark/.test(source) ||
    /^%pyspark/.test(source) ||
    /^%python/.test(source)
  ) {
    return "python";
  }

  if (/^%sh/.test(source)) {
    return "shell";
  }

  if (/^%spark/.test(source)) {
    return "text/x-scala";
  }

  if (/^%r/.test(source)) {
    return "r";
  }

  if (/^%html/.test(source)) {
    return "html";
  }

  return "text/x-scala";
};

const Paragraph = props => {
  const lang = whichLanguage(props.text);
  if (lang === "markdown") {
    return (

        <Result result={props.result} />

    );
  }

  return (

      <Editor
        completion
        input={props.text}
        language={lang}
        theme="composition"
        cellFocused={false}
        onChange={() => {}}
        onFocusChange={() => {}}
        channels={{}}
        cursorBlinkRate={0}
        executionState={"not connected"}
        editorFocused={false}
        focusAbove={() => {}}
        focusBelow={() => {}}
        style={{
          paddingBottom: "10px",
          paddingTop: "10px"
        }}
      />

        <Result result={props.result} />

  );
};

type ZeppelinViewProps = {
  notebook: {
    name: string,
    paragraphs: Array<ZParagraph>
  }
};

type ZParagraph = any;

const ZeppelinView = (props: ZeppelinViewProps) => {
  return (

        {props.notebook.name}

      {props.notebook.paragraphs.map(p => <Paragraph key={p.id} {...p} />)}

  );
};

export default ZeppelinView;
<commit_msg>handle older zeppelin notebook formats<commit_after>// @flow
import React from "react";

// $FlowFixMe: our flow config isn't picking up modules that package separate .js.flow files
import JSONTransform from "@nteract/transforms/lib/json";
// $FlowFixMe: our flow config isn't picking up modules that package separate .js.flow files
import HTML from "@nteract/transforms/lib/html";

// $FlowFixMe: our flow config isn't picking up modules that package separate .js.flow files
import Editor from "@nteract/notebook-preview/lib/editor";

const d3 = Object.assign({}, require("d3-dsv"));

const Text = (props: { data: string }) =>

      {props.data}

;

const HokeyTable = props =>

          {props.columnNames.map(column =>

              {column.name}

          )}

        {props.rows.map((row, idx) =>

            {row.map((item, colIdx) =>

                {item}

            )}

        )}

;

const DSVTable = (props: { data: Array<Object> }) => {
  if (!Array.isArray(props.data) || props.data.length <= 0) {
    return null;
  }

  const columnNames = Object.keys(props.data[0]);
  const rows = props.data;

  return (

            {columnNames.map((column, idx) =>

                {column}

            )}

          {rows.map((row, idx) =>

              {columnNames.map((k, colIdx) =>

                  {row[k]}

              )}

          )}

  );
};

const UnsupportedResult = props =>

UNSUPPORTED ZEPPELIN RESULT

      Post an issue to{" "}

        commuter
      {" "}
      to let us know about it

    <JSONTransform data={props.result} />

;

// Old style Zeppelin
const Message = props => {
  switch (props.type) {
    case "HTML":
      return ;
    case "TEXT":
      return <Text data={props.data} />;
    default:
      return null;
  }
};

const Result = props => {
  if (!props.result || props.result.msg === "") {
    return null;
  }

  switch (props.result.type) {
    case "HTML":
      return ;
    case "TEXT":
      return <Text data={props.result.msg} />;
    case "TABLE":
      if (!props.result.columnNames || !props.result.rows) {
        const data = d3.tsvParse(props.result.msg);
        const columnNames = Object.keys(data[0]);

        return <DSVTable data={data} />;
      }
      return (
        <HokeyTable
          columnNames={props.result.columnNames}
          rows={props.result.rows}
        />
      );
    default:
      return null;
  }
};

const whichLanguage = source => {
  if (/^%md/.test(source)) {
    return "markdown";
  }

  if (/^%sql/.test(source)) {
    return "text/x-hive";
  }

  if (/^%pig/.test(source)) {
    return "pig";
  }

  if (
    /^%spark\.pyspark/.test(source) ||
    /^%pyspark/.test(source) ||
    /^%python/.test(source)
  ) {
    return "python";
  }

  if (/^%sh/.test(source)) {
    return "shell";
  }

  if (/^%spark/.test(source)) {
    return "text/x-scala";
  }

  if (/^%r/.test(source)) {
    return "r";
  }

  if (/^%html/.test(source)) {
    return "html";
  }

  return "text/x-scala";
};

const Paragraph = props => {
  const lang = whichLanguage(props.text);

  let resultView = null;
  if (props.result) {
    resultView = <Result result={props.result} />;
  } else if (props.results && Array.isArray(props.results.msg)) {
    resultView = (

        {props.results.msg.map((item, idx) => <Message {...item} key={idx} />)}

    );
  }

  if (lang === "markdown") {
    return (

        {resultView}

    );
  }

  return (

      <Editor
        completion
        input={props.text}
        language={lang}
        theme="composition"
        cellFocused={false}
        onChange={() => {}}
        onFocusChange={() => {}}
        channels={{}}
        cursorBlinkRate={0}
        executionState={"not connected"}
        editorFocused={false}
        focusAbove={() => {}}
        focusBelow={() => {}}
        style={{
          paddingBottom: "10px",
          paddingTop: "10px"
        }}
      />

        {resultView}

  );
};

type ZeppelinViewProps = {
  notebook: {
    name: string,
    paragraphs: Array<ZParagraph>
  }
};

type ZParagraph = any;

const ZeppelinView = (props: ZeppelinViewProps) => {
  return (

        {props.notebook.name}

      {props.notebook.paragraphs.map(p => <Paragraph key={p.id} {...p} />)}

  );
};

export default ZeppelinView;
<|endoftext|>