<commit_before>/**
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you 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

    http://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.
*/

var fs = require('fs');
var path = require('path');
var properties_parser = require('properties-parser');
var AndroidManifest = require('./AndroidManifest');
var AndroidStudio = require('./AndroidStudio');
var pluginHandlers = require('./pluginHandlers');

var projectFileCache = {};

function addToPropertyList(projectProperties, key, value) {
    var i = 1;
    while (projectProperties.get(key + '.' + i))
        i++;

    projectProperties.set(key + '.' + i, value);
    projectProperties.dirty = true;
}

function removeFromPropertyList(projectProperties, key, value) {
    var i = 1;
    var currentValue;
    while ((currentValue = projectProperties.get(key + '.' + i))) {
        if (currentValue === value) {
            while ((currentValue = projectProperties.get(key + '.' + (i + 1)))) {
                projectProperties.set(key + '.' + i, currentValue);
                i++;
            }
            projectProperties.set(key + '.' + i);
            break;
        }
        i++;
    }
    projectProperties.dirty = true;
}

function getRelativeLibraryPath (parentDir, subDir) {
    var libraryPath = path.relative(parentDir, subDir);
    return (path.sep == '\\') ? libraryPath.replace(/\\/g, '/') : libraryPath;
}

function AndroidProject(projectDir) {
    this._propertiesEditors = {};
    this._subProjectDirs = {};
    this._dirty = false;
    this.projectDir = projectDir;
    this.platformWww = path.join(this.projectDir, 'platform_www');
    this.www = path.join(this.projectDir, 'assets/www');
    if(AndroidStudio.isAndroidStudioProject(projectDir) === true) {
      this.www = path.join(this.projectDir, 'app/src/main/assets/www');
    }
}

AndroidProject.getProjectFile = function (projectDir) {
    if (!projectFileCache[projectDir]) {
        projectFileCache[projectDir] = new AndroidProject(projectDir);
    }

    return projectFileCache[projectDir];
};

AndroidProject.purgeCache = function (projectDir) {
    if (projectDir) {
        delete projectFileCache[projectDir];
    } else {
        projectFileCache = {};
    }
};

/**
 * Reads the package name out of the Android Manifest file
 *
 * @param   {String}  projectDir  The absolute path to the directory containing the project
 *
 * @return  {String}              The name of the package
 */
AndroidProject.prototype.getPackageName = function() {
    var manifestPath = path.join(this.projectDir, 'AndroidManifest.xml');
    if(AndroidStudio.isAndroidStudioProject(this.projectDir) === true) {
      manifestPath = path.join(this.projectDir, 'app/src/main/AndroidManifest.xml');
    }
    return new AndroidManifest(manifestPath).getPackageId();
};

AndroidProject.prototype.getCustomSubprojectRelativeDir = function(plugin_id, src) {
    // All custom subprojects are prefixed with the last portion of the package id.
    // This is to avoid collisions when opening multiple projects in Eclipse that have subprojects with the same name.
    var packageName = this.getPackageName();
    var lastDotIndex = packageName.lastIndexOf('.');
    var prefix = packageName.substring(lastDotIndex + 1);
    var subRelativeDir = path.join(plugin_id, prefix + '-' + path.basename(src));
    return subRelativeDir;
};

AndroidProject.prototype.addSubProject = function(parentDir, subDir) {
    var parentProjectFile = path.resolve(parentDir, 'project.properties');
    var subProjectFile = path.resolve(subDir, 'project.properties');
    var parentProperties = this._getPropertiesFile(parentProjectFile);
    // TODO: Setting the target needs to happen only for pre-3.7.0 projects
    if (fs.existsSync(subProjectFile)) {
        var subProperties = this._getPropertiesFile(subProjectFile);
        subProperties.set('target', parentProperties.get('target'));
        subProperties.dirty = true;
        this._subProjectDirs[subDir] = true;
    }
    addToPropertyList(parentProperties, 'android.library.reference', getRelativeLibraryPath(parentDir, subDir));

    this._dirty = true;
};

AndroidProject.prototype.removeSubProject = function(parentDir, subDir) {
    var parentProjectFile = path.resolve(parentDir, 'project.properties');
    var parentProperties = this._getPropertiesFile(parentProjectFile);
    removeFromPropertyList(parentProperties, 'android.library.reference', getRelativeLibraryPath(parentDir, subDir));
    delete this._subProjectDirs[subDir];
    this._dirty = true;
};

AndroidProject.prototype.addGradleReference = function(parentDir, subDir) {
    var parentProjectFile = path.resolve(parentDir, 'project.properties');
    var parentProperties = this._getPropertiesFile(parentProjectFile);
    addToPropertyList(parentProperties, 'cordova.gradle.include', getRelativeLibraryPath(parentDir, subDir));
    this._dirty = true;
};

AndroidProject.prototype.removeGradleReference = function(parentDir, subDir) {
    var parentProjectFile = path.resolve(parentDir, 'project.properties');
    var parentProperties = this._getPropertiesFile(parentProjectFile);
    removeFromPropertyList(parentProperties, 'cordova.gradle.include', getRelativeLibraryPath(parentDir, subDir));
    this._dirty = true;
};

AndroidProject.prototype.addSystemLibrary = function(parentDir, value) {
    var parentProjectFile = path.resolve(parentDir, 'project.properties');
    var parentProperties = this._getPropertiesFile(parentProjectFile);
    addToPropertyList(parentProperties, 'cordova.system.library', value);
    this._dirty = true;
};

AndroidProject.prototype.removeSystemLibrary = function(parentDir, value) {
    var parentProjectFile = path.resolve(parentDir, 'project.properties');
    var parentProperties = this._getPropertiesFile(parentProjectFile);
    removeFromPropertyList(parentProperties, 'cordova.system.library', value);
    this._dirty = true;
};

AndroidProject.prototype.write = function() {
    if (!this._dirty) {
        return;
    }
    this._dirty = false;

    for (var filename in this._propertiesEditors) {
        var editor = this._propertiesEditors[filename];
        if (editor.dirty) {
            fs.writeFileSync(filename, editor.toString());
            editor.dirty = false;
        }
    }
};

AndroidProject.prototype._getPropertiesFile = function (filename) {
    if (!this._propertiesEditors[filename]) {
        if (fs.existsSync(filename)) {
            this._propertiesEditors[filename] = properties_parser.createEditor(filename);
        } else {
            this._propertiesEditors[filename] = properties_parser.createEditor();
        }
    }

    return this._propertiesEditors[filename];
};

AndroidProject.prototype.getInstaller = function (type) {
    return pluginHandlers.getInstaller(type);
};

AndroidProject.prototype.getUninstaller = function (type) {
    return pluginHandlers.getUninstaller(type);
};

/*
 * This checks if an Android project is clean or has old build artifacts
 */

AndroidProject.prototype.isClean = function() {
    var build_path = path.join(this.projectDir, "build");
    //If the build directory doesn't exist, it's clean
    return !(fs.existsSync(build_path));
};

module.exports = AndroidProject;
<commit_msg>Need to pass lint<commit_after>/**
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you 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

    http://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.
*/

var fs = require('fs');
var path = require('path');
var properties_parser = require('properties-parser');
var AndroidManifest = require('./AndroidManifest');
var AndroidStudio = require('./AndroidStudio');
var pluginHandlers = require('./pluginHandlers');

var projectFileCache = {};

function addToPropertyList(projectProperties, key, value) {
    var i = 1;
    while (projectProperties.get(key + '.' + i))
        i++;

    projectProperties.set(key + '.' + i, value);
    projectProperties.dirty = true;
}

function removeFromPropertyList(projectProperties, key, value) {
    var i = 1;
    var currentValue;
    while ((currentValue = projectProperties.get(key + '.' + i))) {
        if (currentValue === value) {
            while ((currentValue = projectProperties.get(key + '.' + (i + 1)))) {
                projectProperties.set(key + '.' + i, currentValue);
                i++;
            }
            projectProperties.set(key + '.' + i);
            break;
        }
        i++;
    }
    projectProperties.dirty = true;
}

function getRelativeLibraryPath (parentDir, subDir) {
    var libraryPath = path.relative(parentDir, subDir);
    return (path.sep == '\\') ? libraryPath.replace(/\\/g, '/') : libraryPath;
}

function AndroidProject(projectDir) {
    this._propertiesEditors = {};
    this._subProjectDirs = {};
    this._dirty = false;
    this.projectDir = projectDir;
    this.platformWww = path.join(this.projectDir, 'platform_www');
    this.www = path.join(this.projectDir, 'assets/www');
    if(AndroidStudio.isAndroidStudioProject(projectDir) === true) {
      this.www = path.join(this.projectDir, 'app/src/main/assets/www');
    }
}

AndroidProject.getProjectFile = function (projectDir) {
    if (!projectFileCache[projectDir]) {
        projectFileCache[projectDir] = new AndroidProject(projectDir);
    }

    return projectFileCache[projectDir];
};

AndroidProject.purgeCache = function (projectDir) {
    if (projectDir) {
        delete projectFileCache[projectDir];
    } else {
        projectFileCache = {};
    }
};

/**
 * Reads the package name out of the Android Manifest file
 *
 * @param   {String}  projectDir  The absolute path to the directory containing the project
 *
 * @return  {String}              The name of the package
 */
AndroidProject.prototype.getPackageName = function() {
    var manifestPath = path.join(this.projectDir, 'AndroidManifest.xml');
    if(AndroidStudio.isAndroidStudioProject(this.projectDir) === true) {
      manifestPath = path.join(this.projectDir, 'app/src/main/AndroidManifest.xml');
    }
    return new AndroidManifest(manifestPath).getPackageId();
};

AndroidProject.prototype.getCustomSubprojectRelativeDir = function(plugin_id, src) {
    // All custom subprojects are prefixed with the last portion of the package id.
    // This is to avoid collisions when opening multiple projects in Eclipse that have subprojects with the same name.
    var packageName = this.getPackageName();
    var lastDotIndex = packageName.lastIndexOf('.');
    var prefix = packageName.substring(lastDotIndex + 1);
    var subRelativeDir = path.join(plugin_id, prefix + '-' + path.basename(src));
    return subRelativeDir;
};

AndroidProject.prototype.addSubProject = function(parentDir, subDir) {
    var parentProjectFile = path.resolve(parentDir, 'project.properties');
    var subProjectFile = path.resolve(subDir, 'project.properties');
    var parentProperties = this._getPropertiesFile(parentProjectFile);
    // TODO: Setting the target needs to happen only for pre-3.7.0 projects
    if (fs.existsSync(subProjectFile)) {
        var subProperties = this._getPropertiesFile(subProjectFile);
        subProperties.set('target', parentProperties.get('target'));
        subProperties.dirty = true;
        this._subProjectDirs[subDir] = true;
    }
    addToPropertyList(parentProperties, 'android.library.reference', getRelativeLibraryPath(parentDir, subDir));

    this._dirty = true;
};

AndroidProject.prototype.removeSubProject = function(parentDir, subDir) {
    var parentProjectFile = path.resolve(parentDir, 'project.properties');
    var parentProperties = this._getPropertiesFile(parentProjectFile);
    removeFromPropertyList(parentProperties, 'android.library.reference', getRelativeLibraryPath(parentDir, subDir));
    delete this._subProjectDirs[subDir];
    this._dirty = true;
};

AndroidProject.prototype.addGradleReference = function(parentDir, subDir) {
    var parentProjectFile = path.resolve(parentDir, 'project.properties');
    var parentProperties = this._getPropertiesFile(parentProjectFile);
    addToPropertyList(parentProperties, 'cordova.gradle.include', getRelativeLibraryPath(parentDir, subDir));
    this._dirty = true;
};

AndroidProject.prototype.removeGradleReference = function(parentDir, subDir) {
    var parentProjectFile = path.resolve(parentDir, 'project.properties');
    var parentProperties = this._getPropertiesFile(parentProjectFile);
    removeFromPropertyList(parentProperties, 'cordova.gradle.include', getRelativeLibraryPath(parentDir, subDir));
    this._dirty = true;
};

AndroidProject.prototype.addSystemLibrary = function(parentDir, value) {
    var parentProjectFile = path.resolve(parentDir, 'project.properties');
    var parentProperties = this._getPropertiesFile(parentProjectFile);
    addToPropertyList(parentProperties, 'cordova.system.library', value);
    this._dirty = true;
};

AndroidProject.prototype.removeSystemLibrary = function(parentDir, value) {
    var parentProjectFile = path.resolve(parentDir, 'project.properties');
    var parentProperties = this._getPropertiesFile(parentProjectFile);
    removeFromPropertyList(parentProperties, 'cordova.system.library', value);
    this._dirty = true;
};

AndroidProject.prototype.write = function() {
    if (!this._dirty) {
        return;
    }
    this._dirty = false;

    for (var filename in this._propertiesEditors) {
        var editor = this._propertiesEditors[filename];
        if (editor.dirty) {
            fs.writeFileSync(filename, editor.toString());
            editor.dirty = false;
        }
    }
};

AndroidProject.prototype._getPropertiesFile = function (filename) {
    if (!this._propertiesEditors[filename]) {
        if (fs.existsSync(filename)) {
            this._propertiesEditors[filename] = properties_parser.createEditor(filename);
        } else {
            this._propertiesEditors[filename] = properties_parser.createEditor();
        }
    }

    return this._propertiesEditors[filename];
};

AndroidProject.prototype.getInstaller = function (type) {
    return pluginHandlers.getInstaller(type);
};

AndroidProject.prototype.getUninstaller = function (type) {
    return pluginHandlers.getUninstaller(type);
};

/*
 * This checks if an Android project is clean or has old build artifacts
 */

AndroidProject.prototype.isClean = function() {
    var build_path = path.join(this.projectDir, 'build');
    //If the build directory doesn't exist, it's clean
    return !(fs.existsSync(build_path));
};

module.exports = AndroidProject;
<|endoftext|>


<commit_before>function updateFromIri(iri) {
  fuseki( "metadata", iri );
  fuseki( "people", iri);
  fuseki( "chart", iri);
}

var _FUSEKI_URLS = {
    "http:" : "http://seweb.abdn.ac.uk/fuseki/ds/query",
    "file:" : "http://localhost:3030/ds/query"};

var fuseki = function(template_key, iri) { console.log("Error - not initialized"); };

function initFuseki() {
  fuseki = function(template_key, iri) {
    fusekiCall(
        _FUSEKI_URLS[$(location).attr('protocol')],
        template_key,
        iri,
        function () {
          console.log( "No response to " + template_key + " query for " + iri );
          $( "#myAjaxAlert" ).removeClass( "hide" );
        });
  };
}

function fusekiCall(fusekiUrl, template_key, iri, errorCallback) {
  var q = $( "body" ).data( "sparql-" + template_key).query.replace(/--IRI--/g, iri);
  $.ajax({
    url: fusekiUrl,
    data: {
      "query" : q},
    dataType: 'json',
    success: $( "body" ).data( "sparql-" + template_key).callback,
    timeout: 2500,
    error: errorCallback,
  });
}

function register(templateName, lines, callback) {
  $( "body" ).data( "sparql-" + templateName, {"query": _PREAMBLE.concat(lines).join("\n"), "callback": callback});
}

$( document ).ready( function() {
  initFuseki();
  register_all_sparql_queries();
  indexJsInit();
  initChart();
  setClickHandler(updateFromIri);
  updateFromIri( "http://dot.rural/sepake/UKEOFOrganisation#Scottish%20Environment%20Protection%20Agency" );
});

function _valuesOfSparqlBinding( sparqlBinding ) {
  var result = {};
  for (key in sparqlBinding) {
    result[key] = sparqlBinding[key].value;
  }
  return result;
}

_PREAMBLE = [
             "BASE <http://dot.rural/sepake/>",
             "PREFIX rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#>",
             "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>",
             "PREFIX prov: <http://www.w3.org/ns/prov#>",
             "PREFIX foaf: <http://xmlns.com/foaf/0.1/>",
             ];

function register_all_sparql_queries() {
  register(
      "metadata",
      [
       "SELECT * WHERE {",
       "    BIND (<--IRI--> AS ?focus) .",
       "    {?focus rdfs:label ?label} .",
       "    OPTIONAL {?focus <htmlDescription> ?description} .",
       "    OPTIONAL {?focus foaf:homepage ?homepage} .",
       "    OPTIONAL {?focus prov:startedAtTime ?startedAtTime} .",
       "    OPTIONAL {?focus prov:endedAtTime ?endedAtTime} .",
       "    OPTIONAL {?owner <owns> ?focus .",
       "               ?owner rdfs:label ?ownerLabel .",
       "               ?owner foaf:homepage ?ownerHomepage} .",
       "}",
       "LIMIT 1",
      ],
      function (response) {
        try{
          var values = _valuesOfSparqlBinding(response.results.bindings[0]);
          $( "#labelOfFocus" ).text(values.label);
          $( "#descriptionOfFocus" ).html(values.description || "(No summary)");
          $( "#homepageOfFocus" ).text(values.homepage || "");
          $( "#homepageOfFocus" ).attr("href", values.homepage || "");
          $( "#startedAtTime" ).text(values.startedAtTime || "(unknown)");
          $( "#endedAtTime" ).text(values.endedAtTime || "(unknown)");
          $( "#labelOfOwner" ).text(values.ownerLabel || "");
          $( "#labelOfOwner" ).attr('href', values.ownerHomepage || "");
        } catch (err) {
          console.log( err );
        }
      });
  register(
      "people",
      [
       "SELECT * WHERE {",
       "    BIND (<--IRI--> AS ?focus) .",
       "    {?person prov:memberOf ?focus} .",
       "    {?person foaf:givenName ?given} .",
       "    {?person foaf:familyName ?family} .",
       "    BIND (CONCAT(?given, ' ', ?family) AS ?label)",
       "}",
       "ORDER BY ASC(?family)",
       "LIMIT 11",
      ],
      function (response) {
        var bindings = response.results.bindings;
        $( "#personList .personWrapper" ).each( function(index, dom_elem) {//TODO: #personList -> .personList to allow several
          if (bindings.length > 0) {
            $( dom_elem ).data( bindings.shift() );
            $( dom_elem ).find( ".personLink" ).text( $( dom_elem ).data().label.value );
            $( dom_elem ).removeClass( "noData" );
          } else {
            $( dom_elem ).addClass( "noData" );
          }
        });
        if (bindings.length > 0) { //More results to display
          $( "#personList" ).removeClass( "noMore" );
        } else {
          $( "#personList" ).addClass( "noMore" );
        }
      });
  register(
      "searchables",
      [
       "SELECT * WHERE {",//TODO: Get type, but only one record per id, maybe using #3
       "    {?id rdfs:label ?label} .",
       "}",
      ],
      function (response) {
        $( "#search" ).trigger( "preloaded", {items: $.map( response.results.bindings, function(binding, index) {
          return _valuesOfSparqlBinding(binding);
        })});
      });
  register(
      "chart",
      [
       "SELECT ?owner ?ownerlabel ?owned ?ownedlabel WHERE {",
       "  {",
       "    BIND (<--IRI--> AS ?owner) .",
       "    {?owner <owns> ?owned} .",
       "    {?owner rdfs:label ?ownerlabel} .",
       "    {?owned rdfs:label ?ownedlabel} .",
       "  } UNION {",
       "    BIND (<--IRI--> AS ?focus) .",
       "    {?owner <owns> ?owned} .",
       "    {?owner <owns> ?focus} .",
       "    {?owner rdfs:label ?ownerlabel} .",
       "    {?owned rdfs:label ?ownedlabel} .",
       "  }",
       "}",
       "ORDER BY ?ownerlabel ?ownedlabel",
       "LIMIT 11",
      ],
      function (response) {
        removeAllNodesFromChart();
        $.each(response.results.bindings, function(index, binding){
          values = _valuesOfSparqlBinding(binding);
          //TODO Handle index > 9
          //Add owned always
          addNodeToChart(values.owned, values.ownedlabel, values.owner, 'owns');
          //Add owner if not there
          addNodeToChartIfNotThere(values.owner, values.ownerlabel, '', '');
        });
        updateChart();
      });
}
<commit_msg>Fixed bug: No owner found for "rainbow all sky imagers" although the chart says Lancaster Uni For #2-project-view<commit_after>function updateFromIri(iri) {
  fuseki( "metadata", iri );
  fuseki( "people", iri);
  fuseki( "chart", iri);
}

var _FUSEKI_URLS = {
    "http:" : "http://seweb.abdn.ac.uk/fuseki/ds/query",
    "file:" : "http://localhost:3030/ds/query"};

var fuseki = function(template_key, iri) { console.log("Error - not initialized"); };

function initFuseki() {
  fuseki = function(template_key, iri) {
    fusekiCall(
        _FUSEKI_URLS[$(location).attr('protocol')],
        template_key,
        iri,
        function () {
          console.log( "No response to " + template_key + " query for " + iri );
          $( "#myAjaxAlert" ).removeClass( "hide" );
        });
  };
}

function fusekiCall(fusekiUrl, template_key, iri, errorCallback) {
  var q = $( "body" ).data( "sparql-" + template_key).query.replace(/--IRI--/g, iri);
  $.ajax({
    url: fusekiUrl,
    data: {
      "query" : q},
    dataType: 'json',
    success: $( "body" ).data( "sparql-" + template_key).callback,
    timeout: 2500,
    error: errorCallback,
  });
}

function register(templateName, lines, callback) {
  $( "body" ).data( "sparql-" + templateName, {"query": _PREAMBLE.concat(lines).join("\n"), "callback": callback});
}

$( document ).ready( function() {
  initFuseki();
  register_all_sparql_queries();
  indexJsInit();
  initChart();
  setClickHandler(updateFromIri);
  updateFromIri( "http://dot.rural/sepake/UKEOFOrganisation#Scottish%20Environment%20Protection%20Agency" );
});

function _valuesOfSparqlBinding( sparqlBinding ) {
  var result = {};
  for (key in sparqlBinding) {
    result[key] = sparqlBinding[key].value;
  }
  return result;
}

_PREAMBLE = [
             "BASE <http://dot.rural/sepake/>",
             "PREFIX rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#>",
             "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>",
             "PREFIX prov: <http://www.w3.org/ns/prov#>",
             "PREFIX foaf: <http://xmlns.com/foaf/0.1/>",
             ];

function register_all_sparql_queries() {
  register(
      "metadata",
      [
       "SELECT * WHERE {",
       "    BIND (<--IRI--> AS ?focus) .",
       "    {?focus rdfs:label ?label} .",
       "    OPTIONAL {?focus <htmlDescription> ?description} .",
       "    OPTIONAL {?focus foaf:homepage ?homepage} .",
       "    OPTIONAL {?focus prov:startedAtTime ?startedAtTime} .",
       "    OPTIONAL {?focus prov:endedAtTime ?endedAtTime} .",
       "    OPTIONAL {?owner <owns> ?focus .",
       "              ?owner rdfs:label ?ownerLabel .",
       "              OPTIONAL {?owner foaf:homepage ?ownerHomepage}} .",
       "}",
       "LIMIT 1",
      ],
      function (response) {
        try{
          var values = _valuesOfSparqlBinding(response.results.bindings[0]);
          $( "#labelOfFocus" ).text(values.label);
          $( "#descriptionOfFocus" ).html(values.description || "(No summary)");
          $( "#homepageOfFocus" ).text(values.homepage || "");
          $( "#homepageOfFocus" ).attr("href", values.homepage || "");
          $( "#startedAtTime" ).text(values.startedAtTime || "(unknown)");
          $( "#endedAtTime" ).text(values.endedAtTime || "(unknown)");
          $( "#labelOfOwner" ).text(values.ownerLabel || "");
          $( "#labelOfOwner" ).attr('href', values.ownerHomepage || "");
        } catch (err) {
          console.log( err );
        }
      });
  register(
      "people",
      [
       "SELECT * WHERE {",
       "    BIND (<--IRI--> AS ?focus) .",
       "    {?person prov:memberOf ?focus} .",
       "    {?person foaf:givenName ?given} .",
       "    {?person foaf:familyName ?family} .",
       "    BIND (CONCAT(?given, ' ', ?family) AS ?label)",
       "}",
       "ORDER BY ASC(?family)",
       "LIMIT 11",
      ],
      function (response) {
        var bindings = response.results.bindings;
        $( "#personList .personWrapper" ).each( function(index, dom_elem) {//TODO: #personList -> .personList to allow several
          if (bindings.length > 0) {
            $( dom_elem ).data( bindings.shift() );
            $( dom_elem ).find( ".personLink" ).text( $( dom_elem ).data().label.value );
            $( dom_elem ).removeClass( "noData" );
          } else {
            $( dom_elem ).addClass( "noData" );
          }
        });
        if (bindings.length > 0) { //More results to display
          $( "#personList" ).removeClass( "noMore" );
        } else {
          $( "#personList" ).addClass( "noMore" );
        }
      });
  register(
      "searchables",
      [
       "SELECT * WHERE {",//TODO: Get type, but only one record per id, maybe using #3
       "    {?id rdfs:label ?label} .",
       "}",
      ],
      function (response) {
        $( "#search" ).trigger( "preloaded", {items: $.map( response.results.bindings, function(binding, index) {
          return _valuesOfSparqlBinding(binding);
        })});
      });
  register(
      "chart",
      [
       "SELECT ?owner ?ownerlabel ?owned ?ownedlabel WHERE {",
       "  {",
       "    BIND (<--IRI--> AS ?owner) .",
       "    {?owner <owns> ?owned} .",
       "    {?owner rdfs:label ?ownerlabel} .",
       "    {?owned rdfs:label ?ownedlabel} .",
       "  } UNION {",
       "    BIND (<--IRI--> AS ?focus) .",
       "    {?owner <owns> ?owned} .",
       "    {?owner <owns> ?focus} .",
       "    {?owner rdfs:label ?ownerlabel} .",
       "    {?owned rdfs:label ?ownedlabel} .",
       "  }",
       "}",
       "ORDER BY ?ownerlabel ?ownedlabel",
       "LIMIT 11",
      ],
      function (response) {
        removeAllNodesFromChart();
        $.each(response.results.bindings, function(index, binding){
          values = _valuesOfSparqlBinding(binding);
          //TODO Handle index > 9
          //Add owned always
          addNodeToChart(values.owned, values.ownedlabel, values.owner, 'owns');
          //Add owner if not there
          addNodeToChartIfNotThere(values.owner, values.ownerlabel, '', '');
        });
        updateChart();
      });
}
<|endoftext|>


<commit_before>var $ = require('jquery')
window.jQuery = $
var Handlebars = require('handlebars'),
    select2 = require("select2"),
    moment = require('moment'),
    _ = require('underscore'),
    Backbone = require('backbone')

var courseCollection = []

var SearchEngine = {

    searchBox: function (eventCal) {
        var that = this
        function formatRepo (repo) {
            if (repo.loading) return repo.text

            var markup = '
{{courseName}} - {{courseCode}}
'

            if (repo.description) { markup += '
' + repo.description + '
' }

            markup += '

'
            return markup
        }

        function formatRepoSelection (repo) {
            return repo.full_name || repo.text
        }
        //TODO: Korjaa Backendin REST APIa get parametrit oikein
        $(".js-data-example-ajax").select2({
            placeholder: "Select a state",
            ajax: {
                url: "http://localhost:8080/lukkarimaatti/rest/course/",
                dataType: 'json',
                delay: 150,
                data: function (params) {
                    return {
                        name: params.term,
                    }
                },
                processResults: function (data, page) {
                    // parse the results into the format expected by Select2.
                    // since we are using custom formatting functions we do not need to
                    // alter the remote JSON data
                    return {
                        results: data.items
                    }
                },
                cache: true
            },
            escapeMarkup: function (markup) { return markup }, // let our custom formatter work
            minimumInputLength: 1,
            templateResult: formatRepo, // omitted for brevity, see the source of this page
            templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
        })
    },

    addUrlParameter: function (courseCode, groupName) {
        var params = window.location.search
        var urlParam = courseCode.substring(0, 2) === 'FV' ? courseCode + '&' + groupName : courseCode
        if (params.length > 0) {
            history.pushState(
                {}, "", "index.html?" + params.substring(1, params.length) + '+' + urlParam)
        } else {
            history.pushState(
                {}, "", "index.html?" + params + urlParam)
        }
    },

    removeUrlParameter: function (id) {
        var params = window.location.search
        var updatedParams = params.substring(1, params.length).split('+').filter(function (p) {
            if (p.indexOf('&') > -1) {
                var groupLetterStripped = p.substring(0, p.indexOf('&'))
                return groupLetterStripped !== id
            } else {
                return p !== id
            }
        })
        if (updatedParams.length > 0) {
            history.pushState({}, "", "index.html?" + updatedParams.join('+'))
        } else {
            history.pushState({}, "", "index.html")
        }
    },

    getDataOnRefresh: function (calendar) {
        var params = window.location.search
        var courseCodes = params.substring(1, params.length).split(/[+]/)
        var that = this
        if (courseCodes[0].length > 0) {
            courseCodes.forEach(function (param) {
                var groupLetter = ""
                if (param.indexOf('&') > -1) {
                    groupLetter = param.substring(param.indexOf('&') + 1, param.length)
                    param = param.substring(0, param.indexOf('&'))
                }
                if (typeof param !== 'undefined') {
                    $.ajax({
                        url: '/rest/code/' + param,
                        type: 'GET',
                        success: function (data) {
                            that.courseCollection = data
                            if (groupLetter.length > 0 && data[0].courseCode.substring(0, 2) === 'FV') {
                                that.courseCollection = that.courseCollection.filter(function (d) {
                                    return d.groupName === groupLetter
                                })
                            }
                            that.addCourseLink(data[0].courseName, data[0].courseCode, data.length)
                            that.addDataToCalendar(calendar)
                        },
                        error: function (xhr, status, error) {
                            console.error('param ' + param + 'xhr' + xhr + ', status=' + status + ', error=' + error)
                        }
                    })
                } else {
                    console.log('Not a valid course code')
                }
            })
        }
    },

    addCourseLink: function (courseName, courseCode, occ) {
        if (typeof occ === 'undefined') {
            occ = 0
        }
        var noppa = 'https://noppa.lut.fi/noppa/opintojakso/'
        $('#courseList').append('
' +
            '' + occ + ', ' + courseCode + ' - ' + courseName + '' +
            '	' +
            '<button id="deleteButton" class="button" type="button">' +
            '' +
            '</button>' +
            '
')
    },

    removeCourseItem: function (element, id) {
        $(element).remove()
        this.removeUrlParameter(id)
    },

    addDataToCalendar: function (calendar) {
        var courseToBeAdded = []
        var that = this

        this.courseCollection.forEach(function (course) {
            function processWeekNumbers(weekNumber) {
                var dateStart = moment()
                    .lang('fi')
                    .years(that.getYearNumber(weekNumber))
                    .day(course.weekDay)
                    .week(weekNumber)
                    .hours(course.timeOfDay.split('-')[0] || 6).minutes(0)
                    .seconds(0)
                    .format('YYYY-MM-DDTHH:mm:ssZ')
                var dateEnd = moment()
                    .lang('fi')
                    .years(that.getYearNumber(weekNumber))
                    .day(course.weekDay).week(weekNumber)
                    .hours(course.timeOfDay.split('-')[1] || 6)
                    .minutes(0)
                    .seconds(0)
                    .format('YYYY-MM-DDTHH:mm:ssZ')
                var calendarEvent = {
                    title: course.courseCode,
                    description: course.courseName + '/' + course.type + '\n' + course.classroom,
                    start: new Date(dateStart),
                    end: new Date(dateEnd),
                    element: null,
                    color: that.stringToColour(course.courseCode),
                    view: null,
                    id: course.courseCode + '#' + course.type
                }
                courseToBeAdded.push(calendarEvent)
            }

            JSON.parse('[' + course.weekNumber + ']').map(processWeekNumbers)
        })
        calendar.createCalendarEvent(courseToBeAdded)
    },

    getYearNumber: function (weekNumber) {
        var isSpringSemester = moment().week() < 35
        if (!isSpringSemester) {
            return parseInt(weekNumber, 10) < 35 ? moment().add(1, 'y').year() : moment().year()
        } else {
            return parseInt(weekNumber, 10) >= 35 ? moment().subtract(1, 'y').year() : moment().year()
        }
    },

    stringToColour: function (colorSeed) {
        var hash = 0, colour = '#', value
        colorSeed.split("").forEach(function (e) {
            hash = colorSeed.charCodeAt(e) + ((hash << 5) - hash)
        })
        for (var j = 0; j < 3; j++) {
            value = (hash >> (j * 8)) & 0xFF
            colour += ('00' + value.toString(16)).substr(-2)
        }
        return colour
    },

    sendLink: function (address) {
        var link = window.location.href.toString()
        $.ajax({
            type: "POST",
            url: '/app/save',
            data: {email: address, link: link},
            dataType: 'json'
        })
    }

}

module.exports = SearchEngine
<commit_msg>dropdown works<commit_after>var $ = require('jquery')
window.jQuery = $
var Handlebars = require('handlebars'),
    select2 = require("select2"),
    moment = require('moment'),
    _ = require('underscore'),
    Backbone = require('backbone')

var courseCollection = []

var SearchEngine = {

    searchBox: function (eventCal) {
        var that = this
        function formatCourse (repo) {
            console.log('formatCourse='+JSON.stringify(repo))
            if (repo.loading) return repo.text

            var markup = '
'+repo.courseName+' - '+repo.courseCode+'
'

            if (repo.groupName) { markup += '
' + repo.groupName + '
' }

            markup += '

'
            return markup
        }

        function formatCourseSelection (repo) {
            console.log('formatCourseSelection='+JSON.stringify(repo))
            return repo.courseName || repo.courseCode
        }
        $(".js-data-example-ajax").select2({
            placeholder: "Select a state",
            ajax: {
                url: "http://localhost:8080/lukkarimaatti/rest/course/",
                dataType: 'json',
                delay: 150,
                data: function (params) {
                    return {
                        name: params.term,
                        page: params.page
                    }
                },
                processResults: function (data, page) {
                    // parse the results into the format expected by Select2.
                    // since we are using custom formatting functions we do not need to
                    // alter the remote JSON data

                    return {
                        results: _.uniq(data, function (cc) {
                            return cc.courseName + cc.courseCode + cc.groupName
                        })
                    }
                },
                cache: true
            },
            escapeMarkup: function (markup) { return markup }, // let our custom formatter work
            minimumInputLength: 2,
            templateResult: formatCourse, // omitted for brevity, see the source of this page
            templateSelection: formatCourseSelection // omitted for brevity, see the source of this page
        })
    },

    addUrlParameter: function (courseCode, groupName) {
        var params = window.location.search
        var urlParam = courseCode.substring(0, 2) === 'FV' ? courseCode + '&' + groupName : courseCode
        if (params.length > 0) {
            history.pushState(
                {}, "", "index.html?" + params.substring(1, params.length) + '+' + urlParam)
        } else {
            history.pushState(
                {}, "", "index.html?" + params + urlParam)
        }
    },

    removeUrlParameter: function (id) {
        var params = window.location.search
        var updatedParams = params.substring(1, params.length).split('+').filter(function (p) {
            if (p.indexOf('&') > -1) {
                var groupLetterStripped = p.substring(0, p.indexOf('&'))
                return groupLetterStripped !== id
            } else {
                return p !== id
            }
        })
        if (updatedParams.length > 0) {
            history.pushState({}, "", "index.html?" + updatedParams.join('+'))
        } else {
            history.pushState({}, "", "index.html")
        }
    },

    getDataOnRefresh: function (calendar) {
        var params = window.location.search
        var courseCodes = params.substring(1, params.length).split(/[+]/)
        var that = this
        if (courseCodes[0].length > 0) {
            courseCodes.forEach(function (param) {
                var groupLetter = ""
                if (param.indexOf('&') > -1) {
                    groupLetter = param.substring(param.indexOf('&') + 1, param.length)
                    param = param.substring(0, param.indexOf('&'))
                }
                if (typeof param !== 'undefined') {
                    $.ajax({
                        url: '/rest/code/' + param,
                        type: 'GET',
                        success: function (data) {
                            that.courseCollection = data
                            if (groupLetter.length > 0 && data[0].courseCode.substring(0, 2) === 'FV') {
                                that.courseCollection = that.courseCollection.filter(function (d) {
                                    return d.groupName === groupLetter
                                })
                            }
                            that.addCourseLink(data[0].courseName, data[0].courseCode, data.length)
                            that.addDataToCalendar(calendar)
                        },
                        error: function (xhr, status, error) {
                            console.error('param ' + param + 'xhr' + xhr + ', status=' + status + ', error=' + error)
                        }
                    })
                } else {
                    console.log('Not a valid course code')
                }
            })
        }
    },

    addCourseLink: function (courseName, courseCode, occ) {
        if (typeof occ === 'undefined') {
            occ = 0
        }
        var noppa = 'https://noppa.lut.fi/noppa/opintojakso/'
        $('#courseList').append('
' +
            '' + occ + ', ' + courseCode + ' - ' + courseName + '' +
            '	' +
            '<button id="deleteButton" class="button" type="button">' +
            '' +
            '</button>' +
            '
')
    },

    removeCourseItem: function (element, id) {
        $(element).remove()
        this.removeUrlParameter(id)
    },

    addDataToCalendar: function (calendar) {
        var courseToBeAdded = []
        var that = this

        this.courseCollection.forEach(function (course) {
            function processWeekNumbers(weekNumber) {
                var dateStart = moment()
                    .lang('fi')
                    .years(that.getYearNumber(weekNumber))
                    .day(course.weekDay)
                    .week(weekNumber)
                    .hours(course.timeOfDay.split('-')[0] || 6).minutes(0)
                    .seconds(0)
                    .format('YYYY-MM-DDTHH:mm:ssZ')
                var dateEnd = moment()
                    .lang('fi')
                    .years(that.getYearNumber(weekNumber))
                    .day(course.weekDay).week(weekNumber)
                    .hours(course.timeOfDay.split('-')[1] || 6)
                    .minutes(0)
                    .seconds(0)
                    .format('YYYY-MM-DDTHH:mm:ssZ')
                var calendarEvent = {
                    title: course.courseCode,
                    description: course.courseName + '/' + course.type + '\n' + course.classroom,
                    start: new Date(dateStart),
                    end: new Date(dateEnd),
                    element: null,
                    color: that.stringToColour(course.courseCode),
                    view: null,
                    id: course.courseCode + '#' + course.type
                }
                courseToBeAdded.push(calendarEvent)
            }

            JSON.parse('[' + course.weekNumber + ']').map(processWeekNumbers)
        })
        calendar.createCalendarEvent(courseToBeAdded)
    },

    getYearNumber: function (weekNumber) {
        var isSpringSemester = moment().week() < 35
        if (!isSpringSemester) {
            return parseInt(weekNumber, 10) < 35 ? moment().add(1, 'y').year() : moment().year()
        } else {
            return parseInt(weekNumber, 10) >= 35 ? moment().subtract(1, 'y').year() : moment().year()
        }
    },

    stringToColour: function (colorSeed) {
        var hash = 0, colour = '#', value
        colorSeed.split("").forEach(function (e) {
            hash = colorSeed.charCodeAt(e) + ((hash << 5) - hash)
        })
        for (var j = 0; j < 3; j++) {
            value = (hash >> (j * 8)) & 0xFF
            colour += ('00' + value.toString(16)).substr(-2)
        }
        return colour
    },

    sendLink: function (address) {
        var link = window.location.href.toString()
        $.ajax({
            type: "POST",
            url: '/app/save',
            data: {email: address, link: link},
            dataType: 'json'
        })
    }

}

module.exports = SearchEngine
<|endoftext|>


<commit_before>/*
 * L.Handler.MapDrag is used to make the map draggable (with panning inertia), enabled by default.
 */

L.Map.mergeOptions({
	dragging: true,

	inertia: !L.Browser.android23,
	inertiaDeceleration: 3400, // px/s^2
	inertiaMaxSpeed: Infinity, // px/s
	inertiaThreshold: L.Browser.touch ? 32 : 18, // ms
	easeLinearity: 0.25,

	// TODO refactor, move to CRS
	worldCopyJump: false
});

L.Map.Drag = L.Handler.extend({
	addHooks: function () {
		if (!this._draggable) {
			var map = this._map;

			this._draggable = new L.Draggable(map._mapPane, map._container);

			this._draggable.on({
				'dragstart': this._onDragStart,
				'drag': this._onDrag,
				'dragend': this._onDragEnd
			}, this);

			if (map.options.worldCopyJump) {
				this._draggable.on('predrag', this._onPreDrag, this);
				map.on('viewreset', this._onViewReset, this);

				map.once('load', this._onViewReset, this);
			}
		}
		this._draggable.enable();
	},

	removeHooks: function () {
		this._draggable.disable();
	},

	moved: function () {
		return this._draggable && this._draggable._moved;
	},

	_onDragStart: function () {
		var map = this._map;

		if (map._panAnim) {
			map._panAnim.stop();
		}

		map
		    .fire('movestart')
		    .fire('dragstart');

		if (map.options.inertia) {
			this._positions = [];
			this._times = [];
		}
	},

	_onDrag: function () {
		if (this._map.options.inertia) {
			var time = this._lastTime = +new Date(),
			    pos = this._lastPos = this._draggable._newPos;

			this._positions.push(pos);
			this._times.push(time);

			if (time - this._times[0] > 200) {
				this._positions.shift();
				this._times.shift();
			}
		}

		this._map
		    .fire('move')
		    .fire('drag');
	},

	_onViewReset: function () {
		// TODO fix hardcoded Earth values
		var pxCenter = this._map.getSize()._divideBy(2),
		    pxWorldCenter = this._map.latLngToLayerPoint([0, 0]);

		this._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x;
		this._worldWidth = this._map.project([0, 180]).x;
	},

	_onPreDrag: function () {
		// TODO refactor to be able to adjust map pane position after zoom
		var worldWidth = this._worldWidth,
		    halfWidth = Math.round(worldWidth / 2),
		    dx = this._initialWorldOffset,
		    x = this._draggable._newPos.x,
		    newX1 = (x - halfWidth + dx) % worldWidth + halfWidth - dx,
		    newX2 = (x + halfWidth + dx) % worldWidth - halfWidth - dx,
		    newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2;

		this._draggable._newPos.x = newX;
	},

	_onDragEnd: function () {
		var map = this._map,
		    options = map.options,
		    delay = +new Date() - this._lastTime,

		    noInertia = !options.inertia || delay > options.inertiaThreshold || !this._positions[0];

		map.fire('dragend');

		if (noInertia) {
			map.fire('moveend');

		} else {

			var direction = this._lastPos.subtract(this._positions[0]),
			    duration = (this._lastTime + delay - this._times[0]) / 1000,
			    ease = options.easeLinearity,

			    speedVector = direction.multiplyBy(ease / duration),
			    speed = speedVector.distanceTo([0, 0]),

			    limitedSpeed = Math.min(options.inertiaMaxSpeed, speed),
			    limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed),

			    decelerationDuration = limitedSpeed / (options.inertiaDeceleration * ease),
			    offset = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round();

			if (!offset.x || !offset.y) {
				map.fire('moveend');

			} else {
				L.Util.requestAnimFrame(function () {
					map.panBy(offset, {
						duration: decelerationDuration,
						easeLinearity: ease,
						noMoveStart: true
					});
				});
			}
		}
	}
});

L.Map.addInitHook('addHandler', 'dragging', L.Map.Drag);
<commit_msg>map.once doesn't get called when the map is already initailized and drag.enabled is called.<commit_after>/*
 * L.Handler.MapDrag is used to make the map draggable (with panning inertia), enabled by default.
 */

L.Map.mergeOptions({
	dragging: true,

	inertia: !L.Browser.android23,
	inertiaDeceleration: 3400, // px/s^2
	inertiaMaxSpeed: Infinity, // px/s
	inertiaThreshold: L.Browser.touch ? 32 : 18, // ms
	easeLinearity: 0.25,

	// TODO refactor, move to CRS
	worldCopyJump: false
});

L.Map.Drag = L.Handler.extend({
	addHooks: function () {
		if (!this._draggable) {
			var map = this._map;

			this._draggable = new L.Draggable(map._mapPane, map._container);

			this._draggable.on({
				'dragstart': this._onDragStart,
				'drag': this._onDrag,
				'dragend': this._onDragEnd
			}, this);

			if (map.options.worldCopyJump) {
				this._draggable.on('predrag', this._onPreDrag, this);
				map.on('viewreset', this._onViewReset, this);

				map.whenReady(this._onViewReset, this);
			}
		}
		this._draggable.enable();
	},

	removeHooks: function () {
		this._draggable.disable();
	},

	moved: function () {
		return this._draggable && this._draggable._moved;
	},

	_onDragStart: function () {
		var map = this._map;

		if (map._panAnim) {
			map._panAnim.stop();
		}

		map
		    .fire('movestart')
		    .fire('dragstart');

		if (map.options.inertia) {
			this._positions = [];
			this._times = [];
		}
	},

	_onDrag: function () {
		if (this._map.options.inertia) {
			var time = this._lastTime = +new Date(),
			    pos = this._lastPos = this._draggable._newPos;

			this._positions.push(pos);
			this._times.push(time);

			if (time - this._times[0] > 200) {
				this._positions.shift();
				this._times.shift();
			}
		}

		this._map
		    .fire('move')
		    .fire('drag');
	},

	_onViewReset: function () {
		// TODO fix hardcoded Earth values
		var pxCenter = this._map.getSize()._divideBy(2),
		    pxWorldCenter = this._map.latLngToLayerPoint([0, 0]);

		this._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x;
		this._worldWidth = this._map.project([0, 180]).x;
	},

	_onPreDrag: function () {
		// TODO refactor to be able to adjust map pane position after zoom
		var worldWidth = this._worldWidth,
		    halfWidth = Math.round(worldWidth / 2),
		    dx = this._initialWorldOffset,
		    x = this._draggable._newPos.x,
		    newX1 = (x - halfWidth + dx) % worldWidth + halfWidth - dx,
		    newX2 = (x + halfWidth + dx) % worldWidth - halfWidth - dx,
		    newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2;

		this._draggable._newPos.x = newX;
	},

	_onDragEnd: function () {
		var map = this._map,
		    options = map.options,
		    delay = +new Date() - this._lastTime,

		    noInertia = !options.inertia || delay > options.inertiaThreshold || !this._positions[0];

		map.fire('dragend');

		if (noInertia) {
			map.fire('moveend');

		} else {

			var direction = this._lastPos.subtract(this._positions[0]),
			    duration = (this._lastTime + delay - this._times[0]) / 1000,
			    ease = options.easeLinearity,

			    speedVector = direction.multiplyBy(ease / duration),
			    speed = speedVector.distanceTo([0, 0]),

			    limitedSpeed = Math.min(options.inertiaMaxSpeed, speed),
			    limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed),

			    decelerationDuration = limitedSpeed / (options.inertiaDeceleration * ease),
			    offset = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round();

			if (!offset.x || !offset.y) {
				map.fire('moveend');

			} else {
				L.Util.requestAnimFrame(function () {
					map.panBy(offset, {
						duration: decelerationDuration,
						easeLinearity: ease,
						noMoveStart: true
					});
				});
			}
		}
	}
});

L.Map.addInitHook('addHandler', 'dragging', L.Map.Drag);
<|endoftext|>


<commit_before>function EstaProyProvincia() {

    //dat del proyecto
    var provincias = new Array();
    event.preventDefault();
    $.ajax({
        "url": base_url + "index.php/PrincipalPmi/EstadisticaPipProvinc",
        type: "POST",
        success: function (respuesta) {
            var registros = eval(respuesta);
            var sum = 0;
            for (var i = 0; i < registros.length; i++) {
                provincias[i] = registros[i]["Cantidadpip"];
                sum = provincias[i] + sum;

            }
            ;
            $("#NumPip").html(sum); //OBTENER NUMERO DE PIP EN LA CABECERA
            cantidadPIPAbancay = (100 * (parseInt(provincias[0])) / sum);
            $("#CantidadPAbancay").html(provincias[0]); //LISTAR CANTIDAD DE PIP REPORTE GENERAL
            $("#porcentajeAban").html(cantidadPIPAbancay.toFixed(2)); //LISTAR PORCENTAJES EN EL GRAFICO PROYECTOS POR PRIVINCIAS EN TEXTO
            cantidadPIPAndahuaylas = (100 * (parseInt(provincias[1])) / sum);
            $("#CantidadPAndahuaylas").html(provincias[1]);
            $("#porcentajeAnd").html(cantidadPIPAndahuaylas.toFixed(2));
            cantidadPIPAntabamba = (100 * (parseInt(provincias[2])) / sum);
            $("#CantidadPAntabamba").html(provincias[2]);
            $("#porcentajeAnt").html(cantidadPIPAntabamba.toFixed(2));
            cantidadPIPAymaraes = (100 * (parseInt(provincias[3])) / sum);
            $("#CantidadPAymaraes").html(provincias[3]);
            $("#porcentajeAy").html(cantidadPIPAymaraes.toFixed(2));
            cantidadPIPChincheros = (100 * (parseInt(provincias[4])) / sum);
            $("#CantidadPChincheros").html(provincias[4]);
            $("#porcentajeChinc").html(cantidadPIPChincheros.toFixed(2));
            cantidadPIPCotabambas = (100 * (parseInt(provincias[5])) / sum);
            $("#CantidadPCotabambas").html(provincias[5]);
            $("#porcentajeCotab").html(cantidadPIPCotabambas.toFixed(2));
            cantidadPIPGrau = (100 * (parseInt(provincias[6])) / sum);
            $("#CantidadPGrau").html(provincias[6]);
            $("#porcentajeGrau").html(cantidadPIPGrau.toFixed(2));
            if ("undefined" != typeof Chart && (console.log("init_chart_doughnut"), $(".canvasDoughnut1").length)) {
                var a = {
                    type: "doughnut",
                    tooltipFillColor: "rgba(51, 51, 51, 0.55)",
                    data: {
                        labels: ["Abancay", "Andahuaylas", "Antabamba", "Aymaraes", "Contabambas", "Chincheros", "Grau"],
                        datasets: [{
                            data: [cantidadPIPAbancay, cantidadPIPAndahuaylas, cantidadPIPAntabamba, cantidadPIPAymaraes, cantidadPIPChincheros, cantidadPIPCotabambas, cantidadPIPGrau],
                            backgroundColor: ["#3498DB", "#9B59B6", "#E74C3C", "#26B99A", "#B6CBD6", "#708B99", "#52C5E1"],
                            hoverBackgroundColor: ["#3498DB", "#B370CF", "#E95E4F", "#36CAAB", "#BDD3DF", "#7C96A3", "#52C5E1"]
                        }]
                    },
                    options: {legend: !1, responsive: !1}
                };
                $(".canvasDoughnut1").each(function () {
                    console.log('Access success.');
                    var b = $(this);
                    new Chart(b, a)
                })
            }

        }
    });
    //fin data del proyecto
}

var EstadistMontosPipProv = function () {
    var MontosPipProv = new Array();
    html1 = "";
    $.ajax({
        "url": base_url + "index.php/PrincipalPmi/EstadisticaMontoPipProvincias",
        success: function (respuesta) {
            var registros = eval(respuesta);
            var suma = 0;
            html1 += "

Provincia

Estadistica

Montos

"
            for (var i = 0; i < registros.length; i++) {
                MontosPipProv[i] = registros[i]["MontoProyecto"]; //OPCIONAL, SIRVE PARA IMPRIR LOS MONTOS  EN DATOS PIP PROYECTOS POR PROVINCIA EN LOS DIV
                suma = MontosPipProv[i] + suma; //TOTAL MONTO PROYECTOS EN CABECERA

                html1 += "

" + registros[i]["provincia"] + "

 	" + registros[i]["MontoProyecto"] + "
";
                //alert(suma);
            }
            ;
            html1 += "
";
            $("#table-estaditMontPIPProv").html(html1);

            document.getElementById("MontoPipAbancay").innerHTML = MontosPipProv[0]; // MONTO TOTAL DE ABANCAY EN EL DIV MontoPipAbancay
            document.getElementById("MontoPipAndahuaylas").innerHTML = MontosPipProv[1];
            document.getElementById("MontoPipAntabamba").innerHTML = MontosPipProv[2];
            document.getElementById("MontoPipAymaraes").innerHTML = MontosPipProv[3];
            document.getElementById("MontoPipChincheros").innerHTML = MontosPipProv[4];
            document.getElementById("MontoPipCotabambas").innerHTML = MontosPipProv[5];
            document.getElementById("MontoPipGrau").innerHTML = MontosPipProv[6];
            //OBTENER EL MONTO TOTAL DE PROYECTOS EN LA CABECERA
            document.getElementById("MontoTotalPip").innerHTML = suma;
        }
    });
};

function EstadisticasPorCiclosInversion() {
    $.ajax({
        url: base_url + "index.php/PrincipalPmi/EstadisticaPipEstadoCiclo",
        type: "POST",
        success: function (respuesta) {
            var registros = eval(respuesta);
            var sql = "";
            var NumProyectos = 0;
            var total_proyectos = registros[0]["Num_Total"];
            var total_otros = registros[0]["TotalNoCiclo"];
            var panel_estadistica = $("#panel_estadistica_ciclo_inversion");

            var porcentaje = 0.00;
            for (var i = 0; i < registros.length; i++) {
                NumProyectos = registros[i]["Num_Proyectos"];
                porcentaje = Math.round((NumProyectos / total_proyectos) * 100);
                sql = "
\n"
                    + "
\n"
                    + "                            " + registros[i]["nombre_estado_ciclo"] + "\n"
                    + "
\n"
                    + "
\n"
                    + "
\n"
                    + "
\n"
                    + "                                    " + porcentaje + "%\n"
                    + "
\n"
                    + "
\n"
                    + "
\n"
                    + "
\n"
                    + "                            " + NumProyectos + "\n"
                    + "
\n"
                    + "

\n"
                    + "
";

                panel_estadistica.append(sql);
                //html += "<option value=" + registros[i]["id_subgerencia"] + "> " + registros[i]["denom_subgerencia"] + " </option>";
            }

            porcentaje = Math.round((total_otros / total_proyectos) * 100);
            sql = "
\n"
                + "
\n"
                + "                            Otros\n"
                + "
\n"
                + "
\n"
                + "
\n"
                + "
\n"
                + "                                    " + porcentaje + "%\n"
                + "
\n"
                + "
\n"
                + "
\n"
                + "
\n"
                + "                            " + total_otros + "\n"
                + "
\n"
                + "

\n"
                + "
";

            panel_estadistica.append(sql);
        }
    });
}

function initMap() {

    //var LatLng = {lat: -25.363, lng: 131.044};

    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 8,
        center: {lat: -14, lng: -73},
        //disableDefaultUI: true
    });

    $.ajax({
        url: base_url + "index.php/PrincipalPmi/GetDatosUbicacion",
        type: "POST",
        success: function (respuesta) {
            var registros = eval(respuesta);

            var marker;
            for (var i = 0; i < registros.length; i++) {

                marker = new google.maps.Marker({
                    position: {lat: registros[i]["latitud"], lng: registros[i]["longitud"]},
                    map: map,
                    title: registros[i]["distrito"] + ": " + registros[i]["nombre_pi"]
                })
            }
        }
    });
}

$(document).ready(function () {
    EstaProyProvincia();
    EstadistMontosPipProv();
    EstadisticasPorCiclosInversion();
});
<commit_msg>Código refactorizado en "pmi.js". Cambio de códigos JavaScript nativo por JQuery.<commit_after>function EstaProyProvincia() {

    //dat del proyecto
    var provincias = new Array();
    event.preventDefault();
    $.ajax({
        "url": base_url + "index.php/PrincipalPmi/EstadisticaPipProvinc",
        type: "POST",
        success: function (respuesta) {
            var registros = eval(respuesta);
            var sum = 0;
            for (var i = 0; i < registros.length; i++) {
                provincias[i] = registros[i]["Cantidadpip"];
                sum = provincias[i] + sum;

            }
            ;
            $("#NumPip").html(sum); //OBTENER NUMERO DE PIP EN LA CABECERA
            cantidadPIPAbancay = (100 * (parseInt(provincias[0])) / sum);
            $("#CantidadPAbancay").html(provincias[0]); //LISTAR CANTIDAD DE PIP REPORTE GENERAL
            $("#porcentajeAban").html(cantidadPIPAbancay.toFixed(2)); //LISTAR PORCENTAJES EN EL GRAFICO PROYECTOS POR PRIVINCIAS EN TEXTO
            cantidadPIPAndahuaylas = (100 * (parseInt(provincias[1])) / sum);
            $("#CantidadPAndahuaylas").html(provincias[1]);
            $("#porcentajeAnd").html(cantidadPIPAndahuaylas.toFixed(2));
            cantidadPIPAntabamba = (100 * (parseInt(provincias[2])) / sum);
            $("#CantidadPAntabamba").html(provincias[2]);
            $("#porcentajeAnt").html(cantidadPIPAntabamba.toFixed(2));
            cantidadPIPAymaraes = (100 * (parseInt(provincias[3])) / sum);
            $("#CantidadPAymaraes").html(provincias[3]);
            $("#porcentajeAy").html(cantidadPIPAymaraes.toFixed(2));
            cantidadPIPChincheros = (100 * (parseInt(provincias[4])) / sum);
            $("#CantidadPChincheros").html(provincias[4]);
            $("#porcentajeChinc").html(cantidadPIPChincheros.toFixed(2));
            cantidadPIPCotabambas = (100 * (parseInt(provincias[5])) / sum);
            $("#CantidadPCotabambas").html(provincias[5]);
            $("#porcentajeCotab").html(cantidadPIPCotabambas.toFixed(2));
            cantidadPIPGrau = (100 * (parseInt(provincias[6])) / sum);
            $("#CantidadPGrau").html(provincias[6]);
            $("#porcentajeGrau").html(cantidadPIPGrau.toFixed(2));
            if ("undefined" != typeof Chart && (console.log("init_chart_doughnut"), $(".canvasDoughnut1").length)) {
                var a = {
                    type: "doughnut",
                    tooltipFillColor: "rgba(51, 51, 51, 0.55)",
                    data: {
                        labels: ["Abancay", "Andahuaylas", "Antabamba", "Aymaraes", "Contabambas", "Chincheros", "Grau"],
                        datasets: [{
                            data: [cantidadPIPAbancay, cantidadPIPAndahuaylas, cantidadPIPAntabamba, cantidadPIPAymaraes, cantidadPIPChincheros, cantidadPIPCotabambas, cantidadPIPGrau],
                            backgroundColor: ["#3498DB", "#9B59B6", "#E74C3C", "#26B99A", "#B6CBD6", "#708B99", "#52C5E1"],
                            hoverBackgroundColor: ["#3498DB", "#B370CF", "#E95E4F", "#36CAAB", "#BDD3DF", "#7C96A3", "#52C5E1"]
                        }]
                    },
                    options: {legend: !1, responsive: !1}
                };
                $(".canvasDoughnut1").each(function () {
                    console.log('Access success.');
                    var b = $(this);
                    new Chart(b, a)
                })
            }

        }
    });
    //fin data del proyecto
}

var EstadistMontosPipProv = function () {
    var MontosPipProv = new Array();
    html1 = "";
    $.ajax({
        "url": base_url + "index.php/PrincipalPmi/EstadisticaMontoPipProvincias",
        success: function (respuesta) {
            var registros = eval(respuesta);
            var suma = 0;
            html1 += "

Provincia

Estadistica

Montos

"
            for (var i = 0; i < registros.length; i++) {
                MontosPipProv[i] = registros[i]["MontoProyecto"]; //OPCIONAL, SIRVE PARA IMPRIR LOS MONTOS  EN DATOS PIP PROYECTOS POR PROVINCIA EN LOS DIV
                suma = MontosPipProv[i] + suma; //TOTAL MONTO PROYECTOS EN CABECERA

                html1 += "

" + registros[i]["provincia"] + "

 	" + registros[i]["MontoProyecto"] + "
";
                //alert(suma);
            }
            ;
            html1 += "
";
            $("#table-estaditMontPIPProv").html(html1);

            $("#MontoPipAbancay").html(MontosPipProv[0]); // MONTO TOTAL DE ABANCAY EN EL DIV MontoPipAbancay
            $("#MontoPipAndahuaylas").html(MontosPipProv[1]);
            $("#MontoPipAntabamba").html(MontosPipProv[2]);
            $("#MontoPipAymaraes").html(MontosPipProv[3]);
            $("#MontoPipChincheros").html(MontosPipProv[4]);
            $("#MontoPipCotabambas").html(MontosPipProv[5]);
            $("#MontoPipGrau").html(MontosPipProv[6]);
            //OBTENER EL MONTO TOTAL DE PROYECTOS EN LA CABECERA
            $("#MontoTotalPip").html(suma);
        }
    });
};

function EstadisticasPorCiclosInversion() {
    $.ajax({
        url: base_url + "index.php/PrincipalPmi/EstadisticaPipEstadoCiclo",
        type: "POST",
        success: function (respuesta) {
            var registros = eval(respuesta);
            var sql = "";
            var NumProyectos = 0;
            var total_proyectos = registros[0]["Num_Total"];
            var total_otros = registros[0]["TotalNoCiclo"];
            var panel_estadistica = $("#panel_estadistica_ciclo_inversion");

            var porcentaje = 0.00;
            for (var i = 0; i < registros.length; i++) {
                NumProyectos = registros[i]["Num_Proyectos"];
                porcentaje = Math.round((NumProyectos / total_proyectos) * 100);
                sql = "
\n"
                    + "
\n"
                    + "                            " + registros[i]["nombre_estado_ciclo"] + "\n"
                    + "
\n"
                    + "
\n"
                    + "
\n"
                    + "
\n"
                    + "                                    " + porcentaje + "%\n"
                    + "
\n"
                    + "
\n"
                    + "
\n"
                    + "
\n"
                    + "                            " + NumProyectos + "\n"
                    + "
\n"
                    + "

\n"
                    + "
";

                panel_estadistica.append(sql);
                //html += "<option value=" + registros[i]["id_subgerencia"] + "> " + registros[i]["denom_subgerencia"] + " </option>";
            }

            porcentaje = Math.round((total_otros / total_proyectos) * 100);
            sql = "
\n"
                + "
\n"
                + "                            Otros\n"
                + "
\n"
                + "
\n"
                + "
\n"
                + "
\n"
                + "                                    " + porcentaje + "%\n"
                + "
\n"
                + "
\n"
                + "
\n"
                + "
\n"
                + "                            " + total_otros + "\n"
                + "
\n"
                + "

\n"
                + "
";

            panel_estadistica.append(sql);
        }
    });
}

function initMap() {

    //var LatLng = {lat: -25.363, lng: 131.044};

    var map = new google.maps.Map($('#map'), {
        zoom: 8,
        center: {lat: -14, lng: -73},
        //disableDefaultUI: true
    });

    $.ajax({
        url: base_url + "index.php/PrincipalPmi/GetDatosUbicacion",
        type: "POST",
        success: function (respuesta) {
            var registros = eval(respuesta);

            var marker;
            for (var i = 0; i < registros.length; i++) {

                marker = new google.maps.Marker({
                    position: {lat: registros[i]["latitud"], lng: registros[i]["longitud"]},
                    map: map,
                    title: registros[i]["distrito"] + ": " + registros[i]["nombre_pi"]
                })
            }
        }
    });
}

$(document).ready(function () {
    EstaProyProvincia();
    EstadistMontosPipProv();
    EstadisticasPorCiclosInversion();
});
<|endoftext|>


<commit_before>/**
 * Count pageviews form GA or local cache file.
 *
 * Dependences:
 *   - jQuery
 *   - countUp.js <https://github.com/inorganik/countUp.js>
 *
 * v2.0
 * https://github.com/cotes2020/jekyll-theme-chirpy
 * © 2018-2019 Cotes Chung
 * MIT License
 */

function countUp(min, max, destId) {
  if (min < max) {
    var numAnim = new CountUp(destId, min, max);
    if (!numAnim.error) {
      numAnim.start();
    } else {
      console.error(numAnim.error);
    }
  }
}

function countPV(path, rows) {
  var count = 0;

  for (var i = 0; i < rows.length; ++i) {
    var gaPath = rows[i][0];
    if (gaPath == path) { /* path format see: site.permalink */
      count += parseInt(rows[i][1]);
      break;
    }
  }

  return count;
}

function tacklePV(rows, path, elem, hasInit) {
  var count = countPV(path, rows);
  count = (count == 0 ? 1 : count);

  if (!hasInit) {
    elem.text(new Intl.NumberFormat().format(count));
  } else {
    var initCount = parseInt(elem.text().replace(/,/g, ''));
    if (count > initCount) {
      countUp(initCount, count, elem.attr('id'));
    }
  }
}

function displayPageviews(data) {
  if (data === undefined) {
    return;
  }

  var hasInit = getInitStatus();
  var rows = data.rows;

  if ($("#post-list").length > 0) { /* the Home page */
    $(".post-preview").each(function() {
      var path = $(this).children("div").children("h1").children("a").attr("href");
      tacklePV(rows, path, $(this).find('.pageviews'), hasInit);
    });

  } else if ($(".post").length > 0) { /* the post */
    var path = window.location.pathname;
    tacklePV(rows, path, $('#pv'), hasInit);
  }
}

var getInitStatus = (function() {
  var hasInit = false;
  return function() {
    let ret = hasInit;
    if (!hasInit) {
      hasInit = true;
    }
    return ret;
  }
})();

var PvCache = (function() {
  const KEY_PV = "pv";
  const KEY_CREATION = "pv_created_date";
  const KEY_PV_SRC = "pv_source";

  var Source = {
    ORIGIN: "origin",
    PROXY: "proxy"
  };

  function get(key) {
    return localStorage.getItem(key);
  }

  function set(key, val) {
    localStorage.setItem(key, val);
  }

  return {
    getData: function() {
      return JSON.parse(localStorage.getItem(KEY_PV) );
    },
    saveOriginCache: function(pv) {
      set(KEY_PV, pv);
      set(KEY_PV_SRC, Source.ORIGIN );
      set(KEY_CREATION, new Date().toJSON() );
    },
    saveProxyCache: function(pv) {
      set(KEY_PV, pv);
      set(KEY_PV_SRC, Source.PROXY );
      set(KEY_CREATION, new Date().toJSON() );
    },
    isFromOrigin: function() {
      return get(KEY_PV_SRC) == Source.ORIGIN;
    },
    isFromProxy: function() {
      return get(KEY_PV_SRC) == Source.PROXY;
    },
    isExpired: function() {
      if (PvCache.isFromOrigin() ) {
        let date = new Date(get(KEY_CREATION));
        date.setDate(date.getDate() + 1); /* update origin records every day */
        return Date.now() >= date.getTime();

      } else if (PvCache.isFromProxy() ) {
        let date = new Date(get(KEY_CREATION) );
        date.setHours(date.getHours() + 1); /* update proxy records per hour */
        return Date.now() >= date.getTime();
      }
      return false;
    },
    getAllPagevies: function() {
      return PvCache.getData().totalsForAllResults["ga:pageviews"];
    },
    newerThan: function(pv) {
      return PvCache.getAllPagevies() > pv.totalsForAllResults["ga:pageviews"];
    },
    inspectKeys: function() {
      if (localStorage.getItem(KEY_PV) == null
        || localStorage.getItem(KEY_PV_SRC) == null
        || localStorage.getItem(KEY_CREATION) == null) {
        localStorage.clear();
      }
    }
  };

})(); /* PvCache */

function fetchPageviews(fetchOrigin = true, filterOrigin = false) {
  /* pvCacheEnabled › see: /assets/js/_pv-config.js */
  if (pvCacheEnabled && fetchOrigin) {
    fetch('/assets/js/data/pageviews.json')
      .then(response => response.json())
      .then(data => {
        if (filterOrigin) {
          if (PvCache.newerThan(data)) {
            return;
          }
        }
        displayPageviews(data);
        PvCache.saveOriginCache(JSON.stringify(data));
      })
      .then(() => fetchProxyPageviews());

  } else {
    fetchProxyPageviews();
  }

}

function fetchProxyPageviews() {
  $.ajax({
    type: 'GET',
    url: proxyEndpoint, /* see: /assets/js/_pv-config.js */
    dataType: 'jsonp',
    jsonpCallback: "displayPageviews",
    success: function(data, textStatus, jqXHR) {
      PvCache.saveProxyCache(JSON.stringify(data));
    },
    error: function(jqXHR, textStatus, errorThrown) {
      console.log("Failed to load pageviews from proxy server: " + errorThrown);
    }
  });
}

$(function() {

  if ($('.pageviews').length > 0) {

    PvCache.inspectKeys();
    let cache = PvCache.getData();

    if (cache) {
      displayPageviews(cache);

      if (PvCache.isExpired()) {
        fetchPageviews(true, PvCache.isFromProxy());

      } else {

        if (PvCache.isFromOrigin()) {
          fetchPageviews(false);
        }

      }

    } else {
      fetchPageviews();
    }

  }

});
<commit_msg>Fixed empty PV issue.<commit_after>/**
 * Count pageviews form GA or local cache file.
 *
 * Dependences:
 *   - jQuery
 *   - countUp.js <https://github.com/inorganik/countUp.js>
 *
 * v2.0
 * https://github.com/cotes2020/jekyll-theme-chirpy
 * © 2018-2019 Cotes Chung
 * MIT License
 */

function countUp(min, max, destId) {
  if (min < max) {
    var numAnim = new CountUp(destId, min, max);
    if (!numAnim.error) {
      numAnim.start();
    } else {
      console.error(numAnim.error);
    }
  }
}

function countPV(path, rows) {
  var count = 0;

  if (rows !== undefined ) {
    for (var i = 0; i < rows.length; ++i) {
      var gaPath = rows[i][0];
      if (gaPath == path) { /* path format see: site.permalink */
        count += parseInt(rows[i][1]);
        break;
      }
    }
  }

  return count;
}

function tacklePV(rows, path, elem, hasInit) {
  var count = countPV(path, rows);
  count = (count == 0 ? 1 : count);

  if (!hasInit) {
    elem.text(new Intl.NumberFormat().format(count));
  } else {
    var initCount = parseInt(elem.text().replace(/,/g, ''));
    if (count > initCount) {
      countUp(initCount, count, elem.attr('id'));
    }
  }
}

function displayPageviews(data) {
  if (data === undefined) {
    return;
  }

  var hasInit = getInitStatus();
  var rows = data.rows; /* could be undefined */

  if ($("#post-list").length > 0) { /* the Home page */
    $(".post-preview").each(function() {
      var path = $(this).children("div").children("h1").children("a").attr("href");
      tacklePV(rows, path, $(this).find('.pageviews'), hasInit);
    });

  } else if ($(".post").length > 0) { /* the post */
    var path = window.location.pathname;
    tacklePV(rows, path, $('#pv'), hasInit);
  }
}

var getInitStatus = (function() {
  var hasInit = false;
  return function() {
    let ret = hasInit;
    if (!hasInit) {
      hasInit = true;
    }
    return ret;
  }
})();

var PvCache = (function() {
  const KEY_PV = "pv";
  const KEY_CREATION = "pv_created_date";
  const KEY_PV_SRC = "pv_source";

  var Source = {
    ORIGIN: "origin",
    PROXY: "proxy"
  };

  function get(key) {
    return localStorage.getItem(key);
  }

  function set(key, val) {
    localStorage.setItem(key, val);
  }

  return {
    getData: function() {
      return JSON.parse(localStorage.getItem(KEY_PV) );
    },
    saveOriginCache: function(pv) {
      set(KEY_PV, pv);
      set(KEY_PV_SRC, Source.ORIGIN );
      set(KEY_CREATION, new Date().toJSON() );
    },
    saveProxyCache: function(pv) {
      set(KEY_PV, pv);
      set(KEY_PV_SRC, Source.PROXY );
      set(KEY_CREATION, new Date().toJSON() );
    },
    isFromOrigin: function() {
      return get(KEY_PV_SRC) == Source.ORIGIN;
    },
    isFromProxy: function() {
      return get(KEY_PV_SRC) == Source.PROXY;
    },
    isExpired: function() {
      if (PvCache.isFromOrigin() ) {
        let date = new Date(get(KEY_CREATION));
        date.setDate(date.getDate() + 1); /* update origin records every day */
        return Date.now() >= date.getTime();

      } else if (PvCache.isFromProxy() ) {
        let date = new Date(get(KEY_CREATION) );
        date.setHours(date.getHours() + 1); /* update proxy records per hour */
        return Date.now() >= date.getTime();
      }
      return false;
    },
    getAllPagevies: function() {
      return PvCache.getData().totalsForAllResults["ga:pageviews"];
    },
    newerThan: function(pv) {
      return PvCache.getAllPagevies() > pv.totalsForAllResults["ga:pageviews"];
    },
    inspectKeys: function() {
      if (localStorage.getItem(KEY_PV) == null
        || localStorage.getItem(KEY_PV_SRC) == null
        || localStorage.getItem(KEY_CREATION) == null) {
        localStorage.clear();
      }
    }
  };

})(); /* PvCache */

function fetchPageviews(fetchOrigin = true, filterOrigin = false) {
  /* pvCacheEnabled › see: /assets/js/_pv-config.js */
  if (pvCacheEnabled && fetchOrigin) {
    fetch('/assets/js/data/pageviews.json')
      .then(response => response.json())
      .then(data => {
        if (filterOrigin) {
          if (PvCache.newerThan(data)) {
            return;
          }
        }
        displayPageviews(data);
        PvCache.saveOriginCache(JSON.stringify(data));
      })
      .then(() => fetchProxyPageviews());

  } else {
    fetchProxyPageviews();
  }

}

function fetchProxyPageviews() {
  $.ajax({
    type: 'GET',
    url: proxyEndpoint, /* see: /assets/js/_pv-config.js */
    dataType: 'jsonp',
    jsonpCallback: "displayPageviews",
    success: function(data, textStatus, jqXHR) {
      PvCache.saveProxyCache(JSON.stringify(data));
    },
    error: function(jqXHR, textStatus, errorThrown) {
      console.log("Failed to load pageviews from proxy server: " + errorThrown);
    }
  });
}

$(function() {

  if ($('.pageviews').length > 0) {

    PvCache.inspectKeys();
    let cache = PvCache.getData();

    if (cache) {
      displayPageviews(cache);

      if (PvCache.isExpired()) {
        fetchPageviews(true, PvCache.isFromProxy());

      } else {

        if (PvCache.isFromOrigin()) {
          fetchPageviews(false);
        }

      }

    } else {
      fetchPageviews();
    }

  }

});
<|endoftext|>


<commit_before>function clearModal() {
  var modalList = document.querySelectorAll('.modal');
  for (i = 0; i < modalList.length; i++) {
      modalList[i].style.animation = 'quote-finish-transition 0.8s ease';
      modalList[i].style.visibility = 'hidden';
  }
}

function openModal() {
  var hash = window.location.hash;
  switch (hash) {
    case '#contact': openModalContactWindow(); break;
    case '#about': openModalAboutWindow(); break;
    case '#software': openModalSoftwareWindow(); break;
    case '#design': openModalDesignWindow(); break;
  }
}

openModal();

window.addEventListener("hashchange", function() {
  clearModal();
  openModal();
}, false);

<commit_msg>Add support to close modal windows using escape key<commit_after>function clearModal() {
  var modalList = document.querySelectorAll('.modal');
  for (i = 0; i < modalList.length; i++) {
      modalList[i].style.animation = 'quote-finish-transition 0.8s ease';
      modalList[i].style.visibility = 'hidden';
  }
}

function openModal() {
  var hash = window.location.hash;
  switch (hash) {
    case '#contact': openModalContactWindow(); break;
    case '#about': openModalAboutWindow(); break;
    case '#software': openModalSoftwareWindow(); break;
    case '#design': openModalDesignWindow(); break;
  }
}

openModal();

window.addEventListener("hashchange", function() {
  clearModal();
  openModal();
}, false);

window.addEventListener("keydown", function(keyPressed) {
  if (keyPressed.keyCode == 27) {
      window.location.hash = "#";
      clearModal();
  }
}, false);

<|endoftext|>


<commit_before>$(function () {

	$(document).on('click', "#schoolmanagement-details-form-enable", function (event) {
		$(this).replaceWith('
<button id="schoolmanagement-details-form-disable" class="btn btn-primary">Cancel</button><button id="schoolmanagement-details-form-submit" class="btn btn-primary" type="submit">Submit</button>
');
		$("#schoolmanagement-details-form input, #schoolmanagement-details-form select").prop("disabled",false);
	})

	$(document).on('click', "#schoolmanagement-details-form-disable", function (event) {
		$(this).parent().replaceWith('<button id="schoolmanagement-details-form-enable" class="btn btn-primary">Edit School Configurations</button>');
		$("#schoolmanagement-details-form input, #schoolmanagement-details-form select").prop("disabled",true);
	})

	$(document).on('click', '#schoolmanagement-details-form-submit', function (event) {
		if (confirm('Are you sure you want to apply these changes?')) {
			$.post(document.location, $('#schoolmanagement-details-form input, #schoolmanagement-details-form select').serialize(), function (response) {
				console.log(response);
				// reload the page to reset the form to read only with the latest db data and show any flash data.
				location.reload();
			});
		}
	})

	$('#schoolmanagement-addschooldetails-key').change(function (event) {
		var value = $(this).val();
		$('.schoolmanagement-addschooldetails-value-container').hide();
		$('.schoolmanagement-addschooldetails-value', $('.schoolmanagement-addschooldetails-value-container')).prop('disabled',true);
		$('#schoolmanagement-addschooldetails-submit').hide();
		if (value !== undefined && value !== '') {
			$('.schoolmanagement-addschooldetails-value-container#'+value).css('display', 'inline-block');
			var target = $('.schoolmanagement-addschooldetails-value', $('.schoolmanagement-addschooldetails-value-container#'+value));
			target.val('');
			target.prop('disabled',false);
			if (target.is('input:text'))
				$('#schoolmanagement-addschooldetails-submit').css('display', 'inline-block');
		}
	})

	$('.schoolmanagement-addschooldetails-value').change(function (event) {
		var value = $(this).val();
		if (value !== undefined && value != '')
			$('#schoolmanagement-addschooldetails-submit').css('display', 'inline-block');
		else
			$('#schoolmanagement-addschooldetails-submit').hide();
	})
})
<commit_msg>#90 Fixed a bug where the school details datatables search field was disabled when the write mode form was cancelled and set back to read only.<commit_after>$(function () {

	$(document).on('click', "#schoolmanagement-details-form-enable", function (event) {
		$(this).replaceWith('
<button id="schoolmanagement-details-form-disable" class="btn btn-primary">Cancel</button><button id="schoolmanagement-details-form-submit" class="btn btn-primary" type="submit">Submit</button>
');
		$("#schoolmanagement-details-form input, #schoolmanagement-details-form select").prop("disabled",false);
	})

	$(document).on('click', "#schoolmanagement-details-form-disable", function (event) {
		$(this).parent().replaceWith('<button id="schoolmanagement-details-form-enable" class="btn btn-primary">Edit School Configurations</button>');
		$("#schoolmanagement-details-form input:not([type *= 'search']), #schoolmanagement-details-form select").prop("disabled",true);
	})

	$(document).on('click', '#schoolmanagement-details-form-submit', function (event) {
		if (confirm('Are you sure you want to apply these changes?')) {
			$.post(document.location, $('#schoolmanagement-details-form input, #schoolmanagement-details-form select').serialize(), function (response) {
				console.log(response);
				// reload the page to reset the form to read only with the latest db data and show any flash data.
				location.reload();
			});
		}
	})

	$('#schoolmanagement-addschooldetails-key').change(function (event) {
		var value = $(this).val();
		$('.schoolmanagement-addschooldetails-value-container').hide();
		$('.schoolmanagement-addschooldetails-value', $('.schoolmanagement-addschooldetails-value-container')).prop('disabled',true);
		$('#schoolmanagement-addschooldetails-submit').hide();
		if (value !== undefined && value !== '') {
			$('.schoolmanagement-addschooldetails-value-container#'+value).css('display', 'inline-block');
			var target = $('.schoolmanagement-addschooldetails-value', $('.schoolmanagement-addschooldetails-value-container#'+value));
			target.val('');
			target.prop('disabled',false);
			if (target.is('input:text'))
				$('#schoolmanagement-addschooldetails-submit').css('display', 'inline-block');
		}
	})

	$('.schoolmanagement-addschooldetails-value').change(function (event) {
		var value = $(this).val();
		if (value !== undefined && value != '')
			$('#schoolmanagement-addschooldetails-submit').css('display', 'inline-block');
		else
			$('#schoolmanagement-addschooldetails-submit').hide();
	})
})
<|endoftext|>


<commit_before>$(function() {
  $(document).on('page:fetch',   function() { NProgress.start();  });
  $(document).on('page:change',  function() { NProgress.done();   });
  $(document).on('page:restore', function() { NProgress.remove(); });
});
<commit_msg>Bump NProgress to 70% when request has returned<commit_after>$(function() {
  $(document).on('page:fetch',   function() { NProgress.start();  });
  $(document).on('page:receive', function() { NProgress.set(0.7); })
  $(document).on('page:change',  function() { NProgress.done();   });
  $(document).on('page:restore', function() { NProgress.remove(); });
});
<|endoftext|>


<commit_before>// Preferences to allow unattended install of R-Kiosk extension
// Needed for Odoo IoT Box Client display
pref("app.update.checkInstallTime", false);
pref("devtools.webide.widget.autoinstall", false);
pref("xpinstall.customConfirmationUI", false);
pref("xpinstall.signatures.required", false);
pref("browser.shell.checkDefaultBrowser", false);
// Open all links in the same tab
// Needed to change URL without having multiple tabs running
pref("browser.link.open_newwindow", 1);
pref("browser.shell.checkDefaultBrowser",false);
<commit_msg>[FIX] point_of_sale: Customer display unresponsive script<commit_after>// Preferences to allow unattended install of R-Kiosk extension
// Needed for Odoo IoT Box Client display
pref("app.update.checkInstallTime", false);
pref("devtools.webide.widget.autoinstall", false);
pref("xpinstall.customConfirmationUI", false);
pref("xpinstall.signatures.required", false);
pref("browser.shell.checkDefaultBrowser", false);
// Open all links in the same tab
// Needed to change URL without having multiple tabs running
pref("browser.link.open_newwindow", 1);
pref("browser.shell.checkDefaultBrowser",false);
pref("dom.max_chrome_script_run_time", 0);
<|endoftext|>


<commit_before>Template = {"entries":{"index":"

\n","entry":"

\n
\n
\n
{{method}}
\n
{{format}}
\n    {{controller}}#{{action}}\n
{{path}}
\n
{{start_time}}
\n
{{duration}}ms
\n
\n

\n

\n
\n

\n"},"backtrace_lines":{"index":"
\n
\n    \n      Toggle Rails\n    	\n
\n

\n
\n","backtrace_line":"{{num}}	\n{{msg}}	\n{{line_num}}	\n\n  {{in}}\n	\n"},"lines":{"index":"
\n

\n

\n
\n","action_controller":{"write_fragment":"","read_fragment":"","expire_fragment":"","exist_fragment":"","write_page":"","expire_page":"","start_processing":"","process_action":"","send_file":"","send_data":"","redirect_to":"","halted_callback":""},"action_view":{"render_template":"render template	\n{{identifier}}	\n\n  layout:\n  {{layout}}\n	\n{{duration}}ms	\n","render_partial":"render partial	\n{{identifier}}	\n{{duration}}ms	\n"},"active_record":{"sql":"{{name}}	\n{{sql}}	\n{{duration}}ms	\n","identity":"{{name}}	\n{{line}}	\n{{duration}}ms	\n"},"action_mailer":{"receive":"","deliver":""},"active_resource":{"request":""},"active_support":{"cache_read":"","cache_generate":"","cache_fetch_hit":"","cache_write":"","cache_delete":"","cache_exist":""}}}<commit_msg>Update templates<commit_after>Template = {"entries":{"index":"

\n","entry":"

\n
\n
\n
{{method}}
\n
{{format}}
\n    {{controller}}#{{action}}\n
{{path}}
\n
{{start_time}}
\n
{{duration}}ms
\n
\n

\n

\n
\n

\n"},"backtrace_lines":{"index":"
\n
\n    \n      T\n    	\n    \n      {{name}}: {{message}}\n    	\n
\n

\n
\n","backtrace_line":"{{num}}	\n{{msg}}	\n{{line_num}}	\n\n  {{in}}\n	\n"},"lines":{"index":"
\n

\n

\n
\n","action_controller":{"write_fragment":"","read_fragment":"","expire_fragment":"","exist_fragment":"","write_page":"","expire_page":"","start_processing":"","process_action":"","send_file":"","send_data":"","redirect_to":"","halted_callback":""},"action_view":{"render_template":"render template	\n{{identifier}}	\n\n  layout:\n  {{layout}}\n	\n{{duration}}ms	\n","render_partial":"render partial	\n{{identifier}}	\n{{duration}}ms	\n"},"active_record":{"sql":"{{name}}	\n{{sql}}	\n{{duration}}ms	\n","identity":"{{name}}	\n{{line}}	\n{{duration}}ms	\n"},"action_mailer":{"receive":"","deliver":""},"active_resource":{"request":""},"active_support":{"cache_read":"","cache_generate":"","cache_fetch_hit":"","cache_write":"","cache_delete":"","cache_exist":""}}}<|endoftext|>