Example #1
0
 public static void Assert(bool condition, string text = "no description")
 {
     Trace.Assert(condition, $"UIExtenderEx failure: {text}.");
 }
        public void Run()
        {
            var collection = new InMemoryFileCollection();

            using (var kvDb = new KeyValueDB(collection, new NoCompressionStrategy(), 100 * 1024 * 1024))
            {
                ulong itemsCount = 0;
                using (var objDb = new ObjectDB())
                {
                    objDb.Open(kvDb, false);

                    Console.WriteLine("started generating");
                    using (var tr = objDb.StartWritingTransaction().Result)
                    {
                        var objects = tr.Singleton <SmallObjects>();
                        while (true)
                        {
                            objects.Items.Add(itemsCount, new SmallObject()
                            {
                                Id = itemsCount, Label = "bu"
                            });

                            if (itemsCount % 1_000_000 == 0)
                            {
                                Console.WriteLine("Generated {0}", itemsCount);
                            }

                            if (itemsCount % 1000 == 0 && collection.GetCount() == 20)
                            {
                                break;
                            }

                            itemsCount++;
                        }

                        tr.Commit();
                    }
                    Console.WriteLine("finished generating");


                    using (var tr = objDb.StartWritingTransaction().Result)
                    {
                        var objects = tr.Singleton <SmallObjects>();
                        itemsCount = (ulong)objects.Items.Count;
                        tr.Commit();
                    }

                    Console.WriteLine("removing items started");
                    using (var tr = objDb.StartWritingTransaction().Result)
                    {
                        var objects = tr.Singleton <SmallObjects>();
                        for (ulong i = 0; i < itemsCount / 5; i++)
                        {
                            if (i % 2 == 0)
                            {
                                continue;
                            }

                            objects.Items.Remove(i);
                        }

                        tr.Commit();
                    }

                    Console.WriteLine("removing items finished");

                    var transactionCreationStarted = new ManualResetEventSlim(false);
                    var compactionFinished         = new ManualResetEventSlim(false);

                    Task.Run(() =>
                    {
                        Console.WriteLine("Started waiting for transaction creating");
                        transactionCreationStarted.Wait();
                        Console.WriteLine("Started Compacting");
                        Trace.Assert(kvDb.Compact(CancellationToken.None));
                        Console.WriteLine("Finished Compacting");
                        compactionFinished.Set();
                    });

                    Console.WriteLine("Started concurrent transaction creation");

                    long      msMax      = 0;
                    long      average    = 0;
                    long      iterations = 0;
                    Stopwatch watch      = new Stopwatch();

                    while (true)
                    {
                        var compactionFinishedBeforeLasttransaction = compactionFinished.IsSet;
                        iterations++;
                        watch.Start();
                        var task = objDb.StartWritingTransaction();
                        if (!transactionCreationStarted.IsSet)
                        {
                            transactionCreationStarted.Set();
                        }

                        task.AsTask().Wait();

                        var ms = watch.ElapsedMilliseconds;
                        average += ms;
                        msMax    = Math.Max(ms, msMax);
                        watch.Reset();
                        using (var tr = task.Result)
                        {
                            tr.Commit();
                        }

                        if ((compactionFinishedBeforeLasttransaction && compactionFinished.IsSet))
                        {
                            break;
                        }
                    }
                    Console.WriteLine("Finished concurrent transaction creation, longest transaction create time was {0}ms, " +
                                      "average {1}ms, iterations {2}", msMax, average / (double)iterations, iterations);
                }
            }
        }
Example #3
0
 public double ToDouble()
 {
     Trace.Assert((this.Row == 1) && (this.Col == 1));
     return(this.m_data[0, 0]);
 }
Example #4
0
        public LowLevelDecoderNative(mfxVideoParam mfxDecParamsX,
                                     mfxVideoParam?VPPParamsX = null,
                                     mfxIMPL impl             = mfxIMPL.MFX_IMPL_AUTO)
        {
            mfxVideoParam tmpMfxVideoParam;

            if (VPPParamsX.HasValue)
            {
                tmpMfxVideoParam = VPPParamsX.Value;
            }
            else
            {
                tmpMfxVideoParam.AsyncDepth = 1;
                tmpMfxVideoParam.IOPattern  = IOPattern.MFX_IOPATTERN_IN_VIDEO_MEMORY | IOPattern.MFX_IOPATTERN_OUT_VIDEO_MEMORY;
                tmpMfxVideoParam.vpp.In     = mfxDecParamsX.mfx.FrameInfo;
                tmpMfxVideoParam.vpp.Out    = mfxDecParamsX.mfx.FrameInfo;
            }


            mfxStatus sts;

            session = new mfxSession();
            var ver = new mfxVersion()
            {
                Major = 1, Minor = 3
            };

            fixed(mfxSession *s = &session)
            sts = UnsafeNativeMethods.MFXInit(impl, &ver, s);

            QuickSyncStatic.ThrowOnBadStatus(sts, "MFXInit");
            //deviceSetup = new DeviceSetup(session, false);

            h = NativeLLDecoderUnsafeNativeMethods.NativeDecoder_New();
            Trace.Assert(h != IntPtr.Zero);


            shared = (DecoderShared *)h;
            //Console.WriteLine("mfxbs offset in C# {0}", (UInt64)(&(shared->mfxBS)) - (UInt64)shared);
            //Console.WriteLine("warningCount offset in C# {0}", (UInt64)(&(shared->warningCount)) - (UInt64)shared);
            //Console.WriteLine("sizeof(mfxBitstream) {0}", sizeof(mfxBitstream));
            //Console.WriteLine("sizeof(DecoderShared) {0}", sizeof(DecoderShared));
            //Console.WriteLine("shared->safety {0}", shared->safety);

            Trace.Assert(shared->safety == sizeof(DecoderShared));

            shared->mfxBS.MaxLength  = 1000000;
            shared->mfxBS.Data       = Marshal.AllocHGlobal((int)shared->mfxBS.MaxLength);
            shared->mfxBS.DataLength = 0;
            shared->mfxBS.DataOffset = 0;



            sts = NativeLLDecoderUnsafeNativeMethods.NativeDecoder_Init(h, session, &mfxDecParamsX, &tmpMfxVideoParam);
            QuickSyncStatic.ThrowOnBadStatus(sts, nameof(NativeLLDecoderUnsafeNativeMethods.NativeDecoder_Init));


            //mfxFrameSurface1 aaa = *shared->foo1[0];
            //aaa.Data = new mfxFrameData();
            //File.WriteAllText("\\x\\a", Newtonsoft.Json.JsonConvert.SerializeObject(aaa,Formatting.Indented));

            // aaa = *shared->foo2[0];
            //aaa.Data = new mfxFrameData();
            //File.WriteAllText("\\x\\b", Newtonsoft.Json.JsonConvert.SerializeObject(aaa, Formatting.Indented));

            //aaa = *shared->foo3[0];
            //aaa.Data = new mfxFrameData();
            //File.WriteAllText("\\x\\c", Newtonsoft.Json.JsonConvert.SerializeObject(aaa, Formatting.Indented));

            //aaa = *shared->foo4[0];
            //aaa.Data = new mfxFrameData();
            //File.WriteAllText("\\x\\d", Newtonsoft.Json.JsonConvert.SerializeObject(aaa, Formatting.Indented));



            GetAndPrintWarnings();
        }
        private void ExecuteSetup(
            RelativePath setupDirectoryRelative = null,
            int?solutionChoice            = null,
            TargetPlatform targetPlatform = TargetPlatform.Core,
            ProjectFormat projectFormat   = ProjectFormat.Sdk,
            string nugetVersion           = null,
            string nukeVersion            = null,
            string buildDirectoryName     = null,
            string buildProjectName       = null)
        {
            var bootstrappingDirectory = RootDirectory / "bootstrapping";
            var setupFileName          = EnvironmentInfo.IsWin ? "setup.ps1" : "setup.sh";
            var workingDirectory       = TestOutputDirectory / (setupDirectoryRelative ?? string.Empty);

            FileSystemTasks.EnsureExistingDirectory(workingDirectory);
            var setupFileAbsolute = workingDirectory / setupFileName;

            var bootstrappingUri = EnvironmentInfo.IsWin ? new Uri(bootstrappingDirectory).AbsoluteUri : $"file://{bootstrappingDirectory}";
            var content          = File.ReadAllText(bootstrappingDirectory / setupFileName)
                                   .Replace("https://raw.githubusercontent.com/nuke-build/nuke/master/bootstrapping", bootstrappingUri)
                                   .Replace("[guid]::NewGuid().ToString().ToUpper()", "99351CF7-E7C8-45AE-8A5B-E3E964AC5F12".DoubleQuote())
                                   .Replace("$(python -c \"import uuid; print str(uuid.uuid4()).upper()\")", "99351CF7-E7C8-45AE-8A5B-E3E964AC5F12".DoubleQuote())
                                   .ReplaceRegex("\\$NukeVersion = \\$\\(Invoke.*", x => "$NukeVersion = \"1.3.3.7\"")
                                   .ReplaceRegex("NUKE_VERSION=\\$\\(curl.*", x => "NUKE_VERSION=\"1.3.3.7\"");

            File.WriteAllText(setupFileAbsolute, content);

            TestOutputHelper.WriteLine("Starting setup script...");
            var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName               = EnvironmentInfo.IsWin ? "powershell" : "bash",
                    Arguments              = setupFileAbsolute,
                    WorkingDirectory       = workingDirectory,
                    UseShellExecute        = false,
                    RedirectStandardInput  = true,
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true
                }
            };

            process.OutputDataReceived += (s, e) =>
            {
                Logger.Log(e.Data);
                TestOutputHelper.WriteLine("STD: " + e.Data);
            };
            process.ErrorDataReceived += (s, e) =>
            {
                Logger.Error(e.Data);
                TestOutputHelper.WriteLine("ERR: " + e.Data);
            };
            process.Start();
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            if (solutionChoice.HasValue)
            {
                process.StandardInput.WriteLine(solutionChoice.Value);
            }

            process.StandardInput.WriteLine(EnvironmentInfo.IsWin
                ? targetPlatform == TargetPlatform.Framework ? "F" : "C"
                : ((int)targetPlatform).ToString());

            if (targetPlatform == TargetPlatform.Framework)
            {
                process.StandardInput.WriteLine(EnvironmentInfo.IsWin
                    ? projectFormat == ProjectFormat.Legacy ? "L" : "S"
                    : ((int)projectFormat).ToString());

                process.StandardInput.WriteLine(nugetVersion);
            }

            if (targetPlatform == TargetPlatform.Core || projectFormat == ProjectFormat.Sdk)
            {
                process.StandardInput.WriteLine(nukeVersion);
            }

            process.StandardInput.WriteLine(buildDirectoryName);
            process.StandardInput.WriteLine(buildProjectName);

            process.WaitForExit();
            Trace.Assert(process.ExitCode == 0);

            File.WriteAllText(TestOutputDirectory / "structure.txt",
                              Directory.GetFiles(TestOutputDirectory, "*", SearchOption.AllDirectories)
                              .Select(x => GetRelativePath(TestOutputDirectory, x).Replace(oldChar: '\\', newChar: '/'))
                              .OrderBy(x => x.Length)
                              .ThenBy(x => x).JoinNewLine(PlatformFamily.Windows));
        }
Example #6
0
 public void Add(CatKind k, CatFxnType ft)
 {
     Trace.Assert(k.IsKindVar());
     Add(k.ToString(), ft);
 }
Example #7
0
        static void Main(string[] args)
        {
            string PreprocessForParsing(string line)
            {
                int index = line.IndexOf(" --");

                if (index != -1)
                {
                    line = line.Substring(0, index);
                }
                else if (line.StartsWith("--"))
                {
                    line = "";
                }
                return(line);
            }

            decimal ParsePercent(string s)
            {
                s = s.Trim();
                Trace.Assert(s.EndsWith("%"));
                s = s.Substring(0, s.Length - 1);
                return(decimal.Parse(s));
            }

            const bool allowMerging = true;

            // for unified decimal numbers parsing
            CultureInfo.DefaultThreadCurrentCulture   = CultureInfo.InvariantCulture;
            CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture;
            CultureInfo.CurrentCulture   = CultureInfo.InvariantCulture;
            CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture;
            var dtCulture = CultureInfo.GetCultureInfo("ru-RU");

            var lines                    = File.ReadAllLines(args[0]).Select(PreprocessForParsing).ToList();
            var startDt                  = DateTime.Parse(lines[0], dtCulture);
            var diffPerMonth             = decimal.Parse(lines[1]);
            var startingBalance          = decimal.Parse(lines[2]);
            var maxDepositDurationMonths = int.Parse(lines[3]);
            var taxPercent               = ParsePercent(lines[5]);
            var annualInflationPercent   = ParsePercent(lines[6]);
            // do not apply inflation to both deposits and diffPerMonth,
            // choose only one,
            // for reality diffPerMonth is chosen
            var depositPercents = lines[4].Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(ParsePercent).Prepend(0m)
                                  .Select(x =>
                                          (100m + x * (1m - (x == 0 ? 0 : taxPercent / 100m))) - 100m).ToList();

            decimal GetAmountWithPercent(Deposit deposit, DateTime?endDate = null)
            {
                endDate = endDate ?? deposit.EndDate;
                if (deposit.StartDate == null || endDate == null || depositPercents.Count == 0)
                {
                    return(deposit.Amount);
                }

                var months        = GetDepositMonthDiff(endDate.Value, deposit.StartDate.Value);
                var annualPercent = depositPercents[Math.Min(months, depositPercents.Count - 1)];

                return(deposit.Amount * (1m + annualPercent / 100m / 365m * (decimal)(endDate - deposit.StartDate).Value.TotalDays));
            }

            decimal WithdrawalToInitialAmount(Deposit deposit, decimal amount, DateTime?endDate = null)
            {
                endDate = endDate ?? deposit.EndDate;
                if (deposit.StartDate == null || endDate == null || depositPercents.Count == 0)
                {
                    return(amount);
                }

                var months        = GetDepositMonthDiff(endDate.Value, deposit.StartDate.Value);
                var annualPercent = depositPercents[Math.Min(months, depositPercents.Count - 1)];

                return(amount / (1m + annualPercent / 100m / 365m * (decimal)(endDate - deposit.StartDate).Value.TotalDays));
            }

            if (lines[7] != "")
            {
                throw new ArgumentException();
            }


            var oldDeposits = lines.Skip(8).Select(s => s.Split(new[] { ' ' }, 3))
                              .Select(ss => new Deposit(decimal.Parse(ss[1]))
            {
                EndDate = CorrectIfWeekend(DateTime.Parse(ss[0], dtCulture)), Name = ss.Length >= 3 ? ss[2] : ""
            }).OrderBy(x => x.EndDate)
                              .ToList();


            // output in usual format
            CultureInfo.DefaultThreadCurrentCulture   = CultureInfo.InstalledUICulture;
            CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InstalledUICulture;
            CultureInfo.CurrentCulture   = CultureInfo.InstalledUICulture;
            CultureInfo.CurrentUICulture = CultureInfo.InstalledUICulture;

            decimal newDepositsBalance = 0;

            var notReturnedDeposits = new List <Deposit>();
            var returnedNewDeposits = new List <Deposit>();

            decimal  balance = startingBalance;
            DateTime dt      = startDt;

            var oldDepositsSet = oldDeposits.ToHashSet(); // remove deposits while processing

            int newDepositsCounter = 0;

            DateTime CorrectIfWeekend(DateTime dt)
            {
                return(dt.DayOfWeek switch
                {
                    DayOfWeek.Saturday => dt.AddDays(2),
                    DayOfWeek.Sunday => dt.AddDays(1),
                    _ => dt
                });
            }
Example #8
0
        public static TRowSet CombineColumnValues(TRowSet rowSet1, TRowSet rowSet2)
        {
            if (rowSet1 == null)
            {
                return(rowSet2);
            }
            if (rowSet2 == null)
            {
                return(rowSet1);
            }
            if (rowSet1.Columns.Count != rowSet2.Columns.Count)
            {
                throw new ArgumentException("two rowset should have same columns");
            }
            TRowSet result = new TRowSet();

            result.Rows = new List <TRow>();

            result.Columns = new List <TColumn>();
            for (int i = 0; i < rowSet1.Columns.Count; i++)
            {
                TColumn combinedColumn = new TColumn();

                TColumn col1 = rowSet1.Columns[i];
                TColumn col2 = rowSet2.Columns[i];
                Trace.Assert(col1 != null && col2 != null);

                if (col1.__isset.binaryVal || col2.__isset.binaryVal)
                {
                    combinedColumn.BinaryVal = new TBinaryColumn()
                    {
                        Values = new List <byte[]>()
                    };
                    combinedColumn.BinaryVal.Values.AddRange((col1.BinaryVal?.Values) ?? new List <byte[]>());
                    combinedColumn.BinaryVal.Values.AddRange((col2.BinaryVal?.Values) ?? new List <byte[]>());
                    combinedColumn.__isset.binaryVal = true;
                }

                if (col1.__isset.boolVal || col2.__isset.boolVal)
                {
                    combinedColumn.BoolVal = new TBoolColumn()
                    {
                        Values = new List <bool>()
                    };
                    combinedColumn.BoolVal.Values.AddRange((col1.BoolVal?.Values) ?? new List <bool>());
                    combinedColumn.BoolVal.Values.AddRange((col2.BoolVal?.Values) ?? new List <bool>());
                    combinedColumn.__isset.boolVal = true;
                }

                if (col1.__isset.byteVal || col2.__isset.byteVal)
                {
                    combinedColumn.ByteVal = new TByteColumn()
                    {
                        Values = new List <sbyte>()
                    };
                    combinedColumn.ByteVal.Values.AddRange((col1.ByteVal?.Values) ?? new List <sbyte>());
                    combinedColumn.ByteVal.Values.AddRange((col2.ByteVal?.Values) ?? new List <sbyte>());
                    combinedColumn.__isset.binaryVal = true;
                }
                if (col1.__isset.doubleVal || col2.__isset.doubleVal)
                {
                    combinedColumn.DoubleVal = new TDoubleColumn()
                    {
                        Values = new List <double>()
                    };
                    combinedColumn.DoubleVal.Values.AddRange((col1.DoubleVal?.Values) ?? new List <double>());
                    combinedColumn.DoubleVal.Values.AddRange((col2.DoubleVal?.Values) ?? new List <double>());
                    combinedColumn.__isset.doubleVal = true;
                }
                if (col1.__isset.i16Val || col2.__isset.i16Val)
                {
                    combinedColumn.I16Val = new TI16Column()
                    {
                        Values = new List <short>()
                    };
                    combinedColumn.I16Val.Values.AddRange((col1.I16Val?.Values) ?? new List <short>());
                    combinedColumn.I16Val.Values.AddRange((col2.I16Val?.Values) ?? new List <short>());
                    combinedColumn.__isset.i16Val = true;
                }
                if (col1.__isset.i32Val || col2.__isset.i32Val)
                {
                    combinedColumn.I32Val = new TI32Column()
                    {
                        Values = new List <int>()
                    };
                    combinedColumn.I32Val.Values.AddRange((col1.I32Val?.Values) ?? new List <int>());
                    combinedColumn.I32Val.Values.AddRange((col2.I32Val?.Values) ?? new List <int>());
                    combinedColumn.__isset.i32Val = true;
                }
                if (col1.__isset.i64Val || col1.__isset.i64Val)
                {
                    combinedColumn.I64Val = new TI64Column()
                    {
                        Values = new List <long>()
                    };
                    combinedColumn.I64Val.Values.AddRange((col1.I64Val?.Values) ?? new List <long>());
                    combinedColumn.I64Val.Values.AddRange((col2.I64Val?.Values) ?? new List <long>());
                    combinedColumn.__isset.i64Val = true;
                }
                if (col1.__isset.stringVal || col2.__isset.stringVal)
                {
                    combinedColumn.StringVal = new TStringColumn()
                    {
                        Values = new List <string>()
                    };
                    combinedColumn.StringVal.Values.AddRange((col1.StringVal?.Values) ?? new List <string>());
                    combinedColumn.StringVal.Values.AddRange((col2.StringVal?.Values) ?? new List <string>());
                    combinedColumn.__isset.stringVal = true;
                }

                result.Columns.Add(combinedColumn);
            }
            return(result);
        }
        public virtual void Process(GameEventArgs handlerArgs)
        {
            var   source        = handlerArgs.Source;
            var   dests         = handlerArgs.Targets;
            var   readonlyCard  = handlerArgs.ReadonlyCard;
            var   inResponseTo  = handlerArgs.InResponseTo;
            var   card          = handlerArgs.Card;
            ICard attributeCard = new Card();

            Game.CurrentGame.SortByOrderOfComputation(Game.CurrentGame.CurrentPlayer, dests);
            foreach (var player in dests)
            {
                if (player.IsDead && IgnoreDeath)
                {
                    continue;
                }
                GameEventArgs args = new GameEventArgs();
                args.Source  = source;
                args.Targets = new List <Player>()
                {
                    player
                };
                args.Card         = card;
                args.ReadonlyCard = readonlyCard;
                try
                {
                    Game.CurrentGame.Emit(GameEvent.CardUsageTargetValidating, args);
                }
                catch (TriggerResultException e)
                {
                    Trace.Assert(e.Status == TriggerResult.End);
                    Game.CurrentGame.NotificationProxy.NotifyLogEvent(new LogEvent("CardInvalid", this, player), args.Targets, false);
                    continue;
                }
                try
                {
                    Game.CurrentGame.Emit(GameEvent.CardUsageBeforeEffected, args);
                }
                catch (TriggerResultException e)
                {
                    Trace.Assert(e.Status == TriggerResult.End);
                    continue;
                }
                if (player.IsDead)
                {
                    continue;
                }
                ReadOnlyCard newCard = new ReadOnlyCard(readonlyCard);
                Process(source, player, card, newCard, inResponseTo);
                if (newCard.Attributes != null)
                {
                    foreach (var attr in newCard.Attributes)
                    {
                        attributeCard[attr.Key] = attr.Value;
                    }
                }
            }
            if (attributeCard.Attributes != null)
            {
                foreach (var attr in attributeCard.Attributes)
                {
                    readonlyCard[attr.Key] = attr.Value;
                }
            }
        }
Example #10
0
        /// <summary>
        /// Event raised while the user is dragging a connector.
        /// </summary>
        private void ConnectorItem_Dragging(object source, ConnectorItemDraggingEventArgs e)
        {
            e.Handled = true;

            Trace.Assert((ConnectorItem)e.OriginalSource == this.draggedOutConnectorItem);

            Point mousePoint = Mouse.GetPosition(this);
            //
            // Raise an event so that application code can compute intermediate connection points.
            //
            var connectionDraggingEventArgs =
                new ConnectionDraggingEventArgs(ConnectionDraggingEvent, this,
                                                this.draggedOutNodeDataContext, this.draggingConnectionDataContext,
                                                this.draggedOutConnectorDataContext);

            RaiseEvent(connectionDraggingEventArgs);

            //
            // Figure out if the connection has been dragged over a connector.
            //

            ConnectorItem connectorDraggedOver            = null;
            object        connectorDataContextDraggedOver = null;
            bool          dragOverSuccess = DetermineConnectorItemDraggedOver(mousePoint, out connectorDraggedOver, out connectorDataContextDraggedOver);

            if (connectorDraggedOver != null)
            {
                //
                // Raise an event so that application code can specify if the connector
                // that was dragged over is valid or not.
                //
                var queryFeedbackEventArgs =
                    new QueryConnectionFeedbackEventArgs(QueryConnectionFeedbackEvent, this, this.draggedOutNodeDataContext, this.draggingConnectionDataContext,
                                                         this.draggedOutConnectorDataContext, connectorDataContextDraggedOver);

                RaiseEvent(queryFeedbackEventArgs);

                if (queryFeedbackEventArgs.FeedbackIndicator != null)
                {
                    //
                    // A feedback indicator was specified by the event handler.
                    // This is used to indicate whether the connection is good or bad!
                    //
                    AddFeedbackAdorner(connectorDraggedOver, queryFeedbackEventArgs.FeedbackIndicator);
                }
                else
                {
                    //
                    // No feedback indicator specified by the event handler.
                    // Clear any existing feedback indicator.
                    //
                    ClearFeedbackAdorner();
                }
            }
            else
            {
                //
                // Didn't drag over any valid connector.
                // Clear any existing feedback indicator.
                //
                ClearFeedbackAdorner();
            }
        }
Example #11
0
        private SortedSet <EnergyBound> BreadthFirstBranchAndBoundTraverse(ShapeConstraints constraints)
        {
            SortedSet <EnergyBound> front = new SortedSet <EnergyBound> {
                this.CalculateEnergyBound(constraints)
            };

            int      currentIteration        = 1;
            DateTime lastOutputTime          = startTime;
            int      processedConstraintSets = 0;

            while (!front.Min.Constraints.CheckIfSatisfied(this.maxCoordFreedom, this.maxWidthFreedom) && !this.IsStopping)
            {
                this.WaitIfPaused();

                EnergyBound parentLowerBound = front.Min;
                front.Remove(parentLowerBound);

                List <ShapeConstraints> expandedConstraints = parentLowerBound.Constraints.SplitMostFree(this.maxCoordFreedom, this.maxWidthFreedom);
                foreach (ShapeConstraints constraintsSet in expandedConstraints)
                {
                    EnergyBound lowerBound = this.CalculateEnergyBound(constraintsSet);
                    front.Add(lowerBound);

                    // Uncomment for strong invariants check
                    //ObjectBackgroundTerm[,] lowerBoundShapeTerm = new ObjectBackgroundTerm[this.segmentedImage.Width, this.segmentedImage.Height];
                    //for (int i = 0; i < this.segmentedImage.Width; ++i)
                    //    for (int j = 0; j < this.segmentedImage.Height; ++j)
                    //        lowerBoundShapeTerm[i, j] = CpuBranchAndBoundShapeTermsCalculator.CalculateShapeTerm(lowerBound.Constraints, new Point(i, j));
                    //ObjectBackgroundTerm[,] parentLowerBoundShapeTerm = new ObjectBackgroundTerm[this.segmentedImage.Width, this.segmentedImage.Height];
                    //for (int i = 0; i < this.segmentedImage.Width; ++i)
                    //    for (int j = 0; j < this.segmentedImage.Height; ++j)
                    //        parentLowerBoundShapeTerm[i, j] = CpuBranchAndBoundShapeTermsCalculator.CalculateShapeTerm(parentLowerBound.Constraints, new Point(i, j));
                    //for (int i = 0; i < this.segmentedImage.Width; ++i)
                    //    for (int j = 0; j < this.segmentedImage.Height; ++j)
                    //    {
                    //        Debug.Assert(lowerBoundShapeTerm[i, j].ObjectTerm >= parentLowerBoundShapeTerm[i, j].ObjectTerm - 1e-7);
                    //        Debug.Assert(lowerBoundShapeTerm[i, j].BackgroundTerm >= parentLowerBoundShapeTerm[i, j].BackgroundTerm - 1e-7);
                    //        //CalculateShapeTerm(lowerBound.Constraints, new Point(0, 67));
                    //        //CalculateShapeTerm(parentLowerBound.Constraints, new Point(0, 67));
                    //    }

                    // Lower bound should not decrease (check always, it's important!)
                    Trace.Assert(lowerBound.SegmentationEnergy >= parentLowerBound.SegmentationEnergy - 1e-6);
                    Trace.Assert(lowerBound.ShapeEnergy >= parentLowerBound.ShapeEnergy - 1e-6);

                    //this.CalculateEnergyBound(lowerBound.Constraints);
                    //this.CalculateEnergyBound(parentLowerBound.Constraints);

                    ++processedConstraintSets;
                }

                // Some debug output
                if (currentIteration % this.ProgressReportRate == 0)
                {
                    DateTime    currentTime = DateTime.Now;
                    EnergyBound currentMin  = front.Min;

                    DebugConfiguration.WriteDebugText(
                        "On iteration {0} front contains {1} constraint sets.", currentIteration, front.Count);
                    DebugConfiguration.WriteDebugText(
                        "Current lower bound is {0:0.0000} ({1:0.0000} + {2:0.0000}).",
                        currentMin.Bound,
                        currentMin.SegmentationEnergy,
                        currentMin.ShapeEnergy * this.ShapeEnergyWeight);
                    double processingSpeed = processedConstraintSets / (currentTime - lastOutputTime).TotalSeconds;
                    DebugConfiguration.WriteDebugText("Processing speed is {0:0.000} items per sec", processingSpeed);

                    double maxVertexConstraintsFreedom = currentMin.Constraints.VertexConstraints.Max(c => c.Freedom);
                    double maxEdgeConstraintsFreedom   = currentMin.Constraints.EdgeConstraints.Max(c => c.Freedom);
                    DebugConfiguration.WriteDebugText(
                        "Max vertex freedom: {0:0.00}, max edge freedom: {1:0.00}",
                        maxVertexConstraintsFreedom,
                        maxEdgeConstraintsFreedom);

                    DebugConfiguration.WriteDebugText("Elapsed time: {0}", DateTime.Now - this.startTime);

                    DebugConfiguration.WriteDebugText();

                    this.ReportBranchAndBoundProgress(front);

                    lastOutputTime          = currentTime;
                    processedConstraintSets = 0;
                }

                currentIteration += 1;
            }

            return(front);
        }
        /// <summary>
        /// Overload .NET framework Invoke method to provide extra XML schema validation function.
        /// </summary>
        /// <param name="methodName">The name of the XML Web service method.</param>
        /// <param name="parameters">An array of objects that contains the parameters to pass to the XML Web service. The order of the values in the array corresponds to the order of the parameters in the calling method of the derived class.</param>
        /// <returns>An array of objects that contains the return value and any reference or out parameters of the derived class method.</returns>
        public new object[] Invoke(string methodName, object[] parameters)
        {
            this.rawRequestXml  = null;
            this.rawResponseXml = null;
            WebResponse webResponse = null;
            WebRequest  webRequest  = null;

            object[]      objArray;
            StringBuilder sb = new StringBuilder();

            using (StringWriter sw = new StringWriter(sb))
            {
                Assembly        assembly    = Assembly.GetAssembly(typeof(ItemType));
                BaseRequestType requestInfo = (BaseRequestType)parameters[0];
                Type            type        = typeof(BaseRequestType);
                Type[]          types       = assembly.GetTypes();
                foreach (Type t in types)
                {
                    if (requestInfo.GetType().Equals(t))
                    {
                        type = t;
                    }
                }

                // Serialize the request.
                XmlSerializer xs = new XmlSerializer(type);
                xs.Serialize(sw, requestInfo);
            }

            try
            {
                // Creates a WebRequest for the specified uri.
                webRequest = this.GetWebRequest(this.baseURI.GetValue(this, null) as Uri);
                webRequest.PreAuthenticate = true;

                // Check PropertyInfo is null or not.
                Trace.Assert(this.basePendingSyncRequest != null, "PropertyInfo can not be NULL");

                // Sets the value of PendingSyncRequest.
                this.basePendingSyncRequest.SetValue(this, webRequest, null);

                // Invoke method of HttpWebClientProtocol.
                SoapClientMessage message       = this.InstanceInvokeBase("BeforeSerialize", webRequest, methodName, parameters) as SoapClientMessage;
                Stream            requestStream = webRequest.GetRequestStream();
                try
                {
                    Trace.Assert(this.setStream != null, "MethodInfo can not be NULL");
                    this.setStream.Invoke(message, new object[] { requestStream });
                    this.InstanceInvokeBase("Serialize", message);
                }
                finally
                {
                    requestStream.Close();
                }

                // Get the actual request xml by using xmlWriterHookInstance. The xmlWriterHookInstance is appended to the GetWriterForMessage method of the proxy class.
                string requestXmlString = this.xmlWriterHookInstance.Xml.ToString();

                // Load the actual request xml to an XmlElement
                if (!string.IsNullOrEmpty(requestXmlString))
                {
                    XmlDocument xmlDocOfReadRequest = new XmlDocument();
                    xmlDocOfReadRequest.LoadXml(requestXmlString);
                    this.rawRequestXml = xmlDocOfReadRequest.DocumentElement;
                    this.site.Log.Add(LogEntryKind.Debug, "The raw xml request message is:\r\n{0}", ((XmlElement)this.rawRequestXml).OuterXml);
                }

                webResponse = this.GetWebResponse(webRequest);
                HttpWebResponse httpWebResponse = (HttpWebResponse)webResponse;
                if (httpWebResponse.StatusCode != HttpStatusCode.OK)
                {
                    throw new WebException(httpWebResponse.StatusDescription);
                }

                Stream responseStream = null;
                try
                {
                    responseStream = webResponse.GetResponseStream();
                    string streamString = string.Empty;
                    using (StreamReader sr = new StreamReader(responseStream))
                    {
                        responseStream = null;

                        StringBuilder xmlString = new StringBuilder();
                        while (sr.Peek() > -1)
                        {
                            string strInput = sr.ReadLine();
                            xmlString.Append(strInput);
                        }

                        streamString = xmlString.ToString();
                        Trace.TraceInformation(streamString);
                    }

                    using (Stream streamObjRawXmlResponse = new MemoryStream(ASCIIEncoding.Default.GetBytes(streamString)))
                    {
                        XmlDocument responseXml = new XmlDocument();
                        responseXml.LoadXml(streamString);
                        this.rawResponseXml = responseXml.DocumentElement;
                        this.site.Log.Add(LogEntryKind.Debug, "The raw xml response message is:\r\n{0}", ((XmlElement)this.rawResponseXml).OuterXml);

                        objArray = this.InstanceInvoke("ReadResponse", message, webResponse, streamObjRawXmlResponse, false) as object[];

                        // Gets SOAP header from the response.
                        string soapHeader = this.GetSoapElement(responseXml, "Header");

                        // Gets SOAP body from the response.
                        string soapBody = this.GetSoapElement(responseXml, "Body");

                        this.XmlValidater(soapHeader, soapBody);

                        if (ExchangeServiceBinding.ServiceResponseEvent != null)
                        {
                            if (objArray[0] is BaseResponseMessageType)
                            {
                                ExchangeServiceBinding.ServiceResponseEvent(
                                    (BaseRequestType)parameters[0],
                                    (BaseResponseMessageType)objArray[0],
                                    this.IsSchemaValidated);
                            }
                        }
                    }
                }
                catch (XmlException exception)
                {
                    if (exception.Message.Contains("The following elements are not closed"))
                    {
                        throw new InvalidOperationException("The xml is not complete.", exception);
                    }
                    else
                    {
                        throw new InvalidOperationException("WebResponseBadXml", exception);
                    }
                }
                finally
                {
                    if (responseStream != null)
                    {
                        responseStream.Dispose();
                    }
                }
            }
            finally
            {
                if (webRequest == this.basePendingSyncRequest.GetValue(this, null) as WebRequest)
                {
                    if (this.basePendingSyncRequest.CanWrite)
                    {
                        this.basePendingSyncRequest.SetValue(this, null, null);
                    }
                }
            }

            return(objArray);
        }
Example #13
0
        public Character GetCurrentCharacter()
        {
            Trace.Assert(currentCharacterId != 0, "Current character ID was 0.");

            return(characters[currentCharacterId]);
        }
Example #14
0
 /// <summary>
 /// Critical runtime compatibility assert. Used when Bannerlord version is not compatible and it
 /// prevents runtime from functioning
 /// </summary>
 /// <param name="condition"></param>
 /// <param name="text"></param>
 public static void CompatAssert(bool condition, string text = "no description")
 {
     Trace.Assert(condition, $"Bannerlord compatibility failure: {text}.");
 }
Example #15
0
        protected sealed override void ExecuteCore(SelectedItemCollection selection)
        {
            //It only supports one item selected for now
            Trace.Assert(selection.Count == 1);

            XenAPI.Network network = (XenAPI.Network)selection.FirstAsXenObject;
            List <PIF>     pifs    = network.Connection.ResolveAll(network.PIFs);

            if (pifs.Count == 0)
            {
                // Should never happen as long as the caller is enabling the button correctly, but
                // it's possible in a tiny window across disconnecting.
                log.Error("Network has no PIFs");
                return;
            }

            // We just want one, so that we can name it.
            PIF pif = pifs[0];

            string msg = string.Format(Messages.DELETE_BOND_MESSAGE, pif.Name);

            bool will_disturb_primary   = NetworkingHelper.ContainsPrimaryManagement(pifs);
            bool will_disturb_secondary = NetworkingHelper.ContainsSecondaryManagement(pifs);

            if (will_disturb_primary)
            {
                Pool pool = Helpers.GetPool(network.Connection);
                if (pool != null && pool.ha_enabled)
                {
                    using (var dlg = new ThreeButtonDialog(
                               new ThreeButtonDialog.Details(
                                   SystemIcons.Error,
                                   string.Format(Messages.BOND_DELETE_HA_ENABLED, pif.Name, pool.Name),
                                   Messages.DELETE_BOND)))
                    {
                        dlg.ShowDialog(Parent);
                    }
                    return;
                }

                string message = string.Format(will_disturb_secondary ? Messages.BOND_DELETE_WILL_DISTURB_BOTH : Messages.BOND_DELETE_WILL_DISTURB_PRIMARY, msg);

                DialogResult result;
                using (var dlg = new ThreeButtonDialog(
                           new ThreeButtonDialog.Details(SystemIcons.Warning, message, Messages.DELETE_BOND),
                           "NetworkingConfigWarning",
                           new ThreeButtonDialog.TBDButton(Messages.BOND_DELETE_CONTINUE, DialogResult.OK),
                           ThreeButtonDialog.ButtonCancel))
                {
                    result = dlg.ShowDialog(Parent);
                }
                if (DialogResult.OK != result)
                {
                    return;
                }
            }
            else if (will_disturb_secondary)
            {
                DialogResult dialogResult;
                using (var dlg = new ThreeButtonDialog(
                           new ThreeButtonDialog.Details(SystemIcons.Warning, string.Format(Messages.BOND_DELETE_WILL_DISTURB_SECONDARY, msg), Messages.XENCENTER),
                           ThreeButtonDialog.ButtonOK,
                           ThreeButtonDialog.ButtonCancel))
                {
                    dialogResult = dlg.ShowDialog(Parent);
                }
                if (DialogResult.OK != dialogResult)
                {
                    return;
                }
            }
            else
            {
                DialogResult dialogResult;
                using (var dlg = new ThreeButtonDialog(
                           new ThreeButtonDialog.Details(SystemIcons.Warning, msg, Messages.XENCENTER),
                           new ThreeButtonDialog.TBDButton(Messages.OK, DialogResult.OK, ThreeButtonDialog.ButtonType.ACCEPT, true),
                           ThreeButtonDialog.ButtonCancel))
                {
                    dialogResult = dlg.ShowDialog(Parent);
                }
                if (DialogResult.OK != dialogResult)
                {
                    return;
                }
            }

            // The UI shouldn't offer deleting a bond in this case, but let's make sure we've
            // done the right thing and that the bond hasn't been deleted in the meantime. (CA-27436).
            Bond bond = pif.BondMasterOf;

            if (bond != null)
            {
                new Actions.DestroyBondAction(bond).RunAsync();
            }
        }
Example #16
0
        private void HandleAuthenticate_Callback2(uint BluetoothStackID,
                                                  ref Structs.GAP_Event_Data GAP_Event_Data, uint CallbackParameter)
        {
            //Debug.WriteLine("Authenticate_Callback Event_Data_Type: " + GAP_Event_Data.Event_Data_Type);
            Debug.Assert(GAP_Event_Data.Event_Data_Type == StackConsts.GAP_Event_Type.Authentication,
                         "Unexpected Authenticate_Callback Event_Data_Type: " + GAP_Event_Data.Event_Data_Type);
            if (GAP_Event_Data.Event_Data_Type == StackConsts.GAP_Event_Type.Authentication)
            {
                var data = (Structs.GAP_Authentication_Event_Data__Status)
                           Marshal.PtrToStructure(GAP_Event_Data.pData,
                                                  typeof(Structs.GAP_Authentication_Event_Data__Status));
                var addr8 = new byte[8];
                data._Remote_Device.CopyTo(addr8, 0);
                var addrI = BitConverter.ToInt64(addr8, 0);
                var addr  = BluetopiaUtils.ToBluetoothAddress(addr8);
#if DEBUG
                var addrI2 = BluetopiaUtils.BluetoothAddressAsInteger(addr);
                Trace.Assert(addrI == addrI2, "addrI: + " + addrI + " != addrI2: " + addrI2);
#endif
                Debug.WriteLine("Authenticate_Callback: type: " + data._GAP_Authentication_Event_Type
                                + ", addr: " + addr.ToString());
                if (data._GAP_Authentication_Event_Type == StackConsts.GAP_Authentication_Event_Type
                    .AuthenticationStatus)
                {
                    Debug.WriteLine("  Status: " + data.GetAuthenticationStatus(_factory.ApiVersion) + ")");
                }
                //
                PinPairItem ppItem;
                byte[]      key = null;
                ppItem = GetPinPairItem_willLock(addr); // Got Pin?
                // Use LinkKey if not PairRequest active.
                if (ppItem == null || ppItem._eventForPairRequest == null)
                {
                    lock (_pins) { // Got LinkKey?
                        var got = _keys.TryGetValue(addr, out key);
                        Debug.Assert(!got || (key != null));
                    }
                }
                if (ppItem == null && key == null)
                {
                    Debug.WriteLine("  No Pin or LinkKey for that device, exiting.");
                    return;
                }
                Debug.WriteLine("  Have Pin: " + (ppItem != null) + ", LinkKey: " + (key != null));
                //
                BluetopiaError ret;
                switch (data._GAP_Authentication_Event_Type)
                {
                case StackConsts.GAP_Authentication_Event_Type.LinkKeyRequest:
                    if (key == null)
                    {
                        ret = RespondWithNoLinkKey(addrI);
                    }
                    else
                    {
                        ret = RespondWithLinkKey(addrI, key);
                    }
                    break;

                case StackConsts.GAP_Authentication_Event_Type.PINCodeRequest:
                    if (ppItem == null)
                    {
                        break;
                    }
                    // Respond with Pin
                    Debug.Assert(ppItem != null, "Would have exited above if not a known device.");
                    var rspndrInfo = new ResponderInfo {
                        AddrI = addrI, PPItem = ppItem
                    };
                    ret = RespondWithPinCode(rspndrInfo);
                    break;

                case StackConsts.GAP_Authentication_Event_Type.AuthenticationStatus:
                    if (ppItem == null)
                    {
                        break;
                    }
                    // Success or Fail??
                    Debug.Assert(ppItem != null, "Would have exited above if not a known device.");
                    lock (_pins) {
                        ppItem.status  = data.GetAuthenticationStatus(_factory.ApiVersion);
                        ppItem.success = (ppItem.status
                                          == StackConsts.HCI_ERROR_CODE.NO_ERROR);
                        ppItem._eventForPairRequest.Set();
                    }
                    break;

                case StackConsts.GAP_Authentication_Event_Type.LinkKeyCreation:
                    // Store the LinkKey for the next time we connect -- the stack doesn't!
                    var authInfoKey = (Structs.GAP_Authentication_Event_Data__LinkKey)
                                      Marshal.PtrToStructure(GAP_Event_Data.pData,
                                                             typeof(Structs.GAP_Authentication_Event_Data__LinkKey));
                    AddOrUpdateLinkKey_willLock(addr, authInfoKey.GetLinkKey(_factory.ApiVersion));
                    break;
                }//switch
            }
        }
Example #17
0
        // Fields...


        public ShellBag0X61(byte[] rawBytes)
        {
            FriendlyName = "URI";

            ExtensionBlocks = new List <IExtensionBlock>();

            var index = 2; //past size

            index += 1;    // move past type and a single unknown value

            var flags = rawBytes[index];

            index += 1;

            var dataSize = BitConverter.ToUInt16(rawBytes, index);

            UserName = string.Empty;

            if (dataSize > 0)
            {
                index += 2; // past size
                index += 4; // skip unknown
                index += 4; // skip unknown

                var ft1 = DateTimeOffset.FromFileTime((long)BitConverter.ToUInt64(rawBytes, index));

                FileTime1 = ft1.ToUniversalTime();


                index += 8;
                index += 4;  // skip unknown FF FF FF FF
                index += 12; // skip unknown 12 0's
                index += 4;  // skip unknown

                var strSize = BitConverter.ToUInt32(rawBytes, index);
                index += 4;

                var str = CodePagesEncodingProvider.Instance.GetEncoding(1252).GetString(rawBytes, index, (int)strSize);

                Value = str.Replace("\0", "");

                index += (int)strSize;

                strSize = BitConverter.ToUInt32(rawBytes, index);
                index  += 4;

                if (strSize > 0)
                {
                    str = CodePagesEncodingProvider.Instance.GetEncoding(1252).GetString(rawBytes, index, (int)strSize);

                    UserName = str.Replace("\0", "");
                    ;
                    index += (int)strSize;
                }

                strSize = BitConverter.ToUInt32(rawBytes, index);
                index  += 4;


                if (strSize > 0)
                {
                    str    = CodePagesEncodingProvider.Instance.GetEncoding(1252).GetString(rawBytes, index, (int)strSize);
                    index += (int)strSize;
                }

                var len1 = 0;

                while (rawBytes[index + len1] != 0x00)
                {
                    len1 += 1;
                }

                Uri = CodePagesEncodingProvider.Instance.GetEncoding(1252).GetString(rawBytes, index, len1);


                index += len1 + 1;
            }
            else
            {
                Value = Encoding.Unicode.GetString(rawBytes, 8, rawBytes.Length - 8).Split('\0').First();
            }

            dataSize = BitConverter.ToUInt16(rawBytes, index);
            index   += 2;


            Trace.Assert(dataSize == 0, "extra data in ftp case");
        }
Example #18
0
 /* Given an action (described as a string), it returns a color
  * that is to be found in the associated color map */
 public Color GetColorFor(String action)
 {
     Trace.Assert(mapData.ContainsKey(action), "Trying to access an action from the color map that has not been assigned to a color: " + action);
     return((Color)mapData[action]);
 }
Example #19
0
 public IEnumerable <CatFxnType> GetAssociatedScopes(CatKind k)
 {
     Trace.Assert(k.IsKindVar());
     return(GetAssociatedScopes(k.ToString()));
 }
Example #20
0
 public static void AssertIntIndex(long index) =>
 Trace.Assert(
     index >= int.MinValue & index <= int.MaxValue,
     "64-bit index expected");
Example #21
0
        private async Task ConnectToBrokerWorker(CancellationToken cancellationToken)
        {
            Trace.Assert(_brokerProcess == null);

            string rhostExe = Path.Combine(_rhostDirectory, RHostExe);

            if (!_services.FileSystem.FileExists(rhostExe))
            {
                throw new RHostBinaryMissingException();
            }

            string rhostBrokerExe = Path.Combine(_rhostDirectory, RHostBrokerExe);

            if (!_services.FileSystem.FileExists(rhostBrokerExe))
            {
                throw new RHostBrokerBinaryMissingException();
            }

            Process process = null;

            try {
                string pipeName = Guid.NewGuid().ToString();
                var    cts      = new CancellationTokenSource(100000);

                using (var processConnectCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, cts.Token))
                    using (var serverUriPipe = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) {
                        var psi = new ProcessStartInfo {
                            FileName        = rhostBrokerExe,
                            UseShellExecute = false,
                            Arguments       =
                                $" --logging:logFolder \"{Log.Folder.TrimTrailingSlash()}\"" +
                                $" --logging:logHostOutput {Log.LogVerbosity >= LogVerbosity.Normal}" +
                                $" --logging:logPackets {Log.LogVerbosity == LogVerbosity.Traffic}" +
                                $" --server.urls http://127.0.0.1:0" + // :0 means first available ephemeral port
                                $" --startup:name \"{Name}\"" +
                                $" --startup:writeServerUrlsToPipe {pipeName}" +
                                $" --lifetime:parentProcessId {Process.GetCurrentProcess().Id}" +
                                $" --security:secret \"{_credentials.Password}\"" +
                                $" --R:autoDetect false" +
                                $" --R:interpreters:{InterpreterId}:name \"{Name}\"" +
                                $" --R:interpreters:{InterpreterId}:basePath \"{_rHome.TrimTrailingSlash()}\""
                        };

                        if (!ShowConsole)
                        {
                            psi.CreateNoWindow = true;
                        }

                        process = StartBroker(psi);
                        process.EnableRaisingEvents = true;

                        process.Exited += delegate {
                            cts.Cancel();
                            _brokerProcess = null;
                            _connectLock.EnqueueReset();
                        };

                        await serverUriPipe.WaitForConnectionAsync(processConnectCts.Token);

                        var serverUriData = new MemoryStream();
                        try {
                            // Pipes are special in that a zero-length read is not an indicator of end-of-stream.
                            // Stream.CopyTo uses a zero-length read as indicator of end-of-stream, so it cannot
                            // be used here. Instead, copy the data manually, using PipeStream.IsConnected to detect
                            // when the other side has finished writing and closed the pipe.
                            var buffer = new byte[0x1000];
                            do
                            {
                                int count = await serverUriPipe.ReadAsync(buffer, 0, buffer.Length, cts.Token);

                                serverUriData.Write(buffer, 0, count);
                            } while (serverUriPipe.IsConnected);
                        } catch (OperationCanceledException) {
                            throw new RHostDisconnectedException("Timed out while waiting for broker process to report its endpoint URI");
                        }

                        string serverUriStr = Encoding.UTF8.GetString(serverUriData.ToArray());
                        Uri[]  serverUri;
                        try {
                            serverUri = Json.DeserializeObject <Uri[]>(serverUriStr);
                        } catch (JsonSerializationException ex) {
                            throw new RHostDisconnectedException($"Invalid JSON for endpoint URIs received from broker ({ex.Message}): {serverUriStr}");
                        }
                        if (serverUri?.Length != 1)
                        {
                            throw new RHostDisconnectedException($"Unexpected number of endpoint URIs received from broker: {serverUriStr}");
                        }

                        CreateHttpClient(serverUri[0]);
                    }

                if (DisposableBag.TryAdd(DisposeBrokerProcess))
                {
                    _brokerProcess = process;
                }
            } finally {
                if (_brokerProcess == null)
                {
                    try {
                        process?.Kill();
                    } catch (Exception) {
                    } finally {
                        process?.Dispose();
                    }
                }
            }
        }
Example #22
0
 public static void AssertIntIndexRange(long range) =>
 Trace.Assert(
     range >= int.MinValue & range <= int.MaxValue,
     "32-bit index out of range");
Example #23
0
        CiExpr ParseConstInitializer()
        {
            if (Eat(CiToken.LeftBrace))
            {
                return new CiAggregateInitializer {
                           Line = this.Line, Items = ParseCollection(CiToken.RightBrace)
                }
            }
            ;
            return(ParseExpr());
        }

        void CheckXcrementParent()
        {
            if (this.XcrementParent != null)
            {
                string op = this.CurrentToken == CiToken.Increment ? "++" : "--";

                throw ParseException($"{op} not allowed on the right side of {this.XcrementParent}");
            }
        }

        bool SeeDigit()
        {
            int c = PeekChar();

            return(c >= '0' && c <= '9');
        }

        CiInterpolatedString ParseInterpolatedString()
        {
            int line = this.Line;
            List <CiInterpolatedPart> parts = new List <CiInterpolatedPart>();

            do
            {
                string prefix = this.StringValue;
                NextToken();
                CiExpr arg       = ParseExpr();
                CiExpr width     = null;
                char   format    = ' ';
                int    precision = -1;
                if (Eat(CiToken.Comma))
                {
                    width = ParseExpr();
                }
                if (See(CiToken.Colon))
                {
                    format = (char)ReadChar();
                    if ("DdEeFfGgXx".IndexOf(format) < 0)
                    {
                        throw ParseException("Invalid format specifier");
                    }

                    if (SeeDigit())
                    {
                        precision = ReadChar() - '0';
                        if (SeeDigit())
                        {
                            precision = precision * 10 + ReadChar() - '0';
                        }
                    }
                    NextToken();
                }
                parts.Add(new CiInterpolatedPart(prefix, arg)
                {
                    WidthExpr = width, Format = format, Precision = precision
                });
                Check(CiToken.RightBrace);
            } while (ReadInterpolatedString() == CiToken.InterpolatedString);
            string suffix = this.StringValue;

            NextToken();
            return(new CiInterpolatedString(parts.ToArray(), suffix)
            {
                Line = line
            });
        }

        CiExpr ParseParenthesized()
        {
            Expect(CiToken.LeftParenthesis);
            CiExpr result = ParseExpr();

            Expect(CiToken.RightParenthesis);
            return(result);
        }

        CiExpr ParsePrimaryExpr()
        {
            CiExpr result;

            switch (this.CurrentToken)
            {
            case CiToken.Increment:
            case CiToken.Decrement:
                CheckXcrementParent();
                goto case CiToken.Minus;

            case CiToken.Minus:
            case CiToken.Tilde:
            case CiToken.ExclamationMark:
                return(new CiPrefixExpr {
                    Line = this.Line, Op = NextToken(), Inner = ParsePrimaryExpr()
                });

            case CiToken.New:
                return(new CiPrefixExpr {
                    Line = this.Line, Op = NextToken(), Inner = ParseType()
                });

            case CiToken.LiteralLong:
                result = new CiLiteralLong(this.LongValue)
                {
                    Line = this.Line
                };
                NextToken();
                break;

            case CiToken.LiteralDouble:
                result = new CiLiteralDouble(this.DoubleValue)
                {
                    Line = this.Line
                };
                NextToken();
                break;

            case CiToken.LiteralString:
                result = new CiLiteralString(this.StringValue)
                {
                    Line = this.Line
                };
                NextToken();
                break;

            case CiToken.False:
                result = new CiLiteralFalse {
                    Line = this.Line
                };
                NextToken();
                break;

            case CiToken.True:
                result = new CiLiteralTrue {
                    Line = this.Line
                };
                NextToken();
                break;

            case CiToken.Null:
                result = new CiLiteralNull {
                    Line = this.Line
                };
                NextToken();
                break;

            case CiToken.InterpolatedString:
                result = ParseInterpolatedString();
                break;

            case CiToken.LeftParenthesis:
                result = ParseParenthesized();
                break;

            case CiToken.Id:
                result = ParseSymbolReference(null);
                break;

            case CiToken.Resource:
                NextToken();
                Expect(CiToken.Less);
                if (ParseId() != "byte")
                {
                    throw ParseException("Expected resource<byte[]>");
                }
                Expect(CiToken.LeftBracket);
                Expect(CiToken.RightBracket);
                Expect(CiToken.Greater);
                result = new CiPrefixExpr {
                    Line = this.Line, Op = CiToken.Resource, Inner = ParseParenthesized()
                };
                break;

            default:
                throw ParseException("Invalid expression");
            }
            for (;;)
            {
                switch (this.CurrentToken)
                {
                case CiToken.Dot:
                    NextToken();
                    result = ParseSymbolReference(result);
                    break;

                case CiToken.LeftParenthesis:
                    if (!(result is CiSymbolReference symbol))
                    {
                        throw ParseException("Expected a method");
                    }
                    NextToken();
                    result = new CiCallExpr {
                        Line = this.Line, Method = symbol, Arguments = ParseCollection(CiToken.RightParenthesis)
                    };
                    break;

                case CiToken.LeftBracket:
                    result = new CiBinaryExpr {
                        Line = this.Line, Left = result, Op = NextToken(), Right = See(CiToken.RightBracket) ? null : ParseExpr()
                    };
                    Expect(CiToken.RightBracket);
                    break;

                case CiToken.Increment:
                case CiToken.Decrement:
                    CheckXcrementParent();
                    goto case CiToken.ExclamationMark;

                case CiToken.ExclamationMark:
                case CiToken.Hash:
                    result = new CiPostfixExpr {
                        Line = this.Line, Inner = result, Op = NextToken()
                    };
                    break;

                default:
                    return(result);
                }
            }
        }

        CiExpr ParseMulExpr()
        {
            CiExpr left = ParsePrimaryExpr();

            for (;;)
            {
                switch (this.CurrentToken)
                {
                case CiToken.Asterisk:
                case CiToken.Slash:
                case CiToken.Mod:
                    left = new CiBinaryExpr {
                        Line = this.Line, Left = left, Op = NextToken(), Right = ParsePrimaryExpr()
                    };
                    break;

                default:
                    return(left);
                }
            }
        }

        CiExpr ParseAddExpr()
        {
            CiExpr left = ParseMulExpr();

            while (See(CiToken.Plus) || See(CiToken.Minus))
            {
                left = new CiBinaryExpr {
                    Line = this.Line, Left = left, Op = NextToken(), Right = ParseMulExpr()
                }
            }
            ;
            return(left);
        }

        CiExpr ParseShiftExpr()
        {
            CiExpr left = ParseAddExpr();

            while (See(CiToken.ShiftLeft) || See(CiToken.ShiftRight))
            {
                left = new CiBinaryExpr {
                    Line = this.Line, Left = left, Op = NextToken(), Right = ParseAddExpr()
                }
            }
            ;
            return(left);
        }

        CiExpr ParseRelExpr()
        {
            CiExpr left = ParseShiftExpr();

            for (;;)
            {
                switch (this.CurrentToken)
                {
                case CiToken.Less:
                case CiToken.LessOrEqual:
                case CiToken.Greater:
                case CiToken.GreaterOrEqual:
                    left = new CiBinaryExpr {
                        Line = this.Line, Left = left, Op = NextToken(), Right = ParseShiftExpr()
                    };
                    break;

                case CiToken.Is:
                    CiBinaryExpr isExpr = new CiBinaryExpr {
                        Line = this.Line, Left = left, Op = NextToken(), Right = ParsePrimaryExpr()
                    };
                    if (See(CiToken.Id))
                    {
                        isExpr.Right = new CiVar {
                            Line = this.Line, TypeExpr = isExpr.Right, Name = ParseId()
                        }
                    }
                    ;
                    return(isExpr);

                default:
                    return(left);
                }
            }
        }

        CiExpr ParseEqualityExpr()
        {
            CiExpr left = ParseRelExpr();

            while (See(CiToken.Equal) || See(CiToken.NotEqual))
            {
                left = new CiBinaryExpr {
                    Line = this.Line, Left = left, Op = NextToken(), Right = ParseRelExpr()
                }
            }
            ;
            return(left);
        }

        CiExpr ParseAndExpr()
        {
            CiExpr left = ParseEqualityExpr();

            while (See(CiToken.And))
            {
                left = new CiBinaryExpr {
                    Line = this.Line, Left = left, Op = NextToken(), Right = ParseEqualityExpr()
                }
            }
            ;
            return(left);
        }

        CiExpr ParseXorExpr()
        {
            CiExpr left = ParseAndExpr();

            while (See(CiToken.Xor))
            {
                left = new CiBinaryExpr {
                    Line = this.Line, Left = left, Op = NextToken(), Right = ParseAndExpr()
                }
            }
            ;
            return(left);
        }

        CiExpr ParseOrExpr()
        {
            CiExpr left = ParseXorExpr();

            while (See(CiToken.Or))
            {
                left = new CiBinaryExpr {
                    Line = this.Line, Left = left, Op = NextToken(), Right = ParseXorExpr()
                }
            }
            ;
            return(left);
        }

        CiExpr ParseCondAndExpr()
        {
            CiExpr left = ParseOrExpr();

            while (See(CiToken.CondAnd))
            {
                string saveXcrementParent = this.XcrementParent;
                this.XcrementParent = "&&";
                left = new CiBinaryExpr {
                    Line = this.Line, Left = left, Op = NextToken(), Right = ParseOrExpr()
                };
                this.XcrementParent = saveXcrementParent;
            }
            return(left);
        }

        CiExpr ParseCondOrExpr()
        {
            CiExpr left = ParseCondAndExpr();

            while (See(CiToken.CondOr))
            {
                string saveXcrementParent = this.XcrementParent;
                this.XcrementParent = "||";
                left = new CiBinaryExpr {
                    Line = this.Line, Left = left, Op = NextToken(), Right = ParseCondAndExpr()
                };
                this.XcrementParent = saveXcrementParent;
            }
            return(left);
        }

        CiExpr ParseExpr()
        {
            CiExpr left = ParseCondOrExpr();

            if (See(CiToken.QuestionMark))
            {
                CiSelectExpr result = new CiSelectExpr {
                    Line = this.Line, Cond = left
                };
                NextToken();
                string saveXcrementParent = this.XcrementParent;
                this.XcrementParent = "?";
                result.OnTrue       = ParseExpr();
                Expect(CiToken.Colon);
                result.OnFalse      = ParseExpr();
                this.XcrementParent = saveXcrementParent;
                return(result);
            }
            return(left);
        }

        CiExpr ParseType()
        {
            CiExpr left = ParsePrimaryExpr();

            if (Eat(CiToken.Range))
            {
                return new CiBinaryExpr {
                           Line = this.Line, Left = left, Op = CiToken.Range, Right = ParsePrimaryExpr()
                }
            }
            ;
            if (left is CiSymbolReference symbol && Eat(CiToken.Less))
            {
                CiSymbol klass = CiSystem.Value.TryLookup(symbol.Name);

                if (klass == null)
                {
                    throw StatementException(symbol, "{0} not found", symbol.Name);
                }
                int  line        = this.Line;
                bool saveTypeArg = this.ParsingTypeArg;
                this.ParsingTypeArg = true;
                CiExpr typeArg = ParseType();
                if (Eat(CiToken.Comma))
                {
                    CiExpr valueType = ParseType();
                    if (klass != CiSystem.DictionaryClass && klass != CiSystem.SortedDictionaryClass)
                    {
                        throw StatementException(symbol, "{0} is not a generic class with two type parameters", symbol.Name);
                    }
                    left = new CiSymbolReference {
                        Line = line, Left = new CiAggregateInitializer {
                            Items = new CiExpr[] { typeArg, valueType }
                        }, Symbol = klass
                    };
                }
                else if (klass != CiSystem.ListClass && klass != CiSystem.StackClass && klass != CiSystem.HashSetClass)
                {
                    throw StatementException(symbol, "{0} is not a generic class with one type parameter", symbol.Name);
                }
                else
                {
                    left = new CiSymbolReference {
                        Line = line, Left = typeArg, Symbol = klass
                    }
                };
                Expect(CiToken.RightAngle);
                this.ParsingTypeArg = saveTypeArg;
                if (Eat(CiToken.LeftParenthesis))
                {
                    Expect(CiToken.RightParenthesis);
                    left = new CiCallExpr {
                        Line = this.Line, Method = (CiSymbolReference)left, Arguments = Array.Empty <CiExpr>()
                    };
                }
            }
            return(left);
        }

        CiExpr ParseAssign(bool allowVar)
        {
            CiExpr left = allowVar ? ParseType() : ParseExpr();

            switch (this.CurrentToken)
            {
            case CiToken.Assign:
            case CiToken.AddAssign:
            case CiToken.SubAssign:
            case CiToken.MulAssign:
            case CiToken.DivAssign:
            case CiToken.ModAssign:
            case CiToken.AndAssign:
            case CiToken.OrAssign:
            case CiToken.XorAssign:
            case CiToken.ShiftLeftAssign:
            case CiToken.ShiftRightAssign:
                return(new CiBinaryExpr {
                    Line = this.Line, Left = left, Op = NextToken(), Right = ParseAssign(false)
                });

            case CiToken.Id:
                if (allowVar)
                {
                    return(ParseVar(left));
                }
                return(left);

            default:
                return(left);
            }
        }

        CiExpr ParseInitializer()
        {
            if (!Eat(CiToken.Assign))
            {
                return(null);
            }
            if (Eat(CiToken.LeftBrace))
            {
                int           startLine = this.Line;
                List <CiExpr> fields    = new List <CiExpr>();
                do
                {
                    int    line  = this.Line;
                    CiExpr field = ParseSymbolReference(null);
                    Expect(CiToken.Assign);
                    fields.Add(new CiBinaryExpr {
                        Line = line, Left = field, Op = CiToken.Assign, Right = ParseExpr()
                    });
                } while (Eat(CiToken.Comma));
                Expect(CiToken.RightBrace);
                return(new CiAggregateInitializer {
                    Line = startLine, Items = fields.ToArray()
                });
            }
            return(ParseExpr());
        }

        CiVar ParseVar(CiExpr type) => new CiVar
        {
            Line = this.Line, TypeExpr = type, Name = ParseId(), Value = ParseInitializer()
        };

        CiVar ParseVar() => ParseVar(ParseType());

        CiConst ParseConst()
        {
            Expect(CiToken.Const);
            CiConst konst = new CiConst {
                Line = this.Line, TypeExpr = ParseType(), Name = ParseId()
            };

            Expect(CiToken.Assign);
            konst.Value = ParseConstInitializer();
            Expect(CiToken.Semicolon);
            return(konst);
        }

        CiBlock ParseBlock()
        {
            int line = this.Line;

            Expect(CiToken.LeftBrace);
            List <CiStatement> statements = new List <CiStatement>();

            while (!Eat(CiToken.RightBrace))
            {
                statements.Add(ParseStatement());
            }
            return(new CiBlock {
                Line = line, Statements = statements.ToArray()
            });
        }

        CiAssert ParseAssert()
        {
            CiAssert result = new CiAssert {
                Line = this.Line
            };

            Expect(CiToken.Assert);
            result.Cond = ParseExpr();
            if (Eat(CiToken.Comma))
            {
                result.Message = ParseExpr();
            }
            Expect(CiToken.Semicolon);
            return(result);
        }

        CiBreak ParseBreak()
        {
            if (this.CurrentLoopOrSwitch == null)
            {
                throw ParseException("break outside loop or switch");
            }
            CiBreak result = new CiBreak(this.CurrentLoopOrSwitch)
            {
                Line = this.Line
            };

            Expect(CiToken.Break);
            Expect(CiToken.Semicolon);
            if (this.CurrentLoopOrSwitch is CiLoop loop)
            {
                loop.HasBreak = true;
            }
            return(result);
        }

        CiContinue ParseContinue()
        {
            if (this.CurrentLoop == null)
            {
                throw ParseException("continue outside loop");
            }
            CiContinue result = new CiContinue(this.CurrentLoop)
            {
                Line = this.Line
            };

            Expect(CiToken.Continue);
            Expect(CiToken.Semicolon);
            return(result);
        }

        void ParseLoopBody(CiLoop loop)
        {
            CiLoop outerLoop = this.CurrentLoop;
            CiCondCompletionStatement outerLoopOrSwitch = this.CurrentLoopOrSwitch;

            this.CurrentLoopOrSwitch = this.CurrentLoop = loop;
            loop.Body = ParseStatement();
            this.CurrentLoopOrSwitch = outerLoopOrSwitch;
            this.CurrentLoop         = outerLoop;
        }

        CiDoWhile ParseDoWhile()
        {
            CiDoWhile result = new CiDoWhile {
                Line = this.Line
            };

            Expect(CiToken.Do);
            ParseLoopBody(result);
            Expect(CiToken.While);
            result.Cond = ParseParenthesized();
            Expect(CiToken.Semicolon);
            return(result);
        }

        CiFor ParseFor()
        {
            CiFor result = new CiFor {
                Line = this.Line
            };

            Expect(CiToken.For);
            Expect(CiToken.LeftParenthesis);
            if (!See(CiToken.Semicolon))
            {
                result.Init = ParseAssign(true);
            }
            Expect(CiToken.Semicolon);
            if (!See(CiToken.Semicolon))
            {
                result.Cond = ParseExpr();
            }
            Expect(CiToken.Semicolon);
            if (!See(CiToken.RightParenthesis))
            {
                result.Advance = ParseAssign(false);
            }
            Expect(CiToken.RightParenthesis);
            ParseLoopBody(result);
            return(result);
        }

        void ParseForeachIterator(CiForeach result)
        {
            result.Add(new CiVar {
                Line = this.Line, TypeExpr = ParseType(), Name = ParseId()
            });
        }

        CiForeach ParseForeach()
        {
            CiForeach result = new CiForeach {
                Line = this.Line
            };

            Expect(CiToken.Foreach);
            Expect(CiToken.LeftParenthesis);
            if (Eat(CiToken.LeftParenthesis))
            {
                ParseForeachIterator(result);
                Expect(CiToken.Comma);
                ParseForeachIterator(result);
                Expect(CiToken.RightParenthesis);
            }
            else
            {
                ParseForeachIterator(result);
            }
            Expect(CiToken.In);
            result.Collection = ParseExpr();
            Expect(CiToken.RightParenthesis);
            ParseLoopBody(result);
            return(result);
        }

        CiIf ParseIf()
        {
            CiIf result = new CiIf {
                Line = this.Line
            };

            Expect(CiToken.If);
            result.Cond   = ParseParenthesized();
            result.OnTrue = ParseStatement();
            if (Eat(CiToken.Else))
            {
                result.OnFalse = ParseStatement();
            }
            return(result);
        }

        CiLock ParseLock()
        {
            CiLock result = new CiLock {
                Line = this.Line
            };

            Expect(CiToken.Lock);
            result.Lock = ParseParenthesized();
            result.Body = ParseStatement();
            return(result);
        }

        CiNative ParseNative()
        {
            int line = this.Line;

            Expect(CiToken.Native);
            StringBuilder sb = new StringBuilder();

            this.CopyTo = sb;
            try {
                Expect(CiToken.LeftBrace);
                int nesting = 1;
                for (;;)
                {
                    if (See(CiToken.EndOfFile))
                    {
                        throw ParseException("Native block not terminated");
                    }
                    if (See(CiToken.LeftBrace))
                    {
                        nesting++;
                    }
                    else if (See(CiToken.RightBrace) && --nesting == 0)
                    {
                        break;
                    }
                    NextToken();
                }
            }
            finally {
                this.CopyTo = null;
            }
            NextToken();
            Trace.Assert(sb[sb.Length - 1] == '}');
            sb.Length--;
            return(new CiNative {
                Line = line, Content = sb.ToString()
            });
        }

        CiReturn ParseReturn()
        {
            CiReturn result = new CiReturn {
                Line = this.Line
            };

            NextToken();
            if (!See(CiToken.Semicolon))
            {
                result.Value = ParseExpr();
            }
            Expect(CiToken.Semicolon);
            return(result);
        }

        CiSwitch ParseSwitch()
        {
            CiSwitch result = new CiSwitch {
                Line = this.Line
            };

            Expect(CiToken.Switch);
            result.Value = ParseParenthesized();
            Expect(CiToken.LeftBrace);

            CiCondCompletionStatement outerLoopOrSwitch = this.CurrentLoopOrSwitch;

            this.CurrentLoopOrSwitch = result;
            List <CiCase> cases = new List <CiCase>();

            while (Eat(CiToken.Case))
            {
                List <CiExpr> values = new List <CiExpr>();
                CiExpr        value;
                do
                {
                    value = ParseExpr();
                    values.Add(value);
                    Expect(CiToken.Colon);
                } while (Eat(CiToken.Case));
                if (See(CiToken.Default))
                {
                    throw StatementException(value, "Please remove case before default");
                }
                CiCase kase = new CiCase {
                    Values = values.ToArray()
                };

                List <CiStatement> statements = new List <CiStatement>();
                for (;;)
                {
                    statements.Add(ParseStatement());
                    switch (this.CurrentToken)
                    {
                    case CiToken.Case:
                    case CiToken.Default:
                    case CiToken.RightBrace:
                        break;

                    default:
                        continue;
                    }
                    break;
                }
                kase.Body = statements.ToArray();
                cases.Add(kase);
            }
            if (cases.Count == 0)
            {
                throw ParseException("Switch with no cases");
            }
            result.Cases = cases.ToArray();

            if (Eat(CiToken.Default))
            {
                Expect(CiToken.Colon);
                List <CiStatement> statements = new List <CiStatement>();
                do
                {
                    statements.Add(ParseStatement());
                }while (!See(CiToken.RightBrace));
                result.DefaultBody = statements.ToArray();
            }

            Expect(CiToken.RightBrace);
            this.CurrentLoopOrSwitch = outerLoopOrSwitch;
            return(result);
        }

        CiThrow ParseThrow()
        {
            CiThrow result = new CiThrow {
                Line = this.Line
            };

            Expect(CiToken.Throw);
            result.Message = ParseExpr();
            Expect(CiToken.Semicolon);
            return(result);
        }

        CiWhile ParseWhile()
        {
            CiWhile result = new CiWhile {
                Line = this.Line
            };

            Expect(CiToken.While);
            result.Cond = ParseParenthesized();
            ParseLoopBody(result);
            return(result);
        }

        CiStatement ParseStatement()
        {
            switch (this.CurrentToken)
            {
            case CiToken.LeftBrace:
                return(ParseBlock());

            case CiToken.Assert:
                return(ParseAssert());

            case CiToken.Break:
                return(ParseBreak());

            case CiToken.Const:
                return(ParseConst());

            case CiToken.Continue:
                return(ParseContinue());

            case CiToken.Do:
                return(ParseDoWhile());

            case CiToken.For:
                return(ParseFor());

            case CiToken.Foreach:
                return(ParseForeach());

            case CiToken.If:
                return(ParseIf());

            case CiToken.Lock:
                return(ParseLock());

            case CiToken.Native:
                return(ParseNative());

            case CiToken.Return:
                return(ParseReturn());

            case CiToken.Switch:
                return(ParseSwitch());

            case CiToken.Throw:
                return(ParseThrow());

            case CiToken.While:
                return(ParseWhile());

            default:
                CiExpr expr = ParseAssign(true);
                Expect(CiToken.Semicolon);
                return(expr);
            }
        }

        CiCallType ParseCallType()
        {
            switch (this.CurrentToken)
            {
            case CiToken.Static:
                NextToken();
                return(CiCallType.Static);

            case CiToken.Abstract:
                NextToken();
                return(CiCallType.Abstract);

            case CiToken.Virtual:
                NextToken();
                return(CiCallType.Virtual);

            case CiToken.Override:
                NextToken();
                return(CiCallType.Override);

            case CiToken.Sealed:
                NextToken();
                return(CiCallType.Sealed);

            default:
                return(CiCallType.Normal);
            }
        }

        void ParseMethod(CiMethod method)
        {
            method.IsMutator = Eat(CiToken.ExclamationMark);
            Expect(CiToken.LeftParenthesis);
            if (!See(CiToken.RightParenthesis))
            {
                do
                {
                    CiCodeDoc doc   = ParseDoc();
                    CiVar     param = ParseVar();
                    param.Documentation = doc;
                    method.Parameters.Add(param);
                } while (Eat(CiToken.Comma));
            }
            Expect(CiToken.RightParenthesis);
            method.Throws = Eat(CiToken.Throws);
            if (method.CallType == CiCallType.Abstract)
            {
                Expect(CiToken.Semicolon);
            }
            else if (See(CiToken.FatArrow))
            {
                method.Body = ParseReturn();
            }
            else
            {
                method.Body = ParseBlock();
            }
        }

        public CiClass ParseClass(CiCallType callType)
        {
            Expect(CiToken.Class);
            CiClass klass = new CiClass {
                Parent = this.Program, Filename = this.Filename, Line = this.Line, CallType = callType, Name = ParseId()
            };

            if (Eat(CiToken.Colon))
            {
                klass.BaseClassName = ParseId();
            }
            Expect(CiToken.LeftBrace);

            List <CiConst>  consts  = new List <CiConst>();
            List <CiField>  fields  = new List <CiField>();
            List <CiMethod> methods = new List <CiMethod>();

            while (!Eat(CiToken.RightBrace))
            {
                CiCodeDoc doc = ParseDoc();

                CiVisibility visibility;
                switch (this.CurrentToken)
                {
                case CiToken.Internal:
                    visibility = CiVisibility.Internal;
                    NextToken();
                    break;

                case CiToken.Protected:
                    visibility = CiVisibility.Protected;
                    NextToken();
                    break;

                case CiToken.Public:
                    visibility = CiVisibility.Public;
                    NextToken();
                    break;

                default:
                    visibility = CiVisibility.Private;
                    break;
                }

                if (See(CiToken.Const))
                {
                    // const
                    CiConst konst = ParseConst();
                    konst.Documentation = doc;
                    konst.Visibility    = visibility;
                    consts.Add(konst);
                    continue;
                }

                callType = ParseCallType();
                // \ class | static | normal | abstract | sealed
                // method \|        |        |          |
                // --------+--------+--------+----------+-------
                // static  |   +    |   +    |    +     |   +
                // normal  |   -    |   +    |    +     |   +
                // abstract|   -    |   -    |    +     |   -
                // virtual |   -    |   +    |    +     |   -
                // override|   -    |   +    |    +     |   +
                // sealed  |   -    |   +    |    +     |   +
                if (callType == CiCallType.Static || klass.CallType == CiCallType.Abstract)
                {
                    // ok
                }
                else if (klass.CallType == CiCallType.Static)
                {
                    throw ParseException("Only static members allowed in a static class");
                }
                else if (callType == CiCallType.Abstract)
                {
                    throw ParseException("Abstract methods allowed only in an abstract class");
                }
                else if (klass.CallType == CiCallType.Sealed && callType == CiCallType.Virtual)
                {
                    throw ParseException("Virtual methods disallowed in a sealed class");
                }
                if (visibility == CiVisibility.Private && callType != CiCallType.Static && callType != CiCallType.Normal)
                {
                    throw ParseException("{0} method cannot be private", callType);
                }

                CiExpr type = Eat(CiToken.Void) ? CiSystem.VoidType : ParseType();
                if (See(CiToken.LeftBrace) && type is CiCallExpr call)
                {
                    // constructor
                    if (call.Method.Name != klass.Name)
                    {
                        throw ParseException("Constructor name doesn't match class name");
                    }
                    if (callType != CiCallType.Normal)
                    {
                        throw ParseException("Constructor cannot be {0}", callType);
                    }
                    if (call.Arguments.Length != 0)
                    {
                        throw ParseException("Constructor parameters not supported");
                    }
                    if (klass.Constructor != null)
                    {
                        throw ParseException("Duplicate constructor, already defined in line {0}", klass.Constructor.Line);
                    }
                    if (visibility == CiVisibility.Private)
                    {
                        visibility = CiVisibility.Internal;                 // TODO
                    }
                    klass.Constructor = new CiMethodBase {
                        Line = call.Line, Documentation = doc, Visibility = visibility, Parent = klass, Type = CiSystem.VoidType, Name = klass.Name, Body = ParseBlock()
                    };
                    continue;
                }

                int    line = this.Line;
                string name = ParseId();
                if (See(CiToken.LeftParenthesis) || See(CiToken.ExclamationMark))
                {
                    // method
                    CiMethod method = new CiMethod {
                        Line = line, Documentation = doc, Visibility = visibility, CallType = callType, TypeExpr = type, Name = name
                    };
                    method.Parameters.Parent = klass;
                    ParseMethod(method);
                    methods.Add(method);
                    continue;
                }

                // field
                if (visibility == CiVisibility.Public)
                {
                    throw ParseException("Field cannot be public");
                }
                if (callType != CiCallType.Normal)
                {
                    throw ParseException("Field cannot be {0}", callType);
                }
                if (type == CiSystem.VoidType)
                {
                    throw ParseException("Field cannot be void");
                }
                CiField field = new CiField {
                    Line = line, Documentation = doc, Visibility = visibility, TypeExpr = type, Name = name, Value = ParseInitializer()
                };
                Expect(CiToken.Semicolon);
                fields.Add(field);
            }

            klass.Consts  = consts.ToArray();
            klass.Fields  = fields.ToArray();
            klass.Methods = methods.ToArray();
            return(klass);
        }

        public CiEnum ParseEnum()
        {
            Expect(CiToken.Enum);
            bool   flags = Eat(CiToken.Asterisk);
            CiEnum enu   = flags ? new CiEnumFlags() : new CiEnum();

            enu.Parent   = this.Program;
            enu.Filename = this.Filename;
            enu.Line     = this.Line;
            enu.Name     = ParseId();
            Expect(CiToken.LeftBrace);
            do
            {
                CiConst konst = new CiConst {
                    Visibility = CiVisibility.Public, Documentation = ParseDoc(), Line = this.Line, Name = ParseId(), Type = enu
                };
                if (Eat(CiToken.Assign))
                {
                    konst.Value = ParseExpr();
                }
                else if (flags)
                {
                    throw ParseException("enum* symbol must be assigned a value");
                }
                enu.Add(konst);
            } while (Eat(CiToken.Comma));
            Expect(CiToken.RightBrace);
            return(enu);
        }

        public void Parse(string filename, TextReader reader)
        {
            Open(filename, reader);
            while (!See(CiToken.EndOfFile))
            {
                CiCodeDoc       doc = ParseDoc();
                CiContainerType type;
                bool            isPublic = Eat(CiToken.Public);
                switch (this.CurrentToken)
                {
                // class
                case CiToken.Class:
                    type = ParseClass(CiCallType.Normal);
                    break;

                case CiToken.Static:
                case CiToken.Abstract:
                case CiToken.Sealed:
                    type = ParseClass(ParseCallType());
                    break;

                // enum
                case CiToken.Enum:
                    type = ParseEnum();
                    break;

                // native
                case CiToken.Native:
                    this.Program.TopLevelNatives.Add(ParseNative().Content);
                    continue;

                default:
                    throw ParseException("Expected class or enum");
                }
                type.Documentation = doc;
                type.IsPublic      = isPublic;
                this.Program.Add(type);
            }
        }
    }
}
Example #24
0
 public bool Exists(string title, int?excludedLessonPlaId)
 {
     Trace.Assert(Context.PersonId.HasValue);
     return(DoRead(u => CreateAdminAnnouncementDataAccess(u).Exists(title, Context.PersonId.Value, excludedLessonPlaId)));
 }
Example #25
0
 public ArrayView <T> GetRowView(long y)
 {
     Trace.Assert(y >= 0 && y < Height, "y out of bounds");
     return(AsLinearView().GetSubView(y * Width, Width));
 }
Example #26
0
 public IList <AdminAnnouncement> GetAdminAnnouncementsByFilter(string filter)
 {
     Trace.Assert(Context.PersonId.HasValue);
     return(DoRead(u => CreateAdminAnnouncementDataAccess(u).GetAdminAnnouncementsByFilter(filter, Context.PersonId.Value)));
 }
Example #27
0
 public CbsCacheEntry(CbsNode cbsNode, int agentIndex)
 {
     this.cbsNode    = cbsNode;
     this.agentIndex = agentIndex;
     Trace.Assert(cbsNode.cbs.mergeThreshold == -1, "When agents are merged it affects their paths without explicit constraints");
 }
Example #28
0
 public AdminAnnouncement GetLastDraft()
 {
     Trace.Assert(Context.PersonId.HasValue);
     return(DoRead(u => CreateAdminAnnouncementDataAccess(u).GetLastDraft(Context.PersonId.Value)));
 }
Example #29
0
        private bool DigitPatternsRecognized(IotaVtiOcrProcessor stateManager, out List <CalibratedBlockPosition> normalizedPositions, out bool swapped)
        {
            normalizedPositions = new List <CalibratedBlockPosition>();
            Trace.Assert(m_CalibratedPositons.Count == 10);

            List <int> forwardDiffs = m_CalibratedPositons
                                      .Select(x => GetDiffSignature(x.SecondLastFrameNoDigit, m_CalibratedPositons[0].SecondLastFrameNoDigit))
                                      .ToList();

            List <int> backwardDiffs = m_CalibratedPositons
                                       .Select(x => GetDiffSignature(x.SecondLastFrameNoDigit, m_CalibratedPositons[m_CalibratedPositons.Count - 1].SecondLastFrameNoDigit))
                                       .ToList();

            BinirizeDiffArray(forwardDiffs);
            BinirizeDiffArray(backwardDiffs);

            int forwardChangeIndex  = forwardDiffs.FindIndex(x => x == 1);
            int backwardChangeIndex = backwardDiffs.FindIndex(x => x == 0);

            swapped = false;
            bool isMatch = forwardChangeIndex == backwardChangeIndex &&
                           forwardDiffs.FindIndex(forwardChangeIndex, x => x == 0) == -1 &&
                           backwardDiffs.FindIndex(backwardChangeIndex, x => x == 1) == -1;

            if (!isMatch)
            {
                // Try with swapped fields
                for (int i = 0; i < forwardDiffs.Count / 2; i++)
                {
                    int tmp = forwardDiffs[2 * i];
                    forwardDiffs[2 * i]     = forwardDiffs[2 * i + 1];
                    forwardDiffs[2 * i + 1] = tmp;

                    tmp = backwardDiffs[2 * i];
                    backwardDiffs[2 * i]     = backwardDiffs[2 * i + 1];
                    backwardDiffs[2 * i + 1] = tmp;
                }

                forwardChangeIndex  = forwardDiffs.FindIndex(x => x == 1);
                backwardChangeIndex = backwardDiffs.FindIndex(x => x == 0);

                isMatch = forwardChangeIndex == backwardChangeIndex &&
                          forwardDiffs.FindIndex(forwardChangeIndex, x => x == 0) == -1 &&
                          backwardDiffs.FindIndex(backwardChangeIndex, x => x == 1) == -1;
                swapped = true;
            }

            if (isMatch)
            {
                if (swapped)
                {
                    for (int i = 0; i < m_CalibratedPositons.Count / 2; i++)
                    {
                        normalizedPositions.Add(m_CalibratedPositons[2 * i + 1]);
                        normalizedPositions.Add(m_CalibratedPositons[2 * i]);
                    }
                }
                else
                {
                    normalizedPositions.AddRange(m_CalibratedPositons);
                }

                int indexPixelPrev   = forwardChangeIndex > 0 ? forwardChangeIndex - 1 : 9;
                int indexPixelNext   = forwardChangeIndex < normalizedPositions.Count - 1 ? forwardChangeIndex + 1 : forwardChangeIndex - 9;
                int signalChange     = normalizedPositions[forwardChangeIndex].LastFrameNoDigit.Count(x => x < 127);
                int signalPixelsPrev = normalizedPositions[indexPixelPrev].LastFrameNoDigit.Count(x => x < 127);
                int signalPixelsNext = normalizedPositions[indexPixelNext].LastFrameNoDigit.Count(x => x < 127);

                // OneAfterZero: 9 - 0 - 1
                // ZeroAfterOne: 8 - 1 - 0

                if (signalChange < signalPixelsPrev && signalChange < signalPixelsNext)
                {
                    // One before Zero
                    stateManager.LearnDigitPattern(normalizedPositions[indexPixelNext].LastFrameNoDigit, 0);
                    stateManager.LearnDigitPattern(normalizedPositions[forwardChangeIndex].LastFrameNoDigit, 1);
                    stateManager.LearnDigitPattern(normalizedPositions[indexPixelPrev].LastFrameNoDigit, 8);

                    // 3 - 2 - 5 - 4 - 7 - 6 - 9 - (8 - 1 - 0) - 3 - 2 - 5 - 4 - 7 - 6  - 9 - 8

                    int walkBackIndex = indexPixelPrev - 1;
                    if (walkBackIndex >= 0)
                    {
                        stateManager.LearnDigitPattern(normalizedPositions[walkBackIndex].LastFrameNoDigit, 9);
                    }
                    walkBackIndex--;
                    if (walkBackIndex >= 0)
                    {
                        stateManager.LearnDigitPattern(normalizedPositions[walkBackIndex].LastFrameNoDigit, 6);
                    }
                    walkBackIndex--;
                    if (walkBackIndex >= 0)
                    {
                        stateManager.LearnDigitPattern(normalizedPositions[walkBackIndex].LastFrameNoDigit, 7);
                    }
                    walkBackIndex--;
                    if (walkBackIndex >= 0)
                    {
                        stateManager.LearnDigitPattern(normalizedPositions[walkBackIndex].LastFrameNoDigit, 4);
                    }
                    walkBackIndex--;
                    if (walkBackIndex >= 0)
                    {
                        stateManager.LearnDigitPattern(normalizedPositions[walkBackIndex].LastFrameNoDigit, 5);
                    }
                    walkBackIndex--;
                    if (walkBackIndex >= 0)
                    {
                        stateManager.LearnDigitPattern(normalizedPositions[walkBackIndex].LastFrameNoDigit, 2);
                    }
                    walkBackIndex--;
                    if (walkBackIndex >= 0)
                    {
                        stateManager.LearnDigitPattern(normalizedPositions[walkBackIndex].LastFrameNoDigit, 3);
                    }

                    int walkForwardIndex = indexPixelNext + 1;
                    if (walkForwardIndex < 10)
                    {
                        stateManager.LearnDigitPattern(normalizedPositions[walkForwardIndex].LastFrameNoDigit, 3);
                    }
                    walkForwardIndex++;
                    if (walkForwardIndex < 10)
                    {
                        stateManager.LearnDigitPattern(normalizedPositions[walkForwardIndex].LastFrameNoDigit, 2);
                    }
                    walkForwardIndex++;
                    if (walkForwardIndex < 10)
                    {
                        stateManager.LearnDigitPattern(normalizedPositions[walkForwardIndex].LastFrameNoDigit, 5);
                    }
                    walkForwardIndex++;
                    if (walkForwardIndex < 10)
                    {
                        stateManager.LearnDigitPattern(normalizedPositions[walkForwardIndex].LastFrameNoDigit, 4);
                    }
                    walkForwardIndex++;
                    if (walkForwardIndex < 10)
                    {
                        stateManager.LearnDigitPattern(normalizedPositions[walkForwardIndex].LastFrameNoDigit, 7);
                    }
                    walkForwardIndex++;
                    if (walkForwardIndex < 10)
                    {
                        stateManager.LearnDigitPattern(normalizedPositions[walkForwardIndex].LastFrameNoDigit, 6);
                    }
                    walkForwardIndex++;
                    if (walkForwardIndex < 10)
                    {
                        stateManager.LearnDigitPattern(normalizedPositions[walkForwardIndex].LastFrameNoDigit, 9);
                    }

                    stateManager.SwapFieldsOrder = true;

                    SetupSixEightNineThreeDiffs(stateManager);

                    return(true);
                }
                else if (signalPixelsNext < signalChange && signalPixelsNext < signalPixelsPrev)
                {
                    stateManager.LearnDigitPattern(normalizedPositions[forwardChangeIndex].LastFrameNoDigit, 0);

                    // One after Zero
                    int nextDigitIndex = indexPixelNext;
                    for (int i = 0; i < 9; i++)
                    {
                        stateManager.LearnDigitPattern(normalizedPositions[nextDigitIndex].LastFrameNoDigit, 1 + i);

                        nextDigitIndex++;
                        if (nextDigitIndex > 9)
                        {
                            nextDigitIndex -= 10;
                        }
                    }

                    stateManager.SwapFieldsOrder = false;

                    SetupSixEightNineThreeDiffs(stateManager);

                    return(true);
                }
                else
                {
                    return(false);
                }
            }

            return(false);
        }
Example #30
0
 public static void Assert(bool condition)
 {
     Trace.Assert(condition);
 }