// Private: Handles the logic for a round of betting.
  //
  // round - The name of the betting round, e.g., 'preflop', 'flop', 'turn'
  //
  // Returns an {Observable} signaling the completion of the round
  doBettingRound(round) {
    // If there aren't at least two players with chips to bet, move along to a
    // showdown.
    let playersRemaining = this.getPlayersInHand();
    let playersWhoCanBet = _.filter(playersRemaining, p => !p.isAllIn);
    if (playersWhoCanBet.length < 2) {
      let result = { isHandComplete: false };
      return rx.Observable.return(result);
    }

    this.orderedPlayers = PlayerOrder.determine(this.players, this.dealerButton, round);
    let previousActions = {};
    let roundEnded = new rx.Subject();

    this.resetPlayersForBetting(round, previousActions);

    // Take the players remaining in the hand, in order, and poll each for
    // an action. This cycle will be repeated until the round is ended, which
    // can occur after any player action.
    let queryPlayers = rx.Observable.fromArray(this.orderedPlayers)
      .where((player) => player.isInHand && !player.isAllIn)
      .concatMap((player) => this.deferredActionForPlayer(player, previousActions, roundEnded))
      .repeat()
      .takeUntil(roundEnded)
      .publish();

    queryPlayers.connect();
    return roundEnded.do(() => this.potManager.endBettingRound());
  }
Beispiel #2
0
test('"transformConfig" listens to action on "process" input', function (t) {
  t.plan(1);

  const funcA = td.function();

  const transformConfig = proxyquire('../lib/utils', {
    './ShellUtil': {
      spawn: funcA
    }
  }).transformConfig;

  const subjectA = new Rx.Subject();

  const r = transformConfig('taskName', {
    dependsOn: ['a'],
    process(input, output) {
      input.on('action', (action) => {
        t.deepEqual(action, {type: 'action'});
      });
    }
  });

  r.process({a: subjectA}).subscribe(() => {});

  subjectA.onNext({type: 'ready'});
  subjectA.onNext({type: 'action'});
});
Beispiel #3
0
const run = ()=>{


    refLog.info('log',"Run Begin!!!");

    const data1_subuject = new Rx.Subject()
    const data2_subject = new Rx.Subject()

    Rx.Observable.when(data1_subuject.and(data2_subject).thenDo((data1,data2)=>{return {data1:data1,data2:data2}}))
    .flatMap(data=>{
        var s = new Rx.Subject()
        get_data3(data.data1 , data.data2).then((data3)=>{
          refLog.info('warn',"data3 request received");
          s.onNext(data3);
          s.onCompleted();
        })
        refLog.info('log',"data3 request send!");

        return s
    }).subscribe((data)=>{
      refLog.info('log',"run finished!!!----" + data.url + '---' + data.data);
    })

    get_data1("Hello").then((e) => {refLog.info('warn',"data1 request received!");data1_subuject.onNext(e)});
    refLog.info('log',"data1 request send!");
    get_data2("World").then((e) => {refLog.info('warn',"data2 request received!");data2_subject.onNext(e)});
    refLog.info('log',"data2 request send!");

    refLog.info('warn',"run pending!!!");


}
Beispiel #4
0
 quit() {
   this.gameEnded.onNext(true);
   this.gameEnded.onCompleted();
   this.isRunning = false;
   this.subscription.dispose();
   // this.endTimeout = setTimeout(() => this.chatSubscription.dispose(), 60000);
 }
Beispiel #5
0
 .on("end", function() {
  // Make sure the last one got called as well
  batchStream.onNext(dockingGroupArray);
  batchStream.onCompleted();
  console.log("done");
  //  process.exit();
 });
Beispiel #6
0
test('should be able to hook into tree node', t => {
  const testErr = new Error('bar');
  const testVal = 42;
  const initialVal = {
    a: 1,
    b: 2
  };
  const finalVal = {
    a: 43,
    b: 44
  };
  const state = createState();
  const action = new Rx.Subject();

  state('foo.bar').setInitialState(initialVal);

  state('foo.bar').reduce(action, (state, val) => {
    t.deepEqual(state, initialVal);
    t.is(val, testVal);
    return finalVal
  })

  t.plan(3);

  state('foo.bar').asObservable().skip(1)
    .subscribe(val => t.deepEqual(val, finalVal));

  state.connect();

  action.onNext(testVal);
});
Beispiel #7
0
test('"transformConfig" "ready" action from parent task triggers "start"', function (t) {
  t.plan(2);

  const funcA = td.function();
  td.when(funcA(td.matchers.anything())).thenDo(() => new Rx.BehaviorSubject(null));

  const transformConfig = proxyquire('../lib/utils', {
    './ShellUtil': {
      spawn: funcA
    }
  }).transformConfig;

  const r = transformConfig('taskName', {
    dependsOn: ['a'],
    start: 'command b'
  });

  const subject = new Rx.Subject();

  r.process({a: subject}).subscribe(() => {});

  t.doesNotThrow(() => {
    td.verify(funcA(td.matchers.anything()), {times: 0, ignoreExtraArgs: true});
  });

  subject.onNext({type: 'ready'});

  t.doesNotThrow(() => {
    td.verify(funcA('command b'), {times: 1});
  });
});
Beispiel #8
0
export const createTreeSetNextState = (childrenObservable) => {
  const newStateSubject = new Rx.Subject();
  newStateSubject
    .withLatestFrom(childrenObservable)
    .subscribe(([newState, children]) => {
      const keys = Object.keys(children);
      const newKeys = Object.keys(newState);

      if (newKeys.length !== keys.length) {
        throwShapeError();
      }

      keys.forEach(key => {
        if (key in newState) {
          children[key].getValue().setNextState(newState[key]);
        } else {
          throwShapeError();
        }
      });
    });

  return (newState) => {
    newStateSubject.onNext(newState);
  };
};
  it('plays audio when it receives the play command', function(done) {
    this.timeout(4000)

    const cmds$ = new Subject()
    const audio$ = audioDriver(cmds$).share()

    audio$.filter(evt => evt.event === 'load')
      .subscribe(evt => cmds$.onNext({action: 'play', id: evt.id}))

    audio$.buffer(audio$.filter(evt => evt.event === 'finish'))
      .subscribe(events => {
        expect(events.map(evt => evt.event), 'to contain', 'load')
        expect(events.map(evt => evt.event), 'to contain', 'play')
        expect(events.map(evt => evt.event), 'to contain', 'playing')
        expect(events.map(evt => evt.event), 'to contain', 'finish')

        expect(events.slice(-1)[0], 'to satisfy', {
          event: 'finish',
          playing: false,
          paused: false,
        })
        done()
      })

    cmds$.onNext({src: '/test/test.mp3'})
  })
  it('can pause and resume the audio', function(done) {
    this.timeout(4000)

    const cmds$ = new Subject()
    const audio$ = audioDriver(cmds$).share()

    audio$.first(evt => evt.event === 'load')
      .subscribe(evt => cmds$.onNext({action: 'play', id: evt.id}))

    audio$.first(evt => evt.event === 'playing')
      .subscribe(evt => cmds$.onNext({action: 'pause', id: evt.id}))

    audio$.first(evt => evt.event === 'pause')
      .subscribe(evt => {
        expect(evt, 'to satisfy', {paused: true, playing: false})
        cmds$.onNext({action: 'play', id: evt.id})
      })

    audio$.buffer(audio$.filter(evt => evt.event === 'finish'))
      .subscribe(events => {
        expect(events.map(evt => evt.event), 'to contain', 'pause')
        expect(events.map(evt => evt.event), 'to contain', 'playing')

        done()
      })

    cmds$.onNext({src: '/test/test.mp3'})
  })
Beispiel #11
0
test('should be able to hook into multiple observables', t => {
  const finalVals = [
    [
      1,
      null
    ],
    [
      1,
      2
    ]
  ]
  const state = createState();
  const action1 = new Rx.Subject();
  const action2 = new Rx.Subject();
  state('foo.bar', null).reduce([action1, action2], (state, vals) => {
    return vals;
  })

  t.plan(1);


  state('foo.bar').asObservable().skip(1).take(2).toArray()
    .subscribe(vals => t.deepEqual(vals, finalVals));

  state.connect();

  action1.onNext(finalVals[0][0]);
  action2.onNext(finalVals[1][1]);
});
Beispiel #12
0
test('"transformConfig" "ready" action from single parent task will respawn "start"', function (t) {
  t.plan(2);

  const funcA = td.function();
  td.when(funcA(td.matchers.anything())).thenDo(() => new Rx.Observable.just(null));

  const transformConfig = proxyquire('../lib/utils', {
    './ShellUtil': {
      spawn: funcA
    }
  }).transformConfig;

  const r = transformConfig('taskName', {
    dependsOn: ['a'],
    start: 'command b'
  });

  const subjectA = new Rx.Subject();

  r.process({a: subjectA}).subscribe(() => {});

  subjectA.onNext({type: 'ready'});

  t.doesNotThrow(() => {
    td.verify(funcA('command b'), {times: 1});
  });

  subjectA.onNext({type: 'ready'});

  t.doesNotThrow(() => {
    td.verify(funcA('command b'), {times: 2});
  });
});
  constructor(modulePath, maxConcurrency) {
    const freeWindowList = [];
    const invocationQueue = new Subject();
    const completionQueue = new Subject();

    // This method will find a window that is currently idle or if it doesn't
    // exist, create one.
    const getOrCreateWindow = () => {
      let item = freeWindowList.pop();
      if (item) return Observable.return(item);

      return Observable.fromPromise(rendererRequireDirect(modulePath));
    };

    // Here, we set up a pipeline that maps a stream of invocations (i.e.
    // something we can pass to executeJavaScriptMethod) => stream of Future
    // Results from various windows => Stream of completed results, for which we
    // throw the Window that completed the result back onto the free window stack.
    invocationQueue
      .map(({chain, args, retval}) => Observable.defer(() => {
        return getOrCreateWindow()
          .flatMap((wnd) => {
            d(`Actually invoking ${chain.join('.')}(${JSON.stringify(args)})`);
            let ret = wnd.executeJavaScriptMethodObservable(chain, ...args);

            ret.multicast(retval).connect();
            return ret.map(() => wnd).catch(Observable.return(wnd));
          });
      }))
      .merge(maxConcurrency)
      .subscribe((wnd) => {
        if (!wnd || !wnd.dispose) throw new Error("Bogus!");
        freeWindowList.push(wnd);
        completionQueue.onNext(true);
      });

    // Here, we create a version of RecursiveProxyHandler that will turn method
    // invocations into something we can push onto our invocationQueue pipeline.
    // This is the object that ends up being returned to the caller of
    // requireTaskPool.
    this.moduleProxy = RecursiveProxyHandler.create('__removeme__', (methodChain, args) => {
      let chain = methodChain.splice(1);

      d(`Queuing ${chain.join('.')}(${JSON.stringify(args)})`);
      let retval = new AsyncSubject();

      invocationQueue.onNext({ chain: ['requiredModule'].concat(chain), args, retval });
      return retval.toPromise();
    });

    // If we haven't received any invocations within a certain idle timeout
    // period, burn all of our BrowserWindow instances
    completionQueue.guaranteedThrottle(5*1000).subscribe(() => {
      d(`Freeing ${freeWindowList.length} taskpool processes`);
      while (freeWindowList.length > 0) {
        let wnd = freeWindowList.pop();
        if (wnd) wnd.dispose();
      }
    });
  }
  it('can stop the audio', function(done) {
    this.timeout(4000)

    const cmds$ = new Subject()
    const audio$ = audioDriver(cmds$).share()

    audio$.first(evt => evt.event === 'load')
      .subscribe(evt => {
        cmds$.onNext({action: 'play', id: evt.id})
        setTimeout(() => cmds$.onNext({action: 'stop', id: evt.id}), 200)
      })

    audio$.filter(evt => evt.event === 'playing')
      .skip(2).first()
      .subscribe(evt => cmds$.onNext({action: 'stop', id: evt.id}))

    audio$.buffer(audio$.filter(evt => evt.event === 'stop'))
      .subscribe(events => {
        expect(events.slice(-1)[0], 'to satisfy', {
          event: 'stop',
          playing: false,
          paused: false,
        })
        done()
      })

    cmds$.onNext({src: '/test/test.mp3'})
  })
Beispiel #15
0
test('should be able to hook into leaf node observable prior to initial state', t => {
  const testVal = 42;
  const initialVal = 12;
  const finalVal = 54;
  const state = createState();
  const action = new Rx.Subject();

  state.connect();

  state('foo.bar').hookReducers(action)
    .next((state, val) => {
      t.is(state, initialVal);
      t.is(val, testVal);
      return finalVal;
    });

  t.plan(3);

  state('foo.bar').asObservable().skip(1)
    .subscribe(val => t.is(val, finalVal));

  state('foo.bar')
    .setInitialState(initialVal)
    .connect();

  action.onNext(testVal);
});
    constructor() {
      const subject$ = new Rx.Subject();
      this._callback = (ev) => subject$.onNext(ev);

      // read-only Observable
      this.events$ = subject$.asObservable();
    }
Beispiel #17
0
test('should be able to hook into leaf node on next and error', t => {
  const testErr = new Error('baz');
  const testVal = 42;
  const initialVal = 12;
  const finalVals = [54, 66]
  const state = createState();
  const action = new Rx.Subject();

  state('foo.bar', initialVal).hookReducers(action)
    .next((state, val) => {
      t.is(state, initialVal);
      t.is(val, testVal);
      return finalVals[0];
    })
    .error((state, err) => {
      t.is(state, finalVals[0]);
      t.is(err, testErr);
      return finalVals[1];
    });

  t.plan(5);


  state('foo.bar').asObservable().skip(1).take(2).toArray()
    .subscribe(vals => t.deepEqual(vals, finalVals));

  state.connect();

  action.onNext(testVal);
  action.onError(testErr);
});
	it("should fail if the value is not an array",function()
	{
		var s = new Rx.Subject();
		var total = 0;
		s.iterate().subscribe(function(value){ total += value; });
		expect(function(){s.onNext(1)}).toThrow();
		s.onCompleted();
	});
Beispiel #19
0
function RenameTab({ tabs$, selection$ }) {
    const subject = new Subject();
    const newTabs$ = subject.withLatestFrom(tabs$, selection$, (name, tabs, selection) => ({ name, tabs, selection }))
        .map(getNewTabs)
        .filter(tabs => tabs != null);
    newTabs$.subscribe(tabs$);
    return subject;
}
Beispiel #20
0
 }, (err, result, body) => {
   if (err) {
     response.onError(err);
   } else {
     response.onNext(result.statusCode === 304 ? null : body);
   }
   response.onCompleted();
   response.dispose();
 }));
Beispiel #21
0
    // A pool a requests. Its promise will be resolved with the last
    // request added to the pool.
    function createRequestPool() {
        const requestsPromises = new Rx.Subject();
        const latestCompleted = requestsPromises.flatMapLatest(Rx.Observable.fromPromise);

        return {
            registerPromise: (promise) => requestsPromises.onNext(promise),
            promise: firstAsPromise(latestCompleted)
        };
    }
test('mapPropsStream renders null until stream of props emits value', t => {
  const props$ = new Subject()
  const Container = mapPropsStream(() => props$)('div')
  const wrapper = mount(<Container />)

  t.false(wrapper.some('div'))
  props$.onNext({ foo: 'bar' })
  t.is(wrapper.find('div').prop('foo'), 'bar')
})
Beispiel #23
0
const main = () => {
  const filename = process.argv[4]
  const clockDeviceName = process.argv[2]
  const messageDeviceName = process.argv[3]
  Console.log('Starting recording to', filename)
  const fileStream = fs.createWriteStream(filename)
  const stdin = RxNode.fromStream(process.stdin, 'end')
  stdin.finally(() => fileStream.end())

  const clockInput = new midi.input()
  clockInput.ignoreTypes(false, false, false)

  const messageInput = new midi.input()
  messageInput.ignoreTypes(false, false, false)

  const closePorts = () => {
    Console.log('Closing ports')
    clockInput.closePort()
    messageInput.closePort()
  }

  process.on('exit', closePorts)
  process.on('SIGINT', closePorts)
  process.on('uncaughtException', closePorts)

  const clockInputSubject = new Rx.Subject()
  clockInput.on('message', (deltaTime, message) => clockInputSubject.onNext([deltaTime, message]))
  const clock = clockInputSubject.filter(R.flip(R.contains)([ClockTick, ClockStart]))

  const messageInputSubject = new Rx.Subject()
  messageInput.on('message', (deltaTime, message) => messageInputSubject.onNext([deltaTime, message]))
  const messages = messageInputSubject.filter(R.complement(R.flip(R.contains)([ClockTick, ClockStart])))

  clockInput.openPort(getPortNumber(clockDeviceName))
  messageInput.openPort(getPortNumber(messageDeviceName))

  const position = clock.scan(([phrase, bar, beat, tick], message) => {
    if (R.equals(message, ClockStart)) {
      return [0,0,0,0]
    }

    const tickOverflow = tick === 23 ? 1 : 0
    tick = (tick + 1) % 24
    const beatOverflow = beat === 3 && tickOverflow ? 1 : 0
    beat = (beat + tickOverflow) % 4
    const barOverflow = bar === 3 && beatOverflow ? 1 : 0
    bar = (bar + beatOverflow) % 4
    phrase += barOverflow
    return [phrase, bar, beat, tick]
  }, [0, 0, 0, 0])

  messages.withLatestFrom(position, Array)
    .map(R.reverse)
    .map(JSON.stringify)
    .subscribe(serializedData => fileStream.write(serializedData + '\n'))
}
Beispiel #24
0
export function Model(initial) {
  let current = undefined
  const subject = new Subject()
  const model = subject.startWith(initial).scan((state, fn) => fn(state)).shareReplay(1)
  model.subscribe(val => current = val)
  model.set = val => subject.onNext(() => val)
  model.get = () => current
  model.modify = fn => subject.onNext(fn)
  return model
}
 // Public: Ends the current game immediately.
 //
 // Returns nothing
 quit(winner) {
   if (winner) {
     this.channel.send(`Congratulations ${winner.name}, you've won!`);
   }
   
   this.gameEnded.onNext(winner);
   this.gameEnded.onCompleted();
   
   this.isRunning = false;
 }
function checkboxView() {
    const changes$ = new Rx.Subject;
    return {
        events: {
            changes$: changes$.asObservable()
        },
        render(checked) {
            return checkboxElement(checked, changes$);
        }
    };
}
			getJSON(worksheet.link, data => {
				sheets.onNext({
					data,
					index,
					link: worksheet.link,
					title: worksheet.title
				});

				// decrease countDown and check if it's zero
				if (! -- countDown) sheets.onCompleted();
			});
Beispiel #28
0
test.cb('lifecycle end', t => {
  const result$ = new Subject();
  const { epicMiddleware } = setup(() => result$);
  epicMiddleware.subscribeOnCompleted(() => {
    t.pass('all sagas completed');
    t.end();
  });
  epicMiddleware.end();
  t.pass('saga still active');
  result$.onCompleted();
});
Beispiel #29
0
test('An error should be thrown if an error occurs within an action', t => {
  const state = createState({ foo: 1 });
  const node = state('foo');
  const action = new Rx.Subject();

  node.reduce(
    action.doOnNext(() => { throw new Error('bar') }),
    () => 2
  );

  t.throws(() => action.onNext(3));
});
Beispiel #30
0
rtm.on(RTM_EVENTS.MESSAGE, (message) => {
    if (message.text) {
        if (message.text.startsWith("bot")) {
            configurationMessage.onNext(message);
        } else {
            messageSubject.onNext(message);
        }
        if (message.text.contains("userid")) {
            rtm.sendMessage(message.user, message.channel);
        }
    }
});