<commit_before>/* ------------------
 * Definitions of core native methods
 * ------------------ */

(function ($env) {
  // java.lang.Boolean

  $env.registerNative("java.lang.Boolean :: toString():java.lang.String", function() {
    return $env.makeNativeStrWrapper(this["$jsfield$value "].toString());
  });

  // java.lang.Character

  $env.registerNative("java.lang.Character :: toString():java.lang.String", function() {
    return $env.makeNativeStrWrapper(String.fromCharCode(this["charValue():scala.Char"]()));
  });

  // java.lang.Byte

  $env.registerNative("java.lang.Byte :: toString():java.lang.String", function() {
    return $env.makeNativeStrWrapper(this["$jsfield$value "].toString());
  });

  // java.lang.Short

  $env.registerNative("java.lang.Short :: toString():java.lang.String", function() {
    return $env.makeNativeStrWrapper(this["$jsfield$value "].toString());
  });

  // java.lang.Integer

  $env.registerNative("java.lang.Integer :: toString():java.lang.String", function() {
    return $env.makeNativeStrWrapper(this["$jsfield$value "].toString());
  });

  $env.registerNative("java.lang.Integer$ :: parseInt(java.lang.String):scala.Int", function(str) {
    return parseInt(str.toNativeString());
  });

  // java.lang.Long

  $env.registerNative("java.lang.Long :: toString():java.lang.String", function() {
    return $env.makeNativeStrWrapper(this["$jsfield$value "].toString());
  });

  // java.lang.Float

  $env.registerNative("java.lang.Float :: toString():java.lang.String", function() {
    return $env.makeNativeStrWrapper(this["$jsfield$value "].toString());
  });

  $env.registerNative("java.lang.Float$ :: parseFloat(java.lang.String):scala.Int", function(str) {
    return parseFloat(str.toNativeString());
  });

  // java.lang.Double

  $env.registerNative("java.lang.Double :: toString():java.lang.String", function() {
    return $env.makeNativeStrWrapper(this["$jsfield$value "].toString());
  });

  // java.lang.System

  $env.registerNative("java.lang.System$ :: currentTimeMillis():scala.Long", function() {
    return new Date().getTime();
  });

  $env.registerNative("java.lang.System$ :: arraycopy(java.lang.Object,scala.Int,java.lang.Object,scala.Int,scala.Int):scala.Unit",
    function(src, srcPos, dest, destPos, count) {
      // TODO Throw errors properly
      var srcUnderlying = src.underlying;
      var destUnderlying = dest.underlying;
      for (var i = 0; i < count; i++) {
        destUnderlying[destPos+i] = srcUnderlying[srcPos+i];
      }
    });

  $env.registerNative("java.lang.System$ :: identityHashCode(java.lang.Object):scala.Int", function(obj) {
    // TODO
    return 42;
  });

  $env.registerNative("java.lang.System$ :: halt0(scala.Int):scala.Unit", function(exitCode) {
    // Well, it is not possible to implement this, right?
    throw new this.classes["java.lang.SecurityException"].type()[
      "<init>(java.lang.String):java.lang.SecurityException"](
        this.makeNativeStrWrapper(
          "Cannot terminate a JavaScript program"));
  });

  // java.lang.Runtime

  $env.registerNative("java.lang.Runtime$ :: gc():scala.Unit", function() {
    // Ignore
  });

  // java.lang.reflect.Array

  $env.registerNative("java.lang.reflect.Array$ :: newArray(java.lang.Class,scala.Int):java.lang.Object", function(componentType, length) {
    return $env.newArrayObject(componentType.$data.array, [length]);
  });

  $env.registerNative("java.lang.reflect.Array$ :: multiNewArray(java.lang.Class,scala.Int[]):java.lang.Object", function(componentType, lengths) {
    lengths = lengths.underlying;
    var arrayClassData = componentType.$data;
    for (var i = 0; i < lengths.length; i++)
      arrayClassData = arrayClassData.array;
    return $env.newArrayObject(arrayClassData, lengths);
  });

  $env.registerNative("java.lang.reflect.Array$ :: getLength(java.lang.Object):scala.Int", function(array) {
    return array.length();
  });

  function registerArray_getX_setX(elementShortName) {
    if (elementShortName === "Object") {
      var functionNameSuffix = "";
      var elementTypeName = "java.lang.Object";
    } else {
      var functionNameSuffix = elementShortName;
      var elementTypeName = "scala."+elementShortName;
    }

    $env.registerNative("java.lang.reflect.Array$ :: get"+functionNameSuffix+"(java.lang.Object,scala.Int):"+elementTypeName), function(array, index) {
      return array.get(index);
    }

    $env.registerNative("java.lang.reflect.Array$ :: set"+functionNameSuffix+"(java.lang.Object,scala.Int,"+elementTypeName+"):scala.Unit"), function(array, index, value) {
      array.set(index, value);
    }
  }

  registerArray_getX_setX("Object");
  registerArray_getX_setX("Boolean");
  registerArray_getX_setX("Char");
  registerArray_getX_setX("Byte");
  registerArray_getX_setX("Short");
  registerArray_getX_setX("Int");
  registerArray_getX_setX("Long");
  registerArray_getX_setX("Float");
  registerArray_getX_setX("Double");

  // java.lang.StandardOutPrintStream$

  $env.registerNative("java.lang.StandardOutPrintStream$ :: writeString(java.lang.String):scala.Unit", function(x) {
    console.log("out: " + x.toNativeString());
  });

  // java.lang.StandardErrPrintStream$

  $env.registerNative("java.lang.StandardErrPrintStream$ :: writeString(java.lang.String):scala.Unit", function(x) {
    console.log("err: " + x.toNativeString());
  });

  // JavaScript Dynamic objects

  function unboxJSValue(boxed) {
    if (boxed === null)
      return null;
    else
      return boxed["$jsfield$underlying "];
  }

  function boxJSValue(unboxed) {
    if (unboxed === null)
      return null;
    else {
      return new $env.classes["scala.js.JavaScriptObject"].type()[
        "<init>(java.lang.Object):scala.js.JavaScriptObject"](unboxed);
    }
  }

  function unboxJSValueSeq(boxedSeq) {
    var size = boxedSeq["size():scala.Int"]();
    var result = new Array(size);
    for (var i = 0; i < size; i++) {
      result[i] = unboxJSValue(boxedSeq["apply(scala.Int):java.lang.Object"](i));
    }
    return result;
  }

  $env.registerNative("scala.js.JavaScriptObject :: applyDynamic(java.lang.String,scala.collection.Seq):scala.js.JavaScriptObject", function(fun, argsSeq) {
    var thisValue = unboxJSValue(this);
    var args = unboxJSValueSeq(argsSeq);
    var method = thisValue[fun.toNativeString()];
    return boxJSValue(method.apply(thisValue, args));
  });

  $env.registerNative("scala.js.JavaScriptObject :: selectDynamic(java.lang.String):scala.js.JavaScriptObject", function(property) {
    return boxJSValue(unboxJSValue(this)[property.toNativeString()]);
  });

  $env.registerNative("scala.js.JavaScriptObject :: updateDynamic(java.lang.String,scala.js.JavaScriptObject):scala.Unit", function(property, value) {
    unboxJSValue(this)[property.toNativeString()] = unboxJSValue(value);
  });

  $env.registerNative("scala.js.JavaScriptObject :: apply(scala.collection.Seq):scala.js.JavaScriptObject", function(argsSeq) {
    var thisValue = unboxJSValue(this);
    var args = unboxJSValueSeq(argsSeq);
    return boxJSValue(thisValue.apply(window, args));
  });

  $env.registerNative("scala.js.JavaScriptObject :: toString():java.lang.String", function() {
    return $env.makeNativeStrWrapper(unboxJSValue(this).toString());
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: newEmpty():scala.js.JavaScriptObject", function() {
    return boxJSValue({});
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: window():scala.js.JavaScriptObject", function() {
    return boxJSValue(window);
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: fromUnit(scala.runtime.BoxedUnit):scala.js.JavaScriptObject", function(value) {
    return boxJSValue(undefined);
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: fromBoolean(scala.Boolean):scala.js.JavaScriptObject", function(value) {
    return boxJSValue(value);
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: fromChar(scala.Char):scala.js.JavaScriptObject", function(value) {
    return boxJSValue(value);
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: fromByte(scala.Byte):scala.js.JavaScriptObject", function(value) {
    return boxJSValue(value);
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: fromShort(scala.Short):scala.js.JavaScriptObject", function(value) {
    return boxJSValue(value);
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: fromInt(scala.Int):scala.js.JavaScriptObject", function(value) {
    return boxJSValue(value);
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: fromLong(scala.Long):scala.js.JavaScriptObject", function(value) {
    return boxJSValue(value);
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: fromFloat(scala.Float):scala.js.JavaScriptObject", function(value) {
    return boxJSValue(value);
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: fromDouble(scala.Double):scala.js.JavaScriptObject", function(value) {
    return boxJSValue(value);
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: fromString(java.lang.String):scala.js.JavaScriptObject", function(value) {
    return boxJSValue(value.toNativeString());
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: fromObject(java.lang.Object):scala.js.JavaScriptObject", function(value) {
    return boxJSValue(value);
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: fromArray(scala.js.JavaScriptObject[]):scala.js.JavaScriptObject", function(value) {
    var sourceArray = value.underlying
    var result = new Array(sourceArray.length)
    for (var i = 0; i < sourceArray.length; i++)
      result[i] = unboxJSValue(sourceArray[i]);
    return boxJSValue(result);
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: fromFunction0(scala.Function0):scala.js.JavaScriptObject", function(f) {
    return boxJSValue(function() {
      return unboxJSValue(f["apply():java.lang.Object"]());
    });
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: fromFunction1(scala.Function1):scala.js.JavaScriptObject", function(f) {
    return boxJSValue(function(arg1) {
      return unboxJSValue(f["apply(java.lang.Object):java.lang.Object"](boxJSValue(arg1)));
    });
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: fromFunction2(scala.Function2):scala.js.JavaScriptObject", function(f) {
    return boxJSValue(function(arg1, arg2) {
      return unboxJSValue(f["apply(java.lang.Object,java.lang.Object):java.lang.Object"](boxJSValue(arg1), boxJSValue(arg2)));
    });
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: toBoolean(scala.js.JavaScriptObject):scala.Boolean", function(value) {
    var result = unboxJSValue(value);
    if (typeof(result) !== 'boolean')
      throw "not a boolean";
    return result;
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: toInt(scala.js.JavaScriptObject):scala.Int", function(value) {
    var result = unboxJSValue(value);
    if (typeof(result) !== 'number')
      throw "not an integer";
    return Math.round(result);
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: toString(scala.js.JavaScriptObject):java.lang.String", function(value) {
    var result = unboxJSValue(value);
    if (typeof(result) !== 'string')
      throw "not a string";
    return $env.makeNativeStrWrapper(result);
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: toObject(scala.js.JavaScriptObject):java.lang.Object", function(value) {
    var result = unboxJSValue(value);
    if ((typeof(result) !== 'object') || (result.$classData === undefined))
      throw "not a Scala object";
    return result;
  });
})($ScalaJSEnvironment);
<commit_msg>Better Console.{out,err}.println().<commit_after>/* ------------------
 * Definitions of core native methods
 * ------------------ */

(function ($env) {
  // java.lang.Boolean

  $env.registerNative("java.lang.Boolean :: toString():java.lang.String", function() {
    return $env.makeNativeStrWrapper(this["$jsfield$value "].toString());
  });

  // java.lang.Character

  $env.registerNative("java.lang.Character :: toString():java.lang.String", function() {
    return $env.makeNativeStrWrapper(String.fromCharCode(this["charValue():scala.Char"]()));
  });

  // java.lang.Byte

  $env.registerNative("java.lang.Byte :: toString():java.lang.String", function() {
    return $env.makeNativeStrWrapper(this["$jsfield$value "].toString());
  });

  // java.lang.Short

  $env.registerNative("java.lang.Short :: toString():java.lang.String", function() {
    return $env.makeNativeStrWrapper(this["$jsfield$value "].toString());
  });

  // java.lang.Integer

  $env.registerNative("java.lang.Integer :: toString():java.lang.String", function() {
    return $env.makeNativeStrWrapper(this["$jsfield$value "].toString());
  });

  $env.registerNative("java.lang.Integer$ :: parseInt(java.lang.String):scala.Int", function(str) {
    return parseInt(str.toNativeString());
  });

  // java.lang.Long

  $env.registerNative("java.lang.Long :: toString():java.lang.String", function() {
    return $env.makeNativeStrWrapper(this["$jsfield$value "].toString());
  });

  // java.lang.Float

  $env.registerNative("java.lang.Float :: toString():java.lang.String", function() {
    return $env.makeNativeStrWrapper(this["$jsfield$value "].toString());
  });

  $env.registerNative("java.lang.Float$ :: parseFloat(java.lang.String):scala.Int", function(str) {
    return parseFloat(str.toNativeString());
  });

  // java.lang.Double

  $env.registerNative("java.lang.Double :: toString():java.lang.String", function() {
    return $env.makeNativeStrWrapper(this["$jsfield$value "].toString());
  });

  // java.lang.System

  $env.registerNative("java.lang.System$ :: currentTimeMillis():scala.Long", function() {
    return new Date().getTime();
  });

  $env.registerNative("java.lang.System$ :: arraycopy(java.lang.Object,scala.Int,java.lang.Object,scala.Int,scala.Int):scala.Unit",
    function(src, srcPos, dest, destPos, count) {
      // TODO Throw errors properly
      var srcUnderlying = src.underlying;
      var destUnderlying = dest.underlying;
      for (var i = 0; i < count; i++) {
        destUnderlying[destPos+i] = srcUnderlying[srcPos+i];
      }
    });

  $env.registerNative("java.lang.System$ :: identityHashCode(java.lang.Object):scala.Int", function(obj) {
    // TODO
    return 42;
  });

  $env.registerNative("java.lang.System$ :: halt0(scala.Int):scala.Unit", function(exitCode) {
    // Well, it is not possible to implement this, right?
    throw new this.classes["java.lang.SecurityException"].type()[
      "<init>(java.lang.String):java.lang.SecurityException"](
        this.makeNativeStrWrapper(
          "Cannot terminate a JavaScript program"));
  });

  // java.lang.Runtime

  $env.registerNative("java.lang.Runtime$ :: gc():scala.Unit", function() {
    // Ignore
  });

  // java.lang.reflect.Array

  $env.registerNative("java.lang.reflect.Array$ :: newArray(java.lang.Class,scala.Int):java.lang.Object", function(componentType, length) {
    return $env.newArrayObject(componentType.$data.array, [length]);
  });

  $env.registerNative("java.lang.reflect.Array$ :: multiNewArray(java.lang.Class,scala.Int[]):java.lang.Object", function(componentType, lengths) {
    lengths = lengths.underlying;
    var arrayClassData = componentType.$data;
    for (var i = 0; i < lengths.length; i++)
      arrayClassData = arrayClassData.array;
    return $env.newArrayObject(arrayClassData, lengths);
  });

  $env.registerNative("java.lang.reflect.Array$ :: getLength(java.lang.Object):scala.Int", function(array) {
    return array.length();
  });

  function registerArray_getX_setX(elementShortName) {
    if (elementShortName === "Object") {
      var functionNameSuffix = "";
      var elementTypeName = "java.lang.Object";
    } else {
      var functionNameSuffix = elementShortName;
      var elementTypeName = "scala."+elementShortName;
    }

    $env.registerNative("java.lang.reflect.Array$ :: get"+functionNameSuffix+"(java.lang.Object,scala.Int):"+elementTypeName), function(array, index) {
      return array.get(index);
    }

    $env.registerNative("java.lang.reflect.Array$ :: set"+functionNameSuffix+"(java.lang.Object,scala.Int,"+elementTypeName+"):scala.Unit"), function(array, index, value) {
      array.set(index, value);
    }
  }

  registerArray_getX_setX("Object");
  registerArray_getX_setX("Boolean");
  registerArray_getX_setX("Char");
  registerArray_getX_setX("Byte");
  registerArray_getX_setX("Short");
  registerArray_getX_setX("Int");
  registerArray_getX_setX("Long");
  registerArray_getX_setX("Float");
  registerArray_getX_setX("Double");

  // java.lang.StandardOutPrintStream$

  $env.registerNative("java.lang.StandardOutPrintStream$ :: writeString(java.lang.String):scala.Unit", function(x) {
    if (typeof(console) !== 'undefined') {
      var nativeStr = x.toNativeString();
      if (nativeStr != '\n')
        console.log(nativeStr);
    }
  });

  // java.lang.StandardErrPrintStream$

  $env.registerNative("java.lang.StandardErrPrintStream$ :: writeString(java.lang.String):scala.Unit", function(x) {
    if (typeof(console) !== 'undefined') {
      var nativeStr = x.toNativeString();
      if (nativeStr != '\n')
        console.error(nativeStr);
    }
  });

  // JavaScript Dynamic objects

  function unboxJSValue(boxed) {
    if (boxed === null)
      return null;
    else
      return boxed["$jsfield$underlying "];
  }

  function boxJSValue(unboxed) {
    if (unboxed === null)
      return null;
    else {
      return new $env.classes["scala.js.JavaScriptObject"].type()[
        "<init>(java.lang.Object):scala.js.JavaScriptObject"](unboxed);
    }
  }

  function unboxJSValueSeq(boxedSeq) {
    var size = boxedSeq["size():scala.Int"]();
    var result = new Array(size);
    for (var i = 0; i < size; i++) {
      result[i] = unboxJSValue(boxedSeq["apply(scala.Int):java.lang.Object"](i));
    }
    return result;
  }

  $env.registerNative("scala.js.JavaScriptObject :: applyDynamic(java.lang.String,scala.collection.Seq):scala.js.JavaScriptObject", function(fun, argsSeq) {
    var thisValue = unboxJSValue(this);
    var args = unboxJSValueSeq(argsSeq);
    var method = thisValue[fun.toNativeString()];
    return boxJSValue(method.apply(thisValue, args));
  });

  $env.registerNative("scala.js.JavaScriptObject :: selectDynamic(java.lang.String):scala.js.JavaScriptObject", function(property) {
    return boxJSValue(unboxJSValue(this)[property.toNativeString()]);
  });

  $env.registerNative("scala.js.JavaScriptObject :: updateDynamic(java.lang.String,scala.js.JavaScriptObject):scala.Unit", function(property, value) {
    unboxJSValue(this)[property.toNativeString()] = unboxJSValue(value);
  });

  $env.registerNative("scala.js.JavaScriptObject :: apply(scala.collection.Seq):scala.js.JavaScriptObject", function(argsSeq) {
    var thisValue = unboxJSValue(this);
    var args = unboxJSValueSeq(argsSeq);
    return boxJSValue(thisValue.apply(window, args));
  });

  $env.registerNative("scala.js.JavaScriptObject :: toString():java.lang.String", function() {
    return $env.makeNativeStrWrapper(unboxJSValue(this).toString());
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: newEmpty():scala.js.JavaScriptObject", function() {
    return boxJSValue({});
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: window():scala.js.JavaScriptObject", function() {
    return boxJSValue(window);
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: fromUnit(scala.runtime.BoxedUnit):scala.js.JavaScriptObject", function(value) {
    return boxJSValue(undefined);
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: fromBoolean(scala.Boolean):scala.js.JavaScriptObject", function(value) {
    return boxJSValue(value);
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: fromChar(scala.Char):scala.js.JavaScriptObject", function(value) {
    return boxJSValue(value);
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: fromByte(scala.Byte):scala.js.JavaScriptObject", function(value) {
    return boxJSValue(value);
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: fromShort(scala.Short):scala.js.JavaScriptObject", function(value) {
    return boxJSValue(value);
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: fromInt(scala.Int):scala.js.JavaScriptObject", function(value) {
    return boxJSValue(value);
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: fromLong(scala.Long):scala.js.JavaScriptObject", function(value) {
    return boxJSValue(value);
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: fromFloat(scala.Float):scala.js.JavaScriptObject", function(value) {
    return boxJSValue(value);
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: fromDouble(scala.Double):scala.js.JavaScriptObject", function(value) {
    return boxJSValue(value);
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: fromString(java.lang.String):scala.js.JavaScriptObject", function(value) {
    return boxJSValue(value.toNativeString());
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: fromObject(java.lang.Object):scala.js.JavaScriptObject", function(value) {
    return boxJSValue(value);
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: fromArray(scala.js.JavaScriptObject[]):scala.js.JavaScriptObject", function(value) {
    var sourceArray = value.underlying
    var result = new Array(sourceArray.length)
    for (var i = 0; i < sourceArray.length; i++)
      result[i] = unboxJSValue(sourceArray[i]);
    return boxJSValue(result);
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: fromFunction0(scala.Function0):scala.js.JavaScriptObject", function(f) {
    return boxJSValue(function() {
      return unboxJSValue(f["apply():java.lang.Object"]());
    });
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: fromFunction1(scala.Function1):scala.js.JavaScriptObject", function(f) {
    return boxJSValue(function(arg1) {
      return unboxJSValue(f["apply(java.lang.Object):java.lang.Object"](boxJSValue(arg1)));
    });
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: fromFunction2(scala.Function2):scala.js.JavaScriptObject", function(f) {
    return boxJSValue(function(arg1, arg2) {
      return unboxJSValue(f["apply(java.lang.Object,java.lang.Object):java.lang.Object"](boxJSValue(arg1), boxJSValue(arg2)));
    });
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: toBoolean(scala.js.JavaScriptObject):scala.Boolean", function(value) {
    var result = unboxJSValue(value);
    if (typeof(result) !== 'boolean')
      throw "not a boolean";
    return result;
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: toInt(scala.js.JavaScriptObject):scala.Int", function(value) {
    var result = unboxJSValue(value);
    if (typeof(result) !== 'number')
      throw "not an integer";
    return Math.round(result);
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: toString(scala.js.JavaScriptObject):java.lang.String", function(value) {
    var result = unboxJSValue(value);
    if (typeof(result) !== 'string')
      throw "not a string";
    return $env.makeNativeStrWrapper(result);
  });

  $env.registerNative("scala.js.JavaScriptObject$ :: toObject(scala.js.JavaScriptObject):java.lang.Object", function(value) {
    var result = unboxJSValue(value);
    if ((typeof(result) !== 'object') || (result.$classData === undefined))
      throw "not a Scala object";
    return result;
  });
})($ScalaJSEnvironment);
<|endoftext|>


<commit_before>var screen = null;
var layer = null;
var spriteLives = [];

var lifeGame = {
	label: "LIVES",
	life: 2,
	positionX: 50
};

var scoreGame = {
	label: null,
	score: 0,
	text: "SCORE"
};

var LG = {KEYS: []};

/* Box 2D */
/*var world = null;
var b2Vec2 = Box2D.Common.Math.b2Vec2,
    b2BodyDef = Box2D.Dynamics.b2BodyDef,
    b2Body = Box2D.Dynamics.b2Body,
    b2FixtureDef = Box2D.Dynamics.b2FixtureDef,
    b2World = Box2D.Dynamics.b2World,
    b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape,
    b2Listener = Box2D.Dynamics.b2ContactListener;
	*/

var objects = null;

var gameLayer = cc.Layer.extend({
	spriteFrameCache: cc.SpriteFrameCache.getInstance(),
	gameOver: null,
	_pac: null,
	_blinky: null,
	_pinky: null,
	_inkey: null,
	_clyde: null,
	_score: null,
	map: null,

	init:function(e)
	{
		this._super();

		/* Configuracao do mundo Box 2D */
		//world = new b2World(new b2Vec2(0, 0), true);

		this.setKeyboardEnabled(true);

		map = cc.TMXTiledMap.create(tMap);
		//map.setPosition(cc.p(113, 50));
		this.addChild(map, 0, 1);

		var group = map.getObjectGroup("Camada de Objetos")
        objects = group.getObjects();

        var decisionGroup = map.getObjectGroup("Camada de Decisao");
        decisionObjects = decisionGroup.getObjects();

        scoreObjects = map.getObjectGroup("Score").getObjects();

		this._pac = new Pac();
        map.addChild(this._pac);
		//this.addChild(this._pac);
        this._pac.setPosition(new cc.Point(screen.width/2 - 110, screen.height/2 - 218));
        this._pac.setAnimation("pac", "left", SPRITE_SIZE, 2, "left");
        this._pac.getAnimation("left");
        LG.KEYS[cc.KEY.left] = true;
        this._pac.setPositionOnScreen(LG.KEYS[e]);
        //this._pac.setDynamicPosition('left');

		//lifeGame.life = 2;
		//scoreGame.score = 0;
		screen = cc.Director.getInstance().getWinSizeInPixels();
		livePositionX = 30;
		/*
		this._blinky = new Ghost();
		this._blinky.setGhost("blinky");
        map.addChild(this._blinky);
		//this.addChild(this._blinky);
        this._blinky.setPosition(new cc.Point(screen.width / 2 - 115, screen.height / 2 + 50));
        this._blinky.setAnimation("blinky", "up", SPRITE_SIZE, 2, "up");
        this._blinky.getAnimation("up");
        this._blinky.setPositionOnScreen("blinky", "right");
        */
        //this._blinky.setDynamicPosition("up");

		/*this._pinky = new Ghost();
		this._pinky.setGhost("pinky");
        map.addChild(this._pinky);
		//this.addChild(this._pinky);
        this._pinky.setPosition(new cc.Point(screen.width / 2 - 118, screen.height / 2 - 10));
        this._pinky.setAnimation("pinky", "up", SPRITE_SIZE, 2, "up");
        this._pinky.getAnimation("up");
        //this._pinky.setDynamicPosition("left");
        //this._pinky.setPositionOnScreen("pinky");

        this._inkey = new Ghost();
		this._inkey.setGhost("inkey");
        map.addChild(this._inkey);
		//this.addChild(this._inkey);
        this._inkey.setPosition(new cc.Point(screen.width / 2 - 150, screen.height / 2 - 10));
        this._inkey.setAnimation("inkey", "up", SPRITE_SIZE, 2, "up");
        this._inkey.getAnimation("up");
        //this._inkey.setDynamicPosition("down");
        //this._inkey.setPositionOnScreen("inkey");

        this._clyde = new Ghost();
		this._clyde.setGhost("clyde");
        map.addChild(this._clyde);
		//this.addChild(this._clyde);
        this._clyde.setPosition(new cc.Point(screen.width / 2 - 86, screen.height / 2 - 10));
        this._clyde.setAnimation("clyde", "up", SPRITE_SIZE, 2, "up");
        this._clyde.getAnimation("up");
        //this._clyde.setDynamicPosition();
        //this._clyde.setPositionOnScreen("clyde");
		*/
		if (lifeGame.life == 2){
			this.addLives();
			this.addScore();
		}

		this.fillScore();
		//this.schedule(this.onClick, 3);
		this.scheduleUpdate();

		return true;
	},

	update: function(){
		cc.log("game update");
		this.verifyCollisionBetweenPacMap();
		this.verifyCollisionBetweenPacGhost();
		this.verifiyGhostDirection();
	},

	onClick:function (dt) {
		if (lifeGame.life != 0){
			this.removeLives();
			this.plusScore();
		}

    },

	addLives: function()
	{
		lifeGame.label = cc.LabelTTF.create("LIVES", "fontName", 20);
		lifeGame.label.setPosition( new cc.Point(screen.width/2 + 200, screen.height/2 - 350) );
		this.addChild( lifeGame.label );
		cc.log(lifeGame.life);
		for(var i = 0; i < lifeGame.life; i++)
		{
			spriteLives[i] = cc.Sprite.create(sPacLife);
			spriteLives[i].setPosition(screen.width/2 + 200 + lifeGame.positionX, screen.height/2 - 350);
            this.addChild( spriteLives[i] );
			lifeGame.positionX += 20;
		}
	},

	removeLives: function()
	{
		lifeGame.life--;
		this.removeChild( spriteLives[lifeGame.life] );
		if (lifeGame.life != 0){
			this.init();
		}
		else{
			this.gameOver = new losing();
	        this.addChild( this.gameOver );
			cc.Director.getInstance().replaceScene(cc.TransitionFade.create(10,new highScore()));
		}
	},

	addScore:function()
	{
		scoreGame.label = cc.LabelTTF.create(scoreGame.text + " " + scoreGame.score, "fontName", 20);
		scoreGame.label.setPosition(new cc.Point(screen.width/2 - 300, screen.height/2 - 350) );
		this.addChild( scoreGame.label );

    },

	plusScore: function()
	{
		scoreGame.score += 10;
		scoreGame.label.setString(scoreGame.text + " " + scoreGame.score);
	},

	onKeyDown:function (e) {
		cc.log("pressionou a tecla");
        LG.KEYS[e] = true;
        this._pac.setPositionOnScreen(e);
        this.verifiyCollisionBetweenPacScore();

    },

    onKeyUp:function (e) {
        LG.KEYS[e] = false;
    },

	verifyCollisionBetweenPacMap: function(){
		for (var i = 0; i < objects.length; i++) {
            var dict = objects[i];
            if (!dict)
                break;

            var x = dict["x"];
            var y = dict["y"];
            var width = dict["width"];
            var height = dict["height"];

            point1 = cc.p(x, y);
            point2 = cc.p(width, height);

                /*
            var react = cc.rect(x, y,
                        width, height);

            if(cc.rectIntersectsRect(react, this._pac.getBoundingBoxToWorld())){
            	cc.log("colidiu colidiu colidiu colidiu colidiu colidiu colidiu colidiu");
            	if(this._pac.xVelocity != 0){
            		this._pac.xVelocity = 0;
                }else if(this._pac.yVelocity != 0){
                	this._pac.yVelocity = 0;
                }
            }

            */

            cc.log("verificando colisao");

            cc.renderContext.lineWidth = 3;
            cc.renderContext.strokeStyle = "#ffffff";

            cc.drawingUtil.drawLine(cc.p(x, y), cc.p(x + width, y));
            cc.drawingUtil.drawLine(cc.p(x + width, y), cc.p(x + width, y + height));
            cc.drawingUtil.drawLine(cc.p(x + width, y + height), cc.p(x, y + height));
            cc.drawingUtil.drawLine(cc.p(x, y + height), cc.p(x, y));

            cc.renderContext.lineWidth = 1;

			var rect1 = cc.rect(x, y, width, height);

			var b = this._pac.getContentSize();
			var q = this._pac.getPosition();
			var rect2 = cc.rect(q.x, q.y, b.width, b.height);

			if (cc.rectIntersectsRect(rect1, rect2)){
				cc.log("colidiu colidiu colidiu colidiu");
				if(this._pac.xVelocity != 0){
					this._pac.xVelocity = 0;
                }else if(this._pac.yVelocity != 0){
					this._pac.yVelocity = 0;
                }
			}

        }
	},

	verifyCollisionBetweenPacGhost: function(){
		/*var a = this._blinky.getContentSize();
		var p = this._blinky.getPosition();
		var rect1 = cc.rect(p.x - a.width / 2, p.y - a.height / 2, a.width, a.height);

		var b = this._pac.getContentSize();
		var q = this._pac.getPosition();
		var rect2 = cc.rect(q.x - b.width / 2, q.y - b.height / 2, b.width, b.height);

		if (cc.rectIntersectsRect(rect1, rect2)){
			//this._pac.setDieAnimation();
	        //this._pac.getAnimation("die");
			this.removeChild(this._pac);
	        this.removeLives();
		}*/
	},

	verifiyGhostDirection: function(){
		for (var i = 0; i < decisionObjects.length; i++) {
            var dict = decisionObjects[i];
            if (!dict)
                break;

            var x = dict["x"];
            var y = dict["y"];
            var width = dict["width"];
            var height = dict["height"];

            var point1 = cc.p(x, y);
            var point2 = cc.p(width, height);

            cc.renderContext.lineWidth = 3;
            cc.renderContext.strokeStyle = "#ffffff";

            cc.drawingUtil.drawLine(cc.p(x, y), cc.p(x + width, y));
            cc.drawingUtil.drawLine(cc.p(x + width, y), cc.p(x + width, y + height));
            cc.drawingUtil.drawLine(cc.p(x + width, y + height), cc.p(x, y + height));
            cc.drawingUtil.drawLine(cc.p(x, y + height), cc.p(x, y));

            cc.renderContext.lineWidth = 1;

			var rect1 = cc.rect(point1.x, point1.y, point2.width, point2.height);

			/*var b = this._blinky.getContentSize();
			var q = this._blinky.getPosition();
			var rect2 = cc.rect(q.x - b.width / 2, q.y - b.height / 2, b.width, b.height);

			if (cc.rectIntersectsRect(rect1, rect2)){
				cc.log("colidiu ghost com parede colidiu ghost com parede colidiu ghost com parede colidiu ghost com parede");
				this._blinky.setPositionOnScreen("blinky", "up");
			}				*/

        }
	},

	fillScore: function(){
		for (var i = 0; i < scoreObjects.length; i++) {
            var dict = scoreObjects[i];
            if (!dict)
                break;

            var x = dict["x"];
            var y = dict["y"];

            var point = cc.p(x, y);

			this._score = cc.Sprite.create("res/images/score_6-4.png");
			map.addChild(this._score);
	        this._score.setPosition(point);
        }

	},

	verifiyCollisionBetweenPacScore: function(){
		for (var i = 0; i < scoreObjects.length; i++) {
            var dict = scoreObjects[i];
            if (!dict)
                break;

            var x = dict["x"];
            var y = dict["y"];

            var point = cc.p(x, y);

            this._score.setPosition(point);

            var a = this._score.getContentSize();
    		var p = this._score.getPosition();
    		var rect1 = cc.rect(p.x - a.width / 2, p.y - a.height / 2, a.width, a.height);

    		var b = this._pac.getContentSize();
    		var q = this._pac.getPosition();
    		var rect2 = cc.rect(q.x - b.width / 2, q.y - b.height / 2, b.width, b.height);

    		if (cc.rectIntersectsRect(rect1, rect2)){
    			map.removeChild(this._score);
    			this.plusScore();
    		}
        }
    },

	/*
	createBody: function ( position, shape, object, type, physics, group) {

        var bodyDef = new b2BodyDef();

		if (type == "dynamic")
			bodyDef.type = b2Body.b2_dynamicBody;

		if (type == "static")
			bodyDef.type = b2Body.b2_staticBody;

        bodyDef.position.Set( position.x / PTM_RATIO , position.y / PTM_RATIO );
        bodyDef.userData = object;
        bodyDef.bullet = true;

        shapeDef = new b2FixtureDef();
        shapeDef.shape = shape;

		if (group != null)

        shapeDef.filter.groupIndex = group;

		if (physics) {
			shapeDef.density = physics.density;
			shapeDef.friction = physics.friction;
			shapeDef.restitution = physics.restitution;
		}

        var body = world.CreateBody(bodyDef);
        body.CreateFixture(shapeDef);

        return body;

    },*/

});

var game = cc.Scene.extend({
    onEnter:function()
	{
        this._super();
        var layer = new gameLayer();
        layer.init();
        this.addChild(layer);
    }
});<commit_msg>[pacman1][Cocos2D] Get the score<commit_after>var screen = null;
var layer = null;
var spriteLives = [];

var lifeGame = {
	label: "LIVES",
	life: 2,
	positionX: 50
};

var scoreGame = {
	label: null,
	score: 0,
	text: "SCORE"
};

var LG = {KEYS: []};

/* Box 2D */
/*var world = null;
var b2Vec2 = Box2D.Common.Math.b2Vec2,
    b2BodyDef = Box2D.Dynamics.b2BodyDef,
    b2Body = Box2D.Dynamics.b2Body,
    b2FixtureDef = Box2D.Dynamics.b2FixtureDef,
    b2World = Box2D.Dynamics.b2World,
    b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape,
    b2Listener = Box2D.Dynamics.b2ContactListener;
	*/

var objects = null;

var gameLayer = cc.Layer.extend({
	spriteFrameCache: cc.SpriteFrameCache.getInstance(),
	gameOver: null,
	_pac: null,
	_blinky: null,
	_pinky: null,
	_inkey: null,
	_clyde: null,
	_score: null,
	map: null,

	init:function()
	{
		this._super();

		/* Configuracao do mundo Box 2D */
		//world = new b2World(new b2Vec2(0, 0), true);

		this.setKeyboardEnabled(true);

		map = cc.TMXTiledMap.create(tMap);
		//map.setPosition(cc.p(113, 50));
		this.addChild(map, 0, 1);

		var group = map.getObjectGroup("Camada de Objetos")
        objects = group.getObjects();

        var decisionGroup = map.getObjectGroup("Camada de Decisao");
        decisionObjects = decisionGroup.getObjects();

        scoreObjects = map.getObjectGroup("Score").getObjects();

		this._pac = new Pac();
        map.addChild(this._pac);
		//this.addChild(this._pac);
        this._pac.setPosition(new cc.Point(screen.width/2 - 110, screen.height/2 - 218));
        this._pac.setAnimation("pac", "left", SPRITE_SIZE, 2, "left");
        this._pac.getAnimation("left");
        //LG.KEYS[cc.KEY.left] = true;
        //this._pac.setPositionOnScreen(LG.KEYS[e]);
        //this._pac.setDynamicPosition('left');

		//lifeGame.life = 2;
		//scoreGame.score = 0;
		screen = cc.Director.getInstance().getWinSizeInPixels();
		livePositionX = 30;
		/*
		this._blinky = new Ghost();
		this._blinky.setGhost("blinky");
        map.addChild(this._blinky);
		//this.addChild(this._blinky);
        this._blinky.setPosition(new cc.Point(screen.width / 2 - 115, screen.height / 2 + 50));
        this._blinky.setAnimation("blinky", "up", SPRITE_SIZE, 2, "up");
        this._blinky.getAnimation("up");
        this._blinky.setPositionOnScreen("blinky", "right");
        */
        //this._blinky.setDynamicPosition("up");

		/*this._pinky = new Ghost();
		this._pinky.setGhost("pinky");
        map.addChild(this._pinky);
		//this.addChild(this._pinky);
        this._pinky.setPosition(new cc.Point(screen.width / 2 - 118, screen.height / 2 - 10));
        this._pinky.setAnimation("pinky", "up", SPRITE_SIZE, 2, "up");
        this._pinky.getAnimation("up");
        //this._pinky.setDynamicPosition("left");
        //this._pinky.setPositionOnScreen("pinky");

        this._inkey = new Ghost();
		this._inkey.setGhost("inkey");
        map.addChild(this._inkey);
		//this.addChild(this._inkey);
        this._inkey.setPosition(new cc.Point(screen.width / 2 - 150, screen.height / 2 - 10));
        this._inkey.setAnimation("inkey", "up", SPRITE_SIZE, 2, "up");
        this._inkey.getAnimation("up");
        //this._inkey.setDynamicPosition("down");
        //this._inkey.setPositionOnScreen("inkey");

        this._clyde = new Ghost();
		this._clyde.setGhost("clyde");
        map.addChild(this._clyde);
		//this.addChild(this._clyde);
        this._clyde.setPosition(new cc.Point(screen.width / 2 - 86, screen.height / 2 - 10));
        this._clyde.setAnimation("clyde", "up", SPRITE_SIZE, 2, "up");
        this._clyde.getAnimation("up");
        //this._clyde.setDynamicPosition();
        //this._clyde.setPositionOnScreen("clyde");
		*/
		if (lifeGame.life == 2){
			this.addLives();
			this.addScore();
		}

		this.fillScore();
		//this.schedule(this.onClick, 3);
		this.scheduleUpdate();

		return true;
	},

	update: function(){
		cc.log("game update");
		this.verifiyCollisionBetweenPacScore();
		this.verifyCollisionBetweenPacMap();
		this.verifyCollisionBetweenPacGhost();
		this.verifiyGhostDirection();
	},

	addLives: function()
	{
		lifeGame.label = cc.LabelTTF.create("LIVES", "fontName", 20);
		lifeGame.label.setPosition( new cc.Point(screen.width/2 + 200, screen.height/2 - 350) );
		this.addChild( lifeGame.label );
		cc.log(lifeGame.life);
		for(var i = 0; i < lifeGame.life; i++)
		{
			spriteLives[i] = cc.Sprite.create(sPacLife);
			spriteLives[i].setPosition(screen.width/2 + 200 + lifeGame.positionX, screen.height/2 - 350);
            this.addChild( spriteLives[i] );
			lifeGame.positionX += 20;
		}
	},

	removeLives: function()
	{
		lifeGame.life--;
		this.removeChild( spriteLives[lifeGame.life] );
		if (lifeGame.life != 0){
			this.init();
		}
		else{
			this.gameOver = new losing();
	        this.addChild( this.gameOver );
			cc.Director.getInstance().replaceScene(cc.TransitionFade.create(10,new highScore()));
		}
	},

	addScore:function()
	{
		scoreGame.label = cc.LabelTTF.create(scoreGame.text + " " + scoreGame.score, "fontName", 20);
		scoreGame.label.setPosition(new cc.Point(screen.width/2 - 300, screen.height/2 - 350) );
		this.addChild( scoreGame.label );

    },

	plusScore: function()
	{
		scoreGame.score += 10;
		scoreGame.label.setString(scoreGame.text + " " + scoreGame.score);
	},

	onKeyDown:function (e) {
		cc.log("pressionou a tecla");
        LG.KEYS[e] = true;
        this._pac.setPositionOnScreen(e);

    },

    onKeyUp:function (e) {
        LG.KEYS[e] = false;
    },

	verifyCollisionBetweenPacMap: function(){
		for (var i = 0; i < objects.length; i++) {
            var dict = objects[i];
            if (!dict)
                break;

            var x = dict["x"];
            var y = dict["y"];
            var width = dict["width"];
            var height = dict["height"];

            point1 = cc.p(x, y);
            point2 = cc.p(width, height);

                /*
            var react = cc.rect(x, y,
                        width, height);

            if(cc.rectIntersectsRect(react, this._pac.getBoundingBoxToWorld())){
            	cc.log("colidiu colidiu colidiu colidiu colidiu colidiu colidiu colidiu");
            	if(this._pac.xVelocity != 0){
            		this._pac.xVelocity = 0;
                }else if(this._pac.yVelocity != 0){
                	this._pac.yVelocity = 0;
                }
            }

            */

            cc.log("verificando colisao");

            cc.renderContext.lineWidth = 3;
            cc.renderContext.strokeStyle = "#ffffff";

            cc.drawingUtil.drawLine(cc.p(x, y), cc.p(x + width, y));
            cc.drawingUtil.drawLine(cc.p(x + width, y), cc.p(x + width, y + height));
            cc.drawingUtil.drawLine(cc.p(x + width, y + height), cc.p(x, y + height));
            cc.drawingUtil.drawLine(cc.p(x, y + height), cc.p(x, y));

            cc.renderContext.lineWidth = 1;

			var rect1 = cc.rect(x, y, width, height);

			var b = this._pac.getContentSize();
			var q = this._pac.getPosition();
			var rect2 = cc.rect(q.x, q.y, b.width, b.height);

			if (cc.rectIntersectsRect(rect1, rect2)){
				cc.log("colidiu colidiu colidiu colidiu");
				if(this._pac.xVelocity != 0){
					this._pac.xVelocity = 0;
                }else if(this._pac.yVelocity != 0){
					this._pac.yVelocity = 0;
                }
			}

        }
	},

	verifyCollisionBetweenPacGhost: function(){
		/*var a = this._blinky.getContentSize();
		var p = this._blinky.getPosition();
		var rect1 = cc.rect(p.x - a.width / 2, p.y - a.height / 2, a.width, a.height);

		var b = this._pac.getContentSize();
		var q = this._pac.getPosition();
		var rect2 = cc.rect(q.x - b.width / 2, q.y - b.height / 2, b.width, b.height);

		if (cc.rectIntersectsRect(rect1, rect2)){
			//this._pac.setDieAnimation();
	        //this._pac.getAnimation("die");
			this.removeChild(this._pac);
	        this.removeLives();
		}*/
	},

	verifiyGhostDirection: function(){
		for (var i = 0; i < decisionObjects.length; i++) {
            var dict = decisionObjects[i];
            if (!dict)
                break;

            var x = dict["x"];
            var y = dict["y"];
            var width = dict["width"];
            var height = dict["height"];

            var point1 = cc.p(x, y);
            var point2 = cc.p(width, height);

            cc.renderContext.lineWidth = 3;
            cc.renderContext.strokeStyle = "#ffffff";

            cc.drawingUtil.drawLine(cc.p(x, y), cc.p(x + width, y));
            cc.drawingUtil.drawLine(cc.p(x + width, y), cc.p(x + width, y + height));
            cc.drawingUtil.drawLine(cc.p(x + width, y + height), cc.p(x, y + height));
            cc.drawingUtil.drawLine(cc.p(x, y + height), cc.p(x, y));

            cc.renderContext.lineWidth = 1;

			var rect1 = cc.rect(point1.x, point1.y, point2.width, point2.height);

			/*var b = this._blinky.getContentSize();
			var q = this._blinky.getPosition();
			var rect2 = cc.rect(q.x - b.width / 2, q.y - b.height / 2, b.width, b.height);

			if (cc.rectIntersectsRect(rect1, rect2)){
				cc.log("colidiu ghost com parede colidiu ghost com parede colidiu ghost com parede colidiu ghost com parede");
				this._blinky.setPositionOnScreen("blinky", "up");
			}				*/

        }
	},

	fillScore: function(){
		for (var i = 0; i < scoreObjects.length; i++) {
            var dict = scoreObjects[i];
            if (!dict)
                break;

            var x = dict["x"];
            var y = dict["y"];

            var point = cc.p(x, y);

			this._score = cc.Sprite.create("res/images/score_6-4.png");
			map.addChild(this._score);
	        this._score.setPosition(point);
        }

	},

	verifiyCollisionBetweenPacScore: function(){
		for (var i = 0; i < scoreObjects.length; i++) {
            var dict = scoreObjects[i];
            if (!dict)
                break;

            var x = dict["x"];
            var y = dict["y"];
            var width = dict["width"];
            var height = dict["height"];

            var point = cc.p(x, y);

            this._score.setPosition(point);

			var a = this._pac.getContentSize();
    		var p = this._pac.getPosition();
			var rect1 = cc.rect(p.x, p.y, a.width, a.height);

    		var b = this._pac.getContentSize();
    		var q = this._pac.getPosition();
			var rect2 = cc.rect(q.x, q.y, b.width, b.height);

    		if (cc.rectIntersectsRect(rect1, rect2)){
    			map.removeChild(this._score);
    			this.plusScore();
    		}
        }
    },

	/*
	createBody: function ( position, shape, object, type, physics, group) {

        var bodyDef = new b2BodyDef();

		if (type == "dynamic")
			bodyDef.type = b2Body.b2_dynamicBody;

		if (type == "static")
			bodyDef.type = b2Body.b2_staticBody;

        bodyDef.position.Set( position.x / PTM_RATIO , position.y / PTM_RATIO );
        bodyDef.userData = object;
        bodyDef.bullet = true;

        shapeDef = new b2FixtureDef();
        shapeDef.shape = shape;

		if (group != null)

        shapeDef.filter.groupIndex = group;

		if (physics) {
			shapeDef.density = physics.density;
			shapeDef.friction = physics.friction;
			shapeDef.restitution = physics.restitution;
		}

        var body = world.CreateBody(bodyDef);
        body.CreateFixture(shapeDef);

        return body;

    },*/

});

var game = cc.Scene.extend({
    onEnter:function()
	{
        this._super();
        var layer = new gameLayer();
        layer.init();
        this.addChild(layer);
    }
});<|endoftext|>


<commit_before>#!/usr/local/bin/node --harmony

var co = require('co');

if (process.argv.length != 4)
	throw 'Usage logreg-file.js file iterations'

var file = process.argv[2];
var iterations = process.argv[3];

var ugrid = require('../../../ugrid/lib/ugrid-context.js')();
var LogisticRegression = require('../../../ugrid/lib/ugrid-ml.js').LogisticRegression;

co(function *() {
	yield ugrid.init();

	var points = ugrid.textFile(file).map(function (e) {
		var tmp = e.split(' ').map(parseFloat);
		return [tmp.shift(), tmp];
	}).persist();

	var N = yield points.count();	// a recuperer dans la librairie ml
	var D = 16;						// a recuperer dans le dataset

	var model = new LogisticRegression(points, D, N);

	yield model.train(iterations);

	console.log(model.w);

	ugrid.end();
}).catch(function (err) {
	console.error(err.stack);
	process.exit(1);
});
<commit_msg>fix logreg-file.js to use new syntax<commit_after>#!/usr/local/bin/node --harmony

var co = require('co');
var ugrid = require('../..');

if (process.argv.length != 4)
	throw 'Usage logreg-file.js file iterations'

var file = process.argv[2];
var iterations = process.argv[3];

co(function *() {
	var uc = yield ugrid.context();

	var points = uc.textFile(file).map(function (e) {
		var tmp = e.split(' ').map(parseFloat);
		return [tmp.shift(), tmp];
	}).persist();

	var N = yield points.count();	// a recuperer dans la librairie ml
	var D = 16;						// a recuperer dans le dataset

	var model = new ugrid.ml.LogisticRegression(points, D, N);

	yield model.train(iterations);

	console.log(model.w);

	uc.end();
}).catch(ugrid.onError);
<|endoftext|>


<commit_before>/*
 *  Copyright 2014 TWO SIGMA OPEN SOURCE, LLC
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

/**
 * Node eval plugin
 * For creating and configuring evaluators that evaluate Javascript code on
 *   a remote node server and update code cell results.
 */
define(function(require, exports, module) {
    'use strict';
    var PLUGIN_ID = "Node";
    var PLUGIN_NAME = "Node";
    var COMMAND = "node/nodePlugin";

    var serviceBase = null;

    var nodeProto = {
        pluginName: PLUGIN_NAME,
        cmMode: "javascript",
        background: "#dbecb5",
        bgColor: "#8EC453",
        fgColor: "#FFFFFF",
        borderColor: "",
        shortName: "N",
        tooltip: "Node is a JavaScript runtime built on Chrome's V8 engine, running on the server.",
        newShell: function (shellID, cb, ecb) {
            var self = this;

            if (!shellID) {
                shellID = "";
            }
            //verify server is up and running before a new shell call is attempted
            function checkNodeServerRunning() {
              bkHelper.httpGet(bkHelper.serverUrl(serviceBase + "/pulse"))
                .error(function(){
                    setTimeout(function () {
                        checkNodeServerRunning();
                    }, 2000)
                }).success(function(){
                  bkHelper.httpPost(bkHelper.serverUrl(serviceBase + "/shell"), {shellid: shellID})
                    .success(function(response){
                        shellID = response.shellID;
                        cb(shellID);
                    }).error(function () {
                        console.log("failed to create shell", arguments);
                        ecb("failed to create shell");
                    });
                })
            }
            checkNodeServerRunning();
        },
        evaluate: function (code, modelOutput) {
          var deferred = Q.defer();
            var self = this;
            bkHelper.setupProgressOutput(modelOutput);
            bkHelper.httpPost(bkHelper.serverUrl(serviceBase + "/evaluate"), {shellID: self.settings.shellID, code: encodeURIComponent(code)})
            .success(function(ret) {
                modelOutput.result = JSON.parse(ret);
                bkHelper.refreshRootScope();
                deferred.resolve(ret);
            }).error(function(xhr, textStatus, error) {
              var errorText = xhr.status !== 502 ? xhr.responseText : error;
              modelOutput.result = {
                    type: "BeakerDisplay",
                    innertype: "Error",
                    object: errorText
                };
                deferred.reject(errorText);
            });
          return deferred.promise;
        },
        autocomplete: function (code, cpos, cb) {
            console.log("Autocomplete Called: Not implemented");
        },
        addModulePath: function (callback) {
          if(!this.settings.modulePath) {
            if (callback) {
              callback();
            }
            return;
          }
          bkHelper.showLanguageManagerSpinner(PLUGIN_NAME);
          bkHelper.httpPost(bkHelper.serverUrl(serviceBase + '/add-module-path'), {
            shellId: this.settings.shellID,
            path: this.settings.modulePath
          }).success(function() {
            bkHelper.hideLanguageManagerSpinner();
            if (callback) {
              callback();
            }
          }).error(function(err) {
            bkHelper.hideLanguageManagerSpinner(err);
            bkHelper.show1ButtonModal('ERROR: ' + err, 'Failed to add module path');
          });
        },
        setSessionId: function (callback) {
          return bkHelper.httpPost(bkHelper.serverUrl(serviceBase + '/session'), {
            shellID: this.settings.shellID,
            session: bkHelper.getSessionId()
          }).success(function () {
            if (callback) {
              callback();
            }
          });
        },
        exit: function (cb) {
            console.log("Exit Called");
            var self = this;
            bkHelper.httpPost(bkHelper.serverUrl(serviceBase + "/rest/node/exit"), { shellID: self.settings.shellID })
            .success(cb);
        },
        spec: {
          modulePath: {type: 'settableString', action: 'addModulePath', name: 'Modules path'}
        }
    };

    var shellReadyDeferred = bkHelper.newDeferred();
    var init = function () {
      bkHelper.locatePluginService(PLUGIN_ID, {
        command: COMMAND,
        startedIndicator: "Server Starting",
        recordOutput: "true"
        }).success(function (ret) {
            serviceBase = ret;
            var NodeShell = function (settings, doneCB, ecb) {
                var self = this;
                var setShellIdCB = function (id) {
                    if (id !== settings.shellID) {
                        console.log("A new Node shell was created.");
                    }
                    settings.shellID = id;
                    self.settings = settings;
                    self.setSessionId(function () {
                      self.addModulePath(function () {
                        if (doneCB) {
                          doneCB(self);
                        }
                      });
                    });
                };
                if (!settings.shellID) {
                    settings.shellID = "";
                }
                var newShellErrorCb = function(reason) {
                  if (ecb) {
                    ecb(reason);
                  }
                };
                this.newShell(settings.shellID, setShellIdCB, newShellErrorCb);
                this.perform = function (what) {
                    var action = this.spec[what].action;
                    this[action]();
                };
            };
            NodeShell.prototype = nodeProto;
            shellReadyDeferred.resolve(NodeShell);
        }).error(function () {
            shellReadyDeferred.reject("failed to locate plugin service");
            console.log("process start failed", arguments);
        });
    };
    init();

  exports.getEvaluatorFactory = function() {
    return shellReadyDeferred.promise.then(function(Shell) {
      return {
        create: function(settings) {
          var deferred = bkHelper.newDeferred();
          new Shell(settings, function(shell) {
            deferred.resolve(shell);
          }, function(reason) {
            deferred.reject(reason);
          });
          return deferred.promise;
        }
      };
    },
    function(err) { return err; });
  };

    exports.name = PLUGIN_NAME;
});
<commit_msg>issue #4933 "autotranslation to node broken" -- FIXED (need to test)<commit_after>/*
 *  Copyright 2014 TWO SIGMA OPEN SOURCE, LLC
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

/**
 * Node eval plugin
 * For creating and configuring evaluators that evaluate Javascript code on
 *   a remote node server and update code cell results.
 */
define(function(require, exports, module) {
    'use strict';
    var PLUGIN_ID = "Node";
    var PLUGIN_NAME = "Node";
    var COMMAND = "node/nodePlugin";

    var serviceBase = null;

    var nodeProto = {
        pluginName: PLUGIN_NAME,
        cmMode: "javascript",
        background: "#dbecb5",
        bgColor: "#8EC453",
        fgColor: "#FFFFFF",
        borderColor: "",
        shortName: "N",
        tooltip: "Node is a JavaScript runtime built on Chrome's V8 engine, running on the server.",
        newShell: function (shellID, cb, ecb) {
            var self = this;

            if (!shellID) {
                shellID = "";
            }
            //verify server is up and running before a new shell call is attempted
            function checkNodeServerRunning() {
              bkHelper.httpGet(bkHelper.serverUrl(serviceBase + "/pulse"))
                .error(function(){
                    setTimeout(function () {
                        checkNodeServerRunning();
                    }, 2000)
                }).success(function(){
                  bkHelper.httpPost(bkHelper.serverUrl(serviceBase + "/shell"), {shellid: shellID})
                    .success(function(response){
                        shellID = response.shellID;
                        cb(shellID);
                    }).error(function () {
                        console.log("failed to create shell", arguments);
                        ecb("failed to create shell");
                    });
                })
            }
            checkNodeServerRunning();
        },
        evaluate: function (code, modelOutput) {
          var deferred = Q.defer();
            var self = this;
            bkHelper.setupProgressOutput(modelOutput);
            bkHelper.httpPost(bkHelper.serverUrl(serviceBase + "/evaluate"), {shellID: self.settings.shellID, code: encodeURIComponent(code)})
            .success(function(ret) {
                modelOutput.result = ret;
                bkHelper.refreshRootScope();
                deferred.resolve(ret);
            }).error(function(xhr, textStatus, error) {
              var errorText = xhr.status !== 502 ? xhr.responseText : error;
              modelOutput.result = {
                    type: "BeakerDisplay",
                    innertype: "Error",
                    object: errorText
                };
                deferred.reject(errorText);
            });
          return deferred.promise;
        },
        autocomplete: function (code, cpos, cb) {
            console.log("Autocomplete Called: Not implemented");
        },
        addModulePath: function (callback) {
          if(!this.settings.modulePath) {
            if (callback) {
              callback();
            }
            return;
          }
          bkHelper.showLanguageManagerSpinner(PLUGIN_NAME);
          bkHelper.httpPost(bkHelper.serverUrl(serviceBase + '/add-module-path'), {
            shellId: this.settings.shellID,
            path: this.settings.modulePath
          }).success(function() {
            bkHelper.hideLanguageManagerSpinner();
            if (callback) {
              callback();
            }
          }).error(function(err) {
            bkHelper.hideLanguageManagerSpinner(err);
            bkHelper.show1ButtonModal('ERROR: ' + err, 'Failed to add module path');
          });
        },
        setSessionId: function (callback) {
          return bkHelper.httpPost(bkHelper.serverUrl(serviceBase + '/session'), {
            shellID: this.settings.shellID,
            session: bkHelper.getSessionId()
          }).success(function () {
            if (callback) {
              callback();
            }
          });
        },
        exit: function (cb) {
            console.log("Exit Called");
            var self = this;
            bkHelper.httpPost(bkHelper.serverUrl(serviceBase + "/rest/node/exit"), { shellID: self.settings.shellID })
            .success(cb);
        },
        spec: {
          modulePath: {type: 'settableString', action: 'addModulePath', name: 'Modules path'}
        }
    };

    var shellReadyDeferred = bkHelper.newDeferred();
    var init = function () {
      bkHelper.locatePluginService(PLUGIN_ID, {
        command: COMMAND,
        startedIndicator: "Server Starting",
        recordOutput: "true"
        }).success(function (ret) {
            serviceBase = ret;
            var NodeShell = function (settings, doneCB, ecb) {
                var self = this;
                var setShellIdCB = function (id) {
                    if (id !== settings.shellID) {
                        console.log("A new Node shell was created.");
                    }
                    settings.shellID = id;
                    self.settings = settings;
                    self.setSessionId(function () {
                      self.addModulePath(function () {
                        if (doneCB) {
                          doneCB(self);
                        }
                      });
                    });
                };
                if (!settings.shellID) {
                    settings.shellID = "";
                }
                var newShellErrorCb = function(reason) {
                  if (ecb) {
                    ecb(reason);
                  }
                };
                this.newShell(settings.shellID, setShellIdCB, newShellErrorCb);
                this.perform = function (what) {
                    var action = this.spec[what].action;
                    this[action]();
                };
            };
            NodeShell.prototype = nodeProto;
            shellReadyDeferred.resolve(NodeShell);
        }).error(function () {
            shellReadyDeferred.reject("failed to locate plugin service");
            console.log("process start failed", arguments);
        });
    };
    init();

  exports.getEvaluatorFactory = function() {
    return shellReadyDeferred.promise.then(function(Shell) {
      return {
        create: function(settings) {
          var deferred = bkHelper.newDeferred();
          new Shell(settings, function(shell) {
            deferred.resolve(shell);
          }, function(reason) {
            deferred.reject(reason);
          });
          return deferred.promise;
        }
      };
    },
    function(err) { return err; });
  };

    exports.name = PLUGIN_NAME;
});
<|endoftext|>


<commit_before>const React = require('react-native');
const Camera = require('../base');
const TwoSideMenus = require('./two-side-menus');

const {
  Dimensions,
  StyleSheet,
  Component,
  View,
  PanResponder,
  Animated,
  TouchableWithoutFeedback
} = React;

const window = Dimensions.get('window');

const styles = StyleSheet.create({
  menuWrapper: {
    position: 'absolute',
    top: 0,
    left: 0,
    width: window.width,
    height: window.height,
    backgroundColor: 'transparent'
  },
  view: {
    position: 'absolute',
    left: 0,
    top: 0,
    backgroundColor: 'transparent',
    width: window.width,
    height: window.height
  },
  overlay: {
    position: 'absolute',
    left: 0, // this value will be modified by this._position in base canera class
    top: 0, // this value will be modified by this._position in base canera class
    backgroundColor: 'transparent',
    width: window.width,
    height: window.height
  }
});

const animationFunction = (prop, value) => {
  return Animated.timing(
    prop,
    {
      toValue: value,
      duration: 300
    }
  );
};

const animationStyle = (value) => {
  return {
    transform: [
      {
        translateX: value,
      }
    ],
  };
};

class CameraWith2SideMenus extends Camera {
  constructor(props, context) {
    super(props, context);

    //////////////////////////////
    // Menu
    this._responder = null;
    this._leftMenuOpacity = new Animated.Value(0);
    this._rightMenuOpacity = new Animated.Value(0);
    this._overlayOpacity = new Animated.Value(0);

    this._value = new Animated.Value(0);
    this._prevValue = 0;

    this._enabledLeftMenu = true;
    this._enabledRightMenu = true;

    this._isOpen = false;
  }

  _handleMoveShouldSetPanResponder(e, gesture) {
    const {
      userProps: {
        LeftMenu, RightMenu, toleranceX, toleranceY
      }
    } = this.props;

    const dx = gesture.dx;
    const dy = gesture.dy;

    //in these two conditions we are checking
    // - which side we are trying to show
    // - does the component for that menu available
    // - has some one disable the menu by calling enableMenu
    if (dx > 0 && (!LeftMenu || !this._enabledLeftMenu)) {
      //we are not letting slider over to left if left menu doesn't pass
      console.log(`${dx} > 0 && (!${LeftMenu} || !${this._enabledLeftMenu})`);
      return false;
    } else if (dx < 0 && (!RightMenu || !this._enabledRightMenu)) {
      //we are not letting slider over to right if right menu doesn't pass
      console.log('wow2');
      return false;
    }

    return (
      Math.round(Math.abs(dx)) > toleranceX &&
      Math.round(Math.abs(dy)) < toleranceY
    );
  }

  _handlePanResponderMove(e, gesture) {
    const {
      userProps: {
        openLeftMenuOffset,
        openRightMenuOffset
      }
    } = this.props;
    let value = this._prevValue + gesture.dx;

    if (value > 0) {
      value = value < openLeftMenuOffset? value : openLeftMenuOffset;
      this._showMenu('left');
    } else {
      value = value > openRightMenuOffset? value : openRightMenuOffset;
      this._showMenu('right');
    }

    this._value.setValue(value);
  }

  _handlePanResponderEnd(e, gesture) {
    const { userProps: { offsetUntilOpen } } = this.props;
    //i need to detect whether I need to open or close the menu on any sides.
    const dx = gesture.dx;
    const absDx = Math.abs(dx);

    if (absDx > offsetUntilOpen && !this._isOpen) {
      if (dx < 0) {
        this.openMenu('right');
      } else {
        this.openMenu('left');
      }
    } else {
      this.closeMenu();
    }
  }

  _wrappedMenuController(sceneAsChild) {
    const { userProps: { gestures } } = this.props;
    const panHandlers = gestures? this._responder.panHandlers : {};
    return (
      <Animated.View
        style={[styles.view, animationStyle(this._value)]}
        {...panHandlers}>
        {sceneAsChild}
        {this._renderOverlay()}
      </Animated.View>
    );
  }

  _renderOverlay() {
    const value = this._position.__getValue();
    return (
      <Animated.View style={[styles.overlay, { opacity: this._overlayOpacity, top: -value.y, left: -value.x }]}>
        <TouchableWithoutFeedback onPress={() => { this.closeMenu() }}>
          <View style={{ flex: 1, backgroundColor: 'transparent' }}/>
        </TouchableWithoutFeedback>
      </Animated.View>
    );
  }

  _showMenu(side) {
    let leftOpacityValue = 0,
        rightOpacityMenu = 0;

    if (side == 'left') {
      leftOpacityValue = 1;
      rightOpacityMenu = 0;
    } else if (side == 'right') {
      leftOpacityValue = 0;
      rightOpacityMenu = 1;
    }

    this._leftMenuOpacity.setValue(leftOpacityValue);
    this._rightMenuOpacity.setValue(rightOpacityMenu);
  }

  enableMenu(side, enable) {
    switch(side) {
      case 'left':
        this._enabledLeftMenu = !!enable;
        break;
      case 'right':
        this._enabledRightMenu = !!enable;
        break;
      default:
        //do nothing
    }
  }

  openMenu(side) {
    const {
      userProps: {
        openLeftMenuOffset,
        openRightMenuOffset
      }
    } = this.props;

    let toValue;
    if (side === 'left') {
      toValue = openLeftMenuOffset;
    } else {
      toValue = openRightMenuOffset;
    }

    this._showMenu(side);

    animationFunction(this._value, toValue).start(() => {
      this._prevValue = this._value.__getValue();
      //activate overaly
      this._overlayOpacity.setValue(1);

      this._isOpen = true;
    });
  }

  closeMenu() {
    animationFunction(this._value, 0).start(() => {
      this._prevValue = this._value.__getValue();
      //deactivate overlay
      this._overlayOpacity.setValue(0);
      //hide both menus
      this._showMenu();

      this._isOpen = false;
    });
  }

  renderBack() {
    const { userProps: { LeftMenu, RightMenu } } = this.props;

    return (
      <View style={styles.menuWrapper}>
        <LeftMenu key="leftMenu" ref="leftMenu"/>
        <RightMenu key="rightMenu" ref="rightMenu"/>
      </View>
    );
  }

  renderScenes(scenes) {
    const lastIndex = React.Children.count(scenes) - 1;
    return React.Children.map(scenes, (scene, index) => {
      if (index == lastIndex) {
        return this._wrappedMenuController(scene);
      }
      return scene;
    });
  }

  renderGlass() {
    return null;
  }

  componentWillMount() {
    this._responder = PanResponder.create({
      onStartShouldSetResponderCapture: () => true,
      onMoveShouldSetPanResponder: this._handleMoveShouldSetPanResponder.bind(this),
      onPanResponderMove: this._handlePanResponderMove.bind(this),
      onPanResponderRelease: this._handlePanResponderEnd.bind(this),
    });
  }
}

module.exports = CameraWith2SideMenus;
<commit_msg>cleaned up code<commit_after>const React = require('react-native');
const Camera = require('../base');
const TwoSideMenus = require('./two-side-menus');

const {
  Dimensions,
  StyleSheet,
  Component,
  View,
  PanResponder,
  Animated,
  TouchableWithoutFeedback
} = React;

const window = Dimensions.get('window');

const styles = StyleSheet.create({
  menuWrapper: {
    position: 'absolute',
    top: 0,
    left: 0,
    width: window.width,
    height: window.height,
    backgroundColor: 'transparent'
  },
  view: {
    position: 'absolute',
    left: 0,
    top: 0,
    backgroundColor: 'transparent',
    width: window.width,
    height: window.height
  },
  overlay: {
    position: 'absolute',
    left: 0, // this value will be modified by this._position in base canera class
    top: 0, // this value will be modified by this._position in base canera class
    backgroundColor: 'transparent',
    width: window.width,
    height: window.height
  }
});

const animationFunction = (prop, value) => {
  return Animated.timing(
    prop,
    {
      toValue: value,
      duration: 300
    }
  );
};

const animationStyle = (value) => {
  return {
    transform: [
      {
        translateX: value,
      }
    ],
  };
};

class CameraWith2SideMenus extends Camera {
  constructor(props, context) {
    super(props, context);

    //////////////////////////////
    // Menu
    this._responder = null;
    this._leftMenuOpacity = new Animated.Value(0);
    this._rightMenuOpacity = new Animated.Value(0);
    this._overlayOpacity = new Animated.Value(0);

    this._value = new Animated.Value(0);
    this._prevValue = 0;

    this._enabledLeftMenu = true;
    this._enabledRightMenu = true;

    this._isOpen = false;
  }

  _handleMoveShouldSetPanResponder(e, gesture) {
    const {
      userProps: {
        LeftMenu, RightMenu, toleranceX, toleranceY
      }
    } = this.props;

    const dx = gesture.dx;
    const dy = gesture.dy;

    //in these two conditions we are checking
    // - which side we are trying to show
    // - does the component for that menu available
    // - has some one disable the menu by calling enableMenu
    if (dx > 0 && (!LeftMenu || !this._enabledLeftMenu)) {
      //we are not letting slider over to left if left menu doesn't pass
      console.log(`${dx} > 0 && (!${LeftMenu} || !${this._enabledLeftMenu})`);
      return false;
    } else if (dx < 0 && (!RightMenu || !this._enabledRightMenu)) {
      //we are not letting slider over to right if right menu doesn't pass
      console.log('wow2');
      return false;
    }

    return (
      Math.round(Math.abs(dx)) > toleranceX &&
      Math.round(Math.abs(dy)) < toleranceY
    );
  }

  _handlePanResponderMove(e, gesture) {
    const {
      userProps: {
        openLeftMenuOffset,
        openRightMenuOffset
      }
    } = this.props;
    let value = this._prevValue + gesture.dx;

    if (value > 0) {
      value = value < openLeftMenuOffset? value : openLeftMenuOffset;
      this._showMenu('left');
    } else {
      value = value > openRightMenuOffset? value : openRightMenuOffset;
      this._showMenu('right');
    }

    this._value.setValue(value);
  }

  _handlePanResponderEnd(e, gesture) {
    const { userProps: { offsetUntilOpen } } = this.props;
    //i need to detect whether I need to open or close the menu on any sides.
    const dx = gesture.dx;
    const absDx = Math.abs(dx);

    if (absDx > offsetUntilOpen && !this._isOpen) {
      if (dx < 0) {
        this.openMenu('right');
      } else {
        this.openMenu('left');
      }
    } else {
      this.closeMenu();
    }
  }

  _wrappedMenuController(sceneAsChild) {
    const { userProps: { gestures } } = this.props;
    const panHandlers = gestures? this._responder.panHandlers : {};
    return (
      <Animated.View
        style={[styles.view, animationStyle(this._value)]}
        {...panHandlers}>
        {sceneAsChild}
        {this._renderOverlay()}
      </Animated.View>
    );
  }

  _renderOverlay() {
    const value = this._position.__getValue();
    return (
      <Animated.View style={[styles.overlay, { opacity: this._overlayOpacity, top: -value.y, left: -value.x }]}>
        <TouchableWithoutFeedback onPress={() => { this.closeMenu() }}>
          <View style={{ flex: 1, backgroundColor: 'transparent' }}/>
        </TouchableWithoutFeedback>
      </Animated.View>
    );
  }

  _showMenu(side) {
    let leftOpacityValue = 0,
        rightOpacityMenu = 0;

    if (side == 'left') {
      leftOpacityValue = 1;
      rightOpacityMenu = 0;
    } else if (side == 'right') {
      leftOpacityValue = 0;
      rightOpacityMenu = 1;
    }

    this._leftMenuOpacity.setValue(leftOpacityValue);
    this._rightMenuOpacity.setValue(rightOpacityMenu);
  }

  enableMenu(side, enable) {
    switch(side) {
      case 'left':
        this._enabledLeftMenu = !!enable;
        break;
      case 'right':
        this._enabledRightMenu = !!enable;
        break;
      default:
        //do nothing
    }
  }

  openMenu(side) {
    const {
      userProps: {
        openLeftMenuOffset,
        openRightMenuOffset
      }
    } = this.props;

    let toValue;
    if (side === 'left') {
      toValue = openLeftMenuOffset;
    } else {
      toValue = openRightMenuOffset;
    }

    this._showMenu(side);

    animationFunction(this._value, toValue).start(() => {
      this._prevValue = this._value.__getValue();
      //activate overaly
      this._overlayOpacity.setValue(1);

      this._isOpen = true;
    });
  }

  closeMenu() {
    animationFunction(this._value, 0).start(() => {
      this._prevValue = this._value.__getValue();
      //deactivate overlay
      this._overlayOpacity.setValue(0);
      //hide both menus
      this._showMenu();

      this._isOpen = false;
    });
  }

  renderBack() {
    const { userProps: { LeftMenu, RightMenu } } = this.props;

    return (
      <View style={styles.menuWrapper}>
        <LeftMenu key="leftMenu" ref="leftMenu"/>
        <RightMenu key="rightMenu" ref="rightMenu"/>
      </View>
    );
  }

  renderScenes(scenes) {
    const lastIndex = React.Children.count(scenes) - 1;
    return React.Children.map(scenes, (scene, index) => {
      if (index == lastIndex) {
        return this._wrappedMenuController(scene);
      }
      return scene;
    });
  }

  componentWillMount() {
    this._responder = PanResponder.create({
      onStartShouldSetResponderCapture: () => true,
      onMoveShouldSetPanResponder: this._handleMoveShouldSetPanResponder.bind(this),
      onPanResponderMove: this._handlePanResponderMove.bind(this),
      onPanResponderRelease: this._handlePanResponderEnd.bind(this),
    });
  }
}

module.exports = CameraWith2SideMenus;
<|endoftext|>


<commit_before>var config = require(__dirname+'/../config.json');
var _ = require('lodash');
var Q = require('q');
var leaveWalletService = require('../services/leaveWallet.service');
var appConfigService = require('../services/appconfig.service');
var leaveWalletService = require('../services/leaveWallet.service');
var mongo = require('mongoskin');
var db = mongo.db(config.connectionString, { native_parser: true });
db.bind('users');
db.bind('timesheets');

var acquire_leaves_month = 0;
var nowDate = new Date(2019, 3, 1);
var month = nowDate.getMonth() + 1;
var yearMonth = nowDate.getFullYear()+"-"+String(month<10?"0"+month:month);
var yearMonthNumber = nowDate.getFullYear()+String(month<10?"0"+month:month);
var financialYear = (month>=4)?nowDate.getFullYear():nowDate.getFullYear()-1;

appConfigService.getSettings().then(function(response){
    _.each(response, function(item){
        if(item.keyName == "acquire_leaves_month"){
            acquire_leaves_month = item.keyVal;
        }
    });

    db.users.find({isActive: true}).toArray(function(err, users) {
        _.each(users, function (userObj) {
            if(userObj.joinDate){
                updateUserAcquireLeaves(userObj, acquire_leaves_month);
            }
        });
    });
}).catch(function(errors){

});

let updateUserAcquireLeaves = async function(userObj, acquire_leaves_month){
    var acquire_leaves = 0.00;
    joinDate = new Date(userObj.joinDate);
    var middleDate = new Date(nowDate.getFullYear(), nowDate.getMonth(), 15);

    //joinDate = new Date(joinDate.getTime() + (60000 * 330));
    if(nowDate>joinDate && (month == 10 || (month == 4 && nowDate.getFullYear()>joinDate.getFullYear())) ){
        acquire_leaves = 1.00;
    }else if(nowDate.getFullYear()==joinDate.getFullYear() && month <= 9 && month == (joinDate.getMonth()+1) ){
        acquire_leaves = 1.00;
    }else if(nowDate.getFullYear()==joinDate.getFullYear() && month <= 9 && month == (joinDate.getMonth()+2) && joinDate.getDate()>=15){
        acquire_leaves = 1.00;
    }
    acquire_leaves += parseFloat(acquire_leaves_month);

    if(middleDate>joinDate){
        var leaveWalletData = {
            userId: userObj._id,
            yearMonth: yearMonth,
            yearMonthNumber: yearMonthNumber,
            accruedLeaves: acquire_leaves
        };

        await leaveWalletService.saveMonthlyLeaves(leaveWalletData).then(function(response){
            console.log("EMP ID", userObj.employeeId, " ", acquire_leaves);
        }).catch(function(errors){
            console.log(errors);
        });
    }else if(joinDate > nowDate){
        await leaveWalletService.delMonthlyLeaves(userObj._id, yearMonth).then(function(response){
            console.log("Del EMP ID", userObj.employeeId);
        }).catch(function(errors){
            console.log(errors);
        });
    }
}

function userTakenLeaveBalance(userId, financialYear=null) {
    var deferred = Q.defer();
    if(financialYear){
        var financialYearArr = financialYear.split("-");
        var startDate = new Date(financialYearArr[0], 3, 1);
        var endDate = new Date(financialYearArr[1], 3, 1);
    }else{
        var now = new Date();
        var startYear = (now.getMonth()>=3)?now.getFullYear():now.getFullYear()-1;
        var startDate = new Date(startYear, 3, 1);
        var endDate = new Date((startYear+1), 3, 1);
    }
    var queryStr = {
        userId: mongo.helper.toObjectID(userId),
        weekDate: {
            $gte: startDate,
            $lt: endDate
        },
        timeoffHours: {
            $gt: 0
        }
    };
    var userSheetBalance = {
        sickLeaveHours: 0.00,
        sickLeaveDays: 0.00,
        timeoffHours: 0.00,
        timeoffDays: 0.00,
        totalTimeoffHours: 0.00,
        totalTimeoffDays: 0.00
    };
    db.timesheets.find(queryStr).toArray(function(err, sheets) {
        _.each(sheets, function(sheetObj) {
            _.each(sheetObj.projects, function(projectObj) {
                userSheetBalance.sickLeaveHours += projectObj.sickLeaveHours;
                userSheetBalance.timeoffHours += projectObj.timeoffHours;
            });
            userSheetBalance.totalTimeoffHours += sheetObj.timeoffHours;
        });
        userSheetBalance.sickLeaveDays = parseFloat(userSheetBalance.sickLeaveHours/8).toFixed(2);
        userSheetBalance.timeoffDays = parseFloat(userSheetBalance.timeoffHours/8).toFixed(2);
        userSheetBalance.totalTimeoffDays = parseFloat(userSheetBalance.totalTimeoffHours/8).toFixed(2);
        deferred.resolve(userSheetBalance);
    });
    return deferred.promise;
}
<commit_msg>unset value<commit_after>var config = require(__dirname+'/../config.json');
var _ = require('lodash');
var Q = require('q');
var leaveWalletService = require('../services/leaveWallet.service');
var appConfigService = require('../services/appconfig.service');
var leaveWalletService = require('../services/leaveWallet.service');
var mongo = require('mongoskin');
var db = mongo.db(config.connectionString, { native_parser: true });
db.bind('users');
db.bind('timesheets');

var acquire_leaves_month = 0;
var nowDate = new Date();
var month = nowDate.getMonth() + 1;
var yearMonth = nowDate.getFullYear()+"-"+String(month<10?"0"+month:month);
var yearMonthNumber = nowDate.getFullYear()+String(month<10?"0"+month:month);
var financialYear = (month>=4)?nowDate.getFullYear():nowDate.getFullYear()-1;

appConfigService.getSettings().then(function(response){
    _.each(response, function(item){
        if(item.keyName == "acquire_leaves_month"){
            acquire_leaves_month = item.keyVal;
        }
    });

    db.users.find({isActive: true}).toArray(function(err, users) {
        _.each(users, function (userObj) {
            if(userObj.joinDate){
                updateUserAcquireLeaves(userObj, acquire_leaves_month);
            }
        });
    });
}).catch(function(errors){

});

let updateUserAcquireLeaves = async function(userObj, acquire_leaves_month){
    var acquire_leaves = 0.00;
    joinDate = new Date(userObj.joinDate);
    var middleDate = new Date(nowDate.getFullYear(), nowDate.getMonth(), 15);

    //joinDate = new Date(joinDate.getTime() + (60000 * 330));
    if(nowDate>joinDate && (month == 10 || (month == 4 && nowDate.getFullYear()>joinDate.getFullYear())) ){
        acquire_leaves = 1.00;
    }else if(nowDate.getFullYear()==joinDate.getFullYear() && month <= 9 && month == (joinDate.getMonth()+1) ){
        acquire_leaves = 1.00;
    }else if(nowDate.getFullYear()==joinDate.getFullYear() && month <= 9 && month == (joinDate.getMonth()+2) && joinDate.getDate()>=15){
        acquire_leaves = 1.00;
    }
    acquire_leaves += parseFloat(acquire_leaves_month);

    if(middleDate>joinDate){
        var leaveWalletData = {
            userId: userObj._id,
            yearMonth: yearMonth,
            yearMonthNumber: yearMonthNumber,
            accruedLeaves: acquire_leaves
        };

        await leaveWalletService.saveMonthlyLeaves(leaveWalletData).then(function(response){
            console.log("EMP ID", userObj.employeeId, " ", acquire_leaves);
        }).catch(function(errors){
            console.log(errors);
        });
    }else if(joinDate > nowDate){
        await leaveWalletService.delMonthlyLeaves(userObj._id, yearMonth).then(function(response){
            console.log("Del EMP ID", userObj.employeeId);
        }).catch(function(errors){
            console.log(errors);
        });
    }
}

function userTakenLeaveBalance(userId, financialYear=null) {
    var deferred = Q.defer();
    if(financialYear){
        var financialYearArr = financialYear.split("-");
        var startDate = new Date(financialYearArr[0], 3, 1);
        var endDate = new Date(financialYearArr[1], 3, 1);
    }else{
        var now = new Date();
        var startYear = (now.getMonth()>=3)?now.getFullYear():now.getFullYear()-1;
        var startDate = new Date(startYear, 3, 1);
        var endDate = new Date((startYear+1), 3, 1);
    }
    var queryStr = {
        userId: mongo.helper.toObjectID(userId),
        weekDate: {
            $gte: startDate,
            $lt: endDate
        },
        timeoffHours: {
            $gt: 0
        }
    };
    var userSheetBalance = {
        sickLeaveHours: 0.00,
        sickLeaveDays: 0.00,
        timeoffHours: 0.00,
        timeoffDays: 0.00,
        totalTimeoffHours: 0.00,
        totalTimeoffDays: 0.00
    };
    db.timesheets.find(queryStr).toArray(function(err, sheets) {
        _.each(sheets, function(sheetObj) {
            _.each(sheetObj.projects, function(projectObj) {
                userSheetBalance.sickLeaveHours += projectObj.sickLeaveHours;
                userSheetBalance.timeoffHours += projectObj.timeoffHours;
            });
            userSheetBalance.totalTimeoffHours += sheetObj.timeoffHours;
        });
        userSheetBalance.sickLeaveDays = parseFloat(userSheetBalance.sickLeaveHours/8).toFixed(2);
        userSheetBalance.timeoffDays = parseFloat(userSheetBalance.timeoffHours/8).toFixed(2);
        userSheetBalance.totalTimeoffDays = parseFloat(userSheetBalance.totalTimeoffHours/8).toFixed(2);
        deferred.resolve(userSheetBalance);
    });
    return deferred.promise;
}
<|endoftext|>


<commit_before>import '@polymer/iron-ajax/iron-ajax.js';
import '@polymer/iron-icons/iron-icons.js';
import '@polymer/iron-media-query/iron-media-query.js';
import '@polymer/paper-card/paper-card.js';
import '@polymer/iron-a11y-keys/iron-a11y-keys.js';
import 'web-animations-js/web-animations-next.min.js';
import '@polymer/neon-animation/neon-animatable.js';
import '@polymer/neon-animation/neon-animated-pages.js';
import '@polymer/neon-animation/animations/fade-in-animation.js';
import '@polymer/neon-animation/animations/fade-out-animation.js';

import {html, PolymerElement} from '@polymer/polymer/polymer-element.js';

import './resources/md2-input/md2-input.js';
import './resources/carousel-indicator.js';
import './resources/animated-checkmark.js';
import css from './registration-page.css';
import template from './registration-page.pug';
import logo from '../assets/logo.svg';

import utilitiesMixin from './utilities-mixin.js';

/**
 * Entry point for application UI.
 */
export class RegistrationPage extends utilitiesMixin(PolymerElement) {
    static get template() {
        const vars = {logo};
        return html([
            `<style>${css.toString()}</style>${template(vars)}`]);
    }

    static get properties() {
        return {
            userDetails: {type: Object, observer: '_onUserDetails'},
            namespaceInput: {type: Object},
            page: {type: Number, value: 0},
            namespaceName: String,
            error: Object,
            flowComplete: {type: Boolean, value: false},
            waitForRedirect: {type: Boolean, value: false},
            showAPIText: {type: Boolean, value: false},
            _namespaceValidationRegex: {
                type: String,
                readOnly: true,
                // eslint-disable-next-line
                value: '[-a-z0-9\.]',
            },
        };
    }

    ready() {
        super.ready();
        this.namespaceInput = this.$.Namespace;
    }

    _onUserDetails(d) {
        this.namespaceName = this.userDetails
            // eslint-disable-next-line no-useless-escape
            .replace(/[^\w]|\./g, '-')
            .replace(/^-+|-+$|_/g, '')
            .toLowerCase();
    }

    clearInvalidation() {
        this.namespaceInput.invalid = false;
    }

    nextPage() {
        this.page++;
    }

    backPage() {
        this.page--;
    }

    showError(msg) {
        this.set('error', {response: {error: msg}});
    }

    validateNamespace() {
        const finalRgx = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/;
        if (finalRgx.test(this.namespaceName)) return true;
        this.showError(
            `Name can only start and end with alpha-num characters, `+
            `dashes are only permitted between start and end. (minlength >= 1)`
        );
    }

    async pollProfile(times, delay) {
        const profileAPI = this.$.GetMyNamespace;
        if (times < 1) throw Error('Cannot poll profile < 1 times!');
        for (let i = 0; i < times; i++) {
            const req = profileAPI.generateRequest();
            await req.completes.catch(() => 0);
            if (req.response && req.response.hasWorkgroup) return true;
            await this.sleep(delay);
        }
    }

    async finishSetup() {
        const API = this.$.MakeNamespace;
        if (!this.validateNamespace()) return;
        API.body = {namespace: this.namespaceName};
        this.waitForRedirect = true;
        await API.generateRequest().completes;
        await this.sleep(1); // So the errors and callbacks can schedule
        if (this.error && this.error.response) {
            return this.waitForRedirect = false;
        }
        // Poll for profile over a span of 20 seconds (every 300ms)
        // if still not there, let the user click next again!
        const success = await this.pollProfile(66, 300);
        if (success) this._successSetup();
        this.waitForRedirect = false;
    }

    _successSetup() {
        this.flowComplete = true;
        this.set('error', {});
        this.fireEvent('flowcomplete');
    }
}

window.customElements.define('registration-page', RegistrationPage);
<commit_msg>There should be no delay on registration flow retry if an error comes back early (#4662)<commit_after>import '@polymer/iron-ajax/iron-ajax.js';
import '@polymer/iron-icons/iron-icons.js';
import '@polymer/iron-media-query/iron-media-query.js';
import '@polymer/paper-card/paper-card.js';
import '@polymer/iron-a11y-keys/iron-a11y-keys.js';
import 'web-animations-js/web-animations-next.min.js';
import '@polymer/neon-animation/neon-animatable.js';
import '@polymer/neon-animation/neon-animated-pages.js';
import '@polymer/neon-animation/animations/fade-in-animation.js';
import '@polymer/neon-animation/animations/fade-out-animation.js';

import {html, PolymerElement} from '@polymer/polymer/polymer-element.js';

import './resources/md2-input/md2-input.js';
import './resources/carousel-indicator.js';
import './resources/animated-checkmark.js';
import css from './registration-page.css';
import template from './registration-page.pug';
import logo from '../assets/logo.svg';

import utilitiesMixin from './utilities-mixin.js';

/**
 * Entry point for application UI.
 */
export class RegistrationPage extends utilitiesMixin(PolymerElement) {
    static get template() {
        const vars = {logo};
        return html([
            `<style>${css.toString()}</style>${template(vars)}`]);
    }

    static get properties() {
        return {
            userDetails: {type: Object, observer: '_onUserDetails'},
            namespaceInput: {type: Object},
            page: {type: Number, value: 0},
            namespaceName: String,
            error: Object,
            flowComplete: {type: Boolean, value: false},
            waitForRedirect: {type: Boolean, value: false},
            showAPIText: {type: Boolean, value: false},
            _namespaceValidationRegex: {
                type: String,
                readOnly: true,
                // eslint-disable-next-line
                value: '[-a-z0-9\.]',
            },
        };
    }

    ready() {
        super.ready();
        this.namespaceInput = this.$.Namespace;
    }

    _onUserDetails(d) {
        this.namespaceName = this.userDetails
            // eslint-disable-next-line no-useless-escape
            .replace(/[^\w]|\./g, '-')
            .replace(/^-+|-+$|_/g, '')
            .toLowerCase();
    }

    clearInvalidation() {
        this.namespaceInput.invalid = false;
    }

    nextPage() {
        this.page++;
    }

    backPage() {
        this.page--;
    }

    showError(msg) {
        this.set('error', {response: {error: msg}});
    }

    validateNamespace() {
        const finalRgx = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/;
        if (finalRgx.test(this.namespaceName)) return true;
        this.showError(
            `Name can only start and end with alpha-num characters, `+
            `dashes are only permitted between start and end. (minlength >= 1)`
        );
    }

    async pollProfile(times, delay) {
        const profileAPI = this.$.GetMyNamespace;
        if (times < 1) throw Error('Cannot poll profile < 1 times!');
        for (let i = 0; i < times; i++) {
            const req = profileAPI.generateRequest();
            await req.completes.catch(() => 0);
            if (req.response && req.response.hasWorkgroup) return true;
            await this.sleep(delay);
        }
    }

    async finishSetup() {
        const API = this.$.MakeNamespace;
        if (!this.validateNamespace()) return;
        API.body = {namespace: this.namespaceName};
        this.waitForRedirect = true;
        await API.generateRequest().completes.catch((e) => e);
        await this.sleep(1); // So the errors and callbacks can schedule
        if (this.error && this.error.response) {
            return this.waitForRedirect = false;
        }
        // Poll for profile over a span of 20 seconds (every 300ms)
        // if still not there, let the user click next again!
        const success = await this.pollProfile(66, 300);
        if (success) this._successSetup();
        this.waitForRedirect = false;
    }

    _successSetup() {
        this.flowComplete = true;
        this.set('error', {});
        this.fireEvent('flowcomplete');
    }
}

window.customElements.define('registration-page', RegistrationPage);
<|endoftext|>