<commit_before>var Board = function( attributes ){
  this.humanoid;
  this.humanoids = attributes.humanoids || [];
  this.width = attributes.width  || '600px';
  this.height = attributes.height || '400px';
}

Board.prototype = {
  isPositionEqual: function( position1, position2 ){
    return position1.x === position2.x && position1.y === position2.y
  },
  isValidDestination: function( target_position ){
    var result = true
    for(var i= 0; i < this.humanoids.length; i++ ){
      if( this.isPositionEqual( this.humanoids[i].position , target_position ) ){
        result = false
      }
    }
    return result
  },

  nearestHumanoid: function( humanoidType ){
    var similarHumanoids = this.findSimilarHumanoids( humanoidType )
    var closestPos = this.findClosestPos( similarHumanoids )
    var closestHumanoid = this.findClosestHumanoid( closestPos, similarHumanoids )
    return closestHumanoid
  },

  isAnyHumanRemaining: function(){
    var result = false
    for( var i=0; i < this.humanoids.length; i++ ){
      if(this.humanoids[i].humanType == "human") { result = true; break };
    }
    return result
  },

  nextTurn: function(){
    for( var i=0; i< this.humanoids.length; i++ ){
      if( this.humanoids[i].humanType == "infectedHuman" ){
          this.humanoids[i].incrementTimeSinceInfection()
          continue
      }
      this.humanoid = this.humanoids[i]
      var nearestZombie = this.nearestHumanoid( "zombie" )
      var nearestHuman = this.nearestHumanoid( "human" )
      var destination = this.setDestination( nearestHuman, nearestZombie )
      destination.x = ( (destination.x + this.width) % this.width )
      destination.y = ( (destination.y + this.height) % this.height )

      if ( this.humanoid.isAbleToBite() ){
        this.humanoid.bite( nearestHuman )
      }

      if( this.isValidDestination( destination ) ){
        this.humanoid.position = destination
      }
    };
  },

  setDestination: function( nearestHuman, nearestZombie ){
    if( nearestHuman === null || nearestHuman === undefined  ) { return this.humanoid.moveNearest(  nearestZombie  )}
    else if( this.humanoid.humanType == "zombie" ){ return this.setZombieDestination( nearestHuman, nearestZombie ) }
    else if( this.humanoid.humanType == "human" ){ return this.setHumanDestination( nearestHuman, nearestZombie ) }
    else { return this.humanoid.position }
  },
  setZombieDestination: function( nearestHuman, nearestZombie ){
   if ( Pathfinder.distanceTo( nearestHuman.position, this.humanoid.position ) < Pathfinder.distanceTo( nearestZombie.position, this.humanoid.position ) * gameSettings.zombieSpread){
      return this.humanoid.moveNearest( nearestHuman )
    }
    else {
      return this.humanoid.moveNearest( nearestZombie )
    }
  },
  setHumanDestination: function( nearestHuman, nearestZombie ){
    if ( Pathfinder.distanceTo( nearestZombie.position, this.humanoid.position ) < gameSettings.humanFearRange ){
      return this.humanoid.moveNearest( nearestZombie )
    }
    else {
      return this.humanoid.moveNearest( nearestHuman )
    }
  },

  deleteSelfHumanoid: function(){
    var otherHumanoids = []
    for( var i=0; i < this.humanoids.length; i++){otherHumanoids.push(this.humanoids[i])}

    for( var i=0; i < this.humanoids.length; i++ ){
      if( this.isPositionEqual( this.humanoids[i].position , this.humanoid.position ) ){
        otherHumanoids.splice( i, 1 )
        break
      }
    }
    return otherHumanoids
  },
  findSimilarHumanoids: function( humanoidType ){
    var otherHumanoids = this.deleteSelfHumanoid()
    var similar = [];
    for( var i=0; i< otherHumanoids.length; i++ ){
      if( otherHumanoids[i].humanType === humanoidType ){ similar.push(otherHumanoids[i])}
    }
    return similar
  },
  findClosestPos: function( otherHumanoids ){
    var closestPos = []
    for( var i=0; i< otherHumanoids.length; i++ ){
      var dist = Pathfinder.distanceTo( otherHumanoids[i].position, this.humanoid.position )
      closestPos.push( dist );
    }
    return closestPos
  },
  findClosestHumanoid: function( closestPos, otherHumanoids ){
    var closestHumanoidValue = Math.min.apply( null, closestPos )
    for( var i=0; i < closestPos.length; i++ ){
      if( closestPos[i] == closestHumanoidValue ){ var closestHumanoid = otherHumanoids[i]}
    }
   return closestHumanoid
  }
}<commit_msg>move declaration of this.humanoid and rename variables in next turn function<commit_after>var Board = function( attributes ){
  this.humanoid;
  this.humanoids = attributes.humanoids || [];
  this.width = attributes.width  || '600px';
  this.height = attributes.height || '400px';
}

Board.prototype = {
  isPositionEqual: function( position1, position2 ){
    return position1.x === position2.x && position1.y === position2.y
  },
  isValidDestination: function( target_position ){
    var result = true
    for(var i= 0; i < this.humanoids.length; i++ ){
      if( this.isPositionEqual( this.humanoids[i].position , target_position ) ){
        result = false
      }
    }
    return result
  },

  nearestHumanoid: function( humanoidType ){
    var similarHumanoids = this.findSimilarHumanoids( humanoidType )
    var closestPos = this.findClosestPos( similarHumanoids )
    var closestHumanoid = this.findClosestHumanoid( closestPos, similarHumanoids )
    return closestHumanoid
  },

  isAnyHumanRemaining: function(){
    var result = false
    for( var i=0; i < this.humanoids.length; i++ ){
      if(this.humanoids[i].humanType == "human") { result = true; break };
    }
    return result
  },

  nextTurn: function(){
    for( var i=0; i< this.humanoids.length; i++ ){
      this.humanoid = this.humanoids[i]
      if( this.humanoid.humanType == "infectedHuman" ){
          this.humanoid.incrementTimeSinceInfection()
          continue
      }
      var nearestZombie = this.nearestHumanoid( "zombie" )
      var nearestHuman = this.nearestHumanoid( "human" )
      var destination = this.setDestination( nearestHuman, nearestZombie )
      destination.x = ( (destination.x + this.width) % this.width )
      destination.y = ( (destination.y + this.height) % this.height )

      if ( this.humanoid.isAbleToBite() ){
        this.humanoid.bite( nearestHuman )
      }

      if( this.isValidDestination( destination ) ){
        this.humanoid.position = destination
      }
    };
  },

  setDestination: function( nearestHuman, nearestZombie ){
    if( nearestHuman === null || nearestHuman === undefined  ) { return this.humanoid.moveNearest(  nearestZombie  )}
    else if( this.humanoid.humanType == "zombie" ){ return this.setZombieDestination( nearestHuman, nearestZombie ) }
    else if( this.humanoid.humanType == "human" ){ return this.setHumanDestination( nearestHuman, nearestZombie ) }
    else { return this.humanoid.position }
  },
  setZombieDestination: function( nearestHuman, nearestZombie ){
   if ( Pathfinder.distanceTo( nearestHuman.position, this.humanoid.position ) < Pathfinder.distanceTo( nearestZombie.position, this.humanoid.position ) * gameSettings.zombieSpread){
      return this.humanoid.moveNearest( nearestHuman )
    }
    else {
      return this.humanoid.moveNearest( nearestZombie )
    }
  },
  setHumanDestination: function( nearestHuman, nearestZombie ){
    if ( Pathfinder.distanceTo( nearestZombie.position, this.humanoid.position ) < gameSettings.humanFearRange ){
      return this.humanoid.moveNearest( nearestZombie )
    }
    else {
      return this.humanoid.moveNearest( nearestHuman )
    }
  },

  deleteSelfHumanoid: function(){
    var otherHumanoids = []
    for( var i=0; i < this.humanoids.length; i++){otherHumanoids.push(this.humanoids[i])}

    for( var i=0; i < this.humanoids.length; i++ ){
      if( this.isPositionEqual( this.humanoids[i].position , this.humanoid.position ) ){
        otherHumanoids.splice( i, 1 )
        break
      }
    }
    return otherHumanoids
  },
  findSimilarHumanoids: function( humanoidType ){
    var otherHumanoids = this.deleteSelfHumanoid()
    var similar = [];
    for( var i=0; i< otherHumanoids.length; i++ ){
      if( otherHumanoids[i].humanType === humanoidType ){ similar.push(otherHumanoids[i])}
    }
    return similar
  },
  findClosestPos: function( otherHumanoids ){
    var closestPos = []
    for( var i=0; i< otherHumanoids.length; i++ ){
      var dist = Pathfinder.distanceTo( otherHumanoids[i].position, this.humanoid.position )
      closestPos.push( dist );
    }
    return closestPos
  },
  findClosestHumanoid: function( closestPos, otherHumanoids ){
    var closestHumanoidValue = Math.min.apply( null, closestPos )
    for( var i=0; i < closestPos.length; i++ ){
      if( closestPos[i] == closestHumanoidValue ){ var closestHumanoid = otherHumanoids[i]}
    }
   return closestHumanoid
  }
}<|endoftext|>


<commit_before>var EventEmitter     = require('events').EventEmitter;
var assign           = require('../../polyfills/assign');
var RemoteDispatcher = require('../dispatcher/RemoteDispatcher');
var RemoteConstants  = require('../constants/RemoteConstants');

var CHANGE_EVENT = 'change';

var state = {};

var RemoteConfigStore = assign({}, EventEmitter.prototype, {
  emitChange          : function(changeEvent) {this.emit(CHANGE_EVENT, changeEvent); },
  addChangeListener   : function(callback) {this.on(CHANGE_EVENT, callback); },
  removeChangeListener: function(callback) {this.removeListener(CHANGE_EVENT, callback); },
  getAuth             : function(provider) {
    if(state && state.services && state.services.auth && state.services.auth[provider]){
      return state.services.auth[provider]
    }
    return undefined
  },
  getHullToken        : function(){ return state.access_token; },
  getState            : function(){ return state; },

  dispatcherIndex: RemoteDispatcher.register(function(payload) {
    var action = payload.action;
    var text;

    switch(action.actionType) {
      case RemoteConstants.UPDATE_REMOTE_CONFIG:
        state = action.config
        if(!action.options.silent===true){
          RemoteConfigStore.emitChange(action.actionType);
        }
        break;

      case RemoteConstants.UPDATE_SERVICES:
        state.services = action.services;
        if(!action.options.silent===true){
          RemoteConfigStore.emitChange(action.actionType);
        }
        break;

      case RemoteConstants.UPDATE_USER:
        state.access_token = action.user.access_token
        if(!action.options.silent===true){
          RemoteConfigStore.emitChange(action.actionType);
        }
        break;

      case RemoteConstants.LOGOUT_USER:
        delete state.access_token
        if(state.services && state.services.auth){
          _.map(state.services, function(services, type){
            _.map(services, function(service, key){
              delete service.credentials
              // Since Hull Storage doesnt have the same format as the others :(
              if(type==='storage'){ delete service.params }
            });
          });
        }
        if(!action.options.silent===true){
          RemoteConfigStore.emitChange(action.actionType);
        }
        break;

    }
    return true;
  })

});

module.exports = RemoteConfigStore;
<commit_msg>fix missing require<commit_after>var EventEmitter     = require('events').EventEmitter;
var _                = require('../../utils/lodash');
var assign           = require('../../polyfills/assign');
var RemoteDispatcher = require('../dispatcher/RemoteDispatcher');
var RemoteConstants  = require('../constants/RemoteConstants');

var CHANGE_EVENT = 'change';

var state = {};

var RemoteConfigStore = assign({}, EventEmitter.prototype, {
  emitChange          : function(changeEvent) {this.emit(CHANGE_EVENT, changeEvent); },
  addChangeListener   : function(callback) {this.on(CHANGE_EVENT, callback); },
  removeChangeListener: function(callback) {this.removeListener(CHANGE_EVENT, callback); },
  getAuth             : function(provider) {
    if(state && state.services && state.services.auth && state.services.auth[provider]){
      return state.services.auth[provider]
    }
    return undefined
  },
  getHullToken        : function(){ return state.access_token; },
  getState            : function(){ return state; },

  dispatcherIndex: RemoteDispatcher.register(function(payload) {
    var action = payload.action;
    var text;

    switch(action.actionType) {
      case RemoteConstants.UPDATE_REMOTE_CONFIG:
        state = action.config
        if(!action.options.silent===true){
          RemoteConfigStore.emitChange(action.actionType);
        }
        break;

      case RemoteConstants.UPDATE_SERVICES:
        state.services = action.services;
        if(!action.options.silent===true){
          RemoteConfigStore.emitChange(action.actionType);
        }
        break;

      case RemoteConstants.UPDATE_USER:
        state.access_token = action.user.access_token
        if(!action.options.silent===true){
          RemoteConfigStore.emitChange(action.actionType);
        }
        break;

      case RemoteConstants.LOGOUT_USER:
        delete state.access_token
        if(state.services && state.services.auth){
          _.map(state.services, function(services, type){
            _.map(services, function(service, key){
              delete service.credentials
              // Since Hull Storage doesnt have the same format as the others :(
              if(type==='storage'){ delete service.params }
            });
          });
        }
        if(!action.options.silent===true){
          RemoteConfigStore.emitChange(action.actionType);
        }
        break;

    }
    return true;
  })

});

module.exports = RemoteConfigStore;
<|endoftext|>


<commit_before>$(document).ready(function() {
  $("#new_id").attr("placeholder", "(auto-generated identifier)");
});

function addChild()
{
    var id = $("#new_id").val().trim();

    var mixin = $("#new_mixin").val();

    var newURI = $('#main').attr('resource') + (!id ? "" : "/" + id);

    var postURI = newURI;

    if (mixin == "binary") {
        var update_file = document.getElementById("binary_payload").files[0];
        var reader = new FileReader();
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
                if (xhr.status == 201) {
                    var loc = xhr.getResponseHeader('Location');
                    var link = xhr.getResponseHeader('Link');
                    if (link != null && link.match('rel="describedby"')) {
                        var str = link.match(/<[^>]+>/)[0];
                        window.location = str.slice(1, str.length - 1);
                    } else if (loc != null) {
                        window.location = loc;
                    } else {
                        window.location.reload();
                    }
                } else {
                    ajaxErrorHandler(xhr, "", "Error creating binary");
                }
            }
        };

        if (id == "") {
            xhr.open( "POST", newURI );
        } else {
            xhr.open( "PUT", newURI );
        }

        xhr.setRequestHeader("Content-type", update_file.type || "application/octet-stream");
        reader.onload = function(e) {
            var result = e.target.result;
            var data = new Uint8Array(result.length);
            for (var i = 0; i < result.length; i++) {
                data[i] = (result.charCodeAt(i) & 0xff);
            }
            xhr.send(data.buffer);
        };
        reader.readAsBinaryString(update_file);
    } else {
      $.ajax({
        type: id == "" ? "POST" : "PUT",
        url: postURI,
        success: function(data, textStatus, request) { window.location = request.getResponseHeader('Location') || postURI }
      }).fail( ajaxErrorHandler);
    }

    return false;
}

function sendImport() {
    var mixin = $("#import_format").val();
    var postURI = $('#main').attr('resource') + "/fcr:import?format=" + mixin;

    var update_file = document.getElementById("import_file").files[0];
    var reader = new FileReader();
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {

            if (xhr.status == 201) {
                window.location.reload();
            } else {
                ajaxErrorHandler(xhr, "", "Error importing content");
            }
        }
    }

    xhr.open( "POST", postURI );

    xhr.setRequestHeader("Content-type", update_file.type || "application/octet-stream");
    reader.onload = function(e) {
        var result = e.target.result;
        var data = new Uint8Array(result.length);
        for (var i = 0; i < result.length; i++) {
            data[i] = (result.charCodeAt(i) & 0xff);
        }
        xhr.send(data.buffer);
    };
    reader.readAsBinaryString(update_file);

    return false;

}

$(function() {
    $('#new_mixin').change(function() {
        if($('#new_mixin').val() == "binary") {
            $('#binary_payload_container').show();
        } else {
            $('#binary_payload_container').hide();
        }
    });

    $('#btn_action_create').click(function (e) {
  	    if ($("#new_mixin").val() == 'binary') {
  		    var file = $("#binary_payload").val();
  		    if (file.length == 0) {
  			    $('#binary_payload').click();
  			    return false;
  		    }
  	    }
  	   $('#action_create').submit(addChild);
    });

    $('#action_sparql_update').submit(sendSparqlUpdate);
    $('#action_register_namespace').submit(registerNamespace);
    $('#action_delete').submit(deleteItem);
    $('#action_create_transaction').submit(submitAndFollowLocation);
    $('#action_rollback_transaction').submit(submitAndRedirectToBase);
    $('#action_commit_transaction').submit(submitAndRedirectToBase);
    $('#action_import').submit(sendImport);
    $('#action_cnd_update').submit(sendCndUpdate);
    $('#action_sparql_select').submit(sendSparqlQuery);
    $('#action_revert').submit(patchAndReload);
    $('#action_remove_version').submit(removeVersion);

    var ldpContains = $('#childList li').length;
    $('#badge').text(ldpContains);
    $('a[property][href*="' + location.host + '"],#childList a,.breadcrumb a').click(checkIfNonRdfResource);

});

function checkIfNonRdfResource(e) {

    var url = this.href;

    $.ajax({type: "HEAD", url: url}).success(function(data, status, xhr) {
        if (status != "success" || xhr.getResponseHeader("Link") == null) {
            location.href = url;
            return;
        }

        var headers = xhr.getResponseHeader("Link").split(", ");

        var types = $.grep(headers, function(h) {
            return h.match(/rel="type"/);
        });

        if ($.grep(types, function(h) { return h.match(/NonRDFSource/)}).length > 0 ){
            var description = $.grep(headers, function(h) { return h.match(/rel="describedby"/)});

            if (description.length > 0) {
                location.href = description[0].substr(1, description[0].indexOf(">") - 1);
                return;
            }
        }

        location.href = url;
    });
    e.preventDefault();
    return false;
}

function submitAndFollowLocation() {
    var $form = $(this);

    var postURI = $form.attr('action');

    $.post(postURI, "some-data-to-make-chrome-happy", function(data, textStatus, request) {
        window.location = request.getResponseHeader('Location');
    }).fail( ajaxErrorHandler);

    return false;
}

function removeVersion() {
    var $form = $(this);

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            if (xhr.status == 204 ) {
                window.location = $form.attr('data-redirect-after-submit');
            } else {
                ajaxErrorHandler(xhr, "", "Error removing version");
            }
        }
    }
    xhr.open( "DELETE", $form.attr('action') );
    xhr.send(null);

    return false;
}
function patchAndReload() {
    var $form = $(this);
    var patchURI = $form.attr('action');

    $.ajax({url: patchURI, type: "PATCH", data: "", success: function(data, textStatus, request) {
        window.location = $form.attr('data-redirect-after-submit');
    }, error: ajaxErrorHandler});

    return false;
}

function submitAndRedirectToBase() {
    var $form = $(this);

    var postURI = $form.attr('action');

    $.post(postURI, "some-data-to-make-chrome-happy", function(data, textStatus, request) {
        window.location = $form.attr('data-redirect-after-submit');
    }).fail( ajaxErrorHandler);

    return false;
}

function registerNamespace() {
    var postURI = $('#main').attr('resource');

    var query = "INSERT { <" + $('#namespace_uri').val() + "> <http://purl.org/vocab/vann/preferredNamespacePrefix> \"" + $('#namespace_prefix').val() + "\"} WHERE {}";

    $.ajax({url: postURI, type: "POST", contentType: "application/sparql-update", data: query, success: function(data, textStatus, request) {
        window.location.reload(true);
    }}).fail( ajaxErrorHandler);

    return false;
}

function sendSparqlQuery() {
    var $form = $(this);
    var postURI = $form.attr('action');

    $.ajax({url: postURI, type: "POST", contentType: "application/sparql-query", data: $("#sparql_select_query").val(), success: function(data, textStatus, request) {

        $('#errorLabel').text("RESULT");
        $('#errorText').html("

");
        $('#errorText pre').text(request.responseText);
        $('#errorModal').modal('show');
    }, error: ajaxErrorHandler});

    return false;
}

function sendSparqlUpdate() {
    var postURI = $('#main').attr('resource');

    $.ajax({url: postURI, type: "PATCH", contentType: "application/sparql-update", data: $("#sparql_update_query").val(), success: function(data, textStatus, request) {
        window.location.reload(true);
    }, error: ajaxErrorHandler});

    return false;
}

function sendCndUpdate() {
    var postURI = $('#main').attr('resource');

    $.ajax({url: postURI, type: "POST", contentType: "text/cnd", data: $("#cnd_update_query").val(), success: function(data, textStatus, request) {
        window.location.reload(true);
    }, error: ajaxErrorHandler});

    return false;
}

function deleteItem()
{
    var uri = $('#main').attr('resource');
    var arr = uri.toString().split("/");
    arr.pop();
    var newURI = arr.join("/");

    $.ajax({url: uri, type: "DELETE", success: function() {
        window.location = newURI;
    }}).fail( ajaxErrorHandler);
    return false;
}

function updateFile()
{
    var update_file = document.getElementById("update_file").files[0];
    var url = window.location.href.replace("fcr:metadata", "");
    var reader = new FileReader();
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {

            if (xhr.status == 204 || xhr.status == 201) {
                window.location.reload(true);
            } else {
                ajaxErrorHandler(xhr, "", "Error updating binary");
            }
        }
    }
    xhr.open( "PUT", url );
    xhr.setRequestHeader("Content-type", update_file.type);
    reader.onload = function(e) {
        var result = e.target.result;
        var data = new Uint8Array(result.length);
        for (var i = 0; i < result.length; i++) {
            data[i] = (result.charCodeAt(i) & 0xff);
        }
        xhr.send(data.buffer);
    };
    reader.readAsBinaryString(update_file);
}

function updateAccessRoles()
{
    var update_json = document.getElementById("rbacl_json").value;
    var url = window.location + "/fcr:accessroles";
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            if (xhr.status == 204 || xhr.status == 201) {
                window.location.reload(true);
            } else {
                ajaxErrorHandler(xhr, "", "Error");
            }
        }
    }
    xhr.open( "POST", url );
    xhr.setRequestHeader("Content-type", "application/json");
    xhr.send(update_json);
}

function ajaxErrorHandler(xhr, textStatus, errorThrown) {
    $('#errorLabel').text(errorThrown);
    $('#errorText').text(xhr.responseText);
    $('#errorModal').modal('show');

}
<commit_msg>HTML UI: Ensure resource creation URIs have no double '/' chars<commit_after>$(document).ready(function() {
  $("#new_id").attr("placeholder", "(auto-generated identifier)");
});

function removeTrailingSlash(origURI) {
    var trimmed = origURI;
    while (trimmed.lastIndexOf('/') == trimmed.length - 1) {
        trimmed = trimmed.substr(0, trimmed.length - 1);
    }
    return trimmed;
}

function addChild()
{
    var id = $("#new_id").val().trim();

    var mixin = $("#new_mixin").val();

    var newURI = removeTrailingSlash($('#main').attr('resource')) + (!id ? "" : "/" + id);

    var postURI = newURI;

    if (mixin == "binary") {
        var update_file = document.getElementById("binary_payload").files[0];
        var reader = new FileReader();
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
                if (xhr.status == 201) {
                    var loc = xhr.getResponseHeader('Location');
                    var link = xhr.getResponseHeader('Link');
                    if (link != null && link.match('rel="describedby"')) {
                        var str = link.match(/<[^>]+>/)[0];
                        window.location = str.slice(1, str.length - 1);
                    } else if (loc != null) {
                        window.location = loc;
                    } else {
                        window.location.reload();
                    }
                } else {
                    ajaxErrorHandler(xhr, "", "Error creating binary");
                }
            }
        };

        if (id == "") {
            xhr.open( "POST", newURI );
        } else {
            xhr.open( "PUT", newURI );
        }

        xhr.setRequestHeader("Content-type", update_file.type || "application/octet-stream");
        reader.onload = function(e) {
            var result = e.target.result;
            var data = new Uint8Array(result.length);
            for (var i = 0; i < result.length; i++) {
                data[i] = (result.charCodeAt(i) & 0xff);
            }
            xhr.send(data.buffer);
        };
        reader.readAsBinaryString(update_file);
    } else {
      $.ajax({
        type: id == "" ? "POST" : "PUT",
        url: postURI,
        success: function(data, textStatus, request) { window.location = request.getResponseHeader('Location') || postURI }
      }).fail( ajaxErrorHandler);
    }

    return false;
}

function sendImport() {
    var mixin = $("#import_format").val();
    var postURI = $('#main').attr('resource') + "/fcr:import?format=" + mixin;

    var update_file = document.getElementById("import_file").files[0];
    var reader = new FileReader();
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {

            if (xhr.status == 201) {
                window.location.reload();
            } else {
                ajaxErrorHandler(xhr, "", "Error importing content");
            }
        }
    }

    xhr.open( "POST", postURI );

    xhr.setRequestHeader("Content-type", update_file.type || "application/octet-stream");
    reader.onload = function(e) {
        var result = e.target.result;
        var data = new Uint8Array(result.length);
        for (var i = 0; i < result.length; i++) {
            data[i] = (result.charCodeAt(i) & 0xff);
        }
        xhr.send(data.buffer);
    };
    reader.readAsBinaryString(update_file);

    return false;

}

$(function() {
    $('#new_mixin').change(function() {
        if($('#new_mixin').val() == "binary") {
            $('#binary_payload_container').show();
        } else {
            $('#binary_payload_container').hide();
        }
    });

    $('#btn_action_create').click(function (e) {
  	    if ($("#new_mixin").val() == 'binary') {
  		    var file = $("#binary_payload").val();
  		    if (file.length == 0) {
  			    $('#binary_payload').click();
  			    return false;
  		    }
  	    }
  	   $('#action_create').submit(addChild);
    });

    $('#action_sparql_update').submit(sendSparqlUpdate);
    $('#action_register_namespace').submit(registerNamespace);
    $('#action_delete').submit(deleteItem);
    $('#action_create_transaction').submit(submitAndFollowLocation);
    $('#action_rollback_transaction').submit(submitAndRedirectToBase);
    $('#action_commit_transaction').submit(submitAndRedirectToBase);
    $('#action_import').submit(sendImport);
    $('#action_cnd_update').submit(sendCndUpdate);
    $('#action_sparql_select').submit(sendSparqlQuery);
    $('#action_revert').submit(patchAndReload);
    $('#action_remove_version').submit(removeVersion);

    var ldpContains = $('#childList li').length;
    $('#badge').text(ldpContains);
    $('a[property][href*="' + location.host + '"],#childList a,.breadcrumb a').click(checkIfNonRdfResource);

});

function checkIfNonRdfResource(e) {

    var url = this.href;

    $.ajax({type: "HEAD", url: url}).success(function(data, status, xhr) {
        if (status != "success" || xhr.getResponseHeader("Link") == null) {
            location.href = url;
            return;
        }

        var headers = xhr.getResponseHeader("Link").split(", ");

        var types = $.grep(headers, function(h) {
            return h.match(/rel="type"/);
        });

        if ($.grep(types, function(h) { return h.match(/NonRDFSource/)}).length > 0 ){
            var description = $.grep(headers, function(h) { return h.match(/rel="describedby"/)});

            if (description.length > 0) {
                location.href = description[0].substr(1, description[0].indexOf(">") - 1);
                return;
            }
        }

        location.href = url;
    });
    e.preventDefault();
    return false;
}

function submitAndFollowLocation() {
    var $form = $(this);

    var postURI = $form.attr('action');

    $.post(postURI, "some-data-to-make-chrome-happy", function(data, textStatus, request) {
        window.location = request.getResponseHeader('Location');
    }).fail( ajaxErrorHandler);

    return false;
}

function removeVersion() {
    var $form = $(this);

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            if (xhr.status == 204 ) {
                window.location = $form.attr('data-redirect-after-submit');
            } else {
                ajaxErrorHandler(xhr, "", "Error removing version");
            }
        }
    }
    xhr.open( "DELETE", $form.attr('action') );
    xhr.send(null);

    return false;
}
function patchAndReload() {
    var $form = $(this);
    var patchURI = $form.attr('action');

    $.ajax({url: patchURI, type: "PATCH", data: "", success: function(data, textStatus, request) {
        window.location = $form.attr('data-redirect-after-submit');
    }, error: ajaxErrorHandler});

    return false;
}

function submitAndRedirectToBase() {
    var $form = $(this);

    var postURI = $form.attr('action');

    $.post(postURI, "some-data-to-make-chrome-happy", function(data, textStatus, request) {
        window.location = $form.attr('data-redirect-after-submit');
    }).fail( ajaxErrorHandler);

    return false;
}

function registerNamespace() {
    var postURI = $('#main').attr('resource');

    var query = "INSERT { <" + $('#namespace_uri').val() + "> <http://purl.org/vocab/vann/preferredNamespacePrefix> \"" + $('#namespace_prefix').val() + "\"} WHERE {}";

    $.ajax({url: postURI, type: "POST", contentType: "application/sparql-update", data: query, success: function(data, textStatus, request) {
        window.location.reload(true);
    }}).fail( ajaxErrorHandler);

    return false;
}

function sendSparqlQuery() {
    var $form = $(this);
    var postURI = $form.attr('action');

    $.ajax({url: postURI, type: "POST", contentType: "application/sparql-query", data: $("#sparql_select_query").val(), success: function(data, textStatus, request) {

        $('#errorLabel').text("RESULT");
        $('#errorText').html("

");
        $('#errorText pre').text(request.responseText);
        $('#errorModal').modal('show');
    }, error: ajaxErrorHandler});

    return false;
}

function sendSparqlUpdate() {
    var postURI = $('#main').attr('resource');

    $.ajax({url: postURI, type: "PATCH", contentType: "application/sparql-update", data: $("#sparql_update_query").val(), success: function(data, textStatus, request) {
        window.location.reload(true);
    }, error: ajaxErrorHandler});

    return false;
}

function sendCndUpdate() {
    var postURI = $('#main').attr('resource');

    $.ajax({url: postURI, type: "POST", contentType: "text/cnd", data: $("#cnd_update_query").val(), success: function(data, textStatus, request) {
        window.location.reload(true);
    }, error: ajaxErrorHandler});

    return false;
}

function deleteItem()
{
    var uri = $('#main').attr('resource');
    var arr = uri.toString().split("/");
    arr.pop();
    var newURI = arr.join("/");

    $.ajax({url: uri, type: "DELETE", success: function() {
        window.location = newURI;
    }}).fail( ajaxErrorHandler);
    return false;
}

function updateFile()
{
    var update_file = document.getElementById("update_file").files[0];
    var url = window.location.href.replace("fcr:metadata", "");
    var reader = new FileReader();
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {

            if (xhr.status == 204 || xhr.status == 201) {
                window.location.reload(true);
            } else {
                ajaxErrorHandler(xhr, "", "Error updating binary");
            }
        }
    }
    xhr.open( "PUT", url );
    xhr.setRequestHeader("Content-type", update_file.type);
    reader.onload = function(e) {
        var result = e.target.result;
        var data = new Uint8Array(result.length);
        for (var i = 0; i < result.length; i++) {
            data[i] = (result.charCodeAt(i) & 0xff);
        }
        xhr.send(data.buffer);
    };
    reader.readAsBinaryString(update_file);
}

function updateAccessRoles()
{
    var update_json = document.getElementById("rbacl_json").value;
    var url = window.location + "/fcr:accessroles";
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            if (xhr.status == 204 || xhr.status == 201) {
                window.location.reload(true);
            } else {
                ajaxErrorHandler(xhr, "", "Error");
            }
        }
    }
    xhr.open( "POST", url );
    xhr.setRequestHeader("Content-type", "application/json");
    xhr.send(update_json);
}

function ajaxErrorHandler(xhr, textStatus, errorThrown) {
    $('#errorLabel').text(errorThrown);
    $('#errorText').text(xhr.responseText);
    $('#errorModal').modal('show');

}
<|endoftext|>


<commit_before>import d3 from 'd3';

export default class ForceDirectedGraphRenderer {
  renderSvg(containerElement, users) {
    const width = 1000;
    const height = 700;
    const radius = 15;

    const color = d3.scale.category20();

    const vis = d3
      .select(containerElement)
      .append('svg')
      .attr('width', width)
      .attr('height', height);

    const links = [];

    users.forEach((user, userIndex) => {
      if (user.manager) {
        const manager = users.find(x => x.id === user.manager.id);

        if (manager) {
          const managerIndex = users.findIndex(x => x.id === manager.id);

          links.push({
            source: userIndex,
            target: managerIndex,
            value: 1
          });
        }
        else {
          console.log(`Missing manager for ${user.displayName} (${user.id}) in data.`); // eslint-disable-line no-console
        }
      }
    });

    const link = vis.selectAll('line')
      .data(links)
      .enter().append('line');

    const node = vis.selectAll('.node')
      .data(users)
      .enter().append('g')
      .attr('class', 'node')
      .on('mouseover', d => this.onNodeMouseOver(d));

    node.append('circle')
      .attr('r', d => {
        if (!d.manager) {
          return radius * 1.6;
        }

        const atLeastOneDirectReport = users.some(x => x.manager && x.manager.id === d.id);

        const manager = users.find(x => x.id === d.manager.id);
        if (!manager.manager && atLeastOneDirectReport) {
          return radius * 1.5;
        }

        if (atLeastOneDirectReport) {
          return radius * 1.2;
        }

        return radius;
      })
      .style('fill', d => color(d.department));

    node.append('text')
      .attr('text-anchor', 'middle')
      .text(x => this.getNameAbbreviation(x.displayName));

    const force = d3.layout.force()
      .nodes(users)
      .links(links)
      .size([width, height])
      .linkDistance(30)
      .charge(-400)
      .gravity(0.3)
      .start();

    node.call(force.drag);

    force.on('tick', () => {
      link.attr('x1', d => d.source.x)
          .attr('y1', d => d.source.y)
          .attr('x2', d => d.target.x)
          .attr('y2', d => d.target.y);

      d3.selectAll('circle')
          .attr('cx', d => Math.max(radius, Math.min(width - radius, d.x)))
          .attr('cy', d => Math.max(radius, Math.min(height - radius, d.y)));

      d3.selectAll('text')
        // TODO: Fix labels at svg edges
        .attr('x', d => d.x)
        .attr('y', d => d.y + 5);
    });
  }

  getNameAbbreviation(displayName) {
    const split = displayName.split(' ');

    if (split.length > 0) {
      const givenName = split[0];
      const surName = split[1];

      const firstLetter = givenName ? givenName[0] : '?';
      const secondLetter = surName ? surName[0] : '';

      return `${firstLetter}${secondLetter}`;
    }
  }

  onNodeMouseOver(d) {
    this._setElementIdText('js-information-name', d.displayName);
    this._setElementIdText('js-information-job-title', d.jobTitle);
    this._setElementIdText('js-information-department', d.department);
    this._setElementIdText('js-information-telephone-number', d.telephoneNumber ? `Phone: ${d.telephoneNumber}` : '');
    this._setElementIdText('js-information-mobile-number', d.mobileNumber ?  `Mobile: ${d.mobileNumber}` : '');

    const emailLink = document.getElementById('js-information-email-link');
    emailLink.innerText = d.email;
    emailLink.href = `mailto:${d.email}`;
  }

  _setElementIdText(id, text) {
    document.getElementById(id).innerText = text;
  }
}
<commit_msg>eslint fixes<commit_after>/* eslint-disable no-magic-numbers */
import d3 from 'd3';

export default class ForceDirectedGraphRenderer {
  renderSvg(containerElement, users) {
    const width = 1000;
    const height = 700;
    const radius = 15;

    const color = d3.scale.category20();

    const vis = d3
      .select(containerElement)
      .append('svg')
      .attr('width', width)
      .attr('height', height);

    const links = [];

    users.forEach((user, userIndex) => {
      if (user.manager) {
        const manager = users.find(x => x.id === user.manager.id);

        if (manager) {
          const managerIndex = users.findIndex(x => x.id === manager.id);

          links.push({
            source: userIndex,
            target: managerIndex,
            value: 1
          });
        } else {
          // eslint-disable-next-line no-console
          console.log(`Missing manager for ${user.displayName} (${user.id}) in data.`);
        }
      }
    });

    const link = vis.selectAll('line')
      .data(links)
      .enter().append('line');

    const node = vis.selectAll('.node')
      .data(users)
      .enter().append('g')
      .attr('class', 'node')
      .on('mouseover', d => this.onNodeMouseOver(d));

    node.append('circle')
      .attr('r', d => {
        if (!d.manager) {
          return radius * 1.6;
        }

        const atLeastOneDirectReport = users.some(x => x.manager && x.manager.id === d.id);

        const manager = users.find(x => x.id === d.manager.id);

        if (!manager.manager && atLeastOneDirectReport) {
          return radius * 1.5;
        }

        if (atLeastOneDirectReport) {
          return radius * 1.2;
        }

        return radius;
      })
      .style('fill', d => color(d.department));

    node.append('text')
      .attr('text-anchor', 'middle')
      .text(x => this.getNameAbbreviation(x.displayName));

    const force = d3.layout.force()
      .nodes(users)
      .links(links)
      .size([width, height])
      .linkDistance(30)
      .charge(-400)
      .gravity(0.3)
      .start();

    node.call(force.drag);

    force.on('tick', () => {
      link.attr('x1', d => d.source.x)
          .attr('y1', d => d.source.y)
          .attr('x2', d => d.target.x)
          .attr('y2', d => d.target.y);

      d3.selectAll('circle')
          .attr('cx', d => Math.max(radius, Math.min(width - radius, d.x)))
          .attr('cy', d => Math.max(radius, Math.min(height - radius, d.y)));

      d3.selectAll('text')
        // TODO: Fix labels at svg edges
        .attr('x', d => d.x)
        .attr('y', d => d.y + 5);
    });
  }

  getNameAbbreviation(displayName) {
    const split = displayName.split(' ');

    if (split.length > 0) {
      const givenName = split[0];
      const surName = split[1];

      const firstLetter = givenName ? givenName[0] : '?';
      const secondLetter = surName ? surName[0] : '';

      return `${firstLetter}${secondLetter}`;
    }
  }

  onNodeMouseOver(d) {
    this._setElementIdText('js-information-name', d.displayName);
    this._setElementIdText('js-information-job-title', d.jobTitle);
    this._setElementIdText('js-information-department', d.department);
    this._setElementIdText('js-information-telephone-number', d.telephoneNumber ? `Phone: ${d.telephoneNumber}` : '');
    this._setElementIdText('js-information-mobile-number', d.mobileNumber ? `Mobile: ${d.mobileNumber}` : '');

    const emailLink = document.getElementById('js-information-email-link');

    emailLink.innerText = d.email;
    emailLink.href = `mailto:${d.email}`;
  }

  _setElementIdText(id, text) {
    document.getElementById(id).innerText = text;
  }
}
<|endoftext|>


<commit_before>var inherit = require('../utils/inherit'),
    EventEmitter = require('../utils/EventEmitter');

/**
 * The base Input object, holds common functions and properties between input types
 *
 * @class Input
 * @extends Object
 * @uses EventEmitter
 * @constructor
 * @param view {DOMElement} The DOMElement to bind input events to
 */
var InputType = module.exports = function(view) {
    EventEmitter.call(this);

    /**
     * For backwards compatibility
     *
     * @method bind
     * @deprecated use on
     */
    this.bind = this.on;

    /**
     * The dom element to bind events to
     *
     * @property view
     * @type Game
     */
    this.view = view;
};

inherit(InputType, Object, {
    /**
     * Prevents the default action of an event
     *
     * @method preventDefault
     * @param event {DOMEvent} The event to prevent default actions for
     */
    preventDefault: function(e) {
        if(e.preventDefault) e.preventDefault();
        else e.returnValue = false;

        return false;
    },
    /**
     * Prevents an event from bubbling up the DOM.
     *
     * @method stopPropogation
     * @param event {DOMEvent} The event to prevent bubbling for
     */
    stopPropogation: function(e) {
        if(e.stopPropagation) e.stopPropagation();
        else e.cancelBubble = true;
    }
});
<commit_msg>don't need that anymore<commit_after>var inherit = require('../utils/inherit'),
    EventEmitter = require('../utils/EventEmitter');

/**
 * The base Input object, holds common functions and properties between input types
 *
 * @class Input
 * @extends Object
 * @uses EventEmitter
 * @constructor
 * @param game {Game} The game instance
 */
var InputType = module.exports = function(game) {
    EventEmitter.call(this);

    /**
     * The game instance this input belongs to
     *
     * @property game
     * @type Game
     */
    this.game = game;
};

inherit(InputType, Object, {
});
<|endoftext|>


<commit_before>const assert = require('assert')
const homogenize = require('./homogenize')

module.exports = function (comparator, collections) {
    return homogenize(comparator, collections, 1, (iterators, consume) => {
        const got = []
        do {
            const set = iterators.map(iterator => iterator.inner[iterator.index++])
            assert(set.slice(1).every((entry, index) => comparator(set[index].key, set[index + 1].key) == 0))
            const items = []
            got.push({
                key: set[0].key,
                value: set[0].value,
                items: items.concat.apply(items, set.map(entry => entry.items))
                            .sort((left, right) => comparator(left.key, right.key))
            })
        } while (iterators.every(iterator => iterator.inner.length != iterator.index))
        consume(got)
    })
}
<commit_msg>Remove outer key assertion from map.<commit_after>const assert = require('assert')
const homogenize = require('./homogenize')

module.exports = function (comparator, collections) {
    return homogenize(comparator, collections, 1, (iterators, consume) => {
        const got = []
        do {
            const set = iterators.map(iterator => iterator.inner[iterator.index++])
            const items = []
            got.push({
                key: set[0].key,
                value: set[0].value,
                items: items.concat.apply(items, set.map(entry => entry.items))
                            .sort((left, right) => comparator(left.key, right.key))
            })
        } while (iterators.every(iterator => iterator.inner.length != iterator.index))
        consume(got)
    })
}
<|endoftext|>


<commit_before>function displaySelected() {
  var linktext = document.getElementById("shselected").innerHTML;
  var seldiv = document.getElementById("selected");
  var sampdiv = document.getElementById("availstudies");
  var buttondiv = document.getElementById("seperator");
  if(seldiv.style.display == "none") {
    sampdiv.style.bottom = "30%";
    sampdiv.style.height='60%';
    buttondiv.style.bottom = "25%";
    seldiv.style.height = "25%";
    seldiv.style.display = "";
    linktext = "Hide selected samples";
  }
  else {
    sampdiv.style.bottom = "";
    sampdiv.style.height='90%';
    buttondiv.style.bottom = "0px";
    seldiv.style.height = "0px";
    seldiv.style.display = "none";
    linktext = "Show selected samples";
  }
}

function select_category(category, study) {
  if(study != '') {
    $('.'+study+'.'+category).each(function() {this.checked = true;});
  }
  else {
    $('.'+category).each(function() {this.checked = true;});
  }
}

function select_deselect(study, select) {
  if(select == true) {
    $('.'+study).each(function() {this.checked = true;});
  }
  else {
    $('.'+study).each(function() {this.checked = false;});
  }
}

function enable_study_datatype(id) {
  document.getElementById(id).disabled=false;
}

function pre_submit(action) {
  document.getElementById('action').value = action;
  if(action == 'continue') {document.getElementById('results-form').action = '/analysis/3'}
}
<commit_msg>change show/hide text<commit_after>function displaySelected() {
  var linktext = document.getElementById("shselected");
  var seldiv = document.getElementById("selected");
  var sampdiv = document.getElementById("availstudies");
  var buttondiv = document.getElementById("seperator");
  if(seldiv.style.display == "none") {
    sampdiv.style.bottom = "30%";
    sampdiv.style.height='60%';
    buttondiv.style.bottom = "25%";
    seldiv.style.height = "25%";
    seldiv.style.display = "";
    linktext.innerHTML = "Hide selected samples";
  }
  else {
    sampdiv.style.bottom = "";
    sampdiv.style.height='90%';
    buttondiv.style.bottom = "0px";
    seldiv.style.height = "0px";
    seldiv.style.display = "none";
    linktext.innerHTML = "Show selected samples";
  }
}

function select_category(category, study) {
  if(study != '') {
    $('.'+study+'.'+category).each(function() {this.checked = true;});
  }
  else {
    $('.'+category).each(function() {this.checked = true;});
  }
}

function select_deselect(study, select) {
  if(select == true) {
    $('.'+study).each(function() {this.checked = true;});
  }
  else {
    $('.'+study).each(function() {this.checked = false;});
  }
}

function enable_study_datatype(id) {
  document.getElementById(id).disabled=false;
}

function pre_submit(action) {
  document.getElementById('action').value = action;
  if(action == 'continue') {document.getElementById('results-form').action = '/analysis/3'}
}
<|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 => {
            if (error.response.status === 400 && error.response.data === 'Invalid univesity email') {
                this.setState({
                    isSignupButtonLoading: false,
                    invalidEmail: true
                });
                this.signupEmail.focus();
            }
            else {
                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>Handle all errors gently in SignupForm<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>/* global RTCIceCandidate, RTCSessionDescription, RTCPeerConnection, EventEmitter */
'use strict';

/**
 * @ngdoc service
 * @name publicApp.Room
 * @description
 * # Room
 * Factory in the publicApp.
 */
angular.module('publicApp')
  .factory('Room', function ($rootScope, $q, Io, config) {

    var iceConfig = {
                  iceServers: [
                    {url:'stun.l.google.com:19302'},
                  ],
                },
        peerConnections = {},
        currentId, roomId,
        stream;

    function getPeerConnection(id) {
      if (peerConnections[id]) {
        return peerConnections[id];
      }
      var pc = new RTCPeerConnection(iceConfig);
      peerConnections[id] = pc;
      pc.addStream(stream);
      pc.onicecandidate = function (evnt) {
        socket.emit('msg', { by: currentId, to: id, ice: evnt.candidate, type: 'ice' });
      };
      pc.onaddstream = function (evnt) {
        console.log('Received new stream');
        api.trigger('peer.stream', [{
          id: id,
          stream: evnt.stream
        }]);
        if (!$rootScope.$$digest) {
          $rootScope.$apply();
        }
      };
      return pc;
    }

    function makeOffer(id) {
      var pc = getPeerConnection(id);
      pc.createOffer(function (sdp) {
        pc.setLocalDescription(sdp);
        console.log('Creating an offer for', id);
        socket.emit('msg', { by: currentId, to: id, sdp: sdp, type: 'sdp-offer' });
      }, function (e) {
        console.log(e);
      },
      { mandatory: { OfferToReceiveVideo: true, OfferToReceiveAudio: true }});
    }

    function handleMessage(data) {
      var pc = getPeerConnection(data.by);
      switch (data.type) {
        case 'sdp-offer':
          pc.setRemoteDescription(new RTCSessionDescription(data.sdp), function () {
            console.log('Setting remote description by offer');
            pc.createAnswer(function (sdp) {
              pc.setLocalDescription(sdp);
              socket.emit('msg', { by: currentId, to: data.by, sdp: sdp, type: 'sdp-answer' });
            });
          });
          break;
        case 'sdp-answer':
          pc.setRemoteDescription(new RTCSessionDescription(data.sdp), function () {
            console.log('Setting remote description by answer');
          }, function (e) {
            console.error(e);
          });
          break;
        case 'ice':
          if (data.ice) {
            console.log('Adding ice candidates');
            pc.addIceCandidate(new RTCIceCandidate(data.ice));
          }
          break;
      }
    }

    var socket = Io.connect(config.SIGNALIG_SERVER_URL),
        connected = false;

    function addHandlers(socket) {
      socket.on('peer.connected', function (params) {
        makeOffer(params.id);
      });
      socket.on('peer.disconnected', function (data) {
        api.trigger('peer.disconnected', [data]);
        if (!$rootScope.$$digest) {
          $rootScope.$apply();
        }
      });
      socket.on('msg', function (data) {
        handleMessage(data);
      });
    }

    var api = {
      joinRoom: function (r) {
        if (!connected) {
          socket.emit('init', { room: r }, function (roomid, id) {
            currentId = id;
            roomId = roomid;
          });
          connected = true;
        }
      },
      createRoom: function () {
        var d = $q.defer();
        socket.emit('init', null, function (roomid, id) {
          d.resolve(roomid);
          roomId = roomid;
          currentId = id;
          connected = true;
        });
        return d.promise;
      },
      init: function (s) {
        stream = s;
      }
    };
    EventEmitter.call(api);
    Object.setPrototypeOf(api, EventEmitter.prototype);

    addHandlers(socket);
    return api;
  });
<commit_msg>fixed url for google stun<commit_after>/* global RTCIceCandidate, RTCSessionDescription, RTCPeerConnection, EventEmitter */
'use strict';

/**
 * @ngdoc service
 * @name publicApp.Room
 * @description
 * # Room
 * Factory in the publicApp.
 */
angular.module('publicApp')
  .factory('Room', function ($rootScope, $q, Io, config) {

    var iceConfig = {
                  iceServers: [
                    {url:'stun:stun.l.google.com:19302'},
                  ],
                },
        peerConnections = {},
        currentId, roomId,
        stream;

    function getPeerConnection(id) {
      if (peerConnections[id]) {
        return peerConnections[id];
      }
      var pc = new RTCPeerConnection(iceConfig);
      peerConnections[id] = pc;
      pc.addStream(stream);
      pc.onicecandidate = function (evnt) {
        socket.emit('msg', { by: currentId, to: id, ice: evnt.candidate, type: 'ice' });
      };
      pc.onaddstream = function (evnt) {
        console.log('Received new stream');
        api.trigger('peer.stream', [{
          id: id,
          stream: evnt.stream
        }]);
        if (!$rootScope.$$digest) {
          $rootScope.$apply();
        }
      };
      return pc;
    }

    function makeOffer(id) {
      var pc = getPeerConnection(id);
      pc.createOffer(function (sdp) {
        pc.setLocalDescription(sdp);
        console.log('Creating an offer for', id);
        socket.emit('msg', { by: currentId, to: id, sdp: sdp, type: 'sdp-offer' });
      }, function (e) {
        console.log(e);
      },
      { mandatory: { OfferToReceiveVideo: true, OfferToReceiveAudio: true }});
    }

    function handleMessage(data) {
      var pc = getPeerConnection(data.by);
      switch (data.type) {
        case 'sdp-offer':
          pc.setRemoteDescription(new RTCSessionDescription(data.sdp), function () {
            console.log('Setting remote description by offer');
            pc.createAnswer(function (sdp) {
              pc.setLocalDescription(sdp);
              socket.emit('msg', { by: currentId, to: data.by, sdp: sdp, type: 'sdp-answer' });
            });
          });
          break;
        case 'sdp-answer':
          pc.setRemoteDescription(new RTCSessionDescription(data.sdp), function () {
            console.log('Setting remote description by answer');
          }, function (e) {
            console.error(e);
          });
          break;
        case 'ice':
          if (data.ice) {
            console.log('Adding ice candidates');
            pc.addIceCandidate(new RTCIceCandidate(data.ice));
          }
          break;
      }
    }

    var socket = Io.connect(config.SIGNALIG_SERVER_URL),
        connected = false;

    function addHandlers(socket) {
      socket.on('peer.connected', function (params) {
        makeOffer(params.id);
      });
      socket.on('peer.disconnected', function (data) {
        api.trigger('peer.disconnected', [data]);
        if (!$rootScope.$$digest) {
          $rootScope.$apply();
        }
      });
      socket.on('msg', function (data) {
        handleMessage(data);
      });
    }

    var api = {
      joinRoom: function (r) {
        if (!connected) {
          socket.emit('init', { room: r }, function (roomid, id) {
            currentId = id;
            roomId = roomid;
          });
          connected = true;
        }
      },
      createRoom: function () {
        var d = $q.defer();
        socket.emit('init', null, function (roomid, id) {
          d.resolve(roomid);
          roomId = roomid;
          currentId = id;
          connected = true;
        });
        return d.promise;
      },
      init: function (s) {
        stream = s;
      }
    };
    EventEmitter.call(api);
    Object.setPrototypeOf(api, EventEmitter.prototype);

    addHandlers(socket);
    return api;
  });
<|endoftext|>


<commit_before>/*
Name:           geoip2ws
Description:    Maxmind GeoIP2 Web Services for Node.js
Source & docs:  https://github.com/fvdm/nodejs-geoip2ws
Feedback:       https://github.com/fvdm/nodejs-geoip2ws/issues
License:        Public Domain / Unlicense

This product includes GeoLite2 data created by MaxMind, available from
<http://www.maxmind.com>.
*/

var https = require ('https');
var net = require ('net');

// setup
var app = {
  userId: null,
  licenseKey: null,
  service: 'city',
  requestTimeout: 5000
};

module.exports = function (userId, licenseKey, service, requestTimeout) {
  if (userId === undefined || licenseKey === undefined) {
    return new Error ('no userId or licenseKey');
  }

  app.userId = userId;
  app.licenseKey = licenseKey;

  if (typeof service === 'number') {
    app.requestTimeout = service;
  } else {
    app.service = service || app.service;
    app.requestTimeout = requestTimeout || app.requestTimeout;
  }

  return function (service, ip, callback) {
    var serviceRegexp = new RegExp (/^(country|city|insights)$/);

    // service is optional
    if (typeof service === 'string' && ! service.match (serviceRegexp) ) {
      callback = ip;
      ip = service;
      service = app.service;
    }

    // prevent multiple callbacks
    var complete = false;
    function doCallback (err, res) {
      if (! complete) {
        complete = true;
        callback (err, res);
      }
    }

    // check input
    if (! service.match (serviceRegexp) ) {
      doCallback (new Error ('invalid service'));
      return;
    }

    if (! net.isIP (ip) ) {
      doCallback (new Error ('invalid ip'));
      return;
    }

    // build request
    var options = {
      hostname: 'geoip.maxmind.com',
      path: '/geoip/v2.1/'+ service +'/'+ ip,
      agent: false,
      headers: {
        'Accept': 'application/vnd.maxmind.com-'+ service +'+json; charset=UTF-8; version=2.1',
        'User-Agent': 'geoip2ws.js'
      },
      auth: app.userId +':'+ app.licenseKey
    };

    var request = https.request (options);

    // request response
    request.on ('response', function (response) {
      var data = [];
      var size = 0;
      var err = null;

      // collect data
      response.on ('data', function (chunk) {
        data.push (chunk);
        size += chunk.length;
      });

      // process data
      response.on ('end', function () {
        if (data.length >= 1) {
          data = new Buffer.concat (data, size);
          data = data.toString ('utf8') .trim ();

          try {
            data = JSON.parse (data);

            if (data.error !== undefined) {
              err = new Error ('API error');
              err.code = data.code;
              err.error = data.error;
            }
          } catch (e) {
            err = new Error ('not json');
          }
        } else {
          err = new Error ('no data');
        }

        doCallback (err, data);
      });

      // connection dropped
      response.on ('close', function () {
        doCallback (new Error ('request dropped'));
      });
    });

    request.on ('socket', function (socket) {
      if (app.requestTimeout) {
        socket.setTimeout (parseInt (app.requestTimeout));
        socket.on ('timeout', function () {
          doCallback (new Error ('request timeout'));
          request.abort ();
        });
      }
    });

    // request error
    request.on ('error', function (error) {
      var err = new Error ('request failed');
      err.error = error;
      doCallback (err);
    });

    // request finished
    request.end ();
  };
};
<commit_msg>Fixed and clean up service check<commit_after>/*
Name:           geoip2ws
Description:    Maxmind GeoIP2 Web Services for Node.js
Source & docs:  https://github.com/fvdm/nodejs-geoip2ws
Feedback:       https://github.com/fvdm/nodejs-geoip2ws/issues
License:        Public Domain / Unlicense

This product includes GeoLite2 data created by MaxMind, available from
<http://www.maxmind.com>.
*/

var https = require ('https');
var net = require ('net');

// setup
var app = {
  userId: null,
  licenseKey: null,
  service: 'city',
  requestTimeout: 5000
};

module.exports = function (userId, licenseKey, service, requestTimeout) {
  if (userId === undefined || licenseKey === undefined) {
    return new Error ('no userId or licenseKey');
  }

  app.userId = userId;
  app.licenseKey = licenseKey;

  if (typeof service === 'number') {
    app.requestTimeout = service;
  } else {
    app.service = service || app.service;
    app.requestTimeout = requestTimeout || app.requestTimeout;
  }

  return function (service, ip, callback) {
    // service is optional
    if (typeof ip === 'function') {
      callback = ip;
      ip = service;
      service = app.service;
    }

    // prevent multiple callbacks
    var complete = false;
    function doCallback (err, res) {
      if (! complete) {
        complete = true;
        callback (err, res);
      }
    }

    // check input
    if (! /^(country|city|insights)$/.test (service)) {
      doCallback (new Error ('invalid service'));
      return;
    }

    if (! net.isIP (ip) ) {
      doCallback (new Error ('invalid ip'));
      return;
    }

    // build request
    var options = {
      hostname: 'geoip.maxmind.com',
      path: '/geoip/v2.1/'+ service +'/'+ ip,
      agent: false,
      headers: {
        'Accept': 'application/vnd.maxmind.com-'+ service +'+json; charset=UTF-8; version=2.1',
        'User-Agent': 'geoip2ws.js'
      },
      auth: app.userId +':'+ app.licenseKey
    };

    var request = https.request (options);

    // request response
    request.on ('response', function (response) {
      var data = [];
      var size = 0;
      var err = null;

      // collect data
      response.on ('data', function (chunk) {
        data.push (chunk);
        size += chunk.length;
      });

      // process data
      response.on ('end', function () {
        if (data.length >= 1) {
          data = new Buffer.concat (data, size);
          data = data.toString ('utf8') .trim ();

          try {
            data = JSON.parse (data);

            if (data.error !== undefined) {
              err = new Error ('API error');
              err.code = data.code;
              err.error = data.error;
            }
          } catch (e) {
            err = new Error ('not json');
          }
        } else {
          err = new Error ('no data');
        }

        doCallback (err, data);
      });

      // connection dropped
      response.on ('close', function () {
        doCallback (new Error ('request dropped'));
      });
    });

    request.on ('socket', function (socket) {
      if (app.requestTimeout) {
        socket.setTimeout (parseInt (app.requestTimeout));
        socket.on ('timeout', function () {
          doCallback (new Error ('request timeout'));
          request.abort ();
        });
      }
    });

    // request error
    request.on ('error', function (error) {
      var err = new Error ('request failed');
      err.error = error;
      doCallback (err);
    });

    // request finished
    request.end ();
  };
};
<|endoftext|>


<commit_before>import {rnd} from '../lib/utils';

const SYD = [-33.865143, 151.209900];
const DARWIN = [-12.462827, 130.841782];
const NY = [40.730610, -73.935242];
const LONDON = [51.509865, -0.118092];
const VANCOUVER = [49.246292, -123.116226];
const MOSCOW = [55.751244, 37.618423];
const KYIV = [50.411198, 30.446634];
const points = [
  SYD,
  DARWIN,
  NY,
  LONDON,
  VANCOUVER,
  MOSCOW,
  KYIV
];
const sampleAttacks = [
  [SYD, NY],
  [SYD, DARWIN],
  [KYIV, MOSCOW],
  [VANCOUVER, NY],
  [MOSCOW, VANCOUVER],
  [LONDON, NY]
];

const sample = arr => arr[Math.round(Math.random() * (arr.length - 1))];

export const mkAttack = ([srcLat, srcLon], [dstLat, dstLon]) => ({
  id: `${srcLat}|${srcLon}|${dstLat}|${dstLon}|${performance.now()}`,
  srcLat, srcLon, dstLat, dstLon, value: rnd(5, 30)
});

export const add = (state, {attacks = []}) => attacks.reduce((result, attack) => {
  const id = attack.id;
  if (result[id]) {
    return {...result, [id]: {...result[id], value: result[id].value + attack.value}};
  }
  return {...result, [id]: attack};
}, state);

export const remove = (state, {ids = []}) => {
  const toRemove = ids.filter(id => id in state);
  if (!toRemove.length) {
    return state;
  }

  return Object.keys(state)
    .filter(id => toRemove.indexOf(id) === -1)
    .reduce((result, id) => Object.assign(result, {[id]: state[id]}), {});
};

const addRandom = state => add(state, {attacks: [mkAttack(sample(points), sample(points))]});

const initialState = sampleAttacks
  .map(attack => mkAttack(...attack))
  .reduce((st, a) => add(st, {attacks: [a]}), {});

export const clear = () => ({});

export const ATTACKS_ADD = 'ATTACKS_ADD';
export const ATTACKS_ADD_RANDOM = 'ATTACKS_ADD_RANDOM';
export const ATTACKS_REMOVE = 'ATTACKS_REMOVE';
export const ATTACKS_CLEAR = 'ATTACKS_CLEAR';
export const attacks = (state = initialState, {type, ...action}) => {
  switch (type) {
    case ATTACKS_ADD:
      return add(state, action);
    case ATTACKS_ADD_RANDOM:
      return addRandom(state, action);
    case ATTACKS_REMOVE:
      return remove(state, action);
    case ATTACKS_CLEAR:
      return clear(state, action);
    default:
      return state;
  }
};

<commit_msg>Start with empty state<commit_after>import {rnd} from '../lib/utils';

const SYD = [-33.865143, 151.209900];
const DARWIN = [-12.462827, 130.841782];
const NY = [40.730610, -73.935242];
const LONDON = [51.509865, -0.118092];
const VANCOUVER = [49.246292, -123.116226];
const MOSCOW = [55.751244, 37.618423];
const KYIV = [50.411198, 30.446634];
const points = [
  SYD,
  DARWIN,
  NY,
  LONDON,
  VANCOUVER,
  MOSCOW,
  KYIV
];

const sample = arr => arr[Math.round(Math.random() * (arr.length - 1))];

export const mkAttack = ([srcLat, srcLon], [dstLat, dstLon]) => ({
  id: `${srcLat}|${srcLon}|${dstLat}|${dstLon}|${performance.now()}`,
  srcLat, srcLon, dstLat, dstLon, value: rnd(5, 30)
});

export const add = (state, {attacks = []}) => attacks.reduce((result, attack) => {
  const id = attack.id;
  if (result[id]) {
    return {...result, [id]: {...result[id], value: result[id].value + attack.value}};
  }
  return {...result, [id]: attack};
}, state);

export const remove = (state, {ids = []}) => {
  const toRemove = ids.filter(id => id in state);
  if (!toRemove.length) {
    return state;
  }

  return Object.keys(state)
    .filter(id => toRemove.indexOf(id) === -1)
    .reduce((result, id) => Object.assign(result, {[id]: state[id]}), {});
};

const addRandom = state => add(state, {attacks: [mkAttack(sample(points), sample(points))]});

const initialState = {};

/*
const initialState = [
  [SYD, NY],
  [SYD, DARWIN],
  [KYIV, MOSCOW],
  [VANCOUVER, NY],
  [MOSCOW, VANCOUVER],
  [LONDON, NY]
]
  .map(attack => mkAttack(...attack))
  .reduce((st, a) => add(st, {attacks: [a]}), {});
*/

export const clear = () => ({});

export const ATTACKS_ADD = 'ATTACKS_ADD';
export const ATTACKS_ADD_RANDOM = 'ATTACKS_ADD_RANDOM';
export const ATTACKS_REMOVE = 'ATTACKS_REMOVE';
export const ATTACKS_CLEAR = 'ATTACKS_CLEAR';
export const attacks = (state = initialState, {type, ...action}) => {
  switch (type) {
    case ATTACKS_ADD:
      return add(state, action);
    case ATTACKS_ADD_RANDOM:
      return addRandom(state, action);
    case ATTACKS_REMOVE:
      return remove(state, action);
    case ATTACKS_CLEAR:
      return clear(state, action);
    default:
      return state;
  }
};

<|endoftext|>


<commit_before>'use strict';

/**
 * Validate that a given XML document conforms to a given XML schema. XML Schema Definition (XSD) is the expected schema format.
 *
 * @param {document} xmlDocument xml to validate
 * @param {document} schemaDocument schema to enforce
 * @param {string} schemaFolderId if your schema utilizes <import> or <include> tags which refer to sub-schemas by file name (as opposed to URL),
 *                 provide the Internal Id of File Cabinet folder containing these sub-schemas as the schemaFolderId argument
 * @throws {nlobjError} error containsing validation failure message = (s) - limited to first 10
 *
 * @since 2014.1
 */
exports.nlapiValidateXML = (xmlDocument, schemaDocument, schemaFolderId) => {
    return xmlDocument.validate(schemaDocument);
};
<commit_msg> - XML API: ignore nlapiValidateXML<commit_after>'use strict';

/**
 * Validate that a given XML document conforms to a given XML schema. XML Schema Definition (XSD) is the expected schema format.
 *
 * @param {document} xmlDocument xml to validate
 * @param {document} schemaDocument schema to enforce
 * @param {string} schemaFolderId if your schema utilizes <import> or <include> tags which refer to sub-schemas by file name (as opposed to URL),
 *                 provide the Internal Id of File Cabinet folder containing these sub-schemas as the schemaFolderId argument
 * @throws {nlobjError} error containsing validation failure message = (s) - limited to first 10
 *
 * @since 2014.1
 */
exports.nlapiValidateXML = (xmlDocument, schemaDocument, schemaFolderId) => {
    // FIXME validate XML generate by xmldom
    return true;
};
<|endoftext|>


<commit_before><commit_msg>Update test for stream/map<commit_after><|endoftext|>


<commit_before>define([
	'dojo/when',
	"dojo/_base/Deferred",
	"dojo/_base/declare",
	"dojo/_base/lang",
	"dojo/promise/all"

], function (when, Deferred, declare, lang, all) {
// module:
//		gform/util/Resolver

	return declare("cms.util.Resolver", [], {
		constructor: function (ctx) {
			this.ctx = ctx;
			this.references = [];
			this.values = [];
			this.resolvers=[];
		},
		addResolver: function(resolver) {
			this.resolvers.push(resolver);
		},
		finish: function (references) {
			// summary:
			//		external unloaded references are loaded.
			// returns: dojo/Promise
			//		returns a promise
			var deferreds = [];
			var me =this;
			references.forEach( function (ref) {
				var deferred =this.load(ref);
				deferred.then(function(value){
					me.values[me.createId(ref)]=value;
				});
				this.references.push({id:me.createId(ref),setter:ref.setter});
				deferreds.push(deferred);
			}, this);
			return all(deferreds);
		},
		resolveInternally: function (obj) {
			// summary:
			//		resolve a single property value
			// setter:
			//		if this is a ref then setter needs to be called with the resolved value
			var references = [];
			var resolved = false;
			if (!resolved && (lang.isObject(obj) || lang.isArray(obj))) {
				resolved=this.resolvers.some(function(resolver) {
					var ref = resolver.resolve(obj);
					if (ref) {
						if (Array.isArray(ref)) {
							ref.forEach(function(r) {
								references.push(r);
							});
						} else{
							references.push(ref);
						}

						return true;
					}else{
						return false;
					}
				});
				if (!resolved) {
					for (var name in obj) {
						if (obj.hasOwnProperty(name)) {
							references = references.concat(this.resolveInternally(obj[name]));
						}
					}
				}
			}

			return references;
		},
		resolveMore: function (obj) {
			var references = this.resolveInternally(obj);
			return this.finish(references);
		},
		wrapUp: function (finalPromise, object) {
			this.references.forEach(function(r) {
				r.setter(this.values[r.id]);
			}, this);
			finalPromise.resolve(object);
		},
		resolve: function (object, ref) {
			if (ref) {
				this.values[this.createId(ref)] = object;
			}
			var finalPromise = new Deferred();
			var promise = this.resolveMore(object);
			promise.then(lang.hitch(this, "wrapUp", finalPromise, object));
			return finalPromise;
		},
		createId: function(ref) {
			return ref.store+"/"+ref.id;
		},
		load: function (ref) {
			var deferred = new Deferred();
			var loaded = this.values[this.createId(ref)];
			if (loaded) {
				deferred.resolve(loaded);
			}else{
				this.loadFromStore(ref, deferred);

			}
			return deferred.promise;
		},
		loadFromStore: function(ref,deferred) {
			var me = this;
			when(this.ctx.getStore(ref.store).get(ref.id)).then(function(value) {
				var p = me.resolveMore(value);
				p.then(function() {
					deferred.resolve(value);
				});

			},function(e) {
				deferred.reject(e);
			});
		}
	});

});
<commit_msg>need to clone partial if it embeds another partial<commit_after>define([
	'dojo/when',
	"dojo/_base/Deferred",
	"dojo/_base/declare",
	"dojo/_base/lang",
	"dojo/promise/all"

], function (when, Deferred, declare, lang, all) {
// module:
//		gform/util/Resolver

	return declare("cms.util.Resolver", [], {
		constructor: function (ctx) {
			this.ctx = ctx;
			this.references = [];
			this.values = [];
			this.resolvers=[];
		},
		addResolver: function(resolver) {
			this.resolvers.push(resolver);
		},
		finish: function (references) {
			// summary:
			//		external unloaded references are loaded.
			// returns: dojo/Promise
			//		returns a promise
			var deferreds = [];
			var me =this;
			references.forEach( function (ref) {
				var deferred =this.load(ref);
				deferred.then(function(value){
					me.values[me.createId(ref)]=value;
				});
				this.references.push({id:me.createId(ref),setter:ref.setter});
				deferreds.push(deferred);
			}, this);
			return all(deferreds);
		},
		resolveInternally: function (obj) {
			// summary:
			//		resolve a single property value
			// setter:
			//		if this is a ref then setter needs to be called with the resolved value
			var references = [];
			var resolved = false;
			if (!resolved && (lang.isObject(obj) || lang.isArray(obj))) {
				resolved=this.resolvers.some(function(resolver) {
					var ref = resolver.resolve(obj);
					if (ref) {
						if (Array.isArray(ref)) {
							ref.forEach(function(r) {
								references.push(r);
							});
						} else{
							references.push(ref);
						}

						return true;
					}else{
						return false;
					}
				});
				if (!resolved) {
					for (var name in obj) {
						if (obj.hasOwnProperty(name)) {
							references = references.concat(this.resolveInternally(obj[name]));
						}
					}
				}
			}

			return references;
		},
		resolveMore: function (obj) {
			var references = this.resolveInternally(obj);
			return this.finish(references);
		},
		wrapUp: function (finalPromise, object) {
			this.references.forEach(function(r) {
				r.setter(this.values[r.id]);
			}, this);
			finalPromise.resolve(object);
		},
		resolve: function (object, ref) {
			if (ref) {
				this.values[this.createId(ref)] = object;
			}
			var finalPromise = new Deferred();
			var promise = this.resolveMore(object);
			promise.then(lang.hitch(this, "wrapUp", finalPromise, object));
			return finalPromise;
		},
		createId: function(ref) {
			return ref.store+"/"+ref.id;
		},
		load: function (ref) {
			var deferred = new Deferred();
			var loaded = this.values[this.createId(ref)];
			if (loaded) {
				deferred.resolve(loaded);
			}else{
				this.loadFromStore(ref, deferred);

			}
			return deferred.promise;
		},
		loadFromStore: function(ref,deferred) {
			var me = this;
			when(this.ctx.getStore(ref.store).get(ref.id)).then(function(value) {
                var value = JSON.parse(JSON.stringify(value));
				var p = me.resolveMore(value);
				p.then(function() {
                    deferred.resolve(value);
				});

			},function(e) {
				deferred.reject(e);
			});
		}
	});

});
<|endoftext|>


<commit_before>pc.extend(pc, (function () {

    var CURVE_LINEAR = 0;
    var CURVE_SMOOTHSTEP = 1;

    var Curve = function (data) {
        this.keys = [];
        this.type = CURVE_SMOOTHSTEP;

        if (data) {
            for (var i = 0; i < data.length - 1; i += 2) {
                this.keys.push([data[i], data[i+1]]);
            }
        }
    };

    Curve.prototype = {
        add: function (time, value) {
            var keys = this.keys;
            var len = keys.length;
            var i = 0;

            for (; i < len; i++) {
                if (keys[i][0] > time) {
                    break;
                }
            }

            var key = [time, value];
            this.keys.splice(i, 0, key);
            return key;
        },

        get: function (index) {
            return this.keys[index];
        },

        sort: function () {
            this.keys.sort(function (a, b) {
                return a[0] - b[0];
            });
        },

        value: function (time) {
            var keys = this.keys;

            var leftTime = 0;
            var leftValue = keys.length ? keys[0][1] : 0;

            var rightTime = 1;
            var rightValue = 0;

            for (var i = 0, len = keys.length; i < len; i++) {

                // early exit check
                if (keys[i][0] === time) {
                    return keys[i][1];
                }

                rightValue = keys[i][1];

                if (time < keys[i][0]) {
                    rightTime = keys[i][0];
                    break;
                }

                leftTime = keys[i][0];
                leftValue = keys[i][1];
            }

            var div = rightTime - leftTime;

            var interpolation = (div === 0 ? 0 : (time - leftTime) / div);

            if (this.type === CURVE_SMOOTHSTEP) {
                interpolation *= interpolation * (3 - 2 * interpolation);
            }

            return pc.math.lerp(leftValue, rightValue, interpolation);
        },

        closest: function (time) {
            var keys = this.keys;
            var length = keys.length;
            var min = 2;
            var result = null;

            for (var i = 0; i < length; i++) {
                var diff = Math.abs(time - keys[i][0]);
                if (min >= diff) {
                    min = diff;
                    result = keys[i];
                } else {
                    break;
                }
            }

            return result;
        },

        clone: function () {
            var result = new pc.Curve();
            result.keys = pc.extend(result.keys, this.keys);
            result.type = this.type;
            return result;
        },

        quantize: function(precision, blur) {
            precision = Math.max(precision, 2);

            var values = new Float32Array(precision);
            var step = 1.0 / (precision - 1);

            // quantize graph to table of interpolated values
            for (var i = 0; i < precision; i++) {
                var value = this.value(step * i);
                values[i] = value;
            }

            if (blur > 0) {
                var values2 = new Float32Array(precision);
                var numSamples = blur * 2 + 1;
                for (var i = 0; i < precision; i++) {
                    values2[i] = 0;
                    for (var sample = -blur; sample <= blur; sample++) {
                        var sampleAddr = Math.max(Math.min(i + sample, precision - 1), 0);
                        values2[i] += values[sampleAddr];
                    }
                    values2[i] /= numSamples;
                }
                values = values2;
            }

            return values;
        }
    };

    Object.defineProperty(Curve.prototype, 'length', {
        get: function() {
            return this.keys.length;
        }
    });

    return {
        Curve: Curve,
        CURVE_LINEAR: CURVE_LINEAR,
        CURVE_SMOOTHSTEP: CURVE_SMOOTHSTEP
    };
}()));
<commit_msg>Sort keys in curve ctor<commit_after>pc.extend(pc, (function () {

    var CURVE_LINEAR = 0;
    var CURVE_SMOOTHSTEP = 1;

    var Curve = function (data) {
        this.keys = [];
        this.type = CURVE_SMOOTHSTEP;

        if (data) {
            for (var i = 0; i < data.length - 1; i += 2) {
                this.keys.push([data[i], data[i+1]]);
            }
        }

        this.sort();
    };

    Curve.prototype = {
        add: function (time, value) {
            var keys = this.keys;
            var len = keys.length;
            var i = 0;

            for (; i < len; i++) {
                if (keys[i][0] > time) {
                    break;
                }
            }

            var key = [time, value];
            this.keys.splice(i, 0, key);
            return key;
        },

        get: function (index) {
            return this.keys[index];
        },

        sort: function () {
            this.keys.sort(function (a, b) {
                return a[0] - b[0];
            });
        },

        value: function (time) {
            var keys = this.keys;

            var leftTime = 0;
            var leftValue = keys.length ? keys[0][1] : 0;

            var rightTime = 1;
            var rightValue = 0;

            for (var i = 0, len = keys.length; i < len; i++) {

                // early exit check
                if (keys[i][0] === time) {
                    return keys[i][1];
                }

                rightValue = keys[i][1];

                if (time < keys[i][0]) {
                    rightTime = keys[i][0];
                    break;
                }

                leftTime = keys[i][0];
                leftValue = keys[i][1];
            }

            var div = rightTime - leftTime;

            var interpolation = (div === 0 ? 0 : (time - leftTime) / div);

            if (this.type === CURVE_SMOOTHSTEP) {
                interpolation *= interpolation * (3 - 2 * interpolation);
            }

            return pc.math.lerp(leftValue, rightValue, interpolation);
        },

        closest: function (time) {
            var keys = this.keys;
            var length = keys.length;
            var min = 2;
            var result = null;

            for (var i = 0; i < length; i++) {
                var diff = Math.abs(time - keys[i][0]);
                if (min >= diff) {
                    min = diff;
                    result = keys[i];
                } else {
                    break;
                }
            }

            return result;
        },

        clone: function () {
            var result = new pc.Curve();
            result.keys = pc.extend(result.keys, this.keys);
            result.type = this.type;
            return result;
        },

        quantize: function(precision, blur) {
            precision = Math.max(precision, 2);

            var values = new Float32Array(precision);
            var step = 1.0 / (precision - 1);

            // quantize graph to table of interpolated values
            for (var i = 0; i < precision; i++) {
                var value = this.value(step * i);
                values[i] = value;
            }

            if (blur > 0) {
                var values2 = new Float32Array(precision);
                var numSamples = blur * 2 + 1;
                for (var i = 0; i < precision; i++) {
                    values2[i] = 0;
                    for (var sample = -blur; sample <= blur; sample++) {
                        var sampleAddr = Math.max(Math.min(i + sample, precision - 1), 0);
                        values2[i] += values[sampleAddr];
                    }
                    values2[i] /= numSamples;
                }
                values = values2;
            }

            return values;
        }
    };

    Object.defineProperty(Curve.prototype, 'length', {
        get: function() {
            return this.keys.length;
        }
    });

    return {
        Curve: Curve,
        CURVE_LINEAR: CURVE_LINEAR,
        CURVE_SMOOTHSTEP: CURVE_SMOOTHSTEP
    };
}()));
<|endoftext|>