System.Collections.Generic.IEnumerable.ElementAt(int)

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

2213 Examples 7

19 View Source File : GeneratorClass.cs
License : MIT License
Project Creator : 188867052

public static string GenerateRoutes(IEnumerable<RouteInfo> infos)
        {
            StringBuilder sb = new StringBuilder();
            var group = infos.GroupBy(o => o.Namespace);
            sb.AppendLine($"using {typeof(object).Namespace};");
            sb.AppendLine($"using {typeof(Dictionary<int, int>).Namespace};");

            sb.AppendLine();
            for (int i = 0; i < group.Count(); i++)
            {
                sb.Append(GenerateNamespace(group.ElementAt(i), i == (group.Count() - 1)));
            }

            return sb.ToString();
        }

19 View Source File : GeneratorClass.cs
License : MIT License
Project Creator : 188867052

private static StringBuilder GenerateNamespace(IGrouping<string, RouteInfo> namespaceGroup, bool isLast)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine($"namespace {GetConvertedNamespace(namespaceGroup.Key)}");
            sb.AppendLine("{");

            var group = namespaceGroup.GroupBy(o => o.ControllerName);
            for (int i = 0; i < group.Count(); i++)
            {
                sb.Append(GenerateClreplaced(group.ElementAt(i), i == (group.Count() - 1)));
            }

            sb.AppendLine("}");
            if (!isLast)
            {
                sb.AppendLine();
            }

            return sb;
        }

19 View Source File : GeneratorClass.cs
License : MIT License
Project Creator : 188867052

private static StringBuilder GenerateClreplaced(IGrouping<string, RouteInfo> group, bool isLast)
        {
            string clreplacedFullName = $"{group.First().Namespace}.{group.First().ControllerName}Controller";
            string crefNamespace = GetCrefNamespace(clreplacedFullName, GetConvertedNamespace(group.First().Namespace));
            StringBuilder sb = new StringBuilder();
            sb.AppendLine($"    /// <summary>");
            sb.AppendLine($"    /// <see cref=\"{crefNamespace}\"/>");
            sb.AppendLine($"    /// </summary>");
            sb.AppendLine($"    public clreplaced {group.Key}Route");
            sb.AppendLine("    {");
            for (int i = 0; i < group.Count(); i++)
            {
                var item = group.ElementAt(i);
                var renamedAction = RenameOverloadedAction(group, i);
                sb.AppendLine("        /// <summary>");
                sb.AppendLine($"        /// <see cref=\"{crefNamespace}.{item.ActionName}\"/>");
                sb.AppendLine("        /// </summary>");
                sb.AppendLine($"        public const string {renamedAction} = \"{item.Path}\";");

                if (i != group.Count() - 1)
                {
                    sb.AppendLine();
                }
            }

            sb.AppendLine("    }");
            if (!isLast)
            {
                sb.AppendLine();
            }

            return sb;
        }

19 View Source File : GeneratorClass.cs
License : MIT License
Project Creator : 188867052

private static string RenameOverloadedAction(IGrouping<string, RouteInfo> group, int index)
        {
            var currenreplacedem = group.ElementAt(index);
            var sameActionNameGroup = group.GroupBy(o => o.ActionName);
            foreach (var item in sameActionNameGroup)
            {
                if (item.Count() > 1)
                {
                    for (int i = 1; i < item.Count(); i++)
                    {
                        var element = item.ElementAt(i);
                        if (element == currenreplacedem)
                        {
                            return element.ActionName + i;
                        }
                    }
                }
            }

            return currenreplacedem.ActionName;
        }

19 View Source File : RouteGenerator.cs
License : MIT License
Project Creator : 188867052

private static StringBuilder GenerateClreplaced(IGrouping<string, RouteInfo> group, bool isLast)
        {
            string clreplacedFullName = $"{group.First().Namespace}.{group.First().ControllerName}Controller";
            string crefNamespace = GetCrefNamespace(clreplacedFullName, GetConvertedNamespace(group.First().Namespace));
            StringBuilder sb = new StringBuilder();
            sb.AppendLine($"    /// <summary>");
            sb.AppendLine($"    /// <see cref=\"{crefNamespace}\"/>");
            sb.AppendLine($"    /// </summary>");
            sb.AppendLine($"    public clreplaced {group.Key}Route");
            sb.AppendLine("    {");
            for (int i = 0; i < group.Count(); i++)
            {
                var item = group.ElementAt(i);
                var renamedAction = RenameOverloadedAction(group, i);
                sb.AppendLine("        /// <summary>");
                sb.AppendLine($"        /// <see cref=\"{crefNamespace}.{item.ActionName}\"/>");
                sb.AppendLine("        /// </summary>");
                sb.AppendLine($"        public const string {renamedAction} = \"{item.Path}\";");

                if (config != null && config.GenerateMethod)
                {
                    sb.AppendLine($"        public static async Task<T> {item.ActionName}Async<T>({GeneraParameters(item.Parameters, true, false)})");
                    sb.AppendLine("        {");
                    sb.AppendLine($"            var routeInfo = new {nameof(RouteInfo)}");
                    sb.AppendLine("            {");
                    sb.AppendLine($"                {nameof(RouteInfo.HttpMethods)} = \"{item.HttpMethods}\",");
                    sb.AppendLine($"                {nameof(RouteInfo.Path)} = {renamedAction},");
                    sb.Append(GenerateParameters(item.Parameters));
                    sb.AppendLine("            };");
                    sb.AppendLine($"            return await {nameof(HttpClientAsync)}.{nameof(HttpClientAsync.Async)}<T>(routeInfo{GeneraParameters(item.Parameters, false, true)});");
                    sb.AppendLine("        }");
                }

                if (i != group.Count() - 1)
                {
                    sb.AppendLine();
                }
            }

            sb.AppendLine("    }");
            if (!isLast)
            {
                sb.AppendLine();
            }

            return sb;
        }

19 View Source File : HttpClientAsync.cs
License : MIT License
Project Creator : 188867052

private static void PrepareConstraintParameters(out string constraintUrl, out IList<string> constraintNameList, RouteInfo routeInfo, params object[] data)
        {
            var endpoint = CreateEndpoint(routeInfo.Path, routeName: routeInfo.Path);
            constraintNameList = endpoint.RoutePattern.Parameters.Select(o => o.Name).ToList();
            var urlHelper = CreateUrlHelper(new[] { endpoint });

            // Set the endpoint feature and current context just as a normal request to MVC app would be
            var endpointFeature = new EndpointSelectorContext();
            urlHelper.ActionContext.HttpContext.Features.Set<IEndpointFeature>(endpointFeature);
            urlHelper.ActionContext.HttpContext.Features.Set<IRouteValuesFeature>(endpointFeature);
            endpointFeature.Endpoint = endpoint;
            endpointFeature.RouteValues = new RouteValueDictionary();
            foreach (var item in routeInfo.Parameters)
            {
                int dataIndex = routeInfo.Parameters.IndexOf(item);
                object value = data.ElementAt(dataIndex);
                endpointFeature.RouteValues.TryAdd(item.Name, value);
            }

            constraintUrl = urlHelper.RouteUrl(routeName: routeInfo.Path, values: endpointFeature.RouteValues);
        }

19 View Source File : RouteGenerator.cs
License : MIT License
Project Creator : 188867052

public static string GenerateRoutes(IList<RouteInfo> infos)
        {
            StringBuilder sb = new StringBuilder();
            var group = infos.GroupBy(o => o.Namespace);
            sb.AppendLine($"using {typeof(object).Namespace};");
            sb.AppendLine($"using {typeof(Dictionary<int, int>).Namespace};");
            sb.AppendLine($"using {typeof(Task).Namespace};");
            sb.AppendLine($"using {typeof(HttpClientAsync).Namespace};");

            sb.AppendLine();
            for (int i = 0; i < group.Count(); i++)
            {
                sb.Append(GenerateNamespace(group.ElementAt(i), i == (group.Count() - 1)));
            }

            return sb.ToString();
        }

19 View Source File : PackagesConfigLocatorTest.cs
License : MIT License
Project Creator : 3F

[Theory]
        [InlineData(TestData.ROOT + @"PackagesConfig\sln\1\test.sln", SlnItems.PackagesConfig)]
        [InlineData(TestData.ROOT + @"PackagesConfig\sln\2\test.sln", SlnItems.PackagesConfig)]
        [InlineData(TestData.ROOT + @"PackagesConfig\sln\3\test.sln", SlnItems.PackagesConfig)]
        [InlineData(TestData.ROOT + @"PackagesConfig\sln\4\test.sln", SlnItems.PackagesConfig)]

        [InlineData(TestData.ROOT + @"PackagesConfig\sln\1\test.sln", SlnItems.PackagesConfigSolution)]
        [InlineData(TestData.ROOT + @"PackagesConfig\sln\2\test.sln", SlnItems.PackagesConfigSolution)]
        [InlineData(TestData.ROOT + @"PackagesConfig\sln\3\test.sln", SlnItems.PackagesConfigSolution)]
        [InlineData(TestData.ROOT + @"PackagesConfig\sln\4\test.sln", SlnItems.PackagesConfigSolution)]

        [InlineData(TestData.ROOT + @"PackagesConfig\sln\1\test.sln", SlnItems.PackagesConfigLegacy)]
        [InlineData(TestData.ROOT + @"PackagesConfig\sln\2\test.sln", SlnItems.PackagesConfigLegacy)]
        [InlineData(TestData.ROOT + @"PackagesConfig\sln\3\test.sln", SlnItems.PackagesConfigLegacy)]
        [InlineData(TestData.ROOT + @"PackagesConfig\sln\4\test.sln", SlnItems.PackagesConfigLegacy)]
        public void FindTest1(string file, SlnItems items)
        {
            using Sln sln = new(file, items);
            IEnumerable<string> pkgs = PackagesConfigLocator.FindConfigs(sln.Result, sln.Result.ResultType);

            replacedert.Equal(sln.Result.PackagesConfigs.Count(), pkgs.Count());

            int idx = 0;
            foreach(var config in sln.Result.PackagesConfigs)
            {
                replacedert.Equal(config.File, pkgs.ElementAt(idx++));
            }
        }

19 View Source File : CheckCreateFile.cs
License : MIT License
Project Creator : 3RD-Dimension

public static void CheckAndUpdateXMLFile(int CurrentKeyFileVersion)
        {
            MainWindow.Logger.Info($"Updating HotkeyXML File. Current File Version {CurrentKeyFileVersion}, Update to File Version {HotKeyFileVer}");
            // Define new Hotkey fields - This changes every program update if needed   
            var UpdateHotkey = XDoreplacedent.Load(HotKeyFile);

            // NOTES | Sample Code for Add, Add at position, Rename:
            // Add to end of file: xDoc.Root.Add(new XElement("bind", new XAttribute("key_description", "Jog Distance Increase"), new XAttribute("keyfunction", "JDistInc"), new XAttribute("keycode", "")));
            // Add to specific Location: xDoc.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Distance Increase"), new XAttribute("keyfunction", "JDistInc"), new XAttribute("keycode", "")));
            // Rename Hotkey Data
            //var hotKeyRename1 = xDoc.Descendants("bind").Where(arg => arg.Attribute("key_description").Value == "Feed Rate Increase").Single();
            //hotKeyRename1.Attribute("key_description").Value = "Feed Rate Increase X";

            // START FILE MANIPULATION
            // Insert at specific Location - Reverse Order - Bottom will be inserted at the top
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Distance Decrease Z"), new XAttribute("keyfunction", "JDistDecZ"), new XAttribute("keycode", "")));
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Distance Increase Z"), new XAttribute("keyfunction", "JDistIncZ"), new XAttribute("keycode", "")));
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Distance Decrease Y"), new XAttribute("keyfunction", "JDistDecY"), new XAttribute("keycode", "")));
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Distance Increase Y"), new XAttribute("keyfunction", "JDistIncY"), new XAttribute("keycode", "")));
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Distance Decrease X"), new XAttribute("keyfunction", "JDistDecX"), new XAttribute("keycode", "")));
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Distance Increase X"), new XAttribute("keyfunction", "JDistIncX"), new XAttribute("keycode", "")));
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Rate Decrease Z"), new XAttribute("keyfunction", "JRateDecZ"), new XAttribute("keycode", "")));
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Rate Increase Z"), new XAttribute("keyfunction", "JRateIncZ"), new XAttribute("keycode", "")));
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Rate Decrease Y"), new XAttribute("keyfunction", "JRateDecY"), new XAttribute("keycode", "")));
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Rate Increase Y"), new XAttribute("keyfunction", "JRateIncY"), new XAttribute("keycode", "")));

            // Change Hotkey Desciptions and Keyfunction Name
            var hotKeyRename1 = UpdateHotkey.Descendants("bind").Where(arg => arg.Attribute("keyfunction").Value == "JRateInc").Single();
            var hotKeyRename2 = UpdateHotkey.Descendants("bind").Where(arg => arg.Attribute("keyfunction").Value == "JRateDec").Single();
            hotKeyRename1.Attribute("key_description").Value = "Jog Rate Increase X";
            hotKeyRename1.Attribute("keyfunction").Value = "JRateIncX";
            hotKeyRename2.Attribute("key_description").Value = "Jog Rate Decrease X";
            hotKeyRename2.Attribute("keyfunction").Value = "JRateDecX";

            // END FILE MANIPULATION
            UpdateHotkey.Root.Attribute("HotkeyFileVer").Value = HotKeyFileVer.ToString(); // Change HotkeyFileVer to current version

            //And save the XML file
            UpdateHotkey.Save(HotKeyFile);

            // Re-load Hotkeys
            HotKeys.LoadHotKeys();
        }

19 View Source File : PackagesConfigLocatorTest.cs
License : MIT License
Project Creator : 3F

[Theory]
        [InlineData(TestData.ROOT + @"PackagesConfig\sln\1\test.sln", SlnItems.PackagesConfig)]
        [InlineData(TestData.ROOT + @"PackagesConfig\sln\2\test.sln", SlnItems.PackagesConfig)]
        [InlineData(TestData.ROOT + @"PackagesConfig\sln\3\test.sln", SlnItems.PackagesConfig)]
        [InlineData(TestData.ROOT + @"PackagesConfig\sln\4\test.sln", SlnItems.PackagesConfig)]

        [InlineData(TestData.ROOT + @"PackagesConfig\sln\1\test.sln", SlnItems.PackagesConfigSolution)]
        [InlineData(TestData.ROOT + @"PackagesConfig\sln\2\test.sln", SlnItems.PackagesConfigSolution)]
        [InlineData(TestData.ROOT + @"PackagesConfig\sln\3\test.sln", SlnItems.PackagesConfigSolution)]
        [InlineData(TestData.ROOT + @"PackagesConfig\sln\4\test.sln", SlnItems.PackagesConfigSolution)]

        [InlineData(TestData.ROOT + @"PackagesConfig\sln\1\test.sln", SlnItems.PackagesConfigLegacy)]
        [InlineData(TestData.ROOT + @"PackagesConfig\sln\2\test.sln", SlnItems.PackagesConfigLegacy)]
        [InlineData(TestData.ROOT + @"PackagesConfig\sln\3\test.sln", SlnItems.PackagesConfigLegacy)]
        [InlineData(TestData.ROOT + @"PackagesConfig\sln\4\test.sln", SlnItems.PackagesConfigLegacy)]
        public void FindAndLoadTest1(string file, SlnItems items)
        {
            using Sln sln = new(file, items);
            IEnumerable<PackagesConfig> pkgs = PackagesConfigLocator.FindAndLoadConfigs(sln.Result, sln.Result.ResultType);

            replacedert.Equal(sln.Result.PackagesConfigs.Count(), pkgs.Count());

            int idx = 0;
            foreach(var config in sln.Result.PackagesConfigs)
            {
                replacedert.Equal(config.Packages, pkgs.ElementAt(idx++).Packages);
            }
        }

19 View Source File : SimpleJSON.cs
License : MIT License
Project Creator : 71

public override JSONNode Remove(int aIndex)
        {
            if (aIndex < 0 || aIndex >= m_Dict.Count)
                return null;
            var item = m_Dict.ElementAt(aIndex);
            m_Dict.Remove(item.Key);
            return item.Value;
        }

19 View Source File : EnumMethods.cs
License : MIT License
Project Creator : 8T4

[ExcludeFromCodeCoverage]
        public static string GetDescription(this Enum genericEnum)
        {
            var genericEnumType = genericEnum.GetType();
            var memberInfo = genericEnumType.GetMember(genericEnum.ToString());

            if (memberInfo.Length <= 0)
            {
                return genericEnum.ToString();
            }

            var attribs = memberInfo[0].GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
            
            return attribs.Any() 
                ? ((System.ComponentModel.DescriptionAttribute)attribs.ElementAt(0)).Description 
                : genericEnum.ToString();
        }

19 View Source File : AccelChartData.cs
License : MIT License
Project Creator : a1xd

public (double, double, double) FindPointValuesFromOut(double outVelocityValue)
        {
            if (OutVelocityToPoints.TryGetValue(outVelocityValue, out var values))
            {
                return values;
            }
            else
            {
                var velIdx = GetVelocityIndex(outVelocityValue);

                values = (VelocityPoints.ElementAt(velIdx).Key, AccelPoints.ElementAt(velIdx).Value, GainPoints.ElementAt(velIdx).Value);
                OutVelocityToPoints.Add(outVelocityValue, values);
                return values;
            }
        }

19 View Source File : AccelChartData.cs
License : MIT License
Project Creator : a1xd

public (double, double, double) ValuesAtIndex(int index)
        {
            return (AccelPoints.ElementAt(index).Value, VelocityPoints.ElementAt(index).Value, GainPoints.ElementAt(index).Value);
        }

19 View Source File : LUTPanelOptions.cs
License : MIT License
Project Creator : a1xd

public void SetActiveValues(IEnumerable<float> rawData, int length, AccelMode mode)
        {
            if (mode == AccelMode.lut && length > 1 && rawData.First() != 0)
            {
                var pointsLen = length / 2;
                var points = new Vec2<float>[pointsLen];
                for (int i = 0; i < pointsLen; i++)
                {
                    var data_idx = i * 2;
                    points[i] = new Vec2<float>
                    {
                        x = rawData.ElementAt(data_idx),
                        y = rawData.ElementAt(data_idx + 1)
                    };
                }
                ActiveValuesTextBox.Text = PointsToActiveValuesText(points, pointsLen);

                if (string.IsNullOrWhiteSpace(PointsTextBox.Text))
                {
                    PointsTextBox.Text = PointsToEntryTextBoxText(points, pointsLen);
                }
            }
            else
            {
                ActiveValuesTextBox.Text = string.Empty;
            }
        }

19 View Source File : LUTPanelOptions.cs
License : MIT License
Project Creator : a1xd

private string PointsToActiveValuesText(IEnumerable<Vec2<float>> points, int length)
        {
            StringBuilder builder = new StringBuilder();

            for(int i = 0; i < length; i++)
            {
                var point = points.ElementAt(i);
                builder.AppendLine($"{point.x},{point.y};");
            }

            return builder.ToString();
        }

19 View Source File : OverlayLibraryEditor.cs
License : Apache License 2.0
Project Creator : A7ocin

public override void OnInspectorGUI(){	
			m_Object.Update();
			serializedObject.Update();
			
			GUILayout.Label ("overlayList", EditorStyles.boldLabel);


			OverlayDatareplacedet[] overlayElementList = GetOverlayDataArray();
			GUILayout.Space(30);
			GUILayout.Label ("Overlays reduced " + scaleAdjust.intValue +" time(s)");
			GUILayout.BeginHorizontal();
				
				if(scaleAdjust.intValue > 0){
					if(GUILayout.Button("Resolution +")){
						ScaleUpTextures();
					
						isDirty = true;
						canUpdate = false;
						scaleAdjust.intValue --;
					}
					
				}
			
				if(GUILayout.Button("Resolution -")){
					ScaleDownTextures();
				
					isDirty = true;
					canUpdate = false;
					scaleAdjust.intValue ++;
				}
				

			GUILayout.EndHorizontal();
			
			GUILayout.Space(20);
			
			
			GUILayout.BeginHorizontal();
				compress.boolValue = GUILayout.Toggle (compress.boolValue ? true : false," Compress Textures");

				readWrite.boolValue = GUILayout.Toggle (readWrite.boolValue ? true : false," Read/Write");

				if(GUILayout.Button(" Apply")){
					ConfigureTextures();
					
					isDirty = true;
					canUpdate = false;
				}

			GUILayout.EndHorizontal();
			
			GUILayout.Space(20);
			
			
			GUILayout.BeginHorizontal();
				if(GUILayout.Button("Order by Name")){
					canUpdate = false;

					List<OverlayDatareplacedet> OverlayDataTemp = overlayElementList.ToList();  
				
					//Make sure there's no invalid data
					for(int i = 0; i < OverlayDataTemp.Count; i++){
						if(OverlayDataTemp[i] == null){
							OverlayDataTemp.RemoveAt(i);
							i--;
						}
					}
				
					OverlayDataTemp.Sort((x,y) => x.name.CompareTo(y.name));

					for(int i = 0; i < OverlayDataTemp.Count; i++){
						SetOverlayData(i,OverlayDataTemp[i]);
					}
				
				}
				
				if(GUILayout.Button("Update List")){
					isDirty = true;
					canUpdate = false;
				}
				if (GUILayout.Button("Remove Duplicates"))
				{
					HashSet<OverlayDatareplacedet> Overlays = new HashSet<OverlayDatareplacedet>();
					
					foreach(OverlayDatareplacedet oda in overlayElementList)
					{
					Overlays.Add(oda);
					}

					m_OverlayDataCount.intValue = Overlays.Count;
					for(int i=0;i<Overlays.Count;i++)
					{
						SetOverlayData(i,Overlays.ElementAt(i));
					}
					isDirty = true;
					canUpdate = false;
				}
			GUILayout.EndHorizontal();
			
			GUILayout.Space(20);
				Rect dropArea = GUILayoutUtility.GetRect(0.0f,50.0f, GUILayout.ExpandWidth(true));
				GUI.Box(dropArea,"Drag Overlays here");
			GUILayout.Space(20);
			

			for(int i = 0; i < m_OverlayDataCount.intValue; i ++){
				GUILayout.BeginHorizontal();

				var result = EditorGUILayout.ObjectField(overlayElementList[i], typeof(OverlayDatareplacedet), true) as OverlayDatareplacedet;
					
					if(GUI.changed && canUpdate){
						SetOverlayData(i,result);
					}
					
					if(GUILayout.Button("-", GUILayout.Width(20.0f))){
						canUpdate = false;
						RemoveOverlayDataAtIndex(i);					
					}

				GUILayout.EndHorizontal();
				
				if(i == m_OverlayDataCount.intValue -1){
					canUpdate = true;	
					
					if(isDirty){
						overlayLibrary.UpdateDictionary();
						isDirty = false;
					}
				}
			}
			
			DropAreaGUI(dropArea);
			
			if(GUILayout.Button("Add OverlayData")){
				AddOverlayData(null);
			}
			
			if(GUILayout.Button("Clear List")){
				m_OverlayDataCount.intValue = 0;
			}
			
			
			m_Object.ApplyModifiedProperties();
			serializedObject.ApplyModifiedProperties();
		}

19 View Source File : SlotLibraryEditor.cs
License : Apache License 2.0
Project Creator : A7ocin

public override void OnInspectorGUI()
		{
			m_Object.Update();

			GUILayout.Label("slotElementList", EditorStyles.boldLabel);

			SlotDatareplacedet[] slotElementList = GetSlotDatareplacedetArray();

			GUILayout.BeginHorizontal();
			if (GUILayout.Button("Order by Name"))
			{
				canUpdate = false;

				List<SlotDatareplacedet> SlotDatareplacedetTemp = slotElementList.ToList();

				//Make sure there's no invalid data
				for (int i = 0; i < SlotDatareplacedetTemp.Count; i++)
				{
					if (SlotDatareplacedetTemp[i] == null)
					{
						SlotDatareplacedetTemp.RemoveAt(i);
						i--;
					}
				}

				SlotDatareplacedetTemp.Sort((x, y) => x.name.CompareTo(y.name));

				for (int i = 0; i < SlotDatareplacedetTemp.Count; i++)
				{
					SetSlotDatareplacedet(i, SlotDatareplacedetTemp[i]);
				}

			}

			if (GUILayout.Button("Update List"))
			{
				isDirty = true;
				canUpdate = false;
			}
			if (GUILayout.Button("Remove Duplicates"))
			{
				HashSet<SlotDatareplacedet> Slots = new HashSet<SlotDatareplacedet>();
				
				foreach(SlotDatareplacedet osa in slotElementList)
				{
					Slots.Add(osa);
				}
				
				m_SlotDatareplacedetCount.intValue = Slots.Count;
				for(int i=0;i<Slots.Count;i++)
				{
					SetSlotDatareplacedet(i,Slots.ElementAt(i));
				}
				isDirty = true;
				canUpdate = false;
			}

			GUILayout.EndHorizontal();

			GUILayout.Space(20);
			Rect dropArea = GUILayoutUtility.GetRect(0.0f, 50.0f, GUILayout.ExpandWidth(true));
			GUI.Box(dropArea, "Drag Slots here");
			GUILayout.Space(20);


			for (int i = 0; i < m_SlotDatareplacedetCount.intValue; i++)
			{
				GUILayout.BeginHorizontal();

				SlotDatareplacedet result = EditorGUILayout.ObjectField(slotElementList[i], typeof(SlotDatareplacedet), true) as SlotDatareplacedet;

				if (GUI.changed && canUpdate)
				{
					SetSlotDatareplacedet(i, result);
				}

				if (GUILayout.Button("-", GUILayout.Width(20.0f)))
				{
					canUpdate = false;
					RemoveSlotDatareplacedetAtIndex(i);
				}

				GUILayout.EndHorizontal();

				if (i == m_SlotDatareplacedetCount.intValue - 1)
				{
					canUpdate = true;

					if (isDirty)
					{
						slotLibrary.UpdateDictionary();
						isDirty = false;
					}
				}
			}

			DropAreaGUI(dropArea);

			if (GUILayout.Button("Add SlotDatareplacedet"))
			{
				AddSlotDatareplacedet(null);
			}

			if (GUILayout.Button("Clear List"))
			{
				m_SlotDatareplacedetCount.intValue = 0;
			}

			if (GUILayout.Button("Remove Invalid Slot Data"))
			{
				RemoveInvalidSlotDatareplacedet(slotElementList);
			}

			m_Object.ApplyModifiedProperties();
		}

19 View Source File : LUTPanelOptions.cs
License : MIT License
Project Creator : a1xd

private string PointsToEntryTextBoxText(IEnumerable<Vec2<float>> points, int length)
        {
            StringBuilder builder = new StringBuilder();

            for(int i = 0; i < length; i++)
            {
                var point = points.ElementAt(i);
                builder.Append($"{point.x},{point.y};");
            }

            return builder.ToString();
        }

19 View Source File : VectorExtensions.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public static Vector2 Median(this IEnumerable<Vector2> vectors)
        {
            var enumerable = vectors as Vector2[] ?? vectors.ToArray();
            int count = enumerable.Length;
            return count == 0 ? Vector2.zero : enumerable.OrderBy(v => v.sqrMagnitude).ElementAt(count / 2);
        }

19 View Source File : VectorExtensions.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public static Vector3 Median(this IEnumerable<Vector3> vectors)
        {
            var enumerable = vectors as Vector3[] ?? vectors.ToArray();
            int count = enumerable.Length;
            return count == 0 ? Vector3.zero : enumerable.OrderBy(v => v.sqrMagnitude).ElementAt(count / 2);
        }

19 View Source File : VectorExtensions.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public static Vector2 Median(this ICollection<Vector2> vectors)
        {
            int count = vectors.Count;
            return count == 0 ? Vector2.zero : vectors.OrderBy(v => v.sqrMagnitude).ElementAt(count / 2);
        }

19 View Source File : VectorExtensions.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public static Vector3 Median(this ICollection<Vector3> vectors)
        {
            int count = vectors.Count;
            return count == 0 ? Vector3.zero : vectors.OrderBy(v => v.sqrMagnitude).ElementAt(count / 2);
        }

19 View Source File : InterpolationManager.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public void UseTime()
        {
            if (PhysicsObj == null)
                return;

            if (NodeFailCounter > 3 || PositionQueue.Count == 0)
            {
                if (NodeFailCounter <= 0) return;

                var last = PositionQueue.Last.Value;
                if (last.Type != InterpolationNodeType.JumpType && last.Type != InterpolationNodeType.VelocityType)
                {
                    if (PhysicsObj.SetPositionSimple(last.Position, true) != SetPositionError.OK)
                        return;

                    StopInterpolating();
                    return;
                }

                if (PositionQueue.Count > 1)
                {
                    for (var i = PositionQueue.Count; i >= 0; --i)
                    {
                        var node = PositionQueue.ElementAt(i);
                        if (node.Type == InterpolationNodeType.PositionType)
                        {
                            if (PhysicsObj.SetPositionSimple(node.Position, true) != SetPositionError.OK)
                                return;

                            PhysicsObj.set_velocity(last.Velocity, true);
                            StopInterpolating();
                            return;
                        }
                    }
                }

                if (PhysicsObj.SetPositionSimple(BlipToPosition, true) != SetPositionError.OK)
                    return;

                StopInterpolating();
                return;
            }

            var first = PositionQueue.First.Value;
            switch (first.Type)
            {
                case InterpolationNodeType.JumpType:
                    NodeCompleted(true);
                    break;

                case InterpolationNodeType.VelocityType:
                    PhysicsObj.set_velocity(first.Velocity, true);
                    NodeCompleted(true);
                    break;
            }
        }

19 View Source File : InterpolationManager.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public void NodeCompleted(bool success)
        {
            if (PhysicsObj == null)
                return;

            FrameCounter = 0;
            ProgressQuantum = 0.0f;

            var head = PositionQueue.Count == 0 ? null : PositionQueue.First.Value;
            var next = PositionQueue.Count <= 1 ? null : PositionQueue.ElementAt(1);

            if (PositionQueue.Count > 1)
            {
                if (next.Type == InterpolationNodeType.PositionType)
                    OriginalDistance = PhysicsObj.Position.Distance(next.Position);

                else if (!success)
                {
                    if (head == null) return;
                    BlipToPosition = head.Position;
                }
            }
            else
            {
                OriginalDistance = LargeDistance;
                if (!success)
                {
                    if (head == null) return;
                    BlipToPosition = head.Position;
                }
                else
                    StopInterpolating();
            }
            if (PositionQueue.Count > 0)
                PositionQueue.RemoveFirst();
        }

19 View Source File : InterpolationManager.cs
License : GNU General Public License v3.0
Project Creator : ACEmulator

public void NodeCompleted(bool success)
        {
            if (PhysicsObj == null)
                return;

            FrameCounter = 0;
            ProgressQuantum = 0.0f;

            var head = PositionQueue.Count == 0 ? null : PositionQueue.First();
            var next = PositionQueue.Count <= 1 ? null : PositionQueue.ElementAt(1);

            if (PositionQueue.Count > 1)
            {
                if (next.Type == InterpolationNodeType.PositionType)
                    OriginalDistance = PhysicsObj.Position.Distance(next.Position);

                else if (!success)
                {
                    if (head == null) return;
                    BlipToPosition = head.Position;
                }
            }
            else
            {
                OriginalDistance = LargeDistance;
                if (!success)
                {
                    if (head == null) return;
                    BlipToPosition = head.Position;
                }
                else
                    StopInterpolating();
            }
            if (PositionQueue.Count > 0)
                PositionQueue.Dequeue();
        }

19 View Source File : InterpolationManager.cs
License : GNU General Public License v3.0
Project Creator : ACEmulator

public void UseTime()
        {
            if (PhysicsObj == null)
                return;

            if (NodeFailCounter > 3 || PositionQueue.Count == 0)
            {
                if (NodeFailCounter <= 0) return;

                var last = PositionQueue.Last();
                if (last.Type != InterpolationNodeType.JumpType && last.Type != InterpolationNodeType.VelocityType)
                {
                    if (PhysicsObj.SetPositionSimple(last.Position, true) != SetPositionError.OK)
                        return;

                    StopInterpolating();
                    return;
                }

                if (PositionQueue.Count > 1)
                {
                    for (var i = PositionQueue.Count; i >= 0; --i)
                    {
                        var node = PositionQueue.ElementAt(i);
                        if (node.Type == InterpolationNodeType.PositionType)
                        {
                            if (PhysicsObj.SetPositionSimple(node.Position, true) != SetPositionError.OK)
                                return;

                            PhysicsObj.set_velocity(last.Velocity, true);
                            StopInterpolating();
                            return;
                        }
                    }
                }

                if (PhysicsObj.SetPositionSimple(BlipToPosition, true) != SetPositionError.OK)
                    return;

                StopInterpolating();
                return;
            }

            var first = PositionQueue.FirstOrDefault();
            switch (first.Type)
            {
                case InterpolationNodeType.JumpType:
                    NodeCompleted(true);
                    break;

                case InterpolationNodeType.VelocityType:
                    PhysicsObj.set_velocity(first.Velocity, true);
                    NodeCompleted(true);
                    break;
            }
        }

19 View Source File : ExportManager.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas

private void RunExportHooks(string extension, ExportSheet vs)
        {
            for (int i = 0; i < postExportHooks.Count; i++) {
                if (postExportHooks.ElementAt(i).Value.HasExtension(extension))
                {
                    if (FileNameScheme.Hooks.Count < 1) {
                        return;
                    }

                    if (FileNameScheme.Hooks.Contains(postExportHooks.ElementAt(i).Key)) {
                        postExportHooks.ElementAt(i).Value.Run(vs, extension);
                    }
                }
            }
        }

19 View Source File : JobServerQueue.cs
License : MIT License
Project Creator : actions

private async Task ProcessWebConsoleLinesQueueAsync(bool runOnce = false)
        {
            while (!_jobCompletionSource.Task.IsCompleted || runOnce)
            {
                if (_webConsoleLineAggressiveDequeue && ++_webConsoleLineAggressiveDequeueCount > _webConsoleLineAggressiveDequeueLimit)
                {
                    Trace.Info("Stop aggressive process web console line queue.");
                    _webConsoleLineAggressiveDequeue = false;
                }

                // Group consolelines by timeline record of each step
                Dictionary<Guid, List<TimelineRecordLogLine>> stepsConsoleLines = new Dictionary<Guid, List<TimelineRecordLogLine>>();
                List<Guid> stepRecordIds = new List<Guid>(); // We need to keep lines in order
                int linesCounter = 0;
                ConsoleLineInfo lineInfo;
                while (_webConsoleLineQueue.TryDequeue(out lineInfo))
                {
                    if (!stepsConsoleLines.ContainsKey(lineInfo.StepRecordId))
                    {
                        stepsConsoleLines[lineInfo.StepRecordId] = new List<TimelineRecordLogLine>();
                        stepRecordIds.Add(lineInfo.StepRecordId);
                    }

                    if (!string.IsNullOrEmpty(lineInfo.Line) && lineInfo.Line.Length > 1024)
                    {
                        Trace.Verbose("Web console line is more than 1024 chars, truncate to first 1024 chars");
                        lineInfo.Line = $"{lineInfo.Line.Substring(0, 1024)}...";
                    }

                    stepsConsoleLines[lineInfo.StepRecordId].Add(new TimelineRecordLogLine(lineInfo.Line, lineInfo.LineNumber));
                    linesCounter++;

                    // process at most about 500 lines of web console line during regular timer dequeue task.
                    if (!runOnce && linesCounter > 500)
                    {
                        break;
                    }
                }

                // Batch post consolelines for each step timeline record
                foreach (var stepRecordId in stepRecordIds)
                {
                    // Split consolelines into batch, each batch will container at most 100 lines.
                    int batchCounter = 0;
                    List<List<TimelineRecordLogLine>> batchedLines = new List<List<TimelineRecordLogLine>>();
                    foreach (var line in stepsConsoleLines[stepRecordId])
                    {
                        var currentBatch = batchedLines.ElementAtOrDefault(batchCounter);
                        if (currentBatch == null)
                        {
                            batchedLines.Add(new List<TimelineRecordLogLine>());
                            currentBatch = batchedLines.ElementAt(batchCounter);
                        }

                        currentBatch.Add(line);

                        if (currentBatch.Count >= 100)
                        {
                            batchCounter++;
                        }
                    }

                    if (batchedLines.Count > 0)
                    {
                        // When job finish, web console lines becomes less interesting to customer
                        // We batch and produce 500 lines of web console output every 500ms
                        // If customer's task produce mreplacedive of outputs, then the last queue drain run might take forever.
                        // So we will only upload the last 200 lines of each step from all buffered web console lines.
                        if (runOnce && batchedLines.Count > 2)
                        {
                            Trace.Info($"Skip {batchedLines.Count - 2} batches web console lines for last run");
                            batchedLines = batchedLines.TakeLast(2).ToList();
                        }

                        int errorCount = 0;
                        foreach (var batch in batchedLines)
                        {
                            try
                            {
                                // we will not requeue failed batch, since the web console lines are time sensitive.
                                if (batch[0].LineNumber.HasValue)
                                {
                                    await _jobServer.AppendTimelineRecordFeedAsync(_scopeIdentifier, _hubName, _planId, _jobTimelineId, _jobTimelineRecordId, stepRecordId, batch.Select(logLine => logLine.Line).ToList(), batch[0].LineNumber.Value, default(CancellationToken));
                                }
                                else
                                {
                                    await _jobServer.AppendTimelineRecordFeedAsync(_scopeIdentifier, _hubName, _planId, _jobTimelineId, _jobTimelineRecordId, stepRecordId, batch.Select(logLine => logLine.Line).ToList(), default(CancellationToken));
                                }

                                if (_firstConsoleOutputs)
                                {
                                    HostContext.WritePerfCounter($"WorkerJobServerQueueAppendFirstConsoleOutput_{_planId.ToString()}");
                                    _firstConsoleOutputs = false;
                                }
                            }
                            catch (Exception ex)
                            {
                                Trace.Info("Catch exception during append web console line, keep going since the process is best effort.");
                                Trace.Error(ex);
                                errorCount++;
                            }
                        }

                        Trace.Info("Try to append {0} batches web console lines for record '{2}', success rate: {1}/{0}.", batchedLines.Count, batchedLines.Count - errorCount, stepRecordId);
                    }
                }

                if (runOnce)
                {
                    break;
                }
                else
                {
                    await Task.Delay(_webConsoleLineAggressiveDequeue ? _aggressiveDelayForWebConsoleLineDequeue : _delayForWebConsoleLineDequeue);
                }
            }
        }

19 View Source File : Batter.cs
License : MIT License
Project Creator : Actipro

private static string GetRandomPosition() {
			int position = random.Next(0, Positions.Count());
			return Positions.ElementAt(position);
		}

19 View Source File : BaseballViewModel.cs
License : MIT License
Project Creator : Actipro

private IEnumerable<Team> BuildTeamOneTeams() {
			var teams = new List<Team>();
			for (int i = 0; i < TeamOneNames.Count(); i++) {
				var team = new Team();
				team.Name = TeamOneNames.ElementAt(i);
				team.Color = TeamOneColors.ElementAt(i);
				teams.Add(team);
			}

			return teams;
		}

19 View Source File : BaseballViewModel.cs
License : MIT License
Project Creator : Actipro

private IEnumerable<Team> BuildTeamTwoTeams() {
			var teams = new List<Team>();
			for (int i = 0; i < TeamTwoNames.Count(); i++) {
				var team = new Team();
				team.Name = TeamTwoNames.ElementAt(i);
				team.Color = TeamTwoColors.ElementAt(i);
				teams.Add(team);
			}

			return teams;
		}

19 View Source File : BaseballViewModel.cs
License : MIT License
Project Creator : Actipro

private void BuildTeamOneBatters() {
			var teamOneTeams = BuildTeamOneTeams();
			var unsortedBatters = new List<Batter>();
			for (int i = 0; i < TeamOneBatterFirstNames.Count(); i++) {
				string firstName = TeamOneBatterFirstNames.ElementAt(i);
				string lastName = TeamOneBatterLastNames.ElementAt(i);
				var batter = Batter.BuildRandomBatter(firstName, lastName, StartingYear, EndingYear);
				int teamIndex = random.Next(0, teamOneTeams.Count());
				batter.Team = teamOneTeams.ElementAt(teamIndex);
				unsortedBatters.Add(batter);
			}

			foreach (var batter in unsortedBatters.OrderBy(batter => batter.OrderedName)) {
				TeamOneBatters.Add(batter);
			}

			SelectedTeamOneBatter = teamOneBatters[0];
		}

19 View Source File : BaseballViewModel.cs
License : MIT License
Project Creator : Actipro

private void BuildTeamTwoBatters() {
			var teamTwoTeams = BuildTeamTwoTeams();
			var unsortedBatters = new List<Batter>();
			for (int i = 0; i < TeamTwoBatterFirstNames.Count(); i++) {

				string firstName = TeamTwoBatterFirstNames.ElementAt(i);
				string lastName = TeamTwoBatterLastNames.ElementAt(i);
				var batter = Batter.BuildRandomBatter(firstName, lastName, StartingYear, EndingYear);
				int teamIndex = random.Next(0, teamTwoTeams.Count());
				batter.Team = teamTwoTeams.ElementAt(teamIndex);
				unsortedBatters.Add(batter);
			}

			foreach (var batter in unsortedBatters.OrderBy(batter => batter.OrderedName)) {
				TeamTwoBatters.Add(batter);
			}

			SelectedTeamTwoBatter = teamTwoBatters[0];
		}

19 View Source File : CodeFixVerifier.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private async Task VerifyFixAsync(string language, Diagnosticreplacedyzer replacedyzer, CodeFixProvider codeFixProvider, 
										  string oldSource, string newSource, bool allowNewCompilerDiagnostics, int codeFixIndex = 0)
		{
			var doreplacedent = CreateDoreplacedent(oldSource, language);
			var replacedyzerDiagnostics = await GetSortedDiagnosticsFromDoreplacedentsAsync(replacedyzer, new[] { doreplacedent }, checkOnlyFirstDoreplacedent: true).ConfigureAwait(false);
			var compilerDiagnostics = await GetCompilerDiagnosticsAsync(doreplacedent).ConfigureAwait(false);
			var attempts = replacedyzerDiagnostics.Length;

			for (int i = 0; i < attempts; ++i)
			{
				var actions = new List<CodeAction>();
				var context = new CodeFixContext(doreplacedent, replacedyzerDiagnostics[0], (a, d) => actions.Add(a), CancellationToken.None);
				await codeFixProvider.RegisterCodeFixesAsync(context).ConfigureAwait(false);

				if (!actions.Any())
				{
					break;
				}

				doreplacedent = await ApplyCodeActionAsync(doreplacedent, actions.ElementAt(codeFixIndex)).ConfigureAwait(false);
				
				replacedyzerDiagnostics = await GetSortedDiagnosticsFromDoreplacedentsAsync(replacedyzer, new[] { doreplacedent }, checkOnlyFirstDoreplacedent: true).ConfigureAwait(false);

				var newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, await GetCompilerDiagnosticsAsync(doreplacedent).ConfigureAwait(false));

				//check if applying the code fix introduced any new compiler diagnostics
				if (!allowNewCompilerDiagnostics && newCompilerDiagnostics.Any())
				{
					// Format and get the compiler diagnostics again so that the locations make sense in the output
					doreplacedent = doreplacedent.WithSyntaxRoot(Formatter.Format(await doreplacedent.GetSyntaxRootAsync().ConfigureAwait(false), 
						Formatter.Annotation, doreplacedent.Project.Solution.Workspace));
					newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, await GetCompilerDiagnosticsAsync(doreplacedent).ConfigureAwait(false));

					replacedert.True(false,
						string.Format("Fix introduced new compiler diagnostics:\r\n{0}\r\n\r\nNew doreplacedent:\r\n{1}\r\n",
							string.Join("\r\n", newCompilerDiagnostics.Select(d => d.ToString())),
							(await doreplacedent.GetSyntaxRootAsync().ConfigureAwait(false)).ToFullString()));
				}

				//check if there are replacedyzer diagnostics left after the code fix
				if (!replacedyzerDiagnostics.Any())
				{
					break;
				}
			}

			//after applying all of the code fixes, compare the resulting string to the inputted one
			var actual = await GetStringFromDoreplacedentAsync(doreplacedent).ConfigureAwait(false);
			replacedert.Equal(newSource, actual);
		}

19 View Source File : DiagnosticVerifier.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private static void VerifyDiagnosticResults(IEnumerable<Diagnostic> actualResults, Diagnosticreplacedyzer replacedyzer, params DiagnosticResult[] expectedResults)
		{
			int expectedCount = expectedResults.Count();
			int actualCount = actualResults.Count();

			if (expectedCount != actualCount)
			{
				string diagnosticsOutput = actualResults.Any() ? FormatDiagnostics(replacedyzer, actualResults.ToArray()) : "    NONE.";
                
				replacedert.True(false,
					string.Format("Mismatch between number of diagnostics returned, expected \"{0}\" actual \"{1}\"\r\n\r\nDiagnostics:\r\n{2}\r\n", expectedCount, actualCount, diagnosticsOutput));
			}

			for (int i = 0; i < expectedResults.Length; i++)
			{
				var actual = actualResults.ElementAt(i);
				var expected = expectedResults[i];

				if (expected.Line == -1 && expected.Column == -1)
				{
					if (actual.Location != Location.None)
					{
						replacedert.True(false,
							string.Format("Expected:\nA project diagnostic with No location\nActual:\n{0}",
							FormatDiagnostics(replacedyzer, actual)));
					}
				}
				else
				{
					VerifyDiagnosticLocation(replacedyzer, actual, actual.Location, expected.Locations.First());
					var additionalLocations = actual.AdditionalLocations.ToArray();

					if (additionalLocations.Length != expected.Locations.Length - 1)
					{
						replacedert.True(false,
							string.Format("Expected {0} additional locations but got {1} for Diagnostic:\r\n    {2}\r\n",
								expected.Locations.Length - 1, additionalLocations.Length,
								FormatDiagnostics(replacedyzer, actual)));
					}

					for (int j = 0; j < additionalLocations.Length; ++j)
					{
						VerifyDiagnosticLocation(replacedyzer, actual, additionalLocations[j], expected.Locations[j + 1]);
					}
				}

				if (actual.Id != expected.Id)
				{
					replacedert.True(false,
						string.Format("Expected diagnostic id to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n    {2}\r\n",
							expected.Id, actual.Id, FormatDiagnostics(replacedyzer, actual)));
				}

				if (actual.Severity != expected.Severity)
				{
					replacedert.True(false,
						string.Format("Expected diagnostic severity to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n    {2}\r\n",
							expected.Severity, actual.Severity, FormatDiagnostics(replacedyzer, actual)));
				}

				if (actual.GetMessage() != expected.Message)
				{
					replacedert.True(false,
						string.Format("Expected diagnostic message to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n    {2}\r\n",
							expected.Message, actual.GetMessage(), FormatDiagnostics(replacedyzer, actual)));
				}
			}
		}

19 View Source File : PrimeFactory.cs
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat

public static BigInteger GetValueFromIndex(int index)
		{
			while ((primesCount - 1) < index)
			{
				IncreaseMaxValue();
			}
			return primes.ElementAt(index);
		}

19 View Source File : PadView.cs
License : MIT License
Project Creator : ademanuele

void PresentCoverageAtIndex(int index)
    {
      if (currentResults == null || index >= currentResults.Count)
      {
        ClearCoverageResults();
        return;
      }

      var coverage = currentResults.ElementAt(index);
      TestedProjectLabel.StringValue = coverage.Key;      
      LineCoverageLabel.StringValue = $"{Math.Round(coverage.Value.Line, 2)}%";
      BranchCoverageLabel.StringValue = $"{Math.Round(coverage.Value.Branch, 2)}%";
      presentedResultIndex = index;
      EnableCoverageResultsUI();
    }

19 View Source File : EnumerableFilters.cs
License : MIT License
Project Creator : Adoxio

public static object Random(Context context, IEnumerable input)
		{
			IPortalLiquidContext portalLiquidContext;

			var random = context.TryGetPortalLiquidContext(out portalLiquidContext)
				? portalLiquidContext.Random
				: new Random();

			var items = input.Cast<object>().ToArray();

			return items.ElementAt(random.Next(items.Length));
		}

19 View Source File : AssetManager.cs
License : MIT License
Project Creator : Adsito

public static IEnumerator Dispose() 
		{
			IsInitialising = true;
			ProgressManager.RemoveProgressBars("Unload replacedet Bundles");

			int progressID = Progress.Start("Unload replacedet Bundles", null, Progress.Options.Sticky);
			int bundleID = Progress.Start("Bundles", null, Progress.Options.Sticky, progressID);
			int prefabID = Progress.Start("Prefabs", null, Progress.Options.Sticky, progressID);
			Progress.Report(bundleID, 0f);
			Progress.Report(prefabID, 0f);
			PrefabManager.ReplaceWithDefault(PrefabManager.CurrentMapPrefabs, prefabID);

			while (PrefabManager.IsChangingPrefabs)
				yield return null;

			for (int i = 0; i < BundleCache.Count; i++)
            {
				Progress.Report(bundleID, (float)i / BundleCache.Count, "Unloading: " + BundleCache.ElementAt(i).Key);
				BundleCache.ElementAt(i).Value.Unload(true);
				yield return null;
            }
			
			int bundleCount = BundleCache.Count;
			BundleLookup.Clear();
			BundleCache.Clear();
			replacedetCache.Clear();

			Progress.Report(bundleID, 0.99f, "Unloaded: " + bundleCount + " bundles.");
			Progress.Finish(bundleID, Progress.Status.Succeeded);
			IsInitialised = false; IsInitialising = false;
		}

19 View Source File : ModEntry.cs
License : GNU General Public License v3.0
Project Creator : 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 View Source File : ModEntry.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

private int GetRandomQuesreplacedem(RNPC rnpc)
        {
            //Alert(Game1.currentSeason);
            int item;
            if (!Game1.currentSeason.Equals("winter") && Game1.random.NextDouble() < 0.5)
            {
                List<int> crops = Utility.possibleCropsAtThisTime(Game1.currentSeason, Game1.dayOfMonth <= 7);
                item = crops.ElementAt(Game1.random.Next(crops.Count));
            }
            else
            {
                item = Utility.getRandomItemFromSeason(Game1.currentSeason, 1000, true, true);
                if (item == -5)
                {
                    item = 176;
                }
                if (item == -6)
                {
                    item = 184;
                }
            }
            return item;
        }

19 View Source File : ModEntry.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

private int RankStringForNPC(string npcString, string str, int checks)
        {
            int rank = 0;

            IEnumerable<string> stra = str.Split('/').Take(checks);
            IEnumerable<string> npca = npcString.Split('/').Take(checks);
            for (int i = 0; i < checks; i++)
            {
                if (stra.Count() == i)
                {
                    break;
                }
                string strai = stra.ElementAt(i);
                string npcai = npca.ElementAt(i);
                if (strai != "any")
                {
                    List<string> straia = strai.Split('|').ToList();
                    if (strai != "" && strai != npcai && !straia.Contains(npcai))
                    {
                        return -1;
                    }
                    rank++;
                }
            }
            return rank;
        }

19 View Source File : Utils.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

public static void GetRandomPost(string friend)
        {
            IDictionary<string, string> data;
            try
            {
                data = Helper.Content.Load<Dictionary<string, string>>($"Characters\\Dialogue\\{friend}", ContentSource.GameContent);
            }
            catch
            {
                return;
            }
            if (data == null)
                return;

            string NPCLikes;
            Game1.NPCGiftTastes.TryGetValue(friend, out NPCLikes);
            if (NPCLikes == null)
                return;
            string[] likes = NPCLikes.Split('/')[1].Split(' ');
            if (likes.Length == 0)
                return;
            List<Object> foods = new List<Object>();
            List<Object> favs = new List<Object>();
            foreach(string str in likes)
            {
                if (!int.TryParse(str, out int idx))
                    continue;
                var obj = new Object(idx, 1, false, -1, 0);
                if (obj.Type == "Cooking")
                    foods.Add(obj);
                else
                    favs.Add(obj);
            }

            if(foods.Count > 0)
            {
                string itemName = foods[Game1.random.Next(foods.Count)].DisplayName;
                IEnumerable<KeyValuePair<string, string>> strings = data.Where(s => s.Key.StartsWith("SocialNetwork_Food_"));

                if (strings.Count() > 0)
                {
                    string str = strings.ElementAt(Game1.random.Next(strings.Count())).Value;
                    str = str.Replace("{0}", itemName);
                    NPC npc = Game1.getCharacterFromName(friend);
                    Texture2D portrait = npc.Sprite.Texture;
                    Rectangle sourceRect = npc.getMugShotSourceRect();
                    ModEntry.postList.Add(new SocialPost(npc, portrait, sourceRect, str));
                    Monitor.Log($"added food post from {npc.displayName}");
                    return;
                }
            }
            if(favs.Count > 0)
            {
                string itemName = favs[Game1.random.Next(favs.Count)].DisplayName;
                IEnumerable<KeyValuePair<string, string>> strings = data.Where(s => s.Key.StartsWith("SocialNetwork_Favorite_"));
                if (strings.Count() > 0)
                {
                    string str = strings.ElementAt(Game1.random.Next(strings.Count())).Value;
                    str = str.Replace("{0}", itemName);
                    NPC npc = Game1.getCharacterFromName(friend);
                    Texture2D portrait = npc.Sprite.Texture;
                    Rectangle sourceRect = npc.getMugShotSourceRect();
                    ModEntry.postList.Add(new SocialPost(npc, portrait, sourceRect, str));
                    Monitor.Log($"added favorite post from {npc.displayName}");
                    return;
                }
            }
        }

19 View Source File : SwimMaps.cs
License : GNU General Public License v3.0
Project Creator : 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 View Source File : NoodleObjectData.cs
License : MIT License
Project Creator : Aeroluna

private static void FinalizeCustomObject(Dictionary<string, object?> dynData, NoodleObjectData noodleObjectData, IReadonlyBeatmapData beatmapData)
        {
            object? rotation = dynData.Get<object>(ROTATION);
            if (rotation != null)
            {
                if (rotation is List<object> list)
                {
                    IEnumerable<float> rot = list.Select(n => Convert.ToSingle(n));
                    noodleObjectData.WorldRotationQuaternion = Quaternion.Euler(rot.ElementAt(0), rot.ElementAt(1), rot.ElementAt(2));
                }
                else
                {
                    noodleObjectData.WorldRotationQuaternion = Quaternion.Euler(0, Convert.ToSingle(rotation), 0);
                }
            }

            IEnumerable<float>? localrot = dynData.Get<List<object>>(LOCALROTATION)?.Select(n => Convert.ToSingle(n));
            if (localrot != null)
            {
                noodleObjectData.LocalRotationQuaternion = Quaternion.Euler(localrot.ElementAt(0), localrot.ElementAt(1), localrot.ElementAt(2));
            }

            noodleObjectData.Track = AnimationHelper.GetTrackArray(dynData, beatmapData);

            Dictionary<string, object?>? animationObjectDyn = dynData.Get<Dictionary<string, object?>>("_animation");
            if (animationObjectDyn != null)
            {
                Dictionary<string, PointDefinition>? pointDefinitions = ((CustomBeatmapData)beatmapData).customData.Get<Dictionary<string, PointDefinition>>("pointDefinitions")
                    ?? throw new InvalidOperationException("Could not retrieve point definitions.");
                Animation.AnimationHelper.GetAllPointData(
                    animationObjectDyn,
                    pointDefinitions,
                    out PointDefinition? localPosition,
                    out PointDefinition? localRotation,
                    out PointDefinition? localScale,
                    out PointDefinition? localLocalRotation,
                    out PointDefinition? localDissolve,
                    out PointDefinition? localDissolveArrow,
                    out PointDefinition? localCuttable,
                    out PointDefinition? localDefinitePosition);
                NoodleObjectData.AnimationObjectData animationObjectData = new NoodleObjectData.AnimationObjectData
                {
                    LocalPosition = localPosition,
                    LocalRotation = localRotation,
                    LocalScale = localScale,
                    LocalLocalRotation = localLocalRotation,
                    LocalDissolve = localDissolve,
                    LocalDissolveArrow = localDissolveArrow,
                    LocalCuttable = localCuttable,
                    LocalDefinitePosition = localDefinitePosition,
                };
                noodleObjectData.AnimationObject = animationObjectData;
            }

            noodleObjectData.Cuttable = dynData.Get<bool?>(CUTTABLE);
            noodleObjectData.Fake = dynData.Get<bool?>(FAKENOTE);

            IEnumerable<float?>? position = dynData.GetNullableFloats(POSITION);
            noodleObjectData.StartX = position?.ElementAtOrDefault(0);
            noodleObjectData.StartY = position?.ElementAtOrDefault(1);

            noodleObjectData.NJS = dynData.Get<float?>(NOTEJUMPSPEED);
            noodleObjectData.SpawnOffset = dynData.Get<float?>(NOTESPAWNOFFSET);
            noodleObjectData.AheadTimeInternal = dynData.Get<float?>("aheadTime");
        }

19 View Source File : ZPollItems.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

internal static bool PollManyResult(IEnumerable<ZSocket> sockets, IEnumerable<ZPollItem> items, ZPollEvent pollEvents, ref ZMessage[] messages)
		{
			int count = items.Count();
			int readyCount = 0;

			bool send = messages != null && ((pollEvents & ZPollEvent.Out) == ZPollEvent.Out);
			bool receive = ((pollEvents & ZPollEvent.In) == ZPollEvent.In);

			ZMessage[] incoming = null;
			if (receive)
			{
				incoming = new ZMessage[count];
			}

			for (int i = 0; i < count; ++i)
			{
				ZSocket socket = sockets.ElementAt(i);
				ZPollItem item = items.ElementAt(i);
				ZMessage message = send ? messages[i] : null;

				if (PollSingleResult(socket, item, pollEvents, ref message))
				{
					++readyCount;
				}
				if (receive)
				{
					incoming[i] = message;
				}
			}

			if (receive)
			{
				messages = incoming;
			}
			return readyCount > 0;
		}

19 View Source File : ZPollItems.Posix.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

internal static unsafe bool PollMany(
				IEnumerable<ZSocket> sockets, 
				IEnumerable<ZPollItem> items, ZPollEvent pollEvents, 
				out ZError error, TimeSpan? timeout = null)
			{
				error = default(ZError);
				bool result = false;
				int count = items.Count();
				int timeoutMs = !timeout.HasValue ? -1 : (int)timeout.Value.TotalMilliseconds;

				zmq_pollitem_posix_t* natives = stackalloc zmq_pollitem_posix_t[count];
				// fixed (zmq_pollitem_posix_t* natives = managedArray) {

				for (int i = 0; i < count; ++i)
				{
					ZSocket socket = sockets.ElementAt(i);
					ZPollItem item = items.ElementAt(i);
					zmq_pollitem_posix_t* native = natives + i;

					native->SocketPtr = socket.SocketPtr;
					native->Events = (short)(item.Events & pollEvents);
					native->ReadyEvents = (short)ZPollEvent.None;
				}

				while (!(result = (-1 != zmq.poll(natives, count, timeoutMs))))
				{
					error = ZError.GetLastErr();

					if (error == ZError.EINTR)
					{
						error = default(ZError);
						continue;
					}
					break;
				}

				for (int i = 0; i < count; ++i)
				{
					ZPollItem item = items.ElementAt(i);
					zmq_pollitem_posix_t* native = natives + i;

					item.ReadyEvents = (ZPollEvent)native->ReadyEvents;
				}
				// }

				return result;
			}

19 View Source File : ZPollItems.Win32.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

internal static unsafe bool PollMany(
				IEnumerable<ZSocket> sockets, 
				IEnumerable<ZPollItem> items, ZPollEvent pollEvents, 
				out ZError error, TimeSpan? timeout = null)
			{
				error = default(ZError);
				bool result = false;
				int count = items.Count();
				int timeoutMs = !timeout.HasValue ? -1 : (int)timeout.Value.TotalMilliseconds;

				zmq_pollitem_windows_t* natives = stackalloc zmq_pollitem_windows_t[count];
				// fixed (zmq_pollitem_windows_t* natives = managedArray) {

				for (int i = 0; i < count; ++i)
				{
					ZSocket socket = sockets.ElementAt(i);
					ZPollItem item = items.ElementAt(i);
					zmq_pollitem_windows_t* native = natives + i;

					native->SocketPtr = socket.SocketPtr;
					native->Events = (short)(item.Events & pollEvents);
					native->ReadyEvents = (short)ZPollEvent.None;
				}

				while (!(result = (-1 != zmq.poll(natives, count, timeoutMs))))
				{
					error = ZError.GetLastErr();

					// No Signalling on Windows
					/* if (error == ZmqError.EINTR) {
						error = ZmqError.DEFAULT;
						continue;
					} */
					break;
				}

				for (int i = 0; i < count; ++i)
				{
					ZPollItem item = items.ElementAt(i);
					zmq_pollitem_windows_t* native = natives + i;

					item.ReadyEvents = (ZPollEvent)native->ReadyEvents;
				}
				// }

				return result;
			}

19 View Source File : Platform.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static void ExpandPaths(IList<string> stream,
			string extension, IEnumerable<string> paths) 
		{
			int pathsC = paths == null ? 0 : paths.Count();

			foreach (string libraryPath in stream.ToArray())
			{
				if (-1 == libraryPath.IndexOf(extension)) continue;

				int libraryPathI = stream.IndexOf(libraryPath);
				stream.RemoveAt(libraryPathI);

				if (pathsC == 0)
				{
					// just continue, don't Insert them again
					continue;
				}

				if (pathsC == 1)
				{
					stream.Insert(libraryPathI, libraryPath.Replace(extension, paths.ElementAt(0)));
					continue;
				}

				foreach (string realLibraryPath in paths)
				{
					stream.Insert(libraryPathI, libraryPath.Replace(extension, realLibraryPath));
					++libraryPathI;
				}

			}
		}

See More Examples