private static Fork DecodeFork(Span <byte> span, ref int offset) { Fork fork = DecodeFork(span.Slice(offset, Fork.SszLength)); offset += Fork.SszLength; return(fork); }
public void EatWith(Fork fork, params Philosopher[] philosophers) { var random = new Random(); while (Interlocked.Read(ref IsHungry) == 0 && !_cancelEvent.IsSet) { //don't have the spoon - patiently wait for spouse if (fork.Owner != this) { #if PRINTF_DEBUGGING Console.WriteLine($"{fork.Owner.Name} is waiting -> doesn't have the fork"); #endif Thread.Sleep(1500); continue; } //if someone else is hungry, insist on passing the spoon if (philosophers.Any(p => Interlocked.Read(ref p.IsHungry) == 0)) { var hungryPhilosopher = philosophers.OrderBy(x => random.Next()) .FirstOrDefault(p => Interlocked.Read(ref p.IsHungry) == 0) ?? throw new InvalidDataException("philosophers collection to eat with should not be empty.."); #if PRINTF_DEBUGGING Console.WriteLine($"Someone else is hungry, {fork.Owner.Name} passes the fork to {hungryPhilosopher.Name}"); #endif fork.Owner = hungryPhilosopher; Thread.Sleep(1500); continue; } //everyone else are not hungry, finally the owner can eat, then give the spoon to someone else... fork.SignalEating(); fork.Owner = philosophers.FirstOrDefault(p => Interlocked.Read(ref p.IsHungry) == 0); } }
/* * private object aspect_Icon(object rowObject) * { * WalletManager.WalletBalance balance = (WalletManager.WalletBalance)rowObject; * int rowheight = listView.RowHeightEffective - 3; * return ContentManager.ResizeImage(ContentManager.GetWalletIcon(balance.WalletName), rowheight, rowheight); * //return ContentManager.GetWalletIcon(balance.WalletName); * } * * public object aspect_CoinName(object rowObject) * { * WalletBalance listItem = (WalletBalance)rowObject; * string coinName = string.Empty; * CoinMarketCapTicker ticker = PreferenceManager.CoinMarketCapPreferences.Tickers.FirstOrDefault(item => item.symbol == listItem.Symbol); * //Decimal total = 0; * //string price = ""; * * if (ticker != null) * { * coinName = ticker.name; * } * * return coinName; * } */ private object aspect_Symbol(object rowObject) { Fork listItem = (Fork)rowObject; int rowheight = listView.RowHeightEffective - 3; return(ContentManager.ResizeImage(ContentManager.GetSymbolIcon(listItem.ticker), rowheight, rowheight)); }
private Task StartPhilosopher(Fork left, Fork right) { var t1 = new Task(() => { while (eatCounter < MAX_EAT_COUNT) { STMSystem.Atomic(() => { left.AttemptToPickUp(); right.AttemptToPickUp(); }); Console.WriteLine("Thread: " + Thread.CurrentThread.ManagedThreadId + " eating."); Thread.Sleep(100); Console.WriteLine("Eat count: " + ++eatCounter); STMSystem.Atomic(() => { left.State.Value = true; right.State.Value = true; }); Thread.Sleep(100); } }); t1.Start(); return(t1); }
private Thread CreatePhilosopher(VBox <int> eatCounter, Fork left, Fork right) { var t1 = new Thread(() => { while (JVSTMSystem.Atomic((t) => eatCounter.Read(t) < MAX_EAT_COUNT)) { JVSTMSystem.Atomic((t) => { if (!left.State.Read(t) || !right.State.Read(t)) { JVSTMSystem.Retry(); } left.State.Put(t, false); right.State.Put(t, false); }); Thread.Sleep(100); JVSTMSystem.Atomic((t) => { eatCounter.Put(t, eatCounter.Read(t) + 1); }); JVSTMSystem.Atomic((t) => { left.State.Put(t, true); right.State.Put(t, true); }); Thread.Sleep(100); } }); return(t1); }
private void AddForkToTeamAssignment(Fork fork, int leg, TeamAssignment teamAssignment) { if (fork == null) { return; } if (fork.loop) { int count = 0; int[] selectedLoop; do { selectedLoop = RandomLoop(fork.numBranches); ++count; } while (count < 200 && !ValidateLoopAssignment(selectedLoop, fork, leg, teamAssignment)); teamAssignment.legAssignForFork[fork].branchForLeg.Add(selectedLoop); // All subforks are reached. foreach (Fork subFork in fork.subForks) { AddForkToTeamAssignment(subFork, leg, teamAssignment); } } else { int selectedBranch; if (fork.fixedLegs != null && fork.fixedLegs[leg] >= 0) { // This is a fixed leg. selectedBranch = fork.fixedLegs[leg]; } else { // Get the branches remaining to be used for this team. List <int> possibleBranches = GetPossibleBranches(fork); for (int i = 0; i < leg; ++i) { if ((fork.fixedLegs == null || fork.fixedLegs[i] < 0) && teamAssignment.legAssignForFork[fork].branchForLeg[i].Length > 0) { possibleBranches.Remove(teamAssignment.legAssignForFork[fork].branchForLeg[i][0]); } } // Pick a random one. selectedBranch = possibleBranches[random.Next(possibleBranches.Count)]; } // Store it. teamAssignment.legAssignForFork[fork].branchForLeg.Add(new int[1] { selectedBranch }); // Only visit the selected subfork. AddForkToTeamAssignment(fork.subForks[selectedBranch], leg, teamAssignment); } AddForkToTeamAssignment(fork.next, leg, teamAssignment); }
public object aspect_btc(object rowObject) { Fork listItem = (Fork)rowObject; Decimal balance = Decimal.Parse(listItem.balance.expected.ToString(), System.Globalization.NumberStyles.Float) / 100000000; CoinMarketCapTicker ticker = PreferenceManager.CoinMarketCapPreferences.Tickers.FirstOrDefault(item => item.symbol == listItem.ticker.ToUpper() && item.name == listItem.name); decimal total = 0; if (ticker != null) { total = balance * ticker.price_btc; } /* * else * { * CryptoCompareCoin coin = PreferenceManager.CryptoComparePreferences.CoinList.FirstOrDefault(item => item.Name == listItem.ticker.ToUpper() && item.CoinName == listItem.name); * if (coin != null) * { * LogManager.AddLogMessage(Name, "aspect_btc", "coin=" + coin.Name, LogManager.LogMessageType.DEBUG); * } * } */ if (total > 0) { return(total.ToString("N8")); } else { return(String.Empty); } }
public BlsSignature GetEpochSignature(Slot slot, BlsPublicKey blsPublicKey) { Fork fork = _beaconChainInformation.Fork; Epoch epoch = ComputeEpochAtSlot(slot); ForkVersion forkVersion; if (epoch < fork.Epoch) { forkVersion = fork.PreviousVersion; } else { forkVersion = fork.CurrentVersion; } DomainType domainType = _signatureDomainOptions.CurrentValue.Randao; Domain randaoDomain = ComputeDomain(domainType, forkVersion); Root epochRoot = _cryptographyService.HashTreeRoot(epoch); Root signingRoot = ComputeSigningRoot(epochRoot, randaoDomain); BlsSignature randaoReveal = _validatorKeyProvider.SignRoot(blsPublicKey, signingRoot); return(randaoReveal); }
public BeaconState(ulong genesisTime, ulong eth1DepositIndex, Eth1Data eth1Data, BeaconBlockHeader latestBlockHeader, uint slotsPerHistoricalRoot, ulong epochsPerHistoricalVector, ulong epochsPerSlashingsVector, int justificationBitsLength) { GenesisTime = genesisTime; Eth1DepositIndex = eth1DepositIndex; _eth1DataVotes = new List <Eth1Data>(); Eth1Data = eth1Data; LatestBlockHeader = latestBlockHeader; _validators = new List <Validator>(); _balances = new List <Gwei>(); _blockRoots = Enumerable.Repeat(Hash32.Zero, (int)slotsPerHistoricalRoot).ToArray(); _stateRoots = Enumerable.Repeat(Hash32.Zero, (int)slotsPerHistoricalRoot).ToArray(); _historicalRoots = new List <Hash32>(); _randaoMixes = Enumerable.Repeat(Hash32.Zero, (int)epochsPerHistoricalVector).ToArray(); _slashings = Enumerable.Repeat(Gwei.Zero, (int)epochsPerSlashingsVector).ToArray(); _previousEpochAttestations = new List <PendingAttestation>(); _currentEpochAttestations = new List <PendingAttestation>(); JustificationBits = new BitArray(justificationBitsLength); Fork = new Fork(new ForkVersion(), new ForkVersion(), Epoch.Zero); CurrentJustifiedCheckpoint = new Checkpoint(new Epoch(0), Hash32.Zero); PreviousJustifiedCheckpoint = new Checkpoint(new Epoch(0), Hash32.Zero); FinalizedCheckpoint = new Checkpoint(new Epoch(0), Hash32.Zero); //_previousCrosslinks = Enumerable.Repeat(new Crosslink(Shard.Zero), (int)(ulong)shardCount).ToArray(); //_currentCrosslinks = Enumerable.Repeat(new Crosslink(Shard.Zero), (int)(ulong)shardCount).ToArray(); //_currentCrosslinks = Enumerable.Range(0, (int)(ulong)shardCount).Select(x => new Crosslink(new Shard((ulong)x))).ToArray(); }
public Philosopher(int philosopherId, Fork leftFork, Fork rightFork) { _philosopherId = philosopherId; _leftFork = leftFork ?? throw new ArgumentNullException(nameof(leftFork)); _rightFork = rightFork ?? throw new ArgumentNullException(nameof(rightFork)); CancellationTokenSource = new CancellationTokenSource(); }
public async Task EatAsync(Fork fork, Knife knife, Food food) { Console.WriteLine("Yummy {0}", id); await Task.Delay(2000); Console.WriteLine("Burp {0}", id); }
/// <summary> /// Note: elements returned in a fixed order, since tree is ordered by hash code and IComparable comparision. /// </summary> /// <returns></returns> public override IEnumerator <T> GetEnumerator() { LinkedList <Base> queue = new LinkedList <Base>(); queue.AddFirst(this.representation); while (queue.Count > 0) { Base cur = queue.First.Value; queue.RemoveFirst(); while (true) { SingleNode singleNode = cur as SingleNode; if (singleNode != null) { yield return(singleNode.value); break; } else { Fork fork = cur as Fork; if (fork != null) { if (fork.left == Base.EmptyTree) { cur = fork.right; } else if (fork.right == Base.EmptyTree) { cur = fork.left; } else { cur = fork.left; queue.AddLast(fork.right); } } else { ListNode listNode = cur as ListNode; if (listNode != null) { ListNode curList = listNode; while (curList != null) { yield return(curList.value); curList = curList.next; } } break; } } } } }
public void Ensure_that_you_cannot_pick_up_an_item_more_than_once() { Avatar avatar = new Avatar(); Fork fork = new Fork(); avatar.PickUp(fork); avatar.PickUp(fork); }
public object aspect_usd(object rowObject) { //Fork listItem = (Fork)rowObject; Fork listItem = (Fork)rowObject; if (listItem.TotalInUSD > 0) { return(listItem.TotalInUSD.ToString("C")); } else { return(string.Empty); } /* * Decimal balance = Decimal.Parse(listItem.balance.expected.ToString(), System.Globalization.NumberStyles.Float) / 100000000; * CoinMarketCapTicker ticker = PreferenceManager.CoinMarketCapPreferences.Tickers.FirstOrDefault(item => item.symbol == listItem.ticker.ToUpper() && item.name == listItem.name); * decimal total = 0; * * if (ticker != null) * { * total = balance * ticker.price_usd; * } * * if (total > 0) * { * return total.ToString("C"); * } * else * { * return String.Empty; * } */ }
private void CreateFork(Dictionary <int, ForkRawData> rawForks, int forkId) { var forkRawData = rawForks[forkId]; var res = new Fork { Id = forkRawData.Id }; UpdateFork(res, forkRawData); _forks[forkRawData.Id] = res; if (forkRawData.ParentId != 0) { if (!_forks.ContainsKey(forkRawData.ParentId)) { CreateFork(rawForks, forkRawData.ParentId); } res.Parent = _forks[forkRawData.ParentId]; } foreach (var childId in forkRawData.ChildrenIds) { if (!_forks.ContainsKey(childId)) { CreateFork(rawForks, childId); } res.Children.Add(_forks[childId]); } }
private static void ProcessFork(Fork fork, ExecutionContext executionContext) { Flow flow = executionContext.Flow; var delegationRepository = ServiceLocator.Current.GetInstance <IRepository <DelegationDef> >(); DelegationDef delegation = delegationRepository.Get(fork.ForkDelegationId); if (delegation != null) { var delegationHelper = ServiceLocator.Current.GetInstance <IDelegationHelper>(); delegationHelper.DelegateFork(delegation, executionContext); } else { var transitionRepository = ServiceLocator.Current.GetInstance <IRepository <Transition> >(); var leavingTransitions = transitionRepository.With(w => w.To).Where(q => q.From.Id == fork.Id); foreach (var transition in leavingTransitions) { executionContext.ForkFlow(transition); } } Flow parentFlow = executionContext.Flow; executionContext.Flow = parentFlow; IList <ForkedFlow> forkedFlows = executionContext.ForkedFlows; foreach (var forkedFlow in forkedFlows) { executionContext.RunActionsForEvent(EventType.FORK, fork.Id); executionContext.Flow = forkedFlow.Flow; ProcessTransition(forkedFlow.Transition, executionContext); } }
public async Task <BlsSignature> GetAttestationSignatureAsync(Attestation unsignedAttestation, BlsPublicKey blsPublicKey) { Fork fork = _beaconChainInformation.Fork; Epoch epoch = ComputeEpochAtSlot(unsignedAttestation.Data.Slot); ForkVersion forkVersion; if (epoch < fork.Epoch) { forkVersion = fork.PreviousVersion; } else { forkVersion = fork.CurrentVersion; } DomainType domainType = _signatureDomainOptions.CurrentValue.BeaconAttester; (DomainType domainType, ForkVersion forkVersion)cacheKey = (domainType, forkVersion); Domain attesterDomain = await _cache.GetOrCreateAsync(cacheKey, entry => { return(Task.FromResult(ComputeDomain(domainType, forkVersion))); }).ConfigureAwait(false); Root attestationDataRoot = _cryptographyService.HashTreeRoot(unsignedAttestation.Data); Root signingRoot = ComputeSigningRoot(attestationDataRoot, attesterDomain); BlsSignature signature = _validatorKeyProvider.SignRoot(blsPublicKey, signingRoot); return(signature); }
void eat(Fork forksAndSema) { //manupilating with the state of the forksForDrawing bool startedEating = false; forksAndSema.semaphore.WaitOne();//ensuring that no one else will check or get the forks while he is doing that if (forksAndSema.forks[position] && forksAndSema.forks[(position + 1) % 5])//are the left fork and right fork free { changeState(State.eating); startedEating = true; forksAndSema.forks[position] = false; forksAndSema.forks[(position + 1) % 5] = false; Fork.forkForDrawing[position].changeStateUSING(); Fork.forkForDrawing[(position + 1) % 5].changeStateUSING(); } forksAndSema.semaphore.Release(); if (startedEating) { Thread.Sleep(4000); stopEatingAndthink(forksAndSema); } else { changeState(State.waiting); Thread.Sleep(2000); eat(forksAndSema); } }
public BlsSignature GetBlockSignature(BeaconBlock block, BlsPublicKey blsPublicKey) { Fork fork = _beaconChainInformation.Fork; Epoch epoch = ComputeEpochAtSlot(block.Slot); ForkVersion forkVersion; if (epoch < fork.Epoch) { forkVersion = fork.PreviousVersion; } else { forkVersion = fork.CurrentVersion; } DomainType domainType = _signatureDomainOptions.CurrentValue.BeaconProposer; Domain proposerDomain = ComputeDomain(domainType, forkVersion); /* * JsonSerializerOptions options = new System.Text.Json.JsonSerializerOptions { WriteIndented = true }; * options.ConfigureNethermindCore2(); * string blockJson = System.Text.Json.JsonSerializer.Serialize(block, options); */ Root blockRoot = _cryptographyService.HashTreeRoot(block); Root signingRoot = ComputeSigningRoot(blockRoot, proposerDomain); BlsSignature signature = _validatorKeyProvider.SignRoot(blsPublicKey, signingRoot); return(signature); }
void eatLeadingToDeadLock(Fork forkAndSema, bool fork1, bool fork2) { forkAndSema.semaphore.WaitOne(); // bool startedEating = false; if (forkAndSema.forks[position] && !fork1) { forkAndSema.forks[position] = false; fork1 = true; } if (forkAndSema.forks[(position + 1) % 5] && !fork2) { forkAndSema.forks[(position + 1) % 5] = false; fork2 = true; } forkAndSema.semaphore.Release(); if (fork1 && fork2) { changeState(State.eating); Thread.Sleep(3000); stopEatingAndthink(forkAndSema); } else { changeState(State.waiting); Thread.Sleep(300); eatLeadingToDeadLock(forkAndSema, fork1, fork2); } }
static void Main(string[] args) { int i = 0; Knife knife1 = new Knife(); Knife knife2 = new Knife(); Fork fork1 = new Fork(); Fork fork2 = new Fork(); List <Eater> eaters = new List <Eater>() { new Eater("John"), new Eater("Sam"), new Eater("Rob"), new Eater("Sarah") }; while (i < 10) { Thread thread1 = new Thread(() => eaters[0].Eat(fork1, knife1)); thread1.Start(); Thread thread2 = new Thread(() => eaters[1].Eat(fork1, knife1)); thread2.Start(); Thread thread3 = new Thread(() => eaters[2].Eat(fork2, knife2)); thread3.Start(); Thread thread4 = new Thread(() => eaters[3].Eat(fork2, knife2)); thread4.Start(); i++; } }
private void InitializeDinerState(int id, Fork leftFork, Fork rightFork) { ID = id; LeftFork = leftFork; RightFork = rightFork; State = DinerState.TryingToGetForks; }
private bool ValidateLoopAssignment(int[] loop, Fork fork, int leg, TeamAssignment teamAssignment) { // Restriction 1: the first loop must be different for first N legs (N is number of loops) if (leg < fork.numBranches) { for (int otherLeg = 0; otherLeg < leg; ++otherLeg) { int[] otherBranches = teamAssignment.legAssignForFork[fork].branchForLeg[otherLeg]; if (otherBranches.Length > 0 && otherBranches[0] == loop[0]) { return(false); } } } // Restriction 2: the entire loop must be as different as possible. int maxDups = leg / (int)Util.Factorial(fork.numBranches); int dups = teamAssignment.legAssignForFork[fork].branchForLeg.Count(branch => Util.EqualArrays(branch, loop)); if (dups > maxDups) { return(false); } return(true); }
public void Ensure_that_you_cannot_eat_ice_cream_with_a_fork() { Avatar avatar = new Avatar(); IceCream iceCream = new IceCream(); Fork fork = new Fork(); avatar.PickUp(fork); avatar.Eat(iceCream).With(fork); }
public void SetFork(Fork fork, int maxBett) { var coeff1 = Convert.ToDouble(fork.Cof1); var coeff2 = Convert.ToDouble(fork.Cof2); var bet = maxBett; Data = Calculator.CalculatorBet(coeff1, coeff2, bet); }
// ReSharper disable UnusedParameter.Global public async Task EatAsync(Fork fork, Knife knife, Food food) // ReSharper restore UnusedParameter.Global { Console.WriteLine("Yummy {0}", _id); await Task.Delay(TimeSpan.FromSeconds(2)); Console.WriteLine("Burp {0}", _id); }
public BeaconState InitializeBeaconStateFromEth1(Bytes32 eth1BlockHash, ulong eth1Timestamp, IList <Deposit> deposits) { if (_logger.IsInfo()) { Log.InitializeBeaconState(_logger, eth1BlockHash, eth1Timestamp, deposits.Count, null); } InitialValues initialValues = _initialValueOptions.CurrentValue; GweiValues gweiValues = _gweiValueOptions.CurrentValue; TimeParameters timeParameters = _timeParameterOptions.CurrentValue; StateListLengths stateListLengths = _stateListLengthOptions.CurrentValue; Fork fork = new Fork(initialValues.GenesisForkVersion, initialValues.GenesisForkVersion, _chainConstants.GenesisEpoch); ulong genesisTime = eth1Timestamp - (eth1Timestamp % timeParameters.MinimumGenesisDelay) + (2 * timeParameters.MinimumGenesisDelay); Eth1Data eth1Data = new Eth1Data(Root.Zero, (ulong)deposits.Count, eth1BlockHash); Root emptyBlockBodyRoot = _cryptographyService.HashTreeRoot(BeaconBlockBody.Zero); BeaconBlockHeader latestBlockHeader = new BeaconBlockHeader(emptyBlockBodyRoot); Bytes32[] randaoMixes = Enumerable.Repeat(eth1BlockHash, (int)stateListLengths.EpochsPerHistoricalVector) .ToArray(); BeaconState state = new BeaconState(genesisTime, fork, eth1Data, latestBlockHeader, randaoMixes, timeParameters.SlotsPerHistoricalRoot, stateListLengths.EpochsPerHistoricalVector, stateListLengths.EpochsPerSlashingsVector, _chainConstants.JustificationBitsLength); // Process deposits List <DepositData> depositDataList = new List <DepositData>(); foreach (Deposit deposit in deposits) { depositDataList.Add(deposit.Data); Root depositRoot = _cryptographyService.HashTreeRoot(depositDataList); state.Eth1Data.SetDepositRoot(depositRoot); _beaconStateTransition.ProcessDeposit(state, deposit); } // Process activations for (int validatorIndex = 0; validatorIndex < state.Validators.Count; validatorIndex++) { Validator validator = state.Validators[validatorIndex]; Gwei balance = state.Balances[validatorIndex]; Gwei effectiveBalance = Gwei.Min(balance - (balance % gweiValues.EffectiveBalanceIncrement), gweiValues.MaximumEffectiveBalance); validator.SetEffectiveBalance(effectiveBalance); if (validator.EffectiveBalance == gweiValues.MaximumEffectiveBalance) { validator.SetEligible(_chainConstants.GenesisEpoch); validator.SetActive(_chainConstants.GenesisEpoch); } } return(state); }
public static void Ize(out UInt256 root, Fork container) { Merkleizer merkleizer = new Merkleizer(2); merkleizer.Feed(container.PreviousVersion); merkleizer.Feed(container.CurrentVersion); merkleizer.Feed(container.Epoch); merkleizer.CalculateRoot(out root); }
public static Fork Clone(Fork other) { var clone = new Fork( other.PreviousVersion, other.PreviousVersion, other.Epoch); return(clone); }
public Philosopher(string _Name, Fork _left, Fork _right, Waiter _waiter) { Name = _Name; left = _left; right = _right; waiter = _waiter; resetEvent = new AutoResetEvent(false); Task.Run(() => Process()); }
public void Ensure_that_you_cannot_wash_things_if_you_are_holding_non_washable_stuff() { Avatar avatar = new Avatar(); BagOfHolding bag = new BagOfHolding(); Fork fork = new Fork(); avatar.PickUp(bag); avatar.PickUp(fork); avatar.StartWashing(); }
public Philisofers(int index, Point center, int mode, Fork forkAndS) { forksAndSema = forkAndS; Mode = mode; state = State.thinking; position = index; circle = new Circle(center, state); thread = new Thread(new ParameterizedThreadStart(this.start)); }
private static IEnumerable <SszElement> GetValues(Fork item) { yield return(item.PreviousVersion.ToSszBasicVector()); yield return(item.CurrentVersion.ToSszBasicVector()); // Epoch of latest fork yield return(item.Epoch.ToSszBasicElement()); }
public void Eating_raw_bacon_is_bad_for_you() { Avatar avatar = new Avatar(); BaconSlab bacon = new BaconSlab(); Fork fork = new Fork(); Knife knife = new Knife(); avatar.PickUp(fork); avatar.PickUp(knife); avatar.Eat(bacon).With(fork, knife); }
public List<Fork> SearchForks(GameInfo gameInfo, List<Game> gameList, SportType sportType) { if (gameList == null) { throw new ArgumentNullException(nameof(gameList)); } var rulesList = this.rulesProvider.GiveListOfRules(sportType); var listForks = new List<Fork>(); for (var i = 0; i < gameList.Count; i++) { for (var j = i + 1; j < gameList.Count; j++) { foreach (var rule in rulesList) { var firstGame = gameList[i]; var secondGame = gameList[j]; var profitRate = rule.CalculateProfitRate(firstGame, secondGame); if (profitRate == -1) { continue; } var fork = new Fork { SportType = sportType, FirstGame = firstGame, SecondGame = secondGame, ProfitRate = profitRate, FirstBetsName = firstGame.BetsName, SecondBetsName = secondGame.BetsName, DetectedTime = DateTime.Now }; foreach (var firstBet in rule.FirstGameCoefTypes) { fork.CoefsOfFirstBets.Add(firstBet, firstGame.Coefficients[firstBet]); } foreach (var secondBet in rule.SecondGameCoefTypes) { fork.CoefsOfSecondBets.Add(secondBet, secondGame.Coefficients[secondBet]); } listForks.Add(fork); } } } return listForks; }
public void Ensure_that_properly_eating_bacon_causes_it_to_disappear_into_limbo() { Avatar avatar = new Avatar(); BaconSlab bacon = new BaconSlab(); avatar.PickUp(bacon); Assert.AreSame(avatar, bacon.ParentContainerObject); Assert.IsTrue(avatar.Contents.Any(x => x.ObjectId == bacon.ObjectId)); Fork fork = new Fork(); Knife knife = new Knife(); avatar.PickUp(fork); avatar.PickUp(knife); bacon.Cook(); avatar.Eat(bacon).With(fork, knife); Assert.IsNull(bacon.ParentContainerObject); Assert.IsFalse(avatar.Contents.Any(x => x.ObjectId == bacon.ObjectId)); }
public void Contents_of_an_emptied_dishwasher_are_always_clean() { var fork = new Fork(); var spoon = new Spoon(); var glass = new Glass(); Avatar avatar = new Avatar(); avatar.PickUp(fork); avatar.PickUp(spoon); avatar.PickUp(glass); Dishwasher washer = new Dishwasher(); washer.Load(fork); washer.Load(spoon); washer.Load(glass); washer.TakeEverythingOut(); Assert.IsTrue(washer.ContentsAreClean()); }
void FindForks() { variationMapping = QueryEvent.GetVariantCodeMapping(eventDB, new CourseDesignator(courseId)); // Find all forks. allForks = new List<Fork>(); Id<CourseControl> firstCourseControlId = eventDB.GetCourse(courseId).firstCourseControl; firstForkInCourse = FindForksToJoin(firstCourseControlId, Id<CourseControl>.None); }
// Scan forks starting at this fork, updating number of legs and generate warning as needed. // Return number of paths through. private int ScanFork(Fork startFork, int numLegsOnThisFork, int totalPathsToThisPoint) { if (startFork == null) return totalPathsToThisPoint; startFork.numLegsHere = numLegsOnThisFork; if (startFork.loop) { int waysThroughLoops = totalPathsToThisPoint; for (int i = 0; i < startFork.numBranches; ++i) { waysThroughLoops *= ScanFork(startFork.subForks[i], numLegsOnThisFork, 1); } waysThroughLoops *= (int) Util.Factorial(startFork.numBranches); return ScanFork(startFork.next, numLegsOnThisFork, waysThroughLoops); } else { // Figure out how many legs per branch. May not be even. int branchesMore = numLegsOnThisFork % startFork.numBranches; int legsPerBranch = numLegsOnThisFork / startFork.numBranches; if (branchesMore != 0) { // The number of branches doesn't evenly divide the number of legs that start here. Given a warning. branchWarnings.Add(new BranchWarning(startFork.controlCode, legsPerBranch + 1, startFork.codes.Take(branchesMore), legsPerBranch, startFork.codes.Skip(branchesMore))); } int waysThroughBranches = 0; for (int i = 0; i < startFork.numBranches; ++i) { int legsThisBranch = legsPerBranch; if (i < branchesMore) ++legsThisBranch; waysThroughBranches += ScanFork(startFork.subForks[i], legsThisBranch, totalPathsToThisPoint); } return ScanFork(startFork.next, numLegsOnThisFork, waysThroughBranches); } }
public void Ensure_that_you_can_wash_items_without_specifying_wash_event_handlers() { Avatar avatar = new Avatar(); Fork fork1 = new Fork(); Fork fork2 = new Fork(); avatar.PickUp(fork1); avatar.PickUp(fork2); avatar.StartWashing(); }
private bool ValidateLoopAssignment(int[] loop, Fork fork, int leg, TeamAssignment teamAssignment) { // Restriction 1: the first loop must be different for first N legs (N is number of loops) if (leg < fork.numBranches) { for (int otherLeg = 0; otherLeg < leg; ++otherLeg) { int[] otherBranches = teamAssignment.legAssignForFork[fork].branchForLeg[otherLeg]; if (otherBranches.Length > 0 && otherBranches[0] == loop[0]) return false; } } // Restriction 2: the entire loop must be as different as possible. int maxDups = leg / (int)Util.Factorial(fork.numBranches); int dups = teamAssignment.legAssignForFork[fork].branchForLeg.Count(branch => Util.EqualArrays(branch, loop)); if (dups > maxDups) return false; return true; }
public void Ensure_that_you_can_eat_bacon_with_a_knife_and_fork_and_doing_so_makes_them_dirty() { Avatar avatar = new Avatar(); BaconSlab bacon = new BaconSlab(); avatar.PickUp(bacon); Assert.AreSame(avatar, bacon.ParentContainerObject); Assert.IsTrue(avatar.Contents.Any(x => x.ObjectId == bacon.ObjectId)); Fork fork = new Fork(); Knife knife = new Knife(); avatar.PickUp(fork); avatar.PickUp(knife); Assert.AreEqual(DirtRating.SqueakyClean, fork.DirtRating); Assert.AreEqual(100m, fork.PercentClean); Assert.AreEqual(DirtRating.SqueakyClean, knife.DirtRating); Assert.AreEqual(100m, knife.PercentClean); bacon.Cook(); avatar.Eat(bacon).With(fork, knife); Assert.AreEqual(DirtRating.Smudged, fork.DirtRating); Assert.AreEqual(80m, fork.PercentClean); Assert.AreEqual(DirtRating.Smudged, knife.DirtRating); Assert.AreEqual(80m, knife.PercentClean); }
public void Ensure_that_you_can_wash_multiple_items_at_once() { bool dirtRatingImprovedEventHandled = false; bool allItemsCleanEventHandled = false; Avatar avatar = new Avatar(); avatar.NotifyWhenDirtRatingImproves += (sender, args) => { dirtRatingImprovedEventHandled = true; }; avatar.NotifyWhenItemsAreTotallyClean += (sender, args) => { allItemsCleanEventHandled = true; }; Fork fork1 = new Fork {PercentClean = 0}; Fork fork2 = new Fork {PercentClean = 0}; Fork fork3 = new Fork {PercentClean = 0}; avatar.PickUp(fork1); avatar.PickUp(fork2); avatar.PickUp(fork3); avatar.StartWashing(); Assert.IsTrue(dirtRatingImprovedEventHandled); Assert.IsTrue(allItemsCleanEventHandled); }
private void RemoveForkFromTeamAssignment(Fork fork, int leg, TeamAssignment teamAssignment) { teamAssignment.legAssignForFork[fork].branchForLeg.RemoveAt(teamAssignment.legAssignForFork[fork].branchForLeg.Count - 1); }
private void AddForkToStringBuilder(Fork fork, StringBuilder builder, int leg) { if (fork == null) return; int[] selectedBranch = legAssignForFork[fork].branchForLeg[leg]; for (int i = 0; i < selectedBranch.Length; ++i) { builder.Append(fork.codes[selectedBranch[i]]); AddForkToStringBuilder(fork.subForks[selectedBranch[i]], builder, leg); } AddForkToStringBuilder(fork.next, builder, leg); }
Fork FindForksToJoin(Id<CourseControl> begin, Id<CourseControl> join) { Id<CourseControl> nextCourseControlId = begin; Fork firstFork = null, lastFork = null; // Traverse the course control links. while (nextCourseControlId.IsNotNone && nextCourseControlId != join) { CourseControl courseCtl = eventDB.GetCourseControl(nextCourseControlId); if (courseCtl.split) { // Record information about the fork, and link it in. Fork currentFork = new Fork(); currentFork.loop = courseCtl.loop; currentFork.controlCode = eventDB.GetControl(courseCtl.control).code; currentFork.numBranches = courseCtl.loop ? courseCtl.splitCourseControls.Length - 1 : courseCtl.splitCourseControls.Length; currentFork.codes = new char[currentFork.numBranches]; currentFork.subForks = new Fork[currentFork.numBranches]; if (firstFork == null) { firstFork = lastFork = currentFork; } else { lastFork.next = currentFork; lastFork = currentFork; } allForks.Add(currentFork); // Follow all of the alternate paths int j = 0; for (int i = 0; i < courseCtl.splitCourseControls.Length; ++i) { if (!(courseCtl.loop && (i == 0))) { Id<CourseControl> forkStart = courseCtl.splitCourseControls[i]; currentFork.codes[j] = variationMapping[courseCtl.splitCourseControls[i]]; currentFork.subForks[j] = FindForksToJoin(eventDB.GetCourseControl(forkStart).nextCourseControl, courseCtl.splitEnd); ++j; } } if (!courseCtl.loop) { nextCourseControlId = courseCtl.splitEnd; } else { nextCourseControlId = courseCtl.nextCourseControl; } } else { nextCourseControlId = courseCtl.nextCourseControl; } } return firstFork; }
public void ForkIfHitsAPin() { var from = new Coord(1, 1); var shouldBe = new Fork(new Route(new Coord(1, 0), 0.5f), new Route(new Coord(1, 2), 0.5f)); this.AssertNextStep(from, shouldBe); }
public PhilView(bool scalable,bool synchronous) { this.SetStyle(ControlStyles.AllPaintingInWmPaint, true); this.SetStyle(ControlStyles.UserPaint, true); this.SetStyle(ControlStyles.DoubleBuffer, true); Size = new Size(600, 620); Graphics g = Graphics.FromImage(offscreen); g.Clear(Color.Black); Text = (scalable) ? "SCALABLE" : "LOCKBASED"; Text += (synchronous) ? " SYNC": " ASYNC"; var howmany = Constants.howmany; Table = new Table(howmany, stopwatch, scalable,synchronous); sprites = new IViewable[2 * howmany]; for (int i = 0; i < 2 * howmany; i += 2) { sprites[i] = new Fork(i / 2, Table); } for (int i = 1; i < 2 * howmany; i += 2) { sprites[i] = new Phil(i / 2, Table); } angle = 360f / sprites.Length; }
public Fork(Fork from) { forkName = from.forkName; }
List<int> GetPossibleBranches(Fork fork) { List<int> result = new List<int>(); int branch = 0; for (int i = 0; i < fork.numLegsHere; ++i) { result.Add(branch); branch = (branch + 1) % fork.numBranches; } return result; }
private void AddForkToTeamAssignment(Fork fork, int leg, TeamAssignment teamAssignment) { if (fork == null) return; if (fork.loop) { int count = 0; int[] selectedLoop; do { selectedLoop = RandomLoop(fork.numBranches); ++count; } while (count < 200 && !ValidateLoopAssignment(selectedLoop, fork, leg, teamAssignment)); teamAssignment.legAssignForFork[fork].branchForLeg.Add(selectedLoop); // All subforks are reached. foreach (Fork subFork in fork.subForks) AddForkToTeamAssignment(subFork, leg, teamAssignment); } else { // Get the branches remaining to be used for this team. List<int> possibleBranches = GetPossibleBranches(fork); for (int i = 0; i < leg; ++i) { if (teamAssignment.legAssignForFork[fork].branchForLeg[i].Length > 0) possibleBranches.Remove(teamAssignment.legAssignForFork[fork].branchForLeg[i][0]); } // Pick a random one. int selectedBranch = possibleBranches[random.Next(possibleBranches.Count)]; // Store it. teamAssignment.legAssignForFork[fork].branchForLeg.Add(new int[1] { selectedBranch }); // Only visit the selected subfork. AddForkToTeamAssignment(fork.subForks[selectedBranch], leg, teamAssignment); } AddForkToTeamAssignment(fork.next, leg, teamAssignment); }
// Scan forks starting at this fork, returning smallest number of unique paths. private int CalcMinUniquePaths(Fork startFork, int smallestPathsToThisPoint) { if (startFork == null) return smallestPathsToThisPoint; if (startFork.loop) { int waysThroughLoops = smallestPathsToThisPoint; for (int i = 0; i < startFork.numBranches; ++i) { waysThroughLoops *= CalcMinUniquePaths(startFork.subForks[i], 1); } waysThroughLoops *= (int)Util.Factorial(startFork.numBranches); return CalcMinUniquePaths(startFork.next, waysThroughLoops); } else { int minWaysThroughBranches = int.MaxValue; for (int i = 0; i < startFork.numBranches; ++i) { minWaysThroughBranches = Math.Min(CalcMinUniquePaths(startFork.subForks[i], smallestPathsToThisPoint), minWaysThroughBranches); } minWaysThroughBranches *= startFork.numBranches; return CalcMinUniquePaths(startFork.next, minWaysThroughBranches); } }