public static IDictionary<IPAddress, IPAddress> ExtractContiguousRanges(IEnumerable<IPAddress> IPs)
        {
            Logger logger = LogManager.GetCurrentClassLogger();
            IDictionary<IPAddress, IPAddress> ranges = new Dictionary<IPAddress, IPAddress>();
            HashSet<uint> IPNumbers = new HashSet<uint>();
            foreach (IPAddress address in IPs)
            {
                IPNumbers.Add(address.ToUint());
            }
            IEnumerable<IEnumerable<uint>> IPNumberGroups = IPNumbers.Distinct()
                .GroupBy(num => NumberUtils.Range(num, uint.MaxValue - num + 1)
                .TakeWhile(IPNumbers.Contains).Last())
                .Where(seq => seq.Count() >= 3)
                .Select(seq => seq.OrderBy(num => num));

            foreach (IEnumerable<uint> group in IPNumberGroups)
            {
                uint low = group.Min();
                uint high = group.Max();
                IPAddress rangeLow = parseUint(low);
                IPAddress rangeHigh = parseUint(high);
                logger.Debug("Selected for exclusion: " + rangeLow + " to " + rangeHigh);
                ranges.Add(rangeLow, rangeHigh);
            }
            return ranges;
        }
Example #2
0
        protected override int[] GetSkipFrames(AVSValue args, ScriptEnvironment env)
        {
            Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
            string filename = args[1].AsString();
            HashSet<int> f = new HashSet<int>();
            int lineNo = 0;
            string line = "xx";
            try
            {
                using (StreamReader sr = new StreamReader(filename))
                {
                    while ((line = sr.ReadLine()) != null)
                    {
                        lineNo++;
                        f.Add(int.Parse(line));
                    }
                }
            }
            catch (Exception ex)
            {
                env.ThrowError(string.Format("line: {0:4} | {1} {2}\n", lineNo, ex.Message, line));
            }

            return f.Distinct().OrderBy(key => key).ToArray<int>();
        }
        public BenchmarkSettings(TestMode testMode, RunMode runMode, int numberOfIterations, int runTimeMilliseconds,
            IEnumerable<GcBenchmarkSetting> gcBenchmarks,
            IEnumerable<MemoryBenchmarkSetting> memoryBenchmarks,
            IEnumerable<CounterBenchmarkSetting> counterBenchmarks, string description, string skip)
        {
            TestMode = testMode;
            RunMode = runMode;
            NumberOfIterations = numberOfIterations;
            RunTime = TimeSpan.FromMilliseconds(runTimeMilliseconds == 0 ? DefaultRuntimeMilliseconds : runTimeMilliseconds);
            Description = description;
            Skip = skip;

            // Strip out any duplicates here
            // TODO: is it better to move that responsibility outside of the BenchmarkSettings class?

            GcBenchmarks = new HashSet<GcBenchmarkSetting>(gcBenchmarks).ToList();
            MemoryBenchmarks = new HashSet<MemoryBenchmarkSetting>(memoryBenchmarks).ToList();
            CounterBenchmarks = new HashSet<CounterBenchmarkSetting>(counterBenchmarks).ToList();

            DistinctGcBenchmarks =
                GcBenchmarks.Distinct(GcBenchmarkSetting.GcBenchmarkDistinctComparer.Instance).ToList();

            DistinctCounterBenchmarks =
                CounterBenchmarks.Distinct(CounterBenchmarkSetting.CounterBenchmarkDistinctComparer.Instance).ToList();

            DistinctMemoryBenchmarks =
                MemoryBenchmarks.Distinct(MemoryBenchmarkSetting.MemoryBenchmarkDistinctComparer.Instance).ToList();
        }
        public static IEnumerable<string> CollectTabs(this EditorResult editorResult) {
            var set = new HashSet<ShapePosition>();

            foreach (var editor in editorResult.Editors) {
                var positionText = editor.Metadata.Position;

                if (!String.IsNullOrWhiteSpace(positionText)) {
                    var position = ShapePosition.Parse(positionText);
                    set.Add(position);
                }
            }
            return set.Distinct(new ShapePositionDistinctComparer()).OrderBy(x => x.Position).Select(x => x.Name);
        }
Example #5
0
        private static IEnumerable<string> PossibleWords(string word, int level = 1)
        {
            var words = new HashSet<string>();
            Matcher(word, _list).ToList().ForEach(w => words.Add(w));

            if (level < 3)
            {
                var toAdd = new List<string>();
                foreach (var item in words)
                    toAdd.AddRange(PossibleWords(item, level + 1));

                toAdd.ForEach(w => words.Add(w));
            }

            return words.Distinct();
        }
Example #6
0
 public void Search()
 {
     /* 2. All items search method.
      * This method simply returns all the items in the collection, without duplicates.
      */
     HashSet<AbstractItem> results = new HashSet<AbstractItem>(coll);
     if (onSearchComplete != null)
     {
         onSearchComplete(results.Distinct().ToList());
     }
 }
Example #7
0
 // Set of search methods, each for a different ocassion.
 public void Search(List<List<string>> listOfSearchValues, List<SearchFunction> searchFunctions)
 {
     /* 1. Complex search method.
      * This method receives a list of lists of strings and a list of SearchFunction (delegate)
      * The reason for the use of list of lists is to keep generality and keep the code short.
      * Regarding complexity, this theoretically can reach O(n^2), but is most unlikely.
      * The method runs the appropriate search function for the appropriate set of values.
      * The use of the hashset is to handle duplicate entries in collection.
      */
     HashSet<AbstractItem> results = null;
     for (int i = 0; i < searchFunctions.Count; i++)
     {
         List<AbstractItem> funcResults = new List<AbstractItem>();
         foreach (string value in listOfSearchValues[i])
         {
             List<AbstractItem> lastSearchResults = results != null ? results.ToList() : new List<AbstractItem>();
             funcResults.AddRange(searchFunctions[i](value, lastSearchResults));
         }
         results = new HashSet<AbstractItem>();
         results.UnionWith(funcResults);
     }
     if (onSearchComplete != null)
     {
         onSearchComplete(results.Distinct().ToList());
     }
 }
Example #8
0
        public void When_running_the_order_is_random()
        {
            var last = "";
            var runs = new HashSet<string>();

            var ex = Experiment
                .On(() => last = "control")
                .Try(() => last = "try");

            for (int i = 0; i < 1000; i++)
            {
                ex.Run();
                runs.Add(last);
            }

            runs.Distinct().Count().ShouldBeGreaterThan(1);
        }
Example #9
0
        public static string DisplayResults()
        {
            string scope = HostingEnvironment.MapPath("~");

            Regex regex = new Regex(@"([a-fA-F0-9]{64})");
            string connectionString = "Provider=Search.CollatorDSO;Extended Properties=\"Application=Windows\"";
            HashSet<string> imgExtensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
                {
                    ".jpg", ".jpeg", ".jpe", ".gif", ".png", ".tiff", ".tif", ".svg", ".svgz", ".xbm", ".bmp", ".ico"
                };

            OleDbConnection connection = new OleDbConnection(connectionString);

            string query = @"SELECT TOP 100 System.ItemFolderPathDisplay FROM SystemIndex WHERE scope ='file:" + scope + "' AND System.FileName = 'index.htm' ORDER BY System.DateModified DESC";
            OleDbCommand command = new OleDbCommand(query, connection);
            connection.Open();
            HashSet<string> result = new HashSet<string>();
            OleDbDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                string searchString = reader.GetString(0);
                Match match = regex.Match(searchString);
                if (match.Success)
                {
                    result.Add(match.Value);
                }
            }
            connection.Close();
            if (result.Count > 0)
            {
                string searchHTML = "";
                var uniqueResults = result.Distinct();
                foreach (string s in uniqueResults)
                {
                    var signature = "";
                    var img = "";
                    //var file = "";
                    var msg = "";
                    var date = "";
                    var blockchain = "";
                    var profiles = "";
                    var doc = new HtmlAgilityPack.HtmlDocument();
                    try
                    {
                        doc.Load(scope + s + "\\index.htm");
                    }
                    catch { break; }


                    try
                    {
                        img = doc.GetElementbyId("img0").InnerText;
                        searchHTML = searchHTML + "<div class=\"item\"><div class=\"content\"><table><tr><th rowspan=\"6\"><a href=\"" + s + "/index.htm\"><img src=\"" + s + "/" + img + "\" /></a></th><th></th></tr>";
                    }
                    catch { searchHTML = searchHTML + "<div class=\"item\"><div class=\"content\"><table><tr><th rowspan=\"6\"></th><th></th></tr>"; }
                    try { signature = doc.GetElementbyId("signature").InnerText; }
                    catch { }
                    try { blockchain = doc.GetElementbyId("blockchain").InnerText; }
                    catch { }
                    searchHTML = searchHTML + "<tr><td>" + blockchain + " - " + signature + "</td></tr>";
                    try { date = doc.GetElementbyId("block-date").InnerText; }
                    catch { }
                    try { msg = doc.GetElementbyId("msg1").InnerText; }
                    catch { }
                    try { profiles = doc.GetElementbyId("profiles").InnerHtml; }
                    catch { }
                    searchHTML = searchHTML + "<tr><td><a href=\"" + s + "/index.htm\">" + msg.PadRight(50).Substring(0, 49) + "</a></td></tr>";

                    if (msg.Length > 500)
                    { searchHTML = searchHTML + "<tr><td>" + date + " : " + msg.Substring(0, 499) + "...</td></tr>"; }
                    else { searchHTML = searchHTML + "<tr><td>" + date + " : " + msg + "</td></tr>"; }

                    if (profiles.Length > 0)
                    {
                        searchHTML = searchHTML + "<tr><td>" + profiles + "</td></tr>";
                    }
                    searchHTML = searchHTML + "<tr><td><a href=\"" + s + "/index.htm\"><font size=\"1\">" + s + "</font></a></td></tr></table></div></div>";

                }
                return searchHTML;

            }
            else
            { return "<div class=\"item\"><div class=\"content\">Nothing found</div></div>"; }
        
        }
            public void UpdateNotifications(Domain.Entity.Mill.Pipe pipeSavingState)
            {
                if (isProperlyCreated)
                {
                    //* What can happen at Save Pipe: (NRO - non required inspection operation)
                    //* - pipe is new and have no previous state (to update: NROs from current size type(new))
                    if (initialPipeSizeTypeId == Guid.Empty)
                    {
                        AddPipe(pipeSavingState.PipeTestResult);
                        ProcessOperationForPipeSizeType(pipeSavingState.Type.Id);
                    }

                    //* - pipe is existing and pipe size type changed (to update: NROs from previous size type(remove), NROs from current size type(new))
                    else if (pipeSavingState.Type == null || initialPipeSizeTypeId != pipeSavingState.Type.Id)
                    {
                        RemoveAndUpdatePipe(initialSelectivePipeTestResult);
                        AddAndUpdate(pipeSavingState.PipeTestResult);

                    }

                    //* - pipe is existing and operations were edited (to update: NROs from current size type(track changes))
                    else if (initialPipeSizeTypeId == pipeSavingState.Type.Id)
                    {
                        HashSet<TestResultInfo> savingState = new HashSet<TestResultInfo>(GetTestResultInfoListFromPipeTestResultList(pipeSavingState.PipeTestResult));
                        HashSet<TestResultInfo> initialState = new HashSet<TestResultInfo>(initialSelectiveInfo);

                        savingState.ExceptWith(initialState);

                        foreach (TestResultInfo result in savingState.Distinct())
                        {
                            manager.cache.RemovePipeAmount(result.OperationId);
                            manager.cache.AddPipeAmount(result.OperationId);

                            UpdateNotification(result.OperationId);
                        }
                    }

                    //* - pipe deactivation (to update: NRO (remove))
                    else if (!pipeSavingState.IsActive)
                    {
                        RemoveAndUpdatePipe(pipeSavingState.PipeTestResult);
                    }
                }

                NotificationService.Instance.NotifyInterested();
                SavePipeState(pipeSavingState);
            }
Example #11
0
 public HashSet<Timetable> getUniques(HashSet<Timetable> tables)
 {
     return new HashSet<Timetable>(tables.Distinct(new TimetableBookedTimeEquality()).Select(t => t.RemoveAllFreeTime()).OrderBy(x => x.ToString()));
 }
Example #12
0
        protected virtual int[] GetSkipFrames(AVSValue args, ScriptEnvironment env)
        {
            int n = args[1].ArraySize();
            HashSet<int> f = new HashSet<int>();
            int max = vi.num_frames;
            for (int i = 0; i < n; ++i)
            {
                int skipFrm = args[1][i].AsInt();
                if (vi.num_frames > skipFrm)
                {
                    f.Add(skipFrm);
                }
            }

            return f.Distinct().OrderBy(key => key).ToArray<int>();
        }
Example #13
0
        public string GetBinaryPath()
        {
            if (null == assemblies)
               {
               throw new Exception("No mapping assembly specified");
               }
               HashSet<string> paths = new HashSet<string>();
               foreach (MSBuild.BuildItem it in assemblies)
               {
               paths.Add(Path.GetDirectoryName(it.Include).ToLower());
               }
               if (paths.Count == 0)
               {
               throw new Exception("No mapping assembly specified");
               }

               if (paths.Count > 1)
               {
               throw new Exception("Mapping assemblies does not share the same directory.");
               }

               return paths.Distinct().First();
        }
Example #14
0
        public ActionResult Ship(String id, Guid shipID, Guid newID, Guid? parentID, String portName)
        {
            try
            {
                HoloTableController._lockMap[id] = HoloTableController._lockMap.GetValue(id, new Object());

                lock (HoloTableController._lockMap[id])
                {
                    var model = new DetailModel(id, shipID);

                    // Parents being equipped
                    var parentItems = model.Player.Items.Where(i => i.ID == parentID).ToArray();

                    // Ports being equipped
                    var newShipPorts = model.Player.Ships.Where(s => s.ID == shipID).Where(s => s.Ports != null).Where(s => s.Ports.Items != null).SelectMany(s => s.Ports.Items).Where(p => p.PortName == portName).ToArray();
                    var newItemPorts = model.Player.Items.Where(i => i.ID == parentID).Where(i => i.Ports != null).Where(i => i.Ports.Items != null).SelectMany(i => i.Ports.Items).Where(p => p.PortName == portName).ToArray();
                    var newPorts = newShipPorts.Concat(newItemPorts).ToArray();

                    // Item IDs being replaced
                    var oldItemIDs = new HashSet<Guid>(newPorts.Select(p => p.ItemID));

                    // Items being replaced
                    var oldItems = model.Player.Items.Where(i => oldItemIDs.Contains(i.ID)).ToArray();
                    var oldIDs = new HashSet<Guid>(oldItems.SelectMany(i => this.FlattenIDs(model, i)));

                    // Inventory being moved
                    var oldHangarInventory = model.Player.Inventory.Items.Where(i => oldIDs.Contains(i.ID));
                    var oldShipInventory = model.Player.Ships.Where(s => s.Inventory != null).Where(s => s.Inventory.Items != null).SelectMany(s => s.Inventory.Items.Where(i => oldIDs.Contains(i.ID)));
                    var oldInventory = oldShipInventory.Union(oldHangarInventory).ToArray();

                    // Items being equipped
                    var newItems = model.Player.Items.Where(i => i.ID == newID).ToArray();
                    var newIDs = new HashSet<Guid>(newItems.SelectMany(i => this.FlattenIDs(model, i)));

                    // Inventory being moved
                    var newHangarInventory = model.Player.Inventory.Items.Where(i => newIDs.Contains(i.ID));
                    var newShipInventory = model.Player.Ships.Where(s => s.Inventory != null).Where(s => s.Inventory.Items != null).SelectMany(s => s.Inventory.Items.Where(i => newIDs.Contains(i.ID)));
                    var newInventory = newShipInventory.Union(newHangarInventory).ToArray();

                    // Old ports
                    var oldShipPorts = model.Player.Ships.Where(s => s.Ports != null).Where(s => s.Ports.Items != null).SelectMany(s => s.Ports.Items).Where(p => p.ItemID == newID).Where(p => p.ItemID != Guid.Empty).ToArray();
                    var oldItemPorts = model.Player.Items.Where(i => i.Ports != null).Where(i => i.Ports.Items != null).SelectMany(i => i.Ports.Items).Where(p => p.ItemID == newID).Where(p => p.ItemID != Guid.Empty).ToArray();
                    var oldPorts = oldItemPorts.Concat(oldShipPorts).ToArray();

                    // Configure Ship inventory
                    foreach (var ship in model.Player.Ships.Where(s => s.Inventory != null).Where(s => s.Inventory.Items != null))
                    {
                        ship.Inventory.Items = ship.Inventory.Items.Where(i => !oldIDs.Contains(i.ID)).Where(i => !newIDs.Contains(i.ID)).ToArray();

                        if (ship.ID == shipID)
                        {
                            ship.Inventory.Items = ship.Inventory.Items.Union(newInventory).ToArray();
                        }
                    }

                    // Configure Player inventory
                    var shipItemIDs = new HashSet<Guid>(model.Player.Ships.Where(s => s.Inventory != null).Where(s => s.Inventory.Items != null).SelectMany(s => s.Inventory.Items).Select(i => i.ID));

                    model.Player.Inventory = new Inventory.Inventory
                    {
                        Items = model.Player.Items.Where(i => !shipItemIDs.Contains(i.ID)).Select(i => new Inventory.InventoryItem { ID = i.ID }).ToArray()
                    };

                    var oldPort = oldPorts.SingleOrDefault();

                    if (oldPort != null)
                    {
                        oldPort.ItemID = oldItemIDs.Distinct().SingleOrDefault();
                    }

                    var newPort = newPorts.SingleOrDefault();

                    if (newPort != null)
                    {
                        newPort.ItemID = newID;
                    }

                    foreach (var item in newItems)
                    {
                        if (item.Ports.Items == null) continue;
                        var gameItem = model.GameData_ItemMap[newID];
                        if (gameItem.Ports.Items == null) continue;
                        var itemPorts = item.Ports.Items.ToList();
                        var missingPorts = gameItem.Ports.Items.Where(p => !item.Ports.Items.Select(i => i.PortName).Distinct().Contains(p.Name));

                        foreach (var port in missingPorts)
                        {
                            itemPorts.Add(new Port
                            {
                                ItemID = Guid.Empty,
                                PortName = port.Name,
                            });
                        }

                        item.Ports.Items = itemPorts.ToArray();
                    }

                    // TODO: Validate parts - can't because CIG breaks the rules

                    // Set current ship (Optional)
                    model.Player.VehicleID = shipID;

                    model.Save();

                    ViewBag.ID = id;

                    return View(model);
                }
            }
            catch (FileNotFoundException)
            {
                this.Response.StatusCode = 500;
                this.Response.TrySkipIisCustomErrors = true;

                return new JsonResult
                {
                    Data = new
                    {
                        Reason = "Hangar Removed"
                    }
                };
            }
            catch (Exception ex)
            {
                Elmah.ErrorLog.GetDefault(System.Web.HttpContext.Current).Log(new Elmah.Error(ex));

                this.Response.StatusCode = 500;
                this.Response.TrySkipIisCustomErrors = true;

                return new JsonResult
                {
                    Data = new
                    {
                        Reason = "System Error"
                    }
                };
            }
        }
Example #15
0
        static void Main(string[] args)
        {
            List<List<int>> possibles = new List<List<int>>();
            for (int a = 1000; a < 10000; a++)
            {
                if (IsValid(a))
                {
                    int[] digits = a.Digits().ToArray();
                    int startA = GetCycleStart(a);
                    if (startA < 1000) continue;
                    for (int b = startA; b < startA + 100; b++)
                    {
                        if (IsValid(b))
                        {
                            int startB = GetCycleStart(b);
                            if (startB < 1000) continue;
                            for (int c = startB; c < startB + 100; c++)
                            {
                                if (IsValid(c))
                                {
                                    int startC = GetCycleStart(c);
                                    if (startC < 1000) continue;
                                    for (int d = startC; d < startC + 100; d++)
                                    {
                                        if (IsValid(d))
                                        {
                                            int startD = GetCycleStart(d);
                                            if (startD < 1000) continue;
                                            for (int e = startD; e < startD + 100; e++)
                                            {
                                                if (IsValid(e))
                                                {
                                                    int startE = GetCycleStart(e);
                                                    if (startE < 1000) continue;
                                                    for (int k = startE; k < startE + 100; k++)
                                                    {
                                                        List<int> sequence = new List<int>();
                                                        if (IsValid(k))
                                                        {
                                                            sequence.Add(a);
                                                            sequence.Add(b);
                                                            sequence.Add(c);
                                                            sequence.Add(d);
                                                            sequence.Add(e);
                                                            sequence.Add(k);
                                                            int[] kDigits = k.Digits().ToArray();
                                                            if (digits[0] == kDigits[2] && digits[1] == kDigits[3])
                                                            {

                                                                if (IsValidSequence(sequence))
                                                                {
                                                                    possibles.Add(sequence);
                                                                    /*
                                                                    Console.WriteLine(a + "  " + b + "  " + c + "  " + d + "  " + e + "  " + k);
                                                                    Console.WriteLine(a + b + c + d + e + k);*/
                                                                }

                                                                //Console.WriteLine(a + "  " + b + "  " + c + "  " + d + "  " + e + "  " + k);
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                        }
                    }
                }
            }
            HashSet<int> sums = new HashSet<int>();
            foreach (var sequence in possibles)
            {
                if (!sums.Contains(sequence.Sum()))
                {
                    sums.Add(sequence.Sum());
                    Console.WriteLine(sequence.ToStringPretty());
                }

                //Console.WriteLine(sequence.ToStringPretty());
                /*
                if (IsOrdered(sequence))
                {
                    Console.WriteLine(sequence.ToStringPretty());
                    Console.WriteLine(sequence.Sum());
                }*/
            }
            //The answer is the 4th index in this, don't ask me why
            Console.WriteLine(sums.Distinct().ToStringPretty());
            Console.ReadKey();
        }
Example #16
0
 static IEnumerable<string> filesFromDpl(string dplUrl, Langs[] langs) {
   var dplPath = pathFromUrl(dplUrl);
   var cfg = Newtonsoft.Json.JsonConvert.DeserializeObject<deplyConfig>(File.ReadAllText(dplPath));
   HashSet<string> res = new HashSet<string>();
   var relDir = dplUrl.Substring(0, dplUrl.LastIndexOf('/'));
   Func<string, string> fullUrl = url => (url.StartsWith("/") ? url : relDir + "/" + url).ToLower();
   if (dplUrl.IndexOf("{loc}") > 0) {
     foreach (var inc in cfg.includes) foreach (var lng in langs) res.Add(string.Format(fullUrl(inc), swLang(lng)));
   } else {
     //** includes x excludes x regExs
     if (cfg.includes != null)
       foreach (var inc in cfg.includes) {
         if (inc.StartsWith("@")) {
           var regEx = inc.Substring(1);
           var urls = Directory.GetFiles(commonDir, "*.*", SearchOption.AllDirectories).Select(f => urlFromPath(f)).ToArray();
           var rx = new Regex(regEx, RegexOptions.IgnoreCase);
           foreach (var url in urls) if (rx.IsMatch(url)) res.Add(url);
         } else if (inc.EndsWith(".json")) res.UnionWith(filesFromDpl(fullUrl(inc), langs));
         else if (inc.StartsWith("!")) res.Remove(fullUrl(inc));
         else res.Add(fullUrl(inc));
       }
   }
   return res.Distinct();
 }