예제 #1
0
        /// <summary>
        /// Méthode d'écoute de fin d'exécution des BackgroundWorkers
        /// </summary>
        /// <param name="sender">BackgroundWorker emetteur</param>
        /// <param name="e">résultat de fin de traitement</param>
        protected void WorkerEndProcess(object sender, RunWorkerCompletedEventArgs e)
        {
            // Manage if e.Error != null
            Tuple <int, DataInput, int> data = (Tuple <int, DataInput, int>)e.Result;
            DataInput resp = data.Item2;

            UpdateWorkerTaskStatus(data.Item1, data.Item2.NodeTaskId, NodeState.Finish);
            UpdateResult(resp.Data, data.Item2.NodeTaskId, data.Item1);
            if (TaskIsCompleted(resp.NodeTaskId))
            {
                Logger.Write($"Traitement terminé pour {data.Item2.Method}.");
                Logger.Write(@"Résultat envoyé à l'orchestrateur.");
                IReducer reducer = WorkerFactory.GetWorker(resp.Method).Reducer;
                object   result  = reducer.Reduce(GetResultFromTaskId(resp.NodeTaskId));
                resp.Data = result;
                SendData(Orch, resp);
            }
            else
            {
                double    progression = GetWorkersProgression(data.Item2.NodeTaskId, data.Item3);
                DataInput status      = new DataInput()
                {
                    ClientGuid = data.Item2.ClientGuid,
                    NodeGuid   = NodeGuid,
                    MsgType    = MessageType.Call,
                    Method     = TaskStatusMethod,
                    TaskId     = data.Item2.TaskId,
                    NodeTaskId = data.Item2.NodeTaskId,
                    Data       = new Tuple <NodeState, object>(NodeState.Work, progression)
                };
                SendData(Orch, status);
            }
        }
예제 #2
0
 public void Dispatch <T>(IAction action) where T : IState <T>
 {
     if (!subscribers.ContainsKey(action.GetName()))
     {
         return;
     }
     // Before take action
     foreach (Subscriber subscriber in subscribers[action.GetName()])
     {
         subscriber.Invoke(action, true);
     }
     for (int i = 0; i < reducers.Count; i++)
     {
         try
         {
             IReducer <T> reducer = (IReducer <T>)reducers[i];
             this.store[reducer.GetId()] = reducer.Reduce(action, Select <T>(reducer.GetId()));
         }
         catch { }
     }
     // After take action
     foreach (Subscriber subscriber in subscribers[action.GetName()])
     {
         subscriber.Invoke(action, false);
     }
 }
예제 #3
0
        public Symbol Reduce(ReductionContext context, Symbol s)
        {
            if (!_hash.ContainsKey(s))
            {
                _hash[s] = _reducer.Reduce(context, s);
            }

            return(_hash[s]);
        }
 public UserState Reduce(UserState previousState, IAction action)
 {
     return(new UserState(
                RegisterReducer.Reduce(previousState.Registration, action),
                LoginReducer.Reduce(previousState.Login, action),
                EditReducer.Reduce(previousState.Edit, action),
                UserReducer.Reduce(previousState.User, action)
                ));
 }
예제 #5
0
        public void Dispatch(TAction action)
        {
            _state = _reducer.Reduce(_state, action);

            foreach (var listener in _listeners)
            {
                listener.Invoke(_state);
            }
        }
예제 #6
0
        /// <summary>
        /// Dispatchs specified action
        /// </summary>
        /// <param name="action">Action to dispatch</param>
        public async void Dispatch(TAction action)
        {
            State = await _reducer.Reduce(State, action);

            _listeners.ForEach(listener => listener());
            if (_listeners != null)
            {
                Debug.WriteLine("Listeners count : " + _listeners.Count);
            }
        }
예제 #7
0
        public void Dispatch(IAction action)
        {
            if (action == null)
            {
                throw new ArgumentNullException(nameof(action));
            }

            SetState(_rootReducer.Reduce(State, action));
            _storage.Save(State);
            _devToolsInterop.Send(action, State);
        }
예제 #8
0
        public Symbol Reduce(ReductionContext context, Symbol s)
        {
            int hashCode = s.GetHashCode();

            if (!_cache.ContainsKey(hashCode))
            {
                _cache[hashCode] = _reducer.Reduce(context, s);
            }

            return(_cache[hashCode]);
        }
예제 #9
0
        public IDictionary <int, PnLState> Process(int poolSize)
        {
            //Process Single Tickets in the memory
            var watch = System.Diagnostics.Stopwatch.StartNew();

            eventReceiver.Receive(allUpTickets, matchResults, poolSize);

            // the code that you want to measure comes here
            watch.Stop();
            Console.WriteLine("Time Elapsed in ms for Receiving events :  " + watch.ElapsedMilliseconds);
            int matchPlayed = 0;

            while (matchResults.Count > matchPlayed)
            {
                watch.Restart();
                Console.WriteLine("At Thread " + Thread.CurrentThread.ManagedThreadId + " After match " + matchPlayed + " All Up Tickets Unprocessed : " + allUpTickets.Count);
                foreach (AllUpTicket allUpTicket in allUpTickets)
                {
                    foreach (Leg leg in allUpTicket.Legs)
                    {
                        if (leg.PoolId == matchResults[matchPlayed].PoolId)
                        {
                            SingleTicket ticket = reducer.Reduce(allUpTicket, leg);
                            scenarioGenerator.Generate(mutator, sourcer, pnLConsumer, ticket);
                        }
                    }
                }
                watch.Stop();
                Console.WriteLine("Time Elapsed in ms for Generating the single tickets of match number " + matchPlayed + " :  " + watch.ElapsedMilliseconds);
                watch.Restart();
                scenarioGenerator.Pick(mutator, sourcer, pnLConsumer, matchResults[matchPlayed]);
                reducer.Advance(allUpTickets, matchResults[matchPlayed]);
                matchPlayed++;
                watch.Stop();
                Console.WriteLine("Time Elapsed in ms for Resolving the single tickets of match number " + matchPlayed + " :  " + watch.ElapsedMilliseconds);
            }

            //6. Query Dividend
            pnLConsumer.PrintAllInvestment();
            pnLConsumer.PrintAllDividend();
            pnLConsumer.PrintAllRefund();


            Console.WriteLine("At Thread " + Thread.CurrentThread.ManagedThreadId + " High Water Mark Emitted : " + mutator.HighWaterMark);
            Console.WriteLine("At Thread " + Thread.CurrentThread.ManagedThreadId + " High Water Mark Processed : " + pnLConsumer.GetHighWaterMark());
            Console.WriteLine("At Thread " + Thread.CurrentThread.ManagedThreadId + " Remaining All Up Tickets Unprocessed : " + allUpTickets.Count);

            return(pnLConsumer.GetPnL());
        }
예제 #10
0
        TState IReducer <TState> .Reduce(TState currentState, IAction actionContext)
        {
            TSectionType current = m_getValue(currentState);

            TSectionType after = m_sectionReducer.Reduce(current, actionContext);

            if (!ReferenceEquals(current, after))
            {
                TState copyState = (TState)ReflectionUtility.CopyInstance(typeof(TState), currentState);
                m_setValue(copyState, after);
                return(copyState);
            }

            return(currentState);
        }
예제 #11
0
        public override void RunAsync(CancellationToken cancellationToken)
        {
            var enumerable = _inCollection.GetConsumingEnumerable(cancellationToken);

            try
            {
                var outputs = _reducer.Reduce(enumerable);
                foreach (var output in outputs)
                {
                    _outCollection.Add(output, cancellationToken);
                }
            }
            finally
            {
                _outCollection.CompleteAdding();
            }
        }
예제 #12
0
파일: Store.cs 프로젝트: proxoft/Redux
        public void Initialize(Func <T> initialState)
        {
            var init = initialState();

            _stateStreamSubject.OnNext(init);

            _dispatcherSubscription = _dispatcher
                                      .Scan(
                new StateActionPair <T>(init, default),
                (acc, action) =>
            {
                var state = _reducer.Reduce(acc.State, action);
                return(new StateActionPair <T>(state, action));
            })
                                      .Do(pair =>
            {
                _stateStreamSubject.OnNext(pair.State);
                _effectStream.OnNext(pair);
            })
                                      .Subscribe(
                pair =>
            {
                // eventually do (debug) log
            },
                e => _exceptionHandler.OnException(e)
                );

            _dispatcher.Dispatch(DefaultActions.Initialize);

            foreach (var e in _effects.OfType <IEffect <T> >())
            {
                e.Connect(_effectStream);
            }

            _effectsSubscription = Observable
                                   .Merge(_effects.Select(e => e.OutActions))
                                   .Subscribe(a => _dispatcher.Dispatch(a));

            _dispatcher.Dispatch(DefaultActions.InitializeEffects);
        }
예제 #13
0
        public int Process()
        {
            var denList   = new List <Denomination>();
            var inputData = _input.LoadData();

            foreach (var transaction in inputData)
            {
                IReducer         reducer   = GetReducer((int)transaction.AmountOwed);
                IChangeGenerator generator = new ChangeGenerator();//
                var result = generator.ComputeChange(transaction.AmountChangeCents, (list) =>
                {
                    return(reducer.Reduce(list));
                });
                denList.Add(result);
            }
            if (denList.Any())
            {
                _output.SaveData(denList);
            }

            return(denList.Count);
        }
예제 #14
0
        public Symbol Reduce(Symbol symbol, IReducer reducer)
        {
            EnterScope(symbol.Scope);

            if (symbol is TailHolderSymbol t)
            {
                symbol = t.FabricWithScope(t
                                           .Tail
                                           .Select(tailS =>
                                                   tailS is Identifier i && i.Name == Std.BuiltIns.ReduceFirst.Name
                            ? Reduce(tailS)
                            : tailS
                                                   )
                                           .ToImmutableList()
                                           );
            }

            Symbol result = reducer.Reduce(this, symbol);

            result.Scope = new Scope(symbol.Scope, result.Scope.ListScope());
            LeaveScope();

            return(result);
        }
예제 #15
0
 private IConnectableObservable <TApplicationState> GetStateObservable(IReducer <TApplicationState> reducer, TApplicationState initialState)
 {
     return(dispatcher
            .Scan(initialState, (state, action) => reducer.Reduce(state, action))
            .Replay(1));
 }
예제 #16
0
        public void Run()
        {
            try
            {
                if (parent.Context != null)
                {
                    if (parent.Context.NCacheLog.IsInfoEnabled)
                    {
                        parent.Context.NCacheLog.Info("ReducerTask(" + parent.TaskId + ").Start", "Reducer task is started");
                    }
                }

                bool isCompeletedSuccessfully = true;

                while (isAlive)
                {
                    try
                    {
                        object currObj = null;
                        lock (ReducerInputQueue)
                        {
                            if (ReducerInputQueue.Count == 0 && !isMappercompleted)
                            {
                                Monitor.Wait(ReducerInputQueue);
                            }
                            if (ReducerInputQueue.Count > 0)
                            {
                                currObj = ReducerInputQueue.Dequeue();
                            }
                        }
                        if (currObj != null)
                        {
                            Alachisoft.NCache.Runtime.MapReduce.KeyValuePair entry = (Alachisoft.NCache.Runtime.MapReduce.KeyValuePair)currObj;
                            Object   key = entry.Key;
                            IReducer r   = null;
                            lock (mutex)
                            {
                                if (!reducers.ContainsKey(key))
                                {
                                    r = reducerFactory.Create(key);
                                    r.BeginReduce();
                                    reducers.Add(key, r);
                                }
                                else
                                {
                                    r = (IReducer)reducers[key];
                                }
                            }
                            r.Reduce(entry.Value);
                            ReducedCount = ReducedCount + 1; // increment the reducedCount
                            if (parent.Context.PerfStatsColl != null)
                            {
                                parent.Context.PerfStatsColl.IncrementReducedPerSecRate();
                            }
                        }
                        else
                        {
                            if (isMappercompleted)
                            {
                                parent.PersistOutput(FinalizeReducers());
                                if (parent.Context.NCacheLog.IsInfoEnabled)
                                {
                                    parent.Context.NCacheLog.Info("ReducerTask(" + parent.TaskId + ").Run ", "Reducer Completed, output persisted.");
                                }

                                break;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        if (parent.ExceptionCount < parent.MaxExceptions)
                        {
                            if (parent.Context.NCacheLog != null)
                            {
                                parent.Context.NCacheLog.Error("ReducerTask(" + parent.TaskId + ").Run", " Exception:" + ex.Message);
                            }
                            parent.ExceptionCount = parent.ExceptionCount + 1;
                        }
                        else
                        {
                            isCompeletedSuccessfully = false;
                            parent.LocalReducerFailed();

                            lock (mutex)
                            {
                                //Dispose Reducers
                                foreach (IReducer rr in reducers.Values)
                                {
                                    rr.Dispose();
                                }
                                reducers.Clear();
                            }

                            break;
                        }
                    }
                }

                if (isCompeletedSuccessfully && isAlive)
                {
                    if (parent.Context.NCacheLog.IsInfoEnabled)
                    {
                        parent.Context.NCacheLog.Info("ReducerTask (" + parent.TaskId + ").Run ", "Reduced Total Keys : " + this.ReducedCount);
                    }
                    parent.LocalReducerCompleted();
                    lock (mutex)
                    {
                        foreach (IReducer rr in reducers.Values)
                        {
                            rr.Dispose();
                        }
                        reducers.Clear();
                    }
                }
            }
            catch (Exception e)
            {
                try
                {
                    parent.LocalReducerFailed();
                }
                catch (Exception)
                {}
            }
        }
예제 #17
0
 public void Dispatch(IAction action)
 {
     _currentState = _reducer.Reduce(_currentState, action);
     StateChanged?.Invoke(_currentState);
 }
예제 #18
0
 public IReduceExpr ActionReduce() => action.Reduce(this);