<commit_before>var applicationMock;
var ApplicationMock = Ember.Object.extend({
  init: function() {
    this._super();
    this.registrations = {};
    this.injections = [];
  },
  register: function(name, factory, options) {
    this.registrations[name] = {
      factory: factory,
      options: options
    };
  },
  inject: function(target, property, name) {
    var registration = this.registrations[name];
    if (registration) {
      this.injections.push({
        target:   target,
        property: property,
        object:   registration.factory
      });
    }
  }
});

var applicationRouteMock;
var ApplicationRouteMock = Ember.Object.extend({
  init: function() {
    this._super();
    this.sentLoginComplete = false;
  },
  send: function(name) {
    this.sentLoginComplete = name == 'loginComplete';
  }
});

var containerMock;
var ContainerMock = Ember.Object.extend({
  lookup: function(name) {
    return applicationRouteMock;
  }
});

var XhrMock = Ember.Object.extend({
  init: function() {
    this._super();
    this.requestHeaders = {};
  },
  setRequestHeader: function(name, value) {
    this.requestHeaders[name] = value;
  }
});

var registeredAjaxPrefilter;
var ajaxPrefilterMock = function(prefilter) {
  registeredAjaxPrefilter = prefilter;
};

module('Ember.SimpleAuth', {
  originalAjaxPrefilter: Ember.$.ajaxPrefilter,
  setup: function() {
    Ember.$.ajaxPrefilter   = ajaxPrefilterMock;
    registeredAjaxPrefilter = undefined;
    applicationMock         = ApplicationMock.create();
    applicationRouteMock    = ApplicationRouteMock.create();
    containerMock           = ContainerMock.create();
  },
  teardown: function() {
    Ember.$.ajaxPrefilter = this.originalAjaxPrefilter;
  }
});

test('saves serverSessionRoute if specified for setup', function() {
  Ember.SimpleAuth.setup(containerMock, applicationMock, { serverSessionRoute: '/route' });

  equal(Ember.SimpleAuth.serverSessionRoute, '/route', 'Ember.SimpleAuth saves serverSessionRoute when specified for setup.');
});

test('saves routeAfterLogin if specified for setup', function() {
  Ember.SimpleAuth.setup(containerMock, applicationMock, { routeAfterLogin: 'somewhere' });

  equal(Ember.SimpleAuth.routeAfterLogin, 'somewhere', 'Ember.SimpleAuth saves routeAfterLogin when specified for setup.');
});

test('saves routeAfterLogout if specified for setup', function() {
  Ember.SimpleAuth.setup(containerMock, applicationMock, { routeAfterLogout: 'somewhere' });

  equal(Ember.SimpleAuth.routeAfterLogout, 'somewhere', 'Ember.SimpleAuth saves routeAfterLogout when specified for setup.');
});

test('saves loginRoute if specified for setup', function() {
  Ember.SimpleAuth.setup(containerMock, applicationMock, { loginRoute: 'somewhere' });

  equal(Ember.SimpleAuth.loginRoute, 'somewhere', 'Ember.SimpleAuth saves loginRoute when specified for setup.');
});

test('saves logoutRoute if specified for setup', function() {
  Ember.SimpleAuth.setup(containerMock, applicationMock, { logoutRoute: 'somewhere' });

  equal(Ember.SimpleAuth.logoutRoute, 'somewhere', 'Ember.SimpleAuth saves logutRoute when specified for setup.');
});

test('injects a session object in models, views, controllers and routes during setup', function() {
  Ember.SimpleAuth.setup(containerMock, applicationMock);

  Ember.$.each(['model', 'view', 'controller', 'view'], function(i, component) {
    var injection = Ember.$.grep(applicationMock.injections, function(injection) {
      return injection.target === component;
    })[0];

    equal(injection.property, 'session', 'Ember.SimpleAuth injects a session into ' + component + ' during setup.');
    equal(injection.object.constructor, Ember.SimpleAuth.Session, 'Ember.SimpleAuth.setup injects a session into ' + component + ' during setup.');
  });
});

test('registers an AJAX prefilter that adds the authToken for non-crossdomain requests during setup', function() {
  var xhrMock = XhrMock.create();
  var token = Math.random().toString(36);
  sessionStorage.authToken = token;
  Ember.SimpleAuth.setup(containerMock, applicationMock);

  registeredAjaxPrefilter({}, {}, xhrMock);
  equal(xhrMock.requestHeaders['Authorization'], 'Token token="' + token + '"', 'Ember.SimpleAuth.setup registers an AJAX prefilter that adds the authToken for non-crossdomain requests during setup.');

  xhrMock = XhrMock.create();
  xhrMock.crossDomain = true;
  registeredAjaxPrefilter({}, {}, xhrMock);
  equal(xhrMock.requestHeaders['Authorization'], undefined, 'Ember.SimpleAuth.setup registers an AJAX prefilter that does not add the authToken for crossdomain requests during setup.');
});

test('sets up the session correctly in the external login callback', function() {
  Ember.SimpleAuth.setup(containerMock, applicationMock);
  var token = Math.random().toString(36);
  Ember.SimpleAuth.externalLoginCallback({ session: { authToken: token } });

  equal(applicationMock.registrations['simple_auth:session'].factory.get('authToken'), token, 'Ember.SimpleAuth sets up the session with the auth token in the external login callback.');
  ok(applicationRouteMock.sentLoginComplete, 'Ember.SimpleAuth sends the loginComplete event to the application routes in the external login callback.');
});
<commit_msg>fixed JSHINT problem<commit_after>var applicationMock;
var ApplicationMock = Ember.Object.extend({
  init: function() {
    this._super();
    this.registrations = {};
    this.injections = [];
  },
  register: function(name, factory, options) {
    this.registrations[name] = {
      factory: factory,
      options: options
    };
  },
  inject: function(target, property, name) {
    var registration = this.registrations[name];
    if (registration) {
      this.injections.push({
        target:   target,
        property: property,
        object:   registration.factory
      });
    }
  }
});

var applicationRouteMock;
var ApplicationRouteMock = Ember.Object.extend({
  init: function() {
    this._super();
    this.sentLoginComplete = false;
  },
  send: function(name) {
    this.sentLoginComplete = (name === 'loginComplete');
  }
});

var containerMock;
var ContainerMock = Ember.Object.extend({
  lookup: function(name) {
    return applicationRouteMock;
  }
});

var XhrMock = Ember.Object.extend({
  init: function() {
    this._super();
    this.requestHeaders = {};
  },
  setRequestHeader: function(name, value) {
    this.requestHeaders[name] = value;
  }
});

var registeredAjaxPrefilter;
var ajaxPrefilterMock = function(prefilter) {
  registeredAjaxPrefilter = prefilter;
};

module('Ember.SimpleAuth', {
  originalAjaxPrefilter: Ember.$.ajaxPrefilter,
  setup: function() {
    Ember.$.ajaxPrefilter   = ajaxPrefilterMock;
    registeredAjaxPrefilter = undefined;
    applicationMock         = ApplicationMock.create();
    applicationRouteMock    = ApplicationRouteMock.create();
    containerMock           = ContainerMock.create();
  },
  teardown: function() {
    Ember.$.ajaxPrefilter = this.originalAjaxPrefilter;
  }
});

test('saves serverSessionRoute if specified for setup', function() {
  Ember.SimpleAuth.setup(containerMock, applicationMock, { serverSessionRoute: '/route' });

  equal(Ember.SimpleAuth.serverSessionRoute, '/route', 'Ember.SimpleAuth saves serverSessionRoute when specified for setup.');
});

test('saves routeAfterLogin if specified for setup', function() {
  Ember.SimpleAuth.setup(containerMock, applicationMock, { routeAfterLogin: 'somewhere' });

  equal(Ember.SimpleAuth.routeAfterLogin, 'somewhere', 'Ember.SimpleAuth saves routeAfterLogin when specified for setup.');
});

test('saves routeAfterLogout if specified for setup', function() {
  Ember.SimpleAuth.setup(containerMock, applicationMock, { routeAfterLogout: 'somewhere' });

  equal(Ember.SimpleAuth.routeAfterLogout, 'somewhere', 'Ember.SimpleAuth saves routeAfterLogout when specified for setup.');
});

test('saves loginRoute if specified for setup', function() {
  Ember.SimpleAuth.setup(containerMock, applicationMock, { loginRoute: 'somewhere' });

  equal(Ember.SimpleAuth.loginRoute, 'somewhere', 'Ember.SimpleAuth saves loginRoute when specified for setup.');
});

test('saves logoutRoute if specified for setup', function() {
  Ember.SimpleAuth.setup(containerMock, applicationMock, { logoutRoute: 'somewhere' });

  equal(Ember.SimpleAuth.logoutRoute, 'somewhere', 'Ember.SimpleAuth saves logutRoute when specified for setup.');
});

test('injects a session object in models, views, controllers and routes during setup', function() {
  Ember.SimpleAuth.setup(containerMock, applicationMock);

  Ember.$.each(['model', 'view', 'controller', 'view'], function(i, component) {
    var injection = Ember.$.grep(applicationMock.injections, function(injection) {
      return injection.target === component;
    })[0];

    equal(injection.property, 'session', 'Ember.SimpleAuth injects a session into ' + component + ' during setup.');
    equal(injection.object.constructor, Ember.SimpleAuth.Session, 'Ember.SimpleAuth.setup injects a session into ' + component + ' during setup.');
  });
});

test('registers an AJAX prefilter that adds the authToken for non-crossdomain requests during setup', function() {
  var xhrMock = XhrMock.create();
  var token = Math.random().toString(36);
  sessionStorage.authToken = token;
  Ember.SimpleAuth.setup(containerMock, applicationMock);

  registeredAjaxPrefilter({}, {}, xhrMock);
  equal(xhrMock.requestHeaders['Authorization'], 'Token token="' + token + '"', 'Ember.SimpleAuth.setup registers an AJAX prefilter that adds the authToken for non-crossdomain requests during setup.');

  xhrMock = XhrMock.create();
  xhrMock.crossDomain = true;
  registeredAjaxPrefilter({}, {}, xhrMock);
  equal(xhrMock.requestHeaders['Authorization'], undefined, 'Ember.SimpleAuth.setup registers an AJAX prefilter that does not add the authToken for crossdomain requests during setup.');
});

test('sets up the session correctly in the external login callback', function() {
  Ember.SimpleAuth.setup(containerMock, applicationMock);
  var token = Math.random().toString(36);
  Ember.SimpleAuth.externalLoginCallback({ session: { authToken: token } });

  equal(applicationMock.registrations['simple_auth:session'].factory.get('authToken'), token, 'Ember.SimpleAuth sets up the session with the auth token in the external login callback.');
  ok(applicationRouteMock.sentLoginComplete, 'Ember.SimpleAuth sends the loginComplete event to the application routes in the external login callback.');
});
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree.
 */

/* More information about these options at jshint.com/docs/options */

/* globals addCodecParam, channelReady:true, displayError, displayStatus,
   gatheredIceCandidateTypes, goog, hasLocalStream, iceCandidateType,
   localStream, maybePreferAudioReceiveCodec, maybePreferAudioSendCodec,
   maybePreferVideoReceiveCodec, maybePreferVideoSendCodec,
   maybeSetAudioReceiveBitRate, maybeSetAudioSendBitRate,
   maybeSetVideoReceiveBitRate, maybeSetVideoSendBitRate,
   maybeSetVideoSendInitialBitRate, mergeConstraints, msgQueue, onRemoteHangup,
   params, pc:true, remoteStream:true, remoteVideo, sdpConstraints, sharingDiv,
   signalingReady:true, socket:true, startTime:true, started:true,
   transitionToActive, turnDone, updateInfoDiv, waitForRemoteVideo */
/* exported openChannel */

'use strict';

function openChannel() {
  trace('Opening channel.');
  var channel = new goog.appengine.Channel(params.channelToken);
  var handler = {
    'onopen': onChannelOpened,
    'onmessage': onChannelMessage,
    'onerror': onChannelError,
    'onclose': onChannelClosed
  };
  socket = channel.open(handler);
}

function createPeerConnection() {
  try {
    var config = params.peerConnectionConfig;
    var constraints = params.peerConnectionConstraints;
    // Create an RTCPeerConnection via the polyfill (adapter.js).
    pc = new RTCPeerConnection(config, constraints);
    pc.onicecandidate = onIceCandidate;
    trace('Created RTCPeerConnnection with:\n' +
        '  config: \'' + JSON.stringify(config) + '\';\n' +
        '  constraints: \'' + JSON.stringify(constraints) + '\'.');
  } catch (e) {
    displayError('Failed to create PeerConnection, exception: ' + e.message);
    alert('Cannot create RTCPeerConnection object; WebRTC is not supported by this browser.');
    return;
  }
  pc.onaddstream = onRemoteStreamAdded;
  pc.onremovestream = onRemoteStreamRemoved;
  pc.onsignalingstatechange = onSignalingStateChanged;
  pc.oniceconnectionstatechange = onIceConnectionStateChanged;
}

function maybeStart() {
  if (!started && signalingReady && channelReady && turnDone &&
      (localStream || !hasLocalStream)) {
    startTime = window.performance.now();
    displayStatus('Connecting...');
    trace('Creating PeerConnection.');
    createPeerConnection();

    if (hasLocalStream) {
      trace('Adding local stream.');
      pc.addStream(localStream);
    } else {
      trace('Not sending any stream.');
    }
    started = true;

    if (params.isInitiator) {
      doCall();
    } else {
      calleeStart();
    }
  }
}

function doCall() {
  var constraints = mergeConstraints(params.offerConstraints, sdpConstraints);
  trace('Sending offer to peer, with constraints: \n\'' +
      JSON.stringify(constraints) + '\'.');
  pc.createOffer(setLocalAndSendMessage,
      onCreateSessionDescriptionError, constraints);
}

function calleeStart() {
  // Callee starts to process cached offer and other messages.
  while (msgQueue.length > 0) {
    processSignalingMessage(msgQueue.shift());
  }
}

function doAnswer() {
  trace('Sending answer to peer.');
  pc.createAnswer(setLocalAndSendMessage,
      onCreateSessionDescriptionError, sdpConstraints);
}

function setLocalAndSendMessage(sessionDescription) {
  sessionDescription.sdp = maybePreferAudioReceiveCodec(sessionDescription.sdp);
  sessionDescription.sdp = maybePreferVideoReceiveCodec(sessionDescription.sdp);
  sessionDescription.sdp = maybeSetAudioReceiveBitRate(sessionDescription.sdp);
  sessionDescription.sdp = maybeSetVideoReceiveBitRate(sessionDescription.sdp);
  pc.setLocalDescription(sessionDescription,
      onSetSessionDescriptionSuccess, onSetSessionDescriptionError);
  sendMessage(sessionDescription);
}

function setRemote(message) {
  // Set Opus in Stereo, if stereo enabled.
  if (params.isOpusStereo) {
    message.sdp = addCodecParam(message.sdp, 'opus/48000', 'stereo=1');
  }
  if (params.isOpus) {
    message.sdp = addCodecParam(message.sdp, 'opus/48000', 'useinbandfec=1');
  }
  // Set Opus maxplaybackrate, if requested.
  if (params.opusMaxPbr) {
    message.sdp = addCodecParam(message.sdp, 'opus/48000', 'maxplaybackrate=' +
        params.opusMaxPbr);
  }
  message.sdp = maybePreferAudioSendCodec(message.sdp);
  message.sdp = maybePreferVideoSendCodec(message.sdp);
  message.sdp = maybeSetAudioSendBitRate(message.sdp);
  message.sdp = maybeSetVideoSendBitRate(message.sdp);
  message.sdp = maybeSetVideoSendInitialBitRate(message.sdp);
  pc.setRemoteDescription(new RTCSessionDescription(message),
      onSetRemoteDescriptionSuccess, onSetSessionDescriptionError);

  function onSetRemoteDescriptionSuccess() {
    trace('Set remote session description success.');
    // By now all onaddstream events for the setRemoteDescription have fired,
    // so we can know if the peer has any remote video streams that we need
    // to wait for. Otherwise, transition immediately to the active state.
    // NOTE: Ideally we could just check |remoteStream| here, which is populated
    // in the onaddstream callback. But as indicated in
    // https://code.google.com/p/webrtc/issues/detail?id=3358, sometimes this
    // callback is dispatched after the setRemoteDescription success callback.
    // Therefore, we read the remoteStreams array directly from the
    // PeerConnection, which seems to work reliably.
    var remoteStreams = pc.getRemoteStreams();
    if (remoteStreams.length > 0 &&
        remoteStreams[0].getVideoTracks().length > 0) {
      trace('Waiting for remote video.');
      waitForRemoteVideo();
    } else {
      // TODO(juberti): Make this wait for ICE connection before transitioning.
      trace('No remote video stream; not waiting for media to arrive.');
      transitionToActive();
    }
  }
}

function sendMessage(message) {
  var msgString = JSON.stringify(message);
  trace('C->S: ' + msgString);
  // NOTE: AppRTCClient.java searches & parses this line; update there when
  // changing here.
  var path = '/message?r=' + params.roomId + '&u=' + params.clientId;
  var xhr = new XMLHttpRequest();
  xhr.open('POST', path, true);
  xhr.send(msgString);
}

function processSignalingMessage(message) {
  if (!started) {
    displayError('peerConnection has not been created yet!');
    return;
  }

  if (message.type === 'offer') {
    setRemote(message);
    doAnswer();
  } else if (message.type === 'answer') {
    setRemote(message);
  } else if (message.type === 'candidate') {
    var candidate = new RTCIceCandidate({
      sdpMLineIndex: message.label,
      candidate: message.candidate
    });
    recordIceCandidate('Remote', candidate);
    pc.addIceCandidate(candidate,
        onAddIceCandidateSuccess, onAddIceCandidateError);
  } else if (message.type === 'bye') {
    onRemoteHangup();
  }
}

function onAddIceCandidateSuccess() {
  trace('Remote candidate added successfully.');
}

function onAddIceCandidateError(error) {
  displayError('Failed to add remote candidate: ' + error.toString());
}

function onChannelOpened() {
  trace('Channel opened.');
  channelReady = true;
  maybeStart();
}

function onChannelMessage(message) {
  trace('S->C: ' + message.data);
  var msg = JSON.parse(message.data);
  // Since the turn response is async and also GAE might disorder the
  // Message delivery due to possible datastore query at server side,
  // So callee needs to cache messages before peerConnection is created.
  if (!params.isInitiator && !started) {
    if (msg.type === 'offer') {
      // Add offer to the beginning of msgQueue, since we can't handle
      // Early candidates before offer at present.
      msgQueue.unshift(msg);
      // Callee creates PeerConnection
      signalingReady = true;
      maybeStart();
    } else {
      msgQueue.push(msg);
    }
  } else {
    processSignalingMessage(msg);
  }
}

function onChannelError() {
  displayError('Channel error.');
}

function onChannelClosed() {
  trace('Channel closed.');
}

function onCreateSessionDescriptionError(error) {
  displayError('Failed to create session description: ' + error.toString());
}

function onSetSessionDescriptionSuccess() {
  trace('Set session description success.');
}

function onSetSessionDescriptionError(error) {
  displayError('Failed to set session description: ' + error.toString());
}

function onIceCandidate(event) {
  if (event.candidate) {
    // Eat undesired candidates.
    if (filterIceCandidate(event.candidate)) {
      sendMessage({
        type: 'candidate',
        label: event.candidate.sdpMLineIndex,
        id: event.candidate.sdpMid,
        candidate: event.candidate.candidate
      });
      recordIceCandidate('Local', event.candidate);
    }
  } else {
    trace('End of candidates.');
  }
}

function onRemoteStreamAdded(event) {
  sharingDiv.classList.remove('active');
  trace('Remote stream added.');
  attachMediaStream(remoteVideo, event.stream);
  remoteStream = event.stream;
}

function onRemoteStreamRemoved() {
  trace('Remote stream removed.');
}

function onSignalingStateChanged() {
  if (pc) {
    trace('Signaling state changed to: ' + pc.signalingState);
  }
  updateInfoDiv();
}

function onIceConnectionStateChanged() {
  if (pc) {
    trace('ICE connection state changed to: ' + pc.iceConnectionState);
    if (pc.iceConnectionState === 'completed') {
      trace('ICE complete time: ' +
          (performance.now() - startTime).toFixed(0) + 'ms.');
    }
  }
  updateInfoDiv();
}

// Return false if the candidate should be dropped, true if not.
function filterIceCandidate(candidateObj) {
  var candidateStr = candidateObj.candidate;

  // Always eat TCP candidates. Not needed in this context.
  if (candidateStr.indexOf('tcp') !== -1)
    return false;

  // If we're trying to eat non-relay candidates, do that.
  if (params.peerConnectionConfig.iceTransports === 'relay' &&
      iceCandidateType(candidateStr) !== 'relay')
    return false;

  return true;
}

function recordIceCandidate(location, candidateObj) {
  var type = iceCandidateType(candidateObj.candidate);
  var types = gatheredIceCandidateTypes[location];
  if (!types[type]) {
    types[type] = 1;
  } else {
    ++types[type];
  }
  updateInfoDiv();
}
<commit_msg>Make presubmit happy<commit_after>/*
 *  Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree.
 */

/* More information about these options at jshint.com/docs/options */

/* globals addCodecParam, channelReady:true, displayError, displayStatus,
   gatheredIceCandidateTypes, goog, hasLocalStream, iceCandidateType,
   localStream, maybePreferAudioReceiveCodec, maybePreferAudioSendCodec,
   maybePreferVideoReceiveCodec, maybePreferVideoSendCodec,
   maybeSetAudioReceiveBitRate, maybeSetAudioSendBitRate,
   maybeSetVideoReceiveBitRate, maybeSetVideoSendBitRate,
   maybeSetVideoSendInitialBitRate, mergeConstraints, msgQueue, onRemoteHangup,
   params, pc:true, remoteStream:true, remoteVideo, sdpConstraints, sharingDiv,
   signalingReady:true, socket:true, startTime:true, started:true,
   transitionToActive, turnDone, updateInfoDiv, waitForRemoteVideo */
/* exported openChannel */

'use strict';

function openChannel() {
  trace('Opening channel.');
  var channel = new goog.appengine.Channel(params.channelToken);
  var handler = {
    'onopen': onChannelOpened,
    'onmessage': onChannelMessage,
    'onerror': onChannelError,
    'onclose': onChannelClosed
  };
  socket = channel.open(handler);
}

function createPeerConnection() {
  try {
    var config = params.peerConnectionConfig;
    var constraints = params.peerConnectionConstraints;
    // Create an RTCPeerConnection via the polyfill (adapter.js).
    pc = new RTCPeerConnection(config, constraints);
    pc.onicecandidate = onIceCandidate;
    trace('Created RTCPeerConnnection with:\n' +
        '  config: \'' + JSON.stringify(config) + '\';\n' +
        '  constraints: \'' + JSON.stringify(constraints) + '\'.');
  } catch (e) {
    displayError('Failed to create PeerConnection, exception: ' + e.message);
    alert('Cannot create RTCPeerConnection object; WebRTC is not supported by this browser.');
    return;
  }
  pc.onaddstream = onRemoteStreamAdded;
  pc.onremovestream = onRemoteStreamRemoved;
  pc.onsignalingstatechange = onSignalingStateChanged;
  pc.oniceconnectionstatechange = onIceConnectionStateChanged;
}

function maybeStart() {
  if (!started && signalingReady && channelReady && turnDone &&
      (localStream || !hasLocalStream)) {
    startTime = window.performance.now();
    displayStatus('Connecting...');
    trace('Creating PeerConnection.');
    createPeerConnection();

    if (hasLocalStream) {
      trace('Adding local stream.');
      pc.addStream(localStream);
    } else {
      trace('Not sending any stream.');
    }
    started = true;

    if (params.isInitiator) {
      doCall();
    } else {
      calleeStart();
    }
  }
}

function doCall() {
  var constraints = mergeConstraints(params.offerConstraints, sdpConstraints);
  trace('Sending offer to peer, with constraints: \n\'' +
      JSON.stringify(constraints) + '\'.');
  pc.createOffer(setLocalAndSendMessage,
      onCreateSessionDescriptionError, constraints);
}

function calleeStart() {
  // Callee starts to process cached offer and other messages.
  while (msgQueue.length > 0) {
    processSignalingMessage(msgQueue.shift());
  }
}

function doAnswer() {
  trace('Sending answer to peer.');
  pc.createAnswer(setLocalAndSendMessage,
      onCreateSessionDescriptionError, sdpConstraints);
}

function setLocalAndSendMessage(sessionDescription) {
  sessionDescription.sdp = maybePreferAudioReceiveCodec(sessionDescription.sdp);
  sessionDescription.sdp = maybePreferVideoReceiveCodec(sessionDescription.sdp);
  sessionDescription.sdp = maybeSetAudioReceiveBitRate(sessionDescription.sdp);
  sessionDescription.sdp = maybeSetVideoReceiveBitRate(sessionDescription.sdp);
  pc.setLocalDescription(sessionDescription,
      onSetSessionDescriptionSuccess, onSetSessionDescriptionError);
  sendMessage(sessionDescription);
}

function setRemote(message) {
  // Set Opus in Stereo, if stereo enabled.
  if (params.isOpusStereo) {
    message.sdp = addCodecParam(message.sdp, 'opus/48000', 'stereo=1');
  }
  if (params.isOpus) {
    message.sdp = addCodecParam(message.sdp, 'opus/48000', 'useinbandfec=1');
  }
  // Set Opus maxplaybackrate, if requested.
  if (params.opusMaxPbr) {
    message.sdp = addCodecParam(message.sdp, 'opus/48000', 'maxplaybackrate=' +
        params.opusMaxPbr);
  }
  message.sdp = maybePreferAudioSendCodec(message.sdp);
  message.sdp = maybePreferVideoSendCodec(message.sdp);
  message.sdp = maybeSetAudioSendBitRate(message.sdp);
  message.sdp = maybeSetVideoSendBitRate(message.sdp);
  message.sdp = maybeSetVideoSendInitialBitRate(message.sdp);
  pc.setRemoteDescription(new RTCSessionDescription(message),
      onSetRemoteDescriptionSuccess, onSetSessionDescriptionError);

  function onSetRemoteDescriptionSuccess() {
    trace('Set remote session description success.');
    // By now all onaddstream events for the setRemoteDescription have fired,
    // so we can know if the peer has any remote video streams that we need
    // to wait for. Otherwise, transition immediately to the active state.
    // NOTE: Ideally we could just check |remoteStream| here, which is populated
    // in the onaddstream callback. But as indicated in
    // https://code.google.com/p/webrtc/issues/detail?id=3358, sometimes this
    // callback is dispatched after the setRemoteDescription success callback.
    // Therefore, we read the remoteStreams array directly from the
    // PeerConnection, which seems to work reliably.
    var remoteStreams = pc.getRemoteStreams();
    if (remoteStreams.length > 0 &&
        remoteStreams[0].getVideoTracks().length > 0) {
      trace('Waiting for remote video.');
      waitForRemoteVideo();
    } else {
      // TODO(juberti): Make this wait for ICE connection before transitioning.
      trace('No remote video stream; not waiting for media to arrive.');
      transitionToActive();
    }
  }
}

function sendMessage(message) {
  var msgString = JSON.stringify(message);
  trace('C->S: ' + msgString);
  // NOTE: AppRTCClient.java searches & parses this line; update there when
  // changing here.
  var path = '/message?r=' + params.roomId + '&u=' + params.clientId;
  var xhr = new XMLHttpRequest();
  xhr.open('POST', path, true);
  xhr.send(msgString);
}

function processSignalingMessage(message) {
  if (!started) {
    displayError('peerConnection has not been created yet!');
    return;
  }

  if (message.type === 'offer') {
    setRemote(message);
    doAnswer();
  } else if (message.type === 'answer') {
    setRemote(message);
  } else if (message.type === 'candidate') {
    var candidate = new RTCIceCandidate({
      sdpMLineIndex: message.label,
      candidate: message.candidate
    });
    recordIceCandidate('Remote', candidate);
    pc.addIceCandidate(candidate,
        onAddIceCandidateSuccess, onAddIceCandidateError);
  } else if (message.type === 'bye') {
    onRemoteHangup();
  }
}

function onAddIceCandidateSuccess() {
  trace('Remote candidate added successfully.');
}

function onAddIceCandidateError(error) {
  displayError('Failed to add remote candidate: ' + error.toString());
}

function onChannelOpened() {
  trace('Channel opened.');
  channelReady = true;
  maybeStart();
}

function onChannelMessage(message) {
  trace('S->C: ' + message.data);
  var msg = JSON.parse(message.data);
  // Since the turn response is async and also GAE might disorder the
  // Message delivery due to possible datastore query at server side,
  // So callee needs to cache messages before peerConnection is created.
  if (!params.isInitiator && !started) {
    if (msg.type === 'offer') {
      // Add offer to the beginning of msgQueue, since we can't handle
      // Early candidates before offer at present.
      msgQueue.unshift(msg);
      // Callee creates PeerConnection
      signalingReady = true;
      maybeStart();
    } else {
      msgQueue.push(msg);
    }
  } else {
    processSignalingMessage(msg);
  }
}

function onChannelError() {
  displayError('Channel error.');
}

function onChannelClosed() {
  trace('Channel closed.');
}

function onCreateSessionDescriptionError(error) {
  displayError('Failed to create session description: ' + error.toString());
}

function onSetSessionDescriptionSuccess() {
  trace('Set session description success.');
}

function onSetSessionDescriptionError(error) {
  displayError('Failed to set session description: ' + error.toString());
}

function onIceCandidate(event) {
  if (event.candidate) {
    // Eat undesired candidates.
    if (filterIceCandidate(event.candidate)) {
      sendMessage({
        type: 'candidate',
        label: event.candidate.sdpMLineIndex,
        id: event.candidate.sdpMid,
        candidate: event.candidate.candidate
      });
      recordIceCandidate('Local', event.candidate);
    }
  } else {
    trace('End of candidates.');
  }
}

function onRemoteStreamAdded(event) {
  sharingDiv.classList.remove('active');
  trace('Remote stream added.');
  attachMediaStream(remoteVideo, event.stream);
  remoteStream = event.stream;
}

function onRemoteStreamRemoved() {
  trace('Remote stream removed.');
}

function onSignalingStateChanged() {
  if (pc) {
    trace('Signaling state changed to: ' + pc.signalingState);
  }
  updateInfoDiv();
}

function onIceConnectionStateChanged() {
  if (pc) {
    trace('ICE connection state changed to: ' + pc.iceConnectionState);
    if (pc.iceConnectionState === 'completed') {
      trace('ICE complete time: ' +
          (performance.now() - startTime).toFixed(0) + 'ms.');
    }
  }
  updateInfoDiv();
}

// Return false if the candidate should be dropped, true if not.
function filterIceCandidate(candidateObj) {
  var candidateStr = candidateObj.candidate;

  // Always eat TCP candidates. Not needed in this context.
  if (candidateStr.indexOf('tcp') !== -1) {
    return false;
  }

  // If we're trying to eat non-relay candidates, do that.
  if (params.peerConnectionConfig.iceTransports === 'relay' &&
      iceCandidateType(candidateStr) !== 'relay') {
    return false;
  }

  return true;
}

function recordIceCandidate(location, candidateObj) {
  var type = iceCandidateType(candidateObj.candidate);
  var types = gatheredIceCandidateTypes[location];
  if (!types[type]) {
    types[type] = 1;
  } else {
    ++types[type];
  }
  updateInfoDiv();
}
<|endoftext|>


<commit_before>import axios from 'axios';
import {EventEmitter} from 'events';

import Model from '../base/model';
import {buildAPIURL} from '../utils';

export default class Feed extends EventEmitter {
  constructor(path, params) {
    super();

    this.path = path;
    this.query = new Model(params);

    this.nextURL = null;
    this.items = null;
  }

  clear() {
    this.nextURL = null;
    this.items = null;
    this.emit('clear');
  }

  fetchAll() {
    const loadingQuery = this.query.clone();
    let items = null;
    let nextURL = null;

    const hasMore = () => nextURL !== null || items == null;
    const fetchNextPage = () => {
      if (!hasMore()) {
        this._handleLoaded(loadingQuery, items, items, nextURL);
        return;
      }

      this._doFetchMore(loadingQuery, nextURL).then(response => {
        if (!loadingQuery.equals(this.query)) {
          return;
        }
        items = (items || []).concat(response.data.results);
        nextURL = response.data.next;
        fetchNextPage();
      });
    }

    fetchNextPage();
  }

  fetchMore() {
    const loadingQuery = this.query.clone();
    this._doFetchMore(this.query, this.nextURL).then(response => {
      const newItems = response.data.results;
      const allItems = (this.items || []).concat(newItems);
      const nextURL = response.data.next;
      this._handleLoaded(loadingQuery, newItems, allItems, nextURL);
    });
  }

  hasMore() {
    return this.nextURL !== null || this.items === null;
  }

  _doFetchMore(query, nextURL) {
    if (nextURL) {
      return axios.get(nextURL);
    } else {
      return axios.get(
        buildAPIURL(this.path),
        {params: query.data}
      );
    }
  }

  _handleLoaded(loadedQuery, newItems, allItems, nextURL) {
    if (loadedQuery.equals(this.query)) {
      this.items = allItems;
      this.nextURL = nextURL;
      this.emit('load', newItems);
    }
  }
}
<commit_msg>Return Promises from Feed's fetch methods<commit_after>import axios from 'axios';
import {EventEmitter} from 'events';

import Model from '../base/model';
import {buildAPIURL} from '../utils';

export default class Feed extends EventEmitter {
  constructor(path, params) {
    super();

    this.path = path;
    this.query = new Model(params);

    this.nextURL = null;
    this.items = null;
  }

  clear() {
    this.nextURL = null;
    this.items = null;
    this.emit('clear');
  }

  fetchAll() {
    const loadingQuery = this.query.clone();
    let items = null;
    let nextURL = null;

    return new Promise((resolve, reject) => {
      const hasMore = () => nextURL !== null || items == null;
      const fetchNextPage = () => {
        if (!hasMore()) {
          this._handleLoaded(loadingQuery, items, items, nextURL);
          resolve(items);
          return;
        }

        this._doFetchMore(loadingQuery, nextURL).then(response => {
          if (!loadingQuery.equals(this.query)) {
            reject();
            return;
          }
          items = (items || []).concat(response.data.results);
          nextURL = response.data.next;
          fetchNextPage();
        });
      }

      fetchNextPage();
    });
  }

  fetchMore() {
    const loadingQuery = this.query.clone();
    return this._doFetchMore(this.query, this.nextURL).then(response => {
      const newItems = response.data.results;
      const allItems = (this.items || []).concat(newItems);
      const nextURL = response.data.next;
      this._handleLoaded(loadingQuery, newItems, allItems, nextURL);
      return newItems;
    });
  }

  hasMore() {
    return this.nextURL !== null || this.items === null;
  }

  _doFetchMore(query, nextURL) {
    if (nextURL) {
      return axios.get(nextURL);
    } else {
      return axios.get(
        buildAPIURL(this.path),
        {params: query.data}
      );
    }
  }

  _handleLoaded(loadedQuery, newItems, allItems, nextURL) {
    if (loadedQuery.equals(this.query)) {
      this.items = allItems;
      this.nextURL = nextURL;
      this.emit('load', newItems);
    }
  }
}
<|endoftext|>


<commit_before>/**
 * Created by petermares on 20/02/2016.
 */

module.exports = (function() {
    var settings = require('../../settings');
    var o = {};
    var _tiles = {
        tile_grass: 'assets/grass_128x128.png',
        tile_sky: 'assets/sky.png'
    };
    var player;
    var state = 'waiting';
    var platforms;
    var level;
    var numJumps = 0;

    o.preload = function() {
        console.log('Game.preload');

        this.game.stage.backgroundColor = '#000';

        // load images
        for (var k in _tiles) {
            this.load.image(k, _tiles[k]);
        }

        //this.game.load.json('level', 'http://' + settings.server.host + ':' + settings.server.port + '/player/' + settings.playerID + '/level');
        level = {
            size: 1024,
            gaps: 5
        }
    };

    o.create = function() {
        console.log('Game.create');

        //level = this.game.cache.getJSON('level');
        console.log(level);

        var sky = this.game.add.sprite(0, 0, 'sky');
        sky.width = settings.display.width;

        platforms = this.game.add.group();
        platforms.enableBody = true;
        var ground;
        for ( var i = 1; i <= level.size; i++ ) {
            if ( level.gaps && (i == 4 || level.size % Math.floor(Math.random() * 100) == 0) ) {
                level.gaps--;
                console.log('generating gap at position: ' + i);
                i += 2;
            } else {
                ground = platforms.create(i * 64, this.game.world.height-64, 'tile_grass');
                ground.body.immovable = true;
                ground.scale.set(0.5, 0.5);
                ground.body.friction.x = 0;
            }
        }

        // create the player
        player = this.game.add.sprite(128, 0, 'dude');
        this.game.physics.arcade.enable(player);
        player.body.bounce.y = 0;
        player.body.gravity.y = 350;
        player.body.collideWorldBounds = true;
        player.animations.add('right', [1, 2, 3, 4], 10, true);
        player.animations.add('jump', [5, 6], 10, true);
        player.animations.add('fall', [0], 10, true);
    };

    o.update = function() {
        this.game.physics.arcade.collide(player, platforms);
        switch ( state ) {
            case    'waiting':
                if ( player.body.touching.down ) {
                    state = 'running';
                }
                break;

            case    'running':
                this.run();
                break;
        }
    };

    o.run = function() {
        var cursors = this.game.input.keyboard.createCursorKeys();
        var isJumping = !player.body.touching.down;

        platforms.forEach(function(ground) {
            ground.body.velocity.x = -150;
        }, this);

        if ( cursors.up.isDown) {
            // enable a single and double jump.
            // doubleJumps are only allowed on a certain part of the initial jump arc
            if ( player.body.velocity.y > -100 && numJumps < 1 ) {
                player.body.velocity.y = -350;
                numJumps++;
            }
        }
        if ( cursors.down.isDown) {
            player.body.velocity.y = 800;
        }

        if ( isJumping ) {
            player.animations.play('jump');
        } else {
            player.animations.play('right');
            numJumps = 0;
        }
    };

    return o;
})();<commit_msg>Speed increase over distance added<commit_after>/**
 * Created by petermares on 20/02/2016.
 */

module.exports = (function() {
    var settings = require('../../settings');
    var o = {};
    var _tiles = {
        tile_grass: 'assets/grass_128x128.png',
        tile_sky: 'assets/sky.png'
    };
    var player;
    var state = 'waiting';
    var platforms;
    var level;
    var numJumps = 0;

    o.preload = function() {
        console.log('Game.preload');

        this.game.stage.backgroundColor = '#000';

        // load images
        for (var k in _tiles) {
            this.load.image(k, _tiles[k]);
        }

        //this.game.load.json('level', 'http://' + settings.server.host + ':' + settings.server.port + '/player/' + settings.playerID + '/level');
        level = {
            size: 1024,
            gaps: 5
        }
    };

    o.create = function() {
        console.log('Game.create');

        //level = this.game.cache.getJSON('level');
        console.log(level);

        var sky = this.game.add.sprite(0, 0, 'sky');
        sky.width = settings.display.width;

        platforms = this.game.add.group();
        platforms.enableBody = true;
        var ground;
        for ( var i = 1; i <= level.size; i++ ) {

            if ( i > 15 && level.gaps && (i == 4 || level.size % Math.floor(Math.random() * 100) == 0) ) {
                level.gaps--;
                console.log('generating gap at position: ' + i);
                i += 2;
            } else {
                ground = platforms.create((i-1) * 64, this.game.world.height-64, 'tile_grass');
                ground.body.immovable = true;
                ground.scale.set(0.5, 0.5);
                ground.body.friction.x = 0;
            }
        }

        // create the player
        player = this.game.add.sprite(128, 0, 'dude');
        this.game.physics.arcade.enable(player);
        player.body.bounce.y = 0;
        player.body.gravity.y = 350;
        player.body.collideWorldBounds = true;
        player.animations.add('right', [1, 2, 3, 4], 10, true);
        player.animations.add('jump', [5, 6], 10, true);
        player.animations.add('fall', [0], 10, true);
    };

    o.update = function() {
        this.game.physics.arcade.collide(player, platforms);
        switch ( state ) {
            case    'waiting':
                if ( player.body.touching.down ) {
                    state = 'running';
                }
                break;

            case    'running':
                this.run();
                break;
        }
    };

    o.run = function() {
        var cursors = this.game.input.keyboard.createCursorKeys();
        var isJumping = !player.body.touching.down;
        var runSpeed = 150;

        runSpeed += 2 * (Math.abs(platforms.children[0].x) / 64)

        platforms.forEach(function(ground, index) {
            ground.body.velocity.x = -runSpeed;
        }, this);

        if ( cursors.up.isDown) {
            // enable a single and double jump.
            // doubleJumps are only allowed on a certain part of the initial jump arc
            if ( player.body.velocity.y > -100 && numJumps < 1 ) {
                player.body.velocity.y = -350;
                numJumps++;
            }
        }
        if ( cursors.down.isDown) {
            player.body.velocity.y = 800;
        }

        if ( isJumping ) {
            player.animations.play('jump');
        } else {
            player.animations.play('right');
            numJumps = 0;
        }
    };

    return o;
})();<|endoftext|>


<commit_before>module.exports = function(grunt) {

	// Project configuration.
	grunt.initConfig({
		pkg: grunt.file.readJSON('package.json'),
		clean: ['./public/patterns'],
		copy: {
			main: {
				files: [
					{ expand: true, cwd: './source/js/', src: '*', dest: './public/js/'},
					{ expand: true, cwd: './source/css/', src: 'style.css', dest: './public/css/' },
					{ expand: true, cwd: './source/images/', src: ['*.png', '*.jpg', '*.gif', '*.jpeg'], dest: './public/images/' },
					{ expand: true, cwd: './source/images/sample/', src: ['*.png', '*.jpg', '*.gif', '*.jpeg'], dest: './public/images/sample/'},
					{ expand: true, cwd: './source/fonts/', src: '*', dest: './public/fonts/'}
				]
			}
		},
		jshint: {
			options: {
				"curly": true,
				"eqnull": true,
				"eqeqeq": true,
				"undef": true,
				"forin": true,
				//"unused": true,
				"node": true
			},
			patternlab: ['Gruntfile.js', './builder/lib/patternlab.js']
		},
		watch: {
			// scss: { //scss can be watched if you like
			// 	files: ['source/css/**/*.scss', 'public/styleguide/css/*.scss'],
			// 	tasks: ['default']
			// },
			mustache: {
				files: ['source/_patterns/**/*.mustache'],
				tasks: ['default']
			},
			data: {
				files: ['source/_patterns/**/*.json'],
				tasks: ['default']
			}
		},
		sass: {
			build: {
				options: {
					style: 'expanded',
					precision: 8
				},
				files: {
					'./source/css/style.css': './source/css/style.scss',
					'./public/styleguide/css/static.css': './public/styleguide/css/static.scss',
					'./public/styleguide/css/styleguide.css': './public/styleguide/css/styleguide.scss'
				}
			}
		}
	});

	// load all grunt tasks
 	require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);

	//load the patternlab task
	grunt.task.loadTasks('./builder/');

	//if you choose to use scss, or any preprocessor, you can add it here
	grunt.registerTask('default', ['clean', 'patternlab', /*'sass',*/ 'copy']);
};<commit_msg>watch _data/*.json too<commit_after>module.exports = function(grunt) {

	// Project configuration.
	grunt.initConfig({
		pkg: grunt.file.readJSON('package.json'),
		clean: ['./public/patterns'],
		copy: {
			main: {
				files: [
					{ expand: true, cwd: './source/js/', src: '*', dest: './public/js/'},
					{ expand: true, cwd: './source/css/', src: 'style.css', dest: './public/css/' },
					{ expand: true, cwd: './source/images/', src: ['*.png', '*.jpg', '*.gif', '*.jpeg'], dest: './public/images/' },
					{ expand: true, cwd: './source/images/sample/', src: ['*.png', '*.jpg', '*.gif', '*.jpeg'], dest: './public/images/sample/'},
					{ expand: true, cwd: './source/fonts/', src: '*', dest: './public/fonts/'}
				]
			}
		},
		jshint: {
			options: {
				"curly": true,
				"eqnull": true,
				"eqeqeq": true,
				"undef": true,
				"forin": true,
				//"unused": true,
				"node": true
			},
			patternlab: ['Gruntfile.js', './builder/lib/patternlab.js']
		},
		watch: {
			// scss: { //scss can be watched if you like
			// 	files: ['source/css/**/*.scss', 'public/styleguide/css/*.scss'],
			// 	tasks: ['default']
			// },
			mustache: {
				files: ['source/_patterns/**/*.mustache'],
				tasks: ['default']
			},
			data: {
				files: ['source/_patterns/**/*.json', 'source/_data/*.json'],
				tasks: ['default']
			}
		},
		sass: {
			build: {
				options: {
					style: 'expanded',
					precision: 8
				},
				files: {
					'./source/css/style.css': './source/css/style.scss',
					'./public/styleguide/css/static.css': './public/styleguide/css/static.scss',
					'./public/styleguide/css/styleguide.css': './public/styleguide/css/styleguide.scss'
				}
			}
		}
	});

	// load all grunt tasks
 	require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);

	//load the patternlab task
	grunt.task.loadTasks('./builder/');

	//if you choose to use scss, or any preprocessor, you can add it here
	grunt.registerTask('default', ['clean', 'patternlab', /*'sass',*/ 'copy']);
};<|endoftext|>


<commit_before>/* © 2014 nau.com
 * @author Phuong Vo
 */
var game = null;

var completeGame = function(result) {
	$('.modal-congratulation-level3').modal('show');
	console.log('win result ' + result);
};

Template.PageGame.rendered = function() {
};

Template.PageGame.helpers({
	'rendered': function() {
		//
		Session.set('showGame', true);
		//
		var mapId = Router.current().params.mapId;
		//
		Session.set('nextMapId', parseInt(mapId,10) + 1);
		//
		Meteor.call('map', mapId, function(error, result) {
			//we parse the game and init the game
			game = new window.chungapp.Game();
			game.setJSONMapData(result, mapId);
			console.log('result', result);
			game.startGame();

			Session.set('game', game);
			Session.set('steps', 0);

			// game.getNumStep() -> mapResolver.getHistoryNum() is a reactive getter
			Tracker.autorun(function() {
				var steps = game ? game.getNumStep() : 0;
				Session.set('steps', steps);
			});

			// bind keyboard events, will move to an input controller
			$('body').off('keyup keydown').on({
				'keyup': function(event) {
					console.log('keyup', event);
					var direction = '';

					switch (event.keyCode) {
						case 37:
							direction = 'Left';
							break;
						case 38:
							direction = 'Up';
							break;
						case 39:
							direction = 'Right';
							break;
						case 40:
							direction = 'Down';
					}

					if (direction && game) {
						var result = game['go' + direction]();
						if (result !== null) {
							completeGame(result);
						}
						event.preventDefault();
					}
				},

				'keydown': function(event) {
					if (event.keyCode === 37 ||
						event.keyCode === 38 ||
						event.keyCode === 39 ||
						event.keyCode === 40)
					{
						// prevent overflow body to be scrolled by directional key event
						event.preventDefault();
					}
				}
			});
		});
		return '';
	}
});

Template.PageGame.events({
	'click .control-top' : function(/*event*/) {
		console.log('==move top');
		//var game = Session.get('game');
		var result = game.goUp();
		if (result !== null) {
			completeGame(result);
		}
	},

	'click .control-left' : function(/*event*/) {
		console.log('==move left');
		//var game = Session.get('game');
		var result = game.goLeft();
		if (result !== null) {
			completeGame(result);
		}
	},

	'click .control-right' : function(/*event*/) {
		console.log('==move right');
		//var game = Session.get('game');
		var result = game.goRight();
		if (result !== null) {
			completeGame(result);
		}
	},

	'click .control-bottom' : function(/*event*/) {
		console.log('==move bottom');
		//var game = Session.get('game');
		var result = game.goDown();
		if (result !== null) {
			completeGame(result);
		}
	},

	'click .icon-reset' : function(/*event*/) {
		console.log('==restart');
		//var game = Session.get('game');
		game.restart();
	},

	'click .icon-back' : function(/*event*/) {
		console.log('==undo');
		//var game = Session.get('game');
		game.undo();
	}
});<commit_msg>delay 400 milisecond when show congratulation pop up<commit_after>/* © 2014 nau.com
 * @author Phuong Vo
 */
var game = null;

var completeGame = function(result) {
	// delay 300 milisecond when show congratulation pop up
	setTimeout(function() {
		$('.modal-congratulation-level3').modal('show');
		console.log('win result ' + result);
	}, 400);
};

Template.PageGame.rendered = function() {
};

Template.PageGame.helpers({
	'rendered': function() {
		//
		Session.set('showGame', true);
		//
		var mapId = Router.current().params.mapId;
		//
		Session.set('nextMapId', parseInt(mapId,10) + 1);
		//
		Meteor.call('map', mapId, function(error, result) {
			//we parse the game and init the game
			game = new window.chungapp.Game();
			game.setJSONMapData(result, mapId);
			console.log('result', result);
			game.startGame();

			Session.set('game', game);
			Session.set('steps', 0);

			// game.getNumStep() -> mapResolver.getHistoryNum() is a reactive getter
			Tracker.autorun(function() {
				var steps = game ? game.getNumStep() : 0;
				Session.set('steps', steps);
			});

			// bind keyboard events, will move to an input controller
			$('body').off('keyup keydown').on({
				'keyup': function(event) {
					console.log('keyup', event);
					var direction = '';

					switch (event.keyCode) {
						case 37:
							direction = 'Left';
							break;
						case 38:
							direction = 'Up';
							break;
						case 39:
							direction = 'Right';
							break;
						case 40:
							direction = 'Down';
					}

					if (direction && game) {
						var result = game['go' + direction]();
						if (result !== null) {
							completeGame(result);
						}
						event.preventDefault();
					}
				},

				'keydown': function(event) {
					if (event.keyCode === 37 ||
						event.keyCode === 38 ||
						event.keyCode === 39 ||
						event.keyCode === 40)
					{
						// prevent overflow body to be scrolled by directional key event
						event.preventDefault();
					}
				}
			});
		});
		return '';
	}
});

Template.PageGame.events({
	'click .control-top' : function(/*event*/) {
		console.log('==move top');
		//var game = Session.get('game');
		var result = game.goUp();
		if (result !== null) {
			completeGame(result);
		}
	},

	'click .control-left' : function(/*event*/) {
		console.log('==move left');
		//var game = Session.get('game');
		var result = game.goLeft();
		if (result !== null) {
			completeGame(result);
		}
	},

	'click .control-right' : function(/*event*/) {
		console.log('==move right');
		//var game = Session.get('game');
		var result = game.goRight();
		if (result !== null) {
			completeGame(result);
		}
	},

	'click .control-bottom' : function(/*event*/) {
		console.log('==move bottom');
		//var game = Session.get('game');
		var result = game.goDown();
		if (result !== null) {
			completeGame(result);
		}
	},

	'click .icon-reset' : function(/*event*/) {
		console.log('==restart');
		//var game = Session.get('game');
		game.restart();
	},

	'click .icon-back' : function(/*event*/) {
		console.log('==undo');
		//var game = Session.get('game');
		game.undo();
	}
});<|endoftext|>


<commit_before>const Eris = require("eris");

// Replace TOKEN with your bot account's token
const bot = new Eris("Bot TOKEN");

bot.on("ready", () => { // When the bot is ready
    console.log("Ready!"); // Log "Ready!"
});

bot.on("error", (err) => {
    console.error(err); // or your preferred logger
});

bot.on("messageCreate", (msg) => { // When a message is created
    if(msg.content === "!embed") { // If the message content is "!embed"
        bot.createMessage(msg.channel.id, {
            embed: {
                title: "I'm an embed!", // Title of the embed
                description: "Here is some more info, with **awesome** formatting.\nPretty *neat*, huh?",
                author: { // Author property
                    name: msg.author.username,
                    icon_url: msg.author.avatarURL
                },
                color: 0x008000, // Color, either in hex (show), or a base-10 integer
                fields: [ // Array of field objects
                    {
                        name: "Some extra info.", // Field title
                        value: "Some extra value.", // Field
                        inline: true // Whether you want multiple fields in same line
                    },
                    {
                        name: "Some more extra info.",
                        value: "Another extra value.",
                        inline: true
                    }
                ],
                footer: { // Footer text
                    text: "Created with Eris."
                }
            }
        });
    }
});

bot.connect(); // Get the bot to connect to Discord
<commit_msg>Use embeds array in embed example (#1244)<commit_after>const Eris = require("eris");

// Replace TOKEN with your bot account's token
const bot = new Eris("Bot TOKEN");

bot.on("ready", () => { // When the bot is ready
    console.log("Ready!"); // Log "Ready!"
});

bot.on("error", (err) => {
    console.error(err); // or your preferred logger
});

bot.on("messageCreate", (msg) => { // When a message is created
    if(msg.content === "!embed") { // If the message content is "!embed"
        bot.createMessage(msg.channel.id, {
            embeds: [{
                title: "I'm an embed!", // Title of the embed
                description: "Here is some more info, with **awesome** formatting.\nPretty *neat*, huh?",
                author: { // Author property
                    name: msg.author.username,
                    icon_url: msg.author.avatarURL
                },
                color: 0x008000, // Color, either in hex (show), or a base-10 integer
                fields: [ // Array of field objects
                    {
                        name: "Some extra info.", // Field title
                        value: "Some extra value.", // Field
                        inline: true // Whether you want multiple fields in same line
                    },
                    {
                        name: "Some more extra info.",
                        value: "Another extra value.",
                        inline: true
                    }
                ],
                footer: { // Footer text
                    text: "Created with Eris."
                }
            }]
        });
    }
});

bot.connect(); // Get the bot to connect to Discord
<|endoftext|>


<commit_before>import React, {useEffect, useRef} from 'react'
import styled from 'styled-components'
import _get from 'lodash/get'
import ace from 'ace-builds/src-min-noconflict/ace'
import 'ace-builds/webpack-resolver'
import {Mode as GroovyMode} from 'ace-builds/src-min-noconflict/mode-groovy'
import {Mode as HtmlMode} from 'ace-builds/src-min-noconflict/mode-html'
import {Mode as LessMode} from 'ace-builds/src-min-noconflict/mode-less'
import {Mode as XmlMode} from 'ace-builds/src-min-noconflict/mode-xml'
import {Mode as PropertiesMode} from 'ace-builds/src-min-noconflict/mode-properties'
import {Mode as DroolsMode} from 'ace-builds/src-min-noconflict/mode-drools'
import {Mode as JsonMode} from 'ace-builds/src-min-noconflict/mode-json'
import {Mode as TextMode} from 'ace-builds/src-min-noconflict/mode-text'

import AceEditorPropTypes from './AceEditorPropTypes'
import 'ace-builds/src-min-noconflict/snippets/ftl'
import 'ace-builds/src-min-noconflict/snippets/groovy'
import 'ace-builds/src-min-noconflict/snippets/html'
import 'ace-builds/src-min-noconflict/snippets/less'
import 'ace-builds/src-min-noconflict/snippets/xml'
import 'ace-builds/src-min-noconflict/snippets/properties'
import 'ace-builds/src-min-noconflict/snippets/json'
import 'ace-builds/src-min-noconflict/snippets/drools'
import 'ace-builds/src-min-noconflict/theme-textmate'
import 'ace-builds/src-min-noconflict/ext-language_tools'
import TqlMode from './TqlMode'
import ToccoFtlMode from './ToccoFtlMode'

const StyledEditor = styled.div`
  width: 100%;
  z-index: 0; /* gutter lays over menu otherwise */
`

const modeMappings = {
  groovy: new GroovyMode(),
  html: new HtmlMode(),
  xml: new XmlMode(),
  properties: new PropertiesMode(),
  json: new JsonMode(),
  htmlmixed: new ToccoFtlMode(),
  freemarkermixed: new ToccoFtlMode(),
  ftl: new ToccoFtlMode(),
  tql: new TqlMode(),
  less: new LessMode(),
  drools: new DroolsMode(),
  text: new TextMode()
}

const getMode = mode => _get(modeMappings, mode, mode)

const setEditorConfiguration = (editor, {
  mode,
  theme,
  showGutter,
  editorOptions = {}
}) => {
  editor.getSession().setMode(getMode(mode))
  editor.setTheme(`ace/theme/${theme}`)
  Object.entries(editorOptions).forEach(([k, v]) => {
    editor.setOption(k, v)
  })
  editor.renderer.setShowGutter(showGutter)
  editor.resize()
}

const AceEditor = props => {
  const {
    mode,
    theme = 'textmate',
    value,
    onChange,
    showGutter = true,
    editorOptions = {}
  } = props
  const containerReference = useRef(null)
  const editorReference = useRef(null)

  useEffect(() => {
    if (containerReference.current) {
      const aceEditor = ace.edit(containerReference.current)
      aceEditor.getSession().setValue(value)
      aceEditor.on('change', () => onChange(aceEditor.getValue()))
      setEditorConfiguration(aceEditor, props)
      editorReference.current = aceEditor

      return () => aceEditor.destroy()
    }
  }, [containerReference])
  useEffect(() => {
    if (editorReference.current) {
      setEditorConfiguration(editorReference.current, props)
    }
  }, [mode, theme, showGutter, editorOptions])
  return <StyledEditor ref={containerReference}/>
}

AceEditor.propTypes = AceEditorPropTypes

export default AceEditor
<commit_msg>fix(tocco-ui): run setup effect only on mount in AceEditor<commit_after>import React, {useEffect, useRef} from 'react'
import styled from 'styled-components'
import _get from 'lodash/get'
import ace from 'ace-builds/src-min-noconflict/ace'
import 'ace-builds/webpack-resolver'
import {Mode as GroovyMode} from 'ace-builds/src-min-noconflict/mode-groovy'
import {Mode as HtmlMode} from 'ace-builds/src-min-noconflict/mode-html'
import {Mode as LessMode} from 'ace-builds/src-min-noconflict/mode-less'
import {Mode as XmlMode} from 'ace-builds/src-min-noconflict/mode-xml'
import {Mode as PropertiesMode} from 'ace-builds/src-min-noconflict/mode-properties'
import {Mode as DroolsMode} from 'ace-builds/src-min-noconflict/mode-drools'
import {Mode as JsonMode} from 'ace-builds/src-min-noconflict/mode-json'
import {Mode as TextMode} from 'ace-builds/src-min-noconflict/mode-text'

import AceEditorPropTypes from './AceEditorPropTypes'
import 'ace-builds/src-min-noconflict/snippets/ftl'
import 'ace-builds/src-min-noconflict/snippets/groovy'
import 'ace-builds/src-min-noconflict/snippets/html'
import 'ace-builds/src-min-noconflict/snippets/less'
import 'ace-builds/src-min-noconflict/snippets/xml'
import 'ace-builds/src-min-noconflict/snippets/properties'
import 'ace-builds/src-min-noconflict/snippets/json'
import 'ace-builds/src-min-noconflict/snippets/drools'
import 'ace-builds/src-min-noconflict/theme-textmate'
import 'ace-builds/src-min-noconflict/ext-language_tools'
import TqlMode from './TqlMode'
import ToccoFtlMode from './ToccoFtlMode'

const StyledEditor = styled.div`
  width: 100%;
  z-index: 0; /* gutter lays over menu otherwise */
`

const modeMappings = {
  groovy: new GroovyMode(),
  html: new HtmlMode(),
  xml: new XmlMode(),
  properties: new PropertiesMode(),
  json: new JsonMode(),
  htmlmixed: new ToccoFtlMode(),
  freemarkermixed: new ToccoFtlMode(),
  ftl: new ToccoFtlMode(),
  tql: new TqlMode(),
  less: new LessMode(),
  drools: new DroolsMode(),
  text: new TextMode()
}

const getMode = mode => _get(modeMappings, mode, mode)

const setEditorConfiguration = (editor, {
  mode,
  theme,
  showGutter,
  editorOptions = {}
}) => {
  editor.getSession().setMode(getMode(mode))
  editor.setTheme(`ace/theme/${theme}`)
  Object.entries(editorOptions).forEach(([k, v]) => {
    editor.setOption(k, v)
  })
  editor.renderer.setShowGutter(showGutter)
  editor.resize()
}

const AceEditor = props => {
  const {
    mode,
    theme = 'textmate',
    value,
    onChange,
    showGutter = true,
    editorOptions = {}
  } = props
  const containerReference = useRef(null)
  const editorReference = useRef(null)

  useEffect(() => {
    const aceEditor = ace.edit(containerReference.current)
    aceEditor.getSession().setValue(value)
    aceEditor.on('change', () => onChange(aceEditor.getValue()))
    setEditorConfiguration(aceEditor, props)
    editorReference.current = aceEditor

    return () => aceEditor.destroy()
  }, [])
  useEffect(() => {
    if (editorReference.current) {
      setEditorConfiguration(editorReference.current, props)
    }
  }, [mode, theme, showGutter, editorOptions])
  return <StyledEditor ref={containerReference}/>
}

AceEditor.propTypes = AceEditorPropTypes

export default AceEditor
<|endoftext|>


<commit_before>var assert = require("chai").assert;
var Artifactor = require("../");
var contract = require("truffle-contract");
var Schema = require("truffle-contract-schema");
var temp = require("temp").track();
var path = require("path");
var solc = require("solc");
var fs = require("fs");
var requireNoCache = require("require-nocache")(module);
var TestRPC = require("ethereumjs-testrpc");
var Web3 = require("web3");

describe("artifactor + require", function() {
  var Example;
  var accounts;
  var abi;
  var binary;
  var network_id;
  var artifactor;
  var provider = TestRPC.provider();
  var web3 = new Web3();
  web3.setProvider(provider)

  before(function(done) {
    web3.version.getNetwork(function(err, id) {
      if (err) return done(err);
      network_id = id;
      done();
    });
  });

  before(function(done) {
    this.timeout(10000);

    // Compile first
    var result = solc.compile(fs.readFileSync("./test/Example.sol", {encoding: "utf8"}), 1);

    // Clean up after solidity. Only remove solidity's listener,
    // which happens to be the first.
    process.removeListener("uncaughtException", process.listeners("uncaughtException")[0]);

    var compiled = Schema.normalize(result.contracts["Example"]);
    abi = compiled.abi;
    binary = compiled.bytecode;

    // Setup
    var dirPath = temp.mkdirSync({
      dir: path.resolve("./"),
      prefix: 'tmp-test-contract-'
    });

    var expected_filepath = path.join(dirPath, "Example.json");

    artifactor = new Artifactor(dirPath);

    artifactor.save({
      contractName: "Example",
      abi: abi,
      binary: binary,
      address: "0xe6e1652a0397e078f434d6dda181b218cfd42e01",
      network_id: network_id
    }).then(function() {
      var json = requireNoCache(expected_filepath);
      Example = contract(json);
      Example.setProvider(provider);
    }).then(done).catch(done);
  });

  before(function(done) {
    web3.eth.getAccounts(function(err, accs) {
      accounts = accs;

      Example.defaults({
        from: accounts[0]
      });

      done(err);
    });
  });

  after(function(done) {
    temp.cleanupSync();
    done();
  });

  it("should set the transaction hash of contract instantiation", function() {
    return Example.new({gas: 3141592}).then(function(example) {
      assert(example.transactionHash, "transactionHash should be non-empty");
    });
  });

  it("should get and set values via methods and get values via .call", function(done) {
    var example;
    Example.new({gas: 3141592}).then(function(instance) {
      example = instance;
      return example.value.call();
    }).then(function(value) {
      assert.equal(value.valueOf(), 1, "Starting value should be 1");
      return example.setValue(5);
    }).then(function(tx) {
      return example.value.call();
    }).then(function(value) {
      assert.equal(value.valueOf(), 5, "Ending value should be five");
    }).then(done).catch(done);
  });

  it("shouldn't synchronize constant functions", function(done) {
    var example;
    Example.new(5, {gas: 3141592}).then(function(instance) {
      example = instance;
      return example.getValue();
    }).then(function(value) {
      assert.equal(value.valueOf(), 5, "Value should have been retrieved without explicitly calling .call()");
    }).then(done).catch(done);
  });

  it("should allow BigNumbers as input parameters, and not confuse them as transaction objects", function(done) {
    // BigNumber passed on new()
    var example = null;
    Example.new(web3.toBigNumber(30), {gas: 3141592}).then(function(instance) {
      example = instance;
      return example.value.call();
    }).then(function(value) {
      assert.equal(value.valueOf(), 30, "Starting value should be 30");
      // BigNumber passed in a transaction.
      return example.setValue(web3.toBigNumber(25), {gas: 3141592});
    }).then(function(tx) {
      return example.value.call();
    }).then(function(value) {
      assert.equal(value.valueOf(), 25, "Ending value should be twenty-five");
      // BigNumber passed in a call.
      return example.parrot.call(web3.toBigNumber(865));
    }).then(function(parrot_value) {
      assert.equal(parrot_value.valueOf(), 865, "Parrotted value should equal 865")
    }).then(done).catch(done);
  });

  it("should return transaction hash, logs and receipt when using synchronised transactions", function(done) {
    var example = null;
    Example.new({gas: 3141592}).then(function(instance) {
      example = instance;
      return example.triggerEvent();
    }).then(function(result) {
      assert.isDefined(result.tx, "transaction hash wasn't returned");
      assert.isDefined(result.logs, "synchronized transaction didn't return any logs");
      assert.isDefined(result.receipt, "synchronized transaction didn't return a receipt");
      assert.isOk(result.tx.length > 42, "Unexpected transaction hash"); // There has to be a better way to do this.
      assert.equal(result.tx, result.receipt.transactionHash, "Transaction had different hash than receipt");
      assert.equal(result.logs.length, 1, "logs array expected to be 1");

      var log = result.logs[0];

      assert.equal("ExampleEvent", log.event);
      assert.equal(accounts[0], log.args._from);
      assert.equal(8, log.args.num); // 8 is a magic number inside Example.sol
    }).then(done).catch(done);
  });

  it("should trigger the fallback function when calling sendTransaction()", function() {
    var example = null;
    return Example.new({gas: 3141592}).then(function(instance) {
      example = instance;
      return example.fallbackTriggered();
    }).then(function(triggered) {
      assert(triggered == false, "Fallback should not have been triggered yet");
      return example.sendTransaction({
        value: web3.toWei(1, "ether")
      });
    }).then(function(results) {
      return new Promise(function(accept, reject) {
        return web3.eth.getBalance(example.address, function(err, balance) {
          if (err) return reject(err);
          accept(balance);
        });
      });
    }).then(function(balance) {
      assert(balance == web3.toWei(1, "ether"));
    });
  });

  it("should trigger the fallback function when calling send() (shorthand notation)", function() {
    var example = null;
    return Example.new({gas: 3141592}).then(function(instance) {
      example = instance;
      return example.fallbackTriggered();
    }).then(function(triggered) {
      assert(triggered == false, "Fallback should not have been triggered yet");
      return example.send(web3.toWei(1, "ether"));
    }).then(function(results) {
      return new Promise(function(accept, reject) {
        return web3.eth.getBalance(example.address, function(err, balance) {
          if (err) return reject(err);
          accept(balance);
        });
      });
    }).then(function(balance) {
      assert(balance == web3.toWei(1, "ether"));
    });
  });

  it("errors when setting an invalid provider", function(done) {
    try {
      Example.setProvider(null);
      assert.fail("setProvider() should have thrown an error");
    } catch (e) {
      // Do nothing with the error.
    }
    done();
  });

  it("creates a network object when an address is set if no network specified", function(done) {
    var NewExample = contract({
      abi: abi,
      unlinked_binary: binary
    });

    NewExample.setProvider(provider);
    NewExample.defaults({
      from: accounts[0]
    });

    assert.equal(NewExample.network_id, null);

    NewExample.new({gas: 3141592}).then(function(instance) {
      // We have a network id in this case, with new(), since it was detected,
      // but no further configuration.
      assert.equal(NewExample.network_id, network_id);
      assert.equal(NewExample.toJSON().networks[network_id], null);

      NewExample.address = instance.address;

      assert.equal(NewExample.toJSON().networks[network_id].address, instance.address);

      done();
    }).catch(done);
  });

  it("doesn't error when calling .links() or .events() with no network configuration", function(done) {
    var event_abi = {
      "anonymous": false,
      "inputs": [
        {
          "indexed": true,
          "name": "nameHash",
          "type": "bytes32"
        },
        {
          "indexed": true,
          "name": "releaseHash",
          "type": "bytes32"
        }
      ],
      "name": "PackageRelease",
      "type": "event"
    };

    var MyContract = contract({
      contractName: "MyContract",
      abi: [
        event_abi
      ],
      binary: "0x12345678",
    });

    MyContract.setNetwork(5);

    var expected_event_topic = web3.sha3("PackageRelease(bytes32,bytes32)");

    // We want to make sure these don't throw when a network configuration doesn't exist.
    // While we're at it, lets make sure we still get the event we expect.
    assert.deepEqual(MyContract.links, {});
    assert.deepEqual(MyContract.events[expected_event_topic], event_abi);

    done();
  });
});
<commit_msg>Import ganache-cli in test<commit_after>var assert = require("chai").assert;
var Artifactor = require("../");
var contract = require("truffle-contract");
var Schema = require("truffle-contract-schema");
var temp = require("temp").track();
var path = require("path");
var solc = require("solc");
var fs = require("fs");
var requireNoCache = require("require-nocache")(module);
var TestRPC = require("ganache-cli");
var Web3 = require("web3");

describe("artifactor + require", function() {
  var Example;
  var accounts;
  var abi;
  var binary;
  var network_id;
  var artifactor;
  var provider = TestRPC.provider();
  var web3 = new Web3();
  web3.setProvider(provider)

  before(function(done) {
    web3.version.getNetwork(function(err, id) {
      if (err) return done(err);
      network_id = id;
      done();
    });
  });

  before(function(done) {
    this.timeout(10000);

    // Compile first
    var result = solc.compile(fs.readFileSync("./test/Example.sol", {encoding: "utf8"}), 1);

    // Clean up after solidity. Only remove solidity's listener,
    // which happens to be the first.
    process.removeListener("uncaughtException", process.listeners("uncaughtException")[0]);

    var compiled = Schema.normalize(result.contracts["Example"]);
    abi = compiled.abi;
    binary = compiled.bytecode;

    // Setup
    var dirPath = temp.mkdirSync({
      dir: path.resolve("./"),
      prefix: 'tmp-test-contract-'
    });

    var expected_filepath = path.join(dirPath, "Example.json");

    artifactor = new Artifactor(dirPath);

    artifactor.save({
      contractName: "Example",
      abi: abi,
      binary: binary,
      address: "0xe6e1652a0397e078f434d6dda181b218cfd42e01",
      network_id: network_id
    }).then(function() {
      var json = requireNoCache(expected_filepath);
      Example = contract(json);
      Example.setProvider(provider);
    }).then(done).catch(done);
  });

  before(function(done) {
    web3.eth.getAccounts(function(err, accs) {
      accounts = accs;

      Example.defaults({
        from: accounts[0]
      });

      done(err);
    });
  });

  after(function(done) {
    temp.cleanupSync();
    done();
  });

  it("should set the transaction hash of contract instantiation", function() {
    return Example.new({gas: 3141592}).then(function(example) {
      assert(example.transactionHash, "transactionHash should be non-empty");
    });
  });

  it("should get and set values via methods and get values via .call", function(done) {
    var example;
    Example.new({gas: 3141592}).then(function(instance) {
      example = instance;
      return example.value.call();
    }).then(function(value) {
      assert.equal(value.valueOf(), 1, "Starting value should be 1");
      return example.setValue(5);
    }).then(function(tx) {
      return example.value.call();
    }).then(function(value) {
      assert.equal(value.valueOf(), 5, "Ending value should be five");
    }).then(done).catch(done);
  });

  it("shouldn't synchronize constant functions", function(done) {
    var example;
    Example.new(5, {gas: 3141592}).then(function(instance) {
      example = instance;
      return example.getValue();
    }).then(function(value) {
      assert.equal(value.valueOf(), 5, "Value should have been retrieved without explicitly calling .call()");
    }).then(done).catch(done);
  });

  it("should allow BigNumbers as input parameters, and not confuse them as transaction objects", function(done) {
    // BigNumber passed on new()
    var example = null;
    Example.new(web3.toBigNumber(30), {gas: 3141592}).then(function(instance) {
      example = instance;
      return example.value.call();
    }).then(function(value) {
      assert.equal(value.valueOf(), 30, "Starting value should be 30");
      // BigNumber passed in a transaction.
      return example.setValue(web3.toBigNumber(25), {gas: 3141592});
    }).then(function(tx) {
      return example.value.call();
    }).then(function(value) {
      assert.equal(value.valueOf(), 25, "Ending value should be twenty-five");
      // BigNumber passed in a call.
      return example.parrot.call(web3.toBigNumber(865));
    }).then(function(parrot_value) {
      assert.equal(parrot_value.valueOf(), 865, "Parrotted value should equal 865")
    }).then(done).catch(done);
  });

  it("should return transaction hash, logs and receipt when using synchronised transactions", function(done) {
    var example = null;
    Example.new({gas: 3141592}).then(function(instance) {
      example = instance;
      return example.triggerEvent();
    }).then(function(result) {
      assert.isDefined(result.tx, "transaction hash wasn't returned");
      assert.isDefined(result.logs, "synchronized transaction didn't return any logs");
      assert.isDefined(result.receipt, "synchronized transaction didn't return a receipt");
      assert.isOk(result.tx.length > 42, "Unexpected transaction hash"); // There has to be a better way to do this.
      assert.equal(result.tx, result.receipt.transactionHash, "Transaction had different hash than receipt");
      assert.equal(result.logs.length, 1, "logs array expected to be 1");

      var log = result.logs[0];

      assert.equal("ExampleEvent", log.event);
      assert.equal(accounts[0], log.args._from);
      assert.equal(8, log.args.num); // 8 is a magic number inside Example.sol
    }).then(done).catch(done);
  });

  it("should trigger the fallback function when calling sendTransaction()", function() {
    var example = null;
    return Example.new({gas: 3141592}).then(function(instance) {
      example = instance;
      return example.fallbackTriggered();
    }).then(function(triggered) {
      assert(triggered == false, "Fallback should not have been triggered yet");
      return example.sendTransaction({
        value: web3.toWei(1, "ether")
      });
    }).then(function(results) {
      return new Promise(function(accept, reject) {
        return web3.eth.getBalance(example.address, function(err, balance) {
          if (err) return reject(err);
          accept(balance);
        });
      });
    }).then(function(balance) {
      assert(balance == web3.toWei(1, "ether"));
    });
  });

  it("should trigger the fallback function when calling send() (shorthand notation)", function() {
    var example = null;
    return Example.new({gas: 3141592}).then(function(instance) {
      example = instance;
      return example.fallbackTriggered();
    }).then(function(triggered) {
      assert(triggered == false, "Fallback should not have been triggered yet");
      return example.send(web3.toWei(1, "ether"));
    }).then(function(results) {
      return new Promise(function(accept, reject) {
        return web3.eth.getBalance(example.address, function(err, balance) {
          if (err) return reject(err);
          accept(balance);
        });
      });
    }).then(function(balance) {
      assert(balance == web3.toWei(1, "ether"));
    });
  });

  it("errors when setting an invalid provider", function(done) {
    try {
      Example.setProvider(null);
      assert.fail("setProvider() should have thrown an error");
    } catch (e) {
      // Do nothing with the error.
    }
    done();
  });

  it("creates a network object when an address is set if no network specified", function(done) {
    var NewExample = contract({
      abi: abi,
      unlinked_binary: binary
    });

    NewExample.setProvider(provider);
    NewExample.defaults({
      from: accounts[0]
    });

    assert.equal(NewExample.network_id, null);

    NewExample.new({gas: 3141592}).then(function(instance) {
      // We have a network id in this case, with new(), since it was detected,
      // but no further configuration.
      assert.equal(NewExample.network_id, network_id);
      assert.equal(NewExample.toJSON().networks[network_id], null);

      NewExample.address = instance.address;

      assert.equal(NewExample.toJSON().networks[network_id].address, instance.address);

      done();
    }).catch(done);
  });

  it("doesn't error when calling .links() or .events() with no network configuration", function(done) {
    var event_abi = {
      "anonymous": false,
      "inputs": [
        {
          "indexed": true,
          "name": "nameHash",
          "type": "bytes32"
        },
        {
          "indexed": true,
          "name": "releaseHash",
          "type": "bytes32"
        }
      ],
      "name": "PackageRelease",
      "type": "event"
    };

    var MyContract = contract({
      contractName: "MyContract",
      abi: [
        event_abi
      ],
      binary: "0x12345678",
    });

    MyContract.setNetwork(5);

    var expected_event_topic = web3.sha3("PackageRelease(bytes32,bytes32)");

    // We want to make sure these don't throw when a network configuration doesn't exist.
    // While we're at it, lets make sure we still get the event we expect.
    assert.deepEqual(MyContract.links, {});
    assert.deepEqual(MyContract.events[expected_event_topic], event_abi);

    done();
  });
});
<|endoftext|>


<commit_before>var assert = require("assert");
var solc = require("solc");
var Schema = require("../");
var debug = require("debug")("test:solc");

describe("solc", function() {
  var exampleSolidity = `pragma solidity ^0.4.24;
pragma experimental "v0.5.0";

contract A {
  uint x;

  function doStuff() public {
    x = 5;
  }
}

contract B {
  function somethingElse() public pure {}
}
`;

  it("processes solc compile output correctly", function(done) {
    this.timeout(10000);
    var result = solc.compile(exampleSolidity, 1);

    var data = result.contracts[":A"];

    var A = Schema.normalize(data);

    assert.deepEqual(A.abi, JSON.parse(data.interface));
    assert.equal(A.bytecode, "0x" + data.bytecode);
    assert.equal(A.deployedBytecode, "0x" + data.runtimeBytecode);
    assert.equal(A.sourceMap, data.srcmap);
    assert.equal(A.deployedSourceMap, data.srcmapRuntime);

    done();
  });

  it("processes solc compileStandard output correctly", function(done) {
    this.timeout(5000);

    var solcIn = JSON.stringify({
      language: "Solidity",
      sources: {
        "A.sol": {
          "content": exampleSolidity
        }
      },
      settings: {
        outputSelection: {
          "*": {
            "*": [
              "abi",
              "evm.bytecode.object",
              "evm.bytecode.sourceMap",
              "evm.deployedBytecode.object",
              "evm.deployedBytecode.sourceMap",
              "devdoc",
              "userdoc"
            ]
          }
        }
      }
    });
    var solcOut = JSON.parse(solc.compileStandard(solcIn));

    // contracts now grouped by solidity source file
    var rawA = solcOut.contracts["A.sol"].A;

    var A = Schema.normalize(rawA);

    var expected = {
      abi: rawA.abi,
      bytecode: "0x" + rawA.evm.bytecode.object,
      deployedBytecode: "0x" + rawA.evm.deployedBytecode.object,
      sourceMap: rawA.evm.bytecode.sourceMap,
      deployedSourceMap: rawA.evm.deployedBytecode.sourceMap
    };

    Object.keys(expected).forEach(function (key)  {
      var expectedValue = expected[key];
      var actualValue = A[key];

      assert.deepEqual(
        actualValue, expectedValue,
        "Mismatched schema output for key `" + key + "` (" +
        JSON.stringify(actualValue) + " != " + JSON.stringify(expectedValue) +
        ")"
      );
    });

    // throws error if invalid
    Schema.validate(A);
    done();
  });
});
<commit_msg>Remove test for old solc.compile interface<commit_after>var assert = require("assert");
var solc = require("solc");
var Schema = require("../");
var debug = require("debug")("test:solc"); // eslint-disable-line no-unused-vars

describe("solc", function() {
  var exampleSolidity = `pragma solidity ^0.5.0;

contract A {
  uint x;

  function doStuff() public {
    x = 5;
  }
}

contract B {
  function somethingElse() public pure {}
}
`;

  it("processes solc standard JSON output correctly", function(done) {
    this.timeout(5000);

    var solcIn = JSON.stringify({
      language: "Solidity",
      sources: {
        "A.sol": {
          content: exampleSolidity
        }
      },
      settings: {
        outputSelection: {
          "*": {
            "*": [
              "abi",
              "evm.bytecode.object",
              "evm.bytecode.sourceMap",
              "evm.deployedBytecode.object",
              "evm.deployedBytecode.sourceMap",
              "devdoc",
              "userdoc"
            ]
          }
        }
      }
    });
    var solcOut = JSON.parse(solc.compile(solcIn));

    // contracts now grouped by solidity source file
    var rawA = solcOut.contracts["A.sol"].A;

    var A = Schema.normalize(rawA);

    var expected = {
      abi: rawA.abi,
      bytecode: "0x" + rawA.evm.bytecode.object,
      deployedBytecode: "0x" + rawA.evm.deployedBytecode.object,
      sourceMap: rawA.evm.bytecode.sourceMap,
      deployedSourceMap: rawA.evm.deployedBytecode.sourceMap
    };

    Object.keys(expected).forEach(function(key) {
      var expectedValue = expected[key];
      var actualValue = A[key];

      assert.deepEqual(
        actualValue,
        expectedValue,
        "Mismatched schema output for key `" +
          key +
          "` (" +
          JSON.stringify(actualValue) +
          " != " +
          JSON.stringify(expectedValue) +
          ")"
      );
    });

    // throws error if invalid
    Schema.validate(A);
    done();
  });
});
<|endoftext|>


<commit_before>import React from 'react'

function Index(props) {
  return (

Cerebral

          {
            props.compile(`
> Declarative **state and side effects management** for popular JavaScript frameworks
`).tree
          }

              introduction

              api

              {
                props.compile(`
Writing **declaratively**:

\`\`\`js

Hello

\`\`\`
`).tree
              }

              {
                props.compile(`
Compared to **imperatively**:

\`\`\`js
const h1 = document.createElement('h1')
h1.className = 'header'
document.body.appendChild(h1)
\`\`\`
`).tree
              }

          {
            props.compile(`
It makes perfect sense for us to write our UIs in a declarative manner. The reason is that we need to reuse UI elements and compose them together in different configurations. One can also claim that declarative code reads better, not because it is less syntax, but because you only describe **what** you want, not **how** you want it.

But what about our business logic, can we get the same benefits there?

`).tree
          }

              {
                props.compile(`
Writing **declaratively**:

\`\`\`js
[
  setLoading(true),
  getUser, {
    success: setUser,
    error: setError
  },
  setLoading(false),
]
\`\`\`
        `).tree
              }

              {
                props.compile(`
Compared to **imperatively**:

\`\`\`js
function getUser() {
  this.isLoading = true
  ajax.get('/user')
    .then((user) => {
      this.data = user
      this.isLoading = false
    })
    .catch((error) => {
      this.error = error
      this.isLoading = false
    })
}
\`\`\`
        `).tree
              }

          {
            props.compile(`
You might think this example tries to highlight "less lines of code", but it is actually about reaching for these properties:

- **Composability**
- **Readability**
- **Reusability**
- **Testability**

All these properties makes **better code** and **scalable code**. The declarative approach inherits all of these properties by default. In addition to this
it allows us to build developer tools:

![debugger](/images/debugger.gif)

> *Read on to learn more about how Cerebral enforces scalable code and gives you insight into the inner workings of your app*
`).tree
          }

              introduction

              api

            Released under the MIT License
            Copyright © 2017 Christian Alfoni

  )
}

export default Index
<commit_msg>docs(website): add blog post on front page<commit_after>import React from 'react'

function Index(props) {
  return (

Cerebral

          {
            props.compile(`
> Declarative **state and side effects management** for popular JavaScript frameworks
`).tree
          }

              introduction

              api

              {
                props.compile(`
Writing **declaratively**:

\`\`\`js

Hello

\`\`\`
`).tree
              }

              {
                props.compile(`
Compared to **imperatively**:

\`\`\`js
const h1 = document.createElement('h1')
h1.className = 'header'
document.body.appendChild(h1)
\`\`\`
`).tree
              }

          {
            props.compile(`
It makes perfect sense for us to write our UIs in a declarative manner. The reason is that we need to reuse UI elements and compose them together in different configurations. One can also claim that declarative code reads better, not because it is less syntax, but because you only describe **what** you want, not **how** you want it.

But what about our business logic, can we get the same benefits there?

`).tree
          }

              {
                props.compile(`
Writing **declaratively**:

\`\`\`js
[
  setLoading(true),
  getUser, {
    success: setUser,
    error: setError
  },
  setLoading(false),
]
\`\`\`
        `).tree
              }

              {
                props.compile(`
Compared to **imperatively**:

\`\`\`js
function getUser() {
  this.isLoading = true
  ajax.get('/user')
    .then((user) => {
      this.data = user
      this.isLoading = false
    })
    .catch((error) => {
      this.error = error
      this.isLoading = false
    })
}
\`\`\`
        `).tree
              }

          {
            props.compile(`
You might think this example tries to highlight "less lines of code", but it is actually about reaching for these properties:

- **Composability**
- **Readability**
- **Reusability**
- **Testability**

All these properties makes **better code** and **scalable code**. The declarative approach inherits all of these properties by default.
You can read more about declarative code in this short blog post, [Business logic as a data structure](https://www.jsblog.io/articles/christianalfoni/business_logic_as_a_data_structure).

Declarative code also allows us to build developer tools that gives you valuable information:

![debugger](/images/debugger.gif)

> *Read on to learn more about how Cerebral enforces scalable code and gives you insight into the inner workings of your app*
`).tree
          }

              introduction

              api

            Released under the MIT License
            Copyright © 2017 Christian Alfoni

  )
}

export default Index
<|endoftext|>


<commit_before>var Metalsmith = require('metalsmith');
var reactTemplate = require('metalsmith-react-templates');
var templates  = require('metalsmith-templates');
var browserify = require('metalsmith-browserify');
var reactify = require('reactify');

Metalsmith(__dirname)
  .clean(true)
  .use(reactTemplate({
    directory: "templates",
    nonStatic: true
  }))
  .use(browserify({
    files: ['../scripts/loader.js'],
    dest: 'bundle.js',
    transforms: [reactify]
  }))
  .destination('./build')
  .build(function(err) {
    if (err) throw err;
  })
<commit_msg>Removed unused dependency<commit_after>var Metalsmith = require('metalsmith');
var reactTemplate = require('metalsmith-react-templates');
var browserify = require('metalsmith-browserify');
var reactify = require('reactify');

Metalsmith(__dirname)
  .clean(true)
  .use(reactTemplate({
    directory: "templates",
    nonStatic: true
  }))
  .use(browserify({
    files: ['../scripts/loader.js'],
    dest: 'bundle.js',
    transforms: [reactify]
  }))
  .destination('./build')
  .build(function(err) {
    if (err) throw err;
  })
<|endoftext|>


<commit_before>L.Mapzen.apiKey = 'search-RH8pVLv';

var map = L.Mapzen.map('map', {
  tangramOptions: {
    scene: L.Mapzen.BasemapStyles.Zinc
  }

});

var locator = L.Mapzen.locator();
locator.addTo(map);

var control = L.routing.control({
  waypoints: [
    L.latLng(37.752, -122.418),
    L.latLng(37.779, -122.391)
  ],
  // You can get your own Mapzen turn-by-turn & search API key from the Mapzen developer portal (https://mapzen.com/developers/)
  geocoder: L.Control.Geocoder.mapzen(),
  reverseWaypoints: true,
  router: L.Routing.mapzen('valhalla-PVA4Y8g', {costing: 'auto'}),
  formatter: new L.Routing.mapzenFormatter(),
  summaryTemplate:'
{name}

{distance}, {time}
'
}).addTo(map);

L.Routing.errorControl(control).addTo(map);<commit_msg>passing api key in right way in example<commit_after>L.Mapzen.apiKey = 'search-RH8pVLv';

var map = L.Mapzen.map('map', {
  tangramOptions: {
    scene: L.Mapzen.BasemapStyles.Zinc
  }

});

var locator = L.Mapzen.locator();
locator.addTo(map);

var control = L.routing.control({
  waypoints: [
    L.latLng(37.752, -122.418),
    L.latLng(37.779, -122.391)
  ],
  // You can get your own Mapzen turn-by-turn & search API key from the Mapzen developer portal (https://mapzen.com/developers/)
  geocoder: L.Control.Geocoder.mapzen('search-RH8pVLv'),
  reverseWaypoints: true,
  router: L.Routing.mapzen('valhalla-PVA4Y8g', {costing: 'auto'}),
  formatter: new L.Routing.mapzenFormatter(),
  summaryTemplate:'
{name}

{distance}, {time}
'
}).addTo(map);

L.Routing.errorControl(control).addTo(map);<|endoftext|>