<commit_before>/**
 * Copyright 2013-2021 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see https://www.jhipster.tech/
 * for more information.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

const { MONOLITH, MICROSERVICE, GATEWAY } = require('./application-types');
const { COUCHBASE, CASSANDRA, MONGODB, NO } = require('./database-types');
const { OptionNames, OptionValues } = require('./application-options');

const {
  APPLICATION_TYPE,
  AUTHENTICATION_TYPE,
  BASE_NAME,
  BUILD_TOOL,
  CACHE_PROVIDER,
  CLIENT_FRAMEWORK,
  CLIENT_PACKAGE_MANAGER,
  CLIENT_THEME,
  CLIENT_THEME_VARIANT,
  WITH_ADMIN_UI,
  DATABASE_TYPE,
  DEV_DATABASE_TYPE,
  DTO_SUFFIX,
  ENABLE_HIBERNATE_CACHE,
  ENABLE_SWAGGER_CODEGEN,
  ENABLE_TRANSLATION,
  ENTITY_SUFFIX,
  JHI_PREFIX,
  LANGUAGES,
  MESSAGE_BROKER,
  PACKAGE_FOLDER,
  PACKAGE_NAME,
  PROD_DATABASE_TYPE,
  REACTIVE,
  SEARCH_ENGINE,
  SERVER_PORT,
  SERVICE_DISCOVERY_TYPE,
  SKIP_CLIENT,
  SKIP_SERVER,
  SKIP_USER_MANAGEMENT,
  TEST_FRAMEWORKS,
  USE_NPM,
  WEBSOCKET,
} = OptionNames;

module.exports = {
  getConfigForMonolithApplication,
  getConfigForGatewayApplication,
  getConfigForMicroserviceApplication,
  getDefaultConfigForNewApplication,
  getConfigForApplicationType,
};

function getConfigForApplicationType(applicationType = undefined, customOptions = {}) {
  if (applicationType === MONOLITH) {
    return getConfigForMonolithApplication(customOptions);
  }
  if (applicationType === GATEWAY) {
    return getConfigForGatewayApplication(customOptions);
  }
  if (applicationType === MICROSERVICE) {
    return getConfigForMicroserviceApplication(customOptions);
  }
  return getDefaultConfigForNewApplication(customOptions);
}

function getConfigForMonolithApplication(customOptions = {}) {
  const options = {
    [AUTHENTICATION_TYPE]: OptionValues[AUTHENTICATION_TYPE].jwt,
    [CACHE_PROVIDER]: OptionValues[CACHE_PROVIDER].ehcache,
    [CLIENT_FRAMEWORK]: OptionValues[CLIENT_FRAMEWORK].angularX,
    [SERVER_PORT]: OptionValues[SERVER_PORT],
    [SERVICE_DISCOVERY_TYPE]: false,
    [SKIP_USER_MANAGEMENT]: OptionValues[SKIP_USER_MANAGEMENT],
    [WITH_ADMIN_UI]: true,
    ...customOptions,
  };
  if (!options[CLIENT_THEME]) {
    options[CLIENT_THEME] = OptionValues[CLIENT_THEME];
    options[CLIENT_THEME_VARIANT] = OptionValues[CLIENT_THEME_VARIANT].none;
  } else if (options[CLIENT_THEME] !== OptionValues[CLIENT_THEME] && !options[CLIENT_THEME_VARIANT]) {
    options[CLIENT_THEME_VARIANT] = OptionValues[CLIENT_THEME_VARIANT].default;
  }
  if (options[AUTHENTICATION_TYPE] === OptionValues[AUTHENTICATION_TYPE].oauth2) {
    options[SKIP_USER_MANAGEMENT] = true;
  }

  return {
    ...options,
    [APPLICATION_TYPE]: MONOLITH,
  };
}

function getConfigForGatewayApplication(customOptions = {}) {
  const options = {
    [AUTHENTICATION_TYPE]: OptionValues[AUTHENTICATION_TYPE].jwt,
    [CACHE_PROVIDER]: OptionValues[CACHE_PROVIDER].ehcache,
    [CLIENT_FRAMEWORK]: OptionValues[CLIENT_FRAMEWORK].angularX,
    [SERVER_PORT]: OptionValues[SERVER_PORT],
    [SERVICE_DISCOVERY_TYPE]: OptionValues[SERVICE_DISCOVERY_TYPE].eureka,
    [SKIP_USER_MANAGEMENT]: OptionValues[SKIP_USER_MANAGEMENT],
    [WITH_ADMIN_UI]: true,
    ...customOptions,
  };
  if (!options[CLIENT_THEME]) {
    options[CLIENT_THEME] = OptionValues[CLIENT_THEME];
    options[CLIENT_THEME_VARIANT] = OptionValues[CLIENT_THEME_VARIANT].none;
  } else if (options[CLIENT_THEME] !== OptionValues[CLIENT_THEME] && !options[CLIENT_THEME_VARIANT]) {
    options[CLIENT_THEME_VARIANT] = OptionValues[CLIENT_THEME_VARIANT].default;
  }
  if (options[AUTHENTICATION_TYPE] === OptionValues[AUTHENTICATION_TYPE].oauth2) {
    options[SKIP_USER_MANAGEMENT] = true;
  }
  if (options[SERVICE_DISCOVERY_TYPE] === false) {
    options[SERVICE_DISCOVERY_TYPE] = OptionValues[SERVICE_DISCOVERY_TYPE].eureka;
  }
  if (options[SERVICE_DISCOVERY_TYPE] === OptionValues[SERVICE_DISCOVERY_TYPE].no) {
    options[SERVICE_DISCOVERY_TYPE] = false;
  }
  return {
    ...options,
    [REACTIVE]: true,
    [APPLICATION_TYPE]: GATEWAY,
  };
}

function getConfigForMicroserviceApplication(customOptions = {}) {
  const DEFAULT_SERVER_PORT = '8081';
  const options = {
    [AUTHENTICATION_TYPE]: OptionValues[AUTHENTICATION_TYPE].jwt,
    [CACHE_PROVIDER]: OptionValues[CACHE_PROVIDER].hazelcast,
    [SERVER_PORT]: DEFAULT_SERVER_PORT,
    [SERVICE_DISCOVERY_TYPE]: OptionValues[SERVICE_DISCOVERY_TYPE].eureka,
    [SKIP_USER_MANAGEMENT]: true,
    ...customOptions,
  };
  delete options[CLIENT_FRAMEWORK];
  delete options[CLIENT_THEME];
  delete options[CLIENT_THEME_VARIANT];
  delete options[SKIP_SERVER];
  delete options[WITH_ADMIN_UI];
  if (typeof options[SKIP_USER_MANAGEMENT] !== 'boolean') {
    options[SKIP_USER_MANAGEMENT] = true;
  }
  if (options[SERVICE_DISCOVERY_TYPE] === false) {
    options[SERVICE_DISCOVERY_TYPE] = OptionValues[SERVICE_DISCOVERY_TYPE].eureka;
  }
  if (options[SERVICE_DISCOVERY_TYPE] === OptionValues[SERVICE_DISCOVERY_TYPE].no) {
    options[SERVICE_DISCOVERY_TYPE] = false;
  }
  return {
    ...options,
    [APPLICATION_TYPE]: MICROSERVICE,
    [SKIP_CLIENT]: true,
  };
}

function getDefaultConfigForNewApplication(customOptions = {}) {
  const options = {
    [BASE_NAME]: OptionValues[BASE_NAME],
    [BUILD_TOOL]: OptionValues[BUILD_TOOL].maven,
    [DATABASE_TYPE]: OptionValues[DATABASE_TYPE].sql,
    [DEV_DATABASE_TYPE]: OptionValues[DEV_DATABASE_TYPE].h2Disk,
    [CACHE_PROVIDER]: OptionValues[CACHE_PROVIDER].ehcache,
    [ENABLE_HIBERNATE_CACHE]: OptionValues[ENABLE_HIBERNATE_CACHE],
    [ENABLE_SWAGGER_CODEGEN]: OptionValues[ENABLE_SWAGGER_CODEGEN],
    [ENABLE_TRANSLATION]: OptionValues[ENABLE_TRANSLATION],
    [JHI_PREFIX]: OptionValues[JHI_PREFIX],
    [LANGUAGES]: OptionValues[LANGUAGES],
    [MESSAGE_BROKER]: OptionValues[MESSAGE_BROKER].false,
    [PROD_DATABASE_TYPE]: OptionValues[PROD_DATABASE_TYPE].postgresql,
    [SEARCH_ENGINE]: OptionValues[SEARCH_ENGINE].false,
    [SKIP_CLIENT]: OptionValues[SKIP_CLIENT],
    [TEST_FRAMEWORKS]: [],
    [WEBSOCKET]: OptionValues[WEBSOCKET].false,
    ...customOptions,
  };
  if (typeof options[SKIP_SERVER] !== 'boolean') {
    options[SKIP_SERVER] = OptionValues[SKIP_SERVER];
  }
  if (!options[PACKAGE_NAME] && !options[PACKAGE_FOLDER]) {
    options[PACKAGE_FOLDER] = OptionValues[PACKAGE_FOLDER];
    options[PACKAGE_NAME] = OptionValues[PACKAGE_NAME];
  }
  if (!options[PACKAGE_NAME] && options[PACKAGE_FOLDER]) {
    options[PACKAGE_NAME] = options[PACKAGE_FOLDER].replace(/\//g, '.');
  }
  if (!options[PACKAGE_FOLDER] && options[PACKAGE_NAME]) {
    options[PACKAGE_FOLDER] = options[PACKAGE_NAME].replace(/\./g, '/');
  }
  if (options[CLIENT_FRAMEWORK] === OptionValues[CLIENT_FRAMEWORK].angular) {
    options[CLIENT_FRAMEWORK] = OptionValues[CLIENT_FRAMEWORK].angularX;
  }
  if (!options[CLIENT_PACKAGE_MANAGER] && OptionValues[USE_NPM]) {
    options[CLIENT_PACKAGE_MANAGER] = OptionValues[CLIENT_PACKAGE_MANAGER].npm;
  }
  if (typeof options[DTO_SUFFIX] === 'boolean' || typeof options[DTO_SUFFIX] !== 'string') {
    options[DTO_SUFFIX] = OptionValues[DTO_SUFFIX];
  }
  if (typeof options[ENTITY_SUFFIX] === 'boolean' || typeof options[ENTITY_SUFFIX] !== 'string') {
    options[ENTITY_SUFFIX] = OptionValues[ENTITY_SUFFIX];
  }
  if ([MONGODB, COUCHBASE, CASSANDRA, NO].includes(options[DATABASE_TYPE])) {
    options[DEV_DATABASE_TYPE] = options[DATABASE_TYPE];
    options[PROD_DATABASE_TYPE] = options[DATABASE_TYPE];
    if (NO !== options[DATABASE_TYPE]) {
      options[ENABLE_HIBERNATE_CACHE] = false;
    }
  }
  if (options[REACTIVE]) {
    options[CACHE_PROVIDER] = OptionValues[CACHE_PROVIDER].no;
  } else {
    options[REACTIVE] = OptionValues[REACTIVE];
  }
  return options;
}
<commit_msg>Force cache provider to no, for Gateway with JDL<commit_after>/**
 * Copyright 2013-2021 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see https://www.jhipster.tech/
 * for more information.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

const { MONOLITH, MICROSERVICE, GATEWAY } = require('./application-types');
const { COUCHBASE, CASSANDRA, MONGODB, NO } = require('./database-types');
const { OptionNames, OptionValues } = require('./application-options');

const {
  APPLICATION_TYPE,
  AUTHENTICATION_TYPE,
  BASE_NAME,
  BUILD_TOOL,
  CACHE_PROVIDER,
  CLIENT_FRAMEWORK,
  CLIENT_PACKAGE_MANAGER,
  CLIENT_THEME,
  CLIENT_THEME_VARIANT,
  WITH_ADMIN_UI,
  DATABASE_TYPE,
  DEV_DATABASE_TYPE,
  DTO_SUFFIX,
  ENABLE_HIBERNATE_CACHE,
  ENABLE_SWAGGER_CODEGEN,
  ENABLE_TRANSLATION,
  ENTITY_SUFFIX,
  JHI_PREFIX,
  LANGUAGES,
  MESSAGE_BROKER,
  PACKAGE_FOLDER,
  PACKAGE_NAME,
  PROD_DATABASE_TYPE,
  REACTIVE,
  SEARCH_ENGINE,
  SERVER_PORT,
  SERVICE_DISCOVERY_TYPE,
  SKIP_CLIENT,
  SKIP_SERVER,
  SKIP_USER_MANAGEMENT,
  TEST_FRAMEWORKS,
  USE_NPM,
  WEBSOCKET,
} = OptionNames;

module.exports = {
  getConfigForMonolithApplication,
  getConfigForGatewayApplication,
  getConfigForMicroserviceApplication,
  getDefaultConfigForNewApplication,
  getConfigForApplicationType,
};

function getConfigForApplicationType(applicationType = undefined, customOptions = {}) {
  if (applicationType === MONOLITH) {
    return getConfigForMonolithApplication(customOptions);
  }
  if (applicationType === GATEWAY) {
    return getConfigForGatewayApplication(customOptions);
  }
  if (applicationType === MICROSERVICE) {
    return getConfigForMicroserviceApplication(customOptions);
  }
  return getDefaultConfigForNewApplication(customOptions);
}

function getConfigForMonolithApplication(customOptions = {}) {
  const options = {
    [AUTHENTICATION_TYPE]: OptionValues[AUTHENTICATION_TYPE].jwt,
    [CACHE_PROVIDER]: OptionValues[CACHE_PROVIDER].ehcache,
    [CLIENT_FRAMEWORK]: OptionValues[CLIENT_FRAMEWORK].angularX,
    [SERVER_PORT]: OptionValues[SERVER_PORT],
    [SERVICE_DISCOVERY_TYPE]: false,
    [SKIP_USER_MANAGEMENT]: OptionValues[SKIP_USER_MANAGEMENT],
    [WITH_ADMIN_UI]: true,
    ...customOptions,
  };
  if (!options[CLIENT_THEME]) {
    options[CLIENT_THEME] = OptionValues[CLIENT_THEME];
    options[CLIENT_THEME_VARIANT] = OptionValues[CLIENT_THEME_VARIANT].none;
  } else if (options[CLIENT_THEME] !== OptionValues[CLIENT_THEME] && !options[CLIENT_THEME_VARIANT]) {
    options[CLIENT_THEME_VARIANT] = OptionValues[CLIENT_THEME_VARIANT].default;
  }
  if (options[AUTHENTICATION_TYPE] === OptionValues[AUTHENTICATION_TYPE].oauth2) {
    options[SKIP_USER_MANAGEMENT] = true;
  }

  return {
    ...options,
    [APPLICATION_TYPE]: MONOLITH,
  };
}

function getConfigForGatewayApplication(customOptions = {}) {
  const options = {
    [AUTHENTICATION_TYPE]: OptionValues[AUTHENTICATION_TYPE].jwt,
    [CLIENT_FRAMEWORK]: OptionValues[CLIENT_FRAMEWORK].angularX,
    [SERVER_PORT]: OptionValues[SERVER_PORT],
    [SERVICE_DISCOVERY_TYPE]: OptionValues[SERVICE_DISCOVERY_TYPE].eureka,
    [SKIP_USER_MANAGEMENT]: OptionValues[SKIP_USER_MANAGEMENT],
    [WITH_ADMIN_UI]: true,
    ...customOptions,
  };
  if (!options[CLIENT_THEME]) {
    options[CLIENT_THEME] = OptionValues[CLIENT_THEME];
    options[CLIENT_THEME_VARIANT] = OptionValues[CLIENT_THEME_VARIANT].none;
  } else if (options[CLIENT_THEME] !== OptionValues[CLIENT_THEME] && !options[CLIENT_THEME_VARIANT]) {
    options[CLIENT_THEME_VARIANT] = OptionValues[CLIENT_THEME_VARIANT].default;
  }
  if (options[AUTHENTICATION_TYPE] === OptionValues[AUTHENTICATION_TYPE].oauth2) {
    options[SKIP_USER_MANAGEMENT] = true;
  }
  if (options[SERVICE_DISCOVERY_TYPE] === false) {
    options[SERVICE_DISCOVERY_TYPE] = OptionValues[SERVICE_DISCOVERY_TYPE].eureka;
  }
  if (options[SERVICE_DISCOVERY_TYPE] === OptionValues[SERVICE_DISCOVERY_TYPE].no) {
    options[SERVICE_DISCOVERY_TYPE] = false;
  }
  options[CACHE_PROVIDER] = OptionValues[CACHE_PROVIDER].no;
  return {
    ...options,
    [REACTIVE]: true,
    [APPLICATION_TYPE]: GATEWAY,
  };
}

function getConfigForMicroserviceApplication(customOptions = {}) {
  const DEFAULT_SERVER_PORT = '8081';
  const options = {
    [AUTHENTICATION_TYPE]: OptionValues[AUTHENTICATION_TYPE].jwt,
    [CACHE_PROVIDER]: OptionValues[CACHE_PROVIDER].hazelcast,
    [SERVER_PORT]: DEFAULT_SERVER_PORT,
    [SERVICE_DISCOVERY_TYPE]: OptionValues[SERVICE_DISCOVERY_TYPE].eureka,
    [SKIP_USER_MANAGEMENT]: true,
    ...customOptions,
  };
  delete options[CLIENT_FRAMEWORK];
  delete options[CLIENT_THEME];
  delete options[CLIENT_THEME_VARIANT];
  delete options[SKIP_SERVER];
  delete options[WITH_ADMIN_UI];
  if (typeof options[SKIP_USER_MANAGEMENT] !== 'boolean') {
    options[SKIP_USER_MANAGEMENT] = true;
  }
  if (options[SERVICE_DISCOVERY_TYPE] === false) {
    options[SERVICE_DISCOVERY_TYPE] = OptionValues[SERVICE_DISCOVERY_TYPE].eureka;
  }
  if (options[SERVICE_DISCOVERY_TYPE] === OptionValues[SERVICE_DISCOVERY_TYPE].no) {
    options[SERVICE_DISCOVERY_TYPE] = false;
  }
  return {
    ...options,
    [APPLICATION_TYPE]: MICROSERVICE,
    [SKIP_CLIENT]: true,
  };
}

function getDefaultConfigForNewApplication(customOptions = {}) {
  const options = {
    [BASE_NAME]: OptionValues[BASE_NAME],
    [BUILD_TOOL]: OptionValues[BUILD_TOOL].maven,
    [DATABASE_TYPE]: OptionValues[DATABASE_TYPE].sql,
    [DEV_DATABASE_TYPE]: OptionValues[DEV_DATABASE_TYPE].h2Disk,
    [CACHE_PROVIDER]: OptionValues[CACHE_PROVIDER].ehcache,
    [ENABLE_HIBERNATE_CACHE]: OptionValues[ENABLE_HIBERNATE_CACHE],
    [ENABLE_SWAGGER_CODEGEN]: OptionValues[ENABLE_SWAGGER_CODEGEN],
    [ENABLE_TRANSLATION]: OptionValues[ENABLE_TRANSLATION],
    [JHI_PREFIX]: OptionValues[JHI_PREFIX],
    [LANGUAGES]: OptionValues[LANGUAGES],
    [MESSAGE_BROKER]: OptionValues[MESSAGE_BROKER].false,
    [PROD_DATABASE_TYPE]: OptionValues[PROD_DATABASE_TYPE].postgresql,
    [SEARCH_ENGINE]: OptionValues[SEARCH_ENGINE].false,
    [SKIP_CLIENT]: OptionValues[SKIP_CLIENT],
    [TEST_FRAMEWORKS]: [],
    [WEBSOCKET]: OptionValues[WEBSOCKET].false,
    ...customOptions,
  };
  if (typeof options[SKIP_SERVER] !== 'boolean') {
    options[SKIP_SERVER] = OptionValues[SKIP_SERVER];
  }
  if (!options[PACKAGE_NAME] && !options[PACKAGE_FOLDER]) {
    options[PACKAGE_FOLDER] = OptionValues[PACKAGE_FOLDER];
    options[PACKAGE_NAME] = OptionValues[PACKAGE_NAME];
  }
  if (!options[PACKAGE_NAME] && options[PACKAGE_FOLDER]) {
    options[PACKAGE_NAME] = options[PACKAGE_FOLDER].replace(/\//g, '.');
  }
  if (!options[PACKAGE_FOLDER] && options[PACKAGE_NAME]) {
    options[PACKAGE_FOLDER] = options[PACKAGE_NAME].replace(/\./g, '/');
  }
  if (options[CLIENT_FRAMEWORK] === OptionValues[CLIENT_FRAMEWORK].angular) {
    options[CLIENT_FRAMEWORK] = OptionValues[CLIENT_FRAMEWORK].angularX;
  }
  if (!options[CLIENT_PACKAGE_MANAGER] && OptionValues[USE_NPM]) {
    options[CLIENT_PACKAGE_MANAGER] = OptionValues[CLIENT_PACKAGE_MANAGER].npm;
  }
  if (typeof options[DTO_SUFFIX] === 'boolean' || typeof options[DTO_SUFFIX] !== 'string') {
    options[DTO_SUFFIX] = OptionValues[DTO_SUFFIX];
  }
  if (typeof options[ENTITY_SUFFIX] === 'boolean' || typeof options[ENTITY_SUFFIX] !== 'string') {
    options[ENTITY_SUFFIX] = OptionValues[ENTITY_SUFFIX];
  }
  if ([MONGODB, COUCHBASE, CASSANDRA, NO].includes(options[DATABASE_TYPE])) {
    options[DEV_DATABASE_TYPE] = options[DATABASE_TYPE];
    options[PROD_DATABASE_TYPE] = options[DATABASE_TYPE];
    if (NO !== options[DATABASE_TYPE]) {
      options[ENABLE_HIBERNATE_CACHE] = false;
    }
  }
  if (options[REACTIVE]) {
    options[CACHE_PROVIDER] = OptionValues[CACHE_PROVIDER].no;
  } else {
    options[REACTIVE] = OptionValues[REACTIVE];
  }
  return options;
}
<|endoftext|>


<commit_before>var app = app || {};

app.Book = Backbone.Model.extend({
    defaults: {
        coverImage: 'img/placeholder.png',
        title: 'No title',
        author: 'Unknown',
        releaseDate: 'Unknown',
        keywords: 'None'
    }
});<commit_msg>Added parse method to the Book model, so the server _id is cp'd to the the needed id attribute that Backbone expects.<commit_after>var app = app || {};

app.Book = Backbone.Model.extend({
    defaults: {
        coverImage: 'img/placeholder.png',
        title: 'No title',
        author: 'Unknown',
        releaseDate: 'Unknown',
        keywords: 'None'
    },

    parse: function( response ) {
        response.id = response._id;
        return response;
    }
});<|endoftext|>


<commit_before>function gup( name )
{
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );
    if( results == null )
        return "";
    else
        return results[1];
}

Object.extend = function(destination, source) {
    for (var property in source)
        destination[property] = source[property];
    return destination;
};

var point1 = new OpenLayers.LonLat(19.3, 34.75);
var point2 = new OpenLayers.LonLat(29.65,41.8);
var bounds = new OpenLayers.Bounds();
bounds.extend(point1);
bounds.extend(point2);
bounds.transform(new OpenLayers.Projection("EPSG:4326"), new
OpenLayers.Projection("EPSG:900913"));
var map = null;
var apopup = null;
var ktimatologio = new OpenLayers.Layer.WMS("Υπόβαθρο «ΚΤΗΜΑΤΟΛΟΓΙΟ Α.Ε.»",
  "http://gis.ktimanet.gr/wms/wmsopen/wmsserver.aspx",
    {   layers: 'KTBASEMAP', transparent: false},
    {   isBaseLayer: true,
        projection: new OpenLayers.Projection("EPSG:900913"),
        iformat: 'image/png', maxExtent: bounds, numZoomLevels:
        15, units: "m", maxResolution: 900,
        attribution: ""});
var osm = new OpenLayers.Layer.OSM.Mapnik("Υπόβαθρο \"Open Street Map\"",{isBaseLayer: true,
        attribution: "Map by OSM"});
var ocm = new OpenLayers.Layer.OSM.CycleMap("Υπόβαθρο \"Open Cycle Map\"",{isBaseLayer: true,
        attribution: "Map by OSM"});
var base_layers = [ocm, osm, ktimatologio];
function InvokePopup(afeature) {
    apoint = afeature.geometry.getBounds().getCenterLonLat();
    map.panTo(apoint);
    $.get("/stations/b/"+afeature.attributes["id"]+'/', {}, function(data){
        var amessage = '';
        amessage=data;
        apopup = new OpenLayers.Popup(afeature.attributes["name"], apoint, new OpenLayers.Size(190,150), amessage, true);
        apopup.setBorder("2px solid");
        apopup.setBackgroundColor('#E0E0B0');
        map.addPopup(apopup, true);
    });
}
function CreateLayer(AName, ObjectName, AFillColor, AStrokeColor){
    if(map_mode==1){
        var params = {};
    }
    else if(map_mode==2){
        var params = {'gentity_id': agentity_id,};
    }
    var labelvalue = "";
    var labeling_opts = {
            label : labelvalue, fontColor: "#504065",
            fontSize: "9px", fontFamily: "Verdana, Arial",
            fontWeight: "bold", labelAlign: "cm"
    };
    var general_opts = {
            externalGraphic: MEDIA_URL+'images/marker.png',
            graphicWidth: 21, graphicHeight:25, graphicXOffset:-10,
            graphicYOffset: -25, fillOpacity: 1
    };
    general_opts = Object.extend(general_opts, labeling_opts);
    AURL = "/"+ObjectName+"/kml/";
    var alayer = new OpenLayers.Layer.WFS(AName, AURL, params,
    {   projection: new OpenLayers.Projection("EPSG:4326"),
//                    protocol: new OpenLayers.Protocol.HTTP(
//                    {url: AURL, format: new OpenLayers.Format.KML({ extractAttributes: true})}),
        format: OpenLayers.Format.KML,
        formatOptions: { extractAttributes:true },
//                    strategies: [new OpenLayers.Strategy.BBOX(), new
//                    OpenLayers.Strategy.Refresh()],
        styleMap: new OpenLayers.StyleMap({
            "default": new OpenLayers.Style(
                  OpenLayers.Util.applyDefaults(general_opts,
                        OpenLayers.Feature.Vector.style["default"])),
            "select": new OpenLayers.Style(
                  OpenLayers.Util.applyDefaults({
                        externalGraphic: MEDIA_URL+'images/selected_marker.png',
                        graphicWidth: 21, graphicHeight:25, graphicXOffset:-10,
                        graphicYOffset: -25, fillOpacity: 1},
                        OpenLayers.Feature.Vector.style["select"]))
        })
    } );
    alayer.events.register("loadstart", alayer,
        function() { ShowProgress(ObjectName); } );
    alayer.events.register("loadend", alayer,
        function() { HideProgress(ObjectName); } );
    alayer.events.register("loadcancel", alayer,
        function() { HideProgress(ObjectName); } );
    alayer.events.on({
        "featureselected": function(e) {
            InvokePopup(e.feature);
        },
        "featureunselected": function(e) {
            map.removePopup(apopup);
        }
    });
    return alayer;
}
var stations = CreateLayer("Σταθμοί", "stations", '#dd0022', '#990077');
var categories = [stations];
function init() {
    var options = {
        'units' :   "m",
        'numZoomLevels' :   15,
        'sphericalMercator': true,
        'maxExtent': bounds,
        'projection'    :   new OpenLayers.Projection("EPSG:9009313"),
        'displayProjection':    new OpenLayers.Projection("EPSG:4326")
    };
    map = new OpenLayers.Map('map', options);
    map.addControl(new OpenLayers.Control.ScaleLine());
    var ANavToolBar = new OpenLayers.Control.NavToolbar();
        map.addControl(ANavToolBar);
//    if(map_mode!=2)
//    {
        $("div.olControlNavToolbar").css("top","14px");
        $("div.olControlNavToolbar").css("left","11px");
/*    } else {
        $("div.olControlNavToolbar").css("top","-295px");
        $("div.olControlNavToolbar").css("left","340px");
        $("div.olControlNavToolbar").css("z-index","900");
    }*/
    pzb = new OpenLayers.Control.PanZoomBar();
    pzb.zoomWorldIcon = false;
    map.addControl(pzb);
    map.addControl(new OpenLayers.Control.MousePosition());
    map.addControl(new OpenLayers.Control.OverviewMap());
    ls = new OpenLayers.Control.LayerSwitcher();
    map.addControl(ls);
    map.addLayer(ocm);
    map.addLayer(osm);
    map.addLayer(ktimatologio);
    map.addLayers(categories);
    ls.baseLbl.innerHTML='Base layers';
    ls.dataLbl.innerHTML='Data layers';
    var labelButton = new OpenLayers.Control.Button({ type: OpenLayers.Control.TYPE_TOGGLE,
        title: "Show labels", displayClass: "LabelButtonClass" , trigger: function(){}});
    labelButton.events.register("activate", labelButton,
        function() { setLayersLabels(true); } );
    labelButton.events.register("deactivate", labelButton,
        function() { setLayersLabels(false); } );
    var panel = new OpenLayers.Control.Panel({displayClass: 'olControlShowLabels' });
    panel.addControls([labelButton]);
    panel.activateControl(labelButton);
    map.addControl(panel);
    var agentity_id_repr='';
    if(map_mode==2)
    {
        agentity_id_repr=agentity_id;
    }
    $.get("/bound/", {'gentity_id': agentity_id_repr}, function(data){
        bounds = OpenLayers.Bounds.fromString(data);
        bounds.transform(new OpenLayers.Projection("EPSG:4326"), new
          OpenLayers.Projection("EPSG:900913"));
        map.zoomToExtent(bounds);
    });
    var SelectControl = new OpenLayers.Control.SelectFeature(categories, {
          clickout: true, togle: false, multiple: false,
          hover: false});
    map.addControl(SelectControl);
    SelectControl.activate();
    ANavToolBar.controls[0].events.on({
        "activate": function(){
            SelectControl.activate();
        },
        "deactivate": function(){
            SelectControl.deactivate();
        }
    });
    ANavToolBar.controls[0].activate();
}

function ShowProgress(name){
   var aprogress = document.getElementById("map_progress");
   if(aprogress==null)return;
   aprogress.innerHTML=
       "";
}

function HideProgress(name){
   var aprogress = document.getElementById("map_progress");
   if(aprogress==null)return;
   aprogress.innerHTML="";
}

function setLayersOpaque(value){
    for(i=0;i<categories.length;i++){
        var layer = categories[i];
        var defaultStyle = layer.styleMap.styles["default"].defaultStyle;
        if(value)
            defaultStyle["fillOpacity"]=0.6;
        else
            defaultStyle["fillOpacity"]=0;
        layer.styleMap.styles["default"].setDefaultStyle(defaultStyle);
        layer.redraw();
    }
}

function setLayersLabels(value){
    for(i=0;i<categories.length;i++){
        var layer = categories[i];
        var defaultStyle = layer.styleMap.styles["default"].defaultStyle;
        if(value)
            defaultStyle["label"]="${name}";
        else
            defaultStyle["label"]="";
        layer.styleMap.styles["default"].setDefaultStyle(defaultStyle);
        layer.redraw();
    }
}

function changeBaseLayer(value){
    map.setBaseLayer(base_layers[value]);
}
<commit_msg>Add hover - tooltips features<commit_after>function gup( name )
{
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );
    if( results == null )
        return "";
    else
        return results[1];
}

Object.extend = function(destination, source) {
    for (var property in source)
        destination[property] = source[property];
    return destination;
};

var point1 = new OpenLayers.LonLat(19.3, 34.75);
var point2 = new OpenLayers.LonLat(29.65,41.8);
var bounds = new OpenLayers.Bounds();
bounds.extend(point1);
bounds.extend(point2);
bounds.transform(new OpenLayers.Projection("EPSG:4326"), new
OpenLayers.Projection("EPSG:900913"));
var map = null;
var apopup = null;
var ktimatologio = new OpenLayers.Layer.WMS("Υπόβαθρο «ΚΤΗΜΑΤΟΛΟΓΙΟ Α.Ε.»",
  "http://gis.ktimanet.gr/wms/wmsopen/wmsserver.aspx",
    {   layers: 'KTBASEMAP', transparent: false},
    {   isBaseLayer: true,
        projection: new OpenLayers.Projection("EPSG:900913"),
        iformat: 'image/png', maxExtent: bounds, numZoomLevels:
        15, units: "m", maxResolution: 900,
        attribution: ""});
var osm = new OpenLayers.Layer.OSM.Mapnik("Υπόβαθρο \"Open Street Map\"",{isBaseLayer: true,
        attribution: "Map by OSM"});
var ocm = new OpenLayers.Layer.OSM.CycleMap("Υπόβαθρο \"Open Cycle Map\"",{isBaseLayer: true,
        attribution: "Map by OSM"});
var base_layers = [ocm, osm, ktimatologio];
function InvokePopup(afeature) {
    apoint = afeature.geometry.getBounds().getCenterLonLat();
    map.panTo(apoint);
    $.get("/stations/b/"+afeature.attributes["id"]+'/', {}, function(data){
        var amessage = '';
        amessage=data;
        apopup = new OpenLayers.Popup(afeature.attributes["name"], apoint, new OpenLayers.Size(190,150), amessage, true);
        apopup.setBorder("2px solid");
        apopup.setBackgroundColor('#E0E0B0');
        map.addPopup(apopup, true);
    });
}
function InvokeTooltip(atitle){
    document.getElementById("map").title = atitle;
}
function HideTooltip(atitle){
    document.getElementById("map").title = '';
}
function CreateLayer(AName, ObjectName, AFillColor, AStrokeColor){
    if(map_mode==1){
        var params = {};
    }
    else if(map_mode==2){
        var params = {'gentity_id': agentity_id,};
    }
    var labelvalue = "";
    var labeling_opts = {
            label : labelvalue, fontColor: "#504065",
            fontSize: "9px", fontFamily: "Verdana, Arial",
            fontWeight: "bold", labelAlign: "cm"
    };
    var general_opts = {
            externalGraphic: MEDIA_URL+'images/marker.png',
            graphicWidth: 21, graphicHeight:25, graphicXOffset:-10,
            graphicYOffset: -25, fillOpacity: 1
    };
    general_opts = Object.extend(general_opts, labeling_opts);
    AURL = "/"+ObjectName+"/kml/";
    var alayer = new OpenLayers.Layer.WFS(AName, AURL, params,
    {   projection: new OpenLayers.Projection("EPSG:4326"),
//                    protocol: new OpenLayers.Protocol.HTTP(
//                    {url: AURL, format: new OpenLayers.Format.KML({ extractAttributes: true})}),
        format: OpenLayers.Format.KML,
        formatOptions: { extractAttributes:true },
//                    strategies: [new OpenLayers.Strategy.BBOX(), new
//                    OpenLayers.Strategy.Refresh()],
        styleMap: new OpenLayers.StyleMap({
            "default": new OpenLayers.Style(
                  OpenLayers.Util.applyDefaults(general_opts,
                        OpenLayers.Feature.Vector.style["default"])),
            "select": new OpenLayers.Style(
                  OpenLayers.Util.applyDefaults({
                        externalGraphic: MEDIA_URL+'images/selected_marker.png',
                        graphicWidth: 21, graphicHeight:25, graphicXOffset:-10,
                        graphicYOffset: -25, fillOpacity: 1},
                        OpenLayers.Feature.Vector.style["select"])),
            "temporary": new OpenLayers.Style(
                  OpenLayers.Util.applyDefaults({
                        externalGraphic: MEDIA_URL+'images/marker.png',
                        graphicWidth: 21, graphicHeight:25, graphicXOffset:-10,
                        graphicYOffset: -25, fillOpacity: 0.7},
                        OpenLayers.Feature.Vector.style["select"])),
        })
    } );
    alayer.events.register("loadstart", alayer,
        function() { ShowProgress(ObjectName); } );
    alayer.events.register("loadend", alayer,
        function() { HideProgress(ObjectName); } );
    alayer.events.register("loadcancel", alayer,
        function() { HideProgress(ObjectName); } );
    alayer.events.on({
        "featureselected": function(e) {
            InvokePopup(e.feature);
        },
        "featureunselected": function(e) {
            map.removePopup(apopup);
        }
    });
    return alayer;
}
var stations = CreateLayer("Σταθμοί", "stations", '#dd0022', '#990077');
var categories = [stations];
function init() {
    var options = {
        'units' :   "m",
        'numZoomLevels' :   15,
        'sphericalMercator': true,
        'maxExtent': bounds,
        'projection'    :   new OpenLayers.Projection("EPSG:9009313"),
        'displayProjection':    new OpenLayers.Projection("EPSG:4326")
    };
    map = new OpenLayers.Map('map', options);
    map.addControl(new OpenLayers.Control.ScaleLine());
    var ANavToolBar = new OpenLayers.Control.NavToolbar();
        map.addControl(ANavToolBar);
//    if(map_mode!=2)
//    {
        $("div.olControlNavToolbar").css("top","14px");
        $("div.olControlNavToolbar").css("left","11px");
/*    } else {
        $("div.olControlNavToolbar").css("top","-295px");
        $("div.olControlNavToolbar").css("left","340px");
        $("div.olControlNavToolbar").css("z-index","900");
    }*/
    pzb = new OpenLayers.Control.PanZoomBar();
    pzb.zoomWorldIcon = false;
    map.addControl(pzb);
    map.addControl(new OpenLayers.Control.MousePosition());
    map.addControl(new OpenLayers.Control.OverviewMap());
    ls = new OpenLayers.Control.LayerSwitcher();
    map.addControl(ls);
    map.addLayer(ocm);
    map.addLayer(osm);
    map.addLayer(ktimatologio);
    map.addLayers(categories);
    ls.baseLbl.innerHTML='Base layers';
    ls.dataLbl.innerHTML='Data layers';
    var labelButton = new OpenLayers.Control.Button({ type: OpenLayers.Control.TYPE_TOGGLE,
        title: "Show labels", displayClass: "LabelButtonClass" , trigger: function(){}});
    labelButton.events.register("activate", labelButton,
        function() { setLayersLabels(true); } );
    labelButton.events.register("deactivate", labelButton,
        function() { setLayersLabels(false); } );
    var panel = new OpenLayers.Control.Panel({displayClass: 'olControlShowLabels' });
    panel.addControls([labelButton]);
    panel.activateControl(labelButton);
    map.addControl(panel);
    var agentity_id_repr='';
    if(map_mode==2)
    {
        agentity_id_repr=agentity_id;
    }
    $.get("/bound/", {'gentity_id': agentity_id_repr}, function(data){
        bounds = OpenLayers.Bounds.fromString(data);
        bounds.transform(new OpenLayers.Projection("EPSG:4326"), new
          OpenLayers.Projection("EPSG:900913"));
        map.zoomToExtent(bounds);
    });
    var SelectControl = new OpenLayers.Control.SelectFeature(categories, {
          clickout: true, togle: false, multiple: false,
          hover: false});
    var HoverControl = new OpenLayers.Control.SelectFeature(categories, {
          clickout: false, togle: false, multiple: false,
          hover: true, highlightOnly: true, renderIntent: "temporary",
          eventListeners: { beforefeaturehighlighted: function(e){},
                            featurehighlighted: function(e){InvokeTooltip(e.feature.attributes["name"])},
                            featureunhighlighted: function(e){HideTooltip(e.feature.attributes["name"])}
                          }});
    map.addControl(SelectControl);
    map.addControl(HoverControl);
    HoverControl.activate();
    SelectControl.activate();
    ANavToolBar.controls[0].events.on({
        "activate": function(){
            HoverControl.activate();
            SelectControl.activate();
        },
        "deactivate": function(){
            HoverControl.deactivate();
            SelectControl.deactivate();
        }
    });
    ANavToolBar.controls[0].activate();
}

function ShowProgress(name){
   var aprogress = document.getElementById("map_progress");
   if(aprogress==null)return;
   aprogress.innerHTML=
       "";
}

function HideProgress(name){
   var aprogress = document.getElementById("map_progress");
   if(aprogress==null)return;
   aprogress.innerHTML="";
}

function setLayersOpaque(value){
    for(i=0;i<categories.length;i++){
        var layer = categories[i];
        var defaultStyle = layer.styleMap.styles["default"].defaultStyle;
        if(value)
            defaultStyle["fillOpacity"]=0.6;
        else
            defaultStyle["fillOpacity"]=0;
        layer.styleMap.styles["default"].setDefaultStyle(defaultStyle);
        layer.redraw();
    }
}

function setLayersLabels(value){
    for(i=0;i<categories.length;i++){
        var layer = categories[i];
        var defaultStyle = layer.styleMap.styles["default"].defaultStyle;
        if(value)
            defaultStyle["label"]="${name}";
        else
            defaultStyle["label"]="";
        layer.styleMap.styles["default"].setDefaultStyle(defaultStyle);
        layer.redraw();
    }
}

function changeBaseLayer(value){
    map.setBaseLayer(base_layers[value]);
}
<|endoftext|>


<commit_before>/**
 * Contains the functionality that will be used for Muut on the frontend
 * Version 1.0
 * Requires jQuery
 *
 * Copyright (c) 2014 Moot, Inc.
 * Licensed under MIT
 * http://www.opensource.org/licenses/mit-license.php
 */
jQuery(document).ready( function($) {
  var __muut_frontend_strings = muut_frontend_functions_localized;

  // Adds the comments navigation link to the forum navigation.
  var body = $('body');
  if ( body.hasClass('muut-forum-home') && !body.hasClass('muut-custom-nav') && typeof muut_show_comments_in_nav != 'undefined' && muut_show_comments_in_nav ) {
    // Make sure the title of the comments page is "Comments".
    muutObj().on( 'load', function(page) {
      var comments_link_class = "unlisted ";
      if (typeof( muut_comments_base_domain ) == 'string' && page.relativePath == '/' + muut_comments_base_domain) {
        page.title = "Comments";
        var comments_link_class = "m-selected";
      }
      if ($('#muut_site_comments_nav').length == 0) {
        $(".m-forums").append('
' + __muut_frontend_strings.comments + '
');
      }
    });
  }

  $.fn.extend({
    facelinkinit: function() {
      var online_usernames = Array();
      muutObj().online.forEach(function(user) {
        online_usernames.push(user.username);
      });
      var facelinks = $(this).find('.m-facelink');
      $.each(facelinks, function() {
        if ( !$(this).hasClass('m-facelink-inited') ) {
          $(this).tooltip2({prefix: 'm-', delayIn: 0, delayOut: 0}).appendTo($(this));
          if($(this).hasClass('m-is-admin')) {
            $(this).find(".m-tooltip").append(" (" + __muut_frontend_strings.admin + ")");
          }
          $(this).on('click', function(e) {
            var el = $(this);
            var page = el.data('href').substr(2);
            muutObj().load(page);
          });
          var current_user_name = $(this).data('href').substr(4);
          // This class is required for tooltips to work--something on the Muut end.
          $(this).addClass('m-online')
          if($.inArray(current_user_name, online_usernames) >= 0) {
            $(this).addClass('m-user-online_' + current_user_name);
          } else {
            // This hides the "online" circle, which has been added by the required m-online.
            // Ugly, I know.
            $(this).addClass('m-wp-hideafter');
          }
          $(this).addClass('m-facelink-inited');
        }
      });
    }
  });
});

// Function that contains the template for avatars.
var get_user_avatar_html = function(user) {
  var is_admin_class = '';
  if(user.is_admin) {
    is_admin_class = 'm-is-admin ';
  }

  // Construct the actual username without the '@'.
  if(user.path.substr(0,1) == '@') {
    var username = user.path.substr(1);
  }

  var username_for_class = username.replace(' ', '_');
  var online_user_href_markup = '';
  if ( typeof muut_forum_page_permalink == 'string' ) {
    online_user_href_markup = 'href="' + muut_forum_page_permalink + '#!/' + user.path + '"';
  }
  // Return the HTML for the face.
  var html = '';
  return html;
};<commit_msg>Facelinks: Added some commenting to the JS code.<commit_after>/**
 * Contains the functionality that will be used for Muut on the frontend
 * Version 1.0
 * Requires jQuery
 *
 * Copyright (c) 2014 Moot, Inc.
 * Licensed under MIT
 * http://www.opensource.org/licenses/mit-license.php
 */
jQuery(document).ready( function($) {
  var __muut_frontend_strings = muut_frontend_functions_localized;

  // Adds the comments navigation link to the forum navigation.
  var body = $('body');
  if ( body.hasClass('muut-forum-home') && !body.hasClass('muut-custom-nav') && typeof muut_show_comments_in_nav != 'undefined' && muut_show_comments_in_nav ) {
    // Make sure the title of the comments page is "Comments".
    muutObj().on( 'load', function(page) {
      var comments_link_class = "unlisted ";
      if (typeof( muut_comments_base_domain ) == 'string' && page.relativePath == '/' + muut_comments_base_domain) {
        page.title = "Comments";
        var comments_link_class = "m-selected";
      }
      if ($('#muut_site_comments_nav').length == 0) {
        $(".m-forums").append('
' + __muut_frontend_strings.comments + '
');
      }
    });
  }

  $.fn.extend({
    // The function that is used to initialize all m-facelink anchors below the jQuery element collection calling the function.
    facelinkinit: function() {
      var online_usernames = Array();
      muutObj().online.forEach(function(user) {
        online_usernames.push(user.username);
      });
      var facelinks = $(this).find('.m-facelink');
      $.each(facelinks, function() {
        // If the facelinks are not marked as already having been initialized...
        if ( !$(this).hasClass('m-facelink-inited') ) {
          // Add the username tooltip.
          $(this).tooltip2({prefix: 'm-', delayIn: 0, delayOut: 0}).appendTo($(this));
          if($(this).hasClass('m-is-admin')) {
            $(this).find(".m-tooltip").append(" (" + __muut_frontend_strings.admin + ")");
          }
          // Load the user page if the portrait is clicked.
          $(this).on('click', function(e) {
            var el = $(this);
            var page = el.data('href').substr(2);
            muutObj().load(page);
          });
          var current_user_name = $(this).data('href').substr(4);
          // This class is required for tooltips to work--something on the Muut end.
          $(this).addClass('m-online')
          if($.inArray(current_user_name, online_usernames) >= 0) {
            $(this).addClass('m-user-online_' + current_user_name);
          } else {
            // This hides the "online" circle, which has been added by the required m-online.
            // Ugly, I know.
            $(this).addClass('m-wp-hideafter');
          }
          $(this).addClass('m-facelink-inited');
        }
      });
    }
  });
});

// Function that contains the template for avatars.
var get_user_avatar_html = function(user) {
  var is_admin_class = '';
  if(user.is_admin) {
    is_admin_class = 'm-is-admin ';
  }

  // Construct the actual username without the '@'.
  if(user.path.substr(0,1) == '@') {
    var username = user.path.substr(1);
  }

  var username_for_class = username.replace(' ', '_');
  var online_user_href_markup = '';
  if ( typeof muut_forum_page_permalink == 'string' ) {
    online_user_href_markup = 'href="' + muut_forum_page_permalink + '#!/' + user.path + '"';
  }
  // Return the HTML for the face.
  var html = '';
  return html;
};<|endoftext|>


<commit_before>goog.provide('app.SimpleSearchController');
goog.provide('app.simpleSearchDirective');

goog.require('app');
goog.require('app.Document');
goog.require('app.Url');
/** @suppress {extraRequire} */
goog.require('ngeo.searchDirective');

/**
 * The directive for the auto-complete search field shown in the header
 * of every page.
 * @return {angular.Directive} Directive Definition Object.
 */
app.simpleSearchDirective = function() {
  return {
    restrict: 'E',
    controller: 'AppSimpleSearchController',
    bindToController: {
      selectHandler: '&appSelect'
    },
    controllerAs: 'searchCtrl',
    templateUrl: '/static/partials/simplesearch.html',
    link:
        /**
         * @param {angular.Scope} $scope Scope.
         * @param {angular.JQLite} element Element.
         */
        function($scope, element, attrs, ctrl) {

          var phoneScreen = app.constants.SCREEN.SMARTPHONE;
          // don't show "show more" button for this cases.
          if ($(element).closest('app-add-association').length || $(element).closest('#participants-group').length) {
            ctrl.associationContext_ = true;
          }

          // Empty the search field on focus and blur.
          $('.page-header').find('input').on('focus blur', function() {
            $(this).typeahead('val', '');
          });

          //Remove the class 'show-search' when screen width > @phone (defined in LESS)
          $(window).resize(function resize() {
            if ($(window).width() > phoneScreen) {
              $('.show-search').removeClass('show-search');
              $('.logo.header, .menu-open-close.header').removeClass('no-opacity');
            }
          });
          element.on('click', function(e) {

            // collapse suggestions
            if ($('app-simple-search .header').is(e.target)) {
              $(e.target).siblings('.tt-suggestion').slideToggle();
            }

            // Trigger focus on search-icon click for .search
            if (window.innerWidth < phoneScreen) {
              if ($('.page-header .search-icon').is(e.target)) {
                $('.page-header').find('.quick-search').toggleClass('show-search');
                $('.page-header').find('.search').focus();
                $('.logo.header, .menu-open-close.header').toggleClass('no-opacity');
              }
            }
          });

          // hide the menu when click outside (smartphone)
          $('main').click(function(e) {
            if (window.innerWidth < phoneScreen) {
              $('.show-search').removeClass('show-search');
              $('.logo.header, .menu-open-close.header').removeClass('no-opacity');
            }
          });

          //show spinning gif while waiting for the results
          element.on('typeahead:asyncrequest', function() {
            element.find('input').addClass('loading-gif-typehead');
          });
          element.on('typeahead:asynccancel typeahead:asyncreceive', function() {
            element.find('input').removeClass('loading-gif-typehead');
          });

        }

  };
};

app.module.directive('appSimpleSearch', app.simpleSearchDirective);

/**
 * @constructor
 * @param {!angular.Scope} $scope Angular scope.
 * @param {angular.$compile} $compile Angular compile service.
 * @param {angular.$templateCache} $templateCache service
 * @param {app.Document} appDocument service
 * @param {app.Authentication} appAuthentication service
 * @param {angular.Attributes} $attrs Angular attributes.
 * @param {string} apiUrl Base URL of the API.
 * @param {angularGettext.Catalog} gettextCatalog Gettext catalog.
 * @param {app.Url} appUrl URL service.
 * @ngInject
 */
app.SimpleSearchController = function(appDocument, $scope, $compile, $attrs, apiUrl,
    gettextCatalog, $templateCache, appAuthentication, appUrl) {

  /**
   * @type {app.Document}
   * @private
   */
  this.documentService_ = appDocument;

  /**
   * Bound from directive.
   * @type {function({doc: appx.SimpleSearchDocument})|undefined}
   * @export
   */
  this.selectHandler;

  /**
   * @type {angular.$compile}
   * @private
   */
  this.compile_ = $compile;

  if (!$attrs['appSelect']) {
    // Angular puts a noop function when mapping an attribute to a
    // different local name. Hacking it out.
    // See https://docs.angularjs.org/api/ng/service/$compile#-scope-
    this.selectHandler = undefined;
  }

  /**
   * @type  {app.Authentication} appAuthentication
   * @private
   */
  this.auth_ = appAuthentication;

  /**
   * @type {angular.$templateCache}
   * @private
   */
  this.templatecache_ = $templateCache;

  /**
   * @type {string}
   * @private
   */
  this.apiUrl_ = apiUrl;

  /**
   * @type {!angular.Scope}
   * @private
   */
  this.scope_ = $scope;

  /**
   * @type {angularGettext.Catalog}
   * @private
   */
  this.gettextCatalog_ = gettextCatalog;

  /**
   * @type {app.Url}
   * @private
   */
  this.url_ = appUrl;

  /**
   * @type {TypeaheadOptions}
   * @export
   */
  this.options = /** @type {TypeaheadOptions} */ ({
    highlight: true,
    hint: true,
    minLength: 3
  });

  /**
   * @type {Array.<TypeaheadDataset>}
   * @export
   */
  this.datasets = [];

  /**
   * @type {string}
   * @private
   */
  this.datasetLimit_ = $attrs['dataset'];

  // create only given datasets
  for (var i = 0; i < this.datasetLimit_.length; i++) {
    switch (this.datasetLimit_[i]) {
      case 'u':
        this.datasets.push(this.createDataset_('users'));
        break;
      case 'o':
        this.datasets.push(this.createDataset_('outings'));
        break;
      case 'w':
        this.datasets.push(this.createDataset_('waypoints'));
        break;
      case 'r':
        this.datasets.push(this.createDataset_('routes'));
        break;
      default:
        break;
    }
  }

  /**
   * @type {boolean}
   * @private
   */
  this.associationContext_ = false;

  /**
   * @type {ngeox.SearchDirectiveListeners}
   * @export
   */
  this.listeners = /** @type {ngeox.SearchDirectiveListeners} */ ({
    select: app.SimpleSearchController.select_.bind(this)
  });
};

/**
 * @param {string} type The document type.
 * @return {TypeaheadDataset} A data set.
 * @private
 */
app.SimpleSearchController.prototype.createDataset_ = function(type) {
  var bloodhoundEngine = this.createAndInitBloodhound_(type);
  return /** @type {TypeaheadDataset} */({
    contents : type,
    source: bloodhoundEngine.ttAdapter(),
    display: function(doc) {
      if (doc) {
        return doc.label;
      }
    },
    limit: 20,
    templates: {
      header: (function() {
        return '
' + this.gettextCatalog_.getString(type) + '
';
      }).bind(this),
      footer: function(doc) {
        if (!this.associationContext_) {
          // don't add this if you're typing in an add-association-tool
          var moreLink = '
' +
            this.gettextCatalog_.getString('see more results') + '
';
          return this.compile_(moreLink)(this.scope_);
        }
        return '';
      }.bind(this),
      suggestion: function(doc) {
        if (doc) {
          this.scope_['doc'] = doc;
          return this.compile_('<app-suggestion class="tt-suggestion"></app-suggestion>')(this.scope_);
        } else {
          return '

';
        }
      }.bind(this),
      empty: function(res) {
        if ($('.header.empty').length === 0) {
          return this.compile_(this.templatecache_.get('/static/partials/suggestions/empty.html'))(this.scope_);
        }
      }.bind(this)
    }
  });
};

/**
 * @param {string} type The document type.
 * @return {Bloodhound} The bloodhound engine.
 * @private
 */
app.SimpleSearchController.prototype.createAndInitBloodhound_ = function(type) {
  var url = this.apiUrl_ + '/search?q=%QUERY';

  var bloodhound = new Bloodhound(/** @type {BloodhoundOptions} */({
    limit: 7,
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('label'),
    remote: {
      url: url,
      wildcard: '%QUERY',
      rateLimitWait: 300,
      prepare: (function(query, settings) {

        var url = settings['url'] + '&pl=' + this.gettextCatalog_.currentLanguage;

        if (this.datasetLimit_) {
          // add the Auth header if searching for users
          if (this.datasetLimit_.indexOf('u') > -1 && this.auth_.isAuthenticated()) {
            settings['headers'] = {
              'Authorization': 'JWT token="' + this.auth_.userData.token + '"'
            };
          }
          url = url + '&t=' + this.datasetLimit_.split('').join(',');
        }
        settings['url'] = url.replace('%QUERY', encodeURIComponent(query));
        return settings;
      }).bind(this),

      filter: (function(/** appx.SimpleSearchResponse */ resp) {
        var documentResponse =
                /** @type {appx.SimpleSearchDocumentResponse} */ (resp[type]);
        if (documentResponse) {
          var documents = documentResponse.documents;
          var currentLang = this.gettextCatalog_.currentLanguage;
          var hasAssociation;

          return documents.map(function(/** appx.SimpleSearchDocument */ doc) {
            hasAssociation = this.documentService_.hasAssociation(type,  doc.document_id);

            var locale = doc.locales[0];
            doc.label = (type === 'routes' && locale.title_prefix) ? locale.title_prefix + ' : ' : '';
            doc.label += locale.title;

            if (currentLang !== locale.lang) {
              doc.label += ' (' + locale.lang + ')';
            }
            doc.documentType = type;

            // don't show already associated docs in the results, but only in the app-add-association
            // -> everything should be shown in the main simple-search.
            if (!this.associationContext_ || (this.associationContext_ && !hasAssociation)) {
              return doc;
            }
          }.bind(this));
        }
      }).bind(this)
    }
  }));
  bloodhound.initialize();
  return bloodhound;
};

/**
 * @param {jQuery.Event} event Event.
 * @param {!appx.SimpleSearchDocument} doc Suggested document.
 * @param {TypeaheadDataset} dataset Dataset.
 * @this {app.SimpleSearchController}
 * @private
 */
app.SimpleSearchController.select_ = function(event, doc, dataset) {
  if (this.selectHandler) {
    this.selectHandler({'doc': doc});
  } else {
    window.location.href = this.url_.buildDocumentUrl(
      doc.documentType, doc.document_id, doc.locales[0]);
  }
};

app.module.controller('AppSimpleSearchController', app.SimpleSearchController);
<commit_msg>update association context<commit_after>goog.provide('app.SimpleSearchController');
goog.provide('app.simpleSearchDirective');

goog.require('app');
goog.require('app.Document');
goog.require('app.Url');
/** @suppress {extraRequire} */
goog.require('ngeo.searchDirective');

/**
 * The directive for the auto-complete search field shown in the header
 * of every page.
 * @return {angular.Directive} Directive Definition Object.
 */
app.simpleSearchDirective = function() {
  return {
    restrict: 'E',
    controller: 'AppSimpleSearchController',
    bindToController: {
      selectHandler: '&appSelect'
    },
    controllerAs: 'searchCtrl',
    templateUrl: '/static/partials/simplesearch.html',
    link:
        /**
         * @param {angular.Scope} $scope Scope.
         * @param {angular.JQLite} element Element.
         */
        function($scope, element, attrs, ctrl) {

          var phoneScreen = app.constants.SCREEN.SMARTPHONE;
          // don't show "show more" button for this cases.
          if ($(element).closest('app-add-association')
                  || $(element).closest('#participants-group')
                  || $(element).closest('.section.associations')) {
            ctrl.associationContext_ = true;
          }

          // Empty the search field on focus and blur.
          $('.page-header').find('input').on('focus blur', function() {
            $(this).typeahead('val', '');
          });

          //Remove the class 'show-search' when screen width > @phone (defined in LESS)
          $(window).resize(function resize() {
            if ($(window).width() > phoneScreen) {
              $('.show-search').removeClass('show-search');
              $('.logo.header, .menu-open-close.header').removeClass('no-opacity');
            }
          });
          element.on('click', function(e) {

            // collapse suggestions
            if ($('app-simple-search .header').is(e.target)) {
              $(e.target).siblings('.tt-suggestion').slideToggle();
            }

            // Trigger focus on search-icon click for .search
            if (window.innerWidth < phoneScreen) {
              if ($('.page-header .search-icon').is(e.target)) {
                $('.page-header').find('.quick-search').toggleClass('show-search');
                $('.page-header').find('.search').focus();
                $('.logo.header, .menu-open-close.header').toggleClass('no-opacity');
              }
            }
          });

          // hide the menu when click outside (smartphone)
          $('main').click(function(e) {
            if (window.innerWidth < phoneScreen) {
              $('.show-search').removeClass('show-search');
              $('.logo.header, .menu-open-close.header').removeClass('no-opacity');
            }
          });

          //show spinning gif while waiting for the results
          element.on('typeahead:asyncrequest', function() {
            element.find('input').addClass('loading-gif-typehead');
          });
          element.on('typeahead:asynccancel typeahead:asyncreceive', function() {
            element.find('input').removeClass('loading-gif-typehead');
          });

        }

  };
};

app.module.directive('appSimpleSearch', app.simpleSearchDirective);

/**
 * @constructor
 * @param {!angular.Scope} $scope Angular scope.
 * @param {angular.$compile} $compile Angular compile service.
 * @param {angular.$templateCache} $templateCache service
 * @param {app.Document} appDocument service
 * @param {app.Authentication} appAuthentication service
 * @param {angular.Attributes} $attrs Angular attributes.
 * @param {string} apiUrl Base URL of the API.
 * @param {angularGettext.Catalog} gettextCatalog Gettext catalog.
 * @param {app.Url} appUrl URL service.
 * @ngInject
 */
app.SimpleSearchController = function(appDocument, $scope, $compile, $attrs, apiUrl,
    gettextCatalog, $templateCache, appAuthentication, appUrl) {

  /**
   * @type {app.Document}
   * @private
   */
  this.documentService_ = appDocument;

  /**
   * Bound from directive.
   * @type {function({doc: appx.SimpleSearchDocument})|undefined}
   * @export
   */
  this.selectHandler;

  /**
   * @type {angular.$compile}
   * @private
   */
  this.compile_ = $compile;

  if (!$attrs['appSelect']) {
    // Angular puts a noop function when mapping an attribute to a
    // different local name. Hacking it out.
    // See https://docs.angularjs.org/api/ng/service/$compile#-scope-
    this.selectHandler = undefined;
  }

  /**
   * @type  {app.Authentication} appAuthentication
   * @private
   */
  this.auth_ = appAuthentication;

  /**
   * @type {angular.$templateCache}
   * @private
   */
  this.templatecache_ = $templateCache;

  /**
   * @type {string}
   * @private
   */
  this.apiUrl_ = apiUrl;

  /**
   * @type {!angular.Scope}
   * @private
   */
  this.scope_ = $scope;

  /**
   * @type {angularGettext.Catalog}
   * @private
   */
  this.gettextCatalog_ = gettextCatalog;

  /**
   * @type {app.Url}
   * @private
   */
  this.url_ = appUrl;

  /**
   * @type {TypeaheadOptions}
   * @export
   */
  this.options = /** @type {TypeaheadOptions} */ ({
    highlight: true,
    hint: true,
    minLength: 3
  });

  /**
   * @type {Array.<TypeaheadDataset>}
   * @export
   */
  this.datasets = [];

  /**
   * @type {string}
   * @private
   */
  this.datasetLimit_ = $attrs['dataset'];

  // create only given datasets
  for (var i = 0; i < this.datasetLimit_.length; i++) {
    switch (this.datasetLimit_[i]) {
      case 'u':
        this.datasets.push(this.createDataset_('users'));
        break;
      case 'o':
        this.datasets.push(this.createDataset_('outings'));
        break;
      case 'w':
        this.datasets.push(this.createDataset_('waypoints'));
        break;
      case 'r':
        this.datasets.push(this.createDataset_('routes'));
        break;
      default:
        break;
    }
  }

  /**
   * @type {boolean}
   * @private
   */
  this.associationContext_ = false;

  /**
   * @type {ngeox.SearchDirectiveListeners}
   * @export
   */
  this.listeners = /** @type {ngeox.SearchDirectiveListeners} */ ({
    select: app.SimpleSearchController.select_.bind(this)
  });
};

/**
 * @param {string} type The document type.
 * @return {TypeaheadDataset} A data set.
 * @private
 */
app.SimpleSearchController.prototype.createDataset_ = function(type) {
  var bloodhoundEngine = this.createAndInitBloodhound_(type);
  return /** @type {TypeaheadDataset} */({
    contents : type,
    source: bloodhoundEngine.ttAdapter(),
    display: function(doc) {
      if (doc) {
        return doc.label;
      }
    },
    limit: 20,
    templates: {
      header: (function() {
        return '
' + this.gettextCatalog_.getString(type) + '
';
      }).bind(this),
      footer: function(doc) {
        if (!this.associationContext_) {
          // don't add this if you're typing in an add-association-tool
          var moreLink = '
' +
            this.gettextCatalog_.getString('see more results') + '
';
          return this.compile_(moreLink)(this.scope_);
        }
        return '';
      }.bind(this),
      suggestion: function(doc) {
        if (doc) {
          this.scope_['doc'] = doc;
          return this.compile_('<app-suggestion class="tt-suggestion"></app-suggestion>')(this.scope_);
        } else {
          return '

';
        }
      }.bind(this),
      empty: function(res) {
        if ($('.header.empty').length === 0) {
          return this.compile_(this.templatecache_.get('/static/partials/suggestions/empty.html'))(this.scope_);
        }
      }.bind(this)
    }
  });
};

/**
 * @param {string} type The document type.
 * @return {Bloodhound} The bloodhound engine.
 * @private
 */
app.SimpleSearchController.prototype.createAndInitBloodhound_ = function(type) {
  var url = this.apiUrl_ + '/search?q=%QUERY';

  var bloodhound = new Bloodhound(/** @type {BloodhoundOptions} */({
    limit: 7,
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('label'),
    remote: {
      url: url,
      wildcard: '%QUERY',
      rateLimitWait: 300,
      prepare: (function(query, settings) {

        var url = settings['url'] + '&pl=' + this.gettextCatalog_.currentLanguage;

        if (this.datasetLimit_) {
          // add the Auth header if searching for users
          if (this.datasetLimit_.indexOf('u') > -1 && this.auth_.isAuthenticated()) {
            settings['headers'] = {
              'Authorization': 'JWT token="' + this.auth_.userData.token + '"'
            };
          }
          url = url + '&t=' + this.datasetLimit_.split('').join(',');
        }
        settings['url'] = url.replace('%QUERY', encodeURIComponent(query));
        return settings;
      }).bind(this),

      filter: (function(/** appx.SimpleSearchResponse */ resp) {
        var documentResponse =
                /** @type {appx.SimpleSearchDocumentResponse} */ (resp[type]);
        if (documentResponse) {
          var documents = documentResponse.documents;
          var currentLang = this.gettextCatalog_.currentLanguage;
          var hasAssociation;

          return documents.map(function(/** appx.SimpleSearchDocument */ doc) {
            hasAssociation = this.documentService_.hasAssociation(type,  doc.document_id);

            var locale = doc.locales[0];
            doc.label = (type === 'routes' && locale.title_prefix) ? locale.title_prefix + ' : ' : '';
            doc.label += locale.title;

            if (currentLang !== locale.lang) {
              doc.label += ' (' + locale.lang + ')';
            }
            doc.documentType = type;

            // don't show already associated docs in the results, but only in the app-add-association
            // -> everything should be shown in the main simple-search.
            if (!this.associationContext_ || (this.associationContext_ && !hasAssociation)) {
              return doc;
            }
          }.bind(this));
        }
      }).bind(this)
    }
  }));
  bloodhound.initialize();
  return bloodhound;
};

/**
 * @param {jQuery.Event} event Event.
 * @param {!appx.SimpleSearchDocument} doc Suggested document.
 * @param {TypeaheadDataset} dataset Dataset.
 * @this {app.SimpleSearchController}
 * @private
 */
app.SimpleSearchController.select_ = function(event, doc, dataset) {
  if (this.selectHandler) {
    this.selectHandler({'doc': doc});
  } else {
    window.location.href = this.url_.buildDocumentUrl(
      doc.documentType, doc.document_id, doc.locales[0]);
  }
};

app.module.controller('AppSimpleSearchController', app.SimpleSearchController);
<|endoftext|>


<commit_before>require.config({
    baseUrl: "/src/js",
    paths: {
        jquery: "lib/jquery",
        underscore: "lib/underscore",
        backbone: "lib/backbone"
    }
});<commit_msg>Include RequireJS text plugin<commit_after>require.config({
    baseUrl: "/src/js",
    paths: {
        text: "lib/text",
        jquery: "lib/jquery",
        underscore: "lib/underscore",
        backbone: "lib/backbone"
    }
});<|endoftext|>


<commit_before>var phrases = ["Were you born in a barn?", "Get some work done.", "Useless scrub.", "Stop jacking off.", "I'll bust your chops.", "Are you born in a water park?", "Stop fapping around.", "Are you born in a barn?", "Later, shizlord.", "Oy!", "Urh, scrub!", "Excuse me?"];
var dialogs = ["WERE U BORN IN A BARN???", "GET SUM WERK DUN", "Useless scrub...", "Stop jacking off", "I'LL BUST YOUR CHOPS", "R U BORN IN A WATER PARK??", "Stop fapping around", "R U BORN IN A BARN???", "LATER, SHIZLORD", "OI!!", "URGHHHH SCRUB!!!", "ESCUUUUSE MEEEE"];
var remarks = ["Scrub", "Useless twerp", "Uh Uh Uh", "Uh"];

function androo(){
    var index = Math.round(Math.random()*(phrases.length-1));
    var rIndex = Math.round(Math.random()*(remarks.length-1));

    var ttsOptions = {
        gender: "male",
        rate: 0.7,
        pitch: 0.8,
        enqueue: true
    }

    chrome.tts.speak(phrases[index],ttsOptions);
    alert(dialogs[index]);
    chrome.tts.speak(remarks[rIndex],ttsOptions);

    setTimeout(androo,Math.random()*30*1000);
}

setTimeout(androo,20000);
<commit_msg>Added more "inspirational" quotes/phrases<commit_after>var phrases = ["Were you born in a barn?", "Get some work done.", "Useless scrub.", "Stop jacking off.", "I'll bust your chops.", "Are you born in a water park?", "Stop fapping around.", "Are you born in a barn?", "Later, shizlord.", "Oy!", "Urh, scrub!", "Excuse me?", "You should know when to give up...", "You're so pathetic", "How... will this help your future career?","Ugh Ug Uh Guh Gug Guh Gugh Huh","Stop smirking."];
var dialogs = ["WERE U BORN IN A BARN???", "GET SUM WERK DUN", "Useless scrub...", "Stop jacking off", "I'LL BUST YOUR CHOPS", "R U BORN IN A WATER PARK??", "Stop fapping around", "R U BORN IN A BARN???", "LATER, SHIZLORD", "OI!!", "URGHHHH SCRUB!!!", "ESCUUUUSE MEEEE", "You should know when to give up...", "How will this help your future career?", "UR SO PATHETIC", "UGH UG UH GUH GUG GUH GUGH HUH", "STOP SMIRKING."];
var remarks = ["Scrub", "Useless twerp", "Uh Uh Uh", "Uh"];

function androo(){
    var index = Math.round(Math.random()*(phrases.length-1));
    var rIndex = Math.round(Math.random()*(remarks.length-1));

    var ttsOptions = {
        gender: "male",
        rate: 0.7,
        pitch: 0.8,
        enqueue: true
    }

    chrome.tts.speak(phrases[index],ttsOptions);
    alert(dialogs[index]);
    chrome.tts.speak(remarks[rIndex],ttsOptions);

    setTimeout(androo,Math.random()*30*1000);
}

setTimeout(androo,20000);
<|endoftext|>


<commit_before>'use strict';

describe("Accessibility Test", function () {
    var originalTimeout;

    var testcasesHTML = window.__html__;

    for (var testFile in testcasesHTML) {

        (function (testFile) {
            describe("\"" + testFile + "\"", function () {
                beforeEach(function () {
                    originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;

                    jasmine.DEFAULT_TIMEOUT_INTERVAL = 180000;
                });

                it('should have no accessibility violations', function (done) {
                    var testDataFileContent = testcasesHTML[testFile];

                    // Perform the accessibility scan using the AAT.getCompliance API
                    AAT.getCompliance(testDataFileContent, testFile, function (results) {

                        // Call the AAT.assertCompliance API which is used to compare the results with baseline object if we can find one that
                        // matches the same label which was provided.
                        var returnCode = AAT.assertCompliance(results);

                        // In the case that the violationData is not defined then trigger an error right away.
                        expect(returnCode).toBe(0, "Scanning " + testFile + " failed." + JSON.stringify(results));

                        // Mark the testcases as done, when using jasmine as the test framework.
                        done();
                    });
                });

                afterEach(function () {
                    jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
                });
            });
        })(testFile);
    }
});<commit_msg>Add AAT.stringifyResults to console.log the failures<commit_after>'use strict';

describe("Accessibility Test", function () {
    var originalTimeout;

    var testcasesHTML = window.__html__;

    for (var testFile in testcasesHTML) {

        (function (testFile) {
            describe("\"" + testFile + "\"", function () {
                beforeEach(function () {
                    originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;

                    jasmine.DEFAULT_TIMEOUT_INTERVAL = 180000;
                });

                it('should have no accessibility violations', function (done) {
                    var testDataFileContent = testcasesHTML[testFile];

                    // Perform the accessibility scan using the AAT.getCompliance API
                    AAT.getCompliance(testDataFileContent, testFile, function (results) {

                        // Call the AAT.assertCompliance API which is used to compare the results with baseline object if we can find one that
                        // matches the same label which was provided.
                        var returnCode = AAT.assertCompliance(results);

                        if (returnCode !== 0) {
                            console.log(AAT.stringifyResults(results));
                        }

                        // In the case that the violationData is not defined then trigger an error right away.
                        expect(returnCode).toBe(0, "Scanning " + testFile + " failed.");

                        // Mark the testcases as done, when using jasmine as the test framework.
                        done();
                    });
                });

                afterEach(function () {
                    jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
                });
            });
        })(testFile);
    }
});<|endoftext|>


<commit_before>import _ from 'lodash';
import path from 'path';
import {fs} from '../src/promisify';
import BuildMonitor from '../src/build-monitor';
import {Observable, TestScheduler, Disposable, Subject} from 'rx';
import '../src/custom-rx-operators';

const d = require('debug')('surf-test:build-monitor');

function getSeenRefs(refs) {
  return _.reduce(refs, (acc, x) => {
    acc.add(x.object.sha);
    return acc;
  }, new Set());
}

describe('the build monitor', function() {
  beforeEach(async function() {
    let acc = {};
    let fixturesDir = path.join(__dirname, '..', 'fixtures');

    for (let name of await fs.readdir(fixturesDir)) {
      if (!name.match(/^refs.*\.json$/i)) continue;

      let contents = await fs.readFile(path.join(fixturesDir, name), 'utf8');
      acc[name] = JSON.parse(contents.split('\n')[0]);
    }

    this.refExamples = acc;

    this.sched = new TestScheduler();
    this.fixture = new BuildMonitor(null, null, 2, null, null, this.sched);
  });

  afterEach(function() {
    this.fixture.dispose();
  });

  it.only('shouldnt run builds in getOrCreateBuild until you subscribe', function() {
    let buildCount = 0;
    let runBuildCount = 0;

    // Scheduling is live
    this.sched.start();

    let buildSubject = new Subject();
    this.fixture.runBuild = () => {
      runBuildCount++;
      return buildSubject.subUnsub(() => buildCount++);
    };

    d('Initial getOrCreateBuild');
    let ref = this.refExamples['refs1.json'][1];
    let result = this.fixture.getOrCreateBuild(ref);
    this.sched.start();
    expect(buildCount).to.equal(0);
    expect(runBuildCount).to.equal(1);

    d('Subscribing 1x');
    result.observable.subscribe();
    this.sched.start();
    expect(buildCount).to.equal(1);

    // Double subscribes do nothing
    d('Subscribing 2x');
    result.observable.subscribe();
    this.sched.start();
    expect(buildCount).to.equal(1);

    d('Second getOrCreateBuild');
    result = this.fixture.getOrCreateBuild(ref);
    result.observable.subscribe();
    this.sched.start();
    expect(buildCount).to.equal(1);
    expect(runBuildCount).to.equal(1);

    d('Complete the build');
    buildSubject.onNext('');
    buildSubject.onCompleted();

    d('Third getOrCreateBuild');
    result = this.fixture.getOrCreateBuild(ref);
    result.observable.subscribe();
    this.sched.start();
    expect(buildCount).to.equal(2);
    expect(runBuildCount).to.equal(2);
  });

  it('should decide to build new refs from a blank slate', function() {
    this.fixture.fetchRefs = () =>
      Observable.just(this.refExamples['refs1.json']);

    let buildCount = 0;
    this.fixture.runBuild = () => {
      buildCount++;
      return Observable.just('');
    };

    this.fixture.start();
    expect(buildCount).to.equal(0);

    this.sched.advanceBy(30*1000);
    expect(buildCount).to.equal(10);
  });

  it('should decide to build only changed refs', function() {
    this.fixture.fetchRefs = () =>
      Observable.just(this.refExamples['refs1.json']);

    let buildCount = 0;
    this.fixture.runBuild = (ref) => {
      buildCount++;
      return Observable.just('')
        .subUnsub(() => d(`Building ${ref.object.sha}`));
    };

    this.fixture.start();
    expect(buildCount).to.equal(0);

    this.sched.advanceBy(this.fixture.pollInterval + 1000);
    expect(buildCount).to.equal(10);

    this.fixture.fetchRefs = () =>
      Observable.just(this.refExamples['refs2.json']);

    // Move to the next interval, we should only run the one build
    this.sched.advanceBy(this.fixture.pollInterval);
    expect(buildCount).to.equal(11);
  });

  it('should only build at a max level of concurrency', function() {
    let liveBuilds = 0;
    let completedBuilds = 0;
    let completedShas = new Set();

    this.fixture.runBuild = (ref) => {
      return Observable.just('')
        .do(() => {
          if (completedShas.has(ref.object.sha)) d(`Double building! ${ref.object.sha}`);
          liveBuilds++;
          d(`Starting build: ${ref.object.sha}`);
        })
        .delay(2*1000, this.sched)
        .do(() => {}, () => {}, () => {
          liveBuilds--;
          completedBuilds++;
          completedShas.add(ref.object.sha);
          d(`Completing build: ${ref.object.sha}`);
        })
        .publish()
        .refCount();
    };

    this.fixture.fetchRefs = () =>
      Observable.just(this.refExamples['refs1.json']);

    this.fixture.start();
    this.sched.advanceBy(this.fixture.pollInterval + 2);

    expect(liveBuilds).to.equal(2);
    expect(completedBuilds).to.equal(0);

    this.sched.advanceBy(this.fixture.pollInterval);
    expect(liveBuilds).to.equal(2);
    expect(completedBuilds).to.equal(4);  // two builds per 2sec, for 5sec

    this.sched.advanceBy(30 * 1000);
    expect(liveBuilds).to.equal(0);
    expect(completedBuilds).to.equal(10);
  });

  it('shouldnt cancel any builds when we only look at one set of refs', function() {
    let liveBuilds = 0;
    let cancelledRefs = [];

    this.fixture.runBuild = (ref) => {
      let ret = Observable.just('')
        .do(() => {
          liveBuilds++;
          d(`Starting build: ${ref.object.sha}`);
        })
        .delay(2*1000, this.sched)
        .do(() => {}, () => {}, () => {
          liveBuilds--;
          d(`Completing build: ${ref.object.sha}`);
        })
        .publish()
        .refCount();

      return Observable.create((subj) => {
        let producedItem = false;
        let disp = ret
          .do(() => producedItem = true)
          .subscribe(subj);

        return Disposable.create(() => {
          disp.dispose();
          if (producedItem) return;

          d(`Canceled ref before it finished! ${ref.object.sha}`);
          liveBuilds--;
          cancelledRefs.push(ref.object.sha);
        });
      });
    };

    this.fixture.fetchRefs = () =>
      Observable.just(this.refExamples['refs1.json']);

    this.fixture.start();
    this.sched.advanceBy(this.fixture.pollInterval + 1000);

    expect(liveBuilds).to.equal(2);

    this.sched.advanceBy(1000);
    expect(liveBuilds).to.equal(2);

    this.sched.advanceBy(30 * 1000);

    expect(liveBuilds).to.equal(0);
    expect(cancelledRefs.length).to.equal(0);
  });

  it('should cancel builds when their refs disappear', function() {
    let liveBuilds = 0;
    let cancelledRefs = [];

    this.fixture.runBuild = (ref) => {
      let ret = Observable.just('')
        .do(() => {
          liveBuilds++;
          d(`Starting build: ${ref.object.sha}`);
        })
        .delay(10*1000, this.sched)
        .do(() => {}, () => {}, () => {
          liveBuilds--;
          d(`Completing build: ${ref.object.sha}`);
        })
        .publish()
        .refCount();

      return Observable.create((subj) => {
        let producedItem = false;
        let disp = ret
          .do(() => producedItem = true)
          .subscribe(subj);

        return Disposable.create(() => {
          disp.dispose();
          if (producedItem) return;

          d(`Canceled ref before it finished! ${ref.object.sha}`);
          liveBuilds--;
          cancelledRefs.push(ref.object.sha);
        });
      });
    };

    this.fixture.seenCommits = getSeenRefs(this.refExamples['refs1.json']);

    this.fixture.fetchRefs = () =>
      Observable.just(this.refExamples['refs3.json']);

    this.fixture.start();
    this.sched.advanceBy(this.fixture.pollInterval + 1000);

    expect(liveBuilds).to.equal(2);

    this.fixture.fetchRefs = () =>
      Observable.just(this.refExamples['refs4.json']);

    this.sched.advanceBy(this.fixture.pollInterval + 1000);
    expect(liveBuilds).to.equal(1);
  });

  it('should cancel builds when their refs change', function() {
    let liveBuilds = 0;
    let cancelledRefs = [];

    this.fixture.runBuild = (ref) => {
      let ret = Observable.just('')
        .do(() => {
          liveBuilds++;
          d(`Starting build: ${ref.object.sha}`);
        })
        .delay(10*1000, this.sched)
        .do(() => {}, () => {}, () => {
          liveBuilds--;
          d(`Completing build: ${ref.object.sha}`);
        })
        .publish()
        .refCount();

      return Observable.create((subj) => {
        let producedItem = false;
        let disp = ret
          .do(() => producedItem = true)
          .subscribe(subj);

        return Disposable.create(() => {
          disp.dispose();
          if (producedItem) return;

          d(`Canceled ref before it finished! ${ref.object.sha}`);
          liveBuilds--;
          cancelledRefs.push(ref.object.sha);
        });
      });
    };

    this.fixture.fetchRefs = () =>
      Observable.just(this.refExamples['refs1.json']);

    this.fixture.start();
    this.sched.advanceBy(this.fixture.pollInterval + 1000);
    expect(liveBuilds).to.equal(2);

    this.fixture.fetchRefs = () =>
      Observable.just(this.refExamples['refs2.json']);

    this.sched.advanceBy(this.fixture.pollInterval + 1000);
    expect(liveBuilds).to.equal(2);
  });

  it('shouldnt die when builds fail', function() {
    this.fixture.runBuild = () => Observable.throw(new Error("no"));

    this.fixture.fetchRefs = () =>
      Observable.just(this.refExamples['refs1.json']);

    this.fixture.start();
    this.sched.advanceBy(this.fixture.pollInterval + 1);

    let ranBuild = false;
    this.fixture.runBuild = () => {
      ranBuild = true;
      return Observable.just('');
    };

    this.fixture.fetchRefs = () =>
      Observable.just(this.refExamples['refs2.json']);

    this.sched.advanceBy(this.fixture.pollInterval);

    expect(ranBuild).to.be.ok;
  });
});
<commit_msg>Revert "Aw jeez"<commit_after>import _ from 'lodash';
import path from 'path';
import {fs} from '../src/promisify';
import BuildMonitor from '../src/build-monitor';
import {Observable, TestScheduler, Disposable, Subject} from 'rx';
import '../src/custom-rx-operators';

const d = require('debug')('surf-test:build-monitor');

function getSeenRefs(refs) {
  return _.reduce(refs, (acc, x) => {
    acc.add(x.object.sha);
    return acc;
  }, new Set());
}

describe('the build monitor', function() {
  beforeEach(async function() {
    let acc = {};
    let fixturesDir = path.join(__dirname, '..', 'fixtures');

    for (let name of await fs.readdir(fixturesDir)) {
      if (!name.match(/^refs.*\.json$/i)) continue;

      let contents = await fs.readFile(path.join(fixturesDir, name), 'utf8');
      acc[name] = JSON.parse(contents.split('\n')[0]);
    }

    this.refExamples = acc;

    this.sched = new TestScheduler();
    this.fixture = new BuildMonitor(null, null, 2, null, null, this.sched);
  });

  afterEach(function() {
    this.fixture.dispose();
  });

  it('shouldnt run builds in getOrCreateBuild until you subscribe', function() {
    let buildCount = 0;
    let runBuildCount = 0;

    // Scheduling is live
    this.sched.start();

    let buildSubject = new Subject();
    this.fixture.runBuild = () => {
      runBuildCount++;
      return buildSubject.subUnsub(() => buildCount++);
    };

    d('Initial getOrCreateBuild');
    let ref = this.refExamples['refs1.json'][1];
    let result = this.fixture.getOrCreateBuild(ref);
    this.sched.start();
    expect(buildCount).to.equal(0);
    expect(runBuildCount).to.equal(1);

    d('Subscribing 1x');
    result.observable.subscribe();
    this.sched.start();
    expect(buildCount).to.equal(1);

    // Double subscribes do nothing
    d('Subscribing 2x');
    result.observable.subscribe();
    this.sched.start();
    expect(buildCount).to.equal(1);

    d('Second getOrCreateBuild');
    result = this.fixture.getOrCreateBuild(ref);
    result.observable.subscribe();
    this.sched.start();
    expect(buildCount).to.equal(1);
    expect(runBuildCount).to.equal(1);

    d('Complete the build');
    buildSubject.onNext('');
    buildSubject.onCompleted();

    d('Third getOrCreateBuild');
    result = this.fixture.getOrCreateBuild(ref);
    result.observable.subscribe();
    this.sched.start();
    expect(buildCount).to.equal(2);
    expect(runBuildCount).to.equal(2);
  });

  it('should decide to build new refs from a blank slate', function() {
    this.fixture.fetchRefs = () =>
      Observable.just(this.refExamples['refs1.json']);

    let buildCount = 0;
    this.fixture.runBuild = () => {
      buildCount++;
      return Observable.just('');
    };

    this.fixture.start();
    expect(buildCount).to.equal(0);

    this.sched.advanceBy(30*1000);
    expect(buildCount).to.equal(10);
  });

  it('should decide to build only changed refs', function() {
    this.fixture.fetchRefs = () =>
      Observable.just(this.refExamples['refs1.json']);

    let buildCount = 0;
    this.fixture.runBuild = (ref) => {
      buildCount++;
      return Observable.just('')
        .subUnsub(() => d(`Building ${ref.object.sha}`));
    };

    this.fixture.start();
    expect(buildCount).to.equal(0);

    this.sched.advanceBy(this.fixture.pollInterval + 1000);
    expect(buildCount).to.equal(10);

    this.fixture.fetchRefs = () =>
      Observable.just(this.refExamples['refs2.json']);

    // Move to the next interval, we should only run the one build
    this.sched.advanceBy(this.fixture.pollInterval);
    expect(buildCount).to.equal(11);
  });

  it('should only build at a max level of concurrency', function() {
    let liveBuilds = 0;
    let completedBuilds = 0;
    let completedShas = new Set();

    this.fixture.runBuild = (ref) => {
      return Observable.just('')
        .do(() => {
          if (completedShas.has(ref.object.sha)) d(`Double building! ${ref.object.sha}`);
          liveBuilds++;
          d(`Starting build: ${ref.object.sha}`);
        })
        .delay(2*1000, this.sched)
        .do(() => {}, () => {}, () => {
          liveBuilds--;
          completedBuilds++;
          completedShas.add(ref.object.sha);
          d(`Completing build: ${ref.object.sha}`);
        })
        .publish()
        .refCount();
    };

    this.fixture.fetchRefs = () =>
      Observable.just(this.refExamples['refs1.json']);

    this.fixture.start();
    this.sched.advanceBy(this.fixture.pollInterval + 2);

    expect(liveBuilds).to.equal(2);
    expect(completedBuilds).to.equal(0);

    this.sched.advanceBy(this.fixture.pollInterval);
    expect(liveBuilds).to.equal(2);
    expect(completedBuilds).to.equal(4);  // two builds per 2sec, for 5sec

    this.sched.advanceBy(30 * 1000);
    expect(liveBuilds).to.equal(0);
    expect(completedBuilds).to.equal(10);
  });

  it('shouldnt cancel any builds when we only look at one set of refs', function() {
    let liveBuilds = 0;
    let cancelledRefs = [];

    this.fixture.runBuild = (ref) => {
      let ret = Observable.just('')
        .do(() => {
          liveBuilds++;
          d(`Starting build: ${ref.object.sha}`);
        })
        .delay(2*1000, this.sched)
        .do(() => {}, () => {}, () => {
          liveBuilds--;
          d(`Completing build: ${ref.object.sha}`);
        })
        .publish()
        .refCount();

      return Observable.create((subj) => {
        let producedItem = false;
        let disp = ret
          .do(() => producedItem = true)
          .subscribe(subj);

        return Disposable.create(() => {
          disp.dispose();
          if (producedItem) return;

          d(`Canceled ref before it finished! ${ref.object.sha}`);
          liveBuilds--;
          cancelledRefs.push(ref.object.sha);
        });
      });
    };

    this.fixture.fetchRefs = () =>
      Observable.just(this.refExamples['refs1.json']);

    this.fixture.start();
    this.sched.advanceBy(this.fixture.pollInterval + 1000);

    expect(liveBuilds).to.equal(2);

    this.sched.advanceBy(1000);
    expect(liveBuilds).to.equal(2);

    this.sched.advanceBy(30 * 1000);

    expect(liveBuilds).to.equal(0);
    expect(cancelledRefs.length).to.equal(0);
  });

  it('should cancel builds when their refs disappear', function() {
    let liveBuilds = 0;
    let cancelledRefs = [];

    this.fixture.runBuild = (ref) => {
      let ret = Observable.just('')
        .do(() => {
          liveBuilds++;
          d(`Starting build: ${ref.object.sha}`);
        })
        .delay(10*1000, this.sched)
        .do(() => {}, () => {}, () => {
          liveBuilds--;
          d(`Completing build: ${ref.object.sha}`);
        })
        .publish()
        .refCount();

      return Observable.create((subj) => {
        let producedItem = false;
        let disp = ret
          .do(() => producedItem = true)
          .subscribe(subj);

        return Disposable.create(() => {
          disp.dispose();
          if (producedItem) return;

          d(`Canceled ref before it finished! ${ref.object.sha}`);
          liveBuilds--;
          cancelledRefs.push(ref.object.sha);
        });
      });
    };

    this.fixture.seenCommits = getSeenRefs(this.refExamples['refs1.json']);

    this.fixture.fetchRefs = () =>
      Observable.just(this.refExamples['refs3.json']);

    this.fixture.start();
    this.sched.advanceBy(this.fixture.pollInterval + 1000);

    expect(liveBuilds).to.equal(2);

    this.fixture.fetchRefs = () =>
      Observable.just(this.refExamples['refs4.json']);

    this.sched.advanceBy(this.fixture.pollInterval + 1000);
    expect(liveBuilds).to.equal(1);
  });

  it('should cancel builds when their refs change', function() {
    let liveBuilds = 0;
    let cancelledRefs = [];

    this.fixture.runBuild = (ref) => {
      let ret = Observable.just('')
        .do(() => {
          liveBuilds++;
          d(`Starting build: ${ref.object.sha}`);
        })
        .delay(10*1000, this.sched)
        .do(() => {}, () => {}, () => {
          liveBuilds--;
          d(`Completing build: ${ref.object.sha}`);
        })
        .publish()
        .refCount();

      return Observable.create((subj) => {
        let producedItem = false;
        let disp = ret
          .do(() => producedItem = true)
          .subscribe(subj);

        return Disposable.create(() => {
          disp.dispose();
          if (producedItem) return;

          d(`Canceled ref before it finished! ${ref.object.sha}`);
          liveBuilds--;
          cancelledRefs.push(ref.object.sha);
        });
      });
    };

    this.fixture.fetchRefs = () =>
      Observable.just(this.refExamples['refs1.json']);

    this.fixture.start();
    this.sched.advanceBy(this.fixture.pollInterval + 1000);
    expect(liveBuilds).to.equal(2);

    this.fixture.fetchRefs = () =>
      Observable.just(this.refExamples['refs2.json']);

    this.sched.advanceBy(this.fixture.pollInterval + 1000);
    expect(liveBuilds).to.equal(2);
  });

  it('shouldnt die when builds fail', function() {
    this.fixture.runBuild = () => Observable.throw(new Error("no"));

    this.fixture.fetchRefs = () =>
      Observable.just(this.refExamples['refs1.json']);

    this.fixture.start();
    this.sched.advanceBy(this.fixture.pollInterval + 1);

    let ranBuild = false;
    this.fixture.runBuild = () => {
      ranBuild = true;
      return Observable.just('');
    };

    this.fixture.fetchRefs = () =>
      Observable.just(this.refExamples['refs2.json']);

    this.sched.advanceBy(this.fixture.pollInterval);

    expect(ranBuild).to.be.ok;
  });
});
<|endoftext|>