<commit_before>var draw_controls = function (map) {
    // holds the geoJSON text representation
    var geoJSON_element = document.getElementById('id_bounding_geometry');
    geoJSON_element.parentNode.parentNode.className = "hidden";

    var editableLayers = new L.FeatureGroup();
    map.addLayer(editableLayers);

    var SelectCurrentExtentControl = L.Control.extend({
        options: {
            position: 'topright'
            //control position - allowed: 'topleft', 'topright', 'bottomleft', 'bottomright'
        },
        initialize: function (text, options) {
            L.Util.setOptions(this, options);
            this.container = L.DomUtil.create('div', 'leaflet-bar leaflet-control leaflet-control-current-extent');
            this.container.innerHTML = text;
        },
        onAdd: function (map) {
            this.container.style.backgroundColor = 'white';
            this.container.onclick = function(){
                var rectangle = L.rectangle(map.getBounds());
                map.zoomOut();
                map.fire('draw:created', { layer: rectangle, layerType: 'rectangle' });
            };
            return this.container;
        }
    });

    var draw_enabled = {
        polyline: false,
        circle: false, // Turns off this drawing tool
        marker: false,
        polygon: {
            shapeOptions: {
                color: 'black',
                fillOpacity: 0.15
            }
        },
        rectangle: {
            shapeOptions: {
                color: 'black',
                fillOpacity: 0.15
            }
        }
    };
    var options = {
        position: 'topright',
        draw: draw_enabled,
        edit: {
            featureGroup: editableLayers,
            remove: true
        }
    };
    var optionsDisabled = {
        position: 'topright',
        draw: false,
        edit: {
            featureGroup: editableLayers,
            remove: true
        }
    };

    var drawControlEnabled = new L.Control.Draw(options);
    var drawControlDisabled = new L.Control.Draw(optionsDisabled);
    var ourCustomControl = new SelectCurrentExtentControl('Select current extent');
    drawControlEnabled.addTo(map);
    ourCustomControl.addTo(map);
    function updateGeoJSON (layer){
        geoJSON_element.value = JSON.stringify(layer.toGeoJSON()['geometry']);
    }

    function showSizeOfLayer(layer) {
        var allowedMaxSize = 1024 * 1024 * 1024;  // 1 GB in bytes, approx. 1/5 of Germany, estimation of the PBF size
        var allowedMaxSizeSimplified = 3 * allowedMaxSize;  // 3 GB in bytes, approx. 1/2 of Germany, estimation of the PBF size
        var simplifiedSelectValue = "60";
        var nameField = document.getElementById('id_name');
        var detailLevelID = '#id_detail_level';

        jQuery( detailLevelID ).change(function() {
            showSizeOfLayer(layer);
        });

        var e = document.getElementById('error_size_estimation_too_large');
        if (!e) {
            e = document.createElement('span');
            e.className = 'help-block';
            e.id = 'error_size_estimation_too_large';
            nameField.parentNode.appendChild(e);
        }

        function getAllowedMaxSize(){
            var selectedDetailLevel = jQuery('#id_detail_level');
            var selectedValue = selectedDetailLevel.find(":selected").attr('value');
            if (parseInt(selectedValue) === 60) {
                return allowedMaxSizeSimplified;
            }
            return allowedMaxSize;
        }

        function isSimplifiedChosen() {
            var selectedDetailLevel = jQuery(detailLevelID).find(":selected").attr('value');
            return selectedDetailLevel === simplifiedSelectValue;
        }

        function animateUserToSwitchToLowerDetails() {
            if (!isSimplifiedChosen()) {
                jQuery(detailLevelID).animate({
                  backgroundColor: "#F8D568",
                  color: "#B7410E"
                }, 500 );
                jQuery(detailLevelID).animate({
                  backgroundColor: "#fff",
                  color: "#000"
                }, 500 );
            }
        }

        function isExtentTooLarge(estimatedFileSize) {
            var sizeExceeded = estimatedFileSize > getAllowedMaxSize();
            if (sizeExceeded) {
                animateUserToSwitchToLowerDetails();
            }
            return estimatedFileSize > getAllowedMaxSize();
        }

        estimateSize(layer).done(function (data) {
            function formatBytes(bytes) {
                if (bytes == 0) {
                    return '0 Byte';
                }
                var k = 1000;
                var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
                var i = Math.min(Math.floor(Math.log(bytes) / Math.log(k)), sizes.length - 1);
                return parseFloat((bytes / Math.pow(k, i)).toFixed()) + ' ' + sizes[i];
            }

            var estimatedFileSize = Number(data['estimated_file_size_in_bytes']);

            var message_html = '';
            if (isExtentTooLarge(estimatedFileSize)) {
                var howMuchTooLarge = estimatedFileSize ? Math.ceil(estimatedFileSize * 100 / getAllowedMaxSize() - 100) + '% ' : '';
                var message = 'Excerpt {percent}too large!'.replace('{percent}', howMuchTooLarge);

                if (!isSimplifiedChosen()) {
                    message += ' Switching to the simplified data-model allows larger extends.';
                }
                message_html = '' + message + '
';
                nameField.setCustomValidity(message);
            } else {
                nameField.setCustomValidity('');
            }

            if (isNaN(estimatedFileSize)) {
                e.innerHTML = 'Invalid Area selected.';
            } else {
                e.innerHTML = message_html;
            }

        });
    }

    map.on('draw:created', function (e) {
        drawControlDisabled.addTo(map);
        drawControlEnabled.removeFrom(map);
        ourCustomControl.removeFrom(map);
        var layer = e.layer;
        if (layer !== undefined) {
            showSizeOfLayer(layer);
            editableLayers.addLayer(layer);
            map.fitBounds(layer.getBounds());
            updateGeoJSON(layer);
        }
    }.bind(this));

    map.on('draw:edited', function (e) {
        var layers = e.layers;
        layers.eachLayer(function (layer) {
            if (layer !== undefined) {
                showSizeOfLayer(layer);
                map.fitBounds(layer.getBounds());
                updateGeoJSON(layer);
            }
        });
    });

    map.on('draw:deleted', function () {
        geoJSON_element.value = '';
        if (editableLayers.getLayers().length === 0) {
            drawControlEnabled.addTo(map);
            drawControlDisabled.removeFrom(map);
            ourCustomControl.addTo(map);
        }
    });
};

<commit_msg>remove on change events after they are done<commit_after>var draw_controls = function (map) {
    // holds the geoJSON text representation
    var geoJSON_element = document.getElementById('id_bounding_geometry');
    geoJSON_element.parentNode.parentNode.className = "hidden";

    var detailLevelID = '#id_detail_level';

    var editableLayers = new L.FeatureGroup();
    map.addLayer(editableLayers);

    var SelectCurrentExtentControl = L.Control.extend({
        options: {
            position: 'topright'
            //control position - allowed: 'topleft', 'topright', 'bottomleft', 'bottomright'
        },
        initialize: function (text, options) {
            L.Util.setOptions(this, options);
            this.container = L.DomUtil.create('div', 'leaflet-bar leaflet-control leaflet-control-current-extent');
            this.container.innerHTML = text;
        },
        onAdd: function (map) {
            this.container.style.backgroundColor = 'white';
            this.container.onclick = function(){
                var rectangle = L.rectangle(map.getBounds());
                map.zoomOut();
                map.fire('draw:created', { layer: rectangle, layerType: 'rectangle' });
            };
            return this.container;
        }
    });

    var draw_enabled = {
        polyline: false,
        circle: false, // Turns off this drawing tool
        marker: false,
        polygon: {
            shapeOptions: {
                color: 'black',
                fillOpacity: 0.15
            }
        },
        rectangle: {
            shapeOptions: {
                color: 'black',
                fillOpacity: 0.15
            }
        }
    };
    var options = {
        position: 'topright',
        draw: draw_enabled,
        edit: {
            featureGroup: editableLayers,
            remove: true
        }
    };
    var optionsDisabled = {
        position: 'topright',
        draw: false,
        edit: {
            featureGroup: editableLayers,
            remove: true
        }
    };

    var drawControlEnabled = new L.Control.Draw(options);
    var drawControlDisabled = new L.Control.Draw(optionsDisabled);
    var ourCustomControl = new SelectCurrentExtentControl('Select current extent');
    drawControlEnabled.addTo(map);
    ourCustomControl.addTo(map);
    function updateGeoJSON (layer){
        geoJSON_element.value = JSON.stringify(layer.toGeoJSON()['geometry']);
    }

    function showSizeOfLayer(layer) {
        var allowedMaxSize = 1024 * 1024 * 1024;  // 1 GB in bytes, approx. 1/5 of Germany, estimation of the PBF size
        var allowedMaxSizeSimplified = 3 * allowedMaxSize;  // 3 GB in bytes, approx. 1/2 of Germany, estimation of the PBF size
        var simplifiedSelectValue = "60";
        var nameField = document.getElementById('id_name');

        var e = document.getElementById('error_size_estimation_too_large');
        if (!e) {
            e = document.createElement('span');
            e.className = 'help-block';
            e.id = 'error_size_estimation_too_large';
            nameField.parentNode.appendChild(e);
        }

        function getAllowedMaxSize(){
            var selectedDetailLevel = jQuery('#id_detail_level');
            var selectedValue = selectedDetailLevel.find(":selected").attr('value');
            if (parseInt(selectedValue) === 60) {
                return allowedMaxSizeSimplified;
            }
            return allowedMaxSize;
        }

        function isSimplifiedChosen() {
            var selectedDetailLevel = jQuery(detailLevelID).find(":selected").attr('value');
            return selectedDetailLevel === simplifiedSelectValue;
        }

        function animateUserToSwitchToLowerDetails() {
            if (!isSimplifiedChosen()) {
                jQuery(detailLevelID).animate({
                  backgroundColor: "#F8D568",
                  color: "#B7410E"
                }, 500 );
                jQuery(detailLevelID).animate({
                  backgroundColor: "#fff",
                  color: "#000"
                }, 500 );
            }
        }

        function isExtentTooLarge(estimatedFileSize) {
            var sizeExceeded = estimatedFileSize > getAllowedMaxSize();
            if (sizeExceeded) {
                animateUserToSwitchToLowerDetails();
            }
            return estimatedFileSize > getAllowedMaxSize();
        }

        estimateSize(layer).done(function (data) {
            function formatBytes(bytes) {
                if (bytes == 0) {
                    return '0 Byte';
                }
                var k = 1000;
                var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
                var i = Math.min(Math.floor(Math.log(bytes) / Math.log(k)), sizes.length - 1);
                return parseFloat((bytes / Math.pow(k, i)).toFixed()) + ' ' + sizes[i];
            }

            var estimatedFileSize = Number(data['estimated_file_size_in_bytes']);

            var message_html = '';
            if (isExtentTooLarge(estimatedFileSize)) {
                var howMuchTooLarge = estimatedFileSize ? Math.ceil(estimatedFileSize * 100 / getAllowedMaxSize() - 100) + '% ' : '';
                var message = 'Excerpt {percent}too large!'.replace('{percent}', howMuchTooLarge);

                if (!isSimplifiedChosen()) {
                    message += ' Switching to the simplified data-model allows larger extends.';
                }
                message_html = '' + message + '
';
                nameField.setCustomValidity(message);
            } else {
                nameField.setCustomValidity('');
            }

            if (isNaN(estimatedFileSize)) {
                e.innerHTML = 'Invalid Area selected.';
            } else {
                e.innerHTML = message_html;
            }

        });
    }

    map.on('draw:created', function (e) {
        drawControlDisabled.addTo(map);
        drawControlEnabled.removeFrom(map);
        ourCustomControl.removeFrom(map);
        var layer = e.layer;
        if (layer !== undefined) {
            jQuery( detailLevelID ).change(function() {
                    showSizeOfLayer(layer);
            });
            showSizeOfLayer(layer);
            editableLayers.addLayer(layer);
            map.fitBounds(layer.getBounds());
            updateGeoJSON(layer);
        }
    }.bind(this));

    map.on('draw:edited', function (e) {
        var layers = e.layers;
        layers.eachLayer(function (layer) {
            if (layer !== undefined) {
                showSizeOfLayer(layer);
                map.fitBounds(layer.getBounds());
                updateGeoJSON(layer);
            }
        });
    });

    map.on('draw:deleted', function () {
        jQuery( detailLevelID ).off( "change" );
        geoJSON_element.value = '';
        if (editableLayers.getLayers().length === 0) {
            drawControlEnabled.addTo(map);
            drawControlDisabled.removeFrom(map);
            ourCustomControl.addTo(map);
        }
    });
};

<|endoftext|>


<commit_before>'use strict';
const assert = require('assert');
const fs = require('fs-extra');
const path = require('path');

const repository = require('../lib/util/repository');
const Env = require('..');

describe('repository', () => {
  before(() => {
    if (fs.existsSync(repository.repositoryPath)) {
      fs.removeSync(repository.repositoryPath);
    }
  });

  afterEach(function () {
    this.timeout(20000);
    if (fs.existsSync(repository.repositoryPath)) {
      fs.removeSync(repository.repositoryPath);
    }
    repository.cleanupPackageCache('yeoman-environment', true);
  });

  it('is exposed on the Environment object', () => {
    assert.equal(Env.repository, repository);
  });

  describe('Environment#installLocalGenerators', () => {
    before(function () {
      this.timeout(100000);
      this.env = Env.createEnv();
      this.env.installLocalGenerators({'generator-dummytest': '0.1.3'});
    });

    after(() => {
      repository.cleanupPackageCache('generator-dummytest', true);
    });

    it('installs and register the generator', function () {
      this.timeout(10000);
      assert(this.env.get('dummytest:app'));
    });
  });

  describe('#repositoryPath', () => {
    it('returns the repository path', () => {
      assert.equal(repository.repositoryPath, path.resolve('.yo-repository'));
    });
  });

  describe('#resolvePackagePath', () => {
    describe('without args', () => {
      it('returns the node_modules path', () => {
        assert.equal(repository.nodeModulesPath, repository.resolvePackagePath());
      });
    });

    describe('with args', () => {
      it('returns the module path', () => {
        assert.equal(path.join(repository.nodeModulesPath, 'package', 'module'), repository.resolvePackagePath('package', 'module'));
      });
    });
  });

  describe('#createEnvWithVersion()', () => {
    describe('with semver valid range', () => {
      it('returns env', function () {
        this.timeout(500000);
        const env = Env.createEnvWithVersion('~2.3.0');
        assert.ok(env);
        assert.ok(!(env instanceof Env));
      });
    });

    describe('with git repository', () => {
      it('returns env', function () {
        this.timeout(500000);
        const env = Env.createEnvWithVersion('yeoman/environment#v2.8.1');
        assert.equal(repository.getPackageVersion('yeoman-environment'), '2.8.1');
        assert.ok(env);
        assert.ok(!(env instanceof Env));
      });
    });
  });

  describe('repository workflow', () => {
    it('run the workflow correctly', function () {
      this.timeout(500000);
      repository.installPackage('yeoman-environment', '2.3.0');
      assert.equal(repository.getPackageVersion('yeoman-environment'), '2.3.0');

      // Force install another version
      repository.installPackage('yeoman-environment', '2.8.1');
      assert.equal(repository.getPackageVersion('yeoman-environment'), '2.8.1');

      // Instantiate the installed version
      assert.ok(repository.requireModule('yeoman-environment'));
      assert.equal(repository.getPackageVersion('yeoman-environment'), '2.8.1');
    });
  });
});
<commit_msg>Improve repository tests<commit_after>'use strict';
const assert = require('assert');
const fs = require('fs-extra');
const path = require('path');

const repository = require('../lib/util/repository');
const Env = require('..');

describe('repository', () => {
  before(function () {
    this.timeout(20000);
    if (fs.existsSync(repository.repositoryPath)) {
      fs.removeSync(repository.repositoryPath);
    }
  });

  afterEach(function () {
    this.timeout(20000);
    if (fs.existsSync(repository.repositoryPath)) {
      fs.removeSync(repository.repositoryPath);
    }
    repository.cleanupPackageCache('yeoman-environment', true);
  });

  it('is exposed on the Environment object', () => {
    assert.equal(Env.repository, repository);
  });

  describe('Environment#installLocalGenerators', () => {
    before(function () {
      this.timeout(200000);
      this.env = Env.createEnv();
      this.env.installLocalGenerators({'generator-dummytest': '0.1.3'});
    });

    after(() => {
      repository.cleanupPackageCache('generator-dummytest', true);
    });

    it('installs and register the generator', function () {
      this.timeout(10000);
      assert(this.env.get('dummytest:app'));
    });
  });

  describe('#repositoryPath', () => {
    it('returns the repository path', () => {
      assert.equal(repository.repositoryPath, path.resolve('.yo-repository'));
    });
  });

  describe('#resolvePackagePath', () => {
    describe('without args', () => {
      it('returns the node_modules path', () => {
        assert.equal(repository.nodeModulesPath, repository.resolvePackagePath());
      });
    });

    describe('with args', () => {
      it('returns the module path', () => {
        assert.equal(path.join(repository.nodeModulesPath, 'package', 'module'), repository.resolvePackagePath('package', 'module'));
      });
    });
  });

  describe('#createEnvWithVersion()', () => {
    describe('with semver valid range', () => {
      let env;
      beforeEach(function () {
        this.timeout(500000);
        env = Env.createEnvWithVersion('~2.3.0');
      });

      it('returns env and #cleanup without force fails', () => {
        assert.ok(env);
        assert.ok(!(env instanceof Env));
        assert.throws(() => repository.cleanupPackageCache('yeoman-environment'));
      });
    });

    describe('with git repository', () => {
      it('returns env', function () {
        this.timeout(500000);
        const env = Env.createEnvWithVersion('yeoman/environment#v2.8.1');
        assert.equal(repository.getPackageVersion('yeoman-environment'), '2.8.1');
        assert.ok(env);
        assert.ok(!(env instanceof Env));
      });
    });
  });

  describe('repository workflow', () => {
    it('run the workflow correctly', function () {
      this.timeout(500000);
      repository.installPackage('yeoman-environment', '2.3.0');
      assert.equal(repository.getPackageVersion('yeoman-environment'), '2.3.0');

      // Force install another version
      repository.installPackage('yeoman-environment', '2.8.1');
      assert.equal(repository.getPackageVersion('yeoman-environment'), '2.8.1');

      // Instantiate the installed version
      assert.ok(repository.requireModule('yeoman-environment'));
      assert.equal(repository.getPackageVersion('yeoman-environment'), '2.8.1');
    });
  });
});
<|endoftext|>


<commit_before>'use strict';

var emBase64 = angular.module('em.base64', []);

emBase64.factory('base64', function() {
  var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  return {
    encode : function(input) {
      var output = "";
      var chr1, chr2, chr3 = "";
      var enc1, enc2, enc3, enc4 = "";
      var i = 0;

      while (i < input.length) {
        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        chr3 = input.charCodeAt(i++);

        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;

        if (isNaN(chr2)) {
          enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
          enc4 = 64;
        }

        output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4);
        chr1 = chr2 = chr3 = "";
        enc1 = enc2 = enc3 = enc4 = "";
      }
      return output;
    },

    decode : function(input) {
      var output = "";
      var chr1, chr2, chr3 = "";
      var enc1, enc2, enc3, enc4 = "";
      var i = 0;

      // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
      var base64test = /[^A-Za-z0-9\+\/\=]/g;
      if (base64test.exec(input)) {
        alert("There were invalid base64 characters in the input text.\n" + "Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\n" + "Expect errors in decoding.");
      }
      input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

      while (i < input.length) {
        enc1 = keyStr.indexOf(input.charAt(i++));
        enc2 = keyStr.indexOf(input.charAt(i++));
        enc3 = keyStr.indexOf(input.charAt(i++));
        enc4 = keyStr.indexOf(input.charAt(i++));

        chr1 = (enc1 << 2) | (enc2 >> 4);
        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
        chr3 = ((enc3 & 3) << 6) | enc4;

        output = output + String.fromCharCode(chr1);

        if (enc3 != 64) {
          output = output + String.fromCharCode(chr2);
        }
        if (enc4 != 64) {
          output = output + String.fromCharCode(chr3);
        }

        chr1 = chr2 = chr3 = "";
        enc1 = enc2 = enc3 = enc4 = "";
      }
      return output;
    }
  };
});
<commit_msg>Removed global variable declaration from base64 module.<commit_after>/*global angular*/

( function() {'use strict';

    angular.module('em.base64', []);

    angular.module('em.base64').factory('base64', function() {
      var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
      return {
        encode : function(input) {
          var output = "";
          var chr1, chr2, chr3 = "";
          var enc1, enc2, enc3, enc4 = "";
          var i = 0;

          while (i < input.length) {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
              enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
              enc4 = 64;
            }

            output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4);
            chr1 = chr2 = chr3 = "";
            enc1 = enc2 = enc3 = enc4 = "";
          }
          return output;
        },

        decode : function(input) {
          var output = "";
          var chr1, chr2, chr3 = "";
          var enc1, enc2, enc3, enc4 = "";
          var i = 0;

          // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
          var base64test = /[^A-Za-z0-9\+\/\=]/g;
          if (base64test.exec(input)) {
            alert("There were invalid base64 characters in the input text.\n" + "Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\n" + "Expect errors in decoding.");
          }
          input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

          while (i < input.length) {
            enc1 = keyStr.indexOf(input.charAt(i++));
            enc2 = keyStr.indexOf(input.charAt(i++));
            enc3 = keyStr.indexOf(input.charAt(i++));
            enc4 = keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
              output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
              output = output + String.fromCharCode(chr3);
            }

            chr1 = chr2 = chr3 = "";
            enc1 = enc2 = enc3 = enc4 = "";
          }
          return output;
        }
      };
    });
  }());
<|endoftext|>


<commit_before>//var i = 0;
//var images = ["img/bridge.jpg", "img/buckingham.jpg", "img/tower.jpg"];

function changeImage() {
	var currentImage = ("#gallery figure.active");
	var nextImage;
		if(currentImage.next().length == 0) {
			nextImage = $("gallery figure:first");
		}
		else {
			nextImage = currentImage.next();
		}

	currentImage.addClass("last-active");
	nextImage.css({opacity: 0.0}).addClass("active").animate({opacity: 1.0}, 1000,
		function(){currentImage.removeClass("active last-active");
	});
}

//$(document).ready(function() {
	var arrowleft = document.getElementById("left");
	arrowleft.addEventListener("click", changeImage, false);
	var arrowright = document.getElementById("right");
	arrowright.addEventListener("click", changeImage, false);
//});

checkScroll();

$(window).scroll(checkScroll);
function checkScroll() {
	var top = $(window).scrollTop();
	if(top > 100) {
		$("nav").css("backgroundColor", "#f0f0f0", 500);
	}
}
<commit_msg>created nav fade in functionality when you scroll<commit_after>//var i = 0;
//var images = ["img/bridge.jpg", "img/buckingham.jpg", "img/tower.jpg"];

var headerColor = "rgba(240, 240, 240,";

function changeImage() {
	var currentImage = ("#gallery figure.active");
	var nextImage;
		if(currentImage.next().length == 0) {
			nextImage = $("gallery figure:first");
		}
		else {
			nextImage = currentImage.next();
		}

	currentImage.addClass("last-active");
	nextImage.css({opacity: 0.0}).addClass("active").animate({opacity: 1.0}, 1000,
		function(){currentImage.removeClass("active last-active");
	});
}

//$(document).ready(function() {
	var arrowleft = document.getElementById("left");
	arrowleft.addEventListener("click", changeImage, false);
	var arrowright = document.getElementById("right");
	arrowright.addEventListener("click", changeImage, false);
//});

checkScroll();

$(window).scroll(checkScroll);
function checkScroll() {
	var top = $(window).scrollTop();
	if(top > 0) {
		$("nav").css("backgroundColor", headerColor + "0)", 500);
	}
	if(top > 80) {
		$("nav").css("backgroundColor", headerColor + ".05", 500);
	}
	if(top > 100) {
		$("nav").css("backgroundColor", headerColor + ".1", 500);
	}
	if(top > 110) {
		$("nav").css("backgroundColor", headerColor + ".15", 500);
	}
	if(top > 120) {
		$("nav").css("backgroundColor", headerColor + ".3", 500);
	}
	if(top > 130) {
		$("nav").css("backgroundColor", headerColor + ".35", 500);
	}
	if(top > 140) {
		$("nav").css("backgroundColor", headerColor + ".4", 500);
	}
	if(top > 150) {
		$("nav").css("backgroundColor", headerColor + ".45", 500);
	}
	if(top > 160) {
		$("nav").css("backgroundColor", headerColor + ".5", 500);
	}
	if(top > 170) {
		$("nav").css("backgroundColor", headerColor + ".55", 500);
	}
	if(top > 180) {
		$("nav").css("backgroundColor", headerColor + ".6", 500);
	}
	if(top > 190) {
		$("nav").css("backgroundColor", headerColor + ".65", 500);
	}
	if(top > 200) {
		$("nav").css("backgroundColor", headerColor + ".7", 500);
	}
	if(top > 210) {
		$("nav").css("backgroundColor", headerColor + ".75", 500);
	}
	if(top > 220) {
		$("nav").css("backgroundColor", headerColor + ".8", 500);
	}
	if(top > 230) {
		$("nav").css("backgroundColor", headerColor + ".85", 500);
	}
	if(top > 240) {
		$("nav").css("backgroundColor", headerColor + ".9", 500);
	}
	if(top > 250) {
		$("nav").css("backgroundColor", headerColor + ".95", 500);
	}
	if(top > 260) {
		$("nav").css("backgroundColor", headerColor + "1", 500);
	}
}
<|endoftext|>


<commit_before>module.exports = function(env, callback) {
  env.locals.urlbyid = function(contents, id) {
    var pages = env.helpers.getAllPages(contents);
    var url;
    for (var x = 0; x < pages.length; x++) {
      if (pages[x].metadata.id == id) {
        url = pages[x].url;
        break;
      }
    }
    if (!url) {
      console.warn('URL not found for id: ' + id);
    }
    return url;
  }

  env.helpers.getAllPages = function(contents) {
    var output = env.locals.pages || [];
    if (!env.locals.pages) {
      for (var key in contents) {
        var currentObj = contents[key];
        if (isFile(currentObj)) {
          // console.log('pushing page');
          if(currentObj.metadata.hasOwnProperty("primarynavorder")) {
            currentObj.primarynavorder = currentObj.metadata.primarynavorder;
          }
          output.push(currentObj);
        }
        else if(isDirectory(currentObj)) {
          output = output.concat(env.helpers.getAllPages(currentObj));
        }
      }
      env.locals.pages = output;
    }
    return output;
	};

  env.helpers.getPrimaryNavigation = function(contents) {
    var pages = env.helpers.getAllPages(contents);
    var primary_nav = pages.filter(function(page) {
      return page.metadata.primarynavorder;
    });
    sortByKey(primary_nav, 'primarynavorder');
    return primary_nav;
	};

  callback();

  var isFile = function(currentItem) {
		return currentItem.hasOwnProperty('__filename');
	};
  var isDirectory = function(currentItem) {
    return !currentItem.hasOwnProperty('__filename');
  };

  function sortByKey(arr, key) {
    return arr.sort(function(a, b) {
      var x = a[key], y = b[key];
      // console.log(a['metadata.primarynavorder']);
      // console.log(b.metadata.primarynavorder);
      // console.log(x);
      // console.log(y);
      return (x < y) ? -1 : ((x > y) ? 1 : 0);
    });
  }
};
<commit_msg>added sorted navigation<commit_after>module.exports = function(env, callback) {
  env.locals.urlbyid = function(contents, id) {
    var pages = env.helpers.getAllPages(contents);
    var url;
    for (var x = 0; x < pages.length; x++) {
      if (pages[x].metadata.id == id) {
        url = pages[x].url;
        break;
      }
    }
    if (!url) {
      console.warn('URL not found for id: ' + id);
    }
    return url;
  }

  env.helpers.getAllPages = function(contents) {
    var output = env.locals.pages || [];
    if (!env.locals.pages) {
      for (var key in contents) {
        var currentObj = contents[key];
        if (isFile(currentObj)) {
          // console.log('pushing page');
          if(currentObj.metadata.hasOwnProperty("primarynavorder")) {
            currentObj.primarynavorder = currentObj.metadata.primarynavorder;
          }
          if(currentObj.metadata.hasOwnProperty("navorder")) {
            currentObj.navorder = currentObj.metadata.navorder;
          }
          currentObj.filepath.dir = currentObj.filepath.relative.substring(0, currentObj.filepath.relative.lastIndexOf("/"));
          output.push(currentObj);
        }
        else if (isDirectory(currentObj)) {
          output = output.concat(env.helpers.getAllPages(currentObj));
        }
      }
      env.locals.pages = output;
    }
    return output;
	};

  env.helpers.getPrimaryNavigation = function(contents) {
    var pages = env.helpers.getAllPages(contents);
    var primary_nav = pages.filter(function(page) {
      return page.metadata.primarynavorder;
    });
    sortByKey(primary_nav, 'primarynavorder');
    return primary_nav;
	};

  env.helpers.getNavigation = function(contents, folder) {
    var pages = env.helpers.getAllPages(contents);
    var nav = pages.filter(function(page) {
      return page.metadata.navorder && page.filepath.dir == folder;
    });
    sortByKey(nav, 'navorder');
    return nav;
  };

  env.helpers.rawjson = function(obj) {
    return JSON.stringify(obj);
  }

  callback();

  var isFile = function(currentItem) {
		return currentItem.hasOwnProperty('__filename');
	};
  var isDirectory = function(currentItem) {
    return !currentItem.hasOwnProperty('__filename');
  };

  function sortByKey(arr, key) {
    return arr.sort(function(a, b) {
      var x = a[key], y = b[key];
      return (x < y) ? -1 : ((x > y) ? 1 : 0);
    });
  }
};
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var Client = require('../models/client')
var Panel = require('../models/panel')
var Read = require('../models/read')

//Get clients
router.get('/', function(req, res){
  Client.find({}, function(err, clients){
    if(err){
      res.status(500)
      res.send(err)
    }
    else {
      if(clients.length > 0){
        res.status(200)
        res.send(clients)
      }
      else {
        res.status(404)
        res.send('Not clients found')
      }
    }
  })
})

//created clients
router.post('/', Client.findClient(false, false), function(req, res){
  if(req.body.name && req.body.userid){
    var newClient = new Client()
    newClient.name = req.body.name
    newClient.userid = req.body.userid
    newClient.save(function(err){
      if(err){
        res.status(500)
        res.send(err)
      }
      else {
        res.status(201)
        res.send(newClient)
      }
    })
  }
  else {
    res.send(400)
    res.json({
      error : 'Missing parameters'
    })
  }
})

//Get client by id
router.get('/:userid', Client.findClient(true, true), function(req, res){
  res.status(200)
  res.send(req.client)
})

//Eliminated client
router.delete('/:userid', Client.findClient(true, true), function(req, res){
  req.client.remove(function(err){
    if(err){
      res.status(500)
      res.send(err)
    }
    else {
      req.client.panels.forEach(function(panel){
        panel.remove(function(err){
          if(err){
            res.status(500)
            res.send(err)
          }
        })
      })
      res.status(200)
      res.json({
        message : "Client deleted",
        client : req.client
      })
    }
  })
})

//Get panels from userid
router.get('/:userid/panels', Client.findClient(true, false), function(req, res){
  req.client.populate({path : 'panels'}, function(err, client_pop){
    if(err){
      res.status(500)
      res.send(err)
    }
    else {
      if(client_pop.panels.length > 0){
        res.status(200)
        res.send(client_pop.panels)
      }
      else {
        res.status(404)
        res.send('Not panels found found')
      }
    }
  })
})

//Create new panels for a specific client (Missing message update)
router.post('/:userid/', Client.findClient(true, true), Panel.findPanel(false, false), function(req, res){
  if(req.body.panelid && req.body.location && req.params.userid){
    var newPanel = new Panel()
    newPanel.panelid = req.body.panelid
    newPanel.location = req.body.location
    newPanel.save(function(err){
      if(err){
        res.status(500)
        res.send(err)
      }
      else{
        // actualizar el cliente con el nuevo panelid
        req.client.update({$push :{'panels': newPanel}},function(error){
          if (error) {
            res.status(500)
            res.send(error)
          }
          else{
            res.status(201)
            res.json({
              status : "Sucess",
              payload : newPanel,
              message : "Panel created"
            })
          }
        })
      }
    })
  }
  else{
    res.status(400)
    res.json({
      error : 'Missing Parameters'
    })
  }
})

//Delete panels for a specific client
router.delete('/:userid/:panelid', Client.findClient(true, true), Panel.findPanel(true, true), function(req, res){
  if(req.params.userid && req.params.panelid){
    req.client.update({$pull : {'panels': req.panel._id}}, function(err){
      if(err){
        res.status(500)
        res.json({error: 'Error updating object'})
      }
      else{
        req.panel.remove(function(err){
          if(err){
            res.status(500)
            res.send(err)
          }
          else{
            req.panel.reads.forEach(function(read) {
              read.remove();
            })
            res.status(200)
            res.json({
              status : "Sucess",
              payload : req.panel,
              message : "Eliminated panel"
            })
          }
        })
      }
    })
  }
})

//Get Panel by id from user
router.get('/:userid/:panelid', Client.findClient(true, true), Panel.findPanel(true, false), function(req, res){
  res.status(200)
  res.send(req.panel)
})

//Post reads from a specific panel
router.post('/:userid/:panelid/', Client.findClient(true, true), Panel.findPanel(true, false), function(req, res){
  if(req.client && req.panel){
    var newRead = new Read()
    newRead.current = req.body.current
    newRead.temperature = req.body.temperature
    newRead.radiation = req.body.radiation
    newRead.save(function(err){
      if(err){
        res.status(500)
        res.send(err)
      }
      else{
        req.panel.update({$push :{'reads': newRead}},function(err){
          if(err){
            res.status(500)
            res.send(err)
          }
          else{
            res.status(201)
            res.json({
              status : "Sucess",
              // payload : newRead,
              message : "Reads created"
            })
          }
        })
      }
    })
  }
})

//Get reads for a specific panel
router.get('/:userid/:panelid/reads',Client.findClient(true, true), Panel.findPanel(true, true), function(req, res){
  res.status(200)
  res.send(req.panel)
})

router.delete('/:userid/:panelid/reads', Client.findClient(true, true), Panel.findPanel(true, true), function(req, res){
  req.panel.reads.forEach(function(read){
    read.remove()
  })
  req.panel.reads = []
  req.panel.save(function(err){
    if(err){
      res.status(500)
      res.send(err)
    }
    else {
      res.status(200)
      res.send(req.panel)
    }
  })
})

module.exports = router
<commit_msg>Time-reads commit<commit_after>var express = require('express');
var router = express.Router();
var Client = require('../models/client')
var Panel = require('../models/panel')
var Read = require('../models/read')

//Get clients
router.get('/', function(req, res){
  Client.find({}, function(err, clients){
    if(err){
      res.status(500)
      res.send(err)
    }
    else {
      if(clients.length > 0){
        res.status(200)
        res.send(clients)
      }
      else {
        res.status(404)
        res.send('Not clients found')
      }
    }
  })
})

//created clients
router.post('/', Client.findClient(false, false), function(req, res){
  if(req.body.name && req.body.userid){
    var newClient = new Client()
    newClient.name = req.body.name
    newClient.userid = req.body.userid
    newClient.save(function(err){
      if(err){
        res.status(500)
        res.send(err)
      }
      else {
        res.status(201)
        res.send(newClient)
      }
    })
  }
  else {
    res.send(400)
    res.json({
      error : 'Missing parameters'
    })
  }
})

//Get client by id
router.get('/:userid', Client.findClient(true, true), function(req, res){
  res.status(200)
  res.send(req.client)
})

//Eliminated client
router.delete('/:userid', Client.findClient(true, true), function(req, res){
  req.client.remove(function(err){
    if(err){
      res.status(500)
      res.send(err)
    }
    else {
      req.client.panels.forEach(function(panel){
        panel.remove(function(err){
          if(err){
            res.status(500)
            res.send(err)
          }
        })
      })
      res.status(200)
      res.json({
        message : "Client deleted",
        client : req.client
      })
    }
  })
})

//Get panels from userid
router.get('/:userid/panels', Client.findClient(true, false), function(req, res){
  req.client.populate({path : 'panels'}, function(err, client_pop){
    if(err){
      res.status(500)
      res.send(err)
    }
    else {
      if(client_pop.panels.length > 0){
        res.status(200)
        res.send(client_pop.panels)
      }
      else {
        res.status(404)
        res.send('Not panels found found')
      }
    }
  })
})

//Create new panels for a specific client (Missing message update)
router.post('/:userid/', Client.findClient(true, true), Panel.findPanel(false, false), function(req, res){
  if(req.body.panelid && req.body.location && req.params.userid){
    var newPanel = new Panel()
    newPanel.panelid = req.body.panelid
    newPanel.location = req.body.location
    newPanel.save(function(err){
      if(err){
        res.status(500)
        res.send(err)
      }
      else{
        // actualizar el cliente con el nuevo panelid
        req.client.update({$push :{'panels': newPanel}},function(error){
          if (error) {
            res.status(500)
            res.send(error)
          }
          else{
            res.status(201)
            res.json({
              status : "Sucess",
              payload : newPanel,
              message : "Panel created"
            })
          }
        })
      }
    })
  }
  else{
    res.status(400)
    res.json({
      error : 'Missing Parameters'
    })
  }
})

//Delete panels for a specific client
router.delete('/:userid/:panelid', Client.findClient(true, true), Panel.findPanel(true, true), function(req, res){
  if(req.params.userid && req.params.panelid){
    req.client.update({$pull : {'panels': req.panel._id}}, function(err){
      if(err){
        res.status(500)
        res.json({error: 'Error updating object'})
      }
      else{
        req.panel.remove(function(err){
          if(err){
            res.status(500)
            res.send(err)
          }
          else{
            req.panel.reads.forEach(function(read) {
              read.remove();
            })
            res.status(200)
            res.json({
              status : "Sucess",
              payload : req.panel,
              message : "Eliminated panel"
            })
          }
        })
      }
    })
  }
})

//Get Panel by id from user
router.get('/:userid/:panelid', Client.findClient(true, true), Panel.findPanel(true, false), function(req, res){
  res.status(200)
  res.send(req.panel)
})

//Post reads from a specific panel
router.post('/:userid/:panelid/', Client.findClient(true, true), Panel.findPanel(true, false), function(req, res){
  if(req.client && req.panel){
    var newRead = new Read()
    newRead.current = req.body.current
    newRead.temperature = req.body.temperature
    if(req.body.time){
     newRead.time = req.body.time
    }
    newRead.save(function(err){
      if(err){
        res.status(500)
        res.send(err)
      }
      else{
        req.panel.update({$push :{'reads': newRead}},function(err){
          if(err){
            res.status(500)
            res.send(err)
          }
          else{
            res.status(201)
            res.json({
              status : "Sucess",
              // payload : newRead,
              message : "Reads created"
            })
          }
        })
      }
    })
  }
})

//Get reads for a specific panel
router.get('/:userid/:panelid/reads',Client.findClient(true, true), Panel.findPanel(true, true), function(req, res){
  res.status(200)
  res.send(req.panel)
})

router.delete('/:userid/:panelid/reads', Client.findClient(true, true), Panel.findPanel(true, true), function(req, res){
  req.panel.reads.forEach(function(read){
    read.remove()
  })
  req.panel.reads = []
  req.panel.save(function(err){
    if(err){
      res.status(500)
      res.send(err)
    }
    else {
      res.status(200)
      res.send(req.panel)
    }
  })
})

module.exports = router
<|endoftext|>


<commit_before>$(document).ready(function(){
    var endpoint = 'http://logd.tw.rpi.edu:8890/sparql';
    endpoint = 'proxy.php';
    var hashParams = {};
    var facetsLoaded = 0;
    var fetchLimit = 25;
    var fetchOffset = 0;
    var firstQuery = true;
    var ajaxObj = undefined;
    function _updateFacetFromHash(id){
      if(hashParams['keyword-search'] !== undefined && hashParams['keyword-search'] != ""){
        $("#keyword-search").val(hashParams['keyword-search']);
      }
      if(hashParams[id] !== undefined){
        $.each(hashParams[id], function(i, item){
          $("#select-"+id+" option[value='"+item+"']").attr("selected", true);
        });
      }
    }

    function _msgError(msg){
      $("#error-details").html(msg);
      $("#error-msg").modal('show');
    }

    function _executeQuery(){
      var facetPatterns = "";
      var hashString = "#";
      fetchOffset = 0;

      //Stop ajax already existing request
      if(ajaxObj !== undefined){
        ajaxObj.abort();
      }

      if($("#keyword-search").val() !== undefined && $("#keyword-search").val() != "" && $("#keyword-search").val().length >= 3){
        facetPatterns += 'FILTER(regex(?datasetTitle, "'+$("#keyword-search").val()+'", "i")) '
        hashString +="keyword-search="+$("#keyword-search").val()+"&";
      }
      $.each(facets, function(i, item){
          var rightDelimiter = '>', leftDelimiter = '<';
          if(item.facetLabelPredicates === undefined){
            rightDelimiter = '"';
            leftDelimiter = '"';
          }
          selectedValues = $("#select-"+item.id+" option:selected");
          if(firstQuery == true && selectedValues.length == 0 && item.default !== undefined){
            selectedValues.push($("#select-"+item.id+" option[value='"+item.default+"']").attr("selected", true));
          }
          hashString += item.id+"=";
          if(selectedValues.length > 1){
            facetPatterns += '{';
          }
          selectedValues.each(function(index, value){
              facetPatterns += '?dataset ' + item.facetPredicates + ' '+leftDelimiter + $(value).val()+ rightDelimiter +' .               ';
              hashString += $(value).val()+"|";
              if(selectedValues.length > 1){
                if(index < selectedValues.length -1){
                  facetPatterns += '}UNION{';
                }else{
                  facetPatterns += '}';
                }
              }
          });
          hashString += "&";
          console.log(hashString);
      });
      firstQuery = false;
      var query = 'PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \
      PREFIX foaf: <http://xmlns.com/foaf/0.1/> \
      PREFIX dcterms: <http://purl.org/dc/terms/> \
      PREFIX dgtwc: <http://data-gov.tw.rpi.edu/2009/data-gov-twc.rdf#> \
      PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \
      PREFIX conversion: <http://purl.org/twc/vocab/conversion/> \
      SELECT DISTINCT ?dataset ?datasetTitle ?catalog_title ?homepage ?datasetDescription ?catalogHomepage WHERE { \
        GRAPH <http://purl.org/twc/vocab/conversion/MetaDataset> { \
        ?dataset dcterms:title ?datasetTitle ; \
                 dgtwc:catalog_title ?catalog_title; \
                 foaf:homepage ?homepage . \
        '+facetPatterns+' \
        OPTIONAL{ ?dataset dcterms:description ?datasetDescription} \
        OPTIONAL{ ?dataset dgtwc:catalog_homepage ?catalogHomepage} \
      } \
    }ORDER BY ?datasetTitle \
    LIMIT '+(fetchLimit+1) +' \
    OFFSET '+(fetchLimit*fetchOffset);
    $("#results").empty().html('

');
    ajaxObj = $.ajax({
        url: endpoint,
        beforeSend: function(jqXHR, settings) {
          jqXHR.setRequestHeader("Accept", "application/sparql-results+json");
          jqXHR.overrideMimeType('application/sparql-results+json; charset=UTF-8');
        },
        contentType: "application/sparql-results+json; charset=utf-8",
        data: {
          query: query
        },
        dataType: 'json',
        success: function(data){
          $("#results").empty();
          options = "";
          if(data.results.bindings.length > 0){$("#next").removeClass('disabled');}
          $.each(data.results.bindings, function(index, value){
              if(index == fetchLimit){$("#next").removeClass('disabled'); return false;}
              var catalog = value.catalog_title.value;
              if(value.catalogHomepage !== undefined){
                catalog = ''+value.catalog_title.value+'';
              }
              var description = ""
              if(value.datasetDescription !== undefined){
              description = value.datasetDescription.value;
              }
              $("#results").append('

'+value.datasetTitle.value+'

Taken from '+catalog+'

'+description+'
');
          });
          if(data.results.bindings.length < fetchLimit){$("#next").addClass('disabled');}
        }
    });
          window.location.hash = hashString;

}

    function _getFacetData(i, item){
      var predicateLabels = "";
      var labelVariable = "";
      var sparqlLimit = 10000;
      if(item.limit !== undefined){
        sparqlLimit = item.limit;
      }
      if(item.facetLabelPredicates !== undefined){
        predicateLabels = '?thing '+item.facetLabelPredicates+' ?thingLabel .';
        labelVariable = '?thingLabel';
      }
      var query = 'PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \
      PREFIX foaf: <http://xmlns.com/foaf/0.1/> \
      PREFIX dcterms: <http://purl.org/dc/terms/> \
      PREFIX dgtwc: <http://data-gov.tw.rpi.edu/2009/data-gov-twc.rdf#> \
      PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \
      PREFIX conversion: <http://purl.org/twc/vocab/conversion/> \
      SELECT DISTINCT ?thing '+labelVariable+' WHERE { \
        GRAPH <http://purl.org/twc/vocab/conversion/MetaDataset> { \
        [] '+item.facetPredicates+' ?thing . \
        '+predicateLabels+' \
      } \
    }ORDER BY '+labelVariable+' ?thing \
    LIMIT '+sparqlLimit;
    $.ajax({
        url: endpoint,
        beforeSend: function(jqXHR, settings) {
          jqXHR.setRequestHeader("Accept", "application/sparql-results+json");
        },
        data: {
          query: query
        },
        dataType: 'json',
        success: function(data){
          options = "";
          $.each(data.results.bindings, function(index, value){
              var label = value.thing.value;
              if(value.thingLabel !== undefined){
                label = value.thingLabel.value;
              }
              options += '<option value="'+value.thing.value+'" data-name="'+label+'">'+label+'</option>';
          });
          $("#"+item.id).append('<button class="btn btn-mini clear-button" data-target="select-'+item.id+'">clear</button><select multiple class="select-facet facet" id="select-'+item.id+'">'+options+'</select>');
          $('#waiting-'+item.id).addClass('hide');
          //Select values in case they are indicated in hash
          _updateFacetFromHash(item.id);
          if(++facetsLoaded == facets.length){
              $(".select-facet option:first").trigger('change');
          }
        }
    });
}

function _clearFacet(e){
  var selectFacet = $(e.target).attr("data-target");
  $("#"+selectFacet+" option:selected").removeAttr("selected").trigger('change');
}

function init(){
  $.each(facets, function(i, item){
      $("#facets").append('

'+item.id.charAt(0).toUpperCase() + item.id.slice(1)+'

');
      _getFacetData(i, item);
  });
  $(".limit-label").html(fetchLimit);
  $("#keyword-search").typing({
    stop: function (event, $elem) {
      if($elem.val().length >= 3 || $elem.val() === ""){
        $elem.trigger('change');
      }
    },
    delay: 400
});
  $("body").on('change', ".facet", _executeQuery);
  $("body").on('click', ".clear-button", _clearFacet);
  $("body").on('click', ".pager-button", function(e){
      if($(e.target).is('.disabled')){return;}
      if($(e.target).attr("id") == 'previous'){
        fetchOffset--;
      }
      if(fetchOffset < 1){$("#previous").addClass('disabled');}
      if($(e.target).attr("id") == 'next'){
        fetchOffset++;
      }
      if(fetchOffset > 0){$("#previous").removeClass('disabled');}
      _executeQuery();
  });

}

function _parseArgs(){
  var r = {};
  var s = window.location.hash.slice(1);
  $.each(s.split('&'), function(i, item){
      if(item.length > 0){
        pair = item.split('=');
        if(pair[1].length >0){
          var values = [];
          $.each(pair[1].split('|'), function(index, val){if(val.length>1){values.push(val);}});
          r[pair[0]]= values;
        }
      }
  });
  return r;
}

//Init

hashParams = _parseArgs();
init();

});

<commit_msg>Adapted queries to callimachus<commit_after>$(document).ready(function(){
    var endpoint = 'http://logd.tw.rpi.edu:8890/sparql';
    endpoint = 'auth.php';
    var hashParams = {};
    var facetsLoaded = 0;
    var fetchLimit = 25;
    var fetchOffset = 0;
    var firstQuery = true;
    var ajaxObj = undefined;
    function _updateFacetFromHash(id){
      if(hashParams['keyword-search'] !== undefined && hashParams['keyword-search'] != ""){
        $("#keyword-search").val(hashParams['keyword-search']);
      }
      if(hashParams[id] !== undefined){
        $.each(hashParams[id], function(i, item){
          $("#select-"+id+" option[value='"+item+"']").attr("selected", true);
        });
      }
    }

    function _msgError(msg){
      $("#error-details").html(msg);
      $("#error-msg").modal('show');
    }

    function _executeQuery(){
      var facetPatterns = "";
      var hashString = "#";
      fetchOffset = 0;

      //Stop ajax already existing request
      if(ajaxObj !== undefined){
        ajaxObj.abort();
      }

      if($("#keyword-search").val() !== undefined && $("#keyword-search").val() != "" && $("#keyword-search").val().length >= 3){
        facetPatterns += 'FILTER(regex(?datasetTitle, "'+$("#keyword-search").val()+'", "i")) '
        hashString +="keyword-search="+$("#keyword-search").val()+"&";
      }
      $.each(facets, function(i, item){
          var rightDelimiter = '>', leftDelimiter = '<';
          if(item.facetLabelPredicates === undefined){
            rightDelimiter = '"';
            leftDelimiter = '"';
          }
          selectedValues = $("#select-"+item.id+" option:selected");
          if(firstQuery == true && selectedValues.length == 0 && item.default !== undefined){
            selectedValues.push($("#select-"+item.id+" option[value='"+item.default+"']").attr("selected", true));
          }
          hashString += item.id+"=";
          if(selectedValues.length > 1){
            facetPatterns += '{';
          }
          selectedValues.each(function(index, value){
              facetPatterns += '?dataset ' + item.facetPredicates + ' '+leftDelimiter + $(value).val()+ rightDelimiter +' .               ';
              hashString += $(value).val()+"|";
              if(selectedValues.length > 1){
                if(index < selectedValues.length -1){
                  facetPatterns += '}UNION{';
                }else{
                  facetPatterns += '}';
                }
              }
          });
          hashString += "&";
          console.log(hashString);
      });
      firstQuery = false;
      var query = 'PREFIX foaf: <http://xmlns.com/foaf/0.1/> \
      PREFIX dcterms: <http://purl.org/dc/terms/> \
      PREFIX dgtwc: <http://data-gov.tw.rpi.edu/2009/data-gov-twc.rdf#> \
      PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \
      PREFIX conversion: <http://purl.org/twc/vocab/conversion/> \
      SELECT DISTINCT ?dataset ?datasetTitle ?catalog_title ?homepage ?datasetDescription ?catalogHomepage WHERE { \
        ?dataset dcterms:title ?datasetTitle ; \
                 dgtwc:catalog_title ?catalog_title; \
                 foaf:homepage ?homepage . \
        '+facetPatterns+' \
        OPTIONAL{ ?dataset dcterms:description ?datasetDescription} \
        OPTIONAL{ ?dataset dgtwc:catalog_homepage ?catalogHomepage} \
    }ORDER BY ?datasetTitle \
    LIMIT '+(fetchLimit+1) +' \
    OFFSET '+(fetchLimit*fetchOffset);
    $("#results").empty().html('

');
    ajaxObj = $.ajax({
        url: endpoint,
        beforeSend: function(jqXHR, settings) {
          jqXHR.setRequestHeader("Accept", "application/sparql-results+json");
          jqXHR.overrideMimeType('application/sparql-results+json; charset=UTF-8');
        },
        contentType: "application/sparql-results+json; charset=utf-8",
        data: {
          query: query
        },
        dataType: 'json',
        success: function(data){
          $("#results").empty();
          options = "";
          if(data.results.bindings.length > 0){$("#next").removeClass('disabled');}
          $.each(data.results.bindings, function(index, value){
              if(index == fetchLimit){$("#next").removeClass('disabled'); return false;}
              var catalog = value.catalog_title.value;
              if(value.catalogHomepage !== undefined){
                catalog = ''+value.catalog_title.value+'';
              }
              var description = ""
              if(value.datasetDescription !== undefined){
              description = value.datasetDescription.value;
              }
              $("#results").append('

'+value.datasetTitle.value+'

Taken from '+catalog+'

'+description+'
');
          });
          if(data.results.bindings.length < fetchLimit){$("#next").addClass('disabled');}
        }
    });
          window.location.hash = hashString;

}

    function _getFacetData(i, item){
      var predicateLabels = "";
      var labelVariable = "";
      var sparqlLimit = 10000;
      if(item.limit !== undefined){
        sparqlLimit = item.limit;
      }
      if(item.facetLabelPredicates !== undefined){
        predicateLabels = '?thing '+item.facetLabelPredicates+' ?thingLabel .';
        labelVariable = '?thingLabel';
      }
      var query = 'PREFIX foaf: <http://xmlns.com/foaf/0.1/> \
      PREFIX dcterms: <http://purl.org/dc/terms/> \
      PREFIX dgtwc: <http://data-gov.tw.rpi.edu/2009/data-gov-twc.rdf#> \
      PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \
      PREFIX conversion: <http://purl.org/twc/vocab/conversion/> \
      SELECT DISTINCT ?thing '+labelVariable+' WHERE { \
        [] '+item.facetPredicates+' ?thing . \
        '+predicateLabels+' \
    }ORDER BY '+labelVariable+' ?thing \
    LIMIT '+sparqlLimit;
    $.ajax({
        url: endpoint,
        beforeSend: function(jqXHR, settings) {
          jqXHR.setRequestHeader("Accept", "application/sparql-results+json");
        },
        data: {
          query: query
        },
        dataType: 'json',
        success: function(data){
          options = "";
          $.each(data.results.bindings, function(index, value){
              var label = value.thing.value;
              if(value.thingLabel !== undefined){
                label = value.thingLabel.value;
              }
              options += '<option value="'+value.thing.value+'" data-name="'+label+'">'+label+'</option>';
          });
          $("#"+item.id).append('<button class="btn btn-mini clear-button" data-target="select-'+item.id+'">clear</button><select multiple class="select-facet facet" id="select-'+item.id+'">'+options+'</select>');
          $('#waiting-'+item.id).addClass('hide');
          //Select values in case they are indicated in hash
          _updateFacetFromHash(item.id);
          if(++facetsLoaded == facets.length){
              $(".select-facet option:first").trigger('change');
          }
        }
    });
}

function _clearFacet(e){
  var selectFacet = $(e.target).attr("data-target");
  $("#"+selectFacet+" option:selected").removeAttr("selected").trigger('change');
}

function init(){
  $.each(facets, function(i, item){
      $("#facets").append('

'+item.id.charAt(0).toUpperCase() + item.id.slice(1)+'

');
      _getFacetData(i, item);
  });
  $(".limit-label").html(fetchLimit);
  $("#keyword-search").typing({
    stop: function (event, $elem) {
      if($elem.val().length >= 3 || $elem.val() === ""){
        $elem.trigger('change');
      }
    },
    delay: 400
});
  $("body").on('change', ".facet", _executeQuery);
  $("body").on('click', ".clear-button", _clearFacet);
  $("body").on('click', ".pager-button", function(e){
      if($(e.target).is('.disabled')){return;}
      if($(e.target).attr("id") == 'previous'){
        fetchOffset--;
      }
      if(fetchOffset < 1){$("#previous").addClass('disabled');}
      if($(e.target).attr("id") == 'next'){
        fetchOffset++;
      }
      if(fetchOffset > 0){$("#previous").removeClass('disabled');}
      _executeQuery();
  });

}

function _parseArgs(){
  var r = {};
  var s = window.location.hash.slice(1);
  $.each(s.split('&'), function(i, item){
      if(item.length > 0){
        pair = item.split('=');
        if(pair[1].length >0){
          var values = [];
          $.each(pair[1].split('|'), function(index, val){if(val.length>1){values.push(val);}});
          r[pair[0]]= values;
        }
      }
  });
  return r;
}

//Init

hashParams = _parseArgs();
init();

});

<|endoftext|>


<commit_before>function friendlyDate(utcString) {
  var K = function () {
      var a = navigator.userAgent;
      return {
        ie: a.match(/MSIE\s([^;]*)/)
      }
    }();
  var H = function (a) {
      var b = new Date();
      var c = new Date(a);
      if (K.ie) {
        c = Date.parse(a.replace(/( \+)/, ' UTC$1'))
      }
      var d = b - c;
      var e = 1000,
        minute = e * 60,
        hour = minute * 60,
        day = hour * 24,
        week = day * 7;
      if (isNaN(d) || d < 0) {
        return ""
      }
      if (d < e * 7) {
        return "right now"
      }
      if (d < minute) {
        return Math.floor(d / e) + "s"
      }
      if (d < minute * 2) {
        return "1m"
      }
      if (d < hour) {
        return Math.floor(d / minute) + "m"
      }
      if (d < hour * 2) {
        return "1h"
      }
      if (d < day) {
        return Math.floor(d / hour) + "h"
      }
      if (d > day && d < day * 2) {
        return "1d"
      }
      if (d < day * 365) {
        return Math.floor(d / day) + "d"
      } else {
        return "over a year ago"
      }
    };
  return H(utcString);
}

var ftwidget = '

Trending in Timeline

Powered by Trendy

';

var testModal = '

<button type="button" style="float: right;width: 15px;height: 20px;background: url(https://si0.twimg.com/a/1339639284/t1/img/twitter_web_sprite_icons.png) no-repeat 0 -510px;cursor: pointer;" class="close" data-dismiss="modal"></button>

Close

';

var foo = {
  "#mlg": [{
    "username": "StarCraft",
    "name": "StarCraft",
    "text": "Can you believe it? Sase takes down Stephano and is one step closer to meeting MKP in the #MLG Spring Championship LB Final. #SC2",
    "photo": "https://si0.twimg.com/profile_images/360825080/iconS_normal.gif",
    "timestamp": "Sun Jun 10 21:06:12 +0000 2012",
    "id": 211927268539379700,
    "retweet_by": null
  }, {
    "username": "day9tv",
    "name": "Sean Plott",
    "text": "Mad props to SaSe.  Thus far at MLG he's beaten beastyqt, desrow, ostojiy, mystik, sleep, socke, heart, violet, rain, grubby, leenock & polt",
    "photo": "https://si0.twimg.com/profile_images/1796380463/Day9_Twitter_normal.jpg",
    "timestamp": "Sun Jun 10 21:06:12 +0000 2012",
    "id": 211923341479653380,
    "retweet_by": null
  }, {
    "username": "MrBitterTV",
    "name": "Ben Nichol",
    "text": "Casting Sase vs Alicia with Husky on the Blue Stream. After that, I think I'm done! Can't wait to kick back and watch the finals. #MLG",
    "photo": "https://si0.twimg.com/profile_images/1581590309/bitter3_normal.jpg",
    "timestamp": "Sun Jun 10 21:24:38 +0000 2012",
    "id": 211931906156146700,
    "retweet_by": {
      "name": "Husky",
      "username": "HuskyStarcraft"
    }
  }, {
    "username": "HuskyStarcraft",
    "name": "Husky",
    "text": "From what I can tell sase has chat turned off, he's not being BM :P",
    "photo": "https://si0.twimg.com/profile_images/1881061387/husky_no_text_01_200x200_normal.jpg",
    "timestamp": "Sun Jun 10 21:06:12 +0000 2012",
    "id": 211925442926624770,
    "retweet_by": null
  }, {
    "username": "StarCraft",
    "name": "StarCraft",
    "text": "Watching @MLG Anaheim Championship Sunday from a #BarCraft? Tweet us your favorite pics or find a BarCraft near you. http://t.co/H8l0Icev",
    "photo": "https://si0.twimg.com/profile_images/360825080/iconS_normal.gif",
    "timestamp": "Sun Jun 10 20:28:23 +0000 2012",
    "id": 211917751357407230,
    "retweet_by": null
  }, {
    "username": "StarCraft",
    "name": "StarCraft",
    "text": "We're tied up in the battle of the foreigners, Sase vs Stephano, on #MLG SC2 Red. Tune in now to see who will advance! http://t.co/mbPLnDHR",
    "photo": "https://si0.twimg.com/profile_images/360825080/iconS_normal.gif",
    "timestamp": "Sun Jun 10 20:50:37 +0000 2012",
    "id": 211917751357407230,
    "retweet_by": null
  }],
  "facebook": [{
    "username": "mashable",
    "name": "Pete Cashmore",
    "text": "Facebook Client Pica for iPad Returns with Lots of New Features http://t.co/11p3lql1 via @appadvice",
    "photo": "https://si0.twimg.com/profile_images/2015016150/petecashmoreavatar_normal.png",
    "timestamp": "Sun Jun 10 21:30:33 +0000 2012",
    "id": 211933395649953800,
    "retweet_by": null
  }, {
    "username": "barrylibert",
    "name": "Barry Libery",
    "text": "Facebook Growth Shows Signs of Leveling Off after reaching nearly 1 billion customers.  It is clear that trees don't grow to the sky!",
    "photo": "https://si0.twimg.com/profile_images/1127610035/BL_photoALT_normal.jpg",
    "timestamp": "Sun Jun 10 20:54:36 +0000 2012",
    "id": 211924346057396220,
    "retweet_by": null
  }, {
    "username": "KLatif",
    "name": "Khalid Latif",
    "text": "Help us reach 7000 on @KLatif facebook page by liking it and inviting your friends to like it! http://t.co/lXFwhIrr",
    "photo": "https://si0.twimg.com/profile_images/1600235421/tzleft.khalidlatif.cnn_normal.jpg",
    "timestamp": "Sun Jun 10 20:50:07 +0000 2012",
    "id": 211923218402000900,
    "retweet_by": null
  }]
};

(function loadWidget() {

  setTimeout(function () {
    var module = $('div.module.trends.component')
    if (module.length < 1) {
      loadWidget();
      return;
    } else {
      /* WRITE ALL CODE HERE */
      module.after(testModal, ftwidget);

      //This is the screen name of the user currently signed in to Twitter
      var username = $('div.account-group.js-mini-current-user:first').data('screenName');

      var i = 1;
      var ul = $("#ftwidget");

      $('div.dashboard').on('click', 'a.friendTrendLink', function (e) {
        e.preventDefault();
      });

      for (trend in foo) {
        $(ul).append('
' + trend + '
');
        i++;
      };

      // Hides the modal so it doesn't automatically display on page load.
      $('#myModal').hide();

      $('a.friendTrendLink').on('click', function () {
        var trend = $(this).text();
        $('#resultsWinTitle').html('Results for ' + trend + '');

        var tweetsOfTrend = foo[trend];

        // Empty's the contents of the modal loading tweets.
        $('div.modal-body').empty();

        for (var i = 0; i < tweetsOfTrend.length; i++) {
          var tweet = tweetsOfTrend[i];
          $('div.modal-body').append('

' + friendlyDate(tweet.timestamp) + '' + tweet.name + '<s>@</s>' + tweet.username + '

' + tweet.text + '

Details

');
        };
      });

    }

  }, 2500);
});
<commit_msg>Made function self-invoking<commit_after>function friendlyDate(utcString) {
  var K = function () {
      var a = navigator.userAgent;
      return {
        ie: a.match(/MSIE\s([^;]*)/)
      }
    }();
  var H = function (a) {
      var b = new Date();
      var c = new Date(a);
      if (K.ie) {
        c = Date.parse(a.replace(/( \+)/, ' UTC$1'))
      }
      var d = b - c;
      var e = 1000,
        minute = e * 60,
        hour = minute * 60,
        day = hour * 24,
        week = day * 7;
      if (isNaN(d) || d < 0) {
        return ""
      }
      if (d < e * 7) {
        return "right now"
      }
      if (d < minute) {
        return Math.floor(d / e) + "s"
      }
      if (d < minute * 2) {
        return "1m"
      }
      if (d < hour) {
        return Math.floor(d / minute) + "m"
      }
      if (d < hour * 2) {
        return "1h"
      }
      if (d < day) {
        return Math.floor(d / hour) + "h"
      }
      if (d > day && d < day * 2) {
        return "1d"
      }
      if (d < day * 365) {
        return Math.floor(d / day) + "d"
      } else {
        return "over a year ago"
      }
    };
  return H(utcString);
}

var ftwidget = '

Trending in Timeline

Powered by Trendy

';

var testModal = '

<button type="button" style="float: right;width: 15px;height: 20px;background: url(https://si0.twimg.com/a/1339639284/t1/img/twitter_web_sprite_icons.png) no-repeat 0 -510px;cursor: pointer;" class="close" data-dismiss="modal"></button>

Close

';

var foo = {
  "#mlg": [{
    "username": "StarCraft",
    "name": "StarCraft",
    "text": "Can you believe it? Sase takes down Stephano and is one step closer to meeting MKP in the #MLG Spring Championship LB Final. #SC2",
    "photo": "https://si0.twimg.com/profile_images/360825080/iconS_normal.gif",
    "timestamp": "Sun Jun 10 21:06:12 +0000 2012",
    "id": 211927268539379700,
    "retweet_by": null
  }, {
    "username": "day9tv",
    "name": "Sean Plott",
    "text": "Mad props to SaSe.  Thus far at MLG he's beaten beastyqt, desrow, ostojiy, mystik, sleep, socke, heart, violet, rain, grubby, leenock & polt",
    "photo": "https://si0.twimg.com/profile_images/1796380463/Day9_Twitter_normal.jpg",
    "timestamp": "Sun Jun 10 21:06:12 +0000 2012",
    "id": 211923341479653380,
    "retweet_by": null
  }, {
    "username": "MrBitterTV",
    "name": "Ben Nichol",
    "text": "Casting Sase vs Alicia with Husky on the Blue Stream. After that, I think I'm done! Can't wait to kick back and watch the finals. #MLG",
    "photo": "https://si0.twimg.com/profile_images/1581590309/bitter3_normal.jpg",
    "timestamp": "Sun Jun 10 21:24:38 +0000 2012",
    "id": 211931906156146700,
    "retweet_by": {
      "name": "Husky",
      "username": "HuskyStarcraft"
    }
  }, {
    "username": "HuskyStarcraft",
    "name": "Husky",
    "text": "From what I can tell sase has chat turned off, he's not being BM :P",
    "photo": "https://si0.twimg.com/profile_images/1881061387/husky_no_text_01_200x200_normal.jpg",
    "timestamp": "Sun Jun 10 21:06:12 +0000 2012",
    "id": 211925442926624770,
    "retweet_by": null
  }, {
    "username": "StarCraft",
    "name": "StarCraft",
    "text": "Watching @MLG Anaheim Championship Sunday from a #BarCraft? Tweet us your favorite pics or find a BarCraft near you. http://t.co/H8l0Icev",
    "photo": "https://si0.twimg.com/profile_images/360825080/iconS_normal.gif",
    "timestamp": "Sun Jun 10 20:28:23 +0000 2012",
    "id": 211917751357407230,
    "retweet_by": null
  }, {
    "username": "StarCraft",
    "name": "StarCraft",
    "text": "We're tied up in the battle of the foreigners, Sase vs Stephano, on #MLG SC2 Red. Tune in now to see who will advance! http://t.co/mbPLnDHR",
    "photo": "https://si0.twimg.com/profile_images/360825080/iconS_normal.gif",
    "timestamp": "Sun Jun 10 20:50:37 +0000 2012",
    "id": 211917751357407230,
    "retweet_by": null
  }],
  "facebook": [{
    "username": "mashable",
    "name": "Pete Cashmore",
    "text": "Facebook Client Pica for iPad Returns with Lots of New Features http://t.co/11p3lql1 via @appadvice",
    "photo": "https://si0.twimg.com/profile_images/2015016150/petecashmoreavatar_normal.png",
    "timestamp": "Sun Jun 10 21:30:33 +0000 2012",
    "id": 211933395649953800,
    "retweet_by": null
  }, {
    "username": "barrylibert",
    "name": "Barry Libery",
    "text": "Facebook Growth Shows Signs of Leveling Off after reaching nearly 1 billion customers.  It is clear that trees don't grow to the sky!",
    "photo": "https://si0.twimg.com/profile_images/1127610035/BL_photoALT_normal.jpg",
    "timestamp": "Sun Jun 10 20:54:36 +0000 2012",
    "id": 211924346057396220,
    "retweet_by": null
  }, {
    "username": "KLatif",
    "name": "Khalid Latif",
    "text": "Help us reach 7000 on @KLatif facebook page by liking it and inviting your friends to like it! http://t.co/lXFwhIrr",
    "photo": "https://si0.twimg.com/profile_images/1600235421/tzleft.khalidlatif.cnn_normal.jpg",
    "timestamp": "Sun Jun 10 20:50:07 +0000 2012",
    "id": 211923218402000900,
    "retweet_by": null
  }]
};

(function loadWidget() {

  setTimeout(function () {
    var module = $('div.module.trends.component')
    if (module.length < 1) {
      loadWidget();
      return;
    } else {
      /* WRITE ALL CODE HERE */
      module.after(testModal, ftwidget);

      //This is the screen name of the user currently signed in to Twitter
      var username = $('div.account-group.js-mini-current-user:first').data('screenName');

      var i = 1;
      var ul = $("#ftwidget");

      $('div.dashboard').on('click', 'a.friendTrendLink', function (e) {
        e.preventDefault();
      });

      for (trend in foo) {
        $(ul).append('
' + trend + '
');
        i++;
      };

      // Hides the modal so it doesn't automatically display on page load.
      $('#myModal').hide();

      $('a.friendTrendLink').on('click', function () {
        var trend = $(this).text();
        $('#resultsWinTitle').html('Results for ' + trend + '');

        var tweetsOfTrend = foo[trend];

        // Empty's the contents of the modal loading tweets.
        $('div.modal-body').empty();

        for (var i = 0; i < tweetsOfTrend.length; i++) {
          var tweet = tweetsOfTrend[i];
          $('div.modal-body').append('

' + friendlyDate(tweet.timestamp) + '' + tweet.name + '<s>@</s>' + tweet.username + '

' + tweet.text + '

Details

');
        };
      });

    }

  }, 2500);
})();
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import {Form, FormControl, FormGroup, Button} from 'react-bootstrap';
import SignupModal from './SignupModal';
import * as config from '../../config';
import {Link} from 'react-router-dom';

import axios from 'axios';
axios.defaults.withCredentials = true;

class SignupForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            email: '',
            isModalOpen: false,
            isSignupButtonLoading: false,
            invalidEmail: false
        };
    }

    hideModal = () => {
        this.setState({isModalOpen: false});
    }

    handleEmailChange = (event) => {
        this.setState({email: event.target.value});
        if (this.state.invalidEmail) {
            this.setState({invalidEmail: false});
        }
    }

    signupSubmit = (event) => {
        event.preventDefault();
        this.setState({isSignupButtonLoading: true});

        axios.post(config.backendUrl + '/signup', {email: this.state.email})
        .then(res => {
            if (res.status === 200 && res.data === 'Signup OK') {
                this.setState({
                    isSignupButtonLoading: false,
                    isModalOpen: true,
                    email: ''
                });
            }
        })
        .catch(error => {
            this.setState({
                isSignupButtonLoading: false,
                invalidEmail: true
            });
            this.signupEmail.focus();
            console.log(error);
        })
    }

    render() {
        return (

                Το ακαδημαϊκό σου email:
                <Form horizontal className="signup-form" onSubmit={this.signupSubmit}>
                    <FormGroup
                        validationState={this.state.invalidEmail ? "warning" : null}
                        ref={(input) => { this.signupForm = input; }}
                    >
                        <FormControl
                            type="text"
                            name="email"
                            autoComplete="off"
                            autoFocus
                            placeholder="example@uoa.gr"
                            ref={(input) => { this.signupEmail = input; }}
                            value={this.state.email}
                            disabled={this.state.isSignupButtonLoading}
                            onChange={this.handleEmailChange}
                        />
                    </FormGroup>
                    <Button
                        type="submit"
                        bsStyle="primary"
                        id="btn-signup"
                        disabled={this.state.isSignupButtonLoading}
                        onClick={!this.state.isSignupButtonLoading? this.signupSubmit : null}
                    >
                        {this.state.isSignupButtonLoading? 'Εγγραφή...' : 'Εγγραφή'}
                    </Button>
                    {this.state.invalidEmail ?

                            Υπήρξε κάποιο πρόβλημα! Χρησιμοποίησες ένα <Link to="/faq" target="_blank">έγκυρο ακαδημαϊκό</Link> email?

                    : null}
                </Form>

Η διεύθυνση email σου θα χρησιμοποιηθεί μόνο για να επιβεβαιωθεί ότι είσαι φοιτητής.

                <SignupModal isModalOpen={this.state.isModalOpen} hideModal={this.hideModal} />

        );
    }
}

export default SignupForm;
<commit_msg>Correct padding between label/input in signup form<commit_after>import React, { Component } from 'react';
import {Form, FormControl, FormGroup, Button} from 'react-bootstrap';
import SignupModal from './SignupModal';
import * as config from '../../config';
import {Link} from 'react-router-dom';

import axios from 'axios';
axios.defaults.withCredentials = true;

class SignupForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            email: '',
            isModalOpen: false,
            isSignupButtonLoading: false,
            invalidEmail: false
        };
    }

    hideModal = () => {
        this.setState({isModalOpen: false});
    }

    handleEmailChange = (event) => {
        this.setState({email: event.target.value});
        if (this.state.invalidEmail) {
            this.setState({invalidEmail: false});
        }
    }

    signupSubmit = (event) => {
        event.preventDefault();
        this.setState({isSignupButtonLoading: true});

        axios.post(config.backendUrl + '/signup', {email: this.state.email})
        .then(res => {
            if (res.status === 200 && res.data === 'Signup OK') {
                this.setState({
                    isSignupButtonLoading: false,
                    isModalOpen: true,
                    email: ''
                });
            }
        })
        .catch(error => {
            this.setState({
                isSignupButtonLoading: false,
                invalidEmail: true
            });
            this.signupEmail.focus();
            console.log(error);
        })
    }

    render() {
        return (

Το ακαδημαϊκό σου email:

                <Form horizontal className="signup-form" onSubmit={this.signupSubmit}>
                    <FormGroup
                        validationState={this.state.invalidEmail ? "warning" : null}
                        ref={(input) => { this.signupForm = input; }}
                    >
                        <FormControl
                            type="text"
                            name="email"
                            autoComplete="off"
                            autoFocus
                            placeholder="example@uoa.gr"
                            ref={(input) => { this.signupEmail = input; }}
                            value={this.state.email}
                            disabled={this.state.isSignupButtonLoading}
                            onChange={this.handleEmailChange}
                        />
                    </FormGroup>
                    <Button
                        type="submit"
                        bsStyle="primary"
                        id="btn-signup"
                        disabled={this.state.isSignupButtonLoading}
                        onClick={!this.state.isSignupButtonLoading? this.signupSubmit : null}
                    >
                        {this.state.isSignupButtonLoading? 'Εγγραφή...' : 'Εγγραφή'}
                    </Button>
                    {this.state.invalidEmail ?

                            Υπήρξε κάποιο πρόβλημα! Χρησιμοποίησες ένα <Link to="/faq" target="_blank">έγκυρο ακαδημαϊκό</Link> email?

                    : null}
                </Form>

Η διεύθυνση email σου θα χρησιμοποιηθεί μόνο για να επιβεβαιωθεί ότι είσαι φοιτητής.

                <SignupModal isModalOpen={this.state.isModalOpen} hideModal={this.hideModal} />

        );
    }
}

export default SignupForm;
<|endoftext|>


<commit_before>// ./routes/doctor.js

// Recuperation des librairies de base
var express= require("express");
var router = express.Router();

// Recuperation du module controller doctor
var doctor_controller = require("../controllers/doctorController");

// Authentificaiton
function requiresLogin(req, res, next) {
  console.log("requiresLogin",req)
  if (req.sessions && req.sessions.userId) {
    return next();
  } else {
    var err = new Error('not connected');
    err.status = 401;
    return next(err);
  }
}

/// DOCTOR ROUTES ///

/* GET | Page d'accueil */
router.get("/", doctor_controller.index);

/*  POST | Creation d'un medecin */
router.post("/register", doctor_controller.doctor_register_post);

/*  POST | Connection d'un medecin */
router.post("/login", doctor_controller.doctor_login_post);

/*  POST | Deconneixon d'un medecin */
router.get("/logout", requiresLogin, doctor_controller.doctor_logout);

/* GET | Demande le profile d'un medecin */
router.get("/list", doctor_controller.doctor_list);

/* GET | Demande les infos d'un medecins */
router.get("/profile", requiresLogin, doctor_controller.doctor_profile_get);

/* POST | Ajoute un nouveau retard a un medecin */
router.post("/profile", requiresLogin, doctor_controller.doctor_profile_post);

/* DELETE | Demande de suppression d'un medecin */
router.delete("/:id/delete", doctor_controller.doctor_remove_delete);

/* PUT | Demande de mis à jour d'un medecin */
router.put("/:id/update", doctor_controller.doctor_update_put);

/* GET | Demande d'information pour un medecin */
router.get("/:id", doctor_controller.doctor_details);

module.exports = router;<commit_msg>test5<commit_after>// ./routes/doctor.js

// Recuperation des librairies de base
var express= require("express");
var router = express.Router();

// Recuperation du module controller doctor
var doctor_controller = require("../controllers/doctorController");

// Authentificaiton
function requiresLogin(req, res, next) {
  console.log("requiresLogin",req.sessionStore)
  if (req.sessions && req.sessions.userId) {
    return next();
  } else {
    var err = new Error('not connected');
    err.status = 401;
    return next(err);
  }
}

/// DOCTOR ROUTES ///

/* GET | Page d'accueil */
router.get("/", doctor_controller.index);

/*  POST | Creation d'un medecin */
router.post("/register", doctor_controller.doctor_register_post);

/*  POST | Connection d'un medecin */
router.post("/login", doctor_controller.doctor_login_post);

/*  POST | Deconneixon d'un medecin */
router.get("/logout", requiresLogin, doctor_controller.doctor_logout);

/* GET | Demande le profile d'un medecin */
router.get("/list", doctor_controller.doctor_list);

/* GET | Demande les infos d'un medecins */
router.get("/profile", requiresLogin, doctor_controller.doctor_profile_get);

/* POST | Ajoute un nouveau retard a un medecin */
router.post("/profile", requiresLogin, doctor_controller.doctor_profile_post);

/* DELETE | Demande de suppression d'un medecin */
router.delete("/:id/delete", doctor_controller.doctor_remove_delete);

/* PUT | Demande de mis à jour d'un medecin */
router.put("/:id/update", doctor_controller.doctor_update_put);

/* GET | Demande d'information pour un medecin */
router.get("/:id", doctor_controller.doctor_details);

module.exports = router;<|endoftext|>