Пример #1
0
        public bool TryParseDateTimeOffsetIso(StringReference text, out DateTimeOffset dt)
        {
            DateTimeParse dateTimeParser = new DateTimeParse();

            if (!dateTimeParser.Parse(text.Chars, text.StartIndex, text.Length))
            {
                dt = default(DateTimeOffset);
                return(false);
            }

            DateTime d = CreateDateTime(dateTimeParser);

            TimeSpan offset;

            switch (dateTimeParser.Zone)
            {
            case ParserTimeZone.Utc:
                offset = new TimeSpan(0L);
                break;

            case ParserTimeZone.LocalWestOfUtc:
                offset = new TimeSpan(-dateTimeParser.ZoneHour, -dateTimeParser.ZoneMinute, 0);
                break;

            case ParserTimeZone.LocalEastOfUtc:
                offset = new TimeSpan(dateTimeParser.ZoneHour, dateTimeParser.ZoneMinute, 0);
                break;

            default:
                offset = TimeZoneInfo.Local.GetUtcOffset(d);
                break;
            }

            long ticks = d.Ticks - offset.Ticks;

            if (ticks < 0 || ticks > 3155378975999999999)
            {
                dt = default(DateTimeOffset);
                return(false);
            }

            dt = new DateTimeOffset(d, offset);
            return(true);
        }
Пример #2
0
        public void GetValueReference_WithQuotes_ReturnsCorrectStringReference()
        {
            var impl = Substitute.For <ICommandParserImplementation>();

            var sut = CreateSutImpl(impl: impl);

            impl.ClearReceivedCalls();

            var value = new StringReference(20, 200);

            impl.ScanTo('\"', '\\').Returns(value);
            impl.Peek().Returns('\"');

            var result = sut.GetValueReference(true);

            impl.Received(2).Consume();

            result.Should().Be(value);
        }
Пример #3
0
        public void GetShortFormArgument_WhenSingleKeyWithValue_ReturnsCorrectCommandPart()
        {
            var impl = Substitute.For <ICommandParserImplementation>();

            var sut = CreateSutImpl(impl: impl);

            impl.ClearReceivedCalls();

            var key   = new StringReference(10, 1);
            var value = new StringReference(20, 200);

            impl.Peek().Returns('t');
            impl.GetValueReference(false).Returns(key);
            impl.GetValueReference(true).Returns(value);

            var result = sut.GetShortFormArgument();

            result.Should().Be(CP(true, true, 10, 1, 20, 200));
        }
Пример #4
0
        public bool StartsWith(StringReference s, string text)
        {
            if (text.Length > s.Length)
            {
                return(false);
            }

            char[] chars = s.Chars;

            for (int i = 0; i < text.Length; i++)
            {
                if (text[i] != chars[i + s.StartIndex])
                {
                    return(false);
                }
            }

            return(true);
        }
Пример #5
0
        public void TestRuntimeLogTwoStrings()
        {
            m_Node.Messages.DataCount = 2;
            CustomSetup();
            var stringRef4 = new StringReference {
                Index = 4
            };
            var stringRef2 = new StringReference {
                Index = 2
            };

            m_GraphInstanceMock.Setup(x => x.GetString(stringRef4)).Returns(new NativeString128("4"));
            m_GraphInstanceMock.Setup(x => x.GetString(stringRef2)).Returns(new NativeString128("2"));
            m_GraphInstanceMock.Setup(x => x.ReadValue(m_Node.Messages.SelectPort(0))).Returns(stringRef4);
            m_GraphInstanceMock.Setup(x => x.ReadValue(m_Node.Messages.SelectPort(1))).Returns(stringRef2);
            TriggerPort(m_Node.Input);
            LogAssert.Expect(LogType.Log, "42");
            AssertPortTriggered(m_Node.Output, Times.Once());
        }
Пример #6
0
        public void GetLongFormArgument_WhenValue_ReturnsCorrectCommandPart()
        {
            var impl = Substitute.For <ICommandParserImplementation>();

            var sut = CreateSutImpl(impl: impl);

            impl.ClearReceivedCalls();

            var key   = new StringReference(10, 100);
            var value = new StringReference(20, 200);

            impl.ScanToAny('=', ' ').Returns(key);
            impl.Peek().Returns('=');
            impl.GetValueReference(true).Returns(value);

            var result = sut.GetLongFormArgument();

            impl.Received(1).Consume();
            result.Should().Be(CP(true, false, 10, 100, 20, 200));
        }
Пример #7
0
        /// <summary>
        /// Gets the string reference.
        /// </summary>
        /// <param name="formulaText">The formula text.</param>
        /// <param name="pointCountVal">The point count val.</param>
        /// <returns></returns>
        protected static StringReference GetStringReference(string formulaText, int pointCountVal)
        {
            StringReference stringReference = new StringReference();
            Formula         formula         = new Formula();

            formula.Text = formulaText;

            StringCache stringCache = new StringCache();
            PointCount  pointCount  = new PointCount()
            {
                Val = (UInt32Value)(uint)pointCountVal
            };

            stringCache.Append(pointCount);

            stringReference.Append(formula);
            stringReference.Append(stringCache);

            return(stringReference);
        }
Пример #8
0
        protected static void SetStringCache(StringReference stringReference, out StringCache stringCache, out StringPoint stringPoint)
        {
            stringCache = stringReference.Descendants <StringCache>().FirstOrDefault();

            if (stringCache == null)
            {
                stringCache = new StringCache();
                stringReference.AppendChild <StringCache>(stringCache);
            }

            stringPoint = stringCache.Descendants <StringPoint>().FirstOrDefault();

            if (stringPoint == null)
            {
                stringPoint = new StringPoint();
                stringCache.AppendChild <StringPoint>(stringPoint);
            }

            stringPoint.Index = new UInt32Value((uint)0);
        }
Пример #9
0
        /// <summary>
        /// Updates the series text.
        /// </summary>
        /// <param name="sheetName">Name of the sheet.</param>
        /// <param name="chartSeries">The chart series.</param>
        /// <param name="columnName">Name of the column.</param>
        /// <param name="pointCountVal">The point count val.</param>
        /// <param name="stringPointNumericVal">The string point numeric val.</param>
        protected static void UpdateSeriesText(string sheetName, OpenXmlCompositeElement chartSeries, string columnName, int pointCountVal, string stringPointNumericVal)
        {
            if (chartSeries != null)
            {
                SeriesText seriesText = chartSeries.Descendants <SeriesText>().FirstOrDefault();

                if (seriesText == null)
                {
                    seriesText = chartSeries.AppendChild <SeriesText>(new SeriesText());
                }
                else
                {
                    seriesText.RemoveAllChildren <StringReference>();
                }

                StringReference stringReference = GetStringReference(sheetName + "!$" + columnName + "$1", pointCountVal);
                AddStringPoint(stringReference.StringCache, 0, stringPointNumericVal);
                seriesText.Append(stringReference);
            }
        }
Пример #10
0
        /// <summary>
        /// Loads and parses the provided data.
        /// </summary>
        /// <param name="data">ExtendedData.</param>
        public override void PostLoad(byte[] data)
        {
            if (this.Version == WarcraftVersion.Unknown)
            {
                throw new InvalidOperationException("The record data cannot be loaded before SetVersion has been called.");
            }

            using (MemoryStream ms = new MemoryStream(data))
            {
                using (BinaryReader br = new BinaryReader(ms))
                {
                    this.ID   = br.ReadUInt32();
                    this.Name = new StringReference(br.ReadUInt32());

                    this.Type = (LiquidType)br.ReadInt32();

                    this.SpellEffect = new UInt32ForeignKey(SpellRecord.RecordName, "ID", br.ReadUInt32());
                }
            }
        }
Пример #11
0
    public static void Main()
    {
        bool                     success;
        StringReference          errorMessage   = new StringReference();
        RGBABitmapImageReference imageReference = CreateRGBABitmapImageReference();

        double [] xs = { -2, -1, 0, 1, 2 };
        double [] ys = { 2, -1, -2, -1, 2 };

        success = DrawScatterPlot(imageReference, 600, 400, xs, ys, errorMessage);
        if (success)
        {
            double[] pngdata = ConvertToPNG(imageReference.image);
            WriteToFile(pngdata, "example1.png");
            DeleteImage(imageReference.image);
        }
        else
        {
            Console.Error.WriteLine(errorMessage.stringx);
        }
    }
Пример #12
0
        /// <summary>
        /// Modify/Add categories into chart XML
        /// </summary>
        /// <param name="column_index">Corresponds to the column index that needs to be modified in chart spreadsheet (Ex: A, B, C, ...)</param>
        /// <param name="row_index">Corresponds to the column index that needs to be modified in excel </param>
        /// <param name="new_value">Corresponds to the new value we need to insert to the cell </param>
        protected override void ModifyChartXML_Categories(string column_index, uint row_index, string new_value)
        {
            foreach (LineChartSeries linechart_series in chart_part.ChartSpace.Descendants <LineChartSeries>().ToList())
            {
                CategoryAxisData category_axis_data = linechart_series.Descendants <CategoryAxisData>().FirstOrDefault();
                if (category_axis_data == null)
                {
                    // If no StringReference --> Clone one from the 1st (usually we go in this when we create a new BarChartSeries)
                    BarChartSeries   template_barchartseries   = chart_part.ChartSpace.Descendants <BarChartSeries>().FirstOrDefault();
                    CategoryAxisData template_categoryaxisdata = template_barchartseries.Descendants <CategoryAxisData>().FirstOrDefault();
                    CategoryAxisData new_categoryaxisdata      = new CategoryAxisData(template_categoryaxisdata.OuterXml);
                    linechart_series.Append(new_categoryaxisdata);
                }
                else
                {
                    StringReference sr = category_axis_data.Descendants <StringReference>().FirstOrDefault();
                    // If there is a StringReference --> Update its values
                    StringCache sc = sr.Descendants <StringCache>().First();
                    try
                    {
                        StringPoint  sp = sc.Descendants <StringPoint>().ElementAt((int)row_index - 2);
                        NumericValue nv = sp.Descendants <NumericValue>().First();
                        nv.Text = new_value;
                    }
                    catch (Exception)
                    {
                        // Create new data and append to previous XML
                        sc.PointCount.Val = sc.PointCount.Val + 1;
                        NumericValue nv = new NumericValue(new_value);
                        StringPoint  sp = new StringPoint(nv);
                        sp.Index = (uint)sc.Descendants <StringPoint>().ToList().Count;
                        sc.Append(sp);

                        // Change fomula range
                        DocumentFormat.OpenXml.Drawing.Charts.Formula f = sr.Descendants <DocumentFormat.OpenXml.Drawing.Charts.Formula>().FirstOrDefault();
                        f.Text = worksheet_name + "!$A$2:$A$" + GetRowIndexByNum((int)row_index - 2).ToString();
                    }
                }
            }
        }
Пример #13
0
    public static void Main2()
    {
        bool success;
        RGBABitmapImageReference imageReference = CreateRGBABitmapImageReference();
        StringReference          errorMessage   = new StringReference();

        ScatterPlotSeries series = GetDefaultScatterPlotSeriesSettings();

        series.xs = new double [] { -2, -1, 0, 1, 2 };
        series.ys = new double [] { 2, -1, -2, -1, 2 };
        series.linearInterpolation = true;
        series.lineType            = "dashed".ToCharArray();
        series.lineThickness       = 2d;
        series.color = GetGray(0.3);

        ScatterPlotSettings settings = GetDefaultScatterPlotSettings();

        settings.width             = 600;
        settings.height            = 400;
        settings.autoBoundaries    = true;
        settings.autoPadding       = true;
        settings.title             = "x^2 - 2".ToCharArray();
        settings.xLabel            = "X axis".ToCharArray();
        settings.yLabel            = "Y axis".ToCharArray();
        settings.scatterPlotSeries = new ScatterPlotSeries [] { series };

        success = DrawScatterPlotFromSettings(imageReference, settings, errorMessage);

        if (success)
        {
            double[] pngdata = ConvertToPNG(imageReference.image);
            WriteToFile(pngdata, "example2.png");
            DeleteImage(imageReference.image);
        }
        else
        {
            Console.Error.WriteLine(errorMessage.stringx);
        }
    }
Пример #14
0
        public void ReadOffsetMSDateTimeOffset()
        {
            char[]          c         = @"12345/Date(1418924498000+0800)/12345".ToCharArray();
            StringReference reference = new StringReference(c, 5, c.Length - 10);

            DateTimeOffset d;

            DateTimeUtils.TryParseDateTimeOffset(
                reference,
                null,
                CultureInfo.InvariantCulture,
                out d
                );

            long initialTicks = DateTimeUtils.ConvertDateTimeToJavaScriptTicks(
                d.DateTime,
                d.Offset
                );

            Assert.AreEqual(1418924498000, initialTicks);
            Assert.AreEqual(8, d.Offset.Hours);
        }
Пример #15
0
        public void TestLogStringsWithNonConnectedPorts()
        {
            m_Node.Messages.DataCount = 5;
            CustomSetup();
            var stringRef4 = new StringReference {
                Index = 4
            };
            var stringRef2 = new StringReference {
                Index = 2
            };

            m_GraphInstanceMock.Setup(x => x.GetString(stringRef4)).Returns(new NativeString128("4"));
            m_GraphInstanceMock.Setup(x => x.GetString(stringRef2)).Returns(new NativeString128("2"));
            m_GraphInstanceMock.Setup(x => x.ReadValue(m_Node.Messages.SelectPort(0))).Returns(new Value());
            m_GraphInstanceMock.Setup(x => x.ReadValue(m_Node.Messages.SelectPort(1))).Returns(stringRef4);
            m_GraphInstanceMock.Setup(x => x.ReadValue(m_Node.Messages.SelectPort(2))).Returns(new Value());
            m_GraphInstanceMock.Setup(x => x.ReadValue(m_Node.Messages.SelectPort(3))).Returns(stringRef2);
            m_GraphInstanceMock.Setup(x => x.ReadValue(m_Node.Messages.SelectPort(4))).Returns(new Value());
            TriggerPort(m_Node.Input);
            LogAssert.Expect(LogType.Log, "Unknown4Unknown2Unknown");
            AssertPortTriggered(m_Node.Output, Times.Once());
        }
        internal SLDataSeries Clone()
        {
            var ds = new SLDataSeries(Options.ShapeProperties.listThemeColors);

            ds.ChartType         = ChartType;
            ds.Index             = Index;
            ds.Order             = Order;
            ds.IsStringReference = IsStringReference;
            ds.StringReference   = StringReference.Clone();
            ds.NumericValue      = NumericValue;
            ds.Options           = Options.Clone();

            var keys = DataPointOptionsList.Keys.ToList();

            ds.DataPointOptionsList = new Dictionary <int, SLDataPointOptions>();
            foreach (var index in keys)
            {
                ds.DataPointOptionsList[index] = DataPointOptionsList[index].Clone();
            }

            if (GroupDataLabelOptions != null)
            {
                ds.GroupDataLabelOptions = GroupDataLabelOptions.Clone();
            }

            keys = DataLabelOptionsList.Keys.ToList();
            ds.DataLabelOptionsList = new Dictionary <int, SLDataLabelOptions>();
            foreach (var index in keys)
            {
                ds.DataLabelOptionsList[index] = DataLabelOptionsList[index].Clone();
            }

            ds.BubbleSize = BubbleSize.Clone();
            ds.AxisData   = AxisData.Clone();
            ds.NumberData = NumberData.Clone();

            return(ds);
        }
Пример #17
0
    public static StringReference [] removeString(StringReference [] list, double n)
    {
        StringReference [] newlist;
        double             i;

        newlist = new StringReference [(int)(list.Length - 1d)];

        for (i = 0d; i < list.Length; i = i + 1d)
        {
            if (i < n)
            {
                newlist[(int)(i)] = list[(int)(i)];
            }
            if (i > n)
            {
                newlist[(int)(i - 1d)] = list[(int)(i)];
            }
        }

        delete(list);

        return(newlist);
    }
Пример #18
0
    public static StringReference [] split(char [] toSplit, char splitBy)
    {
        StringReference [] splitt;
        char []            next;
        double             i;
        char            c;
        StringReference n;

        splitt = new StringReference [0];

        next = new char [0];
        for (i = 0d; i < toSplit.Length; i = i + 1d)
        {
            c = toSplit[(int)(i)];
            if (c == splitBy)
            {
                n         = new StringReference();
                n.stringx = next;
                splitt    = addString(splitt, n);
                next      = new char [0];
            }
            else
            {
                next = appendCharacter(next, c);
            }
        }

        if (next.Length > 0d)
        {
            n         = new StringReference();
            n.stringx = next;
            splitt    = addString(splitt, n);
        }

        return(splitt);
    }
Пример #19
0
 public static void addStringRef(StringListRef list, StringReference i)
 {
     list.list = addString(list.list, i);
 }
Пример #20
0
 public static char Get(this StringReference stringReference, int i)
 {
     return(XStrings.Api.StringReferences.Get(stringReference, i));
 }
Пример #21
0
        /// <summary>
        /// Measures the string, returning the maximum width and height
        /// (stored in the X, Y coordinates respectively) of the string
        /// as it would be if rendered.
        /// </summary>
        /// <param name="text">The string builder</param>
        /// <returns>Width, height of the string</returns>
        public Vector2 MeasureString(StringBuilder text)
        {
            StringReference strRef = new StringReference(text);

            return(MeasureString(ref strRef));
        }
Пример #22
0
        private void ReadStringIntoBuffer()
        {
            int          charPos           = _charPos;
            int          initialPosition   = _charPos;
            int          lastWritePosition = _charPos;
            StringBuffer buffer            = null;

            while (true)
            {
                var charAt = _chars[charPos++];
                if ('\0' == charAt)
                {
                    if (_charsUsed == charPos - 1)
                    {
                        charPos--;

                        if (ReadData(true) == 0)
                        {
                            _charPos = charPos;
                            throw EdiReaderException.Create(this, "Unterminated string. Expected delimiter.");
                        }
                    }
                }
                // Make use of the release character. Identify escape sequence
                else if (Grammar.ReleaseCharacter == charAt)
                {
                    _charPos = charPos;
                    if (!EnsureChars(0, true))
                    {
                        _charPos = charPos;
                        throw EdiReaderException.Create(this, "Unterminated string. Expected delimiter.");
                    }

                    // start of escape sequence
                    int escapeStartPos = charPos - 1;

                    char currentChar = _chars[charPos];

                    char writeChar;

                    if (Grammar.IsSpecial(currentChar) || Grammar.ReleaseCharacter == currentChar)
                    {
                        charPos++;
                        writeChar = currentChar;
                    }
                    else
                    {
                        charPos++;
                        _charPos = charPos;
                        throw EdiReaderException.Create(this, "Bad EDI escape sequence: {0}{1}.".FormatWith(CultureInfo.InvariantCulture, Grammar.ReleaseCharacter, currentChar));
                    }

                    if (buffer == null)
                    {
                        buffer = GetBuffer();
                    }

                    WriteCharToBuffer(buffer, writeChar, lastWritePosition, escapeStartPos);

                    lastWritePosition = charPos;
                }
                else if (StringUtils.CarriageReturn == charAt && !Grammar.IsSpecial(charAt))
                {
                    _charPos = charPos - 1;
                    ProcessCarriageReturn(true);
                    charPos = _charPos;
                }
                else if (StringUtils.LineFeed == charAt && !Grammar.IsSpecial(charAt))
                {
                    _charPos = charPos - 1;
                    ProcessLineFeed();
                    charPos = _charPos;
                }
                else if (Grammar.IsSpecial(charAt))
                {
                    if (StringUtils.LineFeed == charAt)
                    {
                        ProcessLineFeed(forwardPosition: false);
                    }
                    charPos--;
                    if (initialPosition == lastWritePosition)
                    {
                        _stringReference = new StringReference(_chars, initialPosition, charPos - initialPosition);
                    }
                    else
                    {
                        if (buffer == null)
                        {
                            buffer = GetBuffer();
                        }

                        if (charPos > lastWritePosition)
                        {
                            buffer.Append(_chars, lastWritePosition, charPos - lastWritePosition);
                        }

                        _stringReference = new StringReference(buffer.GetInternalBuffer(), 0, buffer.Position);
                    }
                    _charPos = charPos;
                    return;
                }
            }
        }
Пример #23
0
 public static int IndexOf(this StringReference s, char c, int startIndex, int length)
 {
     return(XStrings.Api.StringReferences.IndexOf(s, c, startIndex, length));
 }
Пример #24
0
 public static bool EndsWith(this StringReference s, string text)
 {
     return(XStrings.Api.StringReferences.EndsWith(s, text));
 }
Пример #25
0
 public static string ConvertToString(this StringReference stringReference)
 {
     return(XStrings.Api.StringReferences.ConvertToString(stringReference));
 }
Пример #26
0
        private GameType CreateMegaloGametype(GameType gametype, uint time)
        {
            // heuheuheuheuheu
            gametype.TimeLimit = time - 1;

            // string table her dongle so hard
            gametype.Name = new StringTable(string.Format("{0}/{1} - Yrs2013", _cityA, _cityB));

            // setup teams
            #region setup teams
            gametype.TeamsEnabled = true;
            gametype.TeamChanging = TeamChangingMode.Disabled;
            #endregion
            #region global variable declaration
            var currentTeamIndex = gametype.Script.GlobalVariables.Integers.Count;
            gametype.Script.GlobalVariables.Integers.Add(new IntegerVariableDefinition(0, NetworkPriority.High));

            var currentDataPointIndex = gametype.Script.GlobalVariables.Integers.Count;
            gametype.Script.GlobalVariables.Integers.Add(new IntegerVariableDefinition(0, NetworkPriority.High));

            var updateNextDataPoint = gametype.Script.GlobalVariables.Integers.Count;
            gametype.Script.GlobalVariables.Integers.Add(new IntegerVariableDefinition(1, NetworkPriority.High));

            var updateTimerIndex = gametype.Script.GlobalVariables.Timers.Count;
            gametype.Script.GlobalVariables.Timers.Add(new TimerVariableDefinition(0));
            #endregion
            #region trait creation
            var traitIndex = gametype.MegaloTraits.Count;
            gametype.MegaloTraits.Add(new MegaloTraits
            {
                WaypointVisible = HUDVisibility.VisibleToEveryone,
                DamageMultiplier = (Modifier)1.6,
                PlayerScale = (Modifier)2.0,
                JumpHeight = (Modifier)2.0
            });
            #endregion

            // ************************************************************************************
            // To All Megalo Script Under Here ****************************************************
            // ************************************************************************************

            var initTrigger = new MegaloTrigger();
            #region trigger_data
            {
                Megalo.SetMegaloAction("var_operation", initTrigger,
                    new List<KeyValuePair<string, object>>
                    {
                        Megalo.CreateCondition("result", new GenericReference(TimerReference.ForGlobal(updateTimerIndex))),
                        Megalo.CreateCondition("value", new GenericReference(IntegerReference.ForConstant(5))),
                        Megalo.CreateCondition("operation", OperationType.Set)
                    });

                Megalo.SetMegaloAction("timer_set_rate", initTrigger,
                    new List<KeyValuePair<string, object>>
                    {
                        Megalo.CreateCondition("timer", TimerReference.ForGlobal(updateTimerIndex)),
                        Megalo.CreateCondition("rate", 5)
                    });

                gametype.Script.EntryPoints.InitTrigger = initTrigger;
                gametype.Script.Triggers.Add(initTrigger);
            }
            #endregion

            var trySetTraitsToTeam0 = new MegaloTrigger { EnumType = TriggerEnumType.EnumPlayers };
            #region trigger_data
            {
                var setPlayerTraits = Megalo.SetMegaloAction("player_set_traits", trySetTraitsToTeam0, new List<KeyValuePair<string, object>>
                {
                    Megalo.CreateCondition("player", PlayerReference.ForGlobal(PlayerVariableType.CurrentPlayer)),
                    Megalo.CreateCondition("traits_index", traitIndex)
                });

                Megalo.SetMegaloCondition("compare", trySetTraitsToTeam0, setPlayerTraits, new List<KeyValuePair<string, object>>
                {
                    Megalo.CreateCondition("value1", new GenericReference(IntegerReference.ForGlobal(currentTeamIndex))),
                    Megalo.CreateCondition("value2", new GenericReference(IntegerReference.ForConstant(0))),
                    Megalo.CreateCondition("comparison", ComparisonType.Equal)
                });

                Megalo.SetMegaloCondition("compare", trySetTraitsToTeam0, setPlayerTraits, new List<KeyValuePair<string, object>>
                {
                    Megalo.CreateCondition("value1", new GenericReference(TeamReference.ForPlayerOwnerTeam(PlayerVariableType.CurrentPlayer))),
                    Megalo.CreateCondition("value2", new GenericReference(TeamReference.ForGlobal(TeamVariableType.Direct, 0))),
                    Megalo.CreateCondition("comparison", ComparisonType.Equal)
                }, 1);

                gametype.Script.Triggers.Add(trySetTraitsToTeam0);
            }
            #endregion

            var trySetTraitsToTeam1 = new MegaloTrigger { EnumType = TriggerEnumType.EnumPlayers };
            #region trigger_data
            {
                var setPlayerTraits = Megalo.SetMegaloAction("player_set_traits", trySetTraitsToTeam1, new List<KeyValuePair<string, object>>
                {
                    Megalo.CreateCondition("player", PlayerReference.ForGlobal(PlayerVariableType.CurrentPlayer)),
                    Megalo.CreateCondition("traits_index", traitIndex)
                });

                Megalo.SetMegaloCondition("compare", trySetTraitsToTeam1, setPlayerTraits, new List<KeyValuePair<string, object>>
                {
                    Megalo.CreateCondition("value1", new GenericReference(IntegerReference.ForGlobal(currentTeamIndex))),
                    Megalo.CreateCondition("value2", new GenericReference(IntegerReference.ForConstant(1))),
                    Megalo.CreateCondition("comparison", ComparisonType.Equal)
                });

                Megalo.SetMegaloCondition("compare", trySetTraitsToTeam1, setPlayerTraits, new List<KeyValuePair<string, object>>
                {
                    Megalo.CreateCondition("value1", new GenericReference(TeamReference.ForPlayerOwnerTeam(PlayerVariableType.CurrentPlayer))),
                    Megalo.CreateCondition("value2", new GenericReference(TeamReference.ForGlobal(TeamVariableType.Direct, 1))),
                    Megalo.CreateCondition("comparison", ComparisonType.Equal)
                }, 1);

                gametype.Script.Triggers.Add(trySetTraitsToTeam1);
            }
            #endregion

            var updateDataPointEntryTrigger = new MegaloTrigger();
            #region trigger_data
            {
                // start action
                var resetNeedUpdateDataPoint = Megalo.SetMegaloAction("var_operation", updateDataPointEntryTrigger,
                    new List<KeyValuePair<string, object>>
                    {
                        Megalo.CreateCondition("result", new GenericReference(IntegerReference.ForGlobal(updateNextDataPoint))),
                        Megalo.CreateCondition("value", new GenericReference(IntegerReference.ForConstant(0))),
                        Megalo.CreateCondition("operation", OperationType.Set)
                    });

                var index = 0;
                foreach (var dataPoint in _session.DataPoints)
                {
                    var constructedMegaloTrigger = new MegaloTrigger();
                    {
                        MegaloAction startAction;
                        var winner = "";
                        if (dataPoint.CityARating > dataPoint.CityBRating)
                        {
                            winner = _session.CityA;

                            startAction = Megalo.SetMegaloAction("var_operation", constructedMegaloTrigger,
                                new List<KeyValuePair<string, object>>
                                {
                                    Megalo.CreateCondition("result",
                                        new GenericReference(IntegerReference.ForGlobal(currentTeamIndex))),
                                    Megalo.CreateCondition("value",
                                        new GenericReference(IntegerReference.ForConstant(0))),
                                    Megalo.CreateCondition("operation", OperationType.Set)
                                });
                        }
                        else if (dataPoint.CityARating < dataPoint.CityBRating)
                        {
                            winner = _session.CityB;

                            startAction = Megalo.SetMegaloAction("var_operation", constructedMegaloTrigger,
                                new List<KeyValuePair<string, object>>
                                {
                                    Megalo.CreateCondition("result",
                                        new GenericReference(IntegerReference.ForGlobal(currentTeamIndex))),
                                    Megalo.CreateCondition("value",
                                        new GenericReference(IntegerReference.ForConstant(1))),
                                    Megalo.CreateCondition("operation", OperationType.Set)
                                });
                        }
                        else
                        {
                            winner = _session.CityA;

                            startAction = Megalo.SetMegaloAction("var_operation", constructedMegaloTrigger,
                                new List<KeyValuePair<string, object>>
                                {
                                    Megalo.CreateCondition("result",
                                        new GenericReference(IntegerReference.ForGlobal(currentTeamIndex))),
                                    Megalo.CreateCondition("value",
                                        new GenericReference(IntegerReference.ForConstant(0))),
                                    Megalo.CreateCondition("operation", OperationType.Set)
                                });
                        }

                        var str = new StringReference(gametype.MegaloStrings.Add(string.Format("Current Winner Is: {0}!", winner)));
                        var effectMessage = new MegaloAction("chud_message");
                        effectMessage.Arguments.Set("target", TargetReference.All);
                        effectMessage.Arguments.Set("sound_index", -1);
                        effectMessage.Arguments.Set("text", str);
                        constructedMegaloTrigger.Actions.Add(effectMessage);

                        // call if swag is gucci
                        Megalo.SetMegaloCondition("compare", constructedMegaloTrigger, startAction,
                            new List<KeyValuePair<string, object>>
                            {
                                Megalo.CreateCondition("value1", new GenericReference(IntegerReference.ForGlobal(currentDataPointIndex))),
                                Megalo.CreateCondition("value2", new GenericReference(IntegerReference.ForConstant((short)index))),
                                Megalo.CreateCondition("comparison", ComparisonType.Equal)
                            });
                    }
                    var callConstructedMegaloTrigger = MegaloAction.ForTriggerCall(constructedMegaloTrigger);
                    updateDataPointEntryTrigger.Actions.Add(callConstructedMegaloTrigger);

                    index++;
                }

                Megalo.SetMegaloAction("var_operation", updateDataPointEntryTrigger,
                    new List<KeyValuePair<string, object>>
                    {
                        Megalo.CreateCondition("result", new GenericReference(IntegerReference.ForGlobal(currentDataPointIndex))),
                        Megalo.CreateCondition("value", new GenericReference(IntegerReference.ForConstant(1))),
                        Megalo.CreateCondition("operation", OperationType.Add)
                    });

                Megalo.SetMegaloCondition("compare", updateDataPointEntryTrigger, resetNeedUpdateDataPoint,
                    new List<KeyValuePair<string, object>>
                    {
                        Megalo.CreateCondition("value1", new GenericReference(IntegerReference.ForGlobal(updateNextDataPoint))),
                        Megalo.CreateCondition("value2", new GenericReference(IntegerReference.ForConstant(1))),
                        Megalo.CreateCondition("comparison", ComparisonType.Equal)
                    });

                gametype.Script.Triggers.Add(updateDataPointEntryTrigger);
            }
            #endregion

            var dealWithTheTimerTrigger = new MegaloTrigger();
            #region trigger_data
            {
                // check timer has expired, if it has, set a variable and start it again
                var setTimer = Megalo.SetMegaloAction("var_operation", dealWithTheTimerTrigger,
                    new List<KeyValuePair<string, object>>
                    {
                        Megalo.CreateCondition("result", new GenericReference(TimerReference.ForGlobal(updateTimerIndex))),
                        Megalo.CreateCondition("value", new GenericReference(IntegerReference.ForConstant(3))),
                        Megalo.CreateCondition("operation", OperationType.Set)
                    });

                Megalo.SetMegaloAction("timer_set_rate", dealWithTheTimerTrigger,
                    new List<KeyValuePair<string, object>>
                    {
                        Megalo.CreateCondition("timer", TimerReference.ForGlobal(updateTimerIndex)),
                        Megalo.CreateCondition("rate", 5)
                    });

                // set variable
                Megalo.SetMegaloAction("var_operation", dealWithTheTimerTrigger,
                    new List<KeyValuePair<string, object>>
                    {
                        Megalo.CreateCondition("result", new GenericReference(IntegerReference.ForGlobal(updateNextDataPoint))),
                        Megalo.CreateCondition("value", new GenericReference(IntegerReference.ForConstant(1))),
                        Megalo.CreateCondition("operation", OperationType.Set)
                    });

                Megalo.SetMegaloCondition("timer_is_zero", dealWithTheTimerTrigger, setTimer,
                    new List<KeyValuePair<string, object>>
                    {
                        Megalo.CreateCondition("timer", TimerReference.ForGlobal(updateTimerIndex))
                    });

                gametype.Script.Triggers.Add(dealWithTheTimerTrigger);
            }
            #endregion

            var roundEndingTimer = new MegaloTrigger();
            #region trigger_data
            {
                var endRound = Megalo.SetMegaloAction("round_end", roundEndingTimer);

                Megalo.SetMegaloCondition("timer_is_zero", roundEndingTimer, endRound,
                    new List<KeyValuePair<string, object>>
                    {
                        Megalo.CreateCondition("timer", TimerReference.RoundTimer)
                    });

                gametype.Script.Triggers.Add(roundEndingTimer);
            }
            #endregion

            return gametype;
        }
        public void StringReferenceUnitTestsSimplePasses()
        {
            // Use the Assert class to test conditions
            Debug.Assert(!(new StringReference() == new StringReference("test")));
            Debug.Assert(!(new StringReference() == "test"));
            Debug.Assert(new StringReference() == new StringReference());

            StringReference p = "test";

            Debug.Log(p.ToString());

            string a = "test";

            Debug.Assert((a == p));
            Debug.Assert((p == a));
            Debug.Assert(!(a != p));
            Debug.Assert(!(p != a));

            StringReference other = "other";

            p = other;

            Debug.Log(p.ToString());
            Debug.Assert(!(a == p));
            Debug.Assert(!(p == a));
            Debug.Assert((a != p));
            Debug.Assert((p != a));

            Debug.Log("s is null");
            a = null;
            Debug.Assert(!(a == p));
            Debug.Assert(!(p == a));
            Debug.Assert((a != p));
            Debug.Assert((p != a));

            Debug.Log("p is null");
            p = null;
            a = "test";
            Debug.Assert(!(a == p));
            Debug.Assert(!(p == a));
            Debug.Assert((a != p));
            Debug.Assert((p != a));

            Debug.Log("both are null");
            p = null;
            a = null;
            Debug.Assert((a == p));
            Debug.Assert((p == a));
            Debug.Assert(!(a != p));
            Debug.Assert(!(p != a));

            StringReference duplicate1 = "test";
            StringReference duplicate2 = "test";
            StringReference duplicate3 = "test";
            StringReference duplicate4 = "test";
            StringReference duplicate5 = "test";
            StringReference duplicate6 = "test";
            StringReference duplicate7 = "test";

            Debug.Assert(StringReference.NumStringsStored() == 2);
        }
Пример #28
0
 public StringReference ReadStringReference()
 {
     var reference = new StringReference();
     if (Magic.Is32Bit)
         reference.Offset = Reader.ReadUInt32();
     else
         reference.Offset = Reader.ReadUInt64();
     return reference;
 }
Пример #29
0
        /// <summary>
        /// Send the packet to every current messenger and add it to the packet cache if it's cachable
        /// </summary>
        /// <param name="envelope"></param>
        private void DispatchPacket(PacketEnvelope envelope)
        {
            IMessengerPacket packet;

            lock (envelope)
            {
                packet = envelope.Packet; // rather than dig it out each time
                bool writeThrough = envelope.WriteThrough;

                // Any special handling for this packet?
                if (envelope.IsCommand)
                {
                    //this is a command packet, we process it as a command instead of just a data message
                    CommandPacket commandPacket = (CommandPacket)packet;

                    // Is this our exit or shutdown packet?  We need to handle those here.
                    if (commandPacket.Command == MessagingCommand.ExitMode)
                    {
                        m_ExitMode = true; // Mark us in ExitMode.  We will be by the time this method returns.
                        // Make sure we block until each messenger flushes, even if we weren't already in writeThrough mode.
                        writeThrough = true;
                    }
                    else if (commandPacket.Command == MessagingCommand.CloseMessenger)
                    {
                        m_Shutdown = true; // Mark us as shut down.  We will be by the time this method returns.
                        // Make sure we block until each messenger closes, even if we weren't already in writeThrough mode.
                        writeThrough = true;
                    }
                }
                else
                {
                    // Not a command, so it must be a Gibraltar data packet of some type.

                    //stamp the packet, and all of its dependent packets (this sets the sequence number)
                    StampPacket(packet, packet.Timestamp);

                    GibraltarPacket gibraltarPacket = packet as GibraltarPacket;
                    if (gibraltarPacket != null)
                    {
                        //this is a gibraltar packet so lets go ahead and fix the data in place now that we're on the background thread.
                        gibraltarPacket.FixData();
                    }

                    //resolve the application user if feasible..
                    if (packet is IUserPacket userPacket && userPacket.Principal != null)
                    {
                        var userResolver = m_ApplicationUserProvider;
                        if (userResolver != null)
                        {
                            ResolveApplicationUser(userResolver, userPacket);
                        }
                    }

                    //and finally run it through our filters..
                    var cancel  = false;
                    var filters = m_Filters;
                    if (filters != null)
                    {
                        foreach (var filter in filters)
                        {
                            try
                            {
                                filter.Process(packet, ref cancel);
                                if (cancel)
                                {
                                    break;
                                }
                            }
                            catch (Exception)
                            {
                                Log.DebugBreak(); // Catch this in the debugger, but otherwise swallow any errors.
                            }
                        }
                    }

                    //if a filter canceled then we can't write out this packet.
                    if (cancel)
                    {
                        envelope.IsCommitted = true; //so people waiting on us don't stall..
                        return;
                    }
                }

                //If this is a header packet we want to put it in the header list now - that way
                //if any messenger recycles while we are writing to the messengers it will be there.
                //(Better to pull the packet forward than to risk having it in an older stream but not a newer stream)
                if (envelope.IsHeader)
                {
                    lock (m_HeaderPacketsLock)
                    {
                        m_HeaderPackets.Add((ICachedMessengerPacket)packet);
                        System.Threading.Monitor.PulseAll(m_HeaderPacketsLock);
                    }
                }

                // Data message or Command packet - either way, send it on to each messenger.
                foreach (IMessenger messenger in m_Messengers)
                {
                    //we don't want an exception with one messenger to cause us a problem, so each gets its own try/catch
                    try
                    {
                        messenger.Write(packet, writeThrough);
                    }
                    catch (Exception)
                    {
                        Log.DebugBreak(); // Stop in debugger, ignore in production.
                    }
                }

                //if this was a write through packet we need to let the caller know that it was committed.
                envelope.IsCommitted = true; //under the covers this does a pulse on the threads waiting on this envelope.
            }

            // Now that it's committed, finally send it to any Notifiers that may be subscribed.
            QueueToNotifier(packet);

            //we only need to do this here if the session file writer is disabled; otherwise it's doing it at the best boundary.
            if ((m_Configuration.SessionFile.Enabled == false) &&
                (packet.Sequence % 8192 == 0))
            {
                StringReference.Pack();
            }
        }
Пример #30
0
        protected void modificaChartData(string FormatoValori, string titoloSerie, out SeriesText seriesText1, out CategoryAxisData categoryAxisData1, out Values values1)
        {
            seriesText1 = new SeriesText();

            StringReference stringReference1 = new StringReference();
            Formula         formula1         = new Formula();

            formula1.Text = "Foglio1!$B$1";

            StringCache stringCache1 = new StringCache();
            PointCount  pointCount1  = new PointCount()
            {
                Val = (UInt32Value)1U
            };

            StringPoint stringPoint1 = new StringPoint()
            {
                Index = (UInt32Value)0U
            };
            NumericValue numericValue1 = new NumericValue();

            numericValue1.Text = titoloSerie;

            stringPoint1.Append(numericValue1);

            stringCache1.Append(pointCount1);
            stringCache1.Append(stringPoint1);

            stringReference1.Append(formula1);
            stringReference1.Append(stringCache1);

            seriesText1.Append(stringReference1);

            DataPoint dataPoint1 = new DataPoint();
            Index     index2     = new Index()
            {
                Val = (UInt32Value)2U
            };


            dataPoint1.Append(index2);

            //################################i testi ####################################
            categoryAxisData1 = new CategoryAxisData();

            StringReference stringReference2 = new StringReference();
            Formula         formula2         = new Formula();

            formula2.Text = string.Format("Foglio1!$A$2:$A${0}", valori.Count + 2);

            StringCache stringCache2 = new StringCache();
            UInt32Value nValori      = Convert.ToUInt32(valori.Count);

            PointCount pointCount2 = new PointCount()
            {
                Val = nValori
            };

            StringPoint[] stringPoints = new StringPoint[nValori];
            UInt32Value   n            = 0;

            foreach (KeyValuePair <string, double> item in valori)
            {
                stringPoints[n] = new StringPoint()
                {
                    Index = (UInt32Value)n
                };
                NumericValue numericValue2 = new NumericValue();
                numericValue2.Text = item.Key;
                stringPoints[n].Append(numericValue2);
                n += 1;
            }



            stringCache2.Append(pointCount2);
            for (int i = 0; i < n; i++)
            {
                stringCache2.Append(stringPoints[i]);
            }

            stringReference2.Append(formula2);
            stringReference2.Append(stringCache2);

            categoryAxisData1.Append(stringReference2);


            //################################i valori####################################

            values1 = new Values();

            NumberReference numberReference1 = new NumberReference();
            Formula         formula3         = new Formula();

            formula3.Text = string.Format("Foglio1!$B$2:$B${0}", valori.Count + 2);

            NumberingCache numberingCache1 = new NumberingCache();
            FormatCode     formatCode1     = new FormatCode();

            formatCode1.Text = FormatoValori; //<-----------------------------------------------------------
            PointCount pointCount3 = new PointCount()
            {
                Val = nValori
            };

            NumericPoint[] numericPoints = new NumericPoint[nValori];
            n = 0;
            foreach (KeyValuePair <string, double> item in valori)
            {
                numericPoints[n] = new NumericPoint()
                {
                    Index = (UInt32Value)n
                };
                NumericValue numericValue = new NumericValue();
                numericValue.Text = item.Value.ToString();
                numericValue.Text = numericValue.Text.Replace(",", "."); // devo forzare il formato americano
                numericPoints[n].Append(numericValue);
                n += 1;
            }



            numberingCache1.Append(formatCode1);
            numberingCache1.Append(pointCount3);
            for (int i = 0; i < n; i++)
            {
                numberingCache1.Append(numericPoints[i]);
            }



            numberReference1.Append(formula3);
            numberReference1.Append(numberingCache1);

            values1.Append(numberReference1);
        }
Пример #31
0
 public char Get(StringReference stringReference, int i)
 {
     return(stringReference.Chars[i]);
 }
Пример #32
0
 public string ConvertToString(StringReference stringReference)
 {
     return(new string(stringReference.Chars, stringReference.StartIndex, stringReference.Length));
 }