Example #1
0
        public Season CreateFirstSeason(Game game, List<Team> teams, IUnitOfWorkRepository repository)
        {
            // First check the number of teams can be evenly divided into the number of leagues.
             bool teamsOk = teams.Count % Constants.HowManyLeagues == 0;
             if (!teamsOk)
             {
            throw new Exception($"The number of teams must be divided by {Constants.HowManyLeagues}");
             }

             var newSeasonInfo = new NewSeasonInfo { Game = game, SeasonNumber = 0 };

             // Divide all teams between the four leagues based on the team rating.
             teams.Sort((team1, team2) => team2.Rating.CompareTo(team1.Rating));
             int countTeamsPerLeague = teams.Count / Constants.HowManyLeagues;
             newSeasonInfo.TeamsLeague1 = teams.Take(countTeamsPerLeague).ToList();
             newSeasonInfo.TeamsLeague2 = teams.Skip(countTeamsPerLeague).Take(countTeamsPerLeague).ToList();
             newSeasonInfo.TeamsLeague3 = teams.Skip(countTeamsPerLeague * 2).Take(countTeamsPerLeague).ToList();
             newSeasonInfo.TeamsLeague4 = teams.Skip(countTeamsPerLeague * 3).ToList();

             // The teams have been sorted on rating, so given them an initial league table position.
             AssignInitialLeagueTablePosition(teams);

             // In the first season there are no champion and cup winner yet, so pick the two best teams.
             newSeasonInfo.NationalChampion = teams[0];
             newSeasonInfo.NationalCupWinner = teams[1];

             // Now all teams have been placed in the right leagues, so create match schedules for all competitions.
             var seasonAndCompetitionSchedules = CreateSeasonAndCompetitionSchedules(newSeasonInfo);

             // Insert the season and all competition schedules.
             var season = InsertSeasonAndCompetitionSchedule(repository, seasonAndCompetitionSchedules);

             return season;
        }
        public void Select_Finds_FirstToSatisfyAllConstraints()
        {
            var mockery = new MockRepository();
            var constraint1 = mockery.StrictMock<IResidentConstraint>();
            var constraint2 = mockery.StrictMock<IResidentConstraint>();
            var selector = new ResidentSelector();
            selector.Constraints.Clear();
            selector.Constraints.Add(constraint1);
            selector.Constraints.Add(constraint2);

            var residents = new List<Resident> { new Resident(), new Resident(), new Resident() };
            var shift = new Shift(DateTime.Today, DateTime.Today, DateTime.Today);
            using (mockery.Record()) {
                SetupResult.For(constraint1.Assignable(residents.First(), shift)).Return(false);
                SetupResult.For(constraint2.Assignable(residents.First(), shift)).Return(true);

                SetupResult.For(constraint1.Assignable(residents.Skip(1).First(), shift)).Return(true);
                SetupResult.For(constraint2.Assignable(residents.Skip(1).First(), shift)).Return(false);

                SetupResult.For(constraint1.Assignable(residents.Skip(2).First(), shift)).Return(true);
                SetupResult.For(constraint2.Assignable(residents.Skip(2).First(), shift)).Return(true);
            }
            using (mockery.Playback()) {
                Assert.AreEqual(residents.Skip(2).First(), selector.Select(residents, shift));
            }
        }
        public static List<List<Tuple<Teams, Teams>>> ListMatches(List<Teams> listTeam)
        {
            var result = new List<List<Tuple<Teams, Teams>>>();

            int numDays = (listTeam.Count - 1);
            int halfSize = listTeam.Count / 2;
            var teams = new List<Teams>();
            teams.AddRange(listTeam.Skip(halfSize).Take(halfSize));
            teams.AddRange(listTeam.Skip(1).Take(halfSize - 1).ToArray().Reverse());
            int teamsSize = teams.Count;

            for (int day = 0; day < numDays; day++)
            {
                var round = new List<Tuple<Teams, Teams>>();
                int teamIdx = day % teamsSize;
                round.Add(new Tuple<Teams, Teams>(teams[teamIdx], listTeam[0]));

                for (int idx = 1; idx < halfSize; idx++)
                {
                    int firstTeam = (day + idx) % teamsSize;
                    int secondTeam = (day + teamsSize - idx) % teamsSize;

                    round.Add(new Tuple<Teams, Teams>(teams[firstTeam], teams[secondTeam]));
                }
                result.Add(round);
            }
            return result;
        }
Example #4
0
        private void SortGlobalSections(List<Line> lines)
        {
            var begin = lines
                .Where(line => line.Content.Trim().StartsWith("GlobalSection(", StringComparison.OrdinalIgnoreCase))
                .ToList();

            var sections = begin.Select(line => new
                {
                    Begin = line,
                    Entries = lines.Skip(line.Index + 1)
                        .TakeWhile(x => !x.Content.Trim().Equals("EndGlobalSection", StringComparison.OrdinalIgnoreCase))
                        .OrderBy(x => x.Content)
                        .ToList(),
                    End = lines.Skip(line.Index + 1)
                        .First(x => x.Content.Trim().Equals("EndGlobalSection", StringComparison.OrdinalIgnoreCase))
                }).ToList();

            foreach (var section in sections)
            {
                lines.RemoveRange(section.Begin.Index + 1, section.Entries.Count);
                lines.InsertRange(section.Begin.Index + 1, section.Entries);
            }

            ResetIndexes(lines);
        }
        private void ReceiveData(List<byte> data, IReadState readState, Action<FrameType, byte[]> processFrame)
        {
            while (data.Count >= 2)
            {
                bool isFinal = (data[0] & 128) != 0;
                var frameType = (FrameType)(data[0] & 15);
                int length = (data[1] & 127);

                var reservedBits = (data[0] & 112);

                if (reservedBits != 0)
                {                    
                    return;
                }

                int index = 2;
                int payloadLength;
                if (length == 127)
                {
                    if (data.Count < index + 8)
                        return; //Not complete
                    payloadLength = data.Skip(index).Take(8).ToArray().ToLittleEndianInt();
                    index += 8;
                }
                else if (length == 126)
                {
                    if (data.Count < index + 2)
                        return; //Not complete
                    payloadLength = data.Skip(index).Take(2).ToArray().ToLittleEndianInt();
                    index += 2;
                }
                else
                {
                    payloadLength = length;
                }

                if (data.Count < index + 4)
                    return; //Not complete

                if (data.Count < index + payloadLength)
                    return; //Not complete
                IEnumerable<byte> payload = data
                    .Skip(index)
                    .Take(payloadLength)
                    .Select(b => b);
                readState.Data.AddRange(payload);
                data.RemoveRange(0, index + payloadLength);
                if (frameType != FrameType.Continuation)
                    readState.FrameType = frameType;
                if (!isFinal || !readState.FrameType.HasValue) continue;
                byte[] stateData = readState.Data.ToArray();
                FrameType? stateFrameType = readState.FrameType;
                readState.Clear();
                processFrame(stateFrameType.Value, stateData);
            }

        }
Example #6
0
	public static void RunArgs (List<String> args) {
		if (args!=null && args.Count>0) {
			var x = args[0].ToUpper();
			if (x=="XTCLI") { App.ExeType="CLI"; App.CommandClass="XT.App+CLI+Commands"; args=args.Skip(1).ToList(); }
			if (x=="XTGUI") { App.ExeType="GUI"; App.CommandClass="XT.App+GUI+Commands"; args=args.Skip(1).ToList(); }
			if (x=="XTSVC") { App.ExeType="SVC"; App.CommandClass="XT.App+SVC+Commands"; args=args.Skip(1).ToList(); }
		}
		//if (args[0].Contains(".Commands")) { App.CommandClass = args[0]; args = args.Skip(1).ToList(); }
		RunCommand(App.CommandClass,args);
	}
Example #7
0
        public PriceModel(List<double> deltas, double tailPercent)
        {
            this.tailPercent = tailPercent;
            // отсечь 0.2% + 0.2% результатов "справа" и "слева" как "хвосты"
            var tailCount = (int)(deltas.Count * this.tailPercent / 100);
            var bodyCount = deltas.Count - tailCount * 2;

            tailLeft = new ValueRange(deltas.Take(tailCount).ToArray(), StepsPerTail);
            body = new ValueRange(deltas.Skip(tailCount).Take(bodyCount).ToArray(), StepsPerBody);
            tailRight = new ValueRange(deltas.Skip(tailCount + bodyCount).ToArray(), StepsPerTail);
        }
Example #8
0
        /// <summary>
        /// Retorna uma lista de KeyValuePair, onde a chave são os valores de input e o seu valor correspondente são os valores de output
        /// </summary>
        /// <param name="dados"></param>
        /// <param name="janelaEntrada">tamanho do input</param>
        /// <param name="janelaSaida">tamanho do output</param>
        /// <param name="considerarSaidasComoEntradas">se verdadeiro, teremos 'dados.Count / janelaEntrada' registros como saida, caso contrario, 'dados.Count / (janelaEntrada + janelaSaida)' </param>
        /// <returns></returns>
        public static List<KeyValuePair<double[], double[]>> SelecionarCotacoesPorJanelamento(List<double> dados, int janelaEntrada, int janelaSaida, bool considerarSaidasComoEntradas)
        {
            /*Cria um mapeamento de entradas para saida com o janelamento informado*/
            List<KeyValuePair<double[], double[]>> dadosPorJanelamento = new List<KeyValuePair<double[], double[]>>();
            for (int i = 0; i < dados.Count - (janelaEntrada + janelaSaida); i += janelaEntrada + (considerarSaidasComoEntradas ? 0 : janelaSaida))
            {
                dadosPorJanelamento.Add(new KeyValuePair<double[], double[]>(dados.Skip(i).Take(janelaEntrada).ToArray(), dados.Skip(i + janelaEntrada).Take(janelaSaida).ToArray()));
            }
            /*Cria um mapeamento de entradas para saida com o janelamento informado*/

            return dadosPorJanelamento;
        }
        public void Select_Finds_Resident_Associated_With_RotationShift_First()
        {
            var rotationShift = new RotationShift(BitwiseDayOfWeek.Monday | BitwiseDayOfWeek.Tuesday, TimeConstants.StartOfDay12HourDay, TimeConstants.EndOfDay12HourDay);
            var shifts = new ShiftFactory().Create(new List<RotationShift> { rotationShift }, new DateTime(2012, 12, 3), new DateTime(2012, 12, 4)).ToList();
            var residents = new List<Resident> { new Resident(), new Resident() };

            shifts.First().Resident = residents.Skip(1).First();

            var selector = new ResidentSelector();
            selector.Constraints.Clear();

            Assert.AreEqual(residents.Skip(1).First(), selector.Select(residents, shifts.Skip(1).First()));
        }
Example #10
0
        public static iDeviceError GetDeviceList(out List<IDevice> deviceList)
        {
            List<IDevice> devices = new List<IDevice>();
            IntPtr devicesPtr;
            iDeviceError returnCode = SearchForDevices(out devices, out devicesPtr);

            devices = devices.Where(x => devices.Skip(devices.IndexOf(x) + 1).Count(y => y.Udid == x.Udid) == 0).ToList();

            deviceList = new List<IDevice>();
            foreach (IDevice currDevice in devices)
            {
                IntPtr lockdownService;
                IntPtr lockdownClient;
                Lockdown.LockdownError lockdownReturnCode = Lockdown.Start(currDevice.Handle, out lockdownClient, out lockdownService);

                XDocument deviceProperties;
                lockdownReturnCode = Lockdown.GetProperties(lockdownClient, out deviceProperties);

                IEnumerable<XElement> keys = deviceProperties.Descendants("dict").Descendants("key");
                deviceList.Add(new IDevice(
                    IntPtr.Zero,
                    keys.Where(x => x.Value == "UniqueDeviceID").Select(x => (x.NextNode as XElement).Value).FirstOrDefault(),
                    keys.Where(x => x.Value == "SerialNumber").Select(x => (x.NextNode as XElement).Value).FirstOrDefault(),
                    keys.Where(x => x.Value == "DeviceName").Select(x => (x.NextNode as XElement).Value).FirstOrDefault(),
                    keys.Where(x => x.Value == "ProductType").Select(x => (x.NextNode as XElement).Value).FirstOrDefault()
                    ));

                // Freeing
                lockdownReturnCode = Lockdown.FreeService(lockdownService);
                lockdownReturnCode = Lockdown.FreeClient(lockdownClient);
                returnCode = FreeDevice(currDevice.Handle);
            }

            return returnCode;
        }
Example #11
0
        private static string Solve(string[] words)
        {
            string prefix = string.Empty;
            List sorted = new List(words);

            while (true) {
                sorted = sorted.OrderBy(x => x).ToList();
                if (sorted.Count == 0) break;

                string pr = sorted.First();
                string sf = sorted.Skip(1)
                                .Where(a => a.StartsWith(pr))
                                .Select(s => s.Substring(pr.Length))
                                .Where(s => !string.IsNullOrEmpty(s))
                                .OrderBy(x => x + pr)
                                .FirstOrDefault();

                if (string.Compare(pr + pr, pr + sf) < 0)
                    sf = null;

                prefix += pr + sf;
                sorted.Remove(pr + sf);
            }

            return prefix;
        }
        public void Write(Storage storage, string fileSpecificPath, string fileWordsPath)
        {
            var bitmap = new List<byte>();

            var words = GenerateWordsStringAndBitmap(bitmap, storage);
            if (words == null || words == "")
                return;
            var bytemap = new List<byte>();

            while (bitmap.Count > 0)
            {
                var oneByte = bitmap.Take(8).ToList();
                bitmap = bitmap.Skip(8).ToList();
                bytemap.Add(oneByte.Aggregate((byte)0, (result, bit) => (byte)((result << 1) | bit)));
            }

            using (var streamWriter = new StreamWriter(fileWordsPath))
            {
                streamWriter.Write(words);
            }
            using (var fileStream = new FileStream(fileSpecificPath, FileMode.OpenOrCreate))
            {
                fileStream.Write(bytemap.ToArray(), 0, bytemap.Count);
                fileStream.Close();
            }
        }
 private bool ExecuteAddRemove(HaloTag tag, List<string> args)
 {
     if (args.Count < 3)
         return false;
     var dependencies = args.Skip(2).Select(a => ArgumentParser.ParseTagIndex(_cache, a)).ToList();
     if (dependencies.Count == 0 || dependencies.Any(d => d == null))
         return false;
     if (args[0] == "add")
     {
         foreach (var dependency in dependencies)
         {
             if (tag.Dependencies.Add(dependency.Index))
                 Console.WriteLine("Added dependency on tag {0:X8}.", dependency.Index);
             else
                 Console.Error.WriteLine("Tag {0:X8} already depends on tag {1:X8}.", tag.Index, dependency.Index);
         }
     }
     else
     {
         foreach (var dependency in dependencies)
         {
             if (tag.Dependencies.Remove(dependency.Index))
                 Console.WriteLine("Removed dependency on tag {0:X8}.", dependency.Index);
             else
                 Console.Error.WriteLine("Tag {0:X8} does not depend on tag {1:X8}.", tag.Index, dependency.Index);
         }
     }
     using (var stream = _fileInfo.Open(FileMode.Open, FileAccess.ReadWrite))
         _cache.UpdateTag(stream, tag);
     return true;
 }
        public Statistics(IEnumerable<double> values)
        {
            list = values.ToList();
            N = list.Count;
            if (N == 0)
                throw new InvalidOperationException("StatSummary: Sequence contains no elements");
            list.Sort();

            if (N == 1)
                Q1 = Median = Q3 = list[0];
            else
            {
                Func<IList<double>, double> getMedian = x => x.Count % 2 == 0
                    ? (x[x.Count / 2 - 1] + x[x.Count / 2]) / 2
                    : x[x.Count / 2];
                Median = getMedian(list);
                Q1 = getMedian(list.Take(N / 2).ToList());
                Q3 = getMedian(list.Skip((N + 1) / 2).ToList());
            }

            Min = list.First();
            Mean = list.Average();
            Max = list.Last();

            InterquartileRange = Q3 - Q1;
            LowerFence = Q1 - 1.5 * InterquartileRange;
            UpperFence = Q3 + 1.5 * InterquartileRange;

            Outliers = list.Where(IsOutlier).ToArray();

            StandardDeviation = N == 1 ? 0 : Math.Sqrt(list.Sum(d => Math.Pow(d - Mean, 2)) / (N - 1));
            StandardError = StandardDeviation / Math.Sqrt(N);
            ConfidenceInterval = new ConfidenceInterval(Mean, StandardError);
            Percentiles = new PercentileValues(list);
        }
        public static List<FortData> Optimize(FortData[] pokeStops, LatLong latlng, GMapOverlay routeOverlay)
        {
            List<FortData> optimizedRoute = new List<FortData>(pokeStops);

            // NN
            FortData NN = FindNN(optimizedRoute, latlng.Latitude, latlng.Longitude);
            optimizedRoute.Remove(NN);
            optimizedRoute.Insert(0, NN);
            for (int i = 1; i < pokeStops.Length; i++)
            {
                NN = FindNN(optimizedRoute.Skip(i), NN.Latitude, NN.Longitude);
                optimizedRoute.Remove(NN);
                optimizedRoute.Insert(i, NN);
                Visualize(optimizedRoute, routeOverlay);
            }

            // 2-Opt
            bool isOptimized;
            do
            {
                optimizedRoute = Optimize2Opt(optimizedRoute, out isOptimized);
                Visualize(optimizedRoute, routeOverlay);
            }
            while (isOptimized);

            return optimizedRoute;
        }
Example #16
0
		public static string BytesToStringDescription(List<byte> bytes)
		{
			bytes = bytes.Skip(8).Take(32).ToList();
			var encoding = Encoding.GetEncoding(1251);
			string result = encoding.GetString(bytes.ToArray()).TrimEnd();
			return result;
		}
Example #17
0
        public CertificateValidationResult Validate(Certificate certificate)
        {
            if (certificate == null)
                throw new ArgumentNullException("certificate");

            try
            {
                var x509Certs = new List<X509Certificate>();
                x509Certs.AddRange(_chain.Select(c => c.BouncyX509Certificate));
                x509Certs.Add(certificate.BouncyX509Certificate);

                IX509Store x509CertStore = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(x509Certs));

                var x509Certificates = x509Certs.Skip(1).ToList();

                var certPath = new PkixCertPath(x509Certificates);

                ISet trust = new HashSet { new TrustAnchor(x509Certs.First(), null) };

                var certPathValidator = new PkixCertPathValidator();

                var paramsPkix = new PkixParameters(trust);
                paramsPkix.AddStore(x509CertStore);
                paramsPkix.IsRevocationEnabled = false;

                var pkixResult = certPathValidator.Validate(certPath, paramsPkix);

                return new CertificateValidationResult(pkixResult);
            }
            catch (Exception e)
            {
                return new CertificateValidationResult(e);
            }
        }
Example #18
0
 private static void HandleLambda(HashSet<string> accessedVariables, HashSet<string> definedVariables, List<object> list)
 {
     List<object> parameters = (List<object>)list[1];
     AssertAllFunctionParametersAreSymbols(parameters);
     foreach (var i in FindFreeVariablesInLambda(parameters.Select(i => i.ToString()), list.Skip(2), new HashSet<string>()))
         if (!definedVariables.Contains(i)) accessedVariables.Add(i);
 }
Example #19
0
		public static InitializerPath FromResolveResult(ResolveResult resolveResult)
		{
			InitializerPath initializerPath = null;
			var memberPath = new List<IMember>();
			var currentResolveResult = resolveResult;
			do {
				if (currentResolveResult is MemberResolveResult) {
					var memberResolveResult = (MemberResolveResult)currentResolveResult;
					memberPath.Add(memberResolveResult.Member);
					currentResolveResult = memberResolveResult.TargetResult;
				} else if (currentResolveResult is LocalResolveResult) {
					var localResolveResult = (LocalResolveResult)currentResolveResult;
					memberPath.Reverse();
					initializerPath = new InitializerPath(localResolveResult.Variable) {
						MemberPath = memberPath
					};
					break;
				} else if (currentResolveResult is ThisResolveResult) {
					break;
				} else {
					return null;
				}

			} while (currentResolveResult != null);

			if (initializerPath == null) {
				// This path is rooted at a member
				memberPath.Reverse();
				initializerPath = new InitializerPath(memberPath [0]) {
					MemberPath = memberPath.Skip(1).ToList()
				};
			}
			return initializerPath;
		}
		public string GetDebugView()
		{
			var matchers = new List<IMatcherTreeNode>();
			var parent = this.Parent;
			while (!(parent is MethodInfoMatcherTreeNode))
			{
				matchers.Add(parent);
				parent = parent.Parent;
			}
			matchers.Reverse();

			var method = ((MethodInfoMatcherTreeNode)parent).MethodInfo;

			var sb = new StringBuilder();
			bool isInstance = !method.IsStatic || method.IsExtensionMethod();
			var argMatchers = isInstance ? matchers.Skip(1) : matchers;

			if (isInstance)
				sb.AppendFormat("({0}).", matchers[0].Matcher.DebugView);
			else
				sb.AppendFormat("{0}.", method.DeclaringType);

			sb.AppendFormat("{0}({1}) called {2} time{3}; (signature: {4})",
				method.Name,
				", ".Join(argMatchers.Select(m => m.Matcher.DebugView)),
				this.Calls, this.Calls != 1 ? "s" : "",
				method);

			return sb.ToString();
		}
Example #21
0
 private IEnumerable<int[]> Chop(List<int> list)
 {
     for (int i = 0; i < list.Count - 4; i++)
     {
         yield return list.Skip(i).Take(4).ToArray();
     }
 }
Example #22
0
        public static String GetPath(this XmlNode target)
        {
            List<KeyValuePair<String, Int32?>> path = new List<KeyValuePair<String, Int32?>> { };

            while (target.ParentNode != null)
            {
                var siblings = target.ParentNode.SelectNodes(target.Name);
                if (siblings.Count > 1)
                {
                    var siblingIndex = 0;
                    foreach (var sibling in siblings)
                    {
                        if (sibling == target)
                        {
                            path.Add(new KeyValuePair<String, Int32?>(target.ParentNode.Name, siblingIndex));
                        }

                        siblingIndex++;
                    }
                }
                else
                {
                    path.Add(new KeyValuePair<String, Int32?>(target.ParentNode.Name, null));
                }

                target = target.ParentNode;
            }

            path.Reverse();

            return String.Join(".", path.Skip(3).Select(p => p.Value.HasValue ? String.Format("{0}[{1}]", p.Key, p.Value) : p.Key));
        }
Example #23
0
        public OperationResult Parse(string arguments)
        {
            if (arguments == null)
            {
                return new OperationResult("default");
            }

            var components = new List<CommandComponent>();
            var tokens = arguments.Split((char[]) null, StringSplitOptions.RemoveEmptyEntries);
            int currentIndex = 0;
            foreach (var token in tokens)
            {
                currentIndex = arguments.IndexOf(token, currentIndex, StringComparison.Ordinal);
                components.Add(new CommandComponent(currentIndex, token));
            }

            if (components.Count == 0)
            {
                return new OperationResult("default");
            }
            if (components[0].Value.StartsWith("-"))
            {
                return operations["default"].Parse(components, "default", arguments);
            }
            if (!operations.ContainsKey(components[0].Value))
            {
                return operations["default"].Parse(components, "default", arguments);
            }
            else
            {
                return operations[components[0].Value].Parse(components.Skip(1), components[0].Value, arguments);
            }
        }
Example #24
0
        private List<Song> QuickSort(List<Song> collection) {
            if (collection.Count == 1) {
                return collection;
            }    
            if (collection.Count != 1) {
                int key = collection.Count/2;
                List<Song> result = new List<Song>();
                result.Add(collection[key]);

                for (int i = 0; i < collection.Count(); i++) {
                    if (collection[i].CompareTo(collection[key]) == -1) {
                        result.Insert(0, collection[i]);
                    }
                    if (collection[i].CompareTo(collection[key]) == 1) {
                        result.Add(collection[i]);        
                    }
                    if (key == i)
                        continue;
                }
                List<Song> Left = QuickSort(result.Take(key).ToList());
                List<Song> Right = QuickSort(result.Skip(key).ToList());
                result = Left.Union(Right).ToList();
                
                return result;
            }
            
            return collection;
        }
Example #25
0
        private const double RATIO = 0.5; // The probability that a prisoner's value is true

        #endregion Fields

        #region Methods

        // Don't change any code beyond this line. This is the bookkeeping of the simulation.
        public static void Main(string[] args)
        {
            var random = new Random();
            var prisoners = new List<bool>(Enumerable.Range(0, N).Select(i => random.NextDouble() < RATIO));
            var ahead = new List<bool>(prisoners);
            var dead = new List<bool>();
            var declared = new List<bool>();
            var numDead = 0;

            // The game loop
            for (int i = 0; i < N; i++)
            {
                ahead.RemoveAt(0);
                bool declaration = PrisonerAction(i, dead, declared, ahead);
                declared.Add(declaration);
                dead.Add(declaration != prisoners[i]);
                if (declaration != prisoners[i])
                {
                    numDead++;
                }
            }

            Console.WriteLine("Out of {0} prisoners, you killed {1}.", N, numDead);

            if (numDead > 1 || dead.Skip(1).Count(d => d) != 0)
            {
                Console.WriteLine("You can do better than that!");
            }
            else
            {
                Console.WriteLine("Great job! You found the right algorithm!");
            }
            Console.ReadKey();
        }
        // This method will recompute the Bound without precondition. It will not cascade upwards to parent nodes, because
        // it is intended to be called recursively.
        public void BottomUpRecalculateBound()
        {
            List<BoundingBox> childBounds = new List<BoundingBox>();
            foreach (SceneNode child in mChildren)
            {
                ImplicitBoundingBoxNode implicitBVChild = child as ImplicitBoundingBoxNode;
                if (implicitBVChild != null)
                {
                    implicitBVChild.BottomUpRecalculateBound();
                    childBounds.Add(implicitBVChild.Bound);
                }
                else
                {
                    childBounds.AddRange(child.FindExplicitBoundingVolumes());
                }
            }

            BoundingBox combinedBound = childBounds.First();

            foreach (BoundingBox childBox in childBounds.Skip(1))
            {
                combinedBound = BoundingBox.CreateMerged(combinedBound, childBox);
            }

            Bound = combinedBound;
        }
        private IDictionary<string, ITriangle> BuildTriangles(List<string[]> csvRows)
        {
            //could potentially read header row to cope with columns changing order. will keep it simple for now
            var dataRows = csvRows.Skip(1);

            var triangleDictionary = new Dictionary<string, ITriangle>();

            var dataGroups = dataRows.GroupBy(row => row[0]).ToArray();
            foreach (var dataGroup in dataGroups)
            {
                
                var triangleDatapoints = new List<TriangleDataPoint>();
                foreach (var row in dataGroup)
                {
                    try
                    {
                        int originYear = int.Parse(row[1]);
                        int developmentYear = int.Parse(row[2]);
                        double value = double.Parse(row[3]);
                        triangleDatapoints.Add(new TriangleDataPoint(originYear, developmentYear, value));
                    }
                    catch (FormatException e)
                    {
                        throw new FormatException("Row bad format: " + row[0] + ", " + row[1] + ", " + row[2] + ", " + row[3], e);
                    }

                }

                var triangleName = dataGroup.Key;
                triangleDictionary.Add(triangleName, new Triangle(triangleName, triangleDatapoints));

            }

            return triangleDictionary;
        }
        public void EigenUpdateWithoutUpdateURL()
        {
            string dir;
            string outDir;

            using (Utility.WithTempDirectory(out outDir))
            using (IntegrationTestHelper.WithFakeInstallDirectory(out dir)) {
                var di = new DirectoryInfo(dir);
                var progress = new Subject<int>();

                var bundledRelease = ReleaseEntry.GenerateFromFile(di.GetFiles("*.nupkg").First().FullName);
                var fixture = new InstallManager(bundledRelease, outDir);
                var pkg = new ZipPackage(Path.Combine(dir, "SampleUpdatingApp.1.1.0.0.nupkg"));

                var progressValues = new List<int>();
                progress.Subscribe(progressValues.Add);

                fixture.ExecuteInstall(dir, pkg, progress).Wait();

                var filesToLookFor = new[] {
                    "SampleUpdatingApp\\app-1.1.0.0\\SampleUpdatingApp.exe",
                    "SampleUpdatingApp\\packages\\RELEASES",
                    "SampleUpdatingApp\\packages\\SampleUpdatingApp.1.1.0.0.nupkg",
                };

                filesToLookFor.ForEach(f => Assert.True(File.Exists(Path.Combine(outDir, f)), "Could not find file: " + f));

                // Progress should be monotonically increasing
                progressValues.Count.ShouldBeGreaterThan(2);
                progressValues.Zip(progressValues.Skip(1), (prev, cur) => cur - prev).All(x => x > 0).ShouldBeTrue();
            }
        }
        public ActionResult SearchUsers(string searchText, int page = 1)
        {
            UsersViewModel vm = new UsersViewModel();
            List<ApplicationUser> users = new List<ApplicationUser>();
            if (searchText == null)
            {
                return View();
            }
            if (searchText == "All")
            {
                users = UserManager.Users.ToList();
            }
            else
            {
                users = UserManager.Users.Where(u => u.UserName.Contains(searchText) || u.Email.Contains(searchText)).ToList();

            }
            PageInfo pageInfo = new PageInfo() { PageSize = 20, CurrentPage = 1 };
            pageInfo.PageCount = (users.Count() - 1) / pageInfo.PageSize + 1;
            pageInfo.CurrentPage = page <= pageInfo.PageCount ? page : 1;
            pageInfo.Url = "/admin/adminaccount/searchUsers?searchText=" + searchText + "@page=";
            vm.Users = users.Skip((pageInfo.CurrentPage - 1) * pageInfo.PageSize).Take(pageInfo.PageSize).ToList();
            vm.PageInfo = pageInfo;
            return View(vm);
        }
Example #30
0
        private static string GetReplacementIL(List<byte> bytes)
        {
            int index = 2;
            int length = ReadPackedLen(bytes, ref index);

            return Encoding.UTF8.GetString(bytes.Skip(index).Take(length).ToArray());
        }