internal FutureProcess Apply(Future future, Exception exception) { return this._handler(new FutureExceptionEventHandlerChain.Event( future, exception, this._next)); }
public void Should_property_adapt_itself_to_a_channel_network() { TraceLogger.Configure(LogLevel.Debug); ILogger log = Logger.GetLogger<Sending_a_message_through_a_wcf_channel>(); log.Debug("Starting"); var serviceUri = new Uri("net.pipe://localhost/Pipe"); string pipeName = "Test"; Channel<TestMessage> adapter = new ChannelAdapter<TestMessage>(); using (var host = new WcfChannelHost<TestMessage>(adapter, serviceUri, pipeName)) { log.Debug("Host started"); var future = new Future<TestMessage>(); using (adapter.Connect(x => { x.AddConsumer(m => { log.Debug(l => l.Write("Received: {0}", m.Value)); future.Complete(m); }); })) { var client = new WcfChannelProxy<TestMessage>(new SynchronousFiber(), serviceUri, pipeName); log.Debug("Client started"); client.Send(new TestMessage("Hello!")); future.WaitUntilCompleted(2.Seconds()).ShouldBeTrue(); log.Debug("Complete"); } } }
public void InvokesOnCompletesWhenCompleted () { var f = new Future<object>(); object completeResult = null; f.RegisterOnComplete((_) => { completeResult = _.Error ?? _.Result; }); f.Complete(5); Assert.AreEqual(5, completeResult); }
public void Should_downconvert_a_request_message_of_type_to_a_request_message() { var received = new Future<Request<Simple>>(); HeaderTypeAdapter<Request<Simple>>.TryConvert(new RequestImpl<Simple>(null, new SimpleImpl()), received.Complete).ShouldBeTrue(); received.IsCompleted.ShouldBeTrue(); received.Value.ShouldNotBeNull(); }
public IFuture<CommandStatus> AcceptCommand(BinaryOutput command, uint index) { System.Console.WriteLine("Received BinaryOutput on index: " + index); var future = new Future<CommandStatus>(); future.Set(CommandStatus.CS_FORMAT_ERROR); return future; }
public void InvokesOnCompletesWhenFailed () { var f = new Future<object>(); object completeResult = null; f.RegisterOnComplete((_) => { completeResult = _.Error ?? _.Result; }); f.Fail(new Exception("test")); Assert.AreEqual("test", (completeResult as Exception).Message); }
public IFuture<CommandStatus> AcceptCommand(Setpoint command, uint index) { System.Console.WriteLine("Received Setpoint on index: " + index); var future = new Future<CommandStatus>(); future.Set(CommandStatus.CS_NOT_SUPPORTED); return future; }
public void Should_properly_arrive_at_the_destination() { var serviceUri = new Uri("net.pipe://localhost/pipe"); string pipeName = "test"; var future = new Future<TestMessage>(); var message = new TestMessage { Id = Guid.NewGuid(), Name = "Alpha", }; UntypedChannel adapter = new ChannelAdapter(); using (var remote = new WcfChannelHost(new SynchronousFiber(), adapter, serviceUri, pipeName)) { using (adapter.Connect(x => { x.AddConsumerOf<TestMessage>() .UsingConsumer(m => future.Complete(m)); })) { var client = new WcfChannelProxy(new SynchronousFiber(), serviceUri, pipeName); client.Send(message); future.WaitUntilCompleted(2.Seconds()).ShouldBeTrue(); } } future.Value.ShouldNotBeNull(); future.Value.ShouldEqual(message); future.Value.ShouldNotBeTheSameAs(message); }
public void Should_support_the_username_password_for_a_host() { var inputAddress = new Uri("rabbitmq://localhost/mt/test_queue"); var future = new Future<IConsumeContext<A>>(); using (IServiceBus bus = ServiceBusFactory.New(c => { c.ReceiveFrom(inputAddress); c.UseRabbitMq(r => { r.ConfigureHost(inputAddress, h => { h.SetUsername("testUser"); h.SetPassword("test"); }); }); c.Subscribe(s => s.Handler<A>((context, message) => future.Complete(context))); })) { bus.Publish(new A()); Assert.IsTrue(future.WaitUntilCompleted(TimeSpan.FromSeconds(8))); } Assert.AreEqual(inputAddress.ToString(), future.Value.SourceAddress.ToString()); }
public void Should_have_the_bits_without_the_message_first() { var engine = new DynamicRoutingEngine(new PoolFiber()); var visualizer = new TraceRoutingEngineVisualizer(); var received = new Future<A>(); engine.Configure(x => x.Receive<A>(received.Complete)); var block = new Future<int>(); engine.Add(0, () => { visualizer.Show(engine); block.Complete(0); }); block.WaitUntilCompleted(2.Seconds()); engine.Send(new A()); received.WaitUntilCompleted(2.Seconds()); engine.Send(new B()); var receivedB = new Future<B>(); engine.Configure(x => x.Receive<B>(receivedB.Complete)); received.WaitUntilCompleted(8.Seconds()).ShouldBeTrue(); receivedB.WaitUntilCompleted(8.Seconds()).ShouldBeTrue(); //engine.Receive<A, B>(x => { }); visualizer.Show(engine); }
public void Should_properly_invoke_the_message_receiver() { var fiber = new PoolFiber(); _engine = new DynamicRoutingEngine(fiber); _receivedA = new Future<A>(); _receivedB = new Future<B>(); _receivedC = new Future<C>(); _receivedMessageB = new Future<Message<B>>(); _receivedMessageC = new Future<Message<C>>(); _engine.Configure(x => { x.Receive<A>(_receivedA.Complete); x.Receive<B>(_receivedB.Complete); x.Receive<C>(_receivedC.Complete); x.Receive<Message<B>>(_receivedMessageB.Complete); x.Receive<Message<C>>(_receivedMessageC.Complete); }); _engine.Send(new B()); _engine.Send(new C()); _engine.Send(new B()); _engine.Send(new C()); fiber.Shutdown(5.Minutes()); }
public GetStockDetailsTest() { this.symbol = "AnySymbol"; this.detail = new Future<StockDetailModel>(); this.stockService = new Mock<IStockService>(); }
protected static EventHeapState query_internal_state() { var reply = new Future<EventHeapState>(); AnonymousActor.New(inbox => eventFilter.Request<QueryInternals>(inbox).Receive<EventHeapState>(msg => reply.Complete(msg))); reply.WaitUntilCompleted(-1); return reply.Value; }
void Start() { Uri endpoint = new Uri("http://creative.semantika.si/api/MemoryApp"); //Fire off the request! m_searchResult = m_restClient.Get<List<string>>(endpoint, new { tag = m_searchQuery }); }
public static IActionBuilder ConductDefaultContent(this IActionBuilder builder, Conductor<IStockTickerContentViewModel> conductor) { var future = new Future<StockDetailModel>(); future.SetValue(null); return builder.ConductContent(future, conductor); }
public void A_single_registered_service_throws_on_start() { _future = new Future<Exception>(); ServiceCoordinator.ShelfFaulted += _future.Complete; IList<Func<IServiceController>> services = new List<Func<IServiceController>> { () => new ServiceController<TestService>("test", WellknownAddresses.GetServiceCoordinatorProxy()) { BuildService = s => new TestService(), StartAction = x => { throw new Exception(); }, StopAction = x => x.Stop(), ContinueAction = x => x.Continue(), PauseAction = x => x.Pause() }, () => new ServiceController<TestService>("test2", WellknownAddresses.GetServiceCoordinatorProxy()) { BuildService = s => new TestService(), StartAction = x => x.Start(), StopAction = x => x.Stop(), ContinueAction = x => x.Continue(), PauseAction = x => x.Pause() } }; ServiceCoordinator.RegisterServices(services); ServiceCoordinator.Start(); }
public void A_request_is_sent_via_wcf() { _pipeUri = new Uri("net.pipe://localhost/pipe"); _response = new Future<Response<TestMessage>>(); _client = new ChannelAdapter(); _clientConnection = _client.Connect(x => { x.SendToWcfChannel(_pipeUri, _pipeName) .HandleOnCallingThread(); x.AddConsumerOf<Response<TestMessage>>() .UsingConsumer(_response.Complete); }); _server = new ChannelAdapter(); _serverConnection = _server.Connect(x => { x.ReceiveFromWcfChannel(_pipeUri, _pipeName); x.AddConsumerOf<Request<TestMessage>>() .UsingConsumer(request => request.Respond(request.Body)); }); }
public void Should_be_fast() { Fiber fiber = new ThreadPoolFiber(); const int limit = 5000000; var complete = new Future<int>(); Channel<MsgStruct> channel = new ConsumerChannel<MsgStruct>(fiber, message => { if (message.Count == limit) complete.Complete(limit); }); using (var timer = new FunctionTimer("Throughput", x => { Trace.WriteLine("Time to execute: " + (int) x.ElapsedMilliseconds + "ms"); Trace.WriteLine("Per second throughput: " + (int) (limit/(x.ElapsedMilliseconds/1000))); })) { for (int i = 1; i <= limit; i++) { channel.Send(new MsgStruct { Count = i, Other = i*8, }); } timer.Mark(); complete.WaitUntilCompleted(30.Seconds()).ShouldBeTrue(); } }
public Subject() { FutureA = new Future<Message<A>>(); FutureB = new Future<Message<B>>(); FutureC = new Future<Message<C>>(); FutureD = new FutureChannel<Message<D>>(); }
public void A_file_is_created() { _baseDirectory = AppDomain.CurrentDomain.BaseDirectory; _filename = "test2.dat"; _path = Path.Combine(_baseDirectory, _filename); System.IO.File.Delete(_path); _listener = new Future<FileCreated>(); _channel = new ChannelAdapter(); FiberFactory fiberFactory = () => new SynchronousFiber(); _scheduler = new TimerScheduler(fiberFactory()); _producer = new PollingFileSystemEventProducer(_baseDirectory, _channel, _scheduler, fiberFactory(), 20.Seconds()); Thread.Sleep(5.Seconds()); using (_channel.Connect(x => x.AddConsumerOf<FileCreated>().UsingConsumer(m => _listener.Complete(m)))) { System.IO.File.Create(_path); _listener.WaitUntilCompleted(25.Seconds()); } _producer.Dispose(); }
public void AttachToStack(CardStack s, Future IsLocalPlayer) { var c = this; if (c.CurrentStack != null) { c.CurrentStack.Cards.Remove(c); } c.PreviousStack = c.CurrentStack; c.CurrentStack = s; s.Cards.Add(c); if (this.Moved != null) this.Moved(); // if the IsLocalPlayer is null then we are not meant to raise MovedByLocalPlayer if (IsLocalPlayer != null) IsLocalPlayer.Continue( delegate { if (this.MovedByLocalPlayer != null) this.MovedByLocalPlayer(); } ); }
public void Should_publish_to_non_transactional_queue() { using (IServiceBus transactionalBus = ServiceBusFactory.New(x => { x.UseMsmq(); x.ReceiveFrom(_transactionalUri); x.UseMulticastSubscriptionClient(); x.SetCreateMissingQueues(true); x.SetCreateTransactionalQueues(true); })) { using (IServiceBus nonTransactionalBus = ServiceBusFactory.New(x => { x.UseMsmq(); x.ReceiveFrom(_nonTransactionalUri); x.UseMulticastSubscriptionClient(); x.SetCreateMissingQueues(true); x.SetCreateTransactionalQueues(false); })) { var future = new Future<MyMessage>(); nonTransactionalBus.SubscribeHandler<MyMessage>(future.Complete); transactionalBus.ShouldHaveSubscriptionFor<MyMessage>(); transactionalBus.Publish(new MyMessage(), ctx => ctx.IfNoSubscribers(() => { throw new Exception("NoSubscribers"); })); future.WaitUntilCompleted(8.Seconds()).ShouldBeTrue("The published message was not received>"); } } }
public void RequestingValueAfterSourceHasDataPerformsTransformation() { Future<string> source = new Future<string>(); FutureProxy<int> subject = FutureProxy<int>.FromFuture(source, x => x.Length); source.Value = "hello"; Assert.AreEqual(5, subject.Value); }
public Future<int> Read (byte[] buffer, int offset, int count) { var f = new Future<int>(); if (!_Socket.Connected) { if (ThrowOnDisconnect) f.Fail(new SocketDisconnectedException()); else f.Complete(0); } else { SocketError errorCode; if (_Socket.Available >= count) { try { int bytesRead = _Socket.Receive(buffer, offset, count, SocketFlags.None, out errorCode); if (ThrowOnDisconnect && (bytesRead == 0)) { f.Fail(new SocketDisconnectedException()); } else { f.Complete(bytesRead); } } catch (Exception ex) { f.Fail(ex); } } else { _Socket.BeginReceive(buffer, offset, count, SocketFlags.None, out errorCode, _ReadCallback, f); } } return f; }
public void Adding_operations_to_a_fiber() { _count = 10000; _values = new int[_count]; Fiber fiber = new PoolFiber(); int index = 0; var completed = new Future<int>(); var go = new Future<bool>(); fiber.Add(() => { go.WaitUntilCompleted(10.Seconds()); }); for (int i = 0; i < _count; i++) { int offset = i; fiber.Add(() => { _values[offset] = index++; if (offset == _count - 1) completed.Complete(offset); }); } go.Complete(true); completed.WaitUntilCompleted(10.Seconds()).ShouldBeTrue(); }
public void A_loopback_registry() { Address = new Uri("loopback://localhost/"); ReceivedA = new Future<A>(); Registry = ActorRegistryFactory.New(x => { x.Remote(r => { r.ListenTo(Address); }); }); ActorId = Guid.NewGuid(); Actor = AnonymousActor.New(inbox => { inbox.Loop(loop => { loop.Receive<Message<A>>(message => { ReceivedA.Complete(message.Body); loop.Continue(); }); }); }); Registry.Register(ActorId, Actor); }
public void Run() { Stopwatch timer = Stopwatch.StartNew(); const int channelCount = 10000; const int seedCount = 500; var channels = new UntypedChannel[channelCount]; var connections = new ChannelConnection[channelCount]; var complete = new Future<int>(); var latch = new CountdownLatch(channelCount*seedCount, complete.Complete); for (int i = 0; i < channelCount; i++) { int channelNumber = i; channels[i] = new ChannelAdapter(); connections[i] = channels[i].Connect(x => { x.AddConsumerOf<AMessage>() .UsingConsumer(message => { if (channelNumber < channels.Length - 1) channels[channelNumber + 1].Send(message); latch.CountDown(); }); }); } var body = new AMessage(); for (int i = 0; i < seedCount; i++) { channels[i].Send(body); for (int j = 0; j < i; j++) latch.CountDown(); } bool completed = complete.WaitUntilCompleted(2.Minutes()); timer.Stop(); connections.Each(x => x.Dispose()); if (!completed) { Console.WriteLine("Process did not complete"); return; } Console.WriteLine("Processed {0} messages in with {1} channels in {2}ms", seedCount, channelCount, timer.ElapsedMilliseconds); Console.WriteLine("That's {0} messages per second!", ((long)seedCount*channelCount*1000)/timer.ElapsedMilliseconds); }
public void Sending_a_message_to_an_nhibernate_backed_state_machine() { TraceLogProvider.Configure(LogLevel.Debug); _newValue = new Random().Next(1, 500000)/100m; using (ISession session = SessionFactory.OpenSession()) using (ITransaction transaction = session.BeginTransaction()) { session.CreateQuery("Delete TestStateMachineInstance").ExecuteUpdate(); transaction.Commit(); } var input = new ChannelAdapter(); using (input.Connect(x => { x.AddConsumersFor<TestStateMachineInstance>() .BindUsing<TestStateMachineInstanceBinding, int>() .ExecuteOnProducerThread() .CreateNewInstanceUsing(id => new TestStateMachineInstance(id)) .PersistUsingNHibernate() .UseSessionProvider(() => SessionFactory.OpenSession()); })) { input.Flatten().Select(c => c.GetType()).ShouldEqual(new[] { typeof(ChannelAdapter), typeof(BroadcastChannel), typeof(TypedChannelAdapter<CreateOrder>), typeof(InstanceChannel<CreateOrder>), typeof(TypedChannelAdapter<UpdateOrder>), typeof(InstanceChannel<UpdateOrder>), typeof(TypedChannelAdapter<CompleteOrder>), typeof(InstanceChannel<CompleteOrder>), }); var future = new Future<int>(); TestStateMachineInstance.CompletedLatch = new CountdownLatch(1, future.Complete); // input.Send(new CreateOrder { Id = 27 }); input.Send(new UpdateOrder { Id = 27, Value = _newValue, }); input.Send(new CompleteOrder { Id = 27, }); future.WaitUntilCompleted(5.Seconds()).ShouldBeTrue(); } }
public SomeActorInstance() { _queue = new ThreadPoolActionQueue(); _future = new Future<MyMessage>(); MessageChannel = new ConsumerChannel<MyMessage>(_queue, Consume); LambdaMessageChannel = new ConsumerChannel<MyMessage>(_queue, message => _future.Complete(message)); }
public SomeActorInstance() { _fiber = new ThreadPoolFiber(); _future = new Future<MyMessage>(); MessageChannel = new ConsumerChannel<MyMessage>(_fiber, Consume); LambdaMessageChannel = new ConsumerChannel<MyMessage>(_fiber, message => _future.Complete(message)); }
public static Future <B> Select <A, B>(this Future <A> fa, Fn <A, B> f) => fa.map(f);
public static Future <B> Map <A, B>(this Future <A> future, Func <A, B> f) { return(FutureFunctor.Instance.Map(future, f)); }
public static Future <C> SelectMany <A, B, C>( this Future <A> fa, Fn <A, Future <B> > f, Fn <A, B, C> g ) => fa.flatMap(f, g);
public static Maybe <Future <A> > SequenceMaybe <A>(this Future <Maybe <A> > future) { return(future.Map(m => m.Map(Future.Now)).Run()); }
public static IEnumerable <Future <T> > SequenceEnumerable <T>(this Future <IEnumerable <T> > future) { return(future.Map(ts => ts.Select(Future.Now)).Run()); }
private Subscription CreateSubscription(Resolution resolution, string symbol = "AAPL", bool isInternalFeed = false, SecurityType type = SecurityType.Equity, TickType tickType = TickType.Trade) { var start = DateTime.UtcNow; var end = start.AddSeconds(10); Security security; Symbol _symbol; if (type == SecurityType.Equity) { _symbol = new Symbol(SecurityIdentifier.GenerateEquity(DateTime.Now, symbol, Market.USA), symbol); security = new Equity( _symbol, SecurityExchangeHours.AlwaysOpen(DateTimeZone.Utc), new Cash(Currencies.USD, 0, 1), SymbolProperties.GetDefault(Currencies.USD), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null, new SecurityCache() ); } else if (type == SecurityType.Option) { _symbol = new Symbol(SecurityIdentifier.GenerateOption(DateTime.Now, SecurityIdentifier.GenerateEquity(DateTime.Now, symbol, Market.USA), Market.USA, 0.0m, OptionRight.Call, OptionStyle.American), symbol); security = new Option( _symbol, SecurityExchangeHours.AlwaysOpen(DateTimeZone.Utc), new Cash(Currencies.USD, 0, 1), new OptionSymbolProperties(SymbolProperties.GetDefault(Currencies.USD)), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null, new SecurityCache() ); } else if (type == SecurityType.Future) { _symbol = new Symbol(SecurityIdentifier.GenerateFuture(DateTime.Now, symbol, Market.USA), symbol); security = new Future( _symbol, SecurityExchangeHours.AlwaysOpen(DateTimeZone.Utc), new Cash(Currencies.USD, 0, 1), SymbolProperties.GetDefault(Currencies.USD), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null, new SecurityCache() ); } else { throw new Exception("SecurityType not implemented"); } var config = new SubscriptionDataConfig(typeof(TradeBar), _symbol, resolution, DateTimeZone.Utc, DateTimeZone.Utc, true, false, isInternalFeed, false, tickType); var timeZoneOffsetProvider = new TimeZoneOffsetProvider(DateTimeZone.Utc, start, end); var enumerator = new EnqueueableEnumerator <BaseData>(); var subscriptionDataEnumerator = new SubscriptionDataEnumerator(config, security.Exchange.Hours, timeZoneOffsetProvider, enumerator); var subscriptionRequest = new SubscriptionRequest(false, null, security, config, start, end); return(new Subscription(subscriptionRequest, subscriptionDataEnumerator, timeZoneOffsetProvider)); }
public void Run() { Stopwatch timer = Stopwatch.StartNew(); const int actorCount = 20; const int pingCount = 4000; var actors = new ActorRef[actorCount + 1]; var complete = new Future <int>(); var latch = new CountdownLatch(actorCount * pingCount, complete.Complete); for (int i = actorCount; i >= 0; i--) { actors[i] = AnonymousActor.New(inbox => { var pong = new Pong(); var server = actors[(i + 1)]; inbox.Loop(loop => { loop.Receive <Request <Ping> >(request => { request.Respond(pong); loop.Continue(); }); }); if (i < actorCount) { var ping = new Ping(); int count = 0; Action loop = null; loop = () => { server.Request(ping, inbox) .Receive <Response <Pong> >(response => { latch.CountDown(); count++; if (count < pingCount) { loop(); } }); }; loop(); } }); } bool completed = complete.WaitUntilCompleted(5.Minutes()); timer.Stop(); for (int i = 0; i < actorCount; i++) { actors[i].Exit(); actors[i] = null; } if (!completed) { Console.WriteLine("Process did not complete"); return; } Console.WriteLine("Processed {0} messages in with {1} actors in {2}ms", pingCount, actorCount, timer.ElapsedMilliseconds); Console.WriteLine("That's {0} messages per second!", ((long)pingCount * actorCount * 2 * 1000) / timer.ElapsedMilliseconds); }
static IEnumerator <object> MessageDispatcher() { while (true) { var waitList = new List <IFuture>(); var waitingPeers = new List <Peer>(); bool moreWork; do { moreWork = false; int newestId = (Messages.Count - 1) + MessageIdBase; long now = Time.Ticks; foreach (Peer peer in Peers.ToArray()) { if (!peer.Connected) { continue; } if (peer.CurrentId != newestId) { if ((newestId - peer.CurrentId) > MaxMessagesToDispatch) { peer.CurrentId = newestId - MaxMessagesToDispatch; } string text = null; Message message = Messages[peer.CurrentId - MessageIdBase + 1]; if (message.From == peer) { peer.CurrentId += 1; continue; } else { text = message.DisplayText; } IFuture f = null; f = peer.Output.PendingOperation; if (f == null) { f = peer.Output.WriteLine(text); f.RegisterOnComplete((_) => { if (_.Failed) { Scheduler.QueueWorkItem(() => { PeerDisconnected(peer); }); } }); peer.CurrentId += 1; } else { waitList.Add(f); waitingPeers.Add(peer); continue; } } if (peer.CurrentId != newestId) { moreWork = true; } } } while (moreWork); var waitForNewMessage = new Future <object>(); WaitingForMessages = waitForNewMessage; waitList.Add(waitForNewMessage); yield return(Future.WaitForFirst(waitList)); } }
protected virtual Future handleSystemMessage(Object systemMessage) { return(Future.value()); }
OnDestroyForwarder() { onEvent = Future <Unit> .async(out _onDestroy); }
public System_IO_StringReaderCanvas() { Width = DefaultWidth; Height = DefaultHeight; #region Gradient for (int i = 0; i < DefaultHeight; i += 4) { new Rectangle { Fill = ((uint)(0xff00007F + Convert.ToInt32(128 * i / DefaultHeight))).ToSolidColorBrush(), Width = DefaultWidth, Height = 4, }.MoveTo(0, i).AttachTo(this); } #endregion var help_idle = new Image { Source = "assets/System_IO_StringReader/help_idle.png".ToSource() }.AttachTo(this); var help = new Image { Source = "assets/System_IO_StringReader/help.png".ToSource() }.AttachTo(this); help.Opacity = 0; var img = new Image { Source = "assets/System_IO_StringReader/jsc.png".ToSource() }.MoveTo(DefaultWidth - 128, DefaultHeight - 128).AttachTo(this); var t = new TextBox { FontSize = 32, Text = "powered by jsc", BorderThickness = new Thickness(0), Foreground = 0xffffffff.ToSolidColorBrush(), Background = Brushes.Transparent, IsReadOnly = true }.MoveTo(32, 32).AttachTo(this); var Data = new Future <string>(); "assets/System_IO_StringReader/data.txt".ToStringAsset(Data); Data.Continue( value => { using (var s = new StringReader(value)) { // skip header var header = s.ReadLine(); var _1 = s.ReadLine(); var _2 = s.ReadLine(); Console.WriteLine("" + new { _1, _1.Length }); Console.WriteLine("" + new { _2, _2.Length }); t.Text = "Content: " + _2; var footer = s.ReadLine(); var empty = s.ReadLine(); } } ); help_idle.Opacity = 0; help.Opacity = 1; img.Opacity = 0.5; t.MouseEnter += delegate { help_idle.Opacity = 1; help.Opacity = 0; img.Opacity = 1; t.Foreground = 0xffffff00.ToSolidColorBrush(); }; t.MouseLeave += delegate { help_idle.Opacity = 0; help.Opacity = 1; img.Opacity = 0.5; t.Foreground = 0xffffffff.ToSolidColorBrush(); }; }
public ISubscription register <Obj, A>(string name, HasObjFn <Obj> objOpt, Fn <Obj, A> run) => register(name, objOpt, obj => Future.successful(run(obj)));
public WriteLock(Future <T> future) => (f = future).guard.EnterWriteLock();
public void Complete_is_called() { var obj1 = new object(); Future.Complete(obj1); }
internal ContextualFuture(T value) { _future = new Future <T>(value); }
public void A_future() { Future = new Future <object>(); }
/// <summary> /// Add future callback /// </summary> /// <param name="tid">tid</param> /// <param name="bundle">callback instance</param> public void AddFuture(string tid, Future bundle) { onCompletion.Add(tid, bundle); }
public OrderDispatcher(Future <OrderPlaced> future) { _future = future; }
public static Maybe <Future <B> > TraverseMabye <A, B>(this Future <A> future, Func <A, Maybe <B> > f) { return(future.Map(f).SequenceMaybe()); }
public OrderProcessor(Future <OrderPlaced> future) { _future = future; }
public static IEnumerable <Future <B> > TraverseEnumerable <A, B>(this Future <A> future, Func <A, IEnumerable <B> > f) { return(future.Map(f).SequenceEnumerable()); }
public static IEnumerator <object> FromFile(string filename, IProgressListener progress) { progress.Status = "Loading diff..."; Future <string> fText; // We could stream the lines in from the IO thread while we parse them, but this // part of the load is usually pretty quick even on a regular hard disk, and // loading the whole diff at once eliminates some context switches using (var fda = new FileDataAdapter( filename, FileMode.Open, FileAccess.Read, FileShare.Read, 1024 * 128 )) { var fBytes = fda.ReadToEnd(); yield return(fBytes); fText = Future.RunInThread( () => Encoding.ASCII.GetString(fBytes.Result) ); yield return(fText); } yield return(fText); var lr = new LineReader(fText.Result); LineReader.Line line; progress.Status = "Parsing diff..."; var frames = new List <TracebackFrame>(); var moduleNames = new NameTable(StringComparer.Ordinal); var symbolTypes = new NameTable(StringComparer.Ordinal); var functionNames = new NameTable(StringComparer.Ordinal); var deltas = new List <DeltaInfo>(); var tracebacks = new Dictionary <UInt32, TracebackInfo>(); var regexes = new Regexes(); // Regex.Groups[string] does an inefficient lookup, so we do that lookup once here int groupModule = regexes.DiffModule.GroupNumberFromName("module"); int groupSymbolType = regexes.DiffModule.GroupNumberFromName("symbol_type"); int groupTraceId = regexes.BytesDelta.GroupNumberFromName("trace_id"); int groupType = regexes.BytesDelta.GroupNumberFromName("type"); int groupDeltaBytes = regexes.BytesDelta.GroupNumberFromName("delta_bytes"); int groupNewBytes = regexes.BytesDelta.GroupNumberFromName("new_bytes"); int groupOldBytes = regexes.BytesDelta.GroupNumberFromName("old_bytes"); int groupNewCount = regexes.BytesDelta.GroupNumberFromName("new_count"); int groupOldCount = regexes.CountDelta.GroupNumberFromName("old_count"); int groupCountDelta = regexes.CountDelta.GroupNumberFromName("delta_count"); int groupTracebackModule = regexes.TracebackFrame.GroupNumberFromName("module"); int groupTracebackFunction = regexes.TracebackFrame.GroupNumberFromName("function"); int groupTracebackOffset = regexes.TracebackFrame.GroupNumberFromName("offset"); int groupTracebackOffset2 = regexes.TracebackFrame.GroupNumberFromName("offset2"); int groupTracebackPath = regexes.TracebackFrame.GroupNumberFromName("path"); int groupTracebackLine = regexes.TracebackFrame.GroupNumberFromName("line"); var delay = new Sleep(0.01); int i = 0; while (lr.ReadLine(out line)) { retryFromHere: i += 1; if (i % ProgressInterval == 0) { progress.Maximum = lr.Length; progress.Progress = lr.Position; // Suspend processing for a bit yield return(delay); } Match m; if (regexes.DiffModule.TryMatch(ref line, out m)) { moduleNames.Add(m.Groups[groupModule].Value); } else if (regexes.BytesDelta.TryMatch(ref line, out m)) { var added = (m.Groups[groupType].Value == "+"); var traceId = UInt32.Parse(m.Groups[groupTraceId].Value, NumberStyles.HexNumber); var info = new DeltaInfo { BytesDelta = int.Parse(m.Groups[groupDeltaBytes].Value, NumberStyles.HexNumber) * (added ? 1 : -1), NewBytes = int.Parse(m.Groups[groupNewBytes].Value, NumberStyles.HexNumber), OldBytes = int.Parse(m.Groups[groupOldBytes].Value, NumberStyles.HexNumber), NewCount = int.Parse(m.Groups[groupNewCount].Value, NumberStyles.HexNumber), }; if (lr.ReadLine(out line)) { if (regexes.CountDelta.TryMatch(ref line, out m)) { info.OldCount = int.Parse(m.Groups[groupOldCount].Value, NumberStyles.HexNumber); info.CountDelta = int.Parse(m.Groups[groupCountDelta].Value, NumberStyles.HexNumber) * (added ? 1 : -1); } } bool readingLeadingWhitespace = true, doRetry = false; frames.Clear(); var itemModules = new NameTable(StringComparer.Ordinal); var itemFunctions = new NameTable(StringComparer.Ordinal); while (lr.ReadLine(out line)) { if (line.ToString().Trim().Length == 0) { if (readingLeadingWhitespace) { continue; } else { break; } } else if (regexes.TracebackFrame.TryMatch(ref line, out m)) { readingLeadingWhitespace = false; var moduleName = moduleNames[m.Groups[groupTracebackModule].Value]; itemModules.Add(moduleName); var functionName = functionNames[m.Groups[groupTracebackFunction].Value]; itemFunctions.Add(functionName); var frame = new TracebackFrame { Module = moduleName, Function = functionName, Offset = UInt32.Parse(m.Groups[groupTracebackOffset].Value, NumberStyles.HexNumber) }; if (m.Groups[groupTracebackOffset2].Success) { frame.Offset2 = UInt32.Parse(m.Groups[groupTracebackOffset2].Value, NumberStyles.HexNumber); } if (m.Groups[groupTracebackPath].Success) { frame.SourceFile = m.Groups[groupTracebackPath].Value; } if (m.Groups[groupTracebackLine].Success) { frame.SourceLine = int.Parse(m.Groups[groupTracebackLine].Value); } frames.Add(frame); } else { // We hit the beginning of a new allocation, so make sure it gets parsed doRetry = true; break; } } if (tracebacks.ContainsKey(traceId)) { info.Traceback = tracebacks[traceId]; Program.ErrorList.ReportError("Duplicate traceback for id {0}!", traceId); } else { var frameArray = ImmutableArrayPool <TracebackFrame> .Allocate(frames.Count); frames.CopyTo(frameArray.Array, frameArray.Offset); info.Traceback = tracebacks[traceId] = new TracebackInfo { TraceId = traceId, Frames = frameArray, Modules = itemModules, Functions = itemFunctions }; } deltas.Add(info); if (doRetry) { goto retryFromHere; } } else if (line.StartsWith("//")) { // Comment, ignore it } else if (line.StartsWith("Total increase") || line.StartsWith("Total decrease")) { // Ignore this too } else if (line.StartsWith(" ") && (line.EndsWith(".pdb"))) { // Symbol path for a module, ignore it } else { Program.ErrorList.ReportError("Unrecognized diff content: {0}", line.ToString()); } } var result = new HeapDiff( filename, moduleNames, functionNames, deltas, tracebacks ); yield return(new Result(result)); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldNotSeeEmptyLogFileWhenReadingTransactionStream() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldNotSeeEmptyLogFileWhenReadingTransactionStream() { // GIVEN LogVersionRepository logVersionRepository = new SimpleLogVersionRepository(); LogFiles logFiles = LogFilesBuilder.builder(_directory.databaseLayout(), _fileSystemRule.get()).withLogVersionRepository(logVersionRepository).withTransactionIdStore(new SimpleTransactionIdStore()).build(); _life.add(logFiles); LogFile logFile = logFiles.LogFile; FlushablePositionAwareChannel writer = logFile.Writer; LogPositionMarker startPosition = new LogPositionMarker(); writer.GetCurrentPosition(startPosition); // WHEN AtomicBoolean end = new AtomicBoolean(); sbyte[] dataChunk = new sbyte[100]; // one thread constantly writing to and rotating the channel AtomicInteger rotations = new AtomicInteger(); System.Threading.CountdownEvent startSignal = new System.Threading.CountdownEvent(1); Future <Void> writeFuture = _t2.execute(ignored => { ThreadLocalRandom random = ThreadLocalRandom.current(); startSignal.Signal(); while (!end.get()) { writer.Put(dataChunk, random.Next(1, dataChunk.Length)); if (logFile.RotationNeeded()) { logFile.Rotate(); // Let's just close the gap to the reader so that it gets closer to the "hot zone" // where the rotation happens. writer.GetCurrentPosition(startPosition); rotations.incrementAndGet(); } } return(null); }); assertTrue(startSignal.await(10, SECONDS)); // one thread reading through the channel long maxEndTime = currentTimeMillis() + _limitTime; int reads = 0; try { for ( ; currentTimeMillis() < maxEndTime && reads < LIMIT_READS && rotations.get() < LIMIT_ROTATIONS; reads++) { using (ReadableLogChannel reader = logFile.GetReader(startPosition.NewPosition())) { Deplete(reader); } } } finally { end.set(true); writeFuture.get(); } // THEN simply getting here means this was successful }
public async Task <bool> Handle(OrderPlaced message) { await Future.Complete(message); return(true); }
public static Future <B> SelectMany <A, B>(this Future <A> fa, Fn <A, Future <B> > f) => fa.flatMap(f);
/// <summary> /// Parses the data. /// </summary> /// <param name="instrumentIds"></param> /// <returns></returns> public static QuotedAssetSet Parse(string[] instrumentIds) { var quotedAssetSetFactory = new QuotedAssetSetFactory(); const string rateQuotationType = "MarketQuote"; for (var i = 0; i < instrumentIds.Length; i++) { Asset underlyingAsset; var instrumentId = instrumentIds[i]; var results = instrumentIds[i].Split('-'); var instrument = results[1]; var listBasicQuotations = new List <BasicQuotation>(); const string priceUnitDecimalRate = "DecimalRate"; switch (instrument) { case "ZeroRate": { underlyingAsset = new Cash { id = instrumentId }; listBasicQuotations.Add(BasicQuotationHelper.Create(rateQuotationType, priceUnitDecimalRate)); break; } case "Xibor": case "OIS": { var tenor = results[2]; underlyingAsset = new RateIndex { id = instrumentId, term = Period.Parse(tenor) }; listBasicQuotations.Add(BasicQuotationHelper.Create(rateQuotationType, priceUnitDecimalRate)); break; } case "IRSwap": case "XccySwap": case "SimpleIRSwap": { underlyingAsset = new SimpleIRSwap { id = instrumentId, term = Period.Parse(results[2]) }; listBasicQuotations.Add(BasicQuotationHelper.Create(rateQuotationType, priceUnitDecimalRate)); break; } case "Deposit": case "XccyDepo": case "BankBill": { underlyingAsset = new Deposit { id = instrumentId, term = Period.Parse(results[2]) }; listBasicQuotations.Add(BasicQuotationHelper.Create(rateQuotationType, priceUnitDecimalRate)); break; } case "SimpleFra": case "Fra": case "BillFra": { var index = results[3]; var asset = new SimpleFra { id = instrumentId, startTerm = Period.Parse(results[2]) }; asset.endTerm = asset.startTerm.Sum(Period.Parse(index)); underlyingAsset = asset; listBasicQuotations.Add(BasicQuotationHelper.Create(rateQuotationType, priceUnitDecimalRate)); break; } case "IRFuture": { underlyingAsset = new Future { id = instrumentId }; listBasicQuotations.Add(BasicQuotationHelper.Create(rateQuotationType, priceUnitDecimalRate)); listBasicQuotations.Add(BasicQuotationHelper.Create("Volatility", "LognormalVolatility")); break; } case "CPIndex": { var tenor = results[2]; underlyingAsset = new RateIndex { id = instrumentId, term = Period.Parse(tenor) }; listBasicQuotations.Add(BasicQuotationHelper.Create(rateQuotationType, priceUnitDecimalRate)); break; } case "SimpleCPISwap": case "CPISwap": case "ZCCPISwap": { underlyingAsset = new SimpleIRSwap { id = instrumentId, term = Period.Parse(results[2]) }; listBasicQuotations.Add(BasicQuotationHelper.Create(rateQuotationType, priceUnitDecimalRate)); break; } default: throw new NotSupportedException(string.Format("Asset type {0} is not supported", instrument)); } quotedAssetSetFactory.AddAssetAndQuotes(underlyingAsset, BasicAssetValuationHelper.Create(underlyingAsset.id, listBasicQuotations.ToArray())); } return(quotedAssetSetFactory.Create()); }
public IHttpActionResult deleteBondss(Future c) { int changeLine = FutureDao.deleteFuture(c); return(Ok(changeLine)); }
/// <summary> /// Parses the string info into an asset. /// </summary> /// <param name="instrumentId"></param> /// <param name="value"></param> /// <param name="adjustment"></param> /// <returns></returns> public static Pair <Asset, BasicAssetValuation> Parse(string instrumentId, decimal value, decimal adjustment) { const string rateQuotationType = "MarketQuote"; Asset underlyingAsset; var results = instrumentId.Split('-'); var instrument = results[1]; var listBasicQuotations = new List <BasicQuotation>(); switch (instrument) { case "ZeroRate": { var zeroRate = new Cash { id = instrumentId }; underlyingAsset = zeroRate; listBasicQuotations.Add(BasicQuotationHelper.Create(value, rateQuotationType, "DecimalRate")); break; } case "Xibor": case "OIS": { var tenor = results[2]; var rateIndex = new RateIndex { id = instrumentId, term = Period.Parse(tenor) }; underlyingAsset = rateIndex; listBasicQuotations.Add(BasicQuotationHelper.Create(value + adjustment, rateQuotationType, "DecimalRate")); break; } case "IRSwap": case "XccySwap": case "SimpleIRSwap": { var simpleIRSwap = new SimpleIRSwap { id = instrumentId, term = Period.Parse(results[2]) }; underlyingAsset = simpleIRSwap; listBasicQuotations.Add(BasicQuotationHelper.Create(value + adjustment, rateQuotationType, "DecimalRate")); break; } case "Deposit": case "XccyDepo": case "BankBill": { var deposit = new Deposit { id = instrumentId, term = Period.Parse(results[2]) }; underlyingAsset = deposit; listBasicQuotations.Add(BasicQuotationHelper.Create(value + adjustment, rateQuotationType, "DecimalRate")); break; } case "SimpleFra": case "Fra": case "BillFra": case "SpreadFra": { var index = results[3]; var asset = new SimpleFra { id = instrumentId, startTerm = Period.Parse(results[2]) }; asset.endTerm = asset.startTerm.Sum(Period.Parse(index)); underlyingAsset = asset; listBasicQuotations.Add(BasicQuotationHelper.Create(value + adjustment, rateQuotationType, "DecimalRate")); break; } case "IRCap": { var simpleIRCap = new SimpleIRSwap { id = instrumentId, term = Period.Parse(results[2]) }; underlyingAsset = simpleIRCap; listBasicQuotations.Add(BasicQuotationHelper.Create(value, "Premium", "Amount")); break; } case "IRFuture": { var future = new Future { id = instrumentId }; underlyingAsset = future; listBasicQuotations.Add(BasicQuotationHelper.Create(value, rateQuotationType, "DecimalRate")); listBasicQuotations.Add(BasicQuotationHelper.Create(adjustment, "Volatility", "LognormalVolatility")); break; } case "CommodityFuture": { var future = new Future { id = instrumentId }; underlyingAsset = future; listBasicQuotations.Add(BasicQuotationHelper.Create(value, rateQuotationType, "DecimalRate")); break; } case "CPIndex": { var tenor = results[2]; var rateIndex = new RateIndex { id = instrumentId, term = Period.Parse(tenor) }; underlyingAsset = rateIndex; listBasicQuotations.Add(BasicQuotationHelper.Create(value + adjustment, rateQuotationType, "DecimalRate")); break; } case "SimpleCPISwap": case "CPISwap": case "ZCCPISwap": { var simpleIRSwap = new SimpleIRSwap { id = instrumentId, term = Period.Parse(results[2]) }; underlyingAsset = simpleIRSwap; listBasicQuotations.Add(BasicQuotationHelper.Create(value + adjustment, rateQuotationType, "DecimalRate")); break; } case "FxSpot": case "FxForward": { // var tenor = results[2]; var fxRateAsset = new FxRateAsset { id = instrumentId }; underlyingAsset = fxRateAsset; listBasicQuotations.Add(BasicQuotationHelper.Create(value + adjustment, rateQuotationType, "FxRate")); break; } case "CommoditySpot": case "CommodityForward": { var commodityAsset = new FxRateAsset { id = instrumentId }; underlyingAsset = commodityAsset; listBasicQuotations.Add(BasicQuotationHelper.Create(value, rateQuotationType, "Price")); break; } case "Bond": { var asset = new Bond { id = instrumentId }; underlyingAsset = asset; listBasicQuotations.Add(BasicQuotationHelper.Create(value, rateQuotationType, "DirtyPrice")); break; } default: throw new NotSupportedException(string.Format("Asset type {0} is not supported", instrument)); } return(new Pair <Asset, BasicAssetValuation>(underlyingAsset, BasicAssetValuationHelper.Create(underlyingAsset.id, listBasicQuotations.ToArray()))); }
public void RefreshesFutureChainUniverseOnDateChange() { var startTime = new DateTime(2018, 10, 17, 10, 0, 0); var timeProvider = new ManualTimeProvider(startTime); var symbolUniverse = new TestDataQueueUniverseProvider(timeProvider); var canonicalSymbol = Symbol.Create(Futures.Indices.VIX, SecurityType.Future, Market.CFE, "/VX"); var quoteCurrency = new Cash(Currencies.USD, 0, 1); var exchangeHours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.CFE, canonicalSymbol, SecurityType.Future); var config = new SubscriptionDataConfig( typeof(ZipEntryName), canonicalSymbol, Resolution.Minute, TimeZones.Utc, TimeZones.Chicago, true, false, false, false, TickType.Quote, false, DataNormalizationMode.Raw ); var future = new Future( canonicalSymbol, exchangeHours, quoteCurrency, SymbolProperties.GetDefault(Currencies.USD), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null, new SecurityCache() ); var universeSettings = new UniverseSettings(Resolution.Minute, 0, true, false, TimeSpan.Zero); using var universe = new FuturesChainUniverse(future, universeSettings); var request = new SubscriptionRequest(true, universe, future, config, startTime, Time.EndOfTime); var enumerator = new DataQueueFuturesChainUniverseDataCollectionEnumerator(request, symbolUniverse, timeProvider); Assert.IsTrue(enumerator.MoveNext()); Assert.IsNotNull(enumerator.Current); Assert.AreEqual(1, symbolUniverse.TotalLookupCalls); var data = enumerator.Current; Assert.IsNotNull(data); Assert.AreEqual(1, data.Data.Count); timeProvider.Advance(Time.OneSecond); Assert.IsTrue(enumerator.MoveNext()); Assert.IsNull(enumerator.Current); Assert.AreEqual(1, symbolUniverse.TotalLookupCalls); timeProvider.Advance(Time.OneMinute); Assert.IsTrue(enumerator.MoveNext()); Assert.IsNull(enumerator.Current); Assert.AreEqual(1, symbolUniverse.TotalLookupCalls); timeProvider.Advance(Time.OneDay); Assert.IsTrue(enumerator.MoveNext()); Assert.IsNotNull(enumerator.Current); Assert.AreEqual(2, symbolUniverse.TotalLookupCalls); data = enumerator.Current; Assert.IsNotNull(data); Assert.AreEqual(2, data.Data.Count); timeProvider.Advance(Time.OneMinute); Assert.IsTrue(enumerator.MoveNext()); Assert.IsNull(enumerator.Current); Assert.AreEqual(2, symbolUniverse.TotalLookupCalls); enumerator.Dispose(); }
public ReadLock(Future <T> future) => (f = future).guard.EnterReadLock();