示例#1
0
文件: After.cs 项目: mvladk/dp2012
        public static void Run()
        {
            const int k_Len = 10;
            int[] array = new int[k_Len];
            Random rand = new Random();
            for (int i = 0; i < k_Len; i++)
            {
                array[i] = rand.Next(10);
                Console.Write(array[i].ToString() + " ");
            }

            Console.WriteLine();

            Sorter sorter = new Sorter(new ComparerUp());

            sorter.Sort(array);
            for (int u = 0; u < k_Len; u++)
            {
                Console.Write(array[u].ToString() + " ");
            }
            Console.WriteLine();

            sorter.Comparer = new ComparerDown();
            for (int u = 0; u < k_Len; u++)
            {
                Console.Write(array[u].ToString() + " ");
            }
            Console.WriteLine();
        }
示例#2
0
文件: SortImage2.cs 项目: hsorby/gdcm
    public static int Main(string[] args)
    {
        Sorter sorter = new Sorter();
        sorter.SetSortFunction( mysort );

        return 0;
    }
        private void button1_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;

            memoResults.Text = "";

            string[] tokens = memoDataToSort.Text.Split(',');
            int[] arr;
            try
            {
                arr = Array.ConvertAll<string, int>(tokens, int.Parse);
                var sorter = new Sorter();
                var results = sorter.GetSortResults(arr);

                foreach (var item in results)
                {
                    memoResults.Text += item.Name + ": " + item.SortTimeInMs + " ms\r\n";
                }

                // Bind the chart to the list.
                chartSortTime.DataSource = results;

                if (chartSortTime.Series.Count == 0)
                    CreateSeries();
            }
            catch (Exception)
            {
                memoResults.Text = "Array is in invalid form.\r\nPlease use format: <number><,>\r\nFor example: 3,2,1";
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }
示例#4
0
        internal void PrintTables(LogStatsParams statsParams, Totals totals)
        {
            foreach (CompareMethod method in statsParams.Options.Keys)
            {
                int tot = statsParams.Options[method];

                foreach (Total table in totals.GetTotals())
                {
                    Sorter sorter = new Sorter(table.GetValues());

                    ArrayList values = sorter.SortBy(method);
                    values.Reverse(); // maximum to minimum

                    if (tot < int.MaxValue)
                    {
                        if (values.Count > tot)
                            values = values.GetRange(0, tot);
                    }

                    Console.WriteLine();
                    Console.WriteLine("{0} {1}", table.GetName(), method.ToString());
                    PrintTable(values);
                }
            }
        }
示例#5
0
 public static Sorter Load()
 {
     Sorter srt = new Sorter();
     File.ReadLines(STUDENTS_FILE, Encoding.UTF8).Select(toStudent).ToList().ForEach(
         std => { if (std != null) srt.stds.Add(std); }
     );
     return srt;
 }
示例#6
0
 public static Sorter Load()
 {
     Sorter srt = new Sorter();
     WithLines(STUDENTS_FILE).Select(toStudent).ToList().ForEach(
         std => { if (std.HasValue) srt.stds.Add(std.Value); }
     );
     return srt;
 }
示例#7
0
 static void Main(string[] args)
 {
     Sorter aSorter = new Sorter();
     aSorter=displayMenu(aSorter);
     String typeOfObj = aSorter.GetType().ToString();
     if (typeOfObj == "Sorter_k112119.Sorter")
         Console.WriteLine("Wrong Choice");
     else
     {
         aSorter.performSort();
         Console.WriteLine(aSorter.getComplexity());
     }
 }
示例#8
0
        public void Should_yield_sorted_array()
        {
            Sorter<double> ss = new Sorter<double>();
            double[] sequence = new [] { 3.0, 7.0, 1.0, 6.0, 4.0, 5.0, 2.0 };

            ss.Sort(sequence);

            sequence[0].Should().Be.EqualTo(1.0);
            sequence[1].Should().Be.EqualTo(2.0);
            sequence[2].Should().Be.EqualTo(3.0);
            sequence[3].Should().Be.EqualTo(4.0);
            sequence[6].Should().Be.EqualTo(7.0);
        }
示例#9
0
        public void Should_yield_sorted_array()
        {
            Sorter<int> ss = new Sorter<int>();
            int[] sequence = new [] { 3, 7, 1, 6, 4, 5, 2 };

            ss.Sort(sequence);

            sequence[0].Should().Be.EqualTo(1);
            sequence[1].Should().Be.EqualTo(2);
            sequence[2].Should().Be.EqualTo(3);
            sequence[3].Should().Be.EqualTo(4);
            sequence[6].Should().Be.EqualTo(7);
        }
        static void Main(string[] args)
        {
            int[] arr = { 6, 5, 4, 3, 2, 1 };

            var sorter = new Sorter();

            var sortResults = sorter.GetSortResults(arr);
            foreach (var result in sortResults)
            {
                Console.WriteLine("{0}: {1} ms", result.Name, result.SortTimeInMs);
            }

            Console.ReadLine();
        }
		/// <summary>
		/// Apply the current sorting again.
		/// </summary>
		public void RefreshSort()
		{
			// Set to sort. This also immediately sorts.
			ListViewItemSorter = new Sorter(
				this,
				Math.Max( 0, lastSortColumnIndex ),
				sortAscending );

			// Enough sorted.
			ListViewItemSorter = null;

			ShowHeaderIcon(
				lastSortColumnIndex,
				sortAscending ? SortOrder.Ascending : SortOrder.Descending );
		}
示例#12
0
 static void Main(string[] args)
 {
     Random r = new Random();
     int[] m = new int[10];
     for (int i = 0; i < m.Length; i++)
     {
         m[i] = r.Next(100);
     }
     Sorter<int> a = new Sorter<int>();
     a.Sort(m, IntCompare);
     for (int i = 0; i < m.Length; i++)
     {
         Console.WriteLine(m[i]);
     }
     Console.ReadLine();
 }
示例#13
0
        public void TestSort1()
        {
            var input = new List<FileInfo>
            {
                new FileInfo(@"TestData\Sort\Input\sort1a.txt"),
                new FileInfo(@"TestData\Sort\Input\sort1b.txt")
            };
            var output = new FileInfo(@"TestData\Sort\Output\sort1.txt");
            var outputFiles = new List<IOutputFile<byte[]>>
            {
                new LegacyOutputFile
                {
                    Output =  output
                }
            };
            var sorter = new Sorter<byte[]>
            {
                InputFiles = input,
                OutputFiles = outputFiles,
                RecordAccessorFactory = new SeparatorAccessorFactory { Separator = CrLf },
                HeaderSize = 1,
                Comparer = new ComparerChain<byte[]>
                {
                    Comparers = new List<IComparer<byte[]>>
                    {
                        new StringComparer { Start = 0, Length = 25 },
                        new DefaultComparer<decimal>
                        {
                            Ascending = false,
                            Accessor = new ZonedAccessor { Start = 25, Length = 10 }
                        }
                    }
                },
                Filter = new DecimalFilter
                {
                    Left = new ZonedAccessor { Start = 35, Length = 1 },
                    Right = new ConstantAccessor<decimal> { Constant = 5 },
                    Operator = ComparisonOperator.Ne
                }
            };
            var expected = new FileInfo(@"TestData\Sort\Expected\sort1.txt");

            sorter.Sort();

            Assert.IsTrue(TestHelper.TestHelper.ContentEquals(expected.OpenRead(), output.OpenRead()));
        }
示例#14
0
        public static void Run()
        {
            const int k_Len = 10;
            int[] numbers = new int[10];
            Random rand = new Random();
            for (int i = 0; i < k_Len; i++)
            {
                numbers[i] = rand.Next(10);
                Console.Write(numbers[i].ToString() + " ");
            }

            Console.WriteLine();

            /// use a delegate to a method as the strategy:
            Sorter sorter = new Sorter(new Func<int, int, bool>(biggerFirstMethod));

            /// we can also dump the explicit creation of the delegate object:
            sorter = new Sorter(biggerFirstMethod);

            ///or, use anonymous method:
            sorter = new Sorter(
                delegate(int num1, int num2)
                {
                    return num1 < num2;
                });

            ///or, use LAMBDA expressions (shorter syntax):
            sorter = new Sorter((num1, num2) => num1 > num2);

            sorter.Sort(numbers);
            foreach(int num in numbers)
            {
                Console.Write(num.ToString() + ",");
            }
            Console.WriteLine();

            /// Lets sort down:
            sorter.ComparerMethod = ((num1, num2) => num1 < num2);
            sorter.Sort(numbers);
            foreach (int num in numbers)
            {
                Console.Write(num.ToString() + ",");
            }
            Console.WriteLine();
        }
示例#15
0
 /// <summary>
 /// Compares sorter, retuns the one which is faster.
 /// Tests on random data.
 /// </summary>
 private static Sorter Compare(Sorter a, Sorter b)
 {
     List<Item> data = GetData().ToList();
     List<Item> data1 = new List<Item>(data);
     DateTime startA = DateTime.Now;
     a.Invoke(data, 0, data.Count - 1);
     DateTime stopA = DateTime.Now;
     DateTime startB = DateTime.Now;
     b.Invoke(data1, 0, data.Count - 1);
     DateTime stopB = DateTime.Now;
     TimeSpan spanA = stopA - startA;
     TimeSpan spanB = stopB - startB;
     if (spanA < spanB)
     {
         return a;
     }
     return b;
 }
        public void Throw_Invalid_Operation_Exception_If_Input_Has_Circle()
        {
            var sorter = new Sorter();

            Assert.Throws <InvalidOperationException>(() => sorter.SortCard(new[]
            {
                new Card
                {
                    Start  = "A",
                    Finish = "B"
                },
                new Card
                {
                    Start  = "B",
                    Finish = "C"
                }, new Card
                {
                    Start  = "C",
                    Finish = "A"
                },
            }).ToArray());
        }
        internal async Task <List <RelatedEntityCollection> > GetRelatedEntitiesAsync(IEnumerable <TInterface> entities, IEnumerable <RelatedEntityForeignAttribute> attributes, IEnumerable <ExpandPath> expandPaths)
        {
            if (entities == null || !entities.Any())
            {
                return(null);
            }
            var list = new List <RelatedEntityCollection>();

            foreach (RelatedEntityForeignAttribute a in attributes)
            {
                var expandPath = expandPaths.FirstOrDefault(ep => a.RelatedEntity == ep.Entity);
                RelatedEntityCollection relatedEntities = await GetRelatedEntities(entities, a.RelatedEntity, a.EntityKeyProperty, a.ForeignKeyProperty, expandPath?.Parenthesis); // Cast is intentional

                var sortDetails = new SortDetails(typeof(TEntity).Name, a.RelatedEntity, RelatedEntity.Type.OneToMany)
                {
                    EntityToRelatedEntityProperty = a.ForeignKeyProperty
                };
                var collections = Sorter.Sort(entities, relatedEntities, sortDetails);
                list.AddRange(collections);
            }
            return(list);
        }
示例#18
0
        public virtual JsonResult Gets(CommonAjaxArgs args)
        {
            EntityResponseDto res = new EntityResponseDto();

            try
            {
                var predicate = ExpressionUtil.GetSearchExpression(typeof(T), args.Query.Searchs) as Expression <Func <T, bool> >;

                var page = args.Query.Page;

                if (page.PageSize <= 0)
                {
                    page.PageSize = 500;
                }

                Sorter sort = new Sorter()
                {
                    SortField = "ID", SortOrder = System.Data.SqlClient.SortOrder.Descending
                };
                if (args.Query.Sorters != null && args.Query.Sorters.Count > 0)
                {
                    sort = args.Query.Sorters.First();
                }
                string[] includes = args.Query.IncludeEntityPaths == null ? null : args.Query.IncludeEntityPaths.ToArray();
                res.Count   = Repository.GetQueryExp <T>(predicate, includes).Count();
                res.Entitys = Repository.QueryPage <T>(predicate, new Pagination()
                {
                    page = page.PageIndex, rows = page.PageSize, sidx = sort.SortField, sord = sort.SortOrder == System.Data.SqlClient.SortOrder.Ascending ? "asc" : "desc"
                }, includes);
                res.Success = true;
            }
            catch (Exception ex)
            {
                res.Success = false;
                res.Message = ex.Message;
                Log.Error(ex);
            }
            return(MyJson(res));
        }
示例#19
0
    static void Main()
    {
        try {
            Console.WriteLine("Enter name of file to be sorted");
            String path = basepath + Console.ReadLine();

            stopWatch.Start();
            LogTime("Starting splitting and sorting");
            List <String> filenames = Sorter.SplitAndSort(path, basepath);

            LogTime("Merge started");
            Sorter.MergeSortedFiles(filenames, path + "1");


            LogTime("File merge completed");
            Console.ReadLine();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }
示例#20
0
        public void TestSortSortedMoreItems()
        {
            int[] data = new[] { 100500, 100600, 1, 1999, 200500, 1000, 100, 5 };
            Array.Sort(data);

            var d = new Deq <int>();

            foreach (var v in data)
            {
                d.PushBack(v);
            }

            d = Sorter.Sort2(d);

            Assert.IsFalse(d.Empty);
            Assert.AreEqual(data.Length, d.Count);

            foreach (var v in data)
            {
                Assert.AreEqual(v, d.PopFront());
            }
        }
示例#21
0
        public Parser Refresh(Sorter sorter)
        {
            IntPtr ptr;

            this.CheckClosed();
            if (this.requests.Count == 0)
            {
                return(Parser.Empty);
            }
            IList <Request> items = this.Prepare(this.GetRequests());

            if (sorter != null)
            {
                sorter(items);
            }
            if (items.Count == 0)
            {
                return(Parser.Empty);
            }
            Meta.Message[] sources = new Meta.Message[items.Count];
            string[]       filters = new string[items.Count];
            for (int i = 0; i < items.Count; i++)
            {
                Request request = items[i];
                if (request != null)
                {
                    sources[i] = request.Source;
                    filters[i] = request.Filter;
                    this.CheckResult(this.module.MTEAddTable(this.handle, request.Handle, i));
                }
            }
            this.CheckResult(this.module.MTERefresh(this.handle, out ptr));
            int structure = Marshal.ReadInt32(ptr);

            ptr += Marshal.SizeOf(structure);
            byte[] destination = new byte[structure];
            Marshal.Copy(ptr, destination, 0, structure);
            return(MultiParser.Acquire(this, sources, filters, destination));
        }
示例#22
0
        static long[] AnaliseSorterReverted(Sorter sorter)
        {
            long[] times = new long[10];
            int    count = 0;

            for (int i = 100; i <= 1000; i += 100)
            {
                int[] randomArray = GetInvertedArray(i);
                long  time        = 0;
                for (int iter = 0; iter < 100; iter++)
                {
                    sorter.Sort(randomArray);
                    time += sorter.LastOperationTicks;
                }
                time        /= 100;
                times[count] = time;
                count++;
                Console.WriteLine(sorter.GetType().Name + ", " + i + ": " + time);
            }

            return(times);
        }
        public string Post([FromBody] string input)
        {
            var args = input.Split(" ");
            var list = new List <int>();

            foreach (var arg in args)
            {
                list.Add(int.Parse(arg));
            }

            var sorter = new Sorter();

            sorter.Sort(list);

            var output = "";

            foreach (var n in list)
            {
                output += n.ToString() + " ";
            }
            return(output);
        }
示例#24
0
        public override void Invoke()
        {
            Sorter sorter = new Sorter();

            if (_view.TextBuffer.ContentType.IsOfType("LESS"))
            {
                sorter.SortLess(_rule.Text);
            }
            else
            {
                sorter.SortStyleSheet(_rule.Text);
            }

            var position = _view.Caret.Position.BufferPosition.Position;

            EditorExtensionsPackage.DTE.UndoContext.Open(DisplayText);

            _view.Caret.MoveTo(new SnapshotPoint(_span.TextBuffer.CurrentSnapshot, position));
            EditorExtensionsPackage.ExecuteCommand("Edit.FormatSelection");

            EditorExtensionsPackage.DTE.UndoContext.Close();
        }
        public async Task<ActionResult> Search(string SearchTerm = "FC Barcelona tickets", string SortBy = "Alphabetical")
        {
            ViewBag.NoEvents = "";
            // Query API for search term
            var searchResults = await AuthSession._viagogoClient.Search.GetAsync(SearchTerm);
            
            // Create a new instance of the ViewModel
            List<SearchVM> ViewModel = new List<SearchVM>();
            int counter = 0;
            
            // Loop through each of the search results
            foreach (var eventx in searchResults.Items)
            {
                if (eventx.Type == "Event")
                {
                    var evnt = await AuthSession._viagogoClient.Hypermedia.GetAsync<Event>(eventx.EventLink);
                    ViewModel.Add(new SearchVM { SearchTerm = SearchTerm,
                        Title = eventx.Title,
                        EventLink = JsonConvert.SerializeObject(eventx.EventLink),
                        SearchIndex = counter,
                        Date = (DateTimeOffset)evnt.StartDate,
                        MinimumPrice = evnt.MinTicketPrice.Display,
                        PriceValue = (decimal)evnt.MinTicketPrice.Amount,
                        City = evnt.Venue.City,
                        Country = evnt.Venue.Country.Name,
                        Cheapest = false
                    });
                    counter++;
                }
            }

            // Sort List of Events
            List<SearchVM> SortedViewModel = Sorter.SortBy(ViewModel, SortBy);
            List<SearchVM> SortCheapViewModel = FindCheapest.CheapestTickets(SortedViewModel);

            if (counter == 0) { ViewBag.NoEvents = "There are no events listed for " + SearchTerm + "."; }
            return View(SortCheapViewModel);
        } // END OF SEARCH METHOD
 internal static void ReadData(string courseName, string studentName, string filter, string order)
 {
     if (IsDatabaseInitialized)
     {
         if (IsQueryValid(courseName, studentName, filter, order))
         {
             Filter        sifter        = new Filter();
             List <Course> coursesToShow = sifter.FilterCourses(Courses, courseName);
             if (HasZeroRecords(coursesToShow))
             {
                 return;
             }
             List <Student> studentsToShow = sifter.FilterScores(coursesToShow, filter);
             if (HasZeroRecords(studentsToShow))
             {
                 return;
             }
             studentsToShow = sifter.FilterStudents(studentsToShow, studentName);
             if (HasZeroRecords(studentsToShow))
             {
                 return;
             }
             var    report = PrepareDatabaseReport(studentsToShow);
             Sorter sorter = new Sorter();
             report = sorter.OrderReport(report, order);
             report = sifter.FilterStudents(report, studentName);
             if (HasZeroRecords(report))
             {
                 return;
             }
             IOManager.PrintDatabaseReport(report);
         }
     }
     else
     {
         throw new DatabaseNotInitializedException();
     }
 }
示例#27
0
        /// <summary>
        /// Validates a decoded sorter and ensures that the string it was decoded from wasn't tampered with.
        /// If it was (properties that shouldn't be sorted are being sorted, or properties that should be
        /// sorted aren't being sorted) they will be added and removed as necessary using a sorter created
        /// by <see cref="CreateNewSorter"/> as a template.
        /// </summary>
        /// <param name="decodedSorter">The decoded sorter</param>
        /// <returns>The validated <paramref name="decodedSorter"/></returns>
        private Sorter <T> ValidateDecodedSorter(Sorter <T> decodedSorter)
        {
            Sorter <T> correctSorter = CreateNewSorter();

            IEnumerable <MatchPair <KeyValuePair <LambdaExpression, bool>, KeyValuePair <LambdaExpression, bool> > > matchPairs =
                decodedSorter.OrderedPropertySelectors
                .MatchUp(correctSorter.OrderedPropertySelectors, (f, s) => decodedSorter.PropertySelectorsEqual(f.Key, s.Key));

            //Find properties that we shouldn't be sorting and remove them
            IEnumerable <LambdaExpression> toRemove = from pair in matchPairs
                                                      where pair.IsSecondSet == false
                                                      select pair.First.Key;

            foreach (LambdaExpression propertySelector in toRemove)
            {
                decodedSorter.RemoveProperty(propertySelector);
            }

            //Find properties that we should be sorting and add them
            IEnumerable <KeyValuePair <LambdaExpression, bool> > toAdd = from pair in matchPairs
                                                                         where pair.IsFirstSet == false
                                                                         select pair.Second;

            MethodInfo addPropertyGenericMethod = decodedSorter.GetType().GetMethod("AddProperty");

            foreach (KeyValuePair <LambdaExpression, bool> kvp in toAdd)
            {
                //Use reflection to add the selector to the sorter, since we don't know the exact
                //type the selector will be at compile time, so we need to "dynamically" call
                //the generic AddProperty method. C# 4 dynamic would be great here.
                Type       funcType   = kvp.Key.GetType().GetGenericArguments()[0];         //Func<T, returnType>
                Type       returnType = funcType.GetGenericArguments()[1];
                MethodInfo method     = addPropertyGenericMethod.MakeGenericMethod(returnType);
                method.Invoke(decodedSorter, new object[] { kvp.Key, kvp.Value });
            }

            return(decodedSorter);
        }
示例#28
0
        public void SetUp()
        {
            _receiver  = Substitute.For <ITransponderReceiver>();
            _converter = new TrackConverter(_receiver);
            _sorter    = new Sorter(_converter);
            _ts        = new TrackSpeed();
            _tcc       = new TrackCompassCourse();

            _checker        = Substitute.For <ISeperationEventChecker>();
            _warningCreator = Substitute.For <ISeperationEventHandler>();
            _logger         = Substitute.For <ISeperationEventLogger>();

            _controller = new Controller(_sorter, _ts, _tcc, _checker, _warningCreator, _logger);

            _fakeRawArgs = new RawTransponderDataEventArgs(new List <string>()
            {
                "Fly1;88000;88000;6000;20180420222222222", "Fly2;72000;91000;19999;20180420222222222", "Fly3;86000;86000;6500;20180420222222222"
            });
            _fakeRawArgs2 = new RawTransponderDataEventArgs(new List <string>()
            {
                "Fly1;86000;86000;6000;20180420223222222", "Fly2;72000;91000;19999;20180420223222222", "Fly3;86000;86000;6500;20180420223222222"
            });
        }
示例#29
0
        public void QuickSort()
        {
            int[] lst = new int[50];
            int[] cpy = new int[50];

            Sorter <int> s = new Sorter <int>();
            Random       r = new Random();

            for (int i = 0; i < 50; i++)
            {
                lst[i] = r.Next(1000);
            }

            Array.Copy(lst, cpy, 50);
            Array.Sort(cpy);

            s.QuickSort(lst, 0, lst.Length - 1);

            for (int i = 0; i < 50; i++)
            {
                Assert.AreEqual <int>(cpy[i], lst[i], "elements do not match");
            }
        }
示例#30
0
    public static IWithSortingExtensions sort_by(this IWithSortingExtensions self, Sorter sorter_obj)
    {
        //"""Sort by sorter.

        //:param sorter_obj: sorter object
        //:return: self object
        //"""
        var sort_by = self._request_data.get("sort_by");

        if (sort_by == null)
        {
            sort_by = (string)sorter_obj;
        }
        else
        {
            sort_by = $"{sort_by},{new_field}".format(
                sort_by: sort_by,
                new_field: (string)sorter_obj
                );
        }
        self._request_data["sort_by"] = sort_by;
        return(self);
    }
示例#31
0
        private void TestSorter(Sorter <int> sorter)
        {
            // Test Reverse sequential list
            List <int> list = GetReverseSequentialTestList();

            sorter.Sort(list);
            AssertGeneralTestListSorted(list);

            // Test allready sorted list
            list = GetSortedList();
            sorter.Sort(list);
            AssertGeneralTestListSorted(list);

            // Test half sequential list
            list = GetHalfSequentialList();
            sorter.Sort(list);
            AssertGeneralTestListSorted(list);

            // Test double numbers
            list = GetDoubleNumbers();
            sorter.Sort(list);
            AssertDoubleNumbersList(list);
        }
示例#32
0
        public void Should_Read_And_Save_File()
        {
            var sorter = new Sorter(@"unsorted-names-list.txt", @"sorted-names-list.txt");

            sorter.Sort();

            var sortedNames = File.ReadAllLines(@"sorted-names-list.txt");

            sortedNames.Should().Equal(new[]
            {
                "Marin Alvarez",
                "Adonis Julius Archer",
                "Beau Tristan Bentley",
                "Hunter Uriah Mathew Clarke",
                "Leo Gardner",
                "Vaughn Lewis",
                "London Lindsey",
                "Mikayla Lopez",
                "Janet Parsons",
                "Frankie Conner Ritter",
                "Shelby Nathan Yoder",
            });
        }
示例#33
0
        public IObservable <ISortedChangeSet <TObject, TKey> > Run()
        {
            return(Observable.Create <ISortedChangeSet <TObject, TKey> >(
                       observer =>
            {
                var sorter = new Sorter(_sortOptimisations, _comparer, _resetThreshold);
                var locker = new object();

                // check for nulls so we can prevent a lock when not required
                if (_comparerChangedObservable is null && _resorter is null)
                {
                    return _source.Select(sorter.Sort).Where(result => result is not null).Select(x => x !).SubscribeSafe(observer);
                }

                var comparerChanged = (_comparerChangedObservable ?? Observable.Never <IComparer <TObject> >()).Synchronize(locker).Select(sorter.Sort);

                var sortAgain = (_resorter ?? Observable.Never <Unit>()).Synchronize(locker).Select(_ => sorter.Sort());

                var dataChanged = _source.Synchronize(locker).Select(sorter.Sort);

                return comparerChanged.Merge(dataChanged).Merge(sortAgain).Where(result => result is not null).Select(x => x !).SubscribeSafe(observer);
            }));
        }
示例#34
0
文件: Program.cs 项目: SIJPA/4Test
        static void SortArray(object sorter)
        {
            Sorter sortObj = sorter as Sorter;

            int[] _resultArray = (int[])_array.Clone();

            Stopwatch watcher = new Stopwatch();

            watcher.Start();
            sortObj.Sort(_resultArray);
            watcher.Stop();

            lock (_lockObj)
            {
                OutputCollection(_resultArray, string.Format("Method: {0}", sortObj.Type.Name));
                Logger.Write(MessageType.Info, string.Format("Sorted an array by {0}", sortObj.Type.Name));

                if (_dbInsert != null)
                {
                    _dbInsert.Insert((float)watcher.Elapsed.TotalMilliseconds, sortObj.Type.Name, _resultArray);
                }
            }
        }
        public static void Main()
        {
            int[] arr = new int[] { 3, -1, 15, 4, 17, 2, 33, 0 };
            Console.WriteLine("arr = [{0}]", string.Join(", ", arr));
            Sorter collectionSorter = new Sorter();
            collectionSorter.SelectionSort(arr);
            Console.WriteLine("sorted = [{0}]", string.Join(", ", arr));

            collectionSorter.SelectionSort(new int[0]); // Test sorting empty array
            collectionSorter.SelectionSort(new int[1]); // Test sorting single element array

            Searcher collectionSearcher = new Searcher();

            Console.WriteLine(collectionSearcher.BinarySearch(arr, -1000));
            Console.WriteLine(collectionSearcher.BinarySearch(arr, 0));
            Console.WriteLine(collectionSearcher.BinarySearch(arr, 17));
            Console.WriteLine(collectionSearcher.BinarySearch(arr, 10));
            Console.WriteLine(collectionSearcher.BinarySearch(arr, 1000));

            int testEmptArraySearch = collectionSearcher.BinarySearch(new int[0], 5); // Test searching empty array
            int testSingleElementExistingSearch = collectionSearcher.BinarySearch(new int[1], 0); // Test searching single element array (Existing value)
            int testSingleelementNoExistingsearch = collectionSearcher.BinarySearch(new int[1], 5); // Test searching single element array (Non existing value)
        }
示例#36
0
        public void TestSort1Parsed()
        {
            var input = new List <FileInfo>
            {
                new FileInfo(@"TestData\Sort\Input\sort1a.txt"),
                new FileInfo(@"TestData\Sort\Input\sort1b.txt")
            };
            var output      = new FileInfo(@"TestData\Sort\Output\sort1p.txt");
            var outputFiles = new List <IOutputFile <byte[]> >
            {
                new LegacyOutputFile
                {
                    Output = output
                }
            };

            var comparerParser = new ComparerParser();
            var filterParser   = new FilterParser();

            var sorter = new Sorter <byte[]>
            {
                InputFiles            = input,
                OutputFiles           = outputFiles,
                RecordAccessorFactory = new SeparatorAccessorFactory {
                    Separator = CrLf
                },
                HeaderSize = 1,
                Comparer   = comparerParser.GetComparer("FORMAT=CH,FIELDS=(1,25,A,26,10,ZD,D)"),
                Filter     = filterParser.GetFilter(null, "(36,1,ZD,EQ,5)")
            };

            var expected = new FileInfo(@"TestData\Sort\Expected\sort1.txt");

            sorter.Sort();

            Assert.IsTrue(TestHelper.TestHelper.ContentEquals(expected.OpenRead(), output.OpenRead()));
        }
示例#37
0
        /// <summary>
        /// Aplica el ordenamiento sobre una lista
        /// </summary>
        /// <typeparam name="T">Tipo de Base de la lista</typeparam>
        /// <param name="collection">Lista</param>
        /// <param name="columnName">Nombre de columna</param>
        /// <param name="ascendig">Orden ascendente</param>
        /// <returns>Lista despues de aplicar los filtros</returns>
        public IEnumerable <T> OrderBySorter <T>(IEnumerable <T> collection, Sorter sorter)
        {
            try
            {
                if (collection == null)
                {
                    return(collection);
                }

                if (collection.Count() < 2)
                {
                    return(collection);
                }

                if (sorter == null)
                {
                    return(collection);
                }

                if (string.IsNullOrWhiteSpace(sorter.PropertyName))
                {
                    return(collection);
                }

                Func <IEnumerable <T>, Func <T, object>, IEnumerable <T> > expression = new SortExpressionConverter <T>().Convert(sorter.SortDirection);

                Func <T, object> lambda = SortLambdaBuilder <T> .Build(sorter.PropertyName);

                collection = expression(collection, lambda);

                return(collection);
            }
            catch (Exception)
            {
                return(collection);
            }
        }
示例#38
0
        /// <summary>
        /// Sorts the array until it is sorted or animation has completed.
        /// </summary>
        /// <param name="sorter">The sorter to loop with.</param>
        void SorterLoop(Sorter sorter)
        {
            while (!finished[0])
            {
                if (frameMaker?.HasCompleted() ?? false)
                {
                    break;
                }
                if (audioMaker?.HasCompleted() ?? false)
                {
                    break;
                }

                sorter.Sort(array);

                if (frameMaker?.HasCompleted() ?? false)
                {
                    break;
                }
                if (audioMaker?.HasCompleted() ?? false)
                {
                    break;
                }

                if (sorter.IsSorted(array))
                {
                    if (profile.LastFrameBlank)
                    {
                        CreateLastBlankFrame();
                    }
                    break;
                }
            }

            lock (finished)
                finished[0] = true;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            textBoxResult.Clear();

            string[] tokens = textBoxIntsToSort.Text.Split(',');
            int[] arr;
            try
            {
                arr = Array.ConvertAll<string, int>(tokens, int.Parse);
                var sorter = new Sorter();
                var results = sorter.GetSortResults(arr);
                if (results.Count > 0)
                    textBoxResult.Text = "Sort results: \r\n\r\n";

                foreach (var item in results)
                {
                    textBoxResult.Text += item.Name + ": " + item.SortTimeInMs + " ms\r\n";
                }
            }
            catch (Exception)
            {
                textBoxResult.Text = "Array is in invalid form.\r\nPlease use format: <number><,>\r\nFor example: 3,2,1";
            }
        }
示例#40
0
        public static Sorter displayMenu(Sorter aSorter)
        {
            Console.WriteLine("Select Options");
            Console.WriteLine("1- Bubble Sort");
            Console.WriteLine("2- Insertion Sort");
            Console.WriteLine("3- Quick Sort");
            String selectionString = Console.ReadLine();
            int InputNumber;
            int.TryParse(selectionString, out InputNumber);
            switch (InputNumber)
            {
                case 1:
                    aSorter = new BubbleSort();
                    break;
                case 2:
                    aSorter = new InsertionSort();
                    break;
                case 3:
                    aSorter = new QuickSort();
                    break;
            }

            return aSorter;
        }
示例#41
0
        // GET: Web
        public ActionResult List(int?brIspisa, int?strana, string sortiraj, string naziv, int?idMarke)
        {
            IVoziloServis         Servis      = new VoziloServis();
            Mape                  Mapa        = new Mape();
            IPagedList <VoziloVM> lstVozilaVM = null;
            IPagedList <IVozilo>  lstVozila   = null;

            ViewBag.sortId          = (String.IsNullOrEmpty(sortiraj)) ? "D_Id" : (sortiraj == "A_Id") ? "D_Id" : "A_Id";
            ViewBag.sortNazivMarke  = (sortiraj == "A_NazivMarke") ? "D_NazivMarke" : "A_NazivMarke";
            ViewBag.sortNazivModela = (sortiraj == "A_NazivModela") ? "D_NazivModela" : "A_NazivModela";
            ViewBag.sortKratica     = (sortiraj == "A_Kratica") ? "D_Kratica" : "A_Kratica";
            ISorter  sorter   = new Sorter(sortiraj ?? "A_Id");
            IFilter  filter   = new Filter(naziv, idMarke);
            INumerer stranica = new Numerer();

            stranica.Str      = strana ?? 1;
            stranica.BrRedova = brIspisa ?? 10;
            IOdgovor <VoziloVM>  odgovor        = new Odgovor <VoziloVM>();
            IList <IVoziloModel> lstVozilaModel = null;

            try
            {
                lstVozilaModel      = Servis.DohvatiVozila(sorter, filter, stranica);
                lstVozila           = Mapa.maper.Map <IList <IVoziloModel>, IList <IVozilo> >(lstVozilaModel).ToPagedList(stranica.Str, stranica.BrRedova);
                odgovor.UkupanBroj  = lstVozila.TotalItemCount;
                lstVozilaVM         = new StaticPagedList <VoziloVM>(Mapa.maper.Map <IEnumerable <IVozilo>, IEnumerable <VoziloVM> >(lstVozila), lstVozila.GetMetaData());
                odgovor.ListaIspisa = lstVozilaVM;

                ViewBag.stranica = stranica;
            }
            catch (Exception ex)
            {
                ViewBag.Message = "Greška kod dohvaćanja popisa vozila. Opis: " + ex.Message;
            }
            return(View(odgovor));
        }
示例#42
0
        public void SortTest()
        {
            Sorter sort = new Sorter();

            var dateList = new List <DateTime> {
                DateTime.Parse("01/01/2001"), DateTime.Parse("01/03/2001"), DateTime.Parse("01/04/2001"), DateTime.Parse("01/02/2001")
            };
            var priceList = new List <decimal> {
                1, 2, 3, 4
            };
            var memoList = new List <string> {
                "a", "b", "c", "d"
            };
            var price = 10;

            sort.Sort(dateList, priceList, memoList, price);

            Assert.AreEqual(priceList, new List <decimal> {
                1, 4, 12, 13
            });
            Assert.AreEqual(memoList, new List <string> {
                "a", "d", "b", "c"
            });
        }
示例#43
0
        //Populate the count of the items passed from the csv file, populate to grid and ask to open file
        private void btnPopularity_Click(object sender, EventArgs e)
        {
            var firstNameSurnameCount = Sorter.GetWordCountDescendingOrder(People_Class.GetFullNameList());
            var names = (from row in firstNameSurnameCount select new { Name = row.Key, Count = row.Value });

            dataGridView1.DataSource = names.ToList();

            string error = null;

            Helpers.FileAccess.WriteAllLines(_file1, names.Select(x => x.Name + "\t" + x.Count), out error);

            if (string.IsNullOrEmpty(error))
            {
                toolStripStatusLabel.Text = "File with Names Count generated";
                if (MessageBox.Show("File generated succesfully, would you like to open the file now?", "Open File", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    Process.Start("notepad.exe", _file1);
                }
            }
            else
            {
                toolStripStatusLabel.Text = error;
            }
        }
示例#44
0
        public static void Main(string[] args)
        {
            retrieveDataFromFile r = new retrieveDataFromFile(@"C:\Users\GabrielFerreira\Documents\repos\sortExercise\src\scrambled.txt");

            int select = 0;

            Console.WriteLine("Exercício 1: \n digite 1");
            Console.WriteLine("Exercício 2: \n digite 2");
            Console.WriteLine("Exercício 3: \n digite 3");
            select = Convert.ToInt32(Console.ReadLine());

            switch (select)
            {
            case 1:
                writeToFile wr           = new writeToFile(@"C:\Users\GabrielFerreira\documents\repos\sortExercise\src\ex1Result.txt");
                Sorter      s            = new Sorter();
                int []      ordenedArray = s.quickSort(r.fileData());
                wr.saveDataToNewFile(ordenedArray);
                break;

            case 2:
                Multiplier m = new Multiplier(1953, 5378);
                m.Result(r.fileData());
                break;

            case 3:
                writeToFile  wt = new writeToFile(@"C:\Users\GabrielFerreira\documents\repos\sortExercise\src\ex2Result.txt");
                getMultiples gt = new getMultiples(350, r.fileData());
                wt.saveDataToNewFile(gt.CalculateMultiples());
                break;

            default:
                Console.WriteLine("error");
                break;
            }
        }
        public void QueryListView_ColumnClick(object sender, System.Windows.Forms.ColumnClickEventArgs e)
        {
            Parent.Cursor = Cursors.WaitCursor;

            Column = e.Column;

            ColumnDataType = ColumnDataTypes[Column];

            // Toggle the sort order when user clicks on the column twice in a row.
            if (Column == PreviousColumn)
            {
                Sorting = Sorting == SortOrder.Ascending ? SortOrder.Descending : SortOrder.Ascending;
            }
            else
            {
                Sorting = SortOrder.Ascending;
            }

            ListViewItemSorter = new Sorter();

            PreviousColumn = Column;

            Parent.Cursor = Cursors.Arrow;
        }
示例#46
0
        public void GenerateAndSortMultiChunkSuccess()
        {
            const string randomFileName = "random";

            using (var writer = new StreamWriter(randomFileName, false))
            {
                var generator = new Generator.Logic.Generator(
                    Path.Combine(TestContext.CurrentContext.TestDirectory, "dictionary.txt"),
                    writer);
                generator.Generate(256 * 1048576);
            }

            var sortWatch = Stopwatch.StartNew();

            const string sortedFileName = "sorted";

            File.Delete(sortedFileName);
            var sortedDir = Directory.CreateDirectory(TestContext.CurrentContext.Test.Name);
            var sorter    = new Sorter(randomFileName, _logger);

            foreach (var fileInfo in sortedDir.GetFiles())
            {
                fileInfo.Delete();
            }

            sorter.Sort(sortedFileName);
            SortingAssert.FileSorted(sortedFileName, new CompositeStringComparer());

            var expectedLines = File.ReadAllLines(randomFileName).Length;
            var actualLines   = File.ReadAllLines(sortedFileName).Length;

            Assert.AreEqual(expectedLines, actualLines);

            sortWatch.Stop();
            _logger.Information($"Sorted for {sortWatch.Elapsed.ToString()}");
        }
        private void button1_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;

            memoResults.Text = "";

            string[] tokens = memoDataToSort.Text.Split(',');
            int[]    arr;
            try
            {
                arr = Array.ConvertAll <string, int>(tokens, int.Parse);
                var sorter  = new Sorter();
                var results = sorter.GetSortResults(arr);

                foreach (var item in results)
                {
                    memoResults.Text += item.Name + ": " + item.SortTimeInMs + " ms\r\n";
                }

                // Bind the chart to the list.
                chartSortTime.DataSource = results;

                if (chartSortTime.Series.Count == 0)
                {
                    CreateSeries();
                }
            }
            catch (Exception)
            {
                memoResults.Text = "Array is in invalid form.\r\nPlease use format: <number><,>\r\nFor example: 3,2,1";
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }
示例#48
0
        public void SortTest()
        {
            var sorter = new Sorter <int>();

            sorter.List = new List <int>()
            {
                5, 3, 1, 4, 9
            };
            sorter.Comparer = new MyComparer();
            sorter.Sort();

            var actualSort = new List <int> {
                1, 3, 4, 5, 9
            };

            if (Enumerable.SequenceEqual(sorter.List, actualSort))
            {
                // Pass!
            }
            else
            {
                Assert.Fail();
            }
        }
示例#49
0
 //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
 //ORIGINAL LINE: SortingDocsEnum(int maxDoc, SortingDocsEnum reuse, final org.apache.lucene.index.DocsEnum in, boolean withFreqs, final Sorter.DocMap docMap) throws java.io.IOException
 //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET:
 internal SortingDocsEnum(int maxDoc, SortingDocsEnum reuse, DocsEnum @in, bool withFreqs, Sorter.DocMap docMap)
     : base(@in)
 {
     this.maxDoc = maxDoc;
       this.withFreqs = withFreqs;
       if (reuse != null)
       {
     if (reuse.maxDoc == maxDoc)
     {
       sorter = reuse.sorter;
     }
     else
     {
       sorter = new DocFreqSorter(maxDoc);
     }
     docs = reuse.docs;
     freqs = reuse.freqs; // maybe null
       }
       else
       {
     docs = new int[64];
     sorter = new DocFreqSorter(maxDoc);
       }
       docIt = -1;
       int i = 0;
       int doc;
       if (withFreqs)
       {
     if (freqs == null || freqs.Length < docs.Length)
     {
       freqs = new int[docs.Length];
     }
     while ((doc = @in.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS)
     {
       if (i >= docs.Length)
       {
     docs = ArrayUtil.grow(docs, docs.Length + 1);
     freqs = ArrayUtil.grow(freqs, freqs.Length + 1);
       }
       docs[i] = docMap.oldToNew(doc);
       freqs[i] = @in.freq();
       ++i;
     }
       }
       else
       {
     freqs = null;
     while ((doc = @in.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS)
     {
       if (i >= docs.Length)
       {
     docs = ArrayUtil.grow(docs, docs.Length + 1);
       }
       docs[i++] = docMap.oldToNew(doc);
     }
       }
       // TimSort can save much time compared to other sorts in case of
       // reverse sorting, or when sorting a concatenation of sorted readers
       sorter.reset(docs, freqs);
       sorter.sort(0, i);
       upto = i;
 }
示例#50
0
 //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET:
 //ORIGINAL LINE: public SortingNumericDocValues(final org.apache.lucene.index.NumericDocValues in, Sorter.DocMap docMap)
 public SortingNumericDocValues(NumericDocValues @in, Sorter.DocMap docMap)
 {
     this.@in = @in;
       this.docMap = docMap;
 }
示例#51
0
 internal SortingSortedDocValues(SortedDocValues @in, Sorter.DocMap docMap)
 {
     this.@in = @in;
       this.docMap = docMap;
 }
示例#52
0
 //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET:
 //ORIGINAL LINE: public SortingBits(final org.apache.lucene.util.Bits in, Sorter.DocMap docMap)
 public SortingBits(Bits @in, Sorter.DocMap docMap)
 {
     this.@in = @in;
       this.docMap = docMap;
 }
示例#53
0
 //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET:
 //ORIGINAL LINE: public SortingFields(final org.apache.lucene.index.Fields in, org.apache.lucene.index.FieldInfos infos, Sorter.DocMap docMap)
 public SortingFields(Fields @in, FieldInfos infos, Sorter.DocMap docMap)
     : base(@in)
 {
     this.docMap = docMap;
       this.infos = infos;
 }
示例#54
0
 internal SortingBinaryDocValues(BinaryDocValues @in, Sorter.DocMap docMap)
 {
     this.@in = @in;
       this.docMap = docMap;
 }
示例#55
0
 //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET:
 //ORIGINAL LINE: public SortingTermsEnum(final org.apache.lucene.index.TermsEnum in, Sorter.DocMap docMap, org.apache.lucene.index.FieldInfo.IndexOptions indexOptions)
 public SortingTermsEnum(TermsEnum @in, Sorter.DocMap docMap, IndexOptions indexOptions)
     : base(@in)
 {
     this.docMap = docMap;
       this.indexOptions = indexOptions;
 }
        public void QueryListView_ColumnClick(object sender, System.Windows.Forms.ColumnClickEventArgs e)
        {
            Parent.Cursor = Cursors.WaitCursor;

            Column = e.Column;

            ColumnDataType = ColumnDataTypes[Column];

            // Toggle the sort order when user clicks on the column twice in a row.
            if (Column == PreviousColumn)
            {
                Sorting = Sorting == SortOrder.Ascending ? SortOrder.Descending : SortOrder.Ascending;
            }
            else
            {
                Sorting = SortOrder.Descending;
            }

            ListViewItemSorter = new Sorter();

            PreviousColumn = Column;

            Parent.Cursor = Cursors.Arrow;
        }
示例#57
0
 //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
 //ORIGINAL LINE: SortingDocsAndPositionsEnum(int maxDoc, SortingDocsAndPositionsEnum reuse, final org.apache.lucene.index.DocsAndPositionsEnum in, Sorter.DocMap docMap, boolean storeOffsets) throws java.io.IOException
 //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET:
 internal SortingDocsAndPositionsEnum(int maxDoc, SortingDocsAndPositionsEnum reuse, DocsAndPositionsEnum @in, Sorter.DocMap docMap, bool storeOffsets)
     : base(@in)
 {
     this.maxDoc = maxDoc;
       this.storeOffsets = storeOffsets;
       if (reuse != null)
       {
     docs = reuse.docs;
     offsets = reuse.offsets;
     payload = reuse.payload;
     file = reuse.file;
     if (reuse.maxDoc == maxDoc)
     {
       sorter = reuse.sorter;
     }
     else
     {
       sorter = new DocOffsetSorter(maxDoc);
     }
       }
       else
       {
     docs = new int[32];
     offsets = new long[32];
     payload = new BytesRef(32);
     file = new RAMFile();
     sorter = new DocOffsetSorter(maxDoc);
       }
     //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
     //ORIGINAL LINE: final org.apache.lucene.store.IndexOutput out = new org.apache.lucene.store.RAMOutputStream(file);
       IndexOutput @out = new RAMOutputStream(file);
       int doc;
       int i = 0;
       while ((doc = @in.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS)
       {
     if (i == docs.Length)
     {
     //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
     //ORIGINAL LINE: final int newLength = org.apache.lucene.util.ArrayUtil.oversize(i + 1, 4);
       int newLength = ArrayUtil.oversize(i + 1, 4);
       docs = Arrays.copyOf(docs, newLength);
       offsets = Arrays.copyOf(offsets, newLength);
     }
     docs[i] = docMap.oldToNew(doc);
     offsets[i] = @out.FilePointer;
     addPositions(@in, @out);
     i++;
       }
       upto = i;
       sorter.reset(docs, offsets);
       sorter.sort(0, upto);
       @out.close();
       this.postingInput = new RAMInputStream("", file);
 }
示例#58
0
 /// <summary>
 /// Expert: same as <seealso cref="#wrap(AtomicReader, Sort)"/> but operates directly on a <seealso cref="Sorter.DocMap"/>. </summary>
 internal static AtomicReader wrap(AtomicReader reader, Sorter.DocMap docMap)
 {
     if (docMap == null)
     {
       // the reader is already sorter
       return reader;
     }
     if (reader.maxDoc() != docMap.size())
     {
       throw new System.ArgumentException("reader.maxDoc() should be equal to docMap.size(), got" + reader.maxDoc() + " != " + docMap.size());
     }
     Debug.Assert(Sorter.isConsistent(docMap));
     return new SortingAtomicReader(reader, docMap);
 }
示例#59
0
        protected override void ParseFileNameLocal()
        {
            Log.Log(LogType.FILE, LogLevel.INFORM, "ParseFileNameLocal() | Searching in directory: " + Dir);

            if (Dir.EndsWith("/") || Dir.EndsWith("\\"))
            {

                ArrayList arrFileNames = new ArrayList();

                foreach (String sFileName in Directory.GetFiles(Dir))
                {
                    string sFile = Path.GetFileName(sFileName).ToString();
                    if (sFile.StartsWith("ISALOG_") && sFile.EndsWith(".w3c"))
                    {
                        arrFileNames.Add(sFile);
                        Log.Log(LogType.FILE, LogLevel.INFORM, "ParseFileNameLocal1() | " + sFile);
                    }
                }

                Sorter[] dSortTemp = new Sorter[arrFileNames.Count];
                for (int i = 0; i < arrFileNames.Count; i++)
                {
                    //ISALOG_20090805_WEB_000.w3c
                    string sFileName = arrFileNames[i].ToString();
                    String[] arr = sFileName.Split('.');
                    String[] arr1 = arr[0].Split('_');
                    dSortTemp[i] = new Sorter(Convert.ToUInt64(arr1[1]), Convert.ToUInt64(arr1[3]), sFileName);
                    Log.Log(LogType.FILE, LogLevel.INFORM, "ParseFileNameLocal2() | " + sFileName);

                }

                Array.Sort(dSortTemp);

                string[] dFileNames = new string[arrFileNames.Count];

                for (int i = 0; i < dSortTemp.Length; i++)
                {
                    dFileNames[i] = dSortTemp[i].name;
                }

                if (String.IsNullOrEmpty(lastFile))
                {
                    if (dFileNames.Length > 0)
                    {
                        FileName = Dir + dFileNames[dFileNames.Length - 1].ToString();
                        lastFile = FileName;
                        Log.Log(LogType.FILE, LogLevel.INFORM, "ParseFileNameLocal() | Last File Is Null So Last File Setted The First File " + lastFile);
                    }
                    else
                    {
                        Log.Log(LogType.FILE, LogLevel.INFORM, "ParseFileNameLocal() | Last File Is Null And There Is No File To Set");
                    }
                }
                else
                {
                    if (File.Exists(lastFile))
                    {
                        FileStream fs = new FileStream(lastFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                        BinaryReader br = new BinaryReader(fs, enc);
                        br.BaseStream.Seek(Position, SeekOrigin.Begin);
                        FileInfo fi = new FileInfo(lastFile);
                        Int64 fileLength = fi.Length;

                        Char c = ' ';
                        while (!Environment.NewLine.Contains(c.ToString()) && (br.BaseStream.Position < fileLength))
                        {
                            Log.Log(LogType.FILE, LogLevel.DEBUG, "ParseFileNameLocal() | Position Setted To Next End of Line : Position Is1 " + br.BaseStream.Position);
                            c = br.ReadChar();
                            Log.Log(LogType.FILE, LogLevel.DEBUG, "ParseFileNameLocal() | Position Setted To Next End of Line : Position Is2 " + br.BaseStream.Position);

                            Log.Log(LogType.FILE, LogLevel.DEBUG, "ParseFileNameLocal() | Char Is" + c.ToString());

                            if (Environment.NewLine.Contains(c.ToString()) || br.BaseStream.Position == fileLength)
                            {
                                Log.Log(LogType.FILE, LogLevel.DEBUG, "ParseFileNameLocal() | Position Setted To Next End of Line : Position Is " + br.BaseStream.Position);
                                Log.Log(LogType.FILE, LogLevel.DEBUG, "ParseFileNameLocal() | Position Setted To Next End of Line : FileLength Is " + fileLength);
                            }
                        }

                        Log.Log(LogType.FILE, LogLevel.DEBUG, "ParseFileNameLocal() | Position Is : " + br.BaseStream.Position.ToString());
                        Log.Log(LogType.FILE, LogLevel.DEBUG, "ParseFileNameLocal() | Length Is : " + br.BaseStream.Length.ToString());

                        if (br.BaseStream.Position == br.BaseStream.Length || br.BaseStream.Position == br.BaseStream.Length - 1)
                        {
                            for (int i = 0; i < dFileNames.Length; i++)
                            {
                                if (Dir + dFileNames[i].ToString() == lastFile)
                                {
                                    if (i + 1 == dFileNames.Length)
                                    {
                                        FileName = lastFile;
                                        lastFile = FileName;
                                        Log.Log(LogType.FILE, LogLevel.INFORM, "ParseFileNameLocal() | There Is No New Fıle and Waiting For New Record");
                                        break;
                                    }
                                    else
                                    {
                                        FileName = Dir + dFileNames[(i + 1)].ToString();
                                        lastFile = FileName;
                                        Log.Log(LogType.FILE, LogLevel.INFORM, "ParseFileNameLocal() | Yeni FileName: " + FileName);
                                        break;
                                    }
                                }
                            }
                        }
                        else
                        {
                            FileName = lastFile;
                            Log.Log(LogType.FILE, LogLevel.DEBUG, "ParseFileNameLocal() | Continue reading the last file : " + FileName);
                        }
                    }
                    else
                    {
                        Log.Log(LogType.FILE, LogLevel.DEBUG, "ParseFileNameLocal() | Last File Not Found : " + lastFile);
                        SetNextFile(dFileNames, "ParseFileNameLocal");

                    }
                }

            }
            else
                FileName = Dir;

            Log.Log(LogType.FILE, LogLevel.INFORM, "ParseFileNameLocal() Exit | Filename is: " + FileName);
        }
示例#60
0
        internal readonly Sorter.DocMap docMap; // pkg-protected to avoid synthetic accessor methods

        #endregion Fields

        #region Constructors

        //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET:
        //ORIGINAL LINE: private SortingAtomicReader(final org.apache.lucene.index.AtomicReader in, final Sorter.DocMap docMap)
        private SortingAtomicReader(AtomicReader @in, Sorter.DocMap docMap)
            : base(@in)
        {
            this.docMap = docMap;
        }