System.Math.Abs(int)

Here are the examples of the csharp api System.Math.Abs(int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1889 Examples 7

19 Source : BitmapHelper.cs
with Apache License 2.0
from AnkiUniversal

public bool IsDiffer(PixelColors color, int diff)
            {
                if (Math.Abs(this.Red - color.Red) > diff)
                    return true;
                if (Math.Abs(this.Green - color.Green) > diff)
                    return true;
                if (Math.Abs(this.Blue - color.Blue) > diff)
                    return true;

                return false;
            }

19 Source : BuildingBlockProvider.cs
with MIT License
from AnnoDesigner

private bool ParseBuildingBlockerForAnno1800(XmlDoreplacedent ifoDoreplacedent, IBuildingInfo building)
        {
            try
            {
                var xf = 0;
                var zf = 0;
                string xc, zc = ""; // just information for checking line calculated mode

                // Change since 25-05-2021 - Fixing measurements of Buildings Buildblockers. 
                // Insttead of taking one XF * 2 and ZF * 2, it will check now the differences between 2 given XF's and ZF's
                // Get all 4 [Position] childs from xml .ifo doreplacedent
                XmlNode node1 = ifoDoreplacedent.FirstChild?[BUILDBLOCKER].FirstChild;
                XmlNode node2 = ifoDoreplacedent.FirstChild?[BUILDBLOCKER].FirstChild.NextSibling;
                XmlNode node3 = ifoDoreplacedent.FirstChild?[BUILDBLOCKER].FirstChild.NextSibling.NextSibling;
                XmlNode node4 = ifoDoreplacedent.FirstChild?[BUILDBLOCKER].FirstChild.NextSibling.NextSibling.NextSibling;

                //check of the nodes contains data
                if (string.IsNullOrEmpty(node1?.InnerText) || string.IsNullOrEmpty(node2?.InnerText) || string.IsNullOrEmpty(node3?.InnerText) || string.IsNullOrEmpty(node4?.InnerText))
                {
                    Console.WriteLine("-'X' and 'Z' are both 'Null' - Building will be skipped!");
                    return false;
                }

                building.BuildBlocker = new SerializableDictionary<int>();

                //Convert the strings to a Variable and replace the "." for a "," to keep calculatable numbers 
                var xfNormal1 = Convert.ToDouble(node1["xf"].InnerText.Replace(".", ","));
                var zfNormal1 = Convert.ToDouble(node1["zf"].InnerText.Replace(".", ","));
                var xfNormal2 = Convert.ToDouble(node2["xf"].InnerText.Replace(".", ","));
                var zfNormal2 = Convert.ToDouble(node2["zf"].InnerText.Replace(".", ","));
                var xfNormal3 = Convert.ToDouble(node3["xf"].InnerText.Replace(".", ","));
                var zfNormal3 = Convert.ToDouble(node3["zf"].InnerText.Replace(".", ","));
                var xfNormal4 = Convert.ToDouble(node4["xf"].InnerText.Replace(".", ","));
                var zfNormal4 = Convert.ToDouble(node4["zf"].InnerText.Replace(".", ","));

                // Calculation mode check highest number minus lowest number
                // example 1:  9 - -2 = 11
                // example 2: 2,5 - -2,5 = 5
                // This will give the right BuildBlocker[X] and BuildBlocker[Y] for all buildings from anno 1800

                // XF Calculation 
                if (xfNormal1 > xfNormal3)
                {
                    xf = Convert.ToInt32(xfNormal1 - xfNormal3);
                    xc = "MA";// just information for checking line calculated mode
                } else
                {
                    xf = Convert.ToInt32(xfNormal3 - xfNormal1);
                    xc = "MB";// just information for checking line calculated mode
                }

                // zf Calculation 
                if (zfNormal1 > zfNormal2)
                {
                    zf = Convert.ToInt32(zfNormal1 - zfNormal2);
                    zc = "MA";// just information for checking line calculated mode
                }
                else if (zfNormal1 == zfNormal2)
                {
                    if (zfNormal1 > zfNormal3)
                    {
                        zf = Convert.ToInt32(zfNormal1 - zfNormal3);
                        zc = "MB";// just information for checking line calculated mode
                    }
                    else
                    {
                        zf = Convert.ToInt32(zfNormal3 - zfNormal1);
                        zc = "MD";// just information for checking line calculated mode
                    }
                }
                else
                {
                    zf = Convert.ToInt32(zfNormal2 - zfNormal1);
                    zc = "MC";// just information for checking line calculated mode
                }

                
                if ((xf == 0 || zf == 0) && building.Identifier != "Trail_05x05") {
                    //when something goes wrong on the measurements, report and stop till a key is hit
                    Console.WriteLine("MEASUREMENTS GOING WRONG!!! CHECK THIS BUILDING");
                    Console.WriteLine(" Node 1 - XF: {0} | ZF: {1} ;\n Node 2 - XF: {2} | ZF: {3} ;\n Node 3 - XF: {4} | ZF: {5} ;\n Node 4 - XF: {6} | ZF: {7}", xfNormal1, zfNormal1, xfNormal2, zfNormal2, xfNormal3, zfNormal3, xfNormal4, zfNormal4);
                    Console.WriteLine("Building measurement is : {0} x {1} (Method {2} and {3})", xf, zf, xc, zc);
                    Console.WriteLine("Press a key to continue");
                    //Console.ReadKey();
                }

                //if both values are zero, then skip building
                if (xf < 1 && zf < 1)
                {
                    Console.WriteLine("-'X' and 'Z' are both 0 - Building will be skipped!");
                    return false;
                }

                if (xf > 0)
                {
                    building.BuildBlocker[X] = Math.Abs(xf);
                }
                else
                {
                    building.BuildBlocker[X] = 1;
                }

                if (zf > 0)
                {
                    building.BuildBlocker[Z] = Math.Abs(zf);
                }
                else
                {
                    building.BuildBlocker[Z] = 1;
                }
            }
            catch (NullReferenceException)
            {
                Console.WriteLine("-BuildBlocker not found, skipping");
                return false;
            }

            return true;
        }

19 Source : Plotter.cs
with GNU General Public License v3.0
from anotak

public void DrawLineSolid(int x1, int y1, int x2, int y2, ref PixelColor c, uint mask = 0xffffffff)
		{
			int i;

			// Check if the line is outside the screen for sure.
			// This is quickly done by checking in which area both points are. When this
			// is above, below, right or left of the screen, then skip drawing the line.
			if(((x1 < 0) && (x2 < 0)) ||
			   ((x1 > visiblewidth) && (x2 > visiblewidth)) ||
			   ((y1 < 0) && (y2 < 0)) ||
			   ((y1 > visibleheight) && (y2 > visibleheight))) return;

			// Distance of the line
			int dx = x2 - x1;
			int dy = y2 - y1;

			// Positive (absolute) distance
			int dxabs = Math.Abs(dx);
			int dyabs = Math.Abs(dy);

			// Half distance
			int x = dyabs >> 1;
			int y = dxabs >> 1;

			// Direction
			int sdx = Math.Sign(dx);
			int sdy = Math.Sign(dy);

			// Start position
			int px = x1;
			int py = y1;

			// When the line is completely inside screen,
			// then do an unchecked draw, because all of its pixels are
			// guaranteed to be within the memory range
			if((x1 >= 0) && (x2 >= 0) && (x1 < visiblewidth) && (x2 < visiblewidth) &&
			   (y1 >= 0) && (y2 >= 0) && (y1 < visibleheight) && (y2 < visibleheight))
			{
				// Draw first pixel
				pixels[py * width + px] = c;

				// Check if the line is more horizontal than vertical
				if(dxabs >= dyabs)
				{
					for(i = 0; i < dxabs; i++)
					{
						y += dyabs;
						if(y >= dxabs)
						{
							y -= dxabs;
							py += sdy;
						}
						px += sdx;

						// Draw pixel
					    if ((mask & (1 << (i & 0x7))) != 0) {
					        pixels[py * width + px] = c;
					    }
					}
				}
				// Else the line is more vertical than horizontal
				else
				{
					for(i = 0; i < dyabs; i++)
					{
						x += dxabs;
						if(x >= dyabs)
						{
							x -= dyabs;
							px += sdx;
						}
						py += sdy;

						// Draw pixel
					    if ((mask & (1 << (i & 0x7))) != 0) {
					        pixels[py * width + px] = c;
					    }
					}
				}
			}
			else
			{
				// Draw first pixel
				if((px >= 0) && (px < visiblewidth) && (py >= 0) && (py < visibleheight))
					pixels[py * width + px] = c;
				
				// Check if the line is more horizontal than vertical
				if(dxabs >= dyabs)
				{
					for(i = 0; i < dxabs; i++)
					{
						y += dyabs;
						if(y >= dxabs)
						{
							y -= dxabs;
							py += sdy;
						}
						px += sdx;
						
						// Draw pixel						
					    if ((mask & (1 << (i & 0x7))) != 0) {
					        if((px >= 0) && (px < visiblewidth) && (py >= 0) && (py < visibleheight))
					            pixels[py * width + px] = c;
					    }
					}
				}
				// Else the line is more vertical than horizontal
				else
				{
					for(i = 0; i < dyabs; i++)
					{
						x += dxabs;
						if(x >= dyabs)
						{
							x -= dyabs;
							px += sdx;
						}
						py += sdy;
						
						// Draw pixel
					    if ((mask & (1 << (i & 0x7))) != 0) {
					        if((px >= 0) && (px < visiblewidth) && (py >= 0) && (py < visibleheight))
					            pixels[py * width + px] = c;
					    }
					}
				}
			}
		}

19 Source : LinedefsMode.cs
with GNU General Public License v3.0
from anotak

protected void Highlight(Linedef l)
		{
			bool completeredraw = false;
			LinedefActionInfo action = null;

			// Often we can get away by simply undrawing the previous
			// highlight and drawing the new highlight. But if replacedociations
			// are or were drawn we need to redraw the entire display.
			
			// Previous replacedociation highlights something?
			if((highlighted != null) && (highlighted.Tag > 0)) completeredraw = true;
			
			// Set highlight replacedociation
			if(l != null)
				highlightreplacedo.Set(l.Tag, UniversalType.LinedefTag);
			else
				highlightreplacedo.Set(0, 0);

			// New replacedociation highlights something?
			if((l != null) && (l.Tag > 0)) completeredraw = true;

			// Use the line tag to highlight sectors (Doom style)
			if(General.Map.Config.LineTagIndicatesSectors)
			{
				if(l != null)
					replacedociation[0].Set(l.Tag, UniversalType.SectorTag);
				else
					replacedociation[0].Set(0, 0);
			}
			else
			{
				if(l != null)
				{
					// Check if we can find the linedefs action
					if((l.Action > 0) && General.Map.Config.LinedefActions.ContainsKey(l.Action))
						action = General.Map.Config.LinedefActions[l.Action];
				}
				
				// Determine linedef replacedociations
				for(int i = 0; i < Linedef.NUM_ARGS; i++)
				{
					// Previous replacedociation highlights something?
					if((replacedociation[i].type == UniversalType.SectorTag) ||
					   (replacedociation[i].type == UniversalType.LinedefTag) ||
					   (replacedociation[i].type == UniversalType.ThingTag) ||
                       (replacedociation[i].type == UniversalType.PortalTag)) completeredraw = true;

					// Make new replacedociation
					if(action != null)
						replacedociation[i].Set(l.Args[i], action.Args[i].Type);
					else
						replacedociation[i].Set(0, 0);

					// New replacedociation highlights something?
					if((replacedociation[i].type == UniversalType.SectorTag) ||
					   (replacedociation[i].type == UniversalType.LinedefTag) ||
					   (replacedociation[i].type == UniversalType.ThingTag) ||
                       (replacedociation[i].type == UniversalType.PortalTag)) completeredraw = true;
				}

                if (replacedociation[PORTAL_replacedOC].type != 0)
                {
                    completeredraw = true;
                }
                replacedociation[PORTAL_replacedOC].Set(0, 0);
                if (General.Map.Config.UDMF)
                {
                    if (l != null
                        && l.Fields.ContainsKey("portal")
                        && l.Fields["portal"].Type == (int)UniversalType.PortalTag)
                    {

                        replacedociation[PORTAL_replacedOC].Set(Math.Abs((int)l.Fields["portal"].Value), (int)UniversalType.PortalTag);
                    }
                    if (replacedociation[PORTAL_replacedOC].type != 0)
                    {
                        completeredraw = true;
                    }
                }

                if (replacedociation[MATCHING_replacedOC].type != 0)
                {
                    completeredraw = true;
                }
                replacedociation[MATCHING_replacedOC].Set(0, 0);
                if (action != null && action.HighlightMatchingLineID)
                {
                    if (l != null && l.Tag != 0)
                    {
                        replacedociation[MATCHING_replacedOC].Set(l.Tag, (int)UniversalType.LinedefTag);
                    }
                    if (replacedociation[MATCHING_replacedOC].type != 0)
                    {
                        completeredraw = true;
                    }
                }

            } // else for argumented linedefs
			
			// If we're changing replacedociations, then we
			// need to redraw the entire display
			if(completeredraw)
			{
				// Set new highlight and redraw completely
				highlighted = l;
				General.Interface.RedrawDisplay();
			}
			else
			{
				// Update display
				if(renderer.StartPlotter(false))
				{
					// Undraw previous highlight
					if((highlighted != null) && !highlighted.IsDisposed)
					{
						renderer.PlotLinedef(highlighted, renderer.DetermineLinedefColor(highlighted));
						renderer.PlotVertex(highlighted.Start, renderer.DetermineVertexColor(highlighted.Start));
						renderer.PlotVertex(highlighted.End, renderer.DetermineVertexColor(highlighted.End));
					}

					// Set new highlight
					highlighted = l;

					// Render highlighted item
					if((highlighted != null) && !highlighted.IsDisposed)
					{
						renderer.PlotLinedef(highlighted, General.Colors.Highlight);
						renderer.PlotVertex(highlighted.Start, renderer.DetermineVertexColor(highlighted.Start));
						renderer.PlotVertex(highlighted.End, renderer.DetermineVertexColor(highlighted.End));
					}

					// Done
					renderer.Finish();
					renderer.Present();
				}
			}

			// Show highlight info
			if((highlighted != null) && !highlighted.IsDisposed)
				General.Interface.ShowLinedefInfo(highlighted);
			else
				General.Interface.HideInfo();
		}

19 Source : SectorsMode.cs
with GNU General Public License v3.0
from anotak

protected void Highlight(Sector s)
		{
			bool completeredraw = false;

			// Often we can get away by simply undrawing the previous
			// highlight and drawing the new highlight. But if replacedociations
			// are or were drawn we need to redraw the entire display.

			// Previous replacedociation highlights something?
			if((highlighted != null) && (highlighted.Tag > 0)) completeredraw = true;

            // Set highlight replacedociation
            if (s != null)
            {
                highlightreplacedo.Set(s.Tag, UniversalType.SectorTag);
                // portals
                if (General.Map.Config.UDMF)
                {
                    // floor
                    if (portalreplacedo[0].type != 0)
                    {
                        completeredraw = true;
                    }
                    portalreplacedo[0].Set(0, 0);
                    if (s != null
                        && s.Fields.ContainsKey("portalfloor")
                        && s.Fields["portalfloor"].Type == (int)UniversalType.PortalTag)
                    {

                       portalreplacedo[0].Set(Math.Abs((int)s.Fields["portalfloor"].Value), (int)UniversalType.PortalTag);
                    }
                    if (portalreplacedo[0].type != 0)
                    {
                        completeredraw = true;
                    }

                    // ceil
                    if (portalreplacedo[1].type != 0)
                    {
                        completeredraw = true;
                    }
                    portalreplacedo[1].Set(0, 0);
                    if (s != null
                        && s.Fields.ContainsKey("portalceiling")
                        && s.Fields["portalceiling"].Type == (int)UniversalType.PortalTag)
                    {

                        portalreplacedo[1].Set(Math.Abs((int)s.Fields["portalceiling"].Value), (int)UniversalType.PortalTag);
                    }
                    if (portalreplacedo[1].type != 0)
                    {
                        completeredraw = true;
                    }
                } // portals
            }
            else
            {
                highlightreplacedo.Set(0, 0);
                for (int i = 0; i < NUM_PORTAL_replacedOCIATIONS; i++)
                {
                    if (portalreplacedo[i].type != 0)
                    {
                        completeredraw = true;
                    }
                    portalreplacedo[i].Set(0, 0);
                }
            }

            // New replacedociation highlights something?
            if ((s != null) && (s.Tag > 0)) completeredraw = true;

			// Change label color
			if((highlighted != null) && !highlighted.IsDisposed)
			{
				TextLabel[] labelarray = labels[highlighted];
				foreach(TextLabel l in labelarray) l.Color = General.Colors.Selection;
			}
			
			// Change label color
			if((s != null) && !s.IsDisposed)
			{
				TextLabel[] labelarray = labels[s];
				foreach(TextLabel l in labelarray) l.Color = General.Colors.Highlight;
			}
			
			// If we're changing replacedociations, then we
			// need to redraw the entire display
			if(completeredraw)
			{
				// Set new highlight and redraw completely
				highlighted = s;
				General.Interface.RedrawDisplay();
			}
			else
			{
				// Update display
				if(renderer.StartPlotter(false))
				{
					// Undraw previous highlight
					if((highlighted != null) && !highlighted.IsDisposed)
						renderer.PlotSector(highlighted);
					
					/*
					// Undraw highlighted things
					if(highlighted != null)
						foreach(Thing t in highlighted.Things)
							renderer.RenderThing(t, renderer.DetermineThingColor(t));
					*/

					// Set new highlight
					highlighted = s;

					// Render highlighted item
					if((highlighted != null) && !highlighted.IsDisposed)
						renderer.PlotSector(highlighted, General.Colors.Highlight);
					
					/*
					// Render highlighted things
					if(highlighted != null)
						foreach(Thing t in highlighted.Things)
							renderer.RenderThing(t, General.Colors.Highlight);
					*/

					// Done
					renderer.Finish();
				}
				
				UpdateOverlay();
				renderer.Present();
			}

			// Show highlight info
			if((highlighted != null) && !highlighted.IsDisposed)
				General.Interface.ShowSectorInfo(highlighted);
			else
				General.Interface.HideInfo();
		}

19 Source : BuilderPlug.cs
with GNU General Public License v3.0
from anotak

public void Plotreplacedociations(IRenderer2D renderer, replacedociation replacedo)
		{
			// Tag must be above zero
			if(replacedo.tag <= 0) return;
			
			// Sectors?
			if(replacedo.type == UniversalType.SectorTag)
			{
				foreach(Sector s in General.Map.Map.Sectors)
					if(s.Tag == replacedo.tag) renderer.PlotSector(s, General.Colors.Indication);
			}
			// Linedefs?
			else if(replacedo.type == UniversalType.LinedefTag)
			{
				foreach(Linedef l in General.Map.Map.Linedefs)
					if(l.Tag == replacedo.tag) renderer.PlotLinedef(l, General.Colors.Indication);
			}
            else if (General.Map.Config.UDMF && replacedo.type == UniversalType.PortalTag)
            {
                foreach (Linedef l in General.Map.Map.Linedefs)
                {
                    if (l.Fields.ContainsKey("portal")
                        && l.Fields["portal"].Type == (int)UniversalType.PortalTag
                        && Math.Abs((int)l.Fields["portal"].Value) == replacedo.tag)
                    {
                        renderer.PlotLinedef(l, General.Colors.Portals);
                    }
                }
                foreach (Sector s in General.Map.Map.Sectors)
                {
                    if ((s.Fields.ContainsKey("portalfloor")
                        && s.Fields["portalfloor"].Type == (int)UniversalType.PortalTag
                        && Math.Abs((int)s.Fields["portalfloor"].Value) == replacedo.tag)
                        ||
                        (s.Fields.ContainsKey("portalceiling")
                        && s.Fields["portalceiling"].Type == (int)UniversalType.PortalTag
                        && Math.Abs((int)s.Fields["portalceiling"].Value) == replacedo.tag))
                    {
                        renderer.PlotSector(s, General.Colors.Portals);
                    }
                }
            }
        }

19 Source : Mathf.cs
with MIT License
from AnotherEnd15

public static int Abs(int value)
        {
            return Math.Abs(value);
        }

19 Source : ProfileAppService.cs
with MIT License
from anteatergames

public ProfileViewModel GenerateNewOne(ProfileType type)
        {
            ProfileViewModel profile = new ProfileViewModel();

            RandomNumberGenerator randomGenerator = RandomNumberGenerator.Create();
            byte[] data = new byte[4];
            randomGenerator.GetBytes(data);
            int randomNumber = BitConverter.ToInt32(data);

            profile.Type = ProfileType.Personal;

            profile.Name = String.Format("NPC {0}", Math.Abs(randomNumber));
            profile.Motto = "It is dangerous out there, take this...";

            profile.Bio = String.Format("{0} {1}", profile.Name, Constants.DefaultProfileDescription);

            profile.StudioName = "Awesome Game Studio";
            profile.Location = "Earth";

            profile.ProfileImageUrl = Constants.DefaultAvatar;
            profile.CoverImageUrl = Constants.DefaultGameCoverImage;

            return profile;
        }

19 Source : TimeFormatter.cs
with MIT License
from AntonyCorbett

public static string FormatTimerDisplayString(int totalSeconds)
        {
            var mins = Math.Abs(totalSeconds) / SecsPerMinute;
            var secs = Math.Abs(totalSeconds) % SecsPerMinute;

            return $"{mins:D2}:{secs:D2}";
        }

19 Source : PdfTimingReport.cs
with MIT License
from AntonyCorbett

private void DrawSummary(XGraphics g, TimeSpan plannedEnd, TimeSpan actualEnd)
        {
            if (_subreplacedleFont == null)
            {
                throw new InvalidOperationException(nameof(_replacedleFont));
            }

            if (_itemFont == null)
            {
                throw new InvalidOperationException(nameof(_itemFont));
            }

            if (_itemreplacedleFont == null)
            {
                throw new InvalidOperationException(nameof(_itemreplacedleFont));
            }

            _currentY += 2 * _itemreplacedleFont.Height;

            var linePen = new XPen(XColors.Gray);
            g.DrawLine(linePen, _leftMargin, _currentY, _rightX, _currentY);

            _currentY += _subreplacedleFont.Height;

            g.DrawString(Resources.OVERALL_STATUS, _subreplacedleFont, _blackBrush, new XPoint(_leftMargin, _currentY));
            _currentY += _subreplacedleFont.Height;

            var minsOvertime = (actualEnd - plannedEnd).TotalMinutes;
            if (minsOvertime > 1)
            {
                var mins = (int)Math.Round(minsOvertime);

                var msg = mins == 1
                   ? Resources.OVERTIME_BY_1
                   : string.Format(Resources.OVERTIME_BY, mins);

                g.DrawString(msg, _itemreplacedleFont, _redBrush, new XPoint(_leftMargin, _currentY));
            }
            else if (minsOvertime < -1)
            {
                var mins = Math.Abs((int)Math.Round(minsOvertime));
                var msg = mins == 1
                   ? Resources.UNDERTIME_BY_1
                   : string.Format(Resources.UNDERTIME_BY, mins);

                g.DrawString(msg, _itemreplacedleFont, _greenBrush, new XPoint(_leftMargin, _currentY));
            }
            else
            {
                g.DrawString(Resources.ON_TIME, _itemreplacedleFont, _greenBrush, new XPoint(_leftMargin, _currentY));
            }

            _currentY += (double)_itemFont.Height / 2;
            g.DrawLine(linePen, _leftMargin, _currentY, _rightX, _currentY);
        }

19 Source : PdfTimingReport.cs
with MIT License
from AntonyCorbett

private void DrawItemOvertime(XGraphics g, double curX, TimeSpan duration, TimeSpan allowedDuration)
        {
            if (_stdTimeFont == null)
            {
                throw new InvalidOperationException(nameof(_stdTimeFont));
            }

            var overtime = allowedDuration - duration;
            var inTheRed = (int)overtime.TotalSeconds < 0;
            var inTheGreen = (int)overtime.TotalSeconds >= 0;
            var spotOn = (int)overtime.TotalSeconds == 0;

            var prefix = string.Empty;

            if (!spotOn)
            {
                prefix = inTheGreen ? "-" : "+";
            }

            var s = $"{prefix} {Math.Abs(overtime.Minutes):D2}:{Math.Abs(overtime.Seconds):D2}";

            var sz = g.MeasureString(s, _durationFont);

            var startX = _rightXIndent - sz.Width;

            var dotsStartX = curX + _stdTimeFont.Height;
            var dotsLength = startX - _stdTimeFont.Height - dotsStartX;

            var sb = new StringBuilder(".");
            var dotsSz = g.MeasureString(sb.ToString(), _smallTimeFont);
            while (dotsSz.Width < dotsLength)
            {
                sb.Append('.');
                dotsSz = g.MeasureString(sb.ToString(), _smallTimeFont);
            }

            dotsStartX = startX - _stdTimeFont.Height - dotsSz.Width;
            g.DrawString(sb.ToString(), _smallTimeFont, XBrushes.LightGray, new XPoint(dotsStartX, _currentY));

            var inTheRedBrush = inTheRed
                ? _redBrush
                : _blackBrush;

            var brush = inTheGreen
                ? _greenBrush
                : inTheRedBrush;

            g.DrawString(s, _durationFont, brush, new XPoint(startX, _currentY));
        }

19 Source : NmsSynchronizationMonitorTest.cs
with Apache License 2.0
from apache

[Test]
        public void TestNestedLockAndWait()
        {
            NmsSynchronizationMonitor syncRoot = new NmsSynchronizationMonitor();
            ManualResetEvent lockedEvent = new ManualResetEvent(false);

            EventList evList = new EventList();

            var task = Task.Run(() =>
            {
                Thread.Sleep(5);
                using (syncRoot.Lock())
                {
                    evList.Add("A1");
                    Thread.Sleep(1);
                    evList.Add("A1");
                    Thread.Sleep(1);
                    evList.Add("A1");
                    Thread.Sleep(1);

                    using (syncRoot.Lock())
                    {
                        evList.Add("A1");
                        Thread.Sleep(1);
                        evList.Add("A1");
                        Thread.Sleep(1);
                        evList.Add("A1");
                        Thread.Sleep(1);

                        lockedEvent.Set();
                        syncRoot.Wait();

                        evList.Add("A2");
                        Thread.Sleep(1);
                        evList.Add("A2");
                        Thread.Sleep(1);
                        evList.Add("A2");
                        Thread.Sleep(1);
                    }

                    evList.Add("A2");
                    Thread.Sleep(1);
                    evList.Add("A2");
                    Thread.Sleep(1);
                    evList.Add("A2");
                    Thread.Sleep(1);
                }
            });

            var taskB = Task.Run(() =>
            {
                while (!task.IsCompleted)
                {
                    using (syncRoot.Lock())
                    {
                        evList.Add("B");
                        Thread.Sleep(1);
                    }
                }
            });

            lockedEvent.WaitOne();
            Thread.Sleep(10); // to give Task A Time to go to sleep and B to work


            Task.Run(() => { syncRoot.Pulse(); });

            task.Wait();
            taskB.Wait();


            // Now replacedes that block A1 and A2 are not intersected by B, however A1 And A2 should have some B between (during sleep period)
            var events = evList.list.Select((a, i) => new Tuple<string, int>(a, i));
            var a1 = events.Where(a => a.Item1 == "A1").ToList();
            var a2 = events.Where(a => a.Item1 == "A2").ToList();
            replacedert.AreEqual(6, a1.Count());
            replacedert.AreEqual(5, a1.Last().Item2 - a1.First().Item2); // not intersected by anything

            replacedert.AreEqual(6, a2.Count());
            replacedert.AreEqual(5, a2.Last().Item2 - a2.First().Item2); // not intersected by anything

            replacedert.Greater(Math.Abs(a1.Last().Item2 - a2.First().Item2), 1, "A1 and A2, should be intersected by B, and not happening one right after another");
        }

19 Source : NmsSynchronizationMonitorTest.cs
with Apache License 2.0
from apache

[Test]
        public void TestNestedLockAndWaitAsync()
        {
            NmsSynchronizationMonitor syncRoot = new NmsSynchronizationMonitor();
            ManualResetEvent lockedEvent = new ManualResetEvent(false);

            EventList evList = new EventList();

            var task = Task.Run(async () =>
            {
                Thread.Sleep(5);
                using (await syncRoot.LockAsync())
                {
                    evList.Add("A1");
                    await Task.Delay(1);
                    await Task.Yield();
                    evList.Add("A1");
                    await Task.Delay(1);
                    await Task.Yield();
                    evList.Add("A1");
                    await Task.Delay(1);
                    await Task.Yield();

                    using (await syncRoot.LockAsync())
                    {
                        evList.Add("A1");
                        await Task.Delay(1);
                        await Task.Yield();
                        evList.Add("A1");
                        await Task.Delay(1);
                        await Task.Yield();
                        evList.Add("A1");
                        await Task.Delay(1);
                        await Task.Yield();

                        lockedEvent.Set();
                        await syncRoot.WaitAsync();

                        evList.Add("A2");
                        await Task.Delay(1);
                        await Task.Yield();
                        evList.Add("A2");
                        await Task.Delay(1);
                        await Task.Yield();
                        evList.Add("A2");
                        await Task.Delay(1);
                        await Task.Yield();
                    }

                    evList.Add("A2");
                    await Task.Delay(1);
                    await Task.Yield();
                    evList.Add("A2");
                    await Task.Delay(1);
                    await Task.Yield();
                    evList.Add("A2");
                    await Task.Delay(1);
                    await Task.Yield();
                }
            });

            var taskB = Task.Run(async () =>
            {
                while (!task.IsCompleted)
                {
                    using (await syncRoot.LockAsync())
                    {
                        evList.Add("B");
                        await Task.Delay(1);
                    }
                }
            });

            lockedEvent.WaitOne();
            Thread.Sleep(10); // to give Task A Time to go to sleep and B to work


            Task.Run(() => { syncRoot.Pulse(); });

            task.Wait();
            taskB.Wait();


            // Now replacedes that block A1 and A2 are not intersected by B, however A1 And A2 should have some B between (during sleep period)
            var events = evList.list.Select((a, i) => new Tuple<string, int>(a, i));
            var a1 = events.Where(a => a.Item1 == "A1").ToList();
            var a2 = events.Where(a => a.Item1 == "A2").ToList();
            replacedert.AreEqual(6, a1.Count());
            replacedert.AreEqual(5, a1.Last().Item2 - a1.First().Item2); // not intersected by anything

            replacedert.AreEqual(6, a2.Count());
            replacedert.AreEqual(5, a2.Last().Item2 - a2.First().Item2); // not intersected by anything

            replacedert.Greater(Math.Abs(a1.Last().Item2 - a2.First().Item2), 1, "A1 and A2, should be intersected by B, and not happening one right after another");
        }

19 Source : CustomApexCodeGeneratorTests.cs
with MIT License
from apexsharp

protected void CompareLineByLine(string actual, string expected)
        {
            var actualList = actual.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
            var expectedList = expected.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);

            for (int i = 0; i < Min(expectedList.Length, actualList.Length); i++)
            {
                replacedert.AreEqual(expectedList[i].Trim(), actualList[i].Trim());
            }

            if (Abs(expectedList.Length - actualList.Length) > 1)
            {
                replacedert.Fail("Too many difference in lines: expected {0}, actual {1}", expectedList.Length, actualList.Length);
            }
        }

19 Source : MathImplementation.cs
with MIT License
from apexsharp

public int abs(int integerValue) => Abs(integerValue);

19 Source : CellStore.cs
with Apache License 2.0
from Appdynamics

private void UpdatePageOffset(ColumnIndex column, int pagePos, int rows)
        {
            //Update Pageoffset
            
            if (++pagePos < column.PageCount)
            {
                for (int p = pagePos; p < column.PageCount; p++)
                {
                    if (column._pages[p].Offset - rows <= -PageSize)
                    {
                        column._pages[p].Index--;
                        column._pages[p].Offset -= rows-PageSize;
                    }
                    else
                    {
                        column._pages[p].Offset -= rows;
                    }
                }

                if (Math.Abs(column._pages[pagePos].Offset) > PageSize ||
                    Math.Abs(column._pages[pagePos].Rows[column._pages[pagePos].RowCount-1].Index) > PageSizeMax) //Split or Merge???
                {
                    rows=ResetPageOffset(column, pagePos, rows);
                    ////MergePages
                    //if (column.Pages[pagePos - 1].Index + 1 == column.Pages[pagePos].Index)
                    //{
                    //    if (column.Pages[pagePos].IndexOffset + column.Pages[pagePos].Rows[column.Pages[pagePos].RowCount - 1].Index + rows -
                    //        column.Pages[pagePos - 1].IndexOffset + column.Pages[pagePos - 1].Rows[0].Index <= PageSize)
                    //    {
                    //        //Merge
                    //        MergePage(column, pagePos - 1, -rows);
                    //    }
                    //    else
                    //    {
                    //        //Split
                    //    }
                    //}
                    //rows -= PageSize;
                    //for (int p = pagePos; p < column.PageCount; p++)
                    //{                            
                    //    column.Pages[p].Index -= 1;
                    //}
                    return;
                }
            }
        }

19 Source : ExcelWorksheet.cs
with Apache License 2.0
from Appdynamics

private void FixSharedFormulasRows(int position, int rows)
        {
            List<Formulas> added = new List<Formulas>();
            List<Formulas> deleted = new List<Formulas>();

            foreach (int id in _sharedFormulas.Keys)
            {
                var f = _sharedFormulas[id];
                int fromCol, fromRow, toCol, toRow;

                ExcelCellBase.GetRowColFromAddress(f.Address, out fromRow, out fromCol, out toRow, out toCol);
                if (position >= fromRow && position+(Math.Abs(rows)) <= toRow) //Insert/delete is whithin the share formula address
                {
                    if (rows > 0) //Insert
                    {
                        f.Address = ExcelCellBase.GetAddress(fromRow, fromCol) + ":" + ExcelCellBase.GetAddress(position - 1, toCol);
                        if (toRow != fromRow)
                        {
                            Formulas newF = new Formulas(SourceCodeTokenizer.Default);
                            newF.StartCol = f.StartCol;
                            newF.StartRow = position + rows;
                            newF.Address = ExcelCellBase.GetAddress(position + rows, fromCol) + ":" + ExcelCellBase.GetAddress(toRow + rows, toCol);
                            newF.Formula = ExcelCellBase.TranslateFromR1C1(ExcelCellBase.TranslateToR1C1(f.Formula, f.StartRow, f.StartCol), position, f.StartCol);
                            added.Add(newF);
                        }
                    }
                    else
                    {
                        if (fromRow - rows < toRow)
                        {
                            f.Address = ExcelCellBase.GetAddress(fromRow, fromCol, toRow+rows, toCol);
                        }
                        else
                        {
                            f.Address = ExcelCellBase.GetAddress(fromRow, fromCol) + ":" + ExcelCellBase.GetAddress(toRow + rows, toCol);
                        }
                    }
                }
                else if (position <= toRow)
                {
                    if (rows > 0) //Insert before shift down
                    {
                        f.StartRow += rows;
                        //f.Formula = ExcelCell.UpdateFormulaReferences(f.Formula, rows, 0, position, 0); //Recalc the cells positions
                        f.Address = ExcelCellBase.GetAddress(fromRow + rows, fromCol) + ":" + ExcelCellBase.GetAddress(toRow + rows, toCol);
                    }
                    else
                    {
                        //Cells[f.Address].SetSharedFormulaID(int.MinValue);
                        if (position <= fromRow && position + Math.Abs(rows) > toRow)  //Delete the formula 
                        {
                            deleted.Add(f);
                        }
                        else
                        {
                            toRow = toRow + rows < position - 1 ? position - 1 : toRow + rows;
                            if (position <= fromRow)
                            {
                                fromRow = fromRow + rows < position ? position : fromRow + rows;
                            }

                            f.Address = ExcelCellBase.GetAddress(fromRow, fromCol, toRow, toCol);
                            Cells[f.Address].SetSharedFormulaID(f.Index);
                            //f.StartRow = fromRow;

                            //f.Formula = ExcelCell.UpdateFormulaReferences(f.Formula, rows, 0, position, 0);
                       
                        }
                    }
                }
            }

            AddFormulas(added, position, rows);

            //Remove formulas
            foreach (Formulas f in deleted)
            {
                _sharedFormulas.Remove(f.Index);
            }

            //Fix Formulas
            added = new List<Formulas>();
            foreach (int id in _sharedFormulas.Keys)
            {
                var f = _sharedFormulas[id];
                UpdateSharedFormulaRow(ref f, position, rows, ref added);
            }
            AddFormulas(added, position, rows);
        }

19 Source : SampleMetrics.cs
with Apache License 2.0
from AppMetrics

public void Request(int i)
        {
            var multiContextMetrics = new MultiContextMetrics(_metrics);
            multiContextMetrics.Run();

            for (var j = 0; j < 5; j++)
            {
                var multiContextInstanceMetrics = new MultiContextInstanceMetrics("Sample Instance " + i.ToString(), _metrics);
                multiContextInstanceMetrics.Run();
            }

            using (_timer.NewContext(i.ToString())) // measure until disposed
            {
                _someValue *= (i + 1); // will be reflected in the gauge 

                _concurrentRequestsCounter.Increment(); // increment concurrent requests counter

                _totalRequestsCounter.Increment(); // increment total requests counter 

                _meter.Mark(); // signal a new request to the meter

                _histogramOfData.Update(new Random().Next(5000), "user-value-" + i); // update the histogram with the input data

                var item = "Item " + new Random().Next(5);
                _setCounter.Increment(item);

                _setMeter.Mark(item);

                // simulate doing some work
                var ms = Math.Abs((int)(new Random().Next(3000)));
                Thread.Sleep(ms);

                _concurrentRequestsCounter.Decrement(); // decrement number of concurrent requests
            }
        }

19 Source : TimeHelper.cs
with MIT License
from aprilyush

public static DateTime GetRandomTime(DateTime time1, DateTime time2)
        {
            Random random = new Random();
            DateTime minTime = new DateTime();
            DateTime maxTime = new DateTime();

            System.TimeSpan ts = new System.TimeSpan(time1.Ticks - time2.Ticks);

            // 获取两个时间相隔的秒数
            double dTotalSecontds = ts.TotalSeconds;
            int iTotalSecontds = 0;

            if (dTotalSecontds > System.Int32.MaxValue)
            {
                iTotalSecontds = System.Int32.MaxValue;
            }
            else if (dTotalSecontds < System.Int32.MinValue)
            {
                iTotalSecontds = System.Int32.MinValue;
            }
            else
            {
                iTotalSecontds = (int)dTotalSecontds;
            }


            if (iTotalSecontds > 0)
            {
                minTime = time2;
                maxTime = time1;
            }
            else if (iTotalSecontds < 0)
            {
                minTime = time1;
                maxTime = time2;
            }
            else
            {
                return time1;
            }

            int maxValue = iTotalSecontds;

            if (iTotalSecontds <= System.Int32.MinValue)
                maxValue = System.Int32.MinValue + 1;

            int i = random.Next(System.Math.Abs(maxValue));

            return minTime.AddSeconds(i);
        }

19 Source : Detector.cs
with MIT License
from architdate

private ResultPointsAndTransitions transitionsBetween(ResultPoint from, ResultPoint to)
		{
			// See QR Code Detector, sizeOfBlackWhiteBlackRun()
			//UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
			int fromX = (int) from.X;
			//UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
			int fromY = (int) from.Y;
			//UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
			int toX = (int) to.X;
			//UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
			int toY = (int) to.Y;
			bool steep = System.Math.Abs(toY - fromY) > System.Math.Abs(toX - fromX);
			if (steep)
			{
				int temp = fromX;
				fromX = fromY;
				fromY = temp;
				temp = toX;
				toX = toY;
				toY = temp;
			}
			
			int dx = System.Math.Abs(toX - fromX);
			int dy = System.Math.Abs(toY - fromY);
			int error = - dx >> 1;
			int ystep = fromY < toY?1:- 1;
			int xstep = fromX < toX?1:- 1;
			int transitions = 0;
			bool inBlack = image.get_Renamed(steep?fromY:fromX, steep?fromX:fromY);
			for (int x = fromX, y = fromY; x != toX; x += xstep)
			{
				bool isBlack = image.get_Renamed(steep?y:x, steep?x:y);
				if (isBlack != inBlack)
				{
					transitions++;
					inBlack = isBlack;
				}
				error += dy;
				if (error > 0)
				{
					if (y == toY)
					{
						break;
					}
					y += ystep;
					error -= dx;
				}
			}
			return new ResultPointsAndTransitions(from, to, transitions);
		}

19 Source : AlignmentPatternFinder.cs
with MIT License
from architdate

private float crossCheckVertical(int startI, int centerJ, int maxCount, int originalStateCountTotal)
		{
			BitMatrix image = this.image;
			
			int maxI = image.Height;
			int[] stateCount = crossCheckStateCount;
			stateCount[0] = 0;
			stateCount[1] = 0;
			stateCount[2] = 0;
			
			// Start counting up from center
			int i = startI;
			while (i >= 0 && image.get_Renamed(centerJ, i) && stateCount[1] <= maxCount)
			{
				stateCount[1]++;
				i--;
			}
			// If already too many modules in this state or ran off the edge:
			if (i < 0 || stateCount[1] > maxCount)
			{
				return System.Single.NaN;
			}
			while (i >= 0 && !image.get_Renamed(centerJ, i) && stateCount[0] <= maxCount)
			{
				stateCount[0]++;
				i--;
			}
			if (stateCount[0] > maxCount)
			{
				return System.Single.NaN;
			}
			
			// Now also count down from center
			i = startI + 1;
			while (i < maxI && image.get_Renamed(centerJ, i) && stateCount[1] <= maxCount)
			{
				stateCount[1]++;
				i++;
			}
			if (i == maxI || stateCount[1] > maxCount)
			{
				return System.Single.NaN;
			}
			while (i < maxI && !image.get_Renamed(centerJ, i) && stateCount[2] <= maxCount)
			{
				stateCount[2]++;
				i++;
			}
			if (stateCount[2] > maxCount)
			{
				return System.Single.NaN;
			}
			
			int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2];
			if (5 * System.Math.Abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal)
			{
				return System.Single.NaN;
			}
			
			return foundPatternCross(stateCount)?centerFromEnd(stateCount, i):System.Single.NaN;
		}

19 Source : FinderPatternFinder.cs
with MIT License
from architdate

protected internal static bool foundPatternCross(int[] stateCount)
		{
			int totalModuleSize = 0;
			for (int i = 0; i < 5; i++)
			{
				int count = stateCount[i];
				if (count == 0)
				{
					return false;
				}
				totalModuleSize += count;
			}
			if (totalModuleSize < 7)
			{
				return false;
			}
			int moduleSize = (totalModuleSize << INTEGER_MATH_SHIFT) / 7;
			int maxVariance = moduleSize / 2;
			// Allow less than 50% variance from 1-1-3-1-1 proportions
			return System.Math.Abs(moduleSize - (stateCount[0] << INTEGER_MATH_SHIFT)) < maxVariance && System.Math.Abs(moduleSize - (stateCount[1] << INTEGER_MATH_SHIFT)) < maxVariance && System.Math.Abs(3 * moduleSize - (stateCount[2] << INTEGER_MATH_SHIFT)) < 3 * maxVariance && System.Math.Abs(moduleSize - (stateCount[3] << INTEGER_MATH_SHIFT)) < maxVariance && System.Math.Abs(moduleSize - (stateCount[4] << INTEGER_MATH_SHIFT)) < maxVariance;
		}

19 Source : Detector.cs
with MIT License
from architdate

private float sizeOfBlackWhiteBlackRun(int fromX, int fromY, int toX, int toY)
		{
			// Mild variant of Bresenham's algorithm;
			// see http://en.wikipedia.org/wiki/Bresenham's_line_algorithm
			bool steep = System.Math.Abs(toY - fromY) > System.Math.Abs(toX - fromX);
			if (steep)
			{
				int temp = fromX;
				fromX = fromY;
				fromY = temp;
				temp = toX;
				toX = toY;
				toY = temp;
			}
			
			int dx = System.Math.Abs(toX - fromX);
			int dy = System.Math.Abs(toY - fromY);
			int error = - dx >> 1;
			int ystep = fromY < toY?1:- 1;
			int xstep = fromX < toX?1:- 1;
			int state = 0; // In black pixels, looking for white, first or second time
			for (int x = fromX, y = fromY; x != toX; x += xstep)
			{
				
				int realX = steep?y:x;
				int realY = steep?x:y;
				if (state == 1)
				{
					// In white pixels, looking for black
					if (image.get_Renamed(realX, realY))
					{
						state++;
					}
				}
				else
				{
					if (!image.get_Renamed(realX, realY))
					{
						state++;
					}
				}
				
				if (state == 3)
				{
					// Found black, white, black, and stumbled back onto white; done
					int diffX = x - fromX;
					int diffY = y - fromY;
					//UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
					return (float) System.Math.Sqrt((double) (diffX * diffX + diffY * diffY));
				}
				error += dy;
				if (error > 0)
				{
					if (y == toY)
					{
						break;
					}
					y += ystep;
					error -= dx;
				}
			}
			int diffX2 = toX - fromX;
			int diffY2 = toY - fromY;
			//UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
			return (float) System.Math.Sqrt((double) (diffX2 * diffX2 + diffY2 * diffY2));
		}

19 Source : FinderPatternFinder.cs
with MIT License
from architdate

private float crossCheckVertical(int startI, int centerJ, int maxCount, int originalStateCountTotal)
		{
			BitMatrix image = this.image;
			
			int maxI = image.Height;
			int[] stateCount = CrossCheckStateCount;
			
			// Start counting up from center
			int i = startI;
			while (i >= 0 && image.get_Renamed(centerJ, i))
			{
				stateCount[2]++;
				i--;
			}
			if (i < 0)
			{
				return System.Single.NaN;
			}
			while (i >= 0 && !image.get_Renamed(centerJ, i) && stateCount[1] <= maxCount)
			{
				stateCount[1]++;
				i--;
			}
			// If already too many modules in this state or ran off the edge:
			if (i < 0 || stateCount[1] > maxCount)
			{
				return System.Single.NaN;
			}
			while (i >= 0 && image.get_Renamed(centerJ, i) && stateCount[0] <= maxCount)
			{
				stateCount[0]++;
				i--;
			}
			if (stateCount[0] > maxCount)
			{
				return System.Single.NaN;
			}
			
			// Now also count down from center
			i = startI + 1;
			while (i < maxI && image.get_Renamed(centerJ, i))
			{
				stateCount[2]++;
				i++;
			}
			if (i == maxI)
			{
				return System.Single.NaN;
			}
			while (i < maxI && !image.get_Renamed(centerJ, i) && stateCount[3] < maxCount)
			{
				stateCount[3]++;
				i++;
			}
			if (i == maxI || stateCount[3] >= maxCount)
			{
				return System.Single.NaN;
			}
			while (i < maxI && image.get_Renamed(centerJ, i) && stateCount[4] < maxCount)
			{
				stateCount[4]++;
				i++;
			}
			if (stateCount[4] >= maxCount)
			{
				return System.Single.NaN;
			}
			
			// If we found a finder-pattern-like section, but its size is more than 40% different than
			// the original, replacedume it's a false positive
			int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
			if (5 * System.Math.Abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal)
			{
				return System.Single.NaN;
			}
			
			return foundPatternCross(stateCount)?centerFromEnd(stateCount, i):System.Single.NaN;
		}

19 Source : FinderPatternFinder.cs
with MIT License
from architdate

private float crossCheckHorizontal(int startJ, int centerI, int maxCount, int originalStateCountTotal)
		{
			BitMatrix image = this.image;
			
			int maxJ = image.Width;
			int[] stateCount = CrossCheckStateCount;
			
			int j = startJ;
			while (j >= 0 && image.get_Renamed(j, centerI))
			{
				stateCount[2]++;
				j--;
			}
			if (j < 0)
			{
				return System.Single.NaN;
			}
			while (j >= 0 && !image.get_Renamed(j, centerI) && stateCount[1] <= maxCount)
			{
				stateCount[1]++;
				j--;
			}
			if (j < 0 || stateCount[1] > maxCount)
			{
				return System.Single.NaN;
			}
			while (j >= 0 && image.get_Renamed(j, centerI) && stateCount[0] <= maxCount)
			{
				stateCount[0]++;
				j--;
			}
			if (stateCount[0] > maxCount)
			{
				return System.Single.NaN;
			}
			
			j = startJ + 1;
			while (j < maxJ && image.get_Renamed(j, centerI))
			{
				stateCount[2]++;
				j++;
			}
			if (j == maxJ)
			{
				return System.Single.NaN;
			}
			while (j < maxJ && !image.get_Renamed(j, centerI) && stateCount[3] < maxCount)
			{
				stateCount[3]++;
				j++;
			}
			if (j == maxJ || stateCount[3] >= maxCount)
			{
				return System.Single.NaN;
			}
			while (j < maxJ && image.get_Renamed(j, centerI) && stateCount[4] < maxCount)
			{
				stateCount[4]++;
				j++;
			}
			if (stateCount[4] >= maxCount)
			{
				return System.Single.NaN;
			}
			
			// If we found a finder-pattern-like section, but its size is significantly different than
			// the original, replacedume it's a false positive
			int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
			if (5 * System.Math.Abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal)
			{
				return System.Single.NaN;
			}
			
			return foundPatternCross(stateCount)?centerFromEnd(stateCount, j):System.Single.NaN;
		}

19 Source : MaskUtil.cs
with MIT License
from architdate

public static int applyMaskPenaltyRule4(ByteMatrix matrix)
		{
			int numDarkCells = 0;
			sbyte[][] array = matrix.Array;
			int width = matrix.Width;
			int height = matrix.Height;
			for (int y = 0; y < height; ++y)
			{
				for (int x = 0; x < width; ++x)
				{
					if (array[y][x] == 1)
					{
						numDarkCells += 1;
					}
				}
			}
			int numTotalCells = matrix.Height * matrix.Width;
			double darkRatio = (double) numDarkCells / numTotalCells;
			//UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
			return System.Math.Abs((int) (darkRatio * 100 - 50)) / 5 * 10;
		}

19 Source : ArchiveReader.cs
with MIT License
from ark-mod

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void SkipString()
        {
            GetInt(out var size, "size");
            if (size == 0) return;
            if (size == 1)
            {
                _position += 1;
                return;
            }
            if (size == -1)
            {
                _position += 2;
                return;
            }

            var multibyte = size < 0;
            var absSize = Math.Abs(size);
            var readSize = multibyte ? absSize * 2 : absSize;

            _offset += readSize;
            _position += readSize;
        }

19 Source : Node_shapes.cs
with GNU Affero General Public License v3.0
from arklumpus

public static Point[] PlotAction(TreeNode tree, Dictionary<string, object> parameterValues, Dictionary<string, Point> coordinates, Graphics graphics)
        {
            List<TreeNode> nodes = tree.GetChildrenRecursive();

            double minX = double.MaxValue;
            double maxX = double.MinValue;
            double minY = double.MaxValue;
            double maxY = double.MinValue;

            bool anyPoint = false;

            void updateMaxMin(Point pt)
            {
                anyPoint = true;

                minX = Math.Min(minX, pt.X);
                maxX = Math.Max(maxX, pt.X);
                minY = Math.Min(minY, pt.Y);
                maxY = Math.Max(maxY, pt.Y);
            }

            static double distance(Point p1, Point p2)
            {
                return Math.Sqrt((p1.X - p2.X) * (p1.X - p2.X) + (p1.Y - p2.Y) * (p1.Y - p2.Y));
            };

            static Point sumPoint(Point p1, Point p2)
            {
                return new Point(p1.X + p2.X, p1.Y + p2.Y);
            }

            static Point subtractPoint(Point p1, Point p2)
            {
                return new Point(p1.X - p2.X, p1.Y - p2.Y);
            }

            static Point multiplyPoint(Point p1, double scale)
            {
                return new Point(p1.X * scale, p1.Y * scale);
            }

            int showOn = (int)parameterValues["Show on:"];
            int anchor = (int)parameterValues["Anchor:"];
            int reference = (int)parameterValues["Orientation reference:"];
            int branchReference = (int)parameterValues["Branch reference:"];

            Point delta = (Point)parameterValues["Position:"];

            bool autoFill = (bool)parameterValues["Auto fill colour by node"];
            double fillOpacity = (double)parameterValues["Fill opacity:"];

            ColourFormatterOptions Fill = (ColourFormatterOptions)parameterValues["Fill colour:"];
            Colour defaultFill = Fill.DefaultColour;
            Func<object, Colour?> fillFormatter = Fill.Formatter;

            bool autoStroke = (bool)parameterValues["Auto stroke colour by node"];
            double strokeOpacity = (double)parameterValues["Stroke opacity:"];

            ColourFormatterOptions Stroke = (ColourFormatterOptions)parameterValues["Stroke colour:"];
            Colour defaultStroke = Stroke.DefaultColour;
            Func<object, Colour?> strokeFormatter = Stroke.Formatter;

            double strokeThickness = (double)parameterValues["Stroke thickness:"];

            double angle = (double)parameterValues["Angle:"] * Math.PI / 180;

            NumberFormatterOptions Size = (NumberFormatterOptions)parameterValues["Size:"];
            double defaultSize = Size.DefaultValue;
            Func<object, double?> sizeFormatter = Size.Formatter;

            bool circle = (int)parameterValues["Shape:"] == 0;

            int sides = (int)(double)parameterValues["Sides:"];
            bool star = (bool)parameterValues["Star"];

            Point rootPoint = coordinates[Modules.RootNodeId];
            coordinates.TryGetValue("92aac276-3af7-4506-a263-7220e0df5797", out Point circularCenter);

            foreach (TreeNode node in nodes)
            {
                if (showOn == 2 || (showOn == 0 && node.Children.Count == 0) || (showOn == 1 && node.Children.Count > 0))
                {
                    Colour fillColour = defaultFill;

                    if (!autoFill)
                    {
                        if (node.Attributes.TryGetValue(Fill.AttributeName, out object fillAttributeObject) && fillAttributeObject != null)
                        {
                            fillColour = fillFormatter(fillAttributeObject) ?? defaultFill;
                        }
                    }
                    else
                    {
                        List<string> leafNames = node.GetLeafNames();
                        if (leafNames.Count > 0)
                        {
                            fillColour = Modules.DefaultColours[Math.Abs(leafNames.Aggregate((a, b) => a + "," + b).GetHashCode()) % Modules.DefaultColours.Length].WithAlpha(fillOpacity);
                        }
                        else
                        {
                            fillColour = Colour.FromRgb(0, 0, 0);
                        }
                    }

                    Colour strokeColour = defaultStroke;

                    if (!autoStroke)
                    {
                        if (node.Attributes.TryGetValue(Stroke.AttributeName, out object strokeAttributeObject) && strokeAttributeObject != null)
                        {
                            strokeColour = strokeFormatter(strokeAttributeObject) ?? defaultStroke;
                        }
                    }
                    else
                    {
                        strokeColour = Modules.DefaultColours[Math.Abs(node.GetLeafNames().Aggregate((a, b) => a + "," + b).GetHashCode()) % Modules.DefaultColours.Length].WithAlpha(strokeOpacity);
                    }

                    double size = defaultSize;

                    if (node.Attributes.TryGetValue(Size.AttributeName, out object sizeAttributeObject) && sizeAttributeObject != null)
                    {
                        size = sizeFormatter(sizeAttributeObject) ?? defaultSize;
                    }

                    Point point = coordinates[node.Id];
                    Point anglePoint = point;
                    double referenceAngle = 0;

                    if (reference == 0 && anchor == 0)
                    {

                    }
                    else
                    {
                        //Rectangular
                        if (branchReference == 0)
                        {
                            if (node.Parent != null)
                            {
                                Point parentPoint = coordinates[node.Parent.Id];

                                Point pA = coordinates[node.Parent.Children[0].Id];
                                Point pB = coordinates[node.Parent.Children[^1].Id];

                                double numerator = pA.Y + pB.Y - 2 * parentPoint.Y;
                                double denominator = pA.X + pB.X - 2 * parentPoint.X;

                                Point rectAnglePoint;

                                if (Math.Abs(numerator) > 1e-5 && Math.Abs(denominator) > 1e-5)
                                {
                                    double m = numerator / denominator;

                                    double x = (m * (parentPoint.Y - point.Y + m * point.X) + parentPoint.X) / (m * m + 1);
                                    double y = parentPoint.Y - (x - parentPoint.X) / m;

                                    rectAnglePoint = new Point(x, y);
                                }
                                else if (Math.Abs(numerator) > 1e-5)
                                {
                                    rectAnglePoint = new Point(point.X, parentPoint.Y);
                                }
                                else if (Math.Abs(denominator) > 1e-5)
                                {
                                    rectAnglePoint = new Point(parentPoint.X, point.Y);
                                }
                                else
                                {
                                    rectAnglePoint = point;
                                }

                                if (reference == 1)
                                {
                                    referenceAngle = Math.Atan2(point.Y - rectAnglePoint.Y, point.X - rectAnglePoint.X);
                                }

                                if (anchor == 1)
                                {
                                    anglePoint = rectAnglePoint;
                                }
                                else if (anchor == 2)
                                {
                                    Point branchVector = new Point(Math.Cos(referenceAngle), Math.Sin(referenceAngle));

                                    double d = (rootPoint.X - point.X) * branchVector.X + (rootPoint.Y - point.Y) * branchVector.Y;

                                    Point proj = new Point(point.X + d * branchVector.X, point.Y + d * branchVector.Y);

                                    anglePoint = new Point(-point.X + proj.X * 2, -point.Y + proj.Y * 2);
                                }
                            }
                            else
                            {
                                Point parentPoint = coordinates[Modules.RootNodeId];

                                if (anchor == 1)
                                {
                                    anglePoint = parentPoint;
                                }
                                else if (anchor == 2)
                                {
                                    anglePoint = new Point(-point.X + parentPoint.X * 2, -point.Y + parentPoint.Y * 2);
                                }

                                if (reference == 1)
                                {
                                    referenceAngle = Math.Atan2(point.Y - parentPoint.Y, point.X - parentPoint.X);
                                }
                            }
                        }
                        //Radial
                        else if (branchReference == 1)
                        {
                            Point parentPoint;

                            if (node.Parent != null)
                            {
                                parentPoint = coordinates[node.Parent.Id];
                            }
                            else
                            {
                                parentPoint = coordinates[Modules.RootNodeId];
                            }

                            if (anchor == 1)
                            {
                                anglePoint = parentPoint;
                            }

                            if (reference == 1)
                            {
                                referenceAngle = Math.Atan2(point.Y - parentPoint.Y, point.X - parentPoint.X);
                            }

                        }
                        //Circular
                        else if (branchReference == 2)
                        {
                            Point parentPoint;

                            if (node.Parent != null)
                            {
                                parentPoint = coordinates[node.Parent.Id];
                            }
                            else
                            {
                                parentPoint = coordinates[Modules.RootNodeId];
                            }

                            double myRadius = distance(point, circularCenter);
                            double parentRadius = distance(parentPoint, circularCenter);

                            Point realElbowPoint = sumPoint(point, multiplyPoint(subtractPoint(circularCenter, point), (myRadius - parentRadius) / myRadius));

                            if (anchor == 1)
                            {
                                anglePoint = realElbowPoint;
                            }
                            else if (anchor == 2)
                            {
                                anglePoint = new Point(-point.X + circularCenter.X * 2, -point.Y + circularCenter.Y * 2);
                            }

                            if (reference == 1)
                            {
                                referenceAngle = Math.Atan2(point.Y - realElbowPoint.Y, point.X - realElbowPoint.X);
                            }
                        }
                    }

                    if (double.IsNaN(referenceAngle))
                    {
                        referenceAngle = 0;
                    }

                    point = new Point((point.X + anglePoint.X) * 0.5, (point.Y + anglePoint.Y) * 0.5);

                    if (size > 0)
                    {
                        graphics.Save();
                        graphics.Translate(point);
                        graphics.Rotate(referenceAngle);

                        Point originalPoint = new Point(point.X + delta.X * Math.Cos(referenceAngle) - delta.Y * Math.Sin(referenceAngle), point.Y + delta.X * Math.Sin(referenceAngle) + delta.Y * Math.Cos(referenceAngle));

                        point = delta;

                        GraphicsPath path = new GraphicsPath();
                        if (circle)
                        {
                            path.Arc(point, size * 0.5, 0, 2 * Math.PI);
                        }
                        else
                        {
                            path.MoveTo(point.X + Math.Cos(angle) * size * 0.5, point.Y + Math.Sin(angle) * size * 0.5);

                            if (!star)
                            {
                                double deltaAngle = Math.PI * 2 / sides;
                                for (int i = 1; i < sides; i++)
                                {
                                    path.LineTo(point.X + Math.Cos(angle + deltaAngle * i) * size * 0.5, point.Y + Math.Sin(angle + deltaAngle * i) * size * 0.5);
                                }
                                path.Close();
                            }
                            else
                            {
                                double deltaAngle = Math.PI / sides;
                                for (int i = 1; i < sides * 2; i++)
                                {
                                    if (i % 2 == 0)
                                    {
                                        path.LineTo(point.X + Math.Cos(angle + deltaAngle * i) * size * 0.5, point.Y + Math.Sin(angle + deltaAngle * i) * size * 0.5);
                                    }
                                    else
                                    {
                                        path.LineTo(point.X + Math.Cos(angle + deltaAngle * i) * size * 0.25, point.Y + Math.Sin(angle + deltaAngle * i) * size * 0.25);
                                    }
                                }
                                path.Close();
                            }
                        }

                        if (fillColour.A > 0)
                        {
                            graphics.FillPath(path, fillColour, tag: node.Id);
                        }

                        if (strokeColour.A > 0 && strokeThickness > 0)
                        {
                            graphics.StrokePath(path, strokeColour, strokeThickness, LineCaps.Round, LineJoins.Round, tag: node.Id);
                        }

                        graphics.Restore();

                        updateMaxMin(new Point(originalPoint.X - size * 1.5, originalPoint.Y - size * 1.5));
                        updateMaxMin(new Point(originalPoint.X - size * 1.5, originalPoint.Y + size * 1.5));
                        updateMaxMin(new Point(originalPoint.X + size * 1.5, originalPoint.Y + size * 1.5));
                        updateMaxMin(new Point(originalPoint.X + size * 1.5, originalPoint.Y - size * 1.5));
                    }
                }
            }

            if (!anyPoint)
            {
                minX = minY = maxX = maxY = 0;
            }

            return new Point[] { new Point(minX, minY), new Point(maxX, maxY) };
        }

19 Source : ImageFormats.cs
with GNU General Public License v3.0
from arklumpus

internal static byte PaethPredictor(byte a, byte b, byte c)
        {
            int p = (int)a + (int)b - (int)c;
            int pa = Math.Abs(p - (int)a);
            int pb = Math.Abs(p - (int)b);
            int pc = Math.Abs(p - (int)c);

            if (pa <= pb && pa <= pc)
            {
                return a;
            }
            else if (pb <= pc)
            {
                return b;
            }
            else
            {
                return c;
            }
        }

19 Source : LineBrush.cs
with MIT License
from Aroueterra

public static IEnumerable<Vector2Int> GetPointsOnLine(Vector2Int p1, Vector2Int p2)
        {
            int x0 = p1.x;
            int y0 = p1.y;
            int x1 = p2.x;
            int y1 = p2.y;

            bool steep = Math.Abs(y1 - y0) > Math.Abs(x1 - x0);
            if (steep)
            {
                int t;
                t = x0; // swap x0 and y0
                x0 = y0;
                y0 = t;
                t = x1; // swap x1 and y1
                x1 = y1;
                y1 = t;
            }
            if (x0 > x1)
            {
                int t;
                t = x0; // swap x0 and x1
                x0 = x1;
                x1 = t;
                t = y0; // swap y0 and y1
                y0 = y1;
                y1 = t;
            }
            int dx = x1 - x0;
            int dy = Math.Abs(y1 - y0);
            int error = dx / 2;
            int ystep = (y0 < y1) ? 1 : -1;
            int y = y0;
            for (int x = x0; x <= x1; x++)
            {
                yield return new Vector2Int((steep ? y : x), (steep ? x : y));
                error = error - dy;
                if (error < 0)
                {
                    y += ystep;
                    error += dx;
                }
            }
            yield break;
        }

19 Source : MathAllMethods.cs
with MIT License
from asc-community

public static int Abs(int a) => Math.Abs(a);

19 Source : Simplificator.cs
with MIT License
from asc-community

internal static IEnumerable<Enreplacedy> Alternate(Enreplacedy src, int level)
        {
            if (src is FiniteSet ss)
                return new[] { ss.Apply(ent => ent.Simplify()).InnerSimplified };
            if (src is Number or Variable or Enreplacedy.Boolean)
                return new[] { src };
            var stage1 = src.InnerSimplified;

#if DEBUG
            if (MathS.Diagnostic.CatchOnSimplify.Value(stage1))
                throw new MathS.Diagnostic.DiagnosticCatchException();
#endif

            if (stage1 is Number or Variable or Enreplacedy.Boolean)
                return new[] { stage1 };

            // List of criteria for expr's complexity
            var history = new SortedDictionary<double, HashSet<Enreplacedy>>();
            void AddHistory(Enreplacedy expr)
            {
#if DEBUG
                if (MathS.Diagnostic.CatchOnSimplify.Value(expr)) throw new MathS.Diagnostic.DiagnosticCatchException();
#endif
                void __IterAddHistory(Enreplacedy expr)
                {
                    var refexpr = expr.Replace(Patterns.SortRules(Treereplacedyzer.SortLevel.HIGH_LEVEL)).InnerSimplified;
                    var compl1 = refexpr.SimplifiedRate;
                    var compl2 = expr.SimplifiedRate;
                    var n = compl1 > compl2 ? expr : refexpr;
                    var ncompl = Math.Min(compl2, compl1);
                    if (history.TryGetValue(ncompl, out var ncomplList))
                        ncomplList.Add(n);
                    else 
                        history[ncompl] = new HashSet<Enreplacedy> { n };
                }
                __IterAddHistory(expr);
                __IterAddHistory(expr.Replace(Patterns.InvertNegativePowers));

                MulreplacedhreadingFunctional.ExitIfCancelled();
            }

            AddHistory(stage1);
            var res = stage1;

            for (int i = 0; i < Math.Abs(level); i++)
            {
                var sortLevel = i switch
                {
                    1 => Treereplacedyzer.SortLevel.MIDDLE_LEVEL,
                    2 => Treereplacedyzer.SortLevel.LOW_LEVEL,
                    _ => Treereplacedyzer.SortLevel.HIGH_LEVEL
                };
                res = res.Replace(Patterns.SortRules(sortLevel)).InnerSimplified;
                if (res.Nodes.Any(child => child is Powf))
                    AddHistory(res = res.Replace(Patterns.PowerRules).InnerSimplified);

                AddHistory(res = SimplifyChildren(res));

                AddHistory(res = res.Replace(Patterns.InvertNegativePowers).Replace(Patterns.DivisionPreparingRules).InnerSimplified);

                AddHistory(res = res.Replace(Patterns.PolynomialLongDivision).InnerSimplified);

                AddHistory(res = res.Replace(Patterns.NormalTrigonometricForm).InnerSimplified);
                AddHistory(res = res.Replace(Patterns.CollapseMultipleFractions).InnerSimplified);
                AddHistory(res = res.Replace(e => Patterns.FractionCommonDenominatorRules(e, sortLevel)).InnerSimplified);
                AddHistory(res = res.Replace(Patterns.InvertNegativePowers).Replace(Patterns.DivisionPreparingRules).InnerSimplified);
                AddHistory(res = res.Replace(Patterns.PowerRules).InnerSimplified);
                AddHistory(res = res.Replace(Patterns.TrigonometricRules).InnerSimplified);
                AddHistory(res = res.Replace(Patterns.CollapseTrigonometricFunctions).InnerSimplified);

                if (res.Nodes.Any(child => child is TrigonometricFunction))
                {
                    var res1 = res.Replace(Patterns.ExpandTrigonometricRules).InnerSimplified;
                    AddHistory(res = res.Replace(Patterns.TrigonometricRules).Replace(Patterns.CommonRules).InnerSimplified);
                    AddHistory(res1);
                    res = PickSimplest(res, res1);
                    AddHistory(res = res.Replace(Patterns.CollapseTrigonometricFunctions).Replace(Patterns.TrigonometricRules));
                }


                if (res.Nodes.Any(child => child is Statement))
                {
                    AddHistory(res = res.Replace(Patterns.BooleanRules).InnerSimplified);
                }


                if (res.Nodes.Any(child => child is ComparisonSign))
                {
                    AddHistory(res = res.Replace(Patterns.InequalityEqualityRules).InnerSimplified);
                }

                if (res.Nodes.Any(child => child is Factorialf))
                {
                    AddHistory(res = res.Replace(Patterns.ExpandFactorialDivisions).InnerSimplified);
                    AddHistory(res = res.Replace(Patterns.FactorizeFactorialMultiplications).InnerSimplified);
                }


                if (res.Nodes.Any(child => child is Powf or Logf))
                    AddHistory(res = res.Replace(Patterns.PowerRules).InnerSimplified);

                if (res.Nodes.Any(child => child is Set))
                {
                    var replaced = res.Replace(Patterns.SetOperatorRules);

                    AddHistory(res = replaced.InnerSimplified);
                }


                if (res.Nodes.Any(child => child is Phif))
                    AddHistory(res = res.Replace(Patterns.PhiFunctionRules).InnerSimplified);

                Enreplacedy? possiblePoly = null;
                foreach (var var in res.Vars)
                    if (TryPolynomial(res, var, out var resPoly)
                        && (possiblePoly is null || resPoly.Complexity < possiblePoly.Complexity))
                        AddHistory(possiblePoly = resPoly);
                if (possiblePoly is { } && possiblePoly.Complexity < res.Complexity)
                    res = possiblePoly;


                AddHistory(res = res.Replace(Patterns.CommonRules));


                AddHistory(res = res.Replace(Patterns.NumericNeatRules));

                /*
                This was intended to simplify expressions as polynomials over nodes, some kind of
                greatest common node and simplifying over it. However, the current algorithm does
                not solve this issue completely and yet too slow to be accepted.

                AddHistory(res = Treereplacedyzer.Factorize(res));
                */

                res = history[history.Keys.Min()].First();
            }

19 Source : Program.cs
with GNU General Public License v3.0
from asimmon

public static void Main(string[] args)
        {
            var parsedArgs = ProgramArguments.Parse(args);
            if (parsedArgs.ShowHelp)
            {
                parsedArgs.WriteHelp(Console.Out);
                return;
            }

            var configuration = GetRequestedConfiguration(parsedArgs.ConfigurationPath);
            configuration.Seed = parsedArgs.Seed ?? Math.Abs(Guid.NewGuid().GetHashCode());

            for (var iter = 1; iter <= parsedArgs.RepeatCount; iter++)
            {
                var outputFile = GetOutputFile(parsedArgs.OutputPath, iter);
                var opts = new WorkerOptions(parsedArgs, iter, outputFile, configuration);

                using var worker = new Worker(opts);
                worker.Work();
            }
        }

19 Source : GraphicsFactory.cs
with GNU General Public License v3.0
from AtomCrafty

public override YukaGraphics FromBinary(Stream s) {
			byte[] colorData = null, alphaData = null, metaData = null;
			long offset = s.Position;

			BinaryReader br = new BinaryReader(s, Encoding.ASCII, true /* don't close the stream! */);
			s.Seek(0x28, SeekOrigin.Current);
			int coloroffset = br.ReadInt32();
			int colorlength = br.ReadInt32();
			int alphaoffset = br.ReadInt32();
			int alphalength = br.ReadInt32();
			int metaoffset = br.ReadInt32();
			int metalength = br.ReadInt32();

			if(coloroffset != 0) {
				s.Seek(offset + coloroffset, SeekOrigin.Begin);
				colorData = br.ReadBytes(colorlength);
				// PNG header hack
				colorData[1] = (byte)'P';
				colorData[3] = (byte)'G';
			}
			else {
				if(FlagCollection.current.Has('v')) {
					Console.WriteLine("Warning: missing color layer");
				}
				// throw new Exception("No color layer found");
			}
			if(alphaoffset != 0) {
				s.Seek(offset + alphaoffset, SeekOrigin.Begin);
				alphaData = br.ReadBytes(alphalength);
				// PNG header hack
				alphaData[1] = (byte)'P';
				alphaData[3] = (byte)'G';
			}
			if(metaoffset != 0) {
				s.Seek(offset + metaoffset, SeekOrigin.Begin);
				metaData = br.ReadBytes(metalength);
			}

			br.Close();

			Bitmap colorLayer = colorData != null ? (Image.FromStream(new MemoryStream(colorData)) as Bitmap) : null;

			if(alphaData != null) {
				Bitmap alphaLayer = Image.FromStream(new MemoryStream(alphaData)) as Bitmap;

				Rectangle rect = new Rectangle(0, 0, alphaLayer.Width, alphaLayer.Height);

				colorLayer = colorLayer != null ? colorLayer.Clone(rect, PixelFormat.Format32bppArgb) : new Bitmap(alphaLayer.Width, alphaLayer.Height, PixelFormat.Format32bppArgb);

				BitmapData colorBits = colorLayer.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
				BitmapData alphaBits = alphaLayer.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);

				int colorBytes = Math.Abs(colorBits.Stride) * colorLayer.Height;
				int alphaBytes = Math.Abs(alphaBits.Stride) * alphaLayer.Height;

				byte[] colorValues = new byte[colorBytes];
				byte[] alphaValues = new byte[alphaBytes];

				Marshal.Copy(colorBits.Scan0, colorValues, 0, colorBytes);
				Marshal.Copy(alphaBits.Scan0, alphaValues, 0, alphaBytes);

				for(int counter = 0; counter < colorValues.Length; counter += 4) {
					// set the alpha channel of colorValue to the inverted red channel of alphaValues
					colorValues[counter + 3] = (byte)(255 - alphaValues[counter]);
				}

				Marshal.Copy(colorValues, 0, colorBits.Scan0, colorBytes);
				Marshal.Copy(alphaValues, 0, alphaBits.Scan0, alphaBytes);

				colorLayer.UnlockBits(colorBits);
				alphaLayer.UnlockBits(alphaBits);
			}

			return new YukaGraphics(colorLayer, metaData);
		}

19 Source : Forge.cs
with GNU General Public License v3.0
from atomex-me

public static string ForgeInt(int value)
        {
            var binary = Convert.ToString(Math.Abs(value), 2);

            int pad = 6;
            if ((binary.Length - 6) % 7 == 0)
                pad = binary.Length;
            else if (binary.Length > 6)
                pad = binary.Length + 7 - (binary.Length - 6) % 7;

            binary = binary.PadLeft(pad, '0');

            var septets = new List<string>();

            for (int i = 0; i <= pad / 7; i++)
                septets.Add(binary.Substring(7 * i, Math.Min(7, pad - 7 * i)));

            septets.Reverse();

            septets[0] = (value >= 0 ? "0" : "1") + septets[0];

            string res = "";

            for (int i = 0; i < septets.Count; i++)
            {
                var prefix = i == septets.Count - 1
                    ? "0"
                    : "1";

                res += Convert.ToByte(prefix + septets[i], 2).ToString("X2");
            }

            return res;
        }

19 Source : ExtensionMethods.cs
with GNU General Public License v3.0
from audiamus

public static string ToStringHMS (this TimeSpan value) {
      string sgn = value < TimeSpan.Zero ? "-" : string.Empty;
      int hours = Abs (value.Days) * 24 + Abs (value.Hours);
      return $"{sgn}{Abs (hours):D2}:{Abs (value.Minutes):D2}:{Abs (value.Seconds):D2}";
    }

19 Source : ExtensionMethods.cs
with GNU General Public License v3.0
from audiamus

public static string ToStringHMSm (this TimeSpan value) => $"{value.ToStringHMS ()}.{Abs (value.Milliseconds):D3}";

19 Source : Loc.cs
with MIT License
from audinowho

public int Dist8()
        {
            return Math.Max(Math.Abs(this.X), Math.Abs(this.Y));
        }

19 Source : Loc.cs
with MIT License
from audinowho

public int Dist4()
        {
            return Math.Abs(this.X) + Math.Abs(this.Y);
        }

19 Source : ExtensionMethods.cs
with GNU General Public License v3.0
from audiamus

public static int Digits (this Int32 n) =>
          n == 0 ? 1 : 1 + (int)Math.Log10 (Math.Abs (n));

19 Source : FocusControl.cs
with GNU General Public License v3.0
from aurelitec

public void ResizeWhileCreating(Point topLeft, Point bottomRight)
        {
            if (this != null)
            {
                this.BringToFront();
                this.SetBounds(
                    Math.Min(topLeft.X, bottomRight.X),
                    Math.Min(topLeft.Y, bottomRight.Y),
                    Math.Abs(bottomRight.X - topLeft.X),
                    Math.Abs(bottomRight.Y - topLeft.Y));
            }
        }

19 Source : Extensions.cs
with GNU General Public License v3.0
from AutoDarkMode

public static bool SuntimeIsWithinSpan(DateTime time, int grace)
        {
            return NowIsBetweenTimes(
                time.AddMinutes(-Math.Abs(grace)).TimeOfDay,
                time.AddMinutes(Math.Abs(grace)).TimeOfDay);
        }

19 Source : RopeNode.cs
with MIT License
from AvaloniaUI

[Conditional("DATACONSISTENCYTEST")]
        internal void CheckInvariants()
        {
            if (Height == 0)
            {
                Debug.replacedert(Left == null && Right == null);
                if (Contents == null)
                {
                    Debug.replacedert(this is FunctionNode<T>);
                    Debug.replacedert(Length > 0);
                    Debug.replacedert(_isShared);
                }
                else
                {
                    Debug.replacedert(Contents != null && Contents.Length == NodeSize);
                    Debug.replacedert(Length >= 0 && Length <= NodeSize);
                }
            }
            else
            {
                Debug.replacedert(Left != null && Right != null);
                Debug.replacedert(Contents == null);
                Debug.replacedert(Length == Left.Length + Right.Length);
                Debug.replacedert(Height == 1 + Math.Max(Left.Height, Right.Height));
                Debug.replacedert(Math.Abs(Balance) <= 1);

                // this is an additional invariant that forces the tree to combine small leafs to prevent excessive memory usage:
                Debug.replacedert(Length > NodeSize);
                // note that this invariant ensures that all nodes except for the empty rope's single node have at least length 1

                if (_isShared)
                    Debug.replacedert(Left._isShared && Right._isShared);
                Left.CheckInvariants();
                Right.CheckInvariants();
            }
        }

19 Source : RopeNode.cs
with MIT License
from AvaloniaUI

internal void Rebalance()
        {
            // Rebalance() shouldn't be called on shared nodes - it's only called after modifications!
            Debug.replacedert(!_isShared);
            // leaf nodes are always balanced (we don't use 'height' to detect leaf nodes here
            // because Balance is supposed to recompute the height).
            if (Left == null)
                return;

            // ensure we didn't miss a MergeIfPossible step
            Debug.replacedert(Length > NodeSize);

            // We need to loop until it's balanced. Rotations might cause two small leaves to combine to a larger one,
            // which changes the height and might mean we need additional balancing steps.
            while (Math.Abs(Balance) > 1)
            {
                // AVL balancing
                // note: because we don't care about the idenreplacedy of concat nodes, this works a little different than usual
                // tree rotations: in our implementation, the "this" node will stay at the top, only its children are rearranged
                if (Balance > 1)
                {
                    if (Right.Balance < 0)
                    {
                        Right = Right.CloneIfShared();
                        Right.RotateRight();
                    }
                    RotateLeft();
                    // If 'this' was unbalanced by more than 2, we've shifted some of the inbalance to the left node; so rebalance that.
                    Left.Rebalance();
                }
                else if (Balance < -1)
                {
                    if (Left.Balance > 0)
                    {
                        Left = Left.CloneIfShared();
                        Left.RotateLeft();
                    }
                    RotateRight();
                    // If 'this' was unbalanced by more than 2, we've shifted some of the inbalance to the right node; so rebalance that.
                    Right.Rebalance();
                }
            }

            Debug.replacedert(Math.Abs(Balance) <= 1);
            Height = (byte)(1 + Math.Max(Left.Height, Right.Height));
        }

19 Source : DragOperation.cs
with MIT License
from awaescher

private void SourceControl_MouseMove(object sender, MouseEventArgs e)
        {
            const int DISTANCE = 3;

            var currentPosition = Control.MousePosition;
            var deltaX = Math.Abs(currentPosition.X - _initialPosition.X);
            var deltaY = Math.Abs(currentPosition.Y - _initialPosition.Y);

            if (deltaX > DISTANCE || deltaY > DISTANCE)
                Start(_definition.Effect);
        }

19 Source : UpdatablePreview.cs
with MIT License
from awaescher

private void UpdatePreview(object state)
		{
			var currentMousePosition = System.Windows.Forms.Control.MousePosition;
			var distanceX = Math.Abs(currentMousePosition.X - _mouseStartPosition.X);
			var distanceY = Math.Abs(currentMousePosition.Y - _mouseStartPosition.Y);
			_distance = Math.Round(Math.Sqrt(Math.Pow(distanceX, 2) + Math.Pow(distanceY, 2)));

			// at 900 distance, we want it to be transparent
			Opacity = (900 - _distance) / 900;
			Updated?.Invoke(this, EventArgs.Empty);
		}

19 Source : StringWildcardExtensionTests.cs
with Apache License 2.0
from aws

[TestMethod]
        public void TestLongStrings()
        {
            // This blew out the stack on a recursive version of wildcardMatch
            char[] t = new char[] { 'a', 'b', 'c', 'd' };
            StringBuilder text = new StringBuilder("a");
            Random r = new Random();
            int size = 8192;

            for (int i = 0; i < size; i++)
            {
                text.Append(t[Math.Abs(r.Next()) % t.Length]);
            }

            text.Append("b");

            replacedert.IsTrue(text.ToString().WildcardMatch("a*b"));
        }

19 Source : VoronoiGenerator.cs
with MIT License
from AximoGames

private float[,] Voronoi3(int width, int height, Vector2i[] points, int minDelta)
        {
            var values = new float[width, height];
            for (int ix = 0; ix < width; ix++)
            {
                for (int iy = 0; iy < height; iy++)
                {
                    float minDist = 999999999f;
                    float minDist2 = 999999999f;
                    for (int p = 0; p < points.GetLength(0); p++)
                    {
                        int pX = points[p].X;
                        int pY = points[p].Y;
                        double dist1X = Math.Abs(ix - pX);
                        double dist1Y = Math.Abs(iy - pY);
                        double dist2X = width - dist1X;
                        double dist2Y = height - dist1Y;
                        /*to grant seamless I take the min between distX and wid-distX
                         |                       |
                         |                       |     ----------- = Dist1X
                         |...i-----------X.......|     ..........  = Dist2X
                         |                       |
                         */
                        dist1X = Math.Min(dist1X, dist2X);
                        /*to grant seamless I take the min between distY and hei-distY*/
                        dist1Y = Math.Min(dist1Y, dist2Y);

                        float dist = (float)Math.Sqrt(Math.Pow(dist1X, 2) + Math.Pow(dist1Y, 2)); //euclidian metric

                        //float dist = (float)(Dist1X + Dist1Y);//Taxicab metric //http://en.wikipedia.org/wiki/Taxicab_geometry

                        //to make it ondulated
                        //1.
                        //dist = dist + (float)Math.Sin(Dist1X * 0.15) * (float)Math.Cos(Dist1Y * 0.15);
                        //2.
                        //dist = dist + (float)Math.Cos(Dist1Y * 0.15);
                        //dist = dist + (float)Math.Sin(Dist1Y * 0.15);

                        // strange effects:
                        // dist = dist % 100;
                        // dist = dist + dist % 100;

                        if (dist <= minDist)
                        {
                            minDist2 = minDist;
                            minDist = dist;
                        }
                        else
                        {
                            if (dist <= minDist2)
                                minDist2 = dist;
                        }
                    }

                    if (minDist2 - minDist < 1f)
                        values[ix, iy] = 0;
                    else
                        if (minDist2 - minDist < (float)minDelta)
                        values[ix, iy] = (minDist2 - minDist) / (float)minDelta * 255f;
                    else
                        values[ix, iy] = 255;
                }

            }

            return values;
        }

19 Source : CiaccoRandom.cs
with MIT License
from AximoGames

public void SetSeed(int seed)
        {
            // seed can only be positive and seed range is [0 -> 9999998] seed=9999999 schould give the same as seed=0
            superSeed = (Math.Abs(seed) % 9999999) + 1;
            // init for randomness fairness
            superSeed = (superSeed * 125) % 2796203;
            superSeed = (superSeed * 125) % 2796203;
            superSeed = (superSeed * 125) % 2796203;
            superSeed = (superSeed * 125) % 2796203;
            superSeed = (superSeed * 125) % 2796203;
            superSeed = (superSeed * 125) % 2796203;
            superSeed = (superSeed * 125) % 2796203;
            superSeed = (superSeed * 125) % 2796203;
            superSeed = (superSeed * 125) % 2796203;
        }

19 Source : MessageUtils.cs
with GNU General Public License v3.0
from az64

public static string NumberToWords(int number)
        {
            if (number == 0)
                return "zero";

            if (number < 0)
                return "minus " + NumberToWords(Math.Abs(number));

            string words = "";

            if ((number / 1000000) > 0)
            {
                words += NumberToWords(number / 1000000) + " million ";
                number %= 1000000;
            }

            if ((number / 1000) > 0)
            {
                words += NumberToWords(number / 1000) + " thousand ";
                number %= 1000;
            }

            if ((number / 100) > 0)
            {
                words += NumberToWords(number / 100) + " hundred ";
                number %= 100;
            }

            if (number > 0)
            {
                if (words != "")
                    words += "and ";

                if (number < 20)
                    words += numberWordUnitsMap[number];
                else
                {
                    words += numberWordTensMap[number / 10];
                    if ((number % 10) > 0)
                        words += "-" + numberWordUnitsMap[number % 10];
                }
            }

            return words;
        }

See More Examples