Пример #1
0
 public Department()
 {
     InitializeComponent();
     admin      = new Admin();
     department = new Departments();
     counts     = new Counts();
 }
Пример #2
0
 private void button1_Click(object sender, EventArgs e)
 {
     param.n       = Convert.ToInt32(textBox1.Text);
     param.maxtime = Convert.ToInt32(textBox2.Text);
     param.np      = Convert.ToInt32(textBox3.Text);
     param.e1      = Convert.ToDouble(textBox4.Text);
     param.e2      = Convert.ToDouble(textBox5.Text);
     param.Uratio  = Convert.ToDouble(textBox6.Text);
     Counts.paramset(param.n, param.maxtime, param.np, param.e1, param.e2, param.Uratio, ref param1);
     if (param.n != param1.n || param.maxtime != param1.maxtime || param.np != param1.np || param.e1 != param1.e1 || param.e2 != param1.e2 || param.Uratio != param1.Uratio)
     {
         param         = param1;
         textBox1.Text = param.n.ToString();
         textBox2.Text = param.maxtime.ToString();
         textBox3.Text = param.np.ToString();
         textBox4.Text = param.e1.ToString();
         textBox5.Text = param.e2.ToString();
         textBox6.Text = param.Uratio.ToString();
         label6.Show();
     }
     else
     {
         this.Close();
     }
 }
Пример #3
0
        /// <summary>
        /// Calculate the inserted, updated, deleted and unchanged counts for the given nodes
        /// </summary>
        private Counts GetCounts(XNode[] original, XNode[] updated)
        {
            var counts = new Counts();

            // Check for attribute changes
            foreach (var child in updated)
            {
                if (child.Match == MatchType.Change)
                {
                    counts.Updates++;
                }

                if (child.Match == MatchType.NoMatch)
                {
                    counts.Inserts++;
                }

                if (child.Match == MatchType.Match)
                {
                    counts.Unchanged++;
                }
            }
            foreach (var child in original)
            {
                if (child.Match == MatchType.NoMatch)
                {
                    counts.Deletes++;
                }
            }

            return(counts);
        }
Пример #4
0
 public void AssertCounts(Counts expectedCounts)
 {
     AssertCount(Counts.Index.Element, expectedCounts, "elements");
     AssertCount(Counts.Index.Sequence, expectedCounts, "sequences");
     AssertCount(Counts.Index.Choice, expectedCounts, "choices");
     AssertCount(Counts.Index.All, expectedCounts, "alls");
     AssertCount(Counts.Index.Group, expectedCounts, "groups");
     AssertCount(Counts.Index.SimpleType, expectedCounts, "simple types");
     AssertCount(Counts.Index.SimpleTypeRestriction, expectedCounts, "simple type restrictions");
     AssertCount(Counts.Index.Length, expectedCounts, "lengths");
     AssertCount(Counts.Index.MinLength, expectedCounts, "minimum lengths");
     AssertCount(Counts.Index.MaxLength, expectedCounts, "maximum lengths");
     AssertCount(Counts.Index.Pattern, expectedCounts, "patterns");
     AssertCount(Counts.Index.Enumeration, expectedCounts, "enumerations");
     AssertCount(Counts.Index.MinInclusive, expectedCounts, "minimum inclusives");
     AssertCount(Counts.Index.MaxInclusive, expectedCounts, "maximum inclusives");
     AssertCount(Counts.Index.MinExclusive, expectedCounts, "minimum exclusives");
     AssertCount(Counts.Index.MaxExclusive, expectedCounts, "maximum exclusives");
     AssertCount(Counts.Index.TotalDigits, expectedCounts, "total digits'");
     AssertCount(Counts.Index.FractionDigits, expectedCounts, "fraction digits'");
     AssertCount(Counts.Index.WhiteSpace, expectedCounts, "white spaces");
     AssertCount(Counts.Index.SimpleTypeUnion, expectedCounts, "simple type unions");
     AssertCount(Counts.Index.SimpleTypeList, expectedCounts, "simple type lists");
     AssertCount(Counts.Index.ComplexType, expectedCounts, "complex types");
     AssertCount(Counts.Index.Attribute, expectedCounts, "attributes");
     AssertCount(Counts.Index.Any, expectedCounts, "anys");
     AssertCount(Counts.Index.AnyAttribute, expectedCounts, "anyAttributes");
     AssertCount(Counts.Index.SimpleContentExtension, expectedCounts, "simple content extensions");
     AssertCount(Counts.Index.ComplexContentExtension, expectedCounts, "complex content extensions");
     AssertCount(Counts.Index.ComplexContentRestriction, expectedCounts, "complex content restrictions");
 }
Пример #5
0
        private static Issue77.Branch CreateSourceBranch(Counts counts)
        {
            var branch  = new Issue77.Branch();
            var product = new Issue77.Product();

            for (var i = 0; i < counts.Warehouses; ++i)
            {
                branch.Warehouses.Add(new Issue77.Warehouse());
            }

            foreach (var warehouse in branch.Warehouses)
            {
                warehouse.Branch = branch;

                for (var i = 0; i < counts.WarehouseProducts; ++i)
                {
                    var warehouseProduct = new Issue77.WarehouseProduct
                    {
                        Product   = product,
                        Warehouse = warehouse
                    };

                    product.Warehouses.Add(warehouseProduct);
                    warehouse.Products.Add(warehouseProduct);
                }
            }

            return(branch);
        }
Пример #6
0
        private static void CheckLabelCounts(GraphDatabaseAPI db)
        {
            using (Transaction ignored = Db.beginTx())
            {
                Dictionary <Label, long> counts = new Dictionary <Label, long>();
                foreach (Node node in Db.AllNodes)
                {
                    foreach (Label label in node.Labels)
                    {
                        long?count = counts[label];
                        if (count != null)
                        {
                            counts[label] = count + 1;
                        }
                        else
                        {
                            counts[label] = 1L;
                        }
                    }
                }

                ThreadToStatementContextBridge bridge = Db.DependencyResolver.resolveDependency(typeof(ThreadToStatementContextBridge));
                KernelTransaction kernelTransaction   = bridge.GetKernelTransactionBoundToThisThread(true);

                foreach (KeyValuePair <Label, long> entry in Counts.SetOfKeyValuePairs())
                {
                    assertEquals(entry.Value.longValue(), kernelTransaction.DataRead().countsForNode(kernelTransaction.TokenRead().nodeLabel(entry.Key.name())));
                }
            }
        }
Пример #7
0
        public StartUpViewModel(IScreen screen) : base(screen)
        {
            IsDbAvailable = App.Features.InAppDatabase == Infrastructure.Features.FeatureAvailability.Available &&
                            App.Features.MultiUserEnabled == Infrastructure.Features.FeatureAvailability.Available;
            Identifier = new TestIndentifier {
                ImpulseRate = _minimumImpulseRate, Correction = false
            };

            NavigateCommand      = ReactiveCommand.Create(StartTest);
            NavigateToturialMode = ReactiveCommand.Create(StartTurotial);
            Quantums             = QuantumTypeLookup.Load();
            Counts          = TestCountTypeLookup.Load();
            SelectedQuantum = Quantums.FirstOrDefault(x => x.Item == Quantum.TwoHalf);
            SelectedCount   = Counts.FirstOrDefault(x => x.Item == TestCount.Sixty);
            Representations = RepresentationTypeLookup.Load();

            SelectedRepresentation = Representations.FirstOrDefault(x => x.Item == RepresentationType.UI);
            SelectedUser           = UserManager.GetDefaultUser();
            SuggestedUsers         = new ObservableCollection <User>();
            this.WhenActivated(disposables =>
            {
                this
                .WhenAnyValue(x => x.SelectedRepresentation)
                .WhereNotNull()
                .Subscribe(x => Identifier.RepresentationType = x.Item)
                .DisposeWith(disposables);

                this.WhenAnyValue(x => x.SearchTerm)
                .WhereNotNull()
                .Subscribe(term => Search(term.Trim()));
            });
        }
Пример #8
0
        private static void ProcessMetadata(
            IEnumerable <MarkdownMetadata> metadataItems,
            SourceInformation[] items,
            Counts counts,
            ConcurrentBag <Result> results
            )
        {
            var exceptions = new ConcurrentQueue <Exception>();

            try
            {
                Parallel.ForEach(
                    metadataItems,
                    metadata =>
                {
                    WriteOutput($"Checking {metadata.SourceInformation.SourcePath}");

                    foreach (var link in metadata.Links)
                    {
                        ProcessLink(link, items, metadata, counts, results);
                    }
                }
                    );
            }
            catch (Exception e)
            {
                exceptions.Enqueue(e);
            }

            if (exceptions.Count > 0)
            {
                throw new AggregateException(exceptions);
            }
        }
Пример #9
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldAccessRelationshipLabels()
        public virtual void ShouldAccessRelationshipLabels()
        {
            // given
            IDictionary <int, int> counts = new Dictionary <int, int>();

            using (RelationshipScanCursor relationships = cursors.allocateRelationshipScanCursor())
            {
                // when
                read.allRelationshipsScan(relationships);
                while (relationships.Next())
                {
                    Counts.compute(relationships.Type(), (k, v) => v == null ? 1 : v + 1);
                }
            }

            // then
            assertEquals(3, Counts.Count);
            int[] values = new int[3];
            int   i      = 0;

            foreach (int value in Counts.Values)
            {
                values[i++] = value;
            }
            Arrays.sort(values);
            assertArrayEquals(new int[] { 1, 6, 6 }, values);
        }
Пример #10
0
 public FormSSS()
 {
     InitializeComponent();
     admin  = new Admin();
     sss    = new SSS();
     counts = new Counts();
 }
 public FormPositions()
 {
     InitializeComponent();
     admin     = new Admin();
     positions = new Positions();
     counts    = new Counts();
 }
Пример #12
0
        public static void TraverseProper(string dirSource, string dirTarget, long countTotal, List <string> logs)
        {
            Terminal.Fore.Line("");
            Terminal.Yellow.Line("Traversing proper...");

            Counts count = new Counts();

            count.countCurrent = 0;
            count.countTotal   = countTotal;

            if (!Directory.Exists(dirSource))
            {
                throw new Exception("Source directory doesn't exist!");
            }
            if (!Directory.Exists(dirTarget))
            {
                throw new Exception("Target directory doesn't exist!");
            }

            ProcessDirectory(dirSource, dirSource, dirTarget, ref count);
            Terminal.Green.Line("\n\nDone traversing!");
            Terminal.Green.Line("File copies:       " + count.copied);
            Terminal.Green.Line("File overwrites:   " + count.overwritten);
            Terminal.Green.Line("File no actions:    " + count.noaction);
            logs.Add(string.Format("{0,30}{1}", "File copies: ", count.copied));
            logs.Add(string.Format("{0,30}{1}", "File overwrites: ", count.overwritten));
            logs.Add(string.Format("{0,30}{1}", "File no actions: ", count.noaction));
        }
Пример #13
0
 public SpecProgress(string id, Counts counts, int step, int total) : base("spec-progress")
 {
     this.id     = id;
     this.counts = counts;
     this.step   = step;
     this.total  = total;
 }
 public FormPagIbig()
 {
     InitializeComponent();
     pagIbig = new PagIbig();
     counts  = new Counts();
     admin   = new Admin();
 }
Пример #15
0
            public void ReloadSeries()
            {
                var views = items.Where(p => p.States.IsStateDoneWithDate(StateEnum.Finished)).ToList();

                Series.Clear();
                Counts.Clear();
                foreach (var t in MovieViewModel.TypesDict)
                {
                    int c      = 0;
                    var points = new List <DateTimePoint>();
                    for (var dt = FirstDay; dt <= LastDay; dt = dt.AddDays(1))
                    {
                        var count = views.Count(p => p.FinishDate == dt && p.Type == t.Key);
                        points.Add(
                            new DateTimePoint()
                        {
                            DateTime = dt,
                            Value    = count
                        });
                        c = c + count;
                    }

                    var a = new StackedColumnSeries()
                    {
                        Values = new ChartValues <DateTimePoint>(points),
                        Title  = t.Value,
                        Fill   = ConvertFuncs.TypeToBrushFunc(t.Key)
                    };
                    Series.Add(a);
                    Counts.Add(new CountClass(c, t.Key, t.Value));
                }
                Totals = Counts.Sum(p => p.Count);
                Reloaded?.Invoke(null, EventArgs.Empty);
            }
Пример #16
0
            public void ReloadSeries()
            {
                var views = items.Where(p => p.IsFinishedWithDate).ToList();

                Series.Clear();
                Counts.Clear();
                foreach (var t in MovieViewModel.TypesDict)
                {
                    int c      = 0;
                    var points = new List <DataModel>();
                    for (var dt = 2012; dt <= DateTime.Today.Year; dt = dt + 1)
                    {
                        var count = views.Count(p => p.FinishDate.Value.Year == dt && p.Type == t.Key);
                        points.Add(
                            new DataModel()
                        {
                            Year  = dt,
                            Count = count
                        });
                        c = c + count;
                    }
                    var a = new StackedColumnSeries()
                    {
                        Values = new ChartValues <DataModel>(points),
                        Title  = t.Value,
                        Fill   = ConvertFuncs.TypeToBrushFunc(t.Key)
                    };
                    Series.Add(a);
                    Counts.Add(new CountClass(c, t.Key, t.Value));
                }
                Totals = Counts.Sum(p => p.Count);
                Reloaded?.Invoke(null, EventArgs.Empty);
            }
Пример #17
0
//JAVA TO C# CONVERTER WARNING: 'final' parameters are ignored unless the option to convert to C# 7.2 'in' parameters is selected:
//ORIGINAL LINE: public void checkCounts(org.neo4j.kernel.impl.api.CountsAccessor counts, final org.neo4j.consistency.report.ConsistencyReporter reporter, org.neo4j.helpers.progress.ProgressMonitorFactory progressFactory)
        public virtual void CheckCounts(CountsAccessor counts, ConsistencyReporter reporter, ProgressMonitorFactory progressFactory)
        {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int nodes = nodeCounts.size();
            int nodes = _nodeCounts.size();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int relationships = relationshipCounts.size();
            int relationships = _relationshipCounts.size();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int total = nodes + relationships;
            int total = nodes + relationships;
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicInteger nodeEntries = new java.util.concurrent.atomic.AtomicInteger(0);
            AtomicInteger nodeEntries = new AtomicInteger(0);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicInteger relationshipEntries = new java.util.concurrent.atomic.AtomicInteger(0);
            AtomicInteger relationshipEntries = new AtomicInteger(0);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.helpers.progress.ProgressListener listener = progressFactory.singlePart("Checking node and relationship counts", total);
            ProgressListener listener = progressFactory.SinglePart("Checking node and relationship counts", total);

            listener.Started();
            Counts.accept(new CountsVisitor_AdapterAnonymousInnerClass(this, reporter, nodeEntries, relationshipEntries, listener));
            reporter.ForCounts(new CountsEntry(nodeKey(WILDCARD), nodeEntries.get()), CHECK_NODE_KEY_COUNT);
            reporter.ForCounts(new CountsEntry(relationshipKey(WILDCARD, WILDCARD, WILDCARD), relationshipEntries.get()), CHECK_RELATIONSHIP_KEY_COUNT);
            listener.Done();
        }
 public FormPhilHealth()
 {
     InitializeComponent();
     philHealth = new PhilHealth();
     counts     = new Counts();
     admin      = new Admin();
 }
Пример #19
0
        private static Counts CountResults(Stream output)
        {
            Counts       res    = new Counts();
            StreamReader reader = new StreamReader(output);

            while (!reader.EndOfStream)
            {
                string l = reader.ReadLine();                                                                            // does not contain \r\n
                l.TrimEnd(' ');
                if (l == "sat" || l == "SAT" || l == "SATISFIABLE" || l == "s SATISFIABLE" || l == "SuccessfulRuns = 1") // || l == "VERIFICATION FAILED")
                {
                    res.sat++;
                }
                else if (l == "unsat" || l == "UNSAT" || l == "UNSATISFIABLE" || l == "s UNSATISFIABLE") // || l == "VERIFICATION SUCCESSFUL")
                {
                    res.unsat++;
                }
                else if (l == "unknown" || l == "UNKNOWN" || l == "INDETERMINATE")
                {
                    res.other++;
                }
            }
            output.Position = 0L;
            return(res);
        }
Пример #20
0
        public void saveUpdateCounts(Counts obCounts, SqlConnection con)
        {
            SqlCommand     com   = null;
            SqlTransaction trans = null;

            try
            {
                com             = new SqlCommand();
                trans           = con.BeginTransaction();
                com.Transaction = trans;
                com.Connection  = con;
                com.CommandText = "spSaveUpdateCounts";
                com.CommandType = CommandType.StoredProcedure;
                com.Parameters.Add("@CountID", SqlDbType.Int).Value            = obCounts.CountID == -1 ? 0 : obCounts.CountID;
                com.Parameters.Add("@CountName", SqlDbType.VarChar, 100).Value = obCounts.CountName;
                com.Parameters.Add("@CompanyID", SqlDbType.Int).Value          = LogInInfo.CompanyID;
                com.Parameters.Add("@UserID", SqlDbType.Int).Value             = LogInInfo.UserID;
                com.ExecuteNonQuery();
                trans.Commit();
            }
            catch (Exception ex)
            {
                trans.Rollback();
                throw new Exception(ex.Message);
            }
        }
Пример #21
0
        public List <XMProductAddCount> GetXMProductByIDsCount(List <int> IDs, int CombinationID)
        {
            var query = from info in this._context.XMProducts
                        join count in this._context.XMProductCombinations
                        on info.Id equals count.ProductID into Counts
                        from counts in Counts.DefaultIfEmpty()
                        where info.IsEnable == false &&
                        counts.IsEnabled == false &&
                        IDs.Contains(info.Id) &&
                        counts.CombinationID == CombinationID
                        select new XMProductAddCount
            {
                Id                     = info.Id,
                BrandTypeId            = info.BrandTypeId,
                ProductName            = info.ProductName,
                ManufacturersCode      = info.ManufacturersCode,
                Specifications         = info.Specifications,
                ManufacturersInventory = info.ManufacturersInventory,
                WarningQuantity        = info.WarningQuantity,
                ProductColors          = info.ProductColors,
                ProductUnit            = info.ProductUnit,
                ProductWeight          = info.ProductWeight,
                ProductVolume          = info.ProductVolume,
                IsPremiums             = info.IsPremiums,
                Count                  = counts.Count,
                IsEnable               = info.IsEnable,
                CreateID               = info.CreateID,
                CreateDate             = info.CreateDate,
                UpdateID               = info.UpdateID,
                UpdateDate             = info.UpdateDate
            };

            return(query.ToList());
        }
Пример #22
0
        public SmugglerResult()
        {
            _sw       = Stopwatch.StartNew();
            _messages = new List <string>();

            /*
             *  NOTE:
             *
             *  About to add new/change property below?
             *
             *  Please remember to include this property in SmugglerProgress class
             */

            DatabaseRecord            = new DatabaseRecordProgress();
            Documents                 = new CountsWithSkippedCountAndLastEtag();
            RevisionDocuments         = new CountsWithLastEtag();
            Tombstones                = new CountsWithLastEtag();
            Conflicts                 = new CountsWithLastEtag();
            Identities                = new CountsWithLastEtag();
            Indexes                   = new Counts();
            CompareExchange           = new CountsWithLastEtag();
            Counters                  = new CountsWithLastEtag();
            CompareExchangeTombstones = new Counts();
            Subscriptions             = new Counts();
            _progress                 = new SmugglerProgress(this);
        }
Пример #23
0
 internal static async void MoveAsync(SmartItem[] items, string toPath)
 {
     Lock();
     for (int i = 0; i < items.Length; i++)
     {
         if (!IsConnected)
         {
             return;
         }
         if (await mainClient.MoveItemAsync(items[i], toPath))
         {
             if (items[i].IsFile)
             {
                 Counts.Files--;
             }
             else
             {
                 Counts.Folders--;
             }
             Counts.Update();
         }
     }
     items = null;
     UnLock();
 }
Пример #24
0
        public string Result()
        {
            string inputFileName  = "../../spec/" + Location;
            string outputFileName = "output/spec/" + Location;

            try
            {
                FileRunner runner = new FileRunner();
                runner.args(new string[] { inputFileName, outputFileName });
                runner.process();
                runner.output.Close();

                Counts counts = runner.fixture.counts;
                if ((counts.exceptions == 0) && (counts.wrong == 0))
                {
                    return("pass");
                }
                else
                {
                    return("fail: " + counts.right + " right, " + counts.wrong + " wrong, " + counts.exceptions + " exceptions");
                }
            }
            catch (IOException)
            {
                return("file not found: " + new FileInfo(inputFileName).FullName);
            }
        }
Пример #25
0
 public SpecProgress(string id, Counts counts, int step, int total) : base("spec-progress")
 {
     this.id = id;
     this.counts = counts;
     this.step = step;
     this.total = total;
 }
Пример #26
0
    private static Counts CallGetTotalAllocatedBytes(Counts previous, out long differenceBetweenPreciseAndImprecise)
    {
        long precise   = GetTotalAllocatedBytes(true);
        long imprecise = GetTotalAllocatedBytes(false);

        if (precise <= 0)
        {
            throw new Exception($"Bytes allocated is not positive, this is unlikely. precise = {precise}");
        }

        if (imprecise < precise)
        {
            throw new Exception($"Imprecise total bytes allocated less than precise, imprecise is required to be a conservative estimate (that estimates high). imprecise = {imprecise}, precise = {precise}");
        }

        if (previous.precise > precise)
        {
            throw new Exception($"Expected more memory to be allocated. previous.precise = {previous.precise}, precise = {precise}, difference = {previous.precise - precise}");
        }

        if (previous.imprecise > imprecise)
        {
            throw new Exception($"Expected more memory to be allocated. previous.imprecise = {previous.imprecise}, imprecise = {imprecise}, difference = {previous.imprecise - imprecise}");
        }

        differenceBetweenPreciseAndImprecise = imprecise - precise;
        return(new Counts(precise, imprecise));
    }
Пример #27
0
        public void DisplayResults_PassTableWithActions_BindToResultsGrid(string action, string expectedActionName, int sortOrder)
        {
            // Arrange
            const string ActionsColumn = "Action";
            const string TotalsColumn  = "Totals";
            const string SortColumn    = "sortOrder";
            const int    FirstRow      = 0;
            const int    LastRow       = 1;
            const int    Counts        = 1;

            var hashTable = new Hashtable();

            hashTable.Add(action, Counts);
            _testObject.SetFieldOrProperty("hUpdatedRecords", hashTable);
            // Act
            _testObject.Invoke("DisplayResults");

            // Assert
            GetProperty <Label>("MessageLabel").Text.ShouldBe("Import Results");
            var dataSource = GetProperty <DataGrid>("ResultsGrid").DataSource as DataTable;

            dataSource.ShouldNotBeNull();
            dataSource.ShouldSatisfyAllConditions(
                () => dataSource.Rows[FirstRow][ActionsColumn].ShouldBe(expectedActionName),
                () => dataSource.Rows[FirstRow][TotalsColumn].ShouldBe(Counts.ToString()),
                () => dataSource.Rows[FirstRow][SortColumn].ShouldBe(sortOrder.ToString()),
                () => dataSource.Rows[LastRow][ActionsColumn].ShouldBe("&nbsp;"),
                () => dataSource.Rows[LastRow][TotalsColumn].ShouldBe(" "),
                () => dataSource.Rows[LastRow][SortColumn].ShouldBe("8"));
        }
Пример #28
0
        public void add_two_counts()
        {
            var count1 = new Counts
            {
                Rights = 2,
                Wrongs = 3,
                Exceptions = 4,
                SyntaxErrors = 7
            };
            var count2 = new Counts
            {
                Rights = 7,
                Wrongs = 4,
                Exceptions = 10,
                SyntaxErrors = 14
            };

            count1.Add(count2);

            count1.Rights.ShouldBe(9);
            count1.Wrongs.ShouldBe(7);
            count1.Exceptions.ShouldBe(14);
            count1.SyntaxErrors.ShouldBe(21);

            count2.Rights.ShouldBe(7);
            count2.Wrongs.ShouldBe(4);
            count2.Exceptions.ShouldBe(10);
            count2.SyntaxErrors.ShouldBe(14);
        }
Пример #29
0
    public static void TestLohSohConcurrently()
    {
        List <Thread>        threads = new List <Thread>();
        ManualResetEventSlim me      = new ManualResetEventSlim();
        int threadNum = Environment.ProcessorCount + Environment.ProcessorCount / 2;

        for (int i = 0; i < threadNum; i++)
        {
            Thread thr = new Thread(() =>
            {
                me.Wait();
                Counts previous = default(Counts);
                for (int i = 0; i < 2; ++i)
                {
                    s_stash  = new byte[123456];
                    previous = CallGetTotalAllocatedBytes(previous);
                    s_stash  = new byte[1234];
                    previous = CallGetTotalAllocatedBytes(previous);
                }
            });

            thr.Start();
            threads.Add(thr);
        }

        me.Set();

        foreach (var thr in threads)
        {
            thr.Join();
        }
    }
Пример #30
0
        public void modify_counts_when_in_success_state()
        {
            var counts = new Counts();
            CellResult.Success("a").Tabulate(counts);

            counts.ShouldEqual(1, 0, 0, 0);
        }
Пример #31
0
        public override int GetHashCode()
        {
            int hashCode = -1677007764;

            if (Context != null)
            {
                hashCode += Context.GetHashCode();
            }

            if (Errors != null)
            {
                hashCode += Errors.GetHashCode();
            }

            if (Counts != null)
            {
                hashCode += Counts.GetHashCode();
            }

            if (Cursor != null)
            {
                hashCode += Cursor.GetHashCode();
            }

            return(hashCode);
        }
Пример #32
0
        public void modify_counts_when_ok()
        {
            var counts = new Counts();
            CellResult.Ok("a").Tabulate(counts);

            counts.ShouldEqual(0, 0, 0, 0);
        }
        private void theCountsShouldBe(int right, int wrong, int ex, int syntax)
        {
            var counts = new Counts();
            theResult.Tabulate(counts);

            counts.ShouldEqual(right, wrong, ex, syntax);
        }
Пример #34
0
        public void add_two_counts()
        {
            var count1 = new Counts
            {
                Rights       = 2,
                Wrongs       = 3,
                Exceptions   = 4,
                SyntaxErrors = 7
            };
            var count2 = new Counts
            {
                Rights       = 7,
                Wrongs       = 4,
                Exceptions   = 10,
                SyntaxErrors = 14
            };

            count1.Add(count2);

            count1.Rights.ShouldBe(9);
            count1.Wrongs.ShouldBe(7);
            count1.Exceptions.ShouldBe(14);
            count1.SyntaxErrors.ShouldBe(21);

            count2.Rights.ShouldBe(7);
            count2.Wrongs.ShouldBe(4);
            count2.Exceptions.ShouldBe(10);
            count2.SyntaxErrors.ShouldBe(14);
        }
Пример #35
0
        private static void OnItemStatusChanged(SmartItem item)
        {
            string status = item.Status.ToString();

            if (status.Ends("Error"))
            {
                item.OptColor = SolidColors.DarkRed;
            }
            else if (status.Equal("Ignored"))
            {
                item.OptColor = SolidColors.DarkOrange;
            }
            else if (status.Ends("ed"))
            {
                item.OptColor = SolidColors.SolidBlue;
            }
            else
            {
                item.OptColor = SolidColors.DarkGreen;
            }
            item.Operation = AppLanguage.Get("LangOperation" + status);

            switch (item.Status)
            {
            case ItemStatus.Uploading: Counts.Files++; Counts.Update(); break;

            case ItemStatus.Created: Counts.Folders++; Counts.Update(); break;
            }
        }
Пример #36
0
        public UpdateCounts(int id)
        {
            conn = DependencyService.Get <ISQLite>().GetSQLiteConnection();
            InitializeComponent();
            counts = new Counts();
            //var allData = (from cnt in conn.Table<Counts>() select cnt);
            //var fltList = from ag in allData where ag.ID.Equals(cntId) select ag;

            var countById = conn.Table <Counts>().Where(x => x.ID == id).Single();

            cntId = id;

            Id.Text   = id.ToString();
            Name.Text = countById.Name;

            DatePicker.Date = DateTime.Parse(countById.Date);

            var taskName = (from tsk in conn.Table <MyTask>() select tsk.MyTaskName).ToList();

            TaskName.ItemsSource = taskName;

            TaskName.SelectedItem = countById.TaskName;

            Count.Text = countById.Count.ToString();
        }
Пример #37
0
        public void modify_counts_when_in_missing_state()
        {
            var counts = new Counts();

            CellResult.Missing("a").Tabulate(counts);

            counts.ShouldEqual(0, 0, 0, 1);
        }
Пример #38
0
        public void modify_counts_when_in_error_state()
        {
            var counts = new Counts();

            CellResult.Error("a","bad message").Tabulate(counts);

            counts.ShouldEqual(0, 0, 1, 0);
        }
Пример #39
0
 public void Tabulate(Counts counts)
 {
     counts.Increment(status);
     if (cells != null)
     {
         cells.Each(x => counts.Increment(x.Status));
     }
 }
 /// <summary>
 /// Constructor that accepts values for all mandatory fields
 /// </summary>
 ///<param name="schoolInfoRefId">Reference to SchoolInfo</param>
 ///<param name="date">Date the count is taken.</param>
 ///<param name="program">A Program</param>
 ///<param name="counts">A Counts</param>
 ///
 public FoodserviceStaffEnrollmentCount( string schoolInfoRefId, DateTime? date, Program program, Counts counts )
     : base(Adk.SifVersion, FoodDTD.FOODSERVICESTAFFENROLLMENTCOUNT)
 {
     this.SchoolInfoRefId = schoolInfoRefId;
     this.Date = date;
     this.Program = program;
     this.Counts = counts;
 }
Пример #41
0
        public void modify_counts_when_in_failure_state()
        {
            var counts = new Counts();

            CellResult.Failure("a","foo").Tabulate(counts);

            counts.ShouldEqual(0, 1, 0, 0);
        }
 public void Tabulate(Counts counts)
 {
     counts.Rights += _matches.Count;
     counts.Wrongs += _missing.Count;
     counts.Wrongs += _extras.Count;
     counts.Wrongs += _wrongOrders.Count;
     
 }
Пример #43
0
        public void counts_are_all_zero_on_construction()
        {
            var counts = new Counts();

            counts.Wrongs.ShouldBe(0);
            counts.Rights.ShouldBe(0);
            counts.Exceptions.ShouldBe(0);
            counts.SyntaxErrors.ShouldBe(0);
        }
 /// <summary>
 /// Constructor that accepts values for all mandatory fields
 /// </summary>
 ///<param name="refId">GUID that identifies the daily meal sales object</param>
 ///<param name="schoolInfoRefId">School for which the sales object applies</param>
 ///<param name="date">Date on which the sales occurred.</param>
 ///<param name="program">A Program</param>
 ///<param name="counts">A Counts</param>
 ///
 public FoodserviceStaffMealCounts( string refId, string schoolInfoRefId, DateTime? date, Program program, Counts counts )
     : base(Adk.SifVersion, FoodDTD.FOODSERVICESTAFFMEALCOUNTS)
 {
     this.RefId = refId;
     this.SchoolInfoRefId = schoolInfoRefId;
     this.Date = date;
     this.Program = program;
     this.Counts = counts;
 }
Пример #45
0
        public static void ShouldEqual(this Counts counts, int rights, int wrongs, int exceptions, int syntaxErrors)
        {
            var expected = new Counts
            {
                Rights = rights,
                Wrongs = wrongs,
                Exceptions = exceptions,
                SyntaxErrors = syntaxErrors
            };

            counts.ShouldBe(expected);
        }
Пример #46
0
        public void modify_increments()
        {
            var counts = new Counts();

            new StepResult("1", ResultStatus.ok).Tabulate(counts);
            counts.ShouldEqual(0, 0, 0, 0);

            new StepResult("1", ResultStatus.success).Tabulate(counts);
            counts.ShouldEqual(1, 0, 0, 0);

            new StepResult("1", ResultStatus.failed).Tabulate(counts);
            counts.ShouldEqual(1, 1, 0, 0);

            new StepResult("1", new NotImplementedException()).Tabulate(counts);
            counts.ShouldEqual(1, 1, 1, 0);
        }
        public void LurchTableDemo()
        {
            var counts = new Counts();
            //Queue where producer helps when queue is full
            using (var queue = new LurchTable<string, int>(LurchTableOrder.Insertion, 10))
            {
                var stop = new ManualResetEvent(false);
                queue.ItemRemoved += kv =>
                    {
                        Interlocked.Increment(ref counts.Dequeued);
                        Console.WriteLine("[{0}] - {1}", Thread.CurrentThread.ManagedThreadId, kv.Key);
                    };
                //start some threads eating queue:
                var thread = new Thread(() => 
                {
                    while (!stop.WaitOne(0))
                    {
                        KeyValuePair<string, int> kv;
                        while (queue.TryDequeue(out kv))
                            continue;
                    }
                })
                    { Name = "worker", IsBackground = true };
                thread.Start();

                var names = Directory.GetFiles(Path.GetTempPath(), "*", SearchOption.AllDirectories);
                if (names.Length < 1) throw new Exception("Not enough trash in your temp dir.");
                var loops = Math.Max(1, 100/names.Length);
                for(int i=0; i < loops; i++)
                    foreach (var name in names)
                    {
                        Interlocked.Increment(ref counts.Queued);
                        queue[name] = i;
                    }

                //help empty the queue
                KeyValuePair<string, int> tmp;
                while (queue.TryDequeue(out tmp))
                    continue;
                //shutdown
                stop.Set();
                thread.Join();
            }

            Assert.AreEqual(counts.Queued, counts.Dequeued);
        }
Пример #48
0
 public void AssertEndCounts(Counts expectedCounts)
 {
     AssertEndCount(Counts.Index.Element, expectedCounts, "elements");
     AssertEndCount(Counts.Index.Sequence, expectedCounts, "sequences");
     AssertEndCount(Counts.Index.Choice, expectedCounts, "choices");
     AssertEndCount(Counts.Index.All, expectedCounts, "alls");
     AssertEndCount(Counts.Index.Group, expectedCounts, "groups");
     AssertEndCount(Counts.Index.SimpleType, expectedCounts, "simple types");
     AssertEndCount(Counts.Index.SimpleTypeRestriction, expectedCounts, "simple type restrictions");
     AssertEndCount(Counts.Index.SimpleTypeUnion, expectedCounts, "simple type unions");
     AssertEndCount(Counts.Index.SimpleTypeList, expectedCounts, "simple type lists");
     AssertEndCount(Counts.Index.ComplexType, expectedCounts, "complex types");
     AssertEndCount(Counts.Index.Attribute, expectedCounts, "attributes");
     AssertEndCount(Counts.Index.Any, expectedCounts, "anys");
     AssertEndCount(Counts.Index.AnyAttribute, expectedCounts, "anyAttributes");
     AssertEndCount(Counts.Index.SimpleContentExtension, expectedCounts, "simple content extensions");
     AssertEndCount(Counts.Index.ComplexContentExtension, expectedCounts, "complex content extensions");
     AssertEndCount(Counts.Index.ComplexContentRestriction, expectedCounts, "complex content restrictions");
 }
Пример #49
0
        public void modify_increments_with_cell_results()
        {
            var result = new StepResult("foo", ResultStatus.ok)
            {
                cells = new[]
                {
                    CellResult.Error("a", "bad!"),
                    CellResult.Error("b", "worse!"),
                    CellResult.Success("c"),
                    CellResult.Failure("d", "different"),
                    CellResult.Failure("e", "different"),
                    CellResult.Failure("f", "different"),
                }
            };

            var counts = new Counts();
            result.Tabulate(counts);

            counts.ShouldEqual(1, 3, 2, 0);
        }
Пример #50
0
 private static void AssertCountsAreEqual(Counts.Index index, Counts expectedCounts, Counts testedCounts, string countName)
 {
     Assert.AreEqual(expectedCounts.Get(index), testedCounts.Get(index), "Handler received wrong number of " + countName);
 }
Пример #51
0
 public void Tabulate(Counts counts)
 {
     counts.Increment(Status);
 }
Пример #52
0
 private void UpdateCounters()
 {
   UIPost(ShowUpdating);
   try
   {
     var newCounts = GetCurrentCodeContractCounters();
     if (this.counts.numRuns == 0)
     {
       this.counts.numRuns = newCounts.numRuns;
       PostUpdateCount(); // likely startup had timeout, so this is startup
     }
     if (this.counts.numUsers == 0)
     {
       this.counts.numUsers = newCounts.numUsers;
       PostUpdateCount(); // likely startup had timeout, so this is startup
     }
     if (this.counts.numFail == 0)
     {
       this.counts.numFail = newCounts.numFail;
       PostUpdateCount(); // likely startup had timeout, so this is startup
     }
     var diffs = this.latestDiffs = newCounts - this.counts;
     if (diffs.numRuns > 0)
     {
       this.counts.numRuns = newCounts.numRuns;
       PostUpdateCount();
       PlayWavResource("notify.wav", true);
     }
     while (diffs.numUsers > 0)
     {
       this.counts.numUsers++;
       diffs.numUsers--;
       PostUpdateCount();
       PlayWavResource("tada.wav", true);
     }
     if (diffs.numFail > 0)
     {
       this.counts.numFail = newCounts.numFail;
       PostUpdateCount();
       PlayWavResource("fail.wav", true);
     }
   }
   finally
   {
     UIPost(HideUpdating);
   }
 }
Пример #53
0
        public void reset_clears_all_counts_to_zero()
        {
            var count1 = new Counts
            {
                Rights = 2,
                Wrongs = 3,
                Exceptions = 4,
                SyntaxErrors = 7
            };
            count1.Reset();

            count1.ShouldEqual(0, 0, 0, 0);
        }
Пример #54
0
        /// <summary>
        /// Calculate the inserted, updated, deleted and unchanged counts for the given nodes
        /// </summary>
        private Counts GetCounts(XNode[] original, XNode[] updated)
        {
            var counts = new Counts();

            // Check for attribute changes
            foreach (var child in updated)
            {
                if (child.Match == MatchType.Change)
                    counts.Updates++;

                if (child.Match == MatchType.NoMatch)
                    counts.Inserts++;

                if (child.Match == MatchType.Match)
                    counts.Unchanged++;

            }
            foreach (var child in original)
            {
                if (child.Match == MatchType.NoMatch)
                    counts.Deletes++;
            }

            return counts;
        }
        /// <summary>
        /// Publishes the list item.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="list">The list.</param>
        /// <param name="test">If true test the change only (don't make any changes).</param>
        /// <param name="source">The source.</param>
        /// <param name="comment">The comment.</param>
        /// <param name="filterExpression">The filter expression.</param>
        public void PublishListItem(SPListItem item, SPList list, bool test, string source, string comment, string filterExpression)
        {
            if (TaskCounts == null)
                TaskCounts = new Counts();

            string title = item.ID.ToString();
            if (item.Fields.ContainsField("Title"))
                title = item.Title;

            try
            {
                item = item.ParentList.GetItemById(item.ID);
                if (item.File == null && !string.IsNullOrEmpty(filterExpression))
                    return;

                if (item.File != null)
                {
                    if (!string.IsNullOrEmpty(filterExpression))
                    {
                        string fileName = item.File.Name;
                        Regex regex = new Regex(filterExpression, RegexOptions.IgnoreCase);
                        if (!regex.IsMatch(fileName))
                            return;
                    }

                    // We first need to handle the case in which we have a file which means that
                    // we have to deal with the possibility that the file may be checked out.
                    if (item.Level == SPFileLevel.Checkout)
                    {
                        // The file is checked out so we now need to check it in - we'll do a major
                        // checkin which will result in it being published.
                        if (!test)
                        {
                            item.File.CheckIn(comment??"Checked in by " + source, SPCheckinType.MajorCheckIn);
                            // We need to get the File's version of the SPListItem so that we get the changes.
                            // Calling item.Update() will fail because the file is no longer checked out.
                            // If workflow is supported this should now be in a pending state.
                            // Re-retrieve the item to avoid save conflict errors.
                            item = item.ParentList.GetItemById(item.ID);
                        }
                        TaskCounts.Checkin++;
                        TaskCounts.Publish++; // The major checkin causes it to be published so we'll track that as well.
                        Logger.Write("Checked in item: {0} ({1})", title, item.Url);
                    }
                    else if (item.Level == SPFileLevel.Draft && item.ModerationInformation == null)
                    {
                        // The file isn't checked out but it is in a draft state so we need to publish it.
                        if (!test)
                        {
                            if (Utilities.IsCheckedOut(item))
                            {
                                item.File.CheckIn(comment ?? "Checked in by " + source, SPCheckinType.MajorCheckIn);
                                TaskCounts.Checkin++;
                                Logger.Write("Checked in item: {0} ({1})", title, item.Url);
                            }
                            if (item.ParentList.EnableMinorVersions)
                                item.File.Publish(comment ?? "Published by " + source);
                            // We need to get the File's version of the SPListItem so that we get the changes.
                            // Calling item.Update() will fail because the file is no longer checked out.
                            // If workflow is supported this should now be in a pending state.
                            // Re-retrieve the item to avoid save conflict errors.
                            item = item.ParentList.GetItemById(item.ID);
                        }
                        TaskCounts.Publish++;
                        Logger.Write("Published item: {0} ({1})", title, item.Url);
                    }
                    else if (item.Level == SPFileLevel.Published && Utilities.IsCheckedOut(item))
                    {
                        // This technically shouldn't be possible but apparently it is.
                        if (!test)
                        {
                            item.File.CheckIn(comment ?? "Checked in by " + source, SPCheckinType.MajorCheckIn);
                            if (item.ParentList.EnableMinorVersions)
                                item.File.Publish(comment ?? "Published by " + source);
                            item = item.ParentList.GetItemById(item.ID);
                        }
                        TaskCounts.Checkin++;
                        Logger.Write("Checked in item: {0} ({1})", title, item.Url);
                        TaskCounts.Publish++;
                        Logger.Write("Published item: {0} ({1})", title, item.Url);
                    }
                }
            }
            catch (Exception ex)
            {
                TaskCounts.Errors++;
                Logger.WriteException(new System.Management.Automation.ErrorRecord(new SPException("An error occured checking in an item", ex), null, System.Management.Automation.ErrorCategory.NotSpecified, item));
            }

            if (item.ModerationInformation != null)
            {
                // If ModerationInformation is not null then the item supports content approval.
                if (item.File == null &&
                    (item.ModerationInformation.Status == SPModerationStatusType.Draft ||
                    item.ModerationInformation.Status == SPModerationStatusType.Pending))
                {
                    // If content approval is supported but no file is associated with the item then we have
                    // to treat it differently.  We simply set the status information directly.
                    try
                    {
                        if (!test)
                        {
                            // Because the SPListItem object has no direct approval method we have to
                            // set the information directly (there's no SPFile object to use).
                            CancelWorkflows(false, list, item);
                            item.ModerationInformation.Status = SPModerationStatusType.Approved;
                            item.ModerationInformation.Comment = comment ?? "Approved by " + source;
                            item.Update(); // Because there's no SPFile object we don't have to worry about the item being checkedout for this to succeed as you can't check it out.
                            // Re-retrieve the item to avoid save conflict errors.
                            item = item.ParentList.GetItemById(item.ID);
                        }
                        TaskCounts.Approve++;
                        Logger.Write("Approved item: {0} ({1})", title, item.Url);
                    }
                    catch (Exception ex)
                    {
                        TaskCounts.Errors++;
                        Logger.WriteException(new System.Management.Automation.ErrorRecord(new SPException("An error occured approving an item.", ex), null, System.Management.Automation.ErrorCategory.NotSpecified, item));
                    }
                }
                else
                {
                    // The item supports content approval and we have an SPFile object to work with.
                    try
                    {
                        if (item.ModerationInformation.Status == SPModerationStatusType.Pending)
                        {
                            // The item is pending so it's already been published - we just need to approve.
                            if (!test)
                            {
                                // Cancel any workflows.
                                CancelWorkflows(false, list, item);
                                item.File.Approve(comment ?? "Approved by " + source);
                                // Re-retrieve the item to avoid save conflict errors.
                                item = item.ParentList.GetItemById(item.ID);
                            }
                            TaskCounts.Approve++;
                            Logger.Write("Approved item: {0} ({1})", title, item.Url);
                        }
                    }
                    catch (Exception ex)
                    {
                        TaskCounts.Errors++;
                        Logger.WriteException(new System.Management.Automation.ErrorRecord(new SPException("An error occured approving an item.", ex), null, System.Management.Automation.ErrorCategory.NotSpecified, item));
                    }

                    try
                    {
                        if (item.ModerationInformation.Status == SPModerationStatusType.Draft)
                        {
                            // The item is in a draft state so we have to first publish it and then approve it.
                            if (!test)
                            {
                                if (Utilities.IsCheckedOut(item))
                                {
                                    item.File.CheckIn(comment ?? "Checked in by " + source, SPCheckinType.MajorCheckIn);
                                    TaskCounts.Checkin++;
                                    Logger.Write("Checked in item: {0} ({1})", title, item.Url);
                                }
                                if (item.ParentList.EnableMinorVersions)
                                    item.File.Publish(comment ?? "Published by " + source);
                                // Cancel any workflows.
                                CancelWorkflows(test, list, item);
                                item.File.Approve(comment ?? "Approved by " + source);
                                // We don't need to re-retrieve the item as we're now done with it.
                            }
                            TaskCounts.Publish++;
                            TaskCounts.Approve++;
                            Logger.Write("Published item: {0} ({1})", title, item.Url);
                        }
                    }
                    catch (Exception ex)
                    {
                        TaskCounts.Errors++;
                        Logger.WriteException(new System.Management.Automation.ErrorRecord(new SPException("An error occured approving an item.", ex), null, System.Management.Automation.ErrorCategory.NotSpecified, item));
                    }
                }
            }
        }
Пример #56
0
 private void AssertEndCount(Counts.Index index, Counts expectedCounts, string countName)
 {
     AssertCountsAreEqual(index, expectedCounts, endCounts, "end " + countName);
 }