System.Collections.Generic.IEnumerable.Last()

Here are the examples of the csharp api System.Collections.Generic.IEnumerable.Last() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

4249 Examples 7

19 Source : PortalViewContext.cs
with MIT License
from Adoxio

public bool IsAncestorSiteMapNode(SiteMapNode siteMapNode, bool excludeRootNodes = false)
		{
			if (siteMapNode == null)
			{
				return false;
			}

			var enreplacedyNode = siteMapNode as CrmSiteMapNode;

			if (enreplacedyNode == null || enreplacedyNode.Enreplacedy == null)
			{
				return IsAncestorSiteMapNode(siteMapNode.Url);
			}

			var currentNodeAncestors = CurrentSiteMapNodeAncestors;

			if (currentNodeAncestors.Length < 1)
			{
				return false;
			}

			var nodeEnreplacedyReference = enreplacedyNode.Enreplacedy.ToEnreplacedyReference();

			var root = currentNodeAncestors.Last();

			foreach (var ancestor in currentNodeAncestors.OfType<CrmSiteMapNode>())
			{
				if (ancestor.Enreplacedy == null)
				{
					continue;
				}

				if (ancestor.Enreplacedy.ToEnreplacedyReference().Equals(nodeEnreplacedyReference))
				{
					return !(excludeRootNodes && ancestor.Equals(root));
				}
			}

			return false;
		}

19 Source : PortalViewContext.cs
with MIT License
from Adoxio

public bool IsAncestorSiteMapNode(EnreplacedyReference enreplacedyReference, bool excludeRootNodes = false)
		{
			if (enreplacedyReference == null)
			{
				return false;
			}

			var currentNodeAncestors = CurrentSiteMapNodeAncestors;

			if (currentNodeAncestors.Length < 1)
			{
				return false;
			}

			var root = currentNodeAncestors.Last();

			foreach (var ancestor in currentNodeAncestors.OfType<CrmSiteMapNode>())
			{
				if (ancestor.Enreplacedy == null)
				{
					continue;
				}

				if (ancestor.Enreplacedy.ToEnreplacedyReference().Equals(enreplacedyReference))
				{
					return !(excludeRootNodes && ancestor.Equals(root));
				}
			}

			return false;
		}

19 Source : ThrottleAttribute.cs
with MIT License
from Adoxio

private static string GetIpAddress()
        {
            var ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

            if (string.IsNullOrEmpty(ip))
            {
                ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }
            else
            {
                ip = ip.Split(',')
                        .Last()
                        .Trim();
            }

            return ip;
        }

19 Source : EmbeddedResourceAssemblyAttribute.cs
with MIT License
from Adoxio

private string ConvertVirtualPathToResourceName(string virtualPath)
		{
			// converting an entire path
			// for all parts: prepend an '_' if the name starts with a numeric character
			// replace all '/' or '\\' with '.'
			// prepend the default namespace
			// besides a leading underscore, filenames remain unchanged

			var parts = virtualPath.Split(_directoryDelimiters, StringSplitOptions.RemoveEmptyEntries);

			if (parts.Any())
			{
				var partsWithUnderscores = parts.Select(p => Regex.IsMatch(p, @"^\d") ? "_" + p : p);
				var directories = partsWithUnderscores.Take(parts.Length - 1).Select(ConvertDirectoryToResourceName);
				var head = directories.Aggregate(Namespace, (h, d) => "{0}.{1}".FormatWith(h, d)).Replace('-', '_');
				var tail = partsWithUnderscores.Last();
				return "{0}.{1}".FormatWith(head, tail);
			}

			return null;
		}

19 Source : Project.cs
with MIT License
from adrenak

private void ParsePath(string path)
        {
            //Unity's Application functions return the replacedets path in the Editor. 
            projectPath = path;

            //pop off the last part of the path for the project name, keep the rest for the root path
            List<string> pathArray = projectPath.Split(separator).ToList<string>();
            name = pathArray.Last();

            pathArray.RemoveAt(pathArray.Count() - 1);
            rootPath = string.Join(separator[0].ToString(), pathArray.ToArray());

            replacedetPath = projectPath + "/replacedets";
            projectSettingsPath = projectPath + "/ProjectSettings";
            libraryPath = projectPath + "/Library";
            packagesPath = projectPath + "/Packages";
            autoBuildPath = projectPath + "/AutoBuild";
            localPackages = projectPath + "/LocalPackages";
        }

19 Source : CodeConverterShould.cs
with MIT License
from AdrianWilczynski

[Fact]
        public void AppendNewLineAtTheEndOfTheFile()
        {
            var converted = _codeConverter.ConvertToTypeScript(
                "clreplaced Item {}",
                new CodeConversionOptions(export: true, useTabs: true, appendNewLine: true));

            var lastLine = Regex.Split(converted, @"\r?\n").Last();

            replacedert.Equal(string.Empty, lastLine);

            converted = _codeConverter.ConvertToTypeScript(
                "clreplaced Item {}",
                new CodeConversionOptions(export: true, useTabs: true, appendNewLine: false));

            lastLine = Regex.Split(converted, @"\r?\n").Last();

            replacedert.NotEqual(string.Empty, lastLine);
        }

19 Source : MapManager.cs
with MIT License
from Adsito

public static IEnumerator Load(MapInfo mapInfo, string path = "")
        {
            ProgressManager.RemoveProgressBars("Load:");

            int progressID = Progress.Start("Load: " + path.Split('/').Last(), "Preparing Map", Progress.Options.Sticky);
            int delPrefab = Progress.Start("Prefabs", null, Progress.Options.Sticky, progressID);
            int spwPrefab = Progress.Start("Prefabs", null, Progress.Options.Sticky, progressID);
            int delPath = Progress.Start("Paths", null, Progress.Options.Sticky, progressID);
            int spwPath = Progress.Start("Paths", null, Progress.Options.Sticky, progressID);
            int terrainID = Progress.Start("Terrain", null, Progress.Options.Sticky, progressID);

            PrefabManager.DeletePrefabs(PrefabManager.CurrentMapPrefabs, delPrefab);
            PathManager.DeletePaths(PathManager.CurrentMapPaths, delPath);
            CentreSceneObjects(mapInfo);
            TerrainManager.Load(mapInfo, terrainID);
            PrefabManager.SpawnPrefabs(mapInfo.prefabData, spwPrefab);
            PathManager.SpawnPaths(mapInfo.pathData, spwPath);

            var sw = new System.Diagnostics.Stopwatch();
            sw.Start();

            while (Progress.GetProgressById(terrainID).progress < 0.99f || Progress.GetProgressById(spwPrefab).running || Progress.GetProgressById(spwPath).running)
            {
                if (sw.Elapsed.TotalMilliseconds > 0.05f)
                {
                    sw.Restart();
                    yield return null;
                }
            }

            Progress.Report(progressID, 0.99f, "Loaded");
            Progress.Finish(terrainID, Progress.Status.Succeeded);
            Progress.Finish(progressID, Progress.Status.Succeeded);

            Callbacks.OnMapLoaded(path);
        }

19 Source : MapManager.cs
with MIT License
from Adsito

public static IEnumerator Save(string path)
        {
            ProgressManager.RemoveProgressBars("Save:");

            int progressID = Progress.Start("Save: " + path.Split('/').Last(), "Saving Map", Progress.Options.Sticky);
            int prefabID = Progress.Start("Prefabs", null, Progress.Options.Sticky, progressID);
            int pathID = Progress.Start("Paths", null, Progress.Options.Sticky, progressID);
            int terrainID = Progress.Start("Terrain", null, Progress.Options.Sticky, progressID);

            SaveLayer();
            yield return null;
            TerrainToWorld(Land, Water, (prefabID, pathID, terrainID)).Save(path);

            Progress.Report(progressID, 0.99f, "Saved");
            Progress.Finish(prefabID, Progress.Status.Succeeded);
            Progress.Finish(pathID, Progress.Status.Succeeded);
            Progress.Finish(terrainID, Progress.Status.Succeeded);
            Progress.Finish(progressID, Progress.Status.Succeeded);

            Callbacks.OnMapSaved(path);
        }

19 Source : MetroWaterfallFlow.cs
with GNU General Public License v3.0
from aduskin

private int GetFistMiniHeight()
      {
         int ret = -1;
         double min = _curHeight.Last();
         for (int i = _colums - 1; i >= 0; i--)
         {
            if (_curHeight[i] <= min)
            {
               min = _curHeight[i];
               ret = i;
            }
         }
         return ret;
      }

19 Source : kcp.cs
with Apache License 2.0
from advancer68

public int Send(ByteBuf buffer)
    {
        if (buffer.Size == 0)
        {
            return -1;
        }
        // append to previous segment in streaming mode (if possible)
        if (this.stream && this.snd_queue.Count > 0)
        {
            Segment seg = snd_queue.Last();
            if (seg.data != null && seg.data.Size < mss)
            {
                int capacity = mss - seg.data.Size;
                int extend = (buffer.Size < capacity) ? buffer.Size : capacity;
                seg.data.WriteBytesFrom(buffer, extend);
                SegmentDelete(seg);
                if (buffer.Size == 0)
                {
                    return 0;
                }
            }
        }
        int count;
        if (buffer.Size <= mss)
        {
            count = 1;
        }
        else
        {
            count = (buffer.Size + mss - 1) / mss;
        }
        if (count > 255)
        {
            return -2;
        }
        if (count == 0)
        {
            count = 1;
        }
        //fragment
        for (int i = 0; i < count; i++)
        {
            int size = buffer.Size > mss ? mss : buffer.Size;
            Segment seg = SegmentNew(size);
            seg.data.WriteBytesFrom(buffer, size);
            seg.frg = this.stream ? 0 : count - i - 1;
            snd_queue.Add(seg);
        }
        return 0;
    }

19 Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn

private static IList<Item> GetVanillaLoot(FishingRod fr)
		{
			float chance = 1f;

			int clearWaterDistance = SHelper.Reflection.GetField<int>(fr, "clearWaterDistance").GetValue();
			List<Item> treasures = new List<Item>();

			while (Game1.random.NextDouble() <= chance)
			{
				chance *= 0.4f;
				if (Game1.currentSeason.Equals("spring") && !(fr.getLastFarmerToUse().currentLocation is Beach) && Game1.random.NextDouble() < 0.1)
				{
					treasures.Add(new Object(273, Game1.random.Next(2, 6) + ((Game1.random.NextDouble() < 0.25) ? 5 : 0), false, -1, 0));
				}
				if (fr.caughtDoubleFish && Game1.random.NextDouble() < 0.5)
				{
					treasures.Add(new Object(774, 2 + ((Game1.random.NextDouble() < 0.25) ? 2 : 0), false, -1, 0));
				}
				switch (Game1.random.Next(4))
				{
					case 0:
						if (clearWaterDistance >= 5 && Game1.random.NextDouble() < 0.03)
						{
							treasures.Add(new Object(386, Game1.random.Next(1, 3), false, -1, 0));
						}
						else
						{
							List<int> possibles = new List<int>();
							if (clearWaterDistance >= 4)
							{
								possibles.Add(384);
							}
							if (clearWaterDistance >= 3 && (possibles.Count == 0 || Game1.random.NextDouble() < 0.6))
							{
								possibles.Add(380);
							}
							if (possibles.Count == 0 || Game1.random.NextDouble() < 0.6)
							{
								possibles.Add(378);
							}
							if (possibles.Count == 0 || Game1.random.NextDouble() < 0.6)
							{
								possibles.Add(388);
							}
							if (possibles.Count == 0 || Game1.random.NextDouble() < 0.6)
							{
								possibles.Add(390);
							}
							possibles.Add(382);
							treasures.Add(new Object(possibles.ElementAt(Game1.random.Next(possibles.Count)), Game1.random.Next(2, 7) * ((Game1.random.NextDouble() < 0.05 + fr.getLastFarmerToUse().luckLevel * 0.015) ? 2 : 1), false, -1, 0));
							if (Game1.random.NextDouble() < 0.05 + fr.getLastFarmerToUse().LuckLevel * 0.03)
							{
								treasures.Last<Item>().Stack *= 2;
							}
						}
						break;
					case 1:
						if (clearWaterDistance >= 4 && Game1.random.NextDouble() < 0.1 && fr.getLastFarmerToUse().FishingLevel >= 6)
						{
							treasures.Add(new Object(687, 1, false, -1, 0));
						}
						else if (Game1.random.NextDouble() < 0.25 && fr.getLastFarmerToUse().craftingRecipes.ContainsKey("Wild Bait"))
						{
							treasures.Add(new Object(774, 5 + ((Game1.random.NextDouble() < 0.25) ? 5 : 0), false, -1, 0));
						}
						else if (fr.getLastFarmerToUse().FishingLevel >= 6)
						{
							treasures.Add(new Object(685, 1, false, -1, 0));
						}
						else
						{
							treasures.Add(new Object(685, 10, false, -1, 0));
						}
						break;
					case 2:
						if (Game1.random.NextDouble() < 0.1 && Game1.netWorldState.Value.LostBooksFound < 21 && fr.getLastFarmerToUse() != null && fr.getLastFarmerToUse().hasOrWillReceiveMail("lostBookFound"))
						{
							treasures.Add(new Object(102, 1, false, -1, 0));
						}
						else if (fr.getLastFarmerToUse().archaeologyFound.Count() > 0)
						{
							if (Game1.random.NextDouble() < 0.25 && fr.getLastFarmerToUse().FishingLevel > 1)
							{
								treasures.Add(new Object(Game1.random.Next(585, 588), 1, false, -1, 0));
							}
							else if (Game1.random.NextDouble() < 0.5 && fr.getLastFarmerToUse().FishingLevel > 1)
							{
								treasures.Add(new Object(Game1.random.Next(103, 120), 1, false, -1, 0));
							}
							else
							{
								treasures.Add(new Object(535, 1, false, -1, 0));
							}
						}
						else
						{
							treasures.Add(new Object(382, Game1.random.Next(1, 3), false, -1, 0));
						}
						break;
					case 3:
						switch (Game1.random.Next(3))
						{
							case 0:
								if (clearWaterDistance >= 4)
								{
									treasures.Add(new Object(537 + ((Game1.random.NextDouble() < 0.4) ? Game1.random.Next(-2, 0) : 0), Game1.random.Next(1, 4), false, -1, 0));
								}
								else if (clearWaterDistance >= 3)
								{
									treasures.Add(new Object(536 + ((Game1.random.NextDouble() < 0.4) ? -1 : 0), Game1.random.Next(1, 4), false, -1, 0));
								}
								else
								{
									treasures.Add(new Object(535, Game1.random.Next(1, 4), false, -1, 0));
								}
								if (Game1.random.NextDouble() < 0.05 + fr.getLastFarmerToUse().LuckLevel * 0.03)
								{
									treasures.Last<Item>().Stack *= 2;
								}
								break;
							case 1:
								if (fr.getLastFarmerToUse().FishingLevel < 2)
								{
									treasures.Add(new Object(382, Game1.random.Next(1, 4), false, -1, 0));
								}
								else
								{
									if (clearWaterDistance >= 4)
									{
										treasures.Add(new Object((Game1.random.NextDouble() < 0.3) ? 82 : ((Game1.random.NextDouble() < 0.5) ? 64 : 60), Game1.random.Next(1, 3), false, -1, 0));
									}
									else if (clearWaterDistance >= 3)
									{
										treasures.Add(new Object((Game1.random.NextDouble() < 0.3) ? 84 : ((Game1.random.NextDouble() < 0.5) ? 70 : 62), Game1.random.Next(1, 3), false, -1, 0));
									}
									else
									{
										treasures.Add(new Object((Game1.random.NextDouble() < 0.3) ? 86 : ((Game1.random.NextDouble() < 0.5) ? 66 : 68), Game1.random.Next(1, 3), false, -1, 0));
									}
									if (Game1.random.NextDouble() < 0.028 * (clearWaterDistance / 5f))
									{
										treasures.Add(new Object(72, 1, false, -1, 0));
									}
									if (Game1.random.NextDouble() < 0.05)
									{
										treasures.Last<Item>().Stack *= 2;
									}
								}
								break;
							case 2:
								if (fr.getLastFarmerToUse().FishingLevel < 2)
								{
									treasures.Add(new Object(770, Game1.random.Next(1, 4), false, -1, 0));
								}
								else
								{
									float luckModifier = (1f + (float)fr.getLastFarmerToUse().DailyLuck) * (clearWaterDistance / 5f);
									if (Game1.random.NextDouble() < 0.05 * luckModifier && !fr.getLastFarmerToUse().specialItems.Contains(14))
									{
										treasures.Add(new MeleeWeapon(14)
										{
											specialItem = true
										});
									}
									if (Game1.random.NextDouble() < 0.05 * luckModifier && !fr.getLastFarmerToUse().specialItems.Contains(51))
									{
										treasures.Add(new MeleeWeapon(51)
										{
											specialItem = true
										});
									}
									if (Game1.random.NextDouble() < 0.07 * luckModifier)
									{
										switch (Game1.random.Next(3))
										{
											case 0:
												treasures.Add(new Ring(516 + ((Game1.random.NextDouble() < fr.getLastFarmerToUse().LuckLevel / 11f) ? 1 : 0)));
												break;
											case 1:
												treasures.Add(new Ring(518 + ((Game1.random.NextDouble() < fr.getLastFarmerToUse().LuckLevel / 11f) ? 1 : 0)));
												break;
											case 2:
												treasures.Add(new Ring(Game1.random.Next(529, 535)));
												break;
										}
									}
									if (Game1.random.NextDouble() < 0.02 * luckModifier)
									{
										treasures.Add(new Object(166, 1, false, -1, 0));
									}
									if (fr.getLastFarmerToUse().FishingLevel > 5 && Game1.random.NextDouble() < 0.001 * luckModifier)
									{
										treasures.Add(new Object(74, 1, false, -1, 0));
									}
									if (Game1.random.NextDouble() < 0.01 * luckModifier)
									{
										treasures.Add(new Object(127, 1, false, -1, 0));
									}
									if (Game1.random.NextDouble() < 0.01 * luckModifier)
									{
										treasures.Add(new Object(126, 1, false, -1, 0));
									}
									if (Game1.random.NextDouble() < 0.01 * luckModifier)
									{
										treasures.Add(new Ring(527));
									}
									if (Game1.random.NextDouble() < 0.01 * luckModifier)
									{
										treasures.Add(new Boots(Game1.random.Next(504, 514)));
									}
									if (Game1.MasterPlayer.mailReceived.Contains("Farm_Eternal") && Game1.random.NextDouble() < 0.01 * luckModifier)
									{
										treasures.Add(new Object(928, 1, false, -1, 0));
									}
									if (treasures.Count == 1)
									{
										treasures.Add(new Object(72, 1, false, -1, 0));
									}
								}
								break;
						}
						break;
				}
			}
			if (treasures.Count == 0)
			{
				treasures.Add(new Object(685, Game1.random.Next(1, 4) * 5, false, -1, 0));
			}
			return treasures;
		}

19 Source : SwimHelperEvents.cs
with GNU General Public License v3.0
from aedenthorn

public static void GameLoop_UpdateTicked(object sender, UpdateTickedEventArgs e)
        {
            if (Game1.player.currentLocation == null || Game1.player == null || !Game1.displayFarmer || Game1.player.position == null)
                return;

            ModEntry.isUnderwater.Value = SwimUtils.IsMapUnderwater(Game1.player.currentLocation.Name);

            if (Game1.player.currentLocation.Name == "ScubaAbigailCave")
            {
                AbigailCaveTick();
            }

            if (Game1.activeClickableMenu == null)
            {
                if (ModEntry.isUnderwater.Value)
                {
                    if (ModEntry.oxygen.Value >= 0)
                    {
                        if (!SwimUtils.IsWearingScubaGear())
                            ModEntry.oxygen.Value--;
                        else {
                            if (ModEntry.oxygen.Value < SwimUtils.MaxOxygen())
                                ModEntry.oxygen.Value++;
                            if (ModEntry.oxygen.Value < SwimUtils.MaxOxygen())
                                ModEntry.oxygen.Value++;
                        }
                    }
                    if(ModEntry.oxygen.Value < 0 && !surfacing.Value)
                    {
                        surfacing.Value = true;
                        Game1.playSound("pullItemFromWater");
                        DiveLocation diveLocation = ModEntry.diveMaps[Game1.player.currentLocation.Name].DiveLocations.Last();
                        SwimUtils.DiveTo(diveLocation);
                    }
                }
                else
                {
                    surfacing.Value = false;
                    if (ModEntry.oxygen.Value < SwimUtils.MaxOxygen())
                        ModEntry.oxygen.Value++;
                    if (ModEntry.oxygen.Value < SwimUtils.MaxOxygen())
                        ModEntry.oxygen.Value++;
                }
            }

            if (SwimUtils.IsWearingScubaGear())
            {
                ticksWearingScubaGear.Value++;
                if (Config.BreatheSound && breatheEffect.Value != null && (lastBreatheSound.Value == 0 || ticksWearingScubaGear.Value - lastBreatheSound.Value > 6000 / 16))
                {
                    Monitor.Log("Playing breathe sound");
                    lastBreatheSound.Value = ticksWearingScubaGear.Value;
                    breatheEffect.Value.Play(0.5f * Game1.options.soundVolumeLevel, 0f, 0f);
                }
            }
            else
            {
                if (breatheEffect.Value != null && lastBreatheSound.Value != 0)
                {
                    breatheEffect.Value.Dispose();
                    LoadBreatheSound();
                }
                lastBreatheSound.Value = 0;
                ticksWearingScubaGear.Value = 0;
            }

            if (isJumping.Value)
            {
                float difx = endJumpLoc.Value.X - startJumpLoc.Value.X;
                float dify = endJumpLoc.Value.Y - startJumpLoc.Value.Y;
                float completed = Game1.player.freezePause / (float)Config.JumpTimeInMilliseconds;
                if (Game1.player.freezePause <= 0)
                {
                    Game1.player.position.Value = endJumpLoc.Value;
                    isJumping.Value = false;
                    if (ModEntry.willSwim.Value)
                    {
                        Game1.player.currentLocation.playSound("waterSlosh", NetAudio.SoundContext.Default);
                        Game1.player.swimming.Value = true;
                    }
                    else
                    {
                        if (!Config.SwimSuitAlways)
                            Game1.player.changeOutOfSwimSuit();
                    }
                    return;
                }
                Game1.player.position.Value = new Vector2(endJumpLoc.Value.X - (difx * completed), endJumpLoc.Value.Y - (dify * completed) - (float)Math.Sin(completed * Math.PI) * 64);
                return;
            }

            // only if ready to swim from here on!

            if (!Config.ReadyToSwim || !Context.IsPlayerFree || Game1.player.currentLocation is BeachNightMarket)
            {
                return;
            }

            if (Game1.player.swimming.Value) {
                if (!SwimUtils.IsInWater() && !isJumping.Value)
                {
                    Monitor.Log("Swimming out of water");
                    ModEntry.willSwim.Value = false;
                    Game1.player.freezePause = Config.JumpTimeInMilliseconds;
                    Game1.player.currentLocation.playSound("dwop", NetAudio.SoundContext.Default);
                    Game1.player.currentLocation.playSound("waterSlosh", NetAudio.SoundContext.Default);
                    isJumping.Value = true;
                    startJumpLoc.Value = Game1.player.position.Value;
                    endJumpLoc.Value = Game1.player.position.Value;

                    Game1.player.swimming.Value = false;
                    if (Game1.player.bathingClothes.Value && !Config.SwimSuitAlways)
                        Game1.player.changeOutOfSwimSuit();
                }

                DiveMap dm = null;
                Point edgePos = Game1.player.getTileLocationPoint();

                if (ModEntry.diveMaps.ContainsKey(Game1.player.currentLocation.Name))
                {
                    dm = ModEntry.diveMaps[Game1.player.currentLocation.Name];
                }

                if (Game1.player.position.Y > Game1.viewport.Y + Game1.viewport.Height - 16)
                {
                    Game1.player.position.Value = new Vector2(Game1.player.position.X, Game1.viewport.Y + Game1.viewport.Height - 17);
                    if (dm != null)
                    {
                        EdgeWarp edge = dm.EdgeWarps.Find((x) => x.ThisMapEdge == "Bottom" && x.FirstTile <= edgePos.X && x.LastTile >= edgePos.X);
                        if (edge != null)
                        {
                            Point pos = SwimUtils.GetEdgeWarpDestination(edgePos.X, edge);
                            if (pos != Point.Zero)
                            {
                                Monitor.Log("warping south");
                                Game1.warpFarmer(edge.OtherMapName, pos.X, pos.Y, false);
                            }
                        }
                    }
                }
                else if (Game1.player.position.Y < Game1.viewport.Y - 16)
                {
                    Game1.player.position.Value = new Vector2(Game1.player.position.X, Game1.viewport.Y - 15);

                    if (dm != null)
                    {
                        EdgeWarp edge = dm.EdgeWarps.Find((x) => x.ThisMapEdge == "Top" && x.FirstTile <= edgePos.X && x.LastTile >= edgePos.X);
                        if (edge != null)
                        {
                            Point pos = SwimUtils.GetEdgeWarpDestination(edgePos.X, edge);
                            if (pos != Point.Zero)
                            {
                                Monitor.Log("warping north");
                                Game1.warpFarmer(edge.OtherMapName, pos.X, pos.Y, false);
                            }
                        }
                    }
                }
                else if (Game1.player.position.X > Game1.viewport.X + Game1.viewport.Width - 32)
                {
                    Game1.player.position.Value = new Vector2(Game1.viewport.X + Game1.viewport.Width - 33, Game1.player.position.Y);

                    if (dm != null)
                    {
                        EdgeWarp edge = dm.EdgeWarps.Find((x) => x.ThisMapEdge == "Right" && x.FirstTile <= edgePos.Y && x.LastTile >= edgePos.Y);
                        if (edge != null)
                        {
                            Point pos = SwimUtils.GetEdgeWarpDestination(edgePos.Y, edge);
                            if (pos != Point.Zero)
                            {
                                Monitor.Log("warping east");
                                Game1.warpFarmer(edge.OtherMapName, pos.X, pos.Y, false);
                            }
                        }
                    }

                    if (Game1.player.currentLocation.Name == "Forest")
                    {
                        if (Game1.player.position.Y / 64 > 74)
                            Game1.warpFarmer("Beach", 0, 13, false);
                        else
                            Game1.warpFarmer("Town", 0, 100, false);
                    }
                }
                else if (Game1.player.position.X < Game1.viewport.X - 32)
                {
                    Game1.player.position.Value = new Vector2(Game1.viewport.X - 31, Game1.player.position.Y);

                    if (dm != null)
                    {
                        EdgeWarp edge = dm.EdgeWarps.Find((x) => x.ThisMapEdge == "Left" && x.FirstTile <= edgePos.Y && x.LastTile >= edgePos.Y);
                        if (edge != null)
                        {
                            Point pos = SwimUtils.GetEdgeWarpDestination(edgePos.Y, edge);
                            if (pos != Point.Zero)
                            {
                                Monitor.Log("warping west");
                                Game1.warpFarmer(edge.OtherMapName, pos.X, pos.Y, false);
                            }
                        }
                    }

                    if (Game1.player.currentLocation.Name == "Town")
                    {
                        Game1.warpFarmer("Forest", 119, 43, false);
                    }
                    else if (Game1.player.currentLocation.Name == "Beach")
                    {
                        Game1.warpFarmer("Forest", 119, 111, false);
                    }
                }

                if (Game1.player.bathingClothes.Value && SwimUtils.IsWearingScubaGear() && !Config.SwimSuitAlways)
                    Game1.player.changeOutOfSwimSuit();
                else if (!Game1.player.bathingClothes.Value && !Config.NoAutoSwimSuit && (!SwimUtils.IsWearingScubaGear() || Config.SwimSuitAlways))
                    Game1.player.changeIntoSwimsuit();

                if (Game1.player.boots.Value != null && ModEntry.scubaFinsID.Value != -1 && Game1.player.boots.Value.indexInTileSheet.Value == ModEntry.scubaFinsID.Value)
                {
                    int buffId = 42883167;
                    Buff buff = Game1.buffsDisplay.otherBuffs.FirstOrDefault((Buff p) => p.which == buffId);
                    if (buff == null)
                    {
                        BuffsDisplay buffsDisplay = Game1.buffsDisplay;
                        Buff buff2 = new Buff(0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 1, "Scuba Fins", Helper.Translation.Get("scuba-fins"));
                        buff2.which = buffId;
                        buff = buff2;
                        buffsDisplay.addOtherBuff(buff2);
                    }
                    buff.millisecondsDuration = 50;
                }
            }
            else
            {
                if (SwimUtils.IsInWater() && !isJumping.Value)
                {
                    Monitor.Log("In water not swimming");

                    ModEntry.willSwim.Value = true;
                    Game1.player.freezePause = Config.JumpTimeInMilliseconds;
                    Game1.player.currentLocation.playSound("dwop", NetAudio.SoundContext.Default);
                    isJumping.Value = true;
                    startJumpLoc.Value = Game1.player.position.Value;
                    endJumpLoc.Value = Game1.player.position.Value;


                    Game1.player.swimming.Value = true;
                    if (!Game1.player.bathingClothes.Value && !SwimUtils.IsWearingScubaGear() && !Config.NoAutoSwimSuit)
                        Game1.player.changeIntoSwimsuit();
                }

            }

            SwimUtils.CheckIfMyButtonDown();

            if (!ModEntry.myButtonDown.Value || Game1.player.millisecondsPlayed - lastJump.Value < 250 || SwimUtils.IsMapUnderwater(Game1.player.currentLocation.Name))
                return;

            if (Helper.Input.IsDown(SButton.MouseLeft) && !Game1.player.swimming.Value && (Game1.player.CurrentTool is WateringCan || Game1.player.CurrentTool is FishingRod))
                return;

            List<Vector2> tiles = SwimUtils.GetTilesInDirection(5);
            Vector2 jumpLocation = Vector2.Zero;
            
            double distance = -1;
            int maxDistance = 0;
            switch (Game1.player.FacingDirection)
            {
                case 0:
                    distance = Math.Abs(Game1.player.position.Y - tiles.Last().Y * Game1.tileSize);
                    maxDistance = 72;
                    break;
                case 2:
                    distance = Math.Abs(Game1.player.position.Y - tiles.Last().Y * Game1.tileSize);
                    maxDistance = 48;
                    break;
                case 1:
                case 3:
                    distance = Math.Abs(Game1.player.position.X - tiles.Last().X * Game1.tileSize);
                    maxDistance = 65;
                    break;
            }
            if (Helper.Input.IsDown(SButton.MouseLeft))
            {
                try
                {
                    int xTile = (Game1.viewport.X + Game1.getOldMouseX()) / 64;
                    int yTile = (Game1.viewport.Y + Game1.getOldMouseY()) / 64;
                    bool water = Game1.player.currentLocation.waterTiles[xTile, yTile];
                    if (Game1.player.swimming.Value != water)
                    {
                        distance = -1;
                    }
                }
                catch
                {

                }
            }
            //Monitor.Value.Log("Distance: " + distance);

            bool nextToLand = Game1.player.swimming.Value && !Game1.player.currentLocation.isTilePreplacedable(new Location((int)tiles.Last().X, (int)tiles.Last().Y), Game1.viewport) && !SwimUtils.IsWaterTile(tiles[tiles.Count - 2]) && distance < maxDistance;
            
            bool nextToWater = false;
            try
            {
                nextToWater = !Game1.player.swimming.Value &&
                    !SwimUtils.IsTilePreplacedable(Game1.player.currentLocation, new Location((int)tiles.Last().X, (int)tiles.Last().Y), Game1.viewport) &&
                    (Game1.player.currentLocation.waterTiles[(int)tiles.Last().X, (int)tiles.Last().Y]
                        || SwimUtils.IsWaterTile(tiles[tiles.Count - 2])) 
                    && distance < maxDistance;
            }
            catch
            {
                //Monitor.Value.Log($"exception trying to get next to water: {ex}");
            }

            //Monitor.Value.Log($"next preplacedable {Game1.player.currentLocation.isTilePreplacedable(new Location((int)tiles.Last().X, (int)tiles.Last().Y), Game1.viewport)} next to land: {nextToLand}, next to water: {nextToWater}");


            if (Helper.Input.IsDown(Config.SwimKey) || nextToLand || nextToWater)
            {
                //Monitor.Value.Log("okay to jump");
                for(int i = 0; i < tiles.Count; i++)
                {
                    Vector2 tileV = tiles[i];
                    bool isWater = false;
                    bool isPreplacedable = false;
                    try
                    {
                        Tile tile = Game1.player.currentLocation.map.GetLayer("Buildings").PickTile(new Location((int)tileV.X * Game1.tileSize, (int)tileV.Y * Game1.tileSize), Game1.viewport.Size);
                        isWater = SwimUtils.IsWaterTile(tileV);
                        isPreplacedable = (nextToLand && !isWater && SwimUtils.IsTilePreplacedable(Game1.player.currentLocation, new Location((int)tileV.X, (int)tileV.Y), Game1.viewport)) || (nextToWater && isWater && (tile == null || tile.TileIndex == 76));
                        //Monitor.Value.Log($"Trying {tileV} is preplacedable {isPreplacedable} isWater {isWater}");
                        if (!SwimUtils.IsTilePreplacedable(Game1.player.currentLocation, new Location((int)tileV.X, (int)tileV.Y), Game1.viewport) && !isWater && nextToLand)
                        {
                            //Monitor.Value.Log($"Nixing {tileV}");
                            jumpLocation = Vector2.Zero;
                        }
                    }
                    catch(Exception ex)
                    {
                        Monitor.Log(""+ex);
                    }
                    if (nextToLand && !isWater && isPreplacedable)
                    {
                        Monitor.Log($"Jumping to {tileV}");
                        jumpLocation = tileV;

                    }

                    if (nextToWater && isWater && isPreplacedable)
                    {
                        Monitor.Log($"Jumping to {tileV}");
                        jumpLocation = tileV;

                    }


                }
            }

            if (jumpLocation != Vector2.Zero)
            {
                lastJump.Value = Game1.player.millisecondsPlayed;
                //Monitor.Value.Log("got swim location");
                if (Game1.player.swimming.Value) 
                { 
                    ModEntry.willSwim.Value = false;
                    Game1.player.swimming.Value = false;
                    Game1.player.freezePause = Config.JumpTimeInMilliseconds;
                    Game1.player.currentLocation.playSound("dwop", NetAudio.SoundContext.Default);
                    Game1.player.currentLocation.playSound("waterSlosh", NetAudio.SoundContext.Default);
                }
                else
                {
                    ModEntry.willSwim.Value = true;
                    if(!SwimUtils.IsWearingScubaGear() && !Config.NoAutoSwimSuit)
                        Game1.player.changeIntoSwimsuit();
                    
                    Game1.player.freezePause = Config.JumpTimeInMilliseconds;
                    Game1.player.currentLocation.playSound("dwop", NetAudio.SoundContext.Default);
                }
                isJumping.Value = true;
                startJumpLoc.Value = Game1.player.position.Value;
                endJumpLoc.Value = new Vector2(jumpLocation.X * Game1.tileSize, jumpLocation.Y * Game1.tileSize);
            }

        }

19 Source : SwimMaps.cs
with GNU General Public License v3.0
from aedenthorn

public static void AddOceanTreasure(GameLocation l)
        {
            List<Vector2> spots = new List<Vector2>();
            for (int x = 0; x < l.map.Layers[0].LayerWidth; x++)
            {
                for (int y = 0; y < l.map.Layers[0].LayerHeight; y++)
                {
                    Tile tile = l.map.GetLayer("Back").PickTile(new Location(x, y) * Game1.tileSize, Game1.viewport.Size);
                    if (tile != null && l.map.GetLayer("Buildings").PickTile(new Location(x, y) * Game1.tileSize, Game1.viewport.Size) == null && l.map.GetLayer("Front").PickTile(new Location(x, y) * Game1.tileSize, Game1.viewport.Size) == null && !l.overlayObjects.ContainsKey(new Vector2(x, y)))
                    {
                        spots.Add(new Vector2(x, y));
                    }
                }
            }
            int n = spots.Count;
            while (n > 1)
            {
                n--;
                int k = Game1.random.Next(n + 1);
                var value = spots[k];
                spots[k] = spots[n];
                spots[n] = value;
            }

            int treasureNo = (int)(Game1.random.Next(Config.MinOceanChests, Config.MaxOceanChests));

            List<Vector2> treasureSpots = new List<Vector2>(spots).Take(treasureNo).ToList();

            foreach (Vector2 v in treasureSpots)
            {

                List<Item> treasures = new List<Item>();
                float chance = 1f;
                while (Game1.random.NextDouble() <= (double)chance)
                {
                    chance *= 0.4f;
                    if (Game1.random.NextDouble() < 0.5)
                    {
                        treasures.Add(new StardewValley.Object(774, 2 + ((Game1.random.NextDouble() < 0.25) ? 2 : 0), false, -1, 0));
                    }
                    switch (Game1.random.Next(4))
                    {
                        case 0:
                            if (Game1.random.NextDouble() < 0.03)
                            {
                                treasures.Add(new StardewValley.Object(386, Game1.random.Next(1, 3), false, -1, 0));
                            }
                            else
                            {
                                List<int> possibles = new List<int>();
                                possibles.Add(384);
                                if (possibles.Count == 0 || Game1.random.NextDouble() < 0.6)
                                {
                                    possibles.Add(380);
                                }
                                if (possibles.Count == 0 || Game1.random.NextDouble() < 0.6)
                                {
                                    possibles.Add(378);
                                }
                                if (possibles.Count == 0 || Game1.random.NextDouble() < 0.6)
                                {
                                    possibles.Add(388);
                                }
                                if (possibles.Count == 0 || Game1.random.NextDouble() < 0.6)
                                {
                                    possibles.Add(390);
                                }
                                possibles.Add(382);
                                treasures.Add(new StardewValley.Object(possibles.ElementAt(Game1.random.Next(possibles.Count)), Game1.random.Next(2, 7) * ((Game1.random.NextDouble() < 0.05 + (double)Game1.player.luckLevel.Value * 0.015) ? 2 : 1), false, -1, 0));
                                if (Game1.random.NextDouble() < 0.05 + (double)Game1.player.LuckLevel * 0.03)
                                {
                                    treasures.Last<Item>().Stack *= 2;
                                }
                            }
                            break;
                        case 1:
                            if (Game1.random.NextDouble() < 0.1)
                            {
                                treasures.Add(new StardewValley.Object(687, 1, false, -1, 0));
                            }
                            else if (Game1.random.NextDouble() < 0.25 && Game1.player.craftingRecipes.ContainsKey("Wild Bait"))
                            {
                                treasures.Add(new StardewValley.Object(774, 5 + ((Game1.random.NextDouble() < 0.25) ? 5 : 0), false, -1, 0));
                            }
                            else
                            {
                                treasures.Add(new StardewValley.Object(685, 10, false, -1, 0));
                            }
                            break;
                        case 2:
                            if (Game1.random.NextDouble() < 0.1 && Game1.netWorldState.Value.LostBooksFound.Value < 21 && Game1.player.hasOrWillReceiveMail("lostBookFound"))
                            {
                                treasures.Add(new StardewValley.Object(102, 1, false, -1, 0));
                            }
                            else if (Game1.player.archaeologyFound.Count() > 0)
                            {
                                if (Game1.random.NextDouble() < 0.25)
                                {
                                    treasures.Add(new StardewValley.Object(Game1.random.Next(585, 588), 1, false, -1, 0));
                                }
                                else if (Game1.random.NextDouble() < 0.5)
                                {
                                    treasures.Add(new StardewValley.Object(Game1.random.Next(103, 120), 1, false, -1, 0));
                                }
                                else
                                {
                                    treasures.Add(new StardewValley.Object(535, 1, false, -1, 0));
                                }
                            }
                            else
                            {
                                treasures.Add(new StardewValley.Object(382, Game1.random.Next(1, 3), false, -1, 0));
                            }
                            break;
                        case 3:
                            switch (Game1.random.Next(3))
                            {
                                case 0:
                                    switch (Game1.random.Next(3))
                                    {
                                        case 0:
                                            treasures.Add(new StardewValley.Object(537 + ((Game1.random.NextDouble() < 0.4) ? Game1.random.Next(-2, 0) : 0), Game1.random.Next(1, 4), false, -1, 0));
                                            break;
                                        case 1:
                                            treasures.Add(new StardewValley.Object(536 + ((Game1.random.NextDouble() < 0.4) ? -1 : 0), Game1.random.Next(1, 4), false, -1, 0));
                                            break;
                                        case 2:
                                            treasures.Add(new StardewValley.Object(535, Game1.random.Next(1, 4), false, -1, 0));
                                            break;
                                    }
                                    if (Game1.random.NextDouble() < 0.05 + (double)Game1.player.LuckLevel * 0.03)
                                    {
                                        treasures.Last<Item>().Stack *= 2;
                                    }
                                    break;
                                case 1:
                                    switch (Game1.random.Next(4))
                                    {
                                        case 0:
                                            treasures.Add(new StardewValley.Object(382, Game1.random.Next(1, 4), false, -1, 0));
                                            break;
                                        case 1:
                                            treasures.Add(new StardewValley.Object((Game1.random.NextDouble() < 0.3) ? 82 : ((Game1.random.NextDouble() < 0.5) ? 64 : 60), Game1.random.Next(1, 3), false, -1, 0));
                                            break;
                                        case 2:
                                            treasures.Add(new StardewValley.Object((Game1.random.NextDouble() < 0.3) ? 84 : ((Game1.random.NextDouble() < 0.5) ? 70 : 62), Game1.random.Next(1, 3), false, -1, 0));
                                            break;
                                        case 3:
                                            treasures.Add(new StardewValley.Object((Game1.random.NextDouble() < 0.3) ? 86 : ((Game1.random.NextDouble() < 0.5) ? 66 : 68), Game1.random.Next(1, 3), false, -1, 0));
                                            break;
                                    }
                                    if (Game1.random.NextDouble() < 0.05)
                                    {
                                        treasures.Add(new StardewValley.Object(72, 1, false, -1, 0));
                                    }
                                    if (Game1.random.NextDouble() < 0.05)
                                    {
                                        treasures.Last<Item>().Stack *= 2;
                                    }
                                    break;
                                case 2:
                                    if (Game1.player.FishingLevel < 2)
                                    {
                                        treasures.Add(new StardewValley.Object(770, Game1.random.Next(1, 4), false, -1, 0));
                                    }
                                    else
                                    {
                                        float luckModifier = (1f + (float)Game1.player.DailyLuck);
                                        if (Game1.random.NextDouble() < 0.05 * (double)luckModifier && !Game1.player.specialItems.Contains(14))
                                        {
                                            treasures.Add(new MeleeWeapon(14)
                                            {
                                                specialItem = true
                                            });
                                        }
                                        if (Game1.random.NextDouble() < 0.05 * (double)luckModifier && !Game1.player.specialItems.Contains(51))
                                        {
                                            treasures.Add(new MeleeWeapon(51)
                                            {
                                                specialItem = true
                                            });
                                        }
                                        if (Game1.random.NextDouble() < 0.07 * (double)luckModifier)
                                        {
                                            switch (Game1.random.Next(3))
                                            {
                                                case 0:
                                                    treasures.Add(new Ring(516 + ((Game1.random.NextDouble() < (double)((float)Game1.player.LuckLevel / 11f)) ? 1 : 0)));
                                                    break;
                                                case 1:
                                                    treasures.Add(new Ring(518 + ((Game1.random.NextDouble() < (double)((float)Game1.player.LuckLevel / 11f)) ? 1 : 0)));
                                                    break;
                                                case 2:
                                                    treasures.Add(new Ring(Game1.random.Next(529, 535)));
                                                    break;
                                            }
                                        }
                                        if (Game1.random.NextDouble() < 0.02 * (double)luckModifier)
                                        {
                                            treasures.Add(new StardewValley.Object(166, 1, false, -1, 0));
                                        }
                                        if (Game1.random.NextDouble() < 0.001 * (double)luckModifier)
                                        {
                                            treasures.Add(new StardewValley.Object(74, 1, false, -1, 0));
                                        }
                                        if (Game1.random.NextDouble() < 0.01 * (double)luckModifier)
                                        {
                                            treasures.Add(new StardewValley.Object(127, 1, false, -1, 0));
                                        }
                                        if (Game1.random.NextDouble() < 0.01 * (double)luckModifier)
                                        {
                                            treasures.Add(new StardewValley.Object(126, 1, false, -1, 0));
                                        }
                                        if (Game1.random.NextDouble() < 0.01 * (double)luckModifier)
                                        {
                                            treasures.Add(new Ring(527));
                                        }
                                        if (Game1.random.NextDouble() < 0.01 * (double)luckModifier)
                                        {
                                            treasures.Add(new Boots(Game1.random.Next(504, 514)));
                                        }
                                        if (treasures.Count == 1)
                                        {
                                            treasures.Add(new StardewValley.Object(72, 1, false, -1, 0));
                                        }
                                    }
                                    break;
                            }
                            break;
                    }
                }
                if (treasures.Count == 0)
                {
                    treasures.Add(new StardewValley.Object(685, Game1.random.Next(1, 4) * 5, false, -1, 0));
                }
                if (treasures.Count > 0)
                {
                    Color tint = Color.White;
                    l.overlayObjects[v] = new Chest(Game1.random.Next(0, 1000), new List<Item>() { treasures[ModEntry.myRand.Value.Next(treasures.Count)] }, v, false, 0)
                    {
                        Tint = tint
                    };
                }
            }
        }

19 Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn

private void GameLoop_UpdateTicked(object sender, StardewModdingAPI.Events.UpdateTickedEventArgs e)
        {
            if (waveStarted)
                Game1.timeOfDay = 100 * (Game1.timeOfDay / 100);
            if (!Context.IsWorldReady || !Game1.player.IsMainPlayer || !(Game1.player.currentLocation is Farm))
                return;
            Farm farm = Game1.getFarm();

            if (farm == null)
                return;



            IEnumerable<Vector2> monsterPosList = farm.characters.Where(n => n is Monster && (n as Monster).health > 0).Select(m => m.position.Value);

            if (!monsterPosList.Any())
                return;

            foreach(Vector2 pos in monsterPosList)
            {
                KeyValuePair<Vector2, TerrainFeature> kvp = farm.terrainFeatures.Pairs.FirstOrDefault(k => k.Value is HoeDirt && (k.Value as HoeDirt).crop != null && k.Key == pos / Game1.tileSize);
                if(!kvp.Equals(default(KeyValuePair<Vector2, TerrainFeature>)))
                {
                    (farm.terrainFeatures[kvp.Key] as HoeDirt).destroyCrop(kvp.Key, false, farm);
                }
                    
            }

            foreach (KeyValuePair<Vector2, Object> crow in farm.objects.Pairs.Where(s => s.Value.bigCraftable && s.Value.Name.Contains("arecrow")))
            {
                MurderCrow mc = murderCrows[crow.Value.Name];
                IEnumerable<Vector2> monsters = monsterPosList.Where(m => Vector2.Distance(m, crow.Key * Game1.tileSize) < mc.range * Game1.tileSize).OrderBy(m => Vector2.Distance(m, crow.Key));

                if (monsters.Any() && ticksSinceMorning % (1000 / mc.rate) == 0)
                {
                    Vector2 dir = (monsters.Last() - crow.Key * Game1.tileSize);
                    dir.Normalize();

                    if(mc.name == "Rarecrow" || mc.name == "Iridium Scarecrow")
                    {
                        if (ticksSinceMorning % 1000  == 0)
                            farm.playSound("furnace"); 


                        float fire_angle = (float)Math.Atan2(dir.Y, dir.X);
                        if(mc.name == "Iridium Scarecrow")
                            fire_angle += (float)Math.Sin((double)((float)ticksSinceMorning % 180f) * 3.1415926535897931 / 180.0) * 25f;
                        else
                            fire_angle += (float)Math.Sin((double)((float)ticksSinceMorning % 10f) * 3.1415926535897931 / 180.0);

                        Vector2 shot_velocity = new Vector2((float)Math.Cos((double)fire_angle), (float)Math.Sin((double)fire_angle));
                        shot_velocity *= 10f;
                        BasicProjectile projectile = new BasicProjectile(mc.damage, 10, 0, 1, 0.196349546f, shot_velocity.X, shot_velocity.Y, crow.Key * Game1.tileSize, "", "", false, true, farm, Game1.MasterPlayer, false, null);
                        projectile.ignoreTravelGracePeriod.Value = true;
                        projectile.maxTravelDistance.Value = mc.range * 64;
                        farm.projectiles.Add(projectile);
                    }
                    else 
                        farm.projectiles.Add(new BasicProjectile(mc.damage, mc.ammoIndex, 0, 0, 0.3f, dir.X * shotVelocity, dir.Y * shotVelocity, crow.Key * Game1.tileSize, mc.hitSound, mc.fireSound, mc.explode, true, farm, Game1.MasterPlayer, mc.useTileSheet));
                }
            }
            ticksSinceMorning++;
        }

19 Source : UIManager.cs
with GNU General Public License v3.0
from aelariane

public static bool Enable(GUIBase gui)
        {
            if (gui.IsActive)
            {
                return false;
            }
            if (Instance == null)
            {
                onAwakeAdds += delegate ()
                {
                    Enable(gui);
                };
                return false;
            }
            lock (activeGUIs)
            {
                if (activeGUIs == null || activeGUIs.Length == 0)
                {
                    activeGUIs = new GUIBase[] { gui };
                    gui.Drawer.Enable();
                    UpdateDepths();
                    return true;
                }

                for (int i = 0; i < activeGUIs.Length; i++)
                {
                    if (activeGUIs[i] == gui)
                    {
                        return false;
                    }
                }

                var list = activeGUIs.ToList();
                list.Add(gui);
                activeGUIs = list
                    .OrderBy(x => x.Layer)
                    .ToArray();

                if(activeGUIs.Last() == gui)
                {
                    if(activeGUIs.Length >= 2)
                    {
                        gui.Drawer.Enable(activeGUIs[activeGUIs.Length - 2].Drawer.Depth - 1);
                    }
                    else
                    {
                        gui.Drawer.Enable();
                        UpdateDepths();
                    }
                }
                else
                {
                    gui.Drawer.Enable();
                    UpdateDepths();
                }

                return true;
            }
        }

19 Source : TreasuryContract.cs
with MIT License
from AElfProject

private void UpdateBasicMinerRewardWeights(IReadOnlyCollection<Round> previousTermInformation)
        {
            if (previousTermInformation.First().RealTimeMinersInformation != null)
            {
                State.ProfitContract.RemoveBeneficiaries.Send(new RemoveBeneficiariesInput
                {
                    SchemeId = State.BasicRewardHash.Value,
                    Beneficiaries =
                    {
                        previousTermInformation.First().RealTimeMinersInformation.Keys.Select(k =>
                            Address.FromPublicKey(ByteArrayHelper.HexStringToByteArray(k)))
                    }
                });
            }

            var averageProducedBlocksCount = CalculateAverage(previousTermInformation.Last().RealTimeMinersInformation
                .Values
                .Select(i => i.ProducedBlocks).ToList());
            // Manage weights of `MinerBasicReward`
            State.ProfitContract.AddBeneficiaries.Send(new AddBeneficiariesInput
            {
                SchemeId = State.BasicRewardHash.Value,
                EndPeriod = previousTermInformation.Last().TermNumber,
                BeneficiaryShares =
                {
                    previousTermInformation.Last().RealTimeMinersInformation.Values.Select(i =>
                    {
                        long shares;
                        if (State.IsReplacedEvilMiner[i.Pubkey])
                        {
                            // The new miner may have more shares than his actually contributes, but it's ok.
                            shares = i.ProducedBlocks;
                            // Clear the state asap.
                            State.IsReplacedEvilMiner.Remove(i.Pubkey);
                        }
                        else
                        {
                            shares = CalculateShares(i.ProducedBlocks, averageProducedBlocksCount);
                        }

                        return new BeneficiaryShare
                        {
                            Beneficiary = Address.FromPublicKey(ByteArrayHelper.HexStringToByteArray(i.Pubkey)),
                            Shares = shares
                        };
                    })
                }
            });
        }

19 Source : CryptoHelper.cs
with MIT License
from AElfProject

public static bool RecoverPublicKey(byte[] signature, byte[] hash, out byte[] pubkey)
        {
            pubkey = null;
            try
            {
                Lock.AcquireWriterLock(Timeout.Infinite);
                // Recover id should be greater than or equal to 0 and less than 4
                if (signature.Length != Secp256k1.SERIALIZED_UNCOMPRESSED_PUBKEY_LENGTH || signature.Last() >= 4)
                    return false;
                var pubKey = new byte[Secp256k1.SERIALIZED_UNCOMPRESSED_PUBKEY_LENGTH];
                var recoveredPubKey = new byte[Secp256k1.PUBKEY_LENGTH];
                var recSig = new byte[65];
                if (!Secp256K1.RecoverableSignatureParseCompact(recSig, signature, signature.Last()))
                    return false;
                if (!Secp256K1.Recover(recoveredPubKey, recSig, hash))
                    return false;
                if (!Secp256K1.PublicKeySerialize(pubKey, recoveredPubKey))
                    return false;
                pubkey = pubKey;
                return true;
            }
            finally
            {
                Lock.ReleaseWriterLock();
            }
        }

19 Source : CrossChainIndexingDataService.cs
with MIT License
from AElfProject

private async Task<List<SideChainBlockData>> GetNonIndexedSideChainBlockDataAsync(Hash blockHash,
            long blockHeight, HashSet<int> excludeChainIdList)
        {
            var crossChainContractAddress = await GetCrossChainContractAddressAsync(new ChainContext
            {
                BlockHash = blockHash,
                BlockHeight = blockHeight
            });
            var sideChainBlockDataList = new List<SideChainBlockData>();
            var sideChainIndexingInformationList = await _contractReaderFactory
                .Create(new ContractReaderContext
                {
                    BlockHash = blockHash,
                    BlockHeight = blockHeight,
                    ContractAddress = crossChainContractAddress
                })
                .GetSideChainIndexingInformationList.CallAsync(new Empty());
            foreach (var sideChainIndexingInformation in sideChainIndexingInformationList.IndexingInformationList)
            {
                var libDto = await _irreversibleBlockStateProvider.GetLastIrreversibleBlockHashAndHeightAsync();
                var sideChainId = sideChainIndexingInformation.ChainId;
                if (excludeChainIdList.Contains(sideChainId))
                    continue;
                var sideChainHeightInLibValue = await _contractReaderFactory
                    .Create(new ContractReaderContext
                    {
                        BlockHash = libDto.BlockHash,
                        BlockHeight = libDto.BlockHeight,
                        ContractAddress = crossChainContractAddress
                    })
                    .GetSideChainHeight.CallAsync(new Int32Value {Value = sideChainId});

                long toBeIndexedCount;
                long targetHeight;
                var sideChainHeightInLib = sideChainHeightInLibValue?.Value ?? 0;
                if (sideChainHeightInLib > 0)
                {
                    targetHeight = sideChainIndexingInformation.IndexedHeight + 1;
                    toBeIndexedCount = CrossChainConstants.DefaultBlockCacheEnreplacedyCount;
                    Logger.LogDebug(
                        $"Target height {targetHeight} of side chain " +
                        $"{ChainHelper.ConvertChainIdToBase58(sideChainId)}.");
                }
                else if (sideChainIndexingInformation.IndexedHeight > 0)
                {
                    toBeIndexedCount = 0;
                    targetHeight = sideChainIndexingInformation.IndexedHeight + 1;
                }
                else
                {
                    toBeIndexedCount = 1;
                    targetHeight = AElfConstants.GenesisBlockHeight;
                    Logger.LogDebug(
                        $"Target height {targetHeight} of side chain " +
                        $"{ChainHelper.ConvertChainIdToBase58(sideChainId)}.");
                }

                var sideChainBlockDataFromCache = new List<SideChainBlockData>();

                var i = 0;
                while (i < toBeIndexedCount)
                {
                    var sideChainBlockData =
                        _blockCacheEnreplacedyConsumer.Take<SideChainBlockData>(sideChainIndexingInformation.ChainId,
                            targetHeight, targetHeight == AElfConstants.GenesisBlockHeight);
                    if (sideChainBlockData == null || sideChainBlockData.Height != targetHeight)
                    {
                        // no more available side chain block info
                        break;
                    }

                    sideChainBlockDataFromCache.Add(sideChainBlockData);
                    targetHeight++;
                    i++;
                }

                if (sideChainBlockDataFromCache.Count > 0)
                {
                    Logger.LogDebug(
                        $"Got height [{sideChainBlockDataFromCache.First().Height} - {sideChainBlockDataFromCache.Last().Height} ]" +
                        $" from side chain {ChainHelper.ConvertChainIdToBase58(sideChainIndexingInformation.ChainId)}.");
                    sideChainBlockDataList.AddRange(sideChainBlockDataFromCache);
                }
            }

            return sideChainBlockDataList;
        }

19 Source : CrossChainIndexingDataService.cs
with MIT License
from AElfProject

private async Task<List<ParentChainBlockData>> GetNonIndexedParentChainBlockDataAsync(Hash blockHash,
            long blockHeight, HashSet<int> excludeChainIdList)
        {
            var parentChainBlockDataList = new List<ParentChainBlockData>();
            var libExists = await _irreversibleBlockStateProvider.ValidateIrreversibleBlockExistingAsync();
            if (!libExists)
                return parentChainBlockDataList;

            var crossChainContractAddress = await GetCrossChainContractAddressAsync(new ChainContext
            {
                BlockHash = blockHash,
                BlockHeight = blockHeight
            });

            var returnValue = await _contractReaderFactory.Create(new ContractReaderContext
                {
                    BlockHash = blockHash,
                    BlockHeight = blockHeight,
                    ContractAddress = crossChainContractAddress
                }).GetParentChainId
                .CallAsync(new Empty());
            var parentChainId = returnValue?.Value ?? 0;
            if (parentChainId == 0 || excludeChainIdList.Contains(parentChainId))
            {
                // no configured parent chain
                return parentChainBlockDataList;
            }

            int length = CrossChainConstants.DefaultBlockCacheEnreplacedyCount;
            var heightInState = (await _contractReaderFactory
                .Create(new ContractReaderContext
                {
                    BlockHash = blockHash,
                    BlockHeight = blockHeight,
                    ContractAddress = crossChainContractAddress
                }).GetParentChainHeight
                .CallAsync(new Empty())).Value;

            var targetHeight = heightInState + 1;
            Logger.LogDebug($"Target height {targetHeight}");

            var i = 0;
            while (i < length)
            {
                var parentChainBlockData =
                    _blockCacheEnreplacedyConsumer.Take<ParentChainBlockData>(parentChainId, targetHeight, false);
                if (parentChainBlockData == null || parentChainBlockData.Height != targetHeight)
                {
                    // no more available parent chain block info
                    break;
                }

                parentChainBlockDataList.Add(parentChainBlockData);
                targetHeight++;
                i++;
            }

            if (parentChainBlockDataList.Count > 0)
                Logger.LogDebug(
                    $"Got height [{parentChainBlockDataList.First().Height} - {parentChainBlockDataList.Last().Height} ]" +
                    $" from parent chain {ChainHelper.ConvertChainIdToBase58(parentChainId)}.");
            return parentChainBlockDataList;
        }

19 Source : RedisLiteHelper.cs
with MIT License
from AElfProject

public static RedisEndpoint ToRedisEndpoint(this string connectionString, int? defaultPort = null)
        {
            if (connectionString == null)
                throw new ArgumentNullException("connectionString");
            if (connectionString.StartsWith("redis://"))
                connectionString = connectionString.Substring("redis://".Length);

            var domainParts = connectionString.SplitOnLast('@');
            var qsParts = domainParts.Last().SplitOnFirst('?');
            var hostParts = qsParts[0].SplitOnLast(':');
            var useDefaultPort = true;
            var port = defaultPort.GetValueOrDefault(RedisConfig.DefaultPort);
            if (hostParts.Length > 1)
            {
                port = int.Parse(hostParts[1]);
                useDefaultPort = false;
            }

            var endpoint = new RedisEndpoint(hostParts[0], port);
            if (domainParts.Length > 1)
            {
                var authParts = domainParts[0].SplitOnFirst(':');
                if (authParts.Length > 1)
                    endpoint.Client = authParts[0];

                endpoint.Preplacedword = authParts.Last();
            }

            if (qsParts.Length > 1)
            {
                var qsParams = qsParts[1].Split('&');
                foreach (var param in qsParams)
                {
                    var entry = param.Split('=');
                    var value = entry.Length > 1 ? WebUtility.UrlDecode( entry[1] ) : null;
                    if (value == null) continue;

                    var name = entry[0].ToLower();
                    HandleEndpointByName(endpoint, useDefaultPort, name, value);
                }
            }

            return endpoint;
        }

19 Source : CrossChainContract_Helper.cs
with MIT License
from AElfProject

private List<SideChainBlockData> IndexSideChainBlockData(IList<SideChainBlockData> sideChainBlockDataList,
            Address proposer, int chainId)
        {
            var indexedSideChainBlockData = new List<SideChainBlockData>();

            {
                var formattedProposerAddress = proposer.ToByteString().ToBase64();
                long indexingFeeAmount = 0;

                var sideChainInfo = State.SideChainInfo[chainId];
                var currentSideChainHeight = State.CurrentSideChainHeight[chainId];
                long arrearsAmount = 0;
                var lockedToken = sideChainInfo.SideChainStatus == SideChainStatus.IndexingFeeDebt
                    ? 0
                    : GetSideChainIndexingFeeDeposit(chainId);

                foreach (var sideChainBlockData in sideChainBlockDataList)
                {
                    var target = currentSideChainHeight != 0
                        ? currentSideChainHeight + 1
                        : AElfConstants.GenesisBlockHeight;
                    var sideChainHeight = sideChainBlockData.Height;
                    if (target != sideChainHeight)
                        break;

                    // indexing fee
                    var indexingPrice = sideChainInfo.IndexingPrice;

                    lockedToken -= indexingPrice;

                    if (lockedToken < 0)
                    {
                        // record arrears
                        arrearsAmount += indexingPrice;
                        sideChainInfo.SideChainStatus = SideChainStatus.IndexingFeeDebt;
                    }
                    else
                    {
                        indexingFeeAmount += indexingPrice;
                    }

                    currentSideChainHeight++;
                    indexedSideChainBlockData.Add(sideChainBlockData);
                }

                if (indexingFeeAmount > 0)
                {
                    TransferDepositToken(new TransferInput
                    {
                        To = proposer,
                        Symbol = Context.Variables.NativeSymbol,
                        Amount = indexingFeeAmount,
                        Memo = "Index fee."
                    }, chainId);
                }

                if (arrearsAmount > 0)
                {
                    if (sideChainInfo.ArrearsInfo.TryGetValue(formattedProposerAddress, out var amount))
                    {
                        sideChainInfo.ArrearsInfo[formattedProposerAddress] = amount + arrearsAmount;
                    }
                    else
                        sideChainInfo.ArrearsInfo[formattedProposerAddress] = arrearsAmount;
                }

                State.SideChainInfo[chainId] = sideChainInfo;
                State.CurrentSideChainHeight[chainId] = currentSideChainHeight;
            }

            if (indexedSideChainBlockData.Count > 0)
                Context.LogDebug(() =>
                    $"Last indexed height {indexedSideChainBlockData.Last().Height} for side chain {chainId}");

            return indexedSideChainBlockData;
        }

19 Source : IChainManager.cs
with MIT License
from AElfProject

public async Task<bool> SetIrreversibleBlockAsync(Chain chain, Hash irreversibleBlockHash)
        {
            var links = new List<ChainBlockLink>();

            while (true)
            {
                var chainBlockLink = await GetChainBlockLinkAsync(irreversibleBlockHash);
                if (chainBlockLink == null || !chainBlockLink.IsLinked)
                    throw new InvalidOperationException(
                        $"should not set an unlinked block as irreversible block, height: {chainBlockLink?.Height}, hash: {chainBlockLink?.BlockHash}");
                if (chainBlockLink.IsIrreversibleBlock)
                    break;
                chainBlockLink.IsIrreversibleBlock = true;
                links.Add(chainBlockLink);
                irreversibleBlockHash = chainBlockLink.PreviousBlockHash;
            }

            if (links.Count > 0)
            {
                if (links.Last().Height <= chain.LastIrreversibleBlockHeight)
                    return false;
                await SetChainBlockIndexesAsync(links.ToDictionary(l => l.Height, l => l.BlockHash));
                await SetChainBlockLinksAsync(links);
                chain.LastIrreversibleBlockHash = links.First().BlockHash;
                chain.LastIrreversibleBlockHeight = links.First().Height;
                await _chains.SetAsync(chain.Id.ToStorageKey(), chain);

                Logger.LogDebug(
                    $"Setting chain lib height: {chain.LastIrreversibleBlockHeight}, chain lib hash: {chain.LastIrreversibleBlockHash}");

                return true;
            }

            return false;
        }

19 Source : Executive.cs
with MIT License
from AElfProject

public byte[] GetFileDescriptorSet()
        {
            var descriptor = Descriptors.Last();
            var output = new FileDescriptorSet();
            output.File.AddRange(GetSelfAndDependency(descriptor.File).Select(x => x.SerializedData));
            return output.ToByteArray();
        }

19 Source : Executive.cs
with MIT License
from AElfProject

public IEnumerable<FileDescriptor> GetFileDescriptors()
        {
            var descriptor = Descriptors.Last();
            return GetSelfAndDependency(descriptor.File);
        }

19 Source : BinaryMerkleTree.cs
with MIT License
from AElfProject

private static void GenerateBinaryMerkleTreeNodesWithLeafNodes(IList<Hash> leafNodes)
        {
            if (!leafNodes.Any())
            {
                return;
            }

            if (leafNodes.Count % 2 == 1)
                leafNodes.Add(leafNodes.Last());
            var nodeToAdd = leafNodes.Count / 2;
            var newAdded = 0;
            var i = 0;
            while (i < leafNodes.Count - 1)
            {
                var left = leafNodes[i++];
                var right = leafNodes[i++];
                leafNodes.Add(HashHelper.ConcatAndCompute(left, right));
                if (++newAdded != nodeToAdd)
                    continue;

                // complete this row
                if (nodeToAdd % 2 == 1 && nodeToAdd != 1)
                {
                    nodeToAdd++;
                    leafNodes.Add(leafNodes.Last());
                }

                // start a new row
                nodeToAdd /= 2;
                newAdded = 0;
            }
        }

19 Source : GrpcServerTests.cs
with MIT License
from AElfProject

[Fact]
        public async Task RequestIndexingParentChain_SpecificResponse_Test()
        {
            var requestData = new CrossChainRequest
            {
                ChainId = ChainHelper.GetChainId(1),
                NextHeight = 81
            };

            var responseResults = new List<ParentChainBlockData>();
            IServerStreamWriter<ParentChainBlockData> responseStream = MockServerStreamWriter(responseResults); 
            var context = BuildServerCallContext();
            await ParentChainGrpcServerBase.RequestIndexingFromParentChain(requestData, responseStream, context);
            replacedert.Equal(20, responseResults.Count);
            replacedert.Equal(81, responseResults.First().Height);
            replacedert.Equal(100, responseResults.Last().Height);
        }

19 Source : PointDefinition.cs
with MIT License
from Aeroluna

public Vector3 Interpolate(float time)
        {
            if (_points == null || _points.Count == 0)
            {
                return Vector3.zero;
            }

            if (_points.First().Point.w >= time)
            {
                return _points.First().Point;
            }

            if (_points.Last().Point.w <= time)
            {
                return _points.Last().Point;
            }

            SearchIndex(time, PropertyType.Vector3, out int l, out int r);
            Vector4 pointL = _points[l].Point;
            Vector4 pointR = _points[r].Point;

            float normalTime;
            float divisor = pointR.w - pointL.w;
            if (divisor != 0)
            {
                normalTime = (time - pointL.w) / divisor;
            }
            else
            {
                normalTime = 0;
            }

            normalTime = Easings.Interpolate(normalTime, _points[r].Easing);
            if (_points[r].Smooth)
            {
                return SmoothVectorLerp(_points, l, r, normalTime);
            }
            else
            {
                return Vector3.LerpUnclamped(pointL, pointR, normalTime);
            }
        }

19 Source : PointDefinition.cs
with MIT License
from Aeroluna

public float InterpolateLinear(float time)
        {
            if (_points == null || _points.Count == 0)
            {
                return 0;
            }

            if (_points.First().LinearPoint.y >= time)
            {
                return _points.First().LinearPoint.x;
            }

            if (_points.Last().LinearPoint.y <= time)
            {
                return _points.Last().LinearPoint.x;
            }

            SearchIndex(time, PropertyType.Linear, out int l, out int r);
            Vector4 pointL = _points[l].LinearPoint;
            Vector4 pointR = _points[r].LinearPoint;

            float normalTime;
            float divisor = pointR.y - pointL.y;
            if (divisor != 0)
            {
                normalTime = (time - pointL.y) / divisor;
            }
            else
            {
                normalTime = 0;
            }

            normalTime = Easings.Interpolate(normalTime, _points[r].Easing);
            return Mathf.LerpUnclamped(pointL.x, pointR.x, normalTime);
        }

19 Source : PointDefinition.cs
with MIT License
from Aeroluna

public Quaternion InterpolateQuaternion(float time)
        {
            if (_points == null || _points.Count == 0)
            {
                return Quaternion.idenreplacedy;
            }

            if (_points.First().Point.w >= time)
            {
                return Quaternion.Euler(_points.First().Point);
            }

            if (_points.Last().Point.w <= time)
            {
                return Quaternion.Euler(_points.Last().Point);
            }

            SearchIndex(time, PropertyType.Quaternion, out int l, out int r);
            Vector4 pointL = _points[l].Point;
            Vector4 pointR = _points[r].Point;
            Quaternion quaternionOne = Quaternion.Euler(pointL);
            Quaternion quaternionTwo = Quaternion.Euler(pointR);

            float normalTime;
            float divisor = pointR.w - pointL.w;
            if (divisor != 0)
            {
                normalTime = (time - pointL.w) / divisor;
            }
            else
            {
                normalTime = 0;
            }

            normalTime = Easings.Interpolate(normalTime, _points[r].Easing);
            return Quaternion.SlerpUnclamped(quaternionOne, quaternionTwo, normalTime);
        }

19 Source : PointDefinition.cs
with MIT License
from Aeroluna

public Vector4 InterpolateVector4(float time)
        {
            if (_points == null || _points.Count == 0)
            {
                return Vector4.zero;
            }

            if (_points.First().Vector4Point.v >= time)
            {
                return _points.First().Vector4Point;
            }

            if (_points.Last().Vector4Point.v <= time)
            {
                return _points.Last().Vector4Point;
            }

            SearchIndex(time, PropertyType.Vector4, out int l, out int r);
            Vector5 pointL = _points[l].Vector4Point;
            Vector5 pointR = _points[r].Vector4Point;

            float normalTime;
            float divisor = pointR.v - pointL.v;
            if (divisor != 0)
            {
                normalTime = (time - pointL.v) / divisor;
            }
            else
            {
                normalTime = 0;
            }

            normalTime = Easings.Interpolate(normalTime, _points[r].Easing);
            return Vector4.LerpUnclamped(pointL, pointR, normalTime);
        }

19 Source : MetadataProvider.cs
with MIT License
from afaniuolo

private string GetFileName(string filePath)
		{
			var filename = filePath.Split('\\').Last();
			return filename;
		}

19 Source : ZeroDiscover.cs
with Mozilla Public License 2.0
from agebullhu

private void ReadEnreplacedy(TypeDoreplacedent typeDoreplacedent, Type type)
        {
            if (type == null || type.IsAutoClreplaced || !IsLetter(type.Name[0]) ||
                type.IsInterface || type.IsMarshalByRef || type.IsCOMObject ||
                type == typeof(object) || type == typeof(void) ||
                type == typeof(ValueType) || type == typeof(Type) || type == typeof(Enum) ||
                type.Namespace == "System" || type.Namespace?.Contains("System.") == true)
                return;
            if (typeDocs.TryGetValue(type, out var doc))
            {
                foreach (var field in doc.Fields)
                {
                    if (typeDoreplacedent.Fields.ContainsKey(field.Key))
                        typeDoreplacedent.Fields[field.Key] = field.Value;
                    else
                        typeDoreplacedent.Fields.Add(field.Key, field.Value);
                }
                return;
            }
            if (typeDocs2.TryGetValue(type, out var _))
            {
                ZeroTrace.WriteError("ReadEnreplacedy", "over flow", type.Name);

                return;
            }

            typeDocs2.Add(type, typeDoreplacedent);
            if (type.IsArray)
            {
                ReadEnreplacedy(typeDoreplacedent, type.replacedembly.GetType(type.FullName.Split('[')[0]));
                return;
            }
            if (type.IsGenericType && !type.IsValueType &&
                type.GetGenericTypeDefinition().GetInterface(typeof(IEnumerable<>).FullName) != null)
            {
                ReadEnreplacedy(typeDoreplacedent, type.GetGenericArguments().Last());
                return;
            }

            XmlMember.Find(type);
            if (type.IsEnum)
            {
                foreach (var field in type.GetFields(BindingFlags.Static | BindingFlags.Public))
                {
                    if (field.IsSpecialName)
                    {
                        continue;
                    }
                    var info = CheckMember(typeDoreplacedent, type, field, field.FieldType, false, false, false);
                    if (info != null)
                    {
                        info.TypeName = "int";
                        info.Example = ((int)field.GetValue(null)).ToString();
                        info.JsonName = null;
                    }
                }
                typeDocs.Add(type, new TypeDoreplacedent
                {
                    fields = typeDoreplacedent.fields?.ToDictionary(p => p.Key, p => p.Value)
                });
                typeDoreplacedent.Copy(XmlMember.Find(type));
                return;
            }

            var dc = type.GetAttribute<DataContractAttribute>();
            var jo = type.GetAttribute<JsonObjectAttribute>();

            foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
            {
                if (property.IsSpecialName)
                {
                    continue;
                }
                CheckMember(typeDoreplacedent, type, property, property.PropertyType, jo != null, dc != null);
            }
            foreach (var field in type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
            {
                if (!char.IsLetter(field.Name[0]) || field.IsSpecialName)
                {
                    continue;
                }
                CheckMember(typeDoreplacedent, type, field, field.FieldType, jo != null, dc != null);
            }

            typeDocs.Add(type, new TypeDoreplacedent
            {
                fields = typeDoreplacedent.fields?.ToDictionary(p => p.Key, p => p.Value)
            });
            typeDoreplacedent.Copy(XmlMember.Find(type));
        }

19 Source : Objects.cs
with MIT License
from agens-no

static string EscapeWithQuotesIfNeeded(string name, string value)
        {
            if (name != "LIBRARY_SEARCH_PATHS")
                return value;
            if (!value.Contains(" "))
                return value;
            if (value.First() == '\"' && value.Last() == '\"')
                return value;
            return "\"" + value + "\"";
        }

19 Source : LayoutDescriptionEx.cs
with GNU General Public License v3.0
from aglab2

public void Trim()
        {
            while (courseDescription.Count() != 0)
            {
                LineDescriptionEx lde = courseDescription.Last();

                if (lde == null || lde.IsEmpty())
                    courseDescription.RemoveAt(courseDescription.Count() - 1);
                else
                    break;
            }

            while (secretDescription.Count() != 0)
            {
                LineDescriptionEx lde = secretDescription.Last();

                if (lde == null || lde.IsEmpty())
                    secretDescription.RemoveAt(secretDescription.Count() - 1);
                else
                    break;
            }

            foreach (var ld in courseDescription)
            {
                if (ld is object)
                    ld.FixType();
            }
            foreach (var ld in secretDescription)
            {
                if (ld is object)
                    ld.FixType();
            }
        }

19 Source : RandomUrlHttpClient.cs
with Apache License 2.0
from agoda-com

private async Task<HttpResponseMessage> SendAsync(
            string url,
            Func<string, Task<HttpResponseMessage>> send)
        {
            var results = await SendAsyncWithDiag(url, send);
            var result = results.Last();
            if (result.IsError)
            {
                throw result.Exception;
            }
            return result.Result;
        }

19 Source : RrCompatibleHttpClient.cs
with Apache License 2.0
from agoda-com

public async Task<ExecuteResult> ExecuteAsync(
            HttpMethod verb,
            string url,
            string content,
            IReadOnlyDictionary<string, string> headers)
        {
            var results = await _httpClient.SendAsyncWithDiag(url, fullUrl =>
            {
                var msg = new HttpRequestMessage(verb, fullUrl);
                if (content != null)
                {
                    msg.Content = new StringContent(content, Encoding.UTF8, "application/json");
                }
                if (headers != null)
                {
                    foreach (var pair in headers)
                    {
                        msg.Headers.TryAddWithoutValidation(pair.Key, pair.Value);
                    }
                }
                return msg;
            });
            var prevResults = new List<ExecuteResult>();
            foreach (var msg in results)
            {
                prevResults.Add(await MsgToExecuteResult(msg, prevResults));
            }

            return prevResults.Last();
        }

19 Source : Cell.cs
with GNU General Public License v3.0
from AHeroicLlama

void InitializePlotData()
		{
			plots = DataHelper.GetAllCellCoords(formID);

			plots = plots.OrderBy(plot => plot.x).ToList();
			xMin = plots.First().x;
			xMax = plots.Last().x;

			plots = plots.OrderBy(plot => plot.y).ToList();
			yMin = plots.First().y;
			yMax = plots.Last().y;

			plots = plots.OrderBy(plot => plot.z).ToList();
			zMin = plots.First().z;
			zMax = plots.Last().z;

			heightRange = Math.Abs(zMax - zMin);
		}

19 Source : CommandsNextUtilities.cs
with MIT License
from Aiko-IT-Systems

internal static string CleanupString(this string s, IList<int> indices)
        {
            if (!indices.Any())
                return s;

            var li = indices.Last();
            var ll = 1;
            for (var x = indices.Count - 2; x >= 0; x--)
            {
                if (li - indices[x] == ll)
                {
                    ll++;
                    continue;
                }

                s = s.Remove(li - ll + 1, ll);
                li = indices[x];
                ll = 1;
            }

            return s.Remove(li - ll + 1, ll);
        }

19 Source : CsvAsyncInputTestBase.cs
with MIT License
from airbreather

protected async Task RunTestAsync(Func<CsvAsyncInputBase> sutCreator, string filePath, bool ignoreUTF8ByteOrderMark)
        {
            (byte[] fileData, int originalLength) = GetExpectedCsvData(filePath, ignoreUTF8ByteOrderMark);
            var expected = TokenizeCsvFileUsingCursively(fileData, fileData.Length, (byte)',');

            // run without progress
            {
                var sut = sutCreator();
                var inputVisitor = new StringBufferingVisitor();

                await sut.ProcessAsync(inputVisitor).ConfigureAwait(false);

                replacedert.Equal(expected, inputVisitor.Records);

                await replacedert.ThrowsAsync<InvalidOperationException>(() => sut.ProcessAsync(null).AsTask());
            }

            // run with progress
            {
                var sut = sutCreator();
                var inputVisitor = new StringBufferingVisitor();

                var readSoFar = new List<int>();
                var progress = new ImmediateProgress<int>(readSoFar.Add);

                await sut.ProcessAsync(inputVisitor, progress).ConfigureAwait(false);

                replacedert.Equal(expected, inputVisitor.Records);

                replacedert.Equal(originalLength, readSoFar.Sum());
                replacedert.Equal(0, readSoFar.Last());

                await replacedert.ThrowsAsync<InvalidOperationException>(() => sut.ProcessAsync(null).AsTask());
            }
        }

19 Source : MongoDBFileStore.cs
with MIT License
from aishang2015

public async Task<bool> TryCreateDirectoryAsync(string path)
        {
            var fileEnreplacedy = await GetFileEnreplacedyByPath(path);
            if (fileEnreplacedy == null)
            {
                var directoryPathArray = path.Split('/', StringSplitOptions.RemoveEmptyEntries);
                var newArray = directoryPathArray.Take(directoryPathArray.Length - 1);
                var fileinfo = new MongoDBFileStoreEntry
                {
                    Path = path.TrimEnd('/'),
                    DirectoryPath = '/' + string.Join('/', newArray).TrimEnd('/'),
                    Name = directoryPathArray.Last(),
                    LastModifiedUtc = DateTime.Now,
                    IsDirectory = true
                };
                await _mongoRepository.AddAsync(fileinfo);
            }
            return true;
        }

19 Source : FolderSplitter.cs
with MIT License
from AiursoftWeb

public (string[] folders, string fileName) SplitToFoldersAndFile(string folderNames)
        {
            if (folderNames == null || folderNames.Length == 0)
            {
                throw new AiurAPIModelException(ErrorType.NotFound, "The root folder isn't a file!");
            }
            var foldersWithFileName = SplitToFolders(folderNames);
            var fileName = foldersWithFileName.Last();
            var folders = foldersWithFileName.Take(foldersWithFileName.Count() - 1).ToArray();
            return (folders, fileName);
        }

19 Source : MongoDBFileStore.cs
with MIT License
from aishang2015

public async Task CopyFileAsync(string srcPath, string dstPath)
        {
            var fileEnreplacedy = await GetFileEnreplacedyByPath(srcPath);
            try
            {
                // 取得流=>取得新文件名=>保存新文件=>取得新文件信息=>保存新文件信息
                var stream = await _mongoRepository.GetFileStreamAsync(fileEnreplacedy._id);
                var newFileName = dstPath.Split('/').Last();
                var newid = await _mongoRepository.UploadFileAsync(newFileName, stream);
                var fileinfo = await _mongoRepository.GetFileByIdAsync(newid);
                await _mongoRepository.AddAsync(new MongoDBFileStoreEntry(fileinfo, dstPath));
            }
            catch (Exception e)
            {
                _logger.LogError(e.StackTrace);
            }
        }

19 Source : MongoDBFileStore.cs
with MIT License
from aishang2015

public async Task<string> CreateFileFromStreamAsync(string path, Stream inputStream, bool overwrite = false)
        {
            var fileName = path.Split('/').Last();
            try
            {
                // 保存文件=>取得文件信息=>保存文件信息
                var fileStoreId = await _mongoRepository.UploadFileAsync(fileName, inputStream);
                var fileinfo = await _mongoRepository.GetFileByIdAsync(fileStoreId);
                await _mongoRepository.AddAsync(new MongoDBFileStoreEntry(fileinfo, path));
            }
            catch (Exception e)
            {
                _logger.LogError(e.StackTrace);
                return null;
            }
            return path;
        }

19 Source : MongoDBFileStore.cs
with MIT License
from aishang2015

public async Task MoveFileAsync(string oldPath, string newPath)
        {
            var fileEnreplacedy = await GetFileEnreplacedyByPath(oldPath);
            try
            {
                // 取得流=>取得新文件名=>保存新文件=>删除旧文件=>取得新文件信息=>更新文件信息
                var stream = await _mongoRepository.GetFileStreamAsync(fileEnreplacedy._id);
                var newFileName = newPath.Split('/').Last();
                var newid = await _mongoRepository.UploadFileAsync(newFileName, stream);
                await _mongoRepository.DeleteFileAsync(fileEnreplacedy.FileStoreId);

                var fileinfo = await _mongoRepository.GetFileByIdAsync(newid);
                fileEnreplacedy.Path = newPath;
                fileEnreplacedy.Name = fileinfo.Filename;
                fileEnreplacedy.DirectoryPath = newPath.Substring(0, newPath.Length - fileinfo.Filename.Length)
                    .TrimEnd('/');
                fileEnreplacedy.FileStoreId = fileinfo.Id.ToString();
                fileEnreplacedy.LastModifiedUtc = fileinfo.UploadDateTime;

                await _mongoRepository.UpdateAsync(fileEnreplacedy);
            }
            catch (Exception e)
            {
                _logger.LogError(e.StackTrace);
            }
        }

19 Source : ProbeLocator.cs
with MIT License
from AiursoftWeb

private (string siteName, string[] folders, string fileName) SplitToPath(string fullPath)
        {
            if (fullPath == null || fullPath.Length == 0)
            {
                throw new AiurAPIModelException(ErrorType.NotFound, $"Can't get your file download address from path: '{fullPath}'!");
            }
            var paths = SplitStrings(fullPath);
            var fileName = paths.Last();
            var siteName = paths.First();
            var folders = paths.Take(paths.Count() - 1).Skip(1).ToArray();
            return (siteName, folders, fileName);
        }

19 Source : StringOperation.cs
with MIT License
from AiursoftWeb

public static string DetachPath(this string path)
        {
            if (path == null || !path.Contains("/"))
            {
                return null;
            }
            return path.Replace("/" + path.Split('/').Last(), "");
        }

19 Source : DBEntryUnitAircraftData.cs
with GNU General Public License v3.0
from akaAgar

internal void Merge(DBEntryUnitAircraftData aircraftData)
        {
            Liveries = Liveries.Union(aircraftData.Liveries).ToList();
            PayloadTasks = PayloadTasks
                .Union(aircraftData.PayloadTasks)
                .GroupBy(g => g.Key)
                .ToDictionary(pair => pair.Key, pair => pair.Last().Value);
        }

19 Source : ReleaseExtractor.cs
with MIT License
from AkiniKites

private bool IsDir(string path)
        {
            if (path == null)
                return false;

            return path.Last() == Path.DirectorySeparatorChar ||
                path.Last() == Path.AltDirectorySeparatorChar;
        }

19 Source : RealExplosion.cs
with MIT License
from Alan-FGR

public Dictionary<Fixture, Vector2> Activate(Vector2 pos, float radius, float maxForce)
        {
            AABB aabb;
            aabb.LowerBound = pos + new Vector2(-radius, -radius);
            aabb.UpperBound = pos + new Vector2(radius, radius);
            Fixture[] shapes = new Fixture[MaxShapes];

            // More than 5 shapes in an explosion could be possible, but still strange.
            Fixture[] containedShapes = new Fixture[5];
            bool exit = false;

            int shapeCount = 0;
            int containedShapeCount = 0;

            // Query the world for overlapping shapes.
            World.QueryAABB(
                fixture =>
                {
                    if (fixture.TestPoint(ref pos))
                    {
                        if (IgnoreWhenInsideShape)
                        {
                            exit = true;
                            return false;
                        }

                        containedShapes[containedShapeCount++] = fixture;
                    }
                    else
                    {
                        shapes[shapeCount++] = fixture;
                    }

                    // Continue the query.
                    return true;
                }, ref aabb);

            if (exit)
                return new Dictionary<Fixture, Vector2>();

            Dictionary<Fixture, Vector2> exploded = new Dictionary<Fixture, Vector2>(shapeCount + containedShapeCount);

            // Per shape max/min angles for now.
            float[] vals = new float[shapeCount * 2];
            int valIndex = 0;
            for (int i = 0; i < shapeCount; ++i)
            {
                PolygonShape ps;
                CircleShape cs = shapes[i].Shape as CircleShape;
                if (cs != null)
                {
                    // We create a "diamond" approximation of the circle
                    Vertices v = new Vertices();
                    Vector2 vec = Vector2.Zero + new Vector2(cs.Radius, 0);
                    v.Add(vec);
                    vec = Vector2.Zero + new Vector2(0, cs.Radius);
                    v.Add(vec);
                    vec = Vector2.Zero + new Vector2(-cs.Radius, cs.Radius);
                    v.Add(vec);
                    vec = Vector2.Zero + new Vector2(0, -cs.Radius);
                    v.Add(vec);
                    ps = new PolygonShape(v, 0);
                }
                else
                    ps = shapes[i].Shape as PolygonShape;

                if ((shapes[i].Body.BodyType == BodyType.Dynamic) && ps != null)
                {
                    Vector2 toCentroid = shapes[i].Body.GetWorldPoint(ps.MreplacedData.Centroid) - pos;
                    float angleToCentroid = (float)Math.Atan2(toCentroid.Y, toCentroid.X);
                    float min = float.MaxValue;
                    float max = float.MinValue;
                    float minAbsolute = 0.0f;
                    float maxAbsolute = 0.0f;

                    for (int j = 0; j < ps.Vertices.Count; ++j)
                    {
                        Vector2 toVertex = (shapes[i].Body.GetWorldPoint(ps.Vertices[j]) - pos);
                        float newAngle = (float)Math.Atan2(toVertex.Y, toVertex.X);
                        float diff = (newAngle - angleToCentroid);

                        diff = (diff - MathHelper.Pi) % (2 * MathHelper.Pi);
                        // the minus pi is important. It means cutoff for going other direction is at 180 deg where it needs to be

                        if (diff < 0.0f)
                            diff += 2 * MathHelper.Pi; // correction for not handling negs

                        diff -= MathHelper.Pi;

                        if (Math.Abs(diff) > MathHelper.Pi)
                            continue; // Something's wrong, point not in shape but exists angle diff > 180

                        if (diff > max)
                        {
                            max = diff;
                            maxAbsolute = newAngle;
                        }
                        if (diff < min)
                        {
                            min = diff;
                            minAbsolute = newAngle;
                        }
                    }

                    vals[valIndex] = minAbsolute;
                    ++valIndex;
                    vals[valIndex] = maxAbsolute;
                    ++valIndex;
                }
            }

            Array.Sort(vals, 0, valIndex, _rdc);
            _data.Clear();
            bool rayMissed = true;

            for (int i = 0; i < valIndex; ++i)
            {
                Fixture fixture = null;
                float midpt;

                int iplus = (i == valIndex - 1 ? 0 : i + 1);
                if (vals[i] == vals[iplus])
                    continue;

                if (i == valIndex - 1)
                {
                    // the single edgecase
                    midpt = (vals[0] + MathHelper.Pi * 2 + vals[i]);
                }
                else
                {
                    midpt = (vals[i + 1] + vals[i]);
                }

                midpt = midpt / 2;

                Vector2 p1 = pos;
                Vector2 p2 = radius * new Vector2((float)Math.Cos(midpt), (float)Math.Sin(midpt)) + pos;

                // RaycastOne
                bool hitClosest = false;
                World.RayCast((f, p, n, fr) =>
                                  {
                                      Body body = f.Body;

                                      if (!IsActiveOn(body))
                                          return 0;

                                      hitClosest = true;
                                      fixture = f;
                                      return fr;
                                  }, p1, p2);

                //draws radius points
                if ((hitClosest) && (fixture.Body.BodyType == BodyType.Dynamic))
                {
                    if ((_data.Any()) && (_data.Last().Body == fixture.Body) && (!rayMissed))
                    {
                        int laPos = _data.Count - 1;
                        ShapeData la = _data[laPos];
                        la.Max = vals[iplus];
                        _data[laPos] = la;
                    }
                    else
                    {
                        // make new
                        ShapeData d;
                        d.Body = fixture.Body;
                        d.Min = vals[i];
                        d.Max = vals[iplus];
                        _data.Add(d);
                    }

                    if ((_data.Count > 1)
                        && (i == valIndex - 1)
                        && (_data.Last().Body == _data.First().Body)
                        && (_data.Last().Max == _data.First().Min))
                    {
                        ShapeData fi = _data[0];
                        fi.Min = _data.Last().Min;
                        _data.RemoveAt(_data.Count - 1);
                        _data[0] = fi;
                        while (_data.First().Min >= _data.First().Max)
                        {
                            fi.Min -= MathHelper.Pi * 2;
                            _data[0] = fi;
                        }
                    }

                    int lastPos = _data.Count - 1;
                    ShapeData last = _data[lastPos];
                    while ((_data.Count > 0)
                           && (_data.Last().Min >= _data.Last().Max)) // just making sure min<max
                    {
                        last.Min = _data.Last().Min - 2 * MathHelper.Pi;
                        _data[lastPos] = last;
                    }
                    rayMissed = false;
                }
                else
                {
                    rayMissed = true; // raycast did not find a shape
                }
            }

            for (int i = 0; i < _data.Count; ++i)
            {
                if (!IsActiveOn(_data[i].Body))
                    continue;

                float arclen = _data[i].Max - _data[i].Min;

                float first = MathHelper.Min(MaxEdgeOffset, EdgeRatio * arclen);
                int insertedRays = (int)Math.Ceiling(((arclen - 2.0f * first) - (MinRays - 1) * MaxAngle) / MaxAngle);

                if (insertedRays < 0)
                    insertedRays = 0;

                float offset = (arclen - first * 2.0f) / ((float)MinRays + insertedRays - 1);

                //Note: This loop can go into infinite as it operates on floats.
                //Added FloatEquals with a large epsilon.
                for (float j = _data[i].Min + first;
                     j < _data[i].Max || MathUtils.FloatEquals(j, _data[i].Max, 0.0001f);
                     j += offset)
                {
                    Vector2 p1 = pos;
                    Vector2 p2 = pos + radius * new Vector2((float)Math.Cos(j), (float)Math.Sin(j));
                    Vector2 hitpoint = Vector2.Zero;
                    float minlambda = float.MaxValue;

                    List<Fixture> fl = _data[i].Body.FixtureList;
                    for (int x = 0; x < fl.Count; x++)
                    {
                        Fixture f = fl[x];
                        RayCastInput ri;
                        ri.Point1 = p1;
                        ri.Point2 = p2;
                        ri.MaxFraction = 50f;

                        RayCastOutput ro;
                        if (f.RayCast(out ro, ref ri, 0))
                        {
                            if (minlambda > ro.Fraction)
                            {
                                minlambda = ro.Fraction;
                                hitpoint = ro.Fraction * p2 + (1 - ro.Fraction) * p1;
                            }
                        }

                        // the force that is to be applied for this particular ray.
                        // offset is angular coverage. lambda*length of segment is distance.
                        float impulse = (arclen / (MinRays + insertedRays)) * maxForce * 180.0f / MathHelper.Pi * (1.0f - Math.Min(1.0f, minlambda));

                        // We Apply the impulse!!!
                        Vector2 vectImp = Vector2.Dot(impulse * new Vector2((float)Math.Cos(j), (float)Math.Sin(j)), -ro.Normal) * new Vector2((float)Math.Cos(j), (float)Math.Sin(j));
                        _data[i].Body.ApplyLinearImpulse(ref vectImp, ref hitpoint);

                        // We gather the fixtures for returning them
                        if (exploded.ContainsKey(f))
                            exploded[f] += vectImp;
                        else
                            exploded.Add(f, vectImp);

                        if (minlambda > 1.0f)
                            hitpoint = p2;
                    }
                }
            }

            // We check contained shapes
            for (int i = 0; i < containedShapeCount; ++i)
            {
                Fixture fix = containedShapes[i];

                if (!IsActiveOn(fix.Body))
                    continue;

                float impulse = MinRays * maxForce * 180.0f / MathHelper.Pi;
                Vector2 hitPoint;

                CircleShape circShape = fix.Shape as CircleShape;
                if (circShape != null)
                {
                    hitPoint = fix.Body.GetWorldPoint(circShape.Position);
                }
                else
                {
                    PolygonShape shape = fix.Shape as PolygonShape;
                    hitPoint = fix.Body.GetWorldPoint(shape.MreplacedData.Centroid);
                }

                Vector2 vectImp = impulse * (hitPoint - pos);

                fix.Body.ApplyLinearImpulse(ref vectImp, ref hitPoint);

                if (!exploded.ContainsKey(fix))
                    exploded.Add(fix, vectImp);
            }

            return exploded;
        }

19 Source : Program.cs
with MIT License
from Alan-FGR

public static string FormatSignature(string declStr, int genQty)
    {
        var func = new GenericFormatter();
        var parameters = new List<GenericFormatter>();

        var split = declStr.Split('(');
        var pars = split.Last().Split(')').First().Split(',');

        var split2 = split.First().Split('<');

        func.preText = split2.First();
        func.postText = "";

        func.generics = split2.Last().Split('>').First().Split(',').ToList();

        foreach (string par in pars)
        {
            if (par.Contains('<'))
            {
                var nam = par.Split('<').First();
                var pgens = par.Split('<').Last().Split('>').First().Split(',').ToList();
                var e = par.Split('<').Last().Split('>').Last();
                parameters.Add(new GenericFormatter(nam, e, pgens));
            }
            else
            {
                parameters.Add(new GenericFormatter(par, "", null));
                //if parameter is a generic (todo get generic parameters) repeat for qty
                if (par.Split(' ').Any(x => x == "T0"))
                {
                    for (int i = 1; i < genQty; i++)
                    {
                        parameters.Add(new GenericFormatter(Utils.IncrementGeneric(par, i), "", null));
                    }
                }
            }
        }

        return $"{func.Format(genQty)}({string.Join(", ",parameters.Select(x=>x.Format(genQty)))})";
    }

See More Examples