public void allocateSpace(Room a, Room b, Vector3 brushSize, PropFill propFill) { var points = new HashSet <Vector3>(a.pointsInRoom); while (points.Count > 0) { var p = points.Last(); points.Remove(points.Last()); /*if (propFill.getHasRequiredSpace(p,brushSize,a.pointsInRoom)){ * //Debug.Log(p); * //GameObject.CreatePrimitive(PrimitiveType.Cube).transform.position = p; * * var p2 = b.pointsInRoom.ToList().Find(x => x.x == p.x && x.y == p.y); * if (p2 != null){ * GameObject.CreatePrimitive(PrimitiveType.Cube).transform.position = p2; * break; * * } * * * * * } */ } }
public int SolveFirst() { var numberOfLoops = 0; var hasNext = true; while (hasNext) { numberOfLoops++; var newLoopList = new List <int>(_listOfmemoryloops.Last()); var largestBlockValue = newLoopList.Max(); var largestBlockField = newLoopList.IndexOf(largestBlockValue); newLoopList[largestBlockField] = 0; largestBlockField++; largestBlockField %= newLoopList.Count; while (largestBlockValue != 0) { newLoopList[largestBlockField]++; largestBlockValue--; largestBlockField++; largestBlockField %= newLoopList.Count; } hasNext = _listOfmemoryloops.Add(newLoopList); } return(numberOfLoops); }
public int ClosestValue(TreeNode root, double target) { HashSet <TreeNode> diff = new HashSet <TreeNode>(); Stack <TreeNode> stack = new Stack <TreeNode>(); stack.Push(root); while (stack.Count > 0) { TreeNode tn = stack.Pop(); if (diff.Count == 0) { diff.Add(tn); } else { if (Math.Abs(tn.val - target) < Math.Abs(diff.Last().val - target)) { diff.Add(tn); } } if (tn.left != null) { stack.Push(tn.left); } if (tn.right != null) { stack.Push(tn.right); } } return(diff.Last().val); }
protected HashSet <int[]> GetArea(int[,] mask, int xpos, int ypos, out int[] borders, Func <int, int, bool> op, int valueToFind = 1, int stopSize = 50) { HashSet <int[]> ignore = new HashSet <int[]>(); //Loop and find value, trace all connected values and store them borders = new int[4] { int.MaxValue, int.MaxValue, 0, 0 }; if (mask[xpos, ypos] == valueToFind) { //begin traversal HashSet <int[]> toCheck = new HashSet <int[]>(); toCheck.Add(new int[] { xpos, ypos }); while (toCheck.Count > 0) { var newPoints = GetSurroundingPoints(mask, ignore, toCheck.Last(), (x, y) => x == y, valueToFind); int[] last = toCheck.Last(); ignore.Add(last); borders = AdjustBorders(borders, last[0], last[1]); toCheck.Remove(last); toCheck.AddElementsUnique(newPoints); } } return(ignore); }
public void DiscernRegions(MagickImage mapRegions, int[,] mask, LibVoronoi voronoi, LibVoronoi detail, int[] bounds, Region[] regList, int threadNo, Random fuzz) { HashSet <VoronoiPoint> pixels = new HashSet <VoronoiPoint>(); for (int x = bounds[0]; x < bounds[2]; x++) { for (int y = bounds[1]; y < bounds[3]; y++) { if (mask[x * 2, y * 2] >= 1) { double detailDis; double normDis; int detailVal = detail.ClosestValue(new int[] { x, y }, out detailDis); int normVal = voronoi.ClosestValue(new int[] { x, y }, out normDis); int ind = voronoi.ClosestIndex(new int[] { x, y }); if (x == voronoi.points[ind].x && y == voronoi.points[ind].y) { pixels.Add(new VoronoiPoint(x, y)); pixels.Last().value = -2; continue; } pixels.Add(new VoronoiPoint(x, y)); if (detailDis < normDis) { pixels.Last().value = detailVal; } else if (normDis <= detailDis) { pixels.Last().value = ind; } } else { int ind = voronoi.ClosestIndex(new int[] { x, y }); if (x == voronoi.points[ind].x && y == voronoi.points[ind].y) { pixels.Add(new VoronoiPoint(x, y)); pixels.Last().value = -2; continue; } pixels.Add(new VoronoiPoint(x, y)); pixels.Last().value = -1; } } } PaintPixel(pixels, map.mapRegions, regList); Console.WriteLine("Thread {0} Exiting", threadNo); return; }
internal void Close() { if (elements.Any()) { elements.RemoveWhere(e => e == elements.Last()); Current = (Count == 1) ? null : elements.Last(); Count--; } }
public int CountPatternsFrom(char firstDot, int length) { if (length == 0) { return(0); } dotChain.Add(firstDot); length--; if (length == 0) { length++; dotChain.Remove(dotChain.Last()); return(++countPattern); } for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (dotChain.Contains(dotMatrix[i, j])) { continue; } if ( (Math.Abs(i - GetDotInd(firstDot)[0]) < 2 && Math.Abs(j - GetDotInd(firstDot)[1]) < 2 || Math.Abs(i - GetDotInd(firstDot)[0]) == 1 && Math.Abs(j - GetDotInd(firstDot)[1]) == 2 || Math.Abs(i - GetDotInd(firstDot)[0]) == 2 && Math.Abs(j - GetDotInd(firstDot)[1]) == 1) || (i != 1 || j != 1) && (Math.Abs(i - GetDotInd(firstDot)[0]) == 2 && Math.Abs(j - GetDotInd(firstDot)[1]) == 0 && dotChain.Contains(dotMatrix[i == 0 ? i + 1 : i - 1, j]) || Math.Abs(i - GetDotInd(firstDot)[0]) == 0 && Math.Abs(j - GetDotInd(firstDot)[1]) == 2 && dotChain.Contains(dotMatrix[i, j == 0 ? j + 1 : j - 1]) || Math.Abs(i - GetDotInd(firstDot)[0]) == 2 && Math.Abs(j - GetDotInd(firstDot)[1]) == 2 && dotChain.Contains(dotMatrix[1, 1])) ) { CountPatternsFrom(dotMatrix[i, j], length); } } } dotChain.Remove(dotChain.Last()); return(countPattern); }
public void checkForCompleteness() { Queue <Vector2> vector2Queue = new Queue <Vector2>(); HashSet <Vector2> source = new HashSet <Vector2>(); vector2Queue.Enqueue(this.tileLocation); Vector2 vector2 = new Vector2(); List <Vector2> vector2List = new List <Vector2>(); while (vector2Queue.Count > 0) { Vector2 index1 = vector2Queue.Dequeue(); if (Game1.currentLocation.objects.ContainsKey(index1) && Game1.currentLocation.objects[index1] is SwitchFloor && (Game1.currentLocation.objects[index1] as SwitchFloor).isOn != this.isOn) { return; } source.Add(index1); List <Vector2> adjacentTileLocations = Utility.getAdjacentTileLocations(index1); for (int index2 = 0; index2 < adjacentTileLocations.Count; ++index2) { if (!source.Contains(adjacentTileLocations[index2]) && Game1.currentLocation.objects.ContainsKey(index1) && Game1.currentLocation.objects[index1] is SwitchFloor) { vector2Queue.Enqueue(adjacentTileLocations[index2]); } } adjacentTileLocations.Clear(); } int ticks = 5; foreach (Vector2 key in source) { if (Game1.currentLocation.objects.ContainsKey(key) && Game1.currentLocation.objects[key] is SwitchFloor) { (Game1.currentLocation.objects[key] as SwitchFloor).setSuccessCountdown(ticks); } ticks += 2; } int coins = (int)Math.Sqrt((double)source.Count) * 2; Vector2 index = source.Last <Vector2>(); while (Game1.currentLocation.isTileOccupiedByFarmer(index) != null) { source.Remove(index); if (source.Count > 0) { index = source.Last <Vector2>(); } } Game1.currentLocation.objects[index] = (StardewValley.Object) new Chest(coins, (List <Item>)null, index, false); Game1.currentLocation.temporarySprites.Add(new TemporaryAnimatedSprite(Game1.animations, new Rectangle(0, 320, 64, 64), 50f, 8, 0, index * (float)Game1.tileSize, false, false)); Game1.playSound("coin"); }
public void checkForCompleteness() { Queue <Vector2> openList = new Queue <Vector2>(); HashSet <Vector2> closedList = new HashSet <Vector2>(); openList.Enqueue(tileLocation); Vector2 current = default(Vector2); List <Vector2> adjacent = new List <Vector2>(); while (openList.Count > 0) { current = openList.Dequeue(); if (Game1.currentLocation.objects.ContainsKey(current) && Game1.currentLocation.objects[current] is SwitchFloor && (Game1.currentLocation.objects[current] as SwitchFloor).isOn != isOn) { return; } closedList.Add(current); adjacent = Utility.getAdjacentTileLocations(current); for (int i = 0; i < adjacent.Count; i++) { if (!closedList.Contains(adjacent[i]) && Game1.currentLocation.objects.ContainsKey(current) && Game1.currentLocation.objects[current] is SwitchFloor) { openList.Enqueue(adjacent[i]); } } adjacent.Clear(); } int successTicks = 5; foreach (Vector2 v in closedList) { if (Game1.currentLocation.objects.ContainsKey(v) && Game1.currentLocation.objects[v] is SwitchFloor) { (Game1.currentLocation.objects[v] as SwitchFloor).setSuccessCountdown(successTicks); } successTicks += 2; } int coins = (int)Math.Sqrt(closedList.Count) * 2; Vector2 treasurePosition = closedList.Last(); while (Game1.currentLocation.isTileOccupiedByFarmer(treasurePosition) != null) { closedList.Remove(treasurePosition); if (closedList.Count > 0) { treasurePosition = closedList.Last(); } } Game1.currentLocation.objects[treasurePosition] = new Chest(coins, null, treasurePosition); Game1.currentLocation.temporarySprites.Add(new TemporaryAnimatedSprite("TileSheets\\animations", new Rectangle(0, 320, 64, 64), 50f, 8, 0, treasurePosition * 64f, flicker: false, flipped: false)); Game1.playSound("coin"); }
public void checkForCompleteness() { Queue <Vector2> queue = new Queue <Vector2>(); HashSet <Vector2> hashSet = new HashSet <Vector2>(); queue.Enqueue(this.tileLocation); Vector2 vector = default(Vector2); List <Vector2> list = new List <Vector2>(); while (queue.Count > 0) { vector = queue.Dequeue(); if (Game1.currentLocation.objects.ContainsKey(vector) && Game1.currentLocation.objects[vector] is SwitchFloor && (Game1.currentLocation.objects[vector] as SwitchFloor).isOn != this.isOn) { return; } hashSet.Add(vector); list = Utility.getAdjacentTileLocations(vector); for (int i = 0; i < list.Count; i++) { if (!hashSet.Contains(list[i]) && Game1.currentLocation.objects.ContainsKey(vector) && Game1.currentLocation.objects[vector] is SwitchFloor) { queue.Enqueue(list[i]); } } list.Clear(); } int num = 5; foreach (Vector2 current in hashSet) { if (Game1.currentLocation.objects.ContainsKey(current) && Game1.currentLocation.objects[current] is SwitchFloor) { (Game1.currentLocation.objects[current] as SwitchFloor).setSuccessCountdown(num); } num += 2; } int coins = (int)Math.Sqrt((double)hashSet.Count) * 2; Vector2 vector2 = hashSet.Last <Vector2>(); while (Game1.currentLocation.isTileOccupiedByFarmer(vector2) != null) { hashSet.Remove(vector2); if (hashSet.Count > 0) { vector2 = hashSet.Last <Vector2>(); } } Game1.currentLocation.objects[vector2] = new Chest(coins, null, vector2, false); Game1.currentLocation.temporarySprites.Add(new TemporaryAnimatedSprite(Game1.animations, new Rectangle(0, 320, 64, 64), 50f, 8, 0, vector2 * (float)Game1.tileSize, false, false)); Game1.playSound("coin"); }
bool AddStatement(Statement statement) { if (reachability.IsReachable(statement)) { return(false); } if (collectedStatements.Contains(statement)) { return(true); } if (statement is BlockStatement && statement.GetChildrenByRole <Statement>(BlockStatement.StatementRole).Any(reachability.IsReachable)) { //There's reachable content return(false); } var prevEnd = statement.GetPrevNode(n => !(n is NewLineNode)).EndLocation; // group multiple continuous statements into one issue var start = statement.StartLocation; collectedStatements.Add(statement); visitor.unreachableNodes.Add(statement); Statement nextStatement; while ((nextStatement = (Statement)statement.GetNextSibling(s => s is Statement)) != null && !(nextStatement is LabelStatement)) { statement = nextStatement; collectedStatements.Add(statement); visitor.unreachableNodes.Add(statement); } var end = statement.EndLocation; var removeAction = new CodeAction(visitor.ctx.TranslateString("Remove unreachable code"), script => { var startOffset = script.GetCurrentOffset(prevEnd); var endOffset = script.GetCurrentOffset(end); script.RemoveText(startOffset, endOffset - startOffset); }, collectedStatements.First().StartLocation, collectedStatements.Last().EndLocation); var commentAction = new CodeAction(visitor.ctx.TranslateString("Comment unreachable code"), script => { var startOffset = script.GetCurrentOffset(prevEnd); script.InsertText(startOffset, Environment.NewLine + "/*"); var endOffset = script.GetCurrentOffset(end); script.InsertText(endOffset, Environment.NewLine + "*/"); }, collectedStatements.First().StartLocation, collectedStatements.Last().EndLocation); var actions = new [] { removeAction, commentAction }; visitor.AddIssue(start, end, visitor.ctx.TranslateString("Code is unreachable"), actions); return(true); }
private static JToken ToJToken(HashSet <string> values, DupPolicy policy) { if (values == null) { throw new ArgumentNullException(nameof(values)); } if (values.Count == 0) { throw new ArgumentException("the collection of values is empty", nameof(values)); } if (values.Count == 1) { JToken.FromObject(values.First()); } switch (policy) { case DupPolicy.OnlyLast: return(JToken.FromObject(values.Last())); case DupPolicy.OnlyFirst: return(JToken.FromObject(values.First())); case DupPolicy.Throw: throw new InvalidOperationException("the collection contains more than one value"); case DupPolicy.Array: return(JArray.FromObject(values)); default: throw new ArgumentOutOfRangeException(nameof(policy), policy, null); } }
private static void LoadImages() { HashSet <string> images = new HashSet <string>(); using (WebClient client = new WebClient()) { //string str = client.DownloadString(@"http://www.skovboernehave.dk/Album/20131119Jager/index.html"); //File.WriteAllText(@"C:\Private\GitHub\Projects\ImageLoader\Image Loader Test\20131119Jager.txt", str); string str = File.ReadAllText(@"C:\Private\GitHub\Projects\ImageLoader\Image Loader Test\20131119Jager.txt"); HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(str); var first_page = doc.DocumentNode.SelectNodes("//a[@href]") .Select(l => l.Attributes["href"].Value) .Where(a => a.Contains("slides")) .First(); var page = Path.GetFileName(first_page); Console.WriteLine("Parsing page " + page); while (ParsePage(page, images)) { page = Path.ChangeExtension(images.Last(), ".html"); Console.WriteLine("Parsing page " + page); } } Console.WriteLine("Downloading images"); foreach (var image in images) { DownloadImage(image); } Console.WriteLine("Images found " + images.Count); }
public void SameListTestInHashSet() { var dictionaryFactory = new JsonDictionaryFactory(); var localizationDictionary0 = dictionaryFactory.CreateDictionary("Localization/slovniky/slovniky.cs.json"); var localizationDictionary1 = dictionaryFactory.CreateDictionary("Localization/slovniky/slovniky.cs.json"); var localizationDictionary2 = dictionaryFactory.CreateDictionary("Localization/slovniky/slovniky.cs.json"); var localizationDictionary3 = dictionaryFactory.CreateDictionary("Localization/slovniky/slovniky.cs.json"); var dictionaries = new HashSet <ILocalizationDictionary> { localizationDictionary0, localizationDictionary1, localizationDictionary2, localizationDictionary3 }; Assert.AreEqual(1, dictionaries.Count); var dic = dictionaries.Last(w => w.CultureInfo() .Equals(new CultureInfo("cs")) && w.Scope().Equals("slovniky")); Assert.AreEqual(new CultureInfo("cs"), dic.CultureInfo()); Assert.AreEqual("slovniky", dic.Scope()); Assert.AreEqual(13, dic.List().Count); }
public static IEnumerable <T2> ShuffleByHealth <T, T2>(this IEnumerable <T> items, Func <T, double> healthSelector, Func <T, T2> resultSelector) { var itemsWithHealth = new HashSet <KeyValuePair <T, double> >(items.Select(x => new KeyValuePair <T, double>(x, healthSelector(x)))); var totalItemListLength = itemsWithHealth.Count; for (var i = 0; i < totalItemListLength; i++) { var result = default(T2); var healthSum = itemsWithHealth.Sum(h => h.Value); var valueFound = false; var randomValue = ThreadLocalRandom.Instance.NextDouble(); foreach (var itemWithHealth in itemsWithHealth) { randomValue -= itemWithHealth.Value / healthSum; if (randomValue < epsilon) { valueFound = true; result = resultSelector(itemWithHealth.Key); itemsWithHealth.Remove(itemWithHealth); break; } } if (!valueFound) { var last = itemsWithHealth.Last(); result = resultSelector(last.Key); itemsWithHealth.Remove(last); } yield return(result); } }
public bool IsHappy(int n) { var set = new HashSet <int>() { n }; while (true) { var str = set.Last().ToString(); var res = 0; for (var index = 0; index < str.Length; index++) { var t = int.Parse(str[index].ToString()); res += t * t; } if (res == 1) { return(true); } if () { return(false); } set.Add(res); } }
private static star foo(HashSet <star> stars) { if (stars.Count == 1) { return(stars.ElementAt(0)); } else if (stars.Count == 0) { return(null); } else { HashSet <star> canidates = new HashSet <star>(); if (stars.Count % 2 == 1) { canidates.Add(stars.Last()); } for (int i = 1; i < stars.Count; i += 2) { if (stars.ElementAt(i - 1).distanceSQRD(stars.ElementAt(i)) <= distanceSQRD) { canidates.Add(stars.ElementAt(i - 1)); } } return(foo(canidates)); } }
private void button1_Click(object sender, EventArgs e) { listaBox.Items.Clear(); HashSet <string> veiculos = new HashSet <string>()//hashSet nao aceita adicionar um item que ja tem na lista { "Carro", "Moto", "Avião", "Helicoptero", "Barco" }; MessageBox.Show(veiculos.ElementAt(2)); MessageBox.Show(veiculos.First()); MessageBox.Show(veiculos.Last()); //if (veiculos.Add("Cavalo")) //{ // MessageBox.Show("Item adicionado"); //} //else //{ // MessageBox.Show("Item não adicionado"); //} foreach (string item in veiculos) { listaBox.Items.Add(item); } }
public override void Run() { var N = int.Parse(Console.ReadLine()); HashSet <string> records = new HashSet <string>(); int cnt = 0; for (int i = 0; i < N; i++) { var w = Console.ReadLine(); if (records.Any() && (records.Contains(w) || records.Last().Last() != w.First())) { if (i % 2 == 0) { Console.WriteLine("LOSE"); } else { Console.WriteLine("WIN"); } return; } records.Add(w); } Console.WriteLine("DRAW"); }
public static void solveMaze(HashSet <Point> maze) { var S = new Stack <Point>(); var discovered = maze.ToDictionary(vertex => vertex, vertex => false); var cameFrom = new Dictionary <Point, Point>(); var root = maze.First(); var goal = maze.Last(); S.Push(root); Program.setBothColours(ConsoleColor.Red); while (S.Count > 0) { var V = S.Pop(); if (V.Equals(goal)) { Program.findPath(goal, root, cameFrom); break; } if (!discovered[V]) { discovered[V] = true; foreach (var w in Program.returnAdjacentVertices(maze, V).Where(w => !discovered[w])) { S.Push(w); cameFrom[w] = V; } } } }
public void HashSetExtensions_Last_ThrowsExceptionIfHashSetIsEmpty() { var set = new HashSet <Int32>(); Assert.That(() => set.Last(), Throws.TypeOf <InvalidOperationException>()); }
// Write a unit test that checks that returned question list length is the same as static number in class public List <PlayerQuestionAnswerDM> GenerateQuestionList(PlayerDM player) { var result = new List <PlayerQuestionAnswerDM>(); var list = new HashSet <int>(); var questions = _db.Questions.ToList(); var rand = new Random(); for (int i = 0; i < QUESTIONS_PER_PLAYER; i++) { var value = rand.Next(0, questions.Count() - 1); var diff = 0; while (!list.Add(value)) { var temp = Math.Abs(diff) + 1; diff = diff > 0 ? temp * -1 : temp; value += diff; if (value < 0) { value += questions.Count(); } if (value >= questions.Count()) { value %= questions.Count(); } } result.Add(new PlayerQuestionAnswerDM() { Player = player, Question = questions[list.Last()], PQA_IsAnswered = false }); } return(result); }
private static void LoadImages() { HashSet<string> images = new HashSet<string>(); using (WebClient client = new WebClient()) { //string str = client.DownloadString(@"http://www.skovboernehave.dk/Album/20131119Jager/index.html"); //File.WriteAllText(@"C:\Private\GitHub\Projects\ImageLoader\Image Loader Test\20131119Jager.txt", str); string str = File.ReadAllText(@"C:\Private\GitHub\Projects\ImageLoader\Image Loader Test\20131119Jager.txt"); HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(str); var first_page = doc.DocumentNode.SelectNodes("//a[@href]") .Select(l => l.Attributes["href"].Value) .Where(a => a.Contains("slides")) .First(); var page = Path.GetFileName(first_page); Console.WriteLine("Parsing page " + page); while (ParsePage(page, images)) { page = Path.ChangeExtension(images.Last(), ".html"); Console.WriteLine("Parsing page " + page); } } Console.WriteLine("Downloading images"); foreach (var image in images) DownloadImage(image); Console.WriteLine("Images found " + images.Count); }
/// <summary> /// 이동 /// </summary> /// <param name="_targetPosition"></param> public override void Move(Vector3Int _targetPosition) { m_CurrentTile.m_Unit = null; HashSet <Vector3Int> path = Map.instance.m_TileSetPathFind.GetPath(); HashSet <Vector3Int> converted = ConvertPathCoordinates(path); m_Animator.SetBool("move", true); // 이동할 방향 설정하고 왼쪽으로 이동할 경우, 스프라이트를 뒤집는다. Vector3Int firstPoint = converted.First(); Vector3Int lastPoint = converted.Last(); if (lastPoint.x - firstPoint.x < 0) { m_Property.m_LookDirection = eDirection.West; } else { m_Property.m_LookDirection = eDirection.East; } // 실제로 목표 지점까지 이동 MoveByPathTile(converted, _targetPosition); }
/// <summary> /// Calculates the shortest possible secret passcode using the keylog information in the text file /// </summary> static void P079() { var passcodes = Functions.getPermutations(new List <int>() { 0, 1, 2, 3, 6, 7, 8, 9 }, 8); var keylog = new HashSet <string>(); foreach (string s in File.ReadAllText(@"...\...\Resources\p079_keylog.txt").Split('\n')) { keylog.Add(s); } foreach (var i in passcodes) { foreach (var j in keylog) { if (i.ToList().IndexOf((int)Char.GetNumericValue(j[0])) < i.ToList().IndexOf((int)Char.GetNumericValue(j[1])) && i.ToList().IndexOf((int)Char.GetNumericValue(j[1])) < i.ToList().IndexOf((int)Char.GetNumericValue(j[2]))) { if (j == keylog.Last()) { Console.WriteLine(String.Join("", i)); } } else { break; } } } }
public void Method() { Console.WriteLine("find the next number after 40755 that is a triangle, pentagonal, and hexagonal number"); const double limit = 1000000; HashSet <double> triangles = new HashSet <double>(); HashSet <double> pentagonals = new HashSet <double>(); HashSet <double> hexagonals = new HashSet <double>(); for (double i = 0; i < limit; i++) { triangles.Add(i * (i + 1) / 2); pentagonals.Add(i * (3 * i - 1) / 2); hexagonals.Add(i * (2 * i - 1)); } HashSet <double> all = new HashSet <double>(); foreach (double i in triangles) { if (!pentagonals.Contains(i) || !hexagonals.Contains(i)) { continue; } all.Add(i); } Console.WriteLine($"There are {all.Count} numbers that are shared between the first {limit} triangular, pentagonal, and hexagonal numbers"); Console.WriteLine($"The next T/P/H number after 40755 = {all.Last()}"); }
public static List <Telefoane> FindElementsMove(HashSet <Telefoane> _HashSet) { string Model; List <Telefoane> _ListNewLocal = new List <Telefoane>(); Console.WriteLine("Introduceti modelul pentru cautare! : "); Model = Console.ReadLine(); foreach (var element in _HashSet) { if (element.Modelul == Model) { Console.WriteLine("A fost gasit un element!"); Telefoane.WriteTelefoane(element); Console.ReadKey(); _ListNewLocal.Add(element); _HashSet.Remove(element); return(_ListNewLocal); } else if (element.Equals(_HashSet.Last()) && element.Modelul != Model && _ListNewLocal.Count == 0) { Console.WriteLine("Nu a fost gasit"); Console.ReadKey(); } } return(_ListNewLocal); }
private static void OnTimedEvent(Object source, ElapsedEventArgs e) { if (indices.Count > 0) { logger.EscribirLog("Llevamos vamos por el chr " + indices.Last().chrEnd + ":" + String.Format("{0:n0}", indices.Last().PosicionEnd) + " en " + stopWatch.Elapsed, Logger.Tipo.Informativo, true); } }
private HashSet <AuditItem> GetAuditData() { HashSet <AuditItem> guardAuditItems = new HashSet <AuditItem>(); Regex guardNoRegex = new Regex(@"\d+"); int startSleepMin = 0; foreach (var item in GetSortedRawEvents(ReadList())) { switch (GetAction(item.Event)) { case RawActionEnum.Begin: var guardNoAudit = int.Parse(guardNoRegex.Match(item.Event).Value); if (!guardAuditItems.Any(x => x.GuardNo == guardNoAudit && x.Date == item.Date.Date)) { guardAuditItems.Add(new AuditItem(guardNoAudit, item.Date.Date)); } break; case RawActionEnum.Sleep: startSleepMin = item.Date.Minute; break; case RawActionEnum.WakeUp: for (int i = startSleepMin; i < item.Date.Minute; i++) { guardAuditItems.Last().States[i] = 1; } break; } } return(guardAuditItems); }
private static Type GetResultTypeFromInterface(Type type, Type genericType, int argumentPosition) { if (!genericType.IsInterface) { throw new ArgumentException($"The type must be an interface, but is {type.Name}."); } var toCheck = new HashSet <Type>(); foreach (var item in type.GetInterfaces()) { toCheck.Add(item); } while (toCheck.Any()) { var item = toCheck.Last(); if (item.IsGenericType) { if (item.GetGenericTypeDefinition() == genericType) { return(item.GetGenericArguments()[argumentPosition]); } } foreach (var inter in item.GetInterfaces()) { toCheck.Add(inter); } toCheck.Remove(item); } return(null); }
public bool ValidateConnection(HashSet <short> char_blob_idx_set) { // check if it has a weak link int idx1 = char_blob_idx_set.First(); // the set has exactly two elements int idx2 = char_blob_idx_set.Last(); // check regular stuff if (FindLabelForTheBiggestCharBlob(char_blob_idx_set) != 0) { //if (weak_link_set.Count > 0) // now I know the real connecting nodes //{ // // the second confirmation check // if (weak_link_set.Contains(idx1 + ":" + idx2) // && weak_link_set.Contains(idx2 + ":" + idx1)) // { // connected_char_blob_idx_set_list[idx1].Remove(idx2); // connected_char_blob_idx_set_list[idx2].Remove(idx1); // return false; // } //} connected_char_blob_idx_set_list[idx1].Add(idx2); connected_char_blob_idx_set_list[idx2].Add(idx1); return(true); } else { return(false); } }
public IList<int> GrayCode(int n) { //List<int> re = new List<int>(); HashSet<int> re = new HashSet<int>(); re.Add(0); while(true) { var val = re.Last(); int i = 0; while(i < n) { int nextval = val ^ (1 << i); if (!re.Contains(nextval)) { re.Add(nextval); break; } i++; } if (i == n) break; } return re.ToList(); }
static void Main() { #if DEBUG Console.SetIn(new System.IO.StreamReader("../../input.txt")); #endif var nodes = new HashSet<int>(); var edges = new List<KeyValuePair<Tuple<int, int>, int>>(); foreach (int i in Enumerable.Range(0, int.Parse(Console.ReadLine()))) { int[] parts = Console.ReadLine().Split().Select(int.Parse).ToArray(); nodes.Add(parts[0]); nodes.Add(parts[1]); edges.Add(new KeyValuePair<Tuple<int, int>, int>( new Tuple<int, int>(parts[0], parts[1]), parts[2] )); } var trees = new HashSet<HashSet<int>>(); foreach (int node in nodes) { var tree = new HashSet<int>(); tree.Add(node); trees.Add(tree); } int result = 0; foreach (var currentEdge in edges.OrderBy(kvp => kvp.Value)) { var tree1 = trees.First(tree => tree.Contains(currentEdge.Key.Item1)); var tree2 = trees.Last(tree => tree.Contains(currentEdge.Key.Item2)); if (tree1 == tree2) continue; tree1.UnionWith(tree2); trees.Remove(tree2); result += currentEdge.Value; if (trees.Count == 1) break; } Console.WriteLine(result); }
public int FindLabelForTheBiggestCharBlob(HashSet<short> char_blob_idx_set) { int idx1 = char_blob_idx_set.First(); // char_blob_idx_set has exactly two elements int idx2 = char_blob_idx_set.Last(); // check if any of the connecting CC has two neighbors already if ((connected_char_blob_idx_set_list[idx1].Count == 2 && !connected_char_blob_idx_set_list[idx1].Contains(idx2)) || (connected_char_blob_idx_set_list[idx2].Count == 2 && !connected_char_blob_idx_set_list[idx2].Contains(idx1))) return 0; if (BreakingAngle(idx1, idx2)) return 0; // check for size ratio int size2 = (int)(char_blob_idx_max_size_table[idx2]); int size1 = (int)(char_blob_idx_max_size_table[idx1]); if ((double)size1 / (double)size2 > size_ratio || (double)size2 / (double)size1 > size_ratio) return 0; else { if (size1 > size2) return idx1 + 1; else return idx2 + 1; } }
public void HashSetExtensions_Last_ReturnsLastItemInHashSet() { var set = new HashSet<Int32>() { 1, 2, 3 }; var result = set.Last(); TheResultingValue(result).ShouldBe(3); }
/// <summary> /// Replacements finder for the document /// </summary> /// <param name="doc">NormaCSAPI.Document object</param> /// <returns>Replacements list</returns> private HashSet<NormaCSAPI.Document> findReplacements(NormaCSAPI.Document doc) { HashSet<NormaCSAPI.Document> replacers = new HashSet<NormaCSAPI.Document>(); NormaCSAPI.Replacements replacedBy = doc.ReplacedBy; while (replacedBy.Count > 0) { foreach (NormaCSAPI.Replacement repl in replacedBy) replacers.Add(repl.get_Document()); replacedBy = replacers.Last().ReplacedBy; } return replacers; }
static void Main(string[] args) { Console.Out.WriteLine(); Console.Out.WriteLine("Specify a file with a list of invoice IDs to archive, one on each line."); Console.Out.WriteLine(); Console.Out.Write("Filename: "); string filenameIn = Console.In.ReadLine(); string outLocation; Console.Out.Write("Output to desktop? (Y if yes)"); if (Console.ReadKey().KeyChar == 'y') { outLocation = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), string.Concat(Path.GetFileNameWithoutExtension(filenameIn), "_out.txt")); } else { outLocation = string.Concat(Path.GetFileNameWithoutExtension(filenameIn), "_out.txt"); } Console.WriteLine(); string[] invoiceIdsStrArr = File.ReadAllLines(filenameIn); HashSet<string> invoiceIds = new HashSet<string>(); foreach (var item in invoiceIdsStrArr) { invoiceIds.Add(item); } using (FileStream fs = File.OpenWrite(string.Concat(outLocation))) { StreamWriter sw = new StreamWriter(fs); List<string> illegalRows = new List<string>(); try { int rowCount = 0; string last = invoiceIds.Last(); foreach (var item in invoiceIds) { if (!Regex.IsMatch(item, "[0-9]{8}")) { illegalRows.Add(item); continue; } if (item != last) { if (rowCount < 499) { sw.Write(string.Concat(item, ",")); rowCount++; } else { sw.Write(item); sw.WriteLine(); rowCount = 0; } } else if (rowCount < 500) { sw.Write(item); } else if (rowCount == 500) { sw.WriteLine(); sw.Write(item); } } } catch (IOException e) { Console.Out.WriteLine("IO exception:"); Console.Out.WriteLine(e.Message); } finally { if (!illegalRows.Any<string>()) { Console.WriteLine(illegalRows.Count().ToString(), " rows contain bad invoice IDs:"); foreach (var item in illegalRows) { Console.WriteLine(" ", item); } Console.WriteLine("Press a key"); Console.ReadKey(); } sw.Close(); sw.Dispose(); } } }
public bool ValidateConnection(HashSet<short> char_blob_idx_set) { // check if it has a weak link int idx1 = char_blob_idx_set.First(); // the set has exactly two elements int idx2 = char_blob_idx_set.Last(); // check regular stuff if (FindLabelForTheBiggestCharBlob(char_blob_idx_set) != 0) { //if (weak_link_set.Count > 0) // now I know the real connecting nodes //{ // // the second confirmation check // if (weak_link_set.Contains(idx1 + ":" + idx2) // && weak_link_set.Contains(idx2 + ":" + idx1)) // { // connected_char_blob_idx_set_list[idx1].Remove(idx2); // connected_char_blob_idx_set_list[idx2].Remove(idx1); // return false; // } //} connected_char_blob_idx_set_list[idx1].Add(idx2); connected_char_blob_idx_set_list[idx2].Add(idx1); return true; } else return false; }
/// <summary> /// Check for conflicts of versions in the referenced assemblies of the workflow. /// </summary> /// <param name="referencedTypes">Referenced types in the project</param> /// <param name="referencedAssemblies">Referenced assemblies in the project</param> /// <param name="projectName">Name of the main type (workflow) of the project</param> private static void CheckForConflictingVersions(HashSet<Type> referencedTypes, HashSet<Assembly> referencedAssemblies, string projectName) { // XamlBuildTask cannot support two different versions of the same dependency in XAML. // As a workaround, we raise an error here if the workflow contains activities/variables/etc. // from different versions of the same assembly. var conflicts = referencedAssemblies.GroupBy(asm => asm.GetName().Name).Where(grp => grp.Count() > 1).ToList(); if (conflicts.Any()) { var conflict = conflicts.First(); Assembly asm1 = referencedAssemblies.First(item => item.GetName().Name == conflict.Key); Assembly asm2 = referencedAssemblies.Last(item => item.GetName().Name == conflict.Key); var type1 = referencedTypes.First(item => item.Assembly.GetName().Name == asm1.GetName().Name && item.Assembly.GetName().Version == asm1.GetName().Version); var type2 = referencedTypes.First(item => item.Assembly.GetName().Name == asm2.GetName().Name && item.Assembly.GetName().Version == asm2.GetName().Version); string message = string.Format(CompileMessages.MultipleVersionsUsed, type1.Name, asm1.FullName, type2.Name, asm2.FullName, conflict.Key); throw new CompileException(message); } // Check if the workflow contains a previous version of itself var referencesToItself = new List<Assembly>( from assemblies in referencedAssemblies where assemblies.GetName().Name == projectName select assemblies); if (referencesToItself.Any()) { string message = string.Format(CompileMessages.PreviousSelfVersion, referencesToItself.First().GetName().Name, referencesToItself.First().GetName().FullName); throw new CompileException(message); } }
private bool FindAnnonces(WebBrowser webbrowser3) { HashSet<string> anonnces = new HashSet<string>(); string[] str_separators = new string[] { ":::", " ;;;" }; string[] strs_in = { "" }; if (one_site["InAnnonce"] != null && one_site["InAnnonce"].ToString().Length > 7) strs_in = one_site["InAnnonce"].ToString().Split(str_separators, StringSplitOptions.RemoveEmptyEntries); string[] strs_ex = { "" }; if (one_site["ExAnnonce"] != null && one_site["ExAnnonce"].ToString().Length > 7) strs_ex = one_site["ExAnnonce"].ToString().Split(str_separators, StringSplitOptions.RemoveEmptyEntries); foreach (HtmlElement link in webbrowser3.Document.All) { bool findannonce = true; IHTMLElement4 ilink4 = (IHTMLElement4)link.DomElement; if (linksTrouve.Contains(link.OuterHtml)) continue; for (int tmp1 = 0; tmp1 < (strs_in.Length / 2); tmp1++) { if (ilink4.getAttributeNode(strs_in[tmp1 * 2]) != null && ilink4.getAttributeNode(strs_in[tmp1 * 2]).nodeValue != null) { if (!ilink4.getAttributeNode(strs_in[tmp1 * 2]).nodeValue.ToString().Contains(strs_in[tmp1 * 2 + 1])) { findannonce = false; break; } } else if (!link.GetAttribute(strs_in[tmp1 * 2]).Contains(strs_in[tmp1 * 2 + 1])) { findannonce = false; break; } } for (int tmp2 = 0; tmp2 < (strs_ex.Length / 2); tmp2++) { if (ilink4.getAttributeNode(strs_ex[tmp2 * 2]) != null && ilink4.getAttributeNode(strs_ex[tmp2 * 2]).nodeValue != null) { if (ilink4.getAttributeNode(strs_ex[tmp2 * 2]).nodeValue.ToString().Contains(strs_ex[tmp2 * 2 + 1]) || !findannonce) { findannonce = false; break; } } else if (link.GetAttribute(strs_ex[tmp2 * 2]).Contains(strs_ex[tmp2 * 2 + 1]) || !findannonce) { findannonce = false; break; } } if (findannonce) { anonnces.Add(link.OuterHtml); linksTrouve.Add(link.OuterHtml); //Console.WriteLine("npage : " + npage.ToString() + " nb linksTrouve :" + linksTrouve.Count.ToString() + " link.OuterHtml :" + link.OuterHtml); if (fullpage) { try { infindannonce = true; this.webBrowser1.DocumentCompleted -= new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(this.webBrowser1_DocumentCompleted); this.webBrowser1.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(this.webBrowser1_DocumentCompleted_2); try { //link.Focus(); //SendKeys.Send("ENTER"); bool bonclik = false; for (int tmp1 = 0; tmp1 < (strs_in.Length / 2); tmp1++) { if (strs_in[tmp1 * 2].IndexOf("onclick", StringComparison.OrdinalIgnoreCase) >= 0) { bonclik = true; link.RaiseEvent("onclick"); break; } } if (!bonclik) link.InvokeMember("click"); } catch (Exception exc) { Console.WriteLine("findAnnonce click " + exc.Message); } } catch (Exception exc) { MessageBox.Show("findAnnonce fullpage " + exc.Message); } break; } else { //SQL.Connect(); int site_id = Convert.ToInt16(SQL.Get(@"select id from sites where ENTREPRISE = '" + one_site["ENTREPRISE"].ToString().Replace("'", "''") + "'")); /* DataRow row = dtAnnIn.NewRow(); row["id"] = site_id; row["Entreprise"] = one_site["ENTREPRISE"].ToString(); row["link"] = link.GetAttribute("href"); row["link_hash"] = CreateMD5Hash(link.GetAttribute("href")); dtAnnIn.Rows.Add(row); */ //dtAnnIn.Rows.Add(site_id, one_site["ENTREPRISE"].ToString(),one_site["ENTREPRISE"].ToString(), link.GetAttribute("href"), CreateMD5Hash(link.GetAttribute("href"))); if (extract && site_id != 0) { if (SQL.Requet(@"insert into liens (id_site, nom, link, link_hash) values (" + site_id + ", '" + one_site["ENTREPRISE"].ToString().Replace("'", "''") + "', '" + link.GetAttribute("href") + "','" + CreateMD5Hash(link.GetAttribute("href")) + "')")) { anonnces.Add(link.GetAttribute("href")); allanonnces.Add(anonnces.Last()); //dtAnnIn.Rows.Add(dr); } else { insertfail++; if (insertfail > 5 && one_site["MAXPAGES"].ToString() == "99") webClose(); } } //SQL.Disconnect(); } } } //nbannonces += anonnces.Count(); if (anonnces.Count() > 0) return true; else return false; }
private static bool Delaunay2DInsertPoints(List<Vertex> vertices, Adjacency adjacency) { // Insert points HashSet<int> toCheck = new HashSet<int>(); for (int i = 0; i < vertices.Count; i++) { // Insert Vi Vertex Vi = vertices[i]; bool skip = false; for (int j = 0; j < adjacency.vertices.Count; j++) { if ((Vi - adjacency.vertices[j]).Length() <= COINCIDENT_POINTS_DISTANCE_EPSILON) { // the point has already been inserted. Skip it skip = true; break; } } if (skip) { continue; } if (OnDelaunayInsertPoint != null) OnDelaunayInsertPoint(adjacency, Vi); int tri = adjacency.PointInTriangle(Vi); if (tri < 0) { Debug.Assert(false); return false; } // check whether the point lies exactly on one edge of the triangle int edgeIdx = adjacency.PointInTriangleEdge(Vi, tri); if (edgeIdx >= 0) { // split the edge by Vi int[] result; adjacency.SplitEdge(edgeIdx, Vi, out result); for (int j = 0; j < 4; j++) { if (result[j] >= 0) { toCheck.Add(result[j]); } } } else { // split the triangle in 3 int[] result; adjacency.SplitTriangle(tri, Vi, out result); for (int j = 0; j < 3; j++) { toCheck.Add(result[j]); } } while (toCheck.Count > 0) { int t = toCheck.Last<int>(); toCheck.Remove(t); Adjacency.Triangle triangle = adjacency.triangles[t]; if (!triangle.valid) { continue; } if (OnDelaunayTriangleCheck != null) OnDelaunayTriangleCheck(adjacency, t); // check Delaunay condition for (int e = 0; e < 3; e++) { if (!adjacency.triangles[t].valid) continue; int adjacentIdx = adjacency.AdjacentTriangle(t, e); if (adjacentIdx < 0) { continue; } int globalEdgeIndex = Math.Abs(triangle.edges[e]) - 1; Adjacency.Triangle adjacent = adjacency.triangles[adjacentIdx]; if (!adjacent.valid) { continue; } Debug.Assert(adjacent.valid); int edgeFromAdjacent = adjacent.LocalEdgeIndex(globalEdgeIndex); Debug.Assert(edgeFromAdjacent >= 0); int v = adjacency.VertexOutOfTriEdge(adjacentIdx, edgeFromAdjacent); Debug.Assert(v >= 0); Debug.Assert(!triangle.Contains(v)); if (triangle.InsideCircumcircle(adjacency.vertices[v], adjacency.vertices) > INSIDE_CIRCUMCIRCLE_EPSILON) { int[] result; if (adjacency.FlipTriangles(t, adjacentIdx, out result)) { toCheck.Add(result[0]); toCheck.Add(result[1]); //break; } } } } if (OnDelaunayStep != null) OnDelaunayStep(adjacency); } return true; }
private GraphicsMode GetDefaultGraphicsMode() { int[] aaLevels = new int[] { 0, 2, 4, 6, 8, 16 }; HashSet<GraphicsMode> availGraphicsModes = new HashSet<GraphicsMode>(new GraphicsModeComparer()); foreach (int samplecount in aaLevels) { GraphicsMode mode = new GraphicsMode(32, 24, 0, samplecount, new OpenTK.Graphics.ColorFormat(0), 2, false); if (!availGraphicsModes.Contains(mode)) availGraphicsModes.Add(mode); } int highestAALevel = MathF.RoundToInt(MathF.Log(MathF.Max(availGraphicsModes.Max(m => m.Samples), 1.0f), 2.0f)); int targetAALevel = highestAALevel; if (DualityApp.AppData.MultisampleBackBuffer) { switch (DualityApp.UserData.AntialiasingQuality) { case AAQuality.High: targetAALevel = highestAALevel; break; case AAQuality.Medium: targetAALevel = highestAALevel / 2; break; case AAQuality.Low: targetAALevel = highestAALevel / 4; break; case AAQuality.Off: targetAALevel = 0; break; } } else { targetAALevel = 0; } int targetSampleCount = MathF.RoundToInt(MathF.Pow(2.0f, targetAALevel)); return availGraphicsModes.LastOrDefault(m => m.Samples <= targetSampleCount) ?? availGraphicsModes.Last(); }
static bool getMaxNumPrimes(string s) { int minPrime = 0; int tempCount = 1; int maxCount = 1; for (int j = 0; j < s.Length; j++) { for (int k = j + 1; k < s.Length; k++) { for (int x = k + 1; x < s.Length; x++) { tempCount = 1; HashSet<int> primes = new HashSet<int>(); for (int i = 0; i < 10; i++) { char iLetter = i.ToString()[0]; StringBuilder buffString = new StringBuilder(s); buffString[j] = iLetter; buffString[k] = iLetter; buffString[x] = iLetter; int newInt = int.Parse(buffString.ToString()); if (newInt < isPrime.Length && isPrime[newInt]) { if (primes.Count > 0 && primes.Last().ToString().Length != buffString.ToString().Length) { primes.Clear(); } // isPrime[newInt] = false; primes.Add(newInt); } if (tempCount > maxCount) { maxCount = tempCount; minPrime = int.Parse(s.ToString()); } if (primes.Count == 8) { foreach (int num in primes) { Console.WriteLine(num); } return true; } } } } } return false; }
public static void FixConsistency(Client client, List<ConfigState.ShardServer> shardServers, Int64 tableID, string startKey, string endKey) { if (shardServers.Count <= 1) return; var keyDiffs = new HashSet<string>(); var serverKeys = new string[shardServers.Count][]; var i = 0; while (true) { System.Console.WriteLine("StartKey: " + startKey); serverKeys = ConfigStateHelpers.ParallelFetchTableKeysHTTP(shardServers, tableID, startKey, endKey, true); for (i = 1; i < serverKeys.Length; i++) { if (serverKeys[0].Length > 0 && serverKeys[i].Length > 1 && serverKeys[0].First().CompareTo(serverKeys[i].Last()) < 0) { foreach (var diff in serverKeys[i].Except(serverKeys[0])) keyDiffs.Add(diff); } if (serverKeys[0].Length > 1 && serverKeys[i].Length > 0 && serverKeys[i].First().CompareTo(serverKeys[0].Last()) < 0) { foreach (var diff in serverKeys[0].Except(serverKeys[i])) keyDiffs.Add(diff); } } if (keyDiffs.Count != 0) { FixDiffs(client, shardServers, tableID, keyDiffs.ToList()); startKey = keyDiffs.Last(); keyDiffs = new HashSet<string>(); continue; } if (serverKeys[0].Length <= 1) break; startKey = serverKeys[0][serverKeys[0].Length - 1]; } }
public void HashSetExtensions_Last_ThrowsExceptionIfHashSetIsEmpty() { var set = new HashSet<Int32>(); set.Last(); }
public void StreamDocCalled_PageSize_NotIgnored() { ValidateConstantValues(); int[] streamDocsRequestCounter = {0}; using (var ravenServer = GetNewServer()) { ravenServer.Server.RequestManager.BeforeRequest += (sender, args) => { if (args.Controller.InnerRequest.RequestUri.PathAndQuery.Contains("/streams/docs?")) { Interlocked.Increment(ref streamDocsRequestCounter[0]); } }; using (var documentStore = NewRemoteDocumentStore(ravenDbServer: ravenServer)) { AddDummyDocuments(documentStore); var fetchedDocumentsCollection1 = new HashSet<DummyDocument>(); using (var docStream = documentStore.DatabaseCommands.StreamDocs(start: 0,pageSize: TestPageSize)) { while (docStream.MoveNext()) { Assert.NotNull(docStream.Current); fetchedDocumentsCollection1.Add(docStream.Current.Deserialize<DummyDocument>(new DocumentConvention())); } Assert.Equal(TestPageSize, fetchedDocumentsCollection1.Count); Assert.Equal(1, streamDocsRequestCounter[0]); } var fetchedDocumentsCollection2 = new HashSet<DummyDocument>(); using (var docStream = documentStore.DatabaseCommands.StreamDocs(start: TestPageSize - 1, pageSize: TestPageSize)) { while (docStream.MoveNext()) { Assert.NotNull(docStream.Current); fetchedDocumentsCollection2.Add(docStream.Current.Deserialize<DummyDocument>(new DocumentConvention())); } Assert.Equal(TestPageSize, fetchedDocumentsCollection2.Count); } Assert.Equal(1, fetchedDocumentsCollection1.Intersect(fetchedDocumentsCollection2).Count()); Assert.True(fetchedDocumentsCollection1.Last().Equals(fetchedDocumentsCollection2.First())); } } }
public void HashSetExtensions_Last_ThrowsExceptionIfHashSetIsEmpty() { var set = new HashSet<Int32>(); Assert.That(() => set.Last(), Throws.TypeOf<InvalidOperationException>()); }
public int GetNesting(MethodDeclarationSyntax method) { var set = new HashSet<int>() { 0 }; var nodes = method.DescendantNodes().OfType<StatementSyntax>().Where(IsEnlargersNesting).ToList(); int c = 0; for (var j = 0; j < nodes.Count; ) { var list = new List<Tuple<SyntaxNode, int>> { Tuple.Create((SyntaxNode)nodes[j], 1) }; for (var i = 0; i < list.Count; ++i) { //Console.WriteLine("Родитель = {0} , {1} - {2} !!!!!!!!!", list[i].Item1, list[i].Item2, list[i].Item1.GetType()); var li = list[i].Item1.ChildNodes().OfType<SyntaxNode>(); set.Add(list[i].Item2); foreach (var statementSyntax in li) { //Console.Write("Ребёнок = "); //Console.WriteLine(statementSyntax); if (IsEnlargersNesting(statementSyntax)) { list.Add(Tuple.Create(statementSyntax, list[i].Item2 + 1)); } else { if (!(statementSyntax is LiteralExpressionSyntax || statementSyntax is ExpressionStatementSyntax || statementSyntax is IdentifierNameSyntax || statementSyntax is BinaryExpressionSyntax)) list.Add(Tuple.Create(statementSyntax, list[i].Item2)); } //Console.WriteLine("++++++++++++"); } //list.AddRange(li.Where(ii => !(ii is ExpressionStatementSyntax || ii is LiteralExpressionSyntax))); // Console.WriteLine("###########"); } var count = list.Count(ii => IsEnlargersNesting(ii.Item1)); // Console.WriteLine(count.ToString()); //Console.WriteLine("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n\n"); // j++; j += count; } return set.Last(); }
private static void Main(string[] args) { SyntaxTree tree = SyntaxTree.ParseText( @"using System; class Sample { public class A { override protected void SendBuffer(LoggingEvent[] events) { if (m_reconnectOnError && (m_dbConnection == null || m_dbConnection.State != ConnectionState.Open)) { InitializeDatabaseConnection(); InitializeDatabaseCommand(); } else if (x == 0) { TestDelegate myDel = n => { string s = n; Console.WriteLine(s); }; } try{ } catch(Exception ex){ } } } } }"); var root = (CompilationUnitSyntax) tree.GetRoot(); var firstMember = root.Members[0]; //var helloWorldDeclaration = (NamespaceDeclarationSyntax)firstMember; //var programDeclaration = (ClassDeclarationSyntax)helloWorldDeclaration.Members[0]; // var mainDeclaration = (MethodDeclarationSyntax)programDeclaration.Members[1]; var methods = root.DescendantNodes() .OfType<MethodDeclarationSyntax>(); var helloWorldString = root.DescendantNodes() .OfType<StatementSyntax>(); int count = 0; foreach (var method in methods) { var set = new HashSet<int>() {0}; var nodes = method.DescendantNodes().OfType<StatementSyntax>().Where(IsEnlargersNesting).ToList(); for(var j = 0; j < nodes.Count;) { var list = new List<Tuple<SyntaxNode, int>>(); list.Add(Tuple.Create((SyntaxNode)nodes[j], 1)); for (var i = 0; i < list.Count; ++i) { Console.WriteLine("Родитель = {0} , {1} - {2} !!!!!!!!!", list[i].Item1, list[i].Item2, list[i].Item1.GetType()); var li = list[i].Item1.ChildNodes().OfType<SyntaxNode>(); set.Add(list[i].Item2); foreach (var statementSyntax in li) { Console.Write("Ребёнок = "); Console.WriteLine(statementSyntax); if (IsEnlargersNesting(statementSyntax)) { list.Add(Tuple.Create(statementSyntax, list[i].Item2 + 1)); } else { if (!(statementSyntax is LiteralExpressionSyntax || statementSyntax is ExpressionStatementSyntax || statementSyntax is IdentifierNameSyntax || statementSyntax is BinaryExpressionSyntax)) list.Add(Tuple.Create(statementSyntax, list[i].Item2)); } Console.WriteLine("++++++++++++"); } //list.AddRange(li.Where(ii => !(ii is ExpressionStatementSyntax || ii is LiteralExpressionSyntax))); Console.WriteLine("###########"); } count = list.Where(ii => IsEnlargersNesting(ii.Item1)).Count(); Console.WriteLine(count.ToString()); Console.WriteLine("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n\n"); // j++; j += count; } Console.WriteLine("NESTING == {0}", set.Last()); } }
//节点开始新建一个匿名组 public void JoinAnonyGroup(object o) { GroupArgs args = (GroupArgs)o; int k = args.k; int L = args.l; int random = args.random; if (random > 0)//需要从匿名组中随机选择一个节点 { int nodeId = PrivacyReader.rootReader.SelectOneFromGroup(); PrivacyReader reader = (PrivacyReader)Node.getNode(nodeId, NodeType.READER); if(reader !=null) reader.JoinAnonyGroup(new GroupArgs(k, L, 0)); return; } if (!this.anonGroups.ks.Contains(k)) this.anonGroups.ks.Add(k); //this.AnonGroups.group.Add(k, new HashSet<int>()); //native 方法 if (global.method == 1) { this.lastesth = 2; Console.WriteLine("{0:F4} [JOIN_ANON_GROUP] {1}{2} start to join group k={3}, l={4}. [IN]", scheduler.currentTime, this.type, this.Id, k, this.lastesth); SendNativeGroupRequest(this.lastesth, this.lastesth, k, this.Id); string groupident = this.Id + "-" + k + "-" + this.lastesth; this.pendingNativeGroupResponses.Add(groupident, new Dictionary<int, NativeGroupResponseEntry>()); this.cachedRecvRequest.Add(groupident, scheduler.currentTime); Event.AddEvent(new Event(scheduler.currentTime + 0.3f, EventType.CHK_NATGROUP, this, groupident)); return; } //是否建立了匿名树 int groupTreeRoot = -1; foreach (KeyValuePair<string, AnonyTreeEntry> pair in this.CachedTreeEntries) { AnonyTreeEntry subTreeInfo = pair.Value; if (subTreeInfo.rootId > 0 && subTreeInfo.status != SubNodeStatus.OUTSIDE) { groupTreeRoot = subTreeInfo.rootId; break; } } //如果建立了匿名树,则不是第一次,或者是native2的方法,那也先获取频繁子集 HashSet<int> freqSet = new HashSet<int>(); //if (groupRoot >= 0 || global.nativeMethod == 2) //第二种方法, native2 if (global.method == 2) { Console.WriteLine("{0:F4} [JOIN_ANON_GROUP] {1}{2} start to join group k={3}, l={4}. [IN]", scheduler.currentTime, this.type, this.Id, k, this.lastesth); //比较现有匿名组中出现次数最多的节点 Dictionary<int, int> h = new Dictionary<int, int>(); foreach (KeyValuePair<int, HashSet<int>> pair in this.anonGroups.groups) { int k1 = pair.Key; HashSet<int> g = pair.Value; foreach (int n in g) { if (!h.ContainsKey(n)) h.Add(n, 0); h[n]++; } } int[] sortedh = Utility.SortDictionary(h); int num = 0; for (int i = 0; i < sortedh.Length; i++) { //选出最大的若干项 //为了增加概率,增加1.5倍候选节点 if (num >= k) break; //如果出现的次数小于阈值,则忽略 if (h[sortedh[i]] < 1) continue; //查找该节点是否已在其他k-匿名组中了 if (groupTreeRoot >= 0) { bool found = false; foreach (int c in this.CachedTreeEntries[groupTreeRoot + ""].subtree.Keys) { string key1 = c + "-" + k; if (!this.anonGroups.subUnavailAnonyNodes.ContainsKey(key1)) { found = true; break; } } if (found == true) continue; } freqSet.Add(sortedh[i]); num++; } if (freqSet.Count > 0 && !freqSet.Contains(this.Id)) { freqSet.Remove(freqSet.Last()); freqSet.Add(this.Id); } if (freqSet.Count == 0) { this.lastesth = 2; SendNativeGroupRequest(this.lastesth, this.lastesth, k, this.Id); string groupident = this.Id + "-" + k + "-" + this.lastesth; this.pendingNativeGroupResponses.Add(groupident, new Dictionary<int, NativeGroupResponseEntry>()); this.cachedRecvRequest.Add(groupident, scheduler.currentTime); Event.AddEvent(new Event(scheduler.currentTime + 0.3f, EventType.CHK_NATGROUP, this, groupident)); return; } else { this.cachedCandidateNodes.Add(k, new HashSet<int>()); foreach (int x in freqSet) SendSetLongNativeGroupRequest(this.Id, k, 0, x); string groupident = this.Id + "-" + k; this.pendingNativeGroupResponses.Add(groupident, new Dictionary<int, NativeGroupResponseEntry>()); this.cachedRecvRequest.Add(groupident, scheduler.currentTime); Event.AddEvent(new Event(scheduler.currentTime + global.native2WaitingTimeout, EventType.CHK_NATGROUP1, this, groupident)); } return; } //否则,为我们改进的方法 int rootId = this.Id; string key = rootId+""; if (groupTreeRoot < 0)//本节点未在匿名树中,新建树,再建组 { Console.WriteLine("{0:F4} [JOIN_ANON_GROUP] {1}{2} start to join group k={3}, l={4}. [IN]", scheduler.currentTime, this.type, this.Id, k, L); int hops = 0; int m = -1; //if (!this.CachedRegionEntries.ContainsKey(key)) this.CachedRegionEntries.Add(key, new AnonyRegionEntry(rootId, hops)); //if(!this.CachedDistEntries.ContainsKey(this.Id)) this.CachedDistEntries.Add(this.Id, new DistanceEntry(this.Id, 0, scheduler.currentTime)); //init double includedAngle = global.includedAngle; SendTreeGroupRequest(rootId,m, L, 0, 0, 0); //if(!this.CachedTreeEntries.ContainsKey(key)) this.CachedTreeEntries.Add(key, new AnonyTreeEntry(rootId, null, m)); this.CachedTreeEntries[key].status = SubNodeStatus.NORMAL; } else { Console.WriteLine("{0:F4} [JOIN_ANON_GROUP] {1}{2} start to join group k={3}, l={4}. [OUT]", scheduler.currentTime, this.type, this.Id, k, L); //之前建立过匿名组,在原有的匿名树的基础上新建一个 ProcessNewGroupRequest(groupTreeRoot, k, this.Id, L, 0, 0, 0, null); //ProcessNewGroup(groupRoot, k, k, this.id, id); } }