System.Collections.Generic.List.IndexOf(string)

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

591 Examples 7

19 Source : PlyHandler.cs
with MIT License
from 3DBear

private static PlyResult ParseAscii(List<string> plyFile, PlyHeader header)
        {
            var vertices = new List<Vector3>();
            var triangles = new List<int>();
            var colors = new List<Color>();
            var headerEndIndex = plyFile.IndexOf("end_header");
            var vertexStartIndex = headerEndIndex + 1;
            var faceStartIndex = vertexStartIndex + header.VertexCount + 1;
            plyFile.GetRange(vertexStartIndex, header.VertexCount).ForEach(vertex =>
            {
                var xyzrgb = vertex.Split(' ');
                vertices.Add(ParseVertex(xyzrgb, header));
                colors.Add(ParseColor(xyzrgb, header));
            });

            plyFile.GetRange(faceStartIndex, header.FaceCount).ForEach(face =>
            {
                triangles.AddRange(GetTriangles(face, header));
            });
            return new PlyResult(vertices, triangles, colors);
        }

19 Source : SkeletonModifierPropertyDrawer.cs
with Apache License 2.0
from A7ocin

public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            int startingIndent = EditorGUI.indentLevel;
            EditorGUI.BeginProperty(position, label, property);
            var valR = new Rect(position.xMin, position.yMin, position.width, EditorGUIUtility.singleLineHeight);
            string betterLabel = label.text;
            if (property.FindPropertyRelative("property").enumDisplayNames[property.FindPropertyRelative("property").enumValueIndex] != "")
            {
                betterLabel += " (" + property.FindPropertyRelative("property").enumDisplayNames[property.FindPropertyRelative("property").enumValueIndex] + ")";
            }
            List<string> boneNames = new List<string>();
            if (bonesInSkeleton != null)
            {
                boneNames = new List<string>(bonesInSkeleton);
            }
            else
            {
                boneNames = new List<string>(hashNames);
            }
            string thisHashName = property.FindPropertyRelative("hashName").stringValue;
            int hashNameIndex = boneNames.IndexOf(thisHashName);
            if (hashNameIndex == -1 && bonesInSkeleton != null)
            {
                boneNames.Insert(0, thisHashName + " (missing)");
                hashNameIndex = 0;
                var warningRect = new Rect((valR.xMin), valR.yMin, 20f, valR.height);
                var warningIconGUI = new GUIContent("", thisHashName + " was not a bone in the Avatars Skeleton. Please choose another bone for this modifier or delete it.");
                warningIconGUI.image = warningIcon;
                betterLabel += " (missing)";
                GUI.Label(warningRect, warningIconGUI, warningStyle);
            }
            property.isExpanded = EditorGUI.Foldout(valR, property.isExpanded, betterLabel, true);
            if (property.isExpanded)
            {
                EditorGUI.indentLevel++;
                valR = new Rect(valR.xMin, valR.yMax + padding, valR.width, EditorGUIUtility.singleLineHeight);
                if (boneNames.Count > 0)
                {
                    int newHashNameIndex = hashNameIndex;
                    EditorGUI.BeginChangeCheck();
                    newHashNameIndex = EditorGUI.Popup(valR, "Hash Name", hashNameIndex, boneNames.ToArray());
                    if (EditorGUI.EndChangeCheck())
                    {
                        if (newHashNameIndex != hashNameIndex)
                        {
                            property.FindPropertyRelative("hashName").stringValue = boneNames[newHashNameIndex];
                            property.FindPropertyRelative("hash").intValue = UMAUtils.StringToHash(boneNames[newHashNameIndex]);
                            property.serializedObject.ApplyModifiedProperties();
                        }
                    }
                }
                else
                {
                    EditorGUI.PropertyField(valR, property.FindPropertyRelative("hashName"));
                }
                valR = new Rect(valR.xMin, valR.yMax + padding, valR.width, EditorGUIUtility.singleLineHeight);
                EditorGUI.PropertyField(valR, property.FindPropertyRelative("property"));
                valR = new Rect(valR.xMin, valR.yMax + padding, valR.width, EditorGUIUtility.singleLineHeight);
                var valXR = valR;
                var valYR = valR;
                var valZR = valR;
                valXR.width = valYR.width = valZR.width = valR.width / 3;
                valYR.x = valYR.x + valXR.width;
                valZR.x = valZR.x + valXR.width + valYR.width;
                SerializedProperty subValsToOpen = null;
                var valuesX = property.FindPropertyRelative("valuesX");
                var valuesY = property.FindPropertyRelative("valuesY");
                var valuesZ = property.FindPropertyRelative("valuesZ");
                if (valuesX.isExpanded)
                {
                    var valXRB = valXR;
                    valXRB.x = valXRB.x + (EditorGUI.indentLevel * 10f);
                    valXRB.width = valXRB.width - (EditorGUI.indentLevel * 10f);
                    EditorGUI.DrawRect(valXRB, new Color32(255, 255, 255, 100));
                }
                valuesX.isExpanded = EditorGUI.Foldout(valXR, valuesX.isExpanded, "ValuesX", true);
                if (valuesX.isExpanded)
                {
                    valuesY.isExpanded = false;
                    valuesZ.isExpanded = false;
                    subValsToOpen = valuesX;
                }
                if (valuesY.isExpanded)
                {
                    EditorGUI.DrawRect(valYR, new Color32(255, 255, 255, 100));
                }
                valuesY.isExpanded = EditorGUI.Foldout(valYR, valuesY.isExpanded, "ValuesY", true);
                if (valuesY.isExpanded)
                {
                    valuesX.isExpanded = false;
                    valuesZ.isExpanded = false;
                    subValsToOpen = valuesY;
                }
                if (valuesZ.isExpanded)
                {
                    EditorGUI.DrawRect(valZR, new Color32(255, 255, 255, 100));
                }
                valuesZ.isExpanded = EditorGUI.Foldout(valZR, valuesZ.isExpanded, "ValuesZ", true);
                if (valuesZ.isExpanded)
                {
                    valuesX.isExpanded = false;
                    valuesY.isExpanded = false;
                    subValsToOpen = valuesZ;
                }
                if (subValsToOpen != null)
                {
                    valR = new Rect(valR.xMin, valR.yMax + padding + 4f, valR.width, EditorGUIUtility.singleLineHeight);
                    valR.width = valR.width - 30;
                    var boxR1 = valR;
                    boxR1.x = boxR1.x + EditorGUI.indentLevel * 10f;
                    boxR1.y = boxR1.y - 6;
                    boxR1.height = boxR1.height + 12;
                    //topbox
                    EditorGUI.DrawRect(boxR1, new Color32(255, 255, 255, 100));
                    var valSXR = valR;
                    var valSYR = valR;
                    var valSZR = valR;
                    valSXR.width = valSYR.width = valSZR.width = valR.width / 3;
                    valSYR.x = valSYR.x + valSXR.width;
                    valSZR.x = valSZR.x + valSXR.width + valSYR.width;
                    var subValuesVal = subValsToOpen.FindPropertyRelative("val");
                    var subValuesMin = subValsToOpen.FindPropertyRelative("min");
                    var subValuesMax = subValsToOpen.FindPropertyRelative("max");
                    var valSXRF = valSXR;
                    valSXRF.x = valSXRF.x + 38f;
                    valSXRF.width = valSXRF.width - 35f;
                    if (!enableSkelModValueEditing) EditorGUI.BeginDisabledGroup(true);
                    EditorGUI.LabelField(valSXR, "Value");
                    subValuesVal.FindPropertyRelative("value").floatValue = EditorGUI.FloatField(valSXRF, subValuesVal.FindPropertyRelative("value").floatValue);
                    subValuesVal.serializedObject.ApplyModifiedProperties();
                    if (!enableSkelModValueEditing) EditorGUI.EndDisabledGroup();
                    var valSYRF = valSYR;
                    valSYRF.x = valSYRF.x + 30f;
                    valSYRF.width = valSYRF.width - 30f;
                    EditorGUI.LabelField(valSYR, "Min");
                    subValuesMin.floatValue = EditorGUI.FloatField(valSYRF, subValuesMin.floatValue);
                    var valSZRF = valSZR;
                    valSZRF.x = valSZRF.x + 30f;
                    valSZRF.width = valSZRF.width - 30f;
                    EditorGUI.LabelField(valSZR, "Max");
                    subValuesMax.floatValue = EditorGUI.FloatField(valSZRF, subValuesMax.floatValue);
                    var thisModifiersProp = subValuesVal.FindPropertyRelative("modifiers");
                    var modifiersi = thisModifiersProp.arraySize;
                    valR = new Rect(valR.xMin, valR.yMax + padding + 4f, valR.width, EditorGUIUtility.singleLineHeight);
                    var boxR = valR;
                    boxR.y = boxR.y - 2f;
                    boxR.x = boxR.x + EditorGUI.indentLevel * 10f;
                    boxR.height = boxR.height + 6f + ((EditorGUIUtility.singleLineHeight + padding) * (modifiersi + 1));
                    //bottombox
                    EditorGUI.DrawRect(boxR, new Color32(255, 255, 255, 100));
                    EditorGUI.LabelField(valR, "Value Modifiers");
                    for (int i = 0; i < modifiersi; i++)
                    {
                        valR = new Rect(valR.xMin, valR.yMax + padding, valR.width, EditorGUIUtility.singleLineHeight);
                        var propsR = valR;
                        propsR.width = valR.width;
                        var valRBut = new Rect((propsR.width + 35f), valR.y, 20f, EditorGUIUtility.singleLineHeight);
                        thisSpValDrawer.OnGUI(propsR, thisModifiersProp.GetArrayElementAtIndex(i), new GUIContent(""));
                        if (GUI.Button(valRBut, "X"))
                        {
                            thisModifiersProp.DeleteArrayElementAtIndex(i);
                        }
                    }
                    var addBut = new Rect(valR.xMin, valR.yMax + padding, valR.width, EditorGUIUtility.singleLineHeight);
                    addBut.x = addBut.xMax - 35f;
                    addBut.width = 60f;
                    if (GUI.Button(addBut, "Add"))
                    {
                        thisModifiersProp.InsertArrayElementAtIndex(modifiersi);
                    }
                    thisModifiersProp.serializedObject.ApplyModifiedProperties();
                }

            }
            EditorGUI.indentLevel = startingIndent;
            EditorGUI.EndProperty();
        }

19 Source : CodeBoxControl.xaml.cs
with MIT License
from Abdesol

private static void LangTypePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is not CodeBoxControl ctrl || e.NewValue is not string) return;
            var lang = (string)e.NewValue;

            bool found = false;
            foreach(string i in LangList.Langs)
            {
                if(lang == i)
                {
                    found = true;
                    break;
                }
            }

            if (!found) throw new NotImplementedException("Language type not recognised");
            ctrl.langImg.Source = new BitmapImage(new Uri(@$"../Resources/Images/LangLogo/{LangList.list[LangList.Langs.IndexOf(lang)]}.png", UriKind.Relative));

        }

19 Source : DataBaseManager.cs
with MIT License
from Abdesol

public async Task<ObservableCollection<CodeBoxModel>> OrderCode(string order)
        {
            int ind = AllOrderKind.IndexOf(order);
            ObservableCollection<CodeBoxModel> lst;

            var currentCodes = AllCodes;

            if (ind > 2)
            {
                lst = new ObservableCollection<CodeBoxModel>();
                foreach (var code in currentCodes)
                {
                    if (code.langType == order) lst.Add(code);
                }
            }
            else
            {
                if (ind == 0) lst = new ObservableCollection<CodeBoxModel>(currentCodes.OrderBy(x => x.replacedle).ToList());
                else if (ind == 1) lst = new ObservableCollection<CodeBoxModel>(currentCodes.OrderBy(x => x.timestamp).ToList());
                else lst = AllCodes;

                if (ind == 0 || ind == 1) ChangeSort(AllOrderKind[ind]);
            }

            return lst;
        }

19 Source : DataBaseManager.cs
with MIT License
from Abdesol

public async Task<ObservableCollection<CodeBoxModel>> OrderCode(string order)
        {
            int ind = AllOrderKind.IndexOf(order);
            ObservableCollection<CodeBoxModel> lst;

            var currentCodes = AllCodes;

            if (ind > 2)
            {
                lst = new ObservableCollection<CodeBoxModel>();
                foreach (var code in currentCodes)
                {
                    if (code.Language == order) lst.Add(code);
                }
            }
            else
            {
                if (ind == 0) lst = new ObservableCollection<CodeBoxModel>(currentCodes.OrderBy(x => x.replacedle).ToList());
                else if (ind == 1) lst = new ObservableCollection<CodeBoxModel>(currentCodes.OrderBy(x => x.Timestamp).ToList());
                else lst = AllCodes;

                if (ind == 0 || ind == 1) ChangeSort(AllOrderKind[ind]);
            }

            return lst;
        }

19 Source : InputMappingAxisUtility.cs
with Apache License 2.0
from abist-co-ltd

private static void RemoveAxis(string axis)
        {
            EnsureInputManagerReference();

            SerializedProperty axesProperty = inputManagerreplacedet.FindProperty("m_Axes");

            RefreshLocalAxesList();

            // This loop accounts for multiple axes with the same name.
            while (AxisNames.Contains(axis))
            {
                int index = AxisNames.IndexOf(axis);
                axesProperty.DeleteArrayElementAtIndex(index);
                AxisNames.RemoveAt(index);
            }
        }

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

public static void BuildOneSpouseRoom(FarmHouse farmHouse, string name, int count)
        {

            NPC spouse = Game1.getCharacterFromName(name);
            Layer back = null;
            Layer buildings = null;
            Layer front = null;
            Layer alwaysFront = null;
            if (spouse != null || name == "")
            {
                if (farmHouse.owner.friendshipData[spouse.Name] != null && farmHouse.owner.friendshipData[spouse.Name].IsEngaged())
                    name = "";
                Map refurbishedMap;
                if (name == "")
                {
                    refurbishedMap = Helper.Content.Load<Map>("Maps\\" + farmHouse.Name + ((farmHouse.upgradeLevel == 0) ? "" : ((farmHouse.upgradeLevel == 3) ? "2" : string.Concat(farmHouse.upgradeLevel))) + "_marriage", ContentSource.GameContent);
                }
                else
                {
                    refurbishedMap = Helper.Content.Load<Map>("Maps\\spouseRooms", ContentSource.GameContent);
                }
                int indexInSpouseMapSheet = -1;

                if (roomIndexes.ContainsKey(name))
                {
                    back = refurbishedMap.GetLayer("Back");
                    buildings = refurbishedMap.GetLayer("Buildings");
                    front = refurbishedMap.GetLayer("Front");

                    indexInSpouseMapSheet = roomIndexes[name];
                    if(name == "Emily")
                    {
                        farmHouse.temporarySprites.RemoveAll((s) => s is EmilysParrot);

                        int offset = (1 + count) * 7 * 64;
                        Vector2 parrotSpot = new Vector2(2064f + offset, 160f);
                        int upgradeLevel = farmHouse.upgradeLevel;
                        if (upgradeLevel > 1)
                        {
                            parrotSpot = new Vector2(2448f + offset, 736f);
                        }
                        ModEntry.PMonitor.Log($"Building Emily's parrot at {parrotSpot}, spouse room count {count}, upgrade level {upgradeLevel}");
                        farmHouse.temporarySprites.Add(new EmilysParrot(parrotSpot));
                    }
                }
                else if (tmxSpouseRooms.ContainsKey(name))
                {

                    refurbishedMap = tmxSpouseRooms[name];
                    if (refurbishedMap == null)
                    {
                        ModEntry.PMonitor.Log($"Couldn't load TMX spouse room for spouse {name}", LogLevel.Error);
                        return;
                    }
                    try 
                    {
                        foreach(Layer l in refurbishedMap.Layers)
                        {
                            ModEntry.PMonitor.Log($"layer ID: {l.Id}");

                            if(l.Id != "Back" && l.Id.StartsWith("Back")){
                                back = l;
                                ModEntry.PMonitor.Log($"Using {l.Id} for back in TMX spouse room layers for spouse {name}.");
                            }
                            else if(back == null && l.Id == "Back"){
                                back = l;
                                ModEntry.PMonitor.Log($"Using {l.Id} for back in TMX spouse room layers for spouse {name}.");
                            }
                            else if(l.Id != "Buildings" && l.Id.StartsWith("Buildings"))
                            {
                                buildings = l;
                                ModEntry.PMonitor.Log($"Using {l.Id} for buildings in TMX spouse room layers for spouse {name}.");
                            }
                            else if(buildings == null && l.Id == "Buildings")
                            {
                                buildings = l;
                                ModEntry.PMonitor.Log($"Using {l.Id} for buildings in TMX spouse room layers for spouse {name}.");
                            }
                            else if (l.Id != "Front" && l.Id.StartsWith("Front"))
                            {
                                front = l;
                                ModEntry.PMonitor.Log($"Using {l.Id} for front in TMX spouse room layers for spouse {name}.");
                            }
                            else if(front == null && l.Id == "Front")
                            {
                                front = l;
                                ModEntry.PMonitor.Log($"Using {l.Id} for front in TMX spouse room layers for spouse {name}.");
                            }
                            else if (l.Id != "AlwaysFront" && l.Id.StartsWith("AlwaysFront"))
                            {
                                alwaysFront = l;
                                ModEntry.PMonitor.Log($"Using {l.Id} for alwaysFront in TMX spouse room layers for spouse {name}.");
                            }
                            else if(alwaysFront == null && l.Id == "AlwaysFront")
                            {
                                alwaysFront = l;
                                ModEntry.PMonitor.Log($"Using {l.Id} for alwaysFront in TMX spouse room layers for spouse {name}.");
                            }
                        }
                        if(back == null)
                            back = refurbishedMap.Layers[0];
                        if (buildings == null)
                            buildings = refurbishedMap.Layers[1];
                        if (front == null)
                            front = refurbishedMap.Layers[2];
                        if(alwaysFront == null && refurbishedMap.Layers.Count > 3)
                            alwaysFront = refurbishedMap.Layers[3]; 
                    }
                    catch(Exception ex)
                    {
                        ModEntry.PMonitor.Log($"Couldn't load TMX spouse room layers for spouse {name}. Exception: {ex}", LogLevel.Error);
                    }
                    ModEntry.PMonitor.Log($"Loaded TMX spouse room layers for spouse {name}.");

                    indexInSpouseMapSheet = 0;
                }
                else if(name != "")
                {
                    return;
                }


                Monitor.Log($"Building {name}'s room", LogLevel.Debug);

                int startx = 29;
                int ox = ModEntry.config.ExistingSpouseRoomOffsetX;
                int oy = ModEntry.config.ExistingSpouseRoomOffsetY;
                if (farmHouse.upgradeLevel > 1)
                {
                    ox += 6;
                    oy += 9;
                }

                Microsoft.Xna.Framework.Rectangle areaToRefurbish = new Microsoft.Xna.Framework.Rectangle(startx + 7 + ox + (7 * count), 1 + oy, 6, 9);

                Point mapReader;
                if (name == "")
                {
                    mapReader = new Point(areaToRefurbish.X, areaToRefurbish.Y);
                }
                else
                {
                    mapReader = new Point(indexInSpouseMapSheet % 5 * 6, indexInSpouseMapSheet / 5 * 9);
                }
                farmHouse.map.Properties.Remove("DayTiles");
                farmHouse.map.Properties.Remove("NightTiles");


                List<string> sheetNames = new List<string>();
                for (int i = 0; i < farmHouse.map.TileSheets.Count; i++)
                {
                    sheetNames.Add(farmHouse.map.TileSheets[i].Id);
                    //Monitor.Log($"tilesheet id: {farmHouse.map.TileSheets[i].Id}");
                }
                int unreplacedled = sheetNames.IndexOf("unreplacedled tile sheet");
                int floorsheet = sheetNames.IndexOf("walls_and_floors");
                int indoor = sheetNames.IndexOf("indoor");

                if (ModEntry.config.BuildAllSpousesRooms)
                {



                    for (int i = 0; i < 7; i++)
                    {
                        // bottom wall
                        farmHouse.setMapTileIndex(ox + startx + 7 + i + (count * 7), oy + 10, 165, "Front", indoor);
                        farmHouse.setMapTileIndex(ox + startx + 7 + i + (count * 7), oy + 11, 0, "Buildings", indoor);


                        farmHouse.removeTile(ox + startx + 6 + (7 * count), oy + 4 + i, "Back");

                        if (count % 2 == 0)
                        {
                            // vert hall
                            farmHouse.setMapTileIndex(ox + startx + 6 + (7 * count), oy + 4 + i, (i % 2 == 0 ? 352 : 336), "Back", floorsheet);
                            // horiz hall
                            farmHouse.setMapTileIndex(ox + startx + 7 + i + (count * 7), oy + 10, (i % 2 == 0 ? 336 : 352), "Back", floorsheet);
                        }
                        else
                        {
                            // vert hall
                            
                            farmHouse.setMapTileIndex(ox + startx + 6 + (7 * count), oy + 4 + i, (i % 2 == 0 ? 336 : 352), "Back", floorsheet);
                            // horiz hall
                            farmHouse.setMapTileIndex(ox + startx + 7 + i + (count * 7), oy + 10, (i % 2 == 0 ? 352 : 336), "Back", floorsheet);
                        }
                    }

                    for (int i = 0; i < 6; i++)
                    {
                        // top wall
                        farmHouse.setMapTileIndex(ox + startx + 7 + i + (count * 7), oy + 0, 2, "Buildings", indoor);
                    }

                    // vert wall
                    farmHouse.setMapTileIndex(ox + startx + 6 + (7 * count), oy + 0, 87, "Buildings", unreplacedled);
                    farmHouse.setMapTileIndex(ox + startx + 6 + (7 * count), oy + 1, 99, "Buildings", unreplacedled);
                    farmHouse.setMapTileIndex(ox + startx + 6 + (7 * count), oy + 2, 111, "Buildings", unreplacedled);
                    farmHouse.setMapTileIndex(ox + startx + 6 + (7 * count), oy + 3, 123, "Buildings", unreplacedled);
                    farmHouse.setMapTileIndex(ox + startx + 6 + (7 * count), oy + 4, 135, "Buildings", unreplacedled);

                }
                for (int x = 0; x < areaToRefurbish.Width; x++)
                {
                    for (int y = 0; y < areaToRefurbish.Height; y++)
                    {
                        //PMonitor.Log($"x {x}, y {y}", LogLevel.Debug);
                        if (back?.Tiles[mapReader.X + x, mapReader.Y + y] != null)
                        {
                            farmHouse.map.GetLayer("Back").Tiles[areaToRefurbish.X + x, areaToRefurbish.Y + y] = new StaticTile(farmHouse.map.GetLayer("Back"), farmHouse.map.GetTileSheet(back.Tiles[mapReader.X + x, mapReader.Y + y].TileSheet.Id), BlendMode.Alpha, back.Tiles[mapReader.X + x, mapReader.Y + y].TileIndex);
                            foreach (KeyValuePair<string, PropertyValue> prop in back.Tiles[mapReader.X + x, mapReader.Y + y].Properties)
                            {
                                farmHouse.setTileProperty(areaToRefurbish.X + x, areaToRefurbish.Y + y, "Back", prop.Key, prop.Value);
                            }
                        }
                        if (buildings?.Tiles[mapReader.X + x, mapReader.Y + y] != null)
                        {
                            farmHouse.map.GetLayer("Buildings").Tiles[areaToRefurbish.X + x, areaToRefurbish.Y + y] = new StaticTile(farmHouse.map.GetLayer("Buildings"), farmHouse.map.GetTileSheet(buildings.Tiles[mapReader.X + x, mapReader.Y + y].TileSheet.Id), BlendMode.Alpha, buildings.Tiles[mapReader.X + x, mapReader.Y + y].TileIndex);

                            foreach(KeyValuePair<string, PropertyValue> prop in buildings.Tiles[mapReader.X + x, mapReader.Y + y].Properties)
                            {
                                farmHouse.setTileProperty(areaToRefurbish.X + x, areaToRefurbish.Y + y, "Buildings", prop.Key, prop.Value);
                            }

                            typeof(GameLocation).GetMethod("adjustMapLightPropertiesForLamp", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(farmHouse, new object[] { buildings.Tiles[mapReader.X + x, mapReader.Y + y].TileIndex, areaToRefurbish.X + x, areaToRefurbish.Y + y, "Buildings" });
                        }
                        else
                        {
                            farmHouse.map.GetLayer("Buildings").Tiles[areaToRefurbish.X + x, areaToRefurbish.Y + y] = null;
                        }
                        if (y < areaToRefurbish.Height - 1 && front?.Tiles[mapReader.X + x, mapReader.Y + y] != null)
                        {
                            farmHouse.map.GetLayer("Front").Tiles[areaToRefurbish.X + x, areaToRefurbish.Y + y] = new StaticTile(farmHouse.map.GetLayer("Front"), farmHouse.map.GetTileSheet(front.Tiles[mapReader.X + x, mapReader.Y + y].TileSheet.Id), BlendMode.Alpha, front.Tiles[mapReader.X + x, mapReader.Y + y].TileIndex);
                            foreach (KeyValuePair<string, PropertyValue> prop in front.Tiles[mapReader.X + x, mapReader.Y + y].Properties)
                            {
                                farmHouse.setTileProperty(areaToRefurbish.X + x, areaToRefurbish.Y + y, "Front", prop.Key, prop.Value);
                            }
                            typeof(GameLocation).GetMethod("adjustMapLightPropertiesForLamp", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(farmHouse, new object[] { front.Tiles[mapReader.X + x, mapReader.Y + y].TileIndex, areaToRefurbish.X + x, areaToRefurbish.Y + y, "Front" });
                        }
                        else if (y < areaToRefurbish.Height - 1)
                        {
                            farmHouse.map.GetLayer("Front").Tiles[areaToRefurbish.X + x, areaToRefurbish.Y + y] = null;
                        }
                        if (y < areaToRefurbish.Height - 2 && alwaysFront?.Tiles[mapReader.X + x, mapReader.Y + y] != null)
                        {
                            if(farmHouse.map.GetLayer("AlwaysFront") == null)
                            {
                                farmHouse.map.AddLayer(new Layer("AlwaysFront", farmHouse.map, farmHouse.map.GetLayer("Front").LayerSize, farmHouse.map.GetLayer("Front").TileSize));

                            }
                            farmHouse.map.GetLayer("AlwaysFront").Tiles[areaToRefurbish.X + x, areaToRefurbish.Y + y] = new StaticTile(farmHouse.map.GetLayer("AlwaysFront"), farmHouse.map.GetTileSheet(alwaysFront.Tiles[mapReader.X + x, mapReader.Y + y].TileSheet.Id), BlendMode.Alpha, alwaysFront.Tiles[mapReader.X + x, mapReader.Y + y].TileIndex);
                            foreach (KeyValuePair<string, PropertyValue> prop in alwaysFront.Tiles[mapReader.X + x, mapReader.Y + y].Properties)
                            {
                                farmHouse.setTileProperty(areaToRefurbish.X + x, areaToRefurbish.Y + y, "AlwaysFront", prop.Key, prop.Value);
                            }
                            typeof(GameLocation).GetMethod("adjustMapLightPropertiesForLamp", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(farmHouse, new object[] { alwaysFront.Tiles[mapReader.X + x, mapReader.Y + y].TileIndex, areaToRefurbish.X + x, areaToRefurbish.Y + y, "AlwaysFront" });
                        }
                        else if (y < areaToRefurbish.Height - 2 && farmHouse.map.GetLayer("AlwaysFront") != null)
                        {
                            farmHouse.map.GetLayer("AlwaysFront").Tiles[areaToRefurbish.X + x, areaToRefurbish.Y + y] = null;
                        }
                        if (x == 4 && y == 4)
                        {
                            try
                            {
                                farmHouse.map.GetLayer("Back").Tiles[areaToRefurbish.X + x, areaToRefurbish.Y + y].Properties["NoFurniture"] = new PropertyValue("T");
                            }
                            catch (Exception ex)
                            {
                                Monitor.Log(ex.ToString());
                            }
                        }
                    }
                }

                if(name == "Sebastian" && Game1.netWorldState.Value.hasWorldStateID("sebastianFrogReal"))
                {
                    Monitor.Log("building Sebastian's terrarium");
                    Vector2 spot = new Vector2(startx + 8 + (7 * count) + ox, 7 + oy);
                    farmHouse.removeTile((int)spot.X, (int)spot.Y - 1, "Front");
                    farmHouse.removeTile((int)spot.X + 1, (int)spot.Y - 1, "Front");
                    farmHouse.removeTile((int)spot.X + 2, (int)spot.Y - 1, "Front");
                    farmHouse.temporarySprites.Add(new TemporaryAnimatedSprite
                    {
                        texture = Game1.mouseCursors,
                        sourceRect = new Microsoft.Xna.Framework.Rectangle(641, 1534, 48, 37),
                        animationLength = 1,
                        sourceRectStartingPos = new Vector2(641f, 1534f),
                        interval = 5000f,
                        totalNumberOfLoops = 9999,
                        position = spot * 64f + new Vector2(0f, -5f) * 4f,
                        scale = 4f,
                        layerDepth = (spot.Y + 2f + 0.1f) * 64f / 10000f
                    });
                    if (Game1.random.NextDouble() < 0.85)
                    {
                        Texture2D crittersText2 = Game1.temporaryContent.Load<Texture2D>("TileSheets\\critters");
                        farmHouse.TemporarySprites.Add(new SebsFrogs
                        {
                            texture = crittersText2,
                            sourceRect = new Microsoft.Xna.Framework.Rectangle(64, 224, 16, 16),
                            animationLength = 1,
                            sourceRectStartingPos = new Vector2(64f, 224f),
                            interval = 100f,
                            totalNumberOfLoops = 9999,
                            position = spot * 64f + new Vector2((float)((Game1.random.NextDouble() < 0.5) ? 22 : 25), (float)((Game1.random.NextDouble() < 0.5) ? 2 : 1)) * 4f,
                            scale = 4f,
                            flipped = (Game1.random.NextDouble() < 0.5),
                            layerDepth = (spot.Y + 2f + 0.11f) * 64f / 10000f,
                            Parent = farmHouse
                        });
                    }
                    if (!Game1.player.activeDialogueEvents.ContainsKey("sebastianFrog2") && Game1.random.NextDouble() < 0.5)
                    {
                        Texture2D crittersText3 = Game1.temporaryContent.Load<Texture2D>("TileSheets\\critters");
                        farmHouse.TemporarySprites.Add(new SebsFrogs
                        {
                            texture = crittersText3,
                            sourceRect = new Microsoft.Xna.Framework.Rectangle(64, 240, 16, 16),
                            animationLength = 1,
                            sourceRectStartingPos = new Vector2(64f, 240f),
                            interval = 150f,
                            totalNumberOfLoops = 9999,
                            position = spot * 64f + new Vector2(8f, 3f) * 4f,
                            scale = 4f,
                            layerDepth = (spot.Y + 2f + 0.11f) * 64f / 10000f,
                            flipped = (Game1.random.NextDouble() < 0.5),
                            pingPong = false,
                            Parent = farmHouse
                        });
                    }
                }

                /*
                List<string> sheets = new List<string>();
                for (int i = 0; i < farmHouse.map.TileSheets.Count; i++)
                {
                    sheets.Add(farmHouse.map.TileSheets[i].Id);
                }
                for (int i = 0; i < 7; i++)
                {

                    // vert floor ext
                    farmHouse.removeTile(ox + 42 + (7 * count), oy + 4 + i, "Back");
                    farmHouse.setMapTileIndex(ox + 42 + (7 * count), oy + 4 + i, farmHouse.getTileIndexAt(ox + 41 + (7 * count), oy + 4 + i, "Back"), "Back", sheets.IndexOf(farmHouse.getTileSheetIDAt(ox + 41 + (7 * count), oy + 4 + i, "Back")));
                }
                */
            }
        }

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

internal static void ExpandKidsRoom(FarmHouse farmHouse)
        {
            ModEntry.PMonitor.Log("Expanding kids room");

            //int extraWidth = Math.Max(ModEntry.config.ExtraCribs,0) * 3 + Math.Max(ModEntry.config.ExtraKidsRoomWidth, 0) + Math.Max(ModEntry.config.ExtraKidsBeds, 0) * 4;
            int extraWidth = Math.Max(ModEntry.config.ExtraKidsRoomWidth, 0);
            int roomWidth = 14;
            int height = 9;
            int startx = 15;
            int starty = 0;
            //int ox = ModEntry.config.ExistingKidsRoomOffsetX;
            int ox = 0;
            //int oy = ModEntry.config.ExistingKidsRoomOffsetY;
            int oy = 0;

            Map map = Helper.Content.Load<Map>("Maps\\" + farmHouse.Name + "2"+ (Misc.GetSpouses(farmHouse.owner,1).Count > 0? "_marriage":""), ContentSource.GameContent);

            List<string> sheets = new List<string>();
            for (int i = 0; i < map.TileSheets.Count; i++)
            {
                sheets.Add(map.TileSheets[i].Id);
            }

            List<int> backIndexes = new List<int>();
            List<int> frontIndexes = new List<int>();
            List<int> buildIndexes = new List<int>();
            List<int> backSheets = new List<int>();
            List<int> frontSheets = new List<int>();
            List<int> buildSheets = new List<int>();


            for (int i = 0; i < roomWidth * height; i++)
            {
                backIndexes.Add(getTileIndexAt(map, ox + startx + (i % roomWidth), oy + starty + (i / roomWidth), "Back"));
                backSheets.Add(sheets.IndexOf(getTileSheetIDAt(map, ox + startx + (i % roomWidth), oy + starty + (i / roomWidth), "Back")));
                frontIndexes.Add(getTileIndexAt(map, ox + startx + (i % roomWidth), oy + starty + (i / roomWidth), "Front"));
                frontSheets.Add(sheets.IndexOf(getTileSheetIDAt(map, ox + startx + (i % roomWidth), oy + starty + (i / roomWidth), "Front")));
                buildIndexes.Add(getTileIndexAt(map, ox + startx + (i % roomWidth), oy + starty + (i / roomWidth), "Buildings"));
                buildSheets.Add(sheets.IndexOf(getTileSheetIDAt(map, ox + startx + (i % roomWidth), oy + starty + (i / roomWidth), "Buildings")));
            }

            if(extraWidth > 0)
            {
                Monitor.Log("total width: " + (29 + ox + extraWidth));
                ExtendMap(farmHouse, 29 + ox + extraWidth);
            }

            int k = 0;

            if (ModEntry.config.ExtraKidsRoomWidth > 0)
            {
                for (int j = 0; j < ModEntry.config.ExtraKidsRoomWidth - 1; j++)
                {
                    k %= 3;
                    for (int i = 0; i < height; i++)
                    {
                        int x = roomWidth + j + ox + startx - 2;
                        int y = oy + starty + i; 
                        int xt = 4 + k;
                        int yt = i;

                        setupTile(x, y, xt, yt, farmHouse, frontIndexes, frontSheets, roomWidth, 0);
                        setupTile(x, y, xt, yt, farmHouse, buildIndexes, buildSheets, roomWidth, 1);
                        setupTile(x, y, xt, yt, farmHouse, backIndexes, backSheets, roomWidth, 2);
                    }
                    k++;
                }
                for (int i = 0; i < height; i++)
                {
                    int x = startx + roomWidth + ox + extraWidth - 3;
                    int y = oy + starty + i;
                    int xt = roomWidth - 2;
                    int yt = i;

                    setupTile(x, y, xt, yt, farmHouse, frontIndexes, frontSheets, roomWidth, 0);
                    setupTile(x, y, xt, yt, farmHouse, buildIndexes, buildSheets, roomWidth, 1);
                    setupTile(x, y, xt, yt, farmHouse, backIndexes, backSheets, roomWidth, 2);
                }
            }



            // far wall
            for (int i = 0; i < height; i++)
            {
                int x = startx + roomWidth + ox + extraWidth - 2;
                int y = oy + starty + i;
                int xt = roomWidth - 1;
                int yt = i;

                setupTile(x, y, xt, yt, farmHouse, frontIndexes, frontSheets, roomWidth, 0);
                setupTile(x, y, xt, yt, farmHouse, buildIndexes, buildSheets, roomWidth, 1);
                setupTile(x, y, xt, yt, farmHouse, backIndexes, backSheets, roomWidth, 2);
            }

            // bottom barrier
            for (int i = 0; i < extraWidth; i++)
            {
                int x = startx + roomWidth + ox + i;
                Tile tile = farmHouse.map.GetLayer("Buildings").PickTile(new Location(x * Game1.tileSize, (9 + oy) * Game1.tileSize), Game1.viewport.Size);
                if (tile == null || tile.TileIndex == -1)
                {
                    Monitor.Log($"Adding building tile at {startx + roomWidth + ox + i},{ 9 + oy}");
                    farmHouse.setMapTileIndex(x, 9 + oy, 0, "Buildings");
                }
            }

            Microsoft.Xna.Framework.Rectangle? crib_location = farmHouse.GetCribBounds();
            if(crib_location != null)
            {
                Monitor.Log($"Adding {Misc.GetExtraCribs()} cribs");
                for (int i = 1; i <= Misc.GetExtraCribs(); i++)
                {
                    Microsoft.Xna.Framework.Rectangle rect = new Microsoft.Xna.Framework.Rectangle(crib_location.Value.X + i * 3, crib_location.Value.Y, crib_location.Value.Width, crib_location.Value.Height); 
                    Monitor.Log($"Adding crib at {rect}");
                    Map override_map = Game1.game1.xTileContent.Load<Map>("Maps\\FarmHouse_Crib_" + farmHouse.cribStyle.Value);
                    HashSet<string> amo = Helper.Reflection.GetField<HashSet<string>>(farmHouse, "_appliedMapOverrides").GetValue();
                    amo.Remove($"crib{i + 1}");
                    Helper.Reflection.GetField<HashSet<string>>(farmHouse, "_appliedMapOverrides").SetValue(amo);
                    farmHouse.ApplyMapOverride(override_map, $"crib{i+1}", null, rect);
                }
            }
        }

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

public static void BuildSpouseRooms(FarmHouse farmHouse)
        {
            if (config.DisableCustomSpousesRooms)
                return;

            try
            {
                if(farmHouse is Cabin)
                {
                    Monitor.Log("BuildSpouseRooms for Cabin");
                }

                Farmer f = farmHouse.owner;
                if (f == null)
                    return;
                Misc.ResetSpouses(f);
                Monitor.Log("Building all spouse rooms");
                if (Misc.GetSpouses(f, 1).Count == 0 || farmHouse.upgradeLevel > 3)
                {
                    ModEntry.PMonitor.Log("No spouses");
                    farmHouse.showSpouseRoom();
                    return;
                }

                List<string> spousesWithRooms = new List<string>();

                foreach (string spouse in Misc.GetSpouses(f, 1).Keys)
                {
                    Monitor.Log($"checking {spouse} for spouse room");
                    if (roomIndexes.ContainsKey(spouse) || tmxSpouseRooms.ContainsKey(spouse))
                    {
                        Monitor.Log($"Adding {spouse} to list for spouse rooms");
                        spousesWithRooms.Add(spouse);
                    }
                }

                if (spousesWithRooms.Count == 0)
                {
                    ModEntry.PMonitor.Log("No spouses with rooms");
                    return;
                }

                spousesWithRooms = new List<string>(Misc.ReorderSpousesForRooms(spousesWithRooms));

                if (!spousesWithRooms.Any())
                    return;

                if (!ModEntry.config.BuildAllSpousesRooms)
                {
                    if (f.spouse != null && !f.friendshipData[f.spouse].IsEngaged() && (roomIndexes.ContainsKey(f.spouse) || tmxSpouseRooms.ContainsKey(f.spouse)))
                    {
                        Monitor.Log($"Building spouse room for official spouse {f.spouse}");
                        BuildOneSpouseRoom(farmHouse, f.spouse, -1);
                    }
                    else
                    {
                        Monitor.Log($"No spouse room for official spouse {f.spouse}, placing for {spousesWithRooms[0]} instead.");
                        BuildOneSpouseRoom(farmHouse, spousesWithRooms[0], -1);
                        spousesWithRooms = new List<string>(spousesWithRooms.Skip(1));
                    }
                    return;
                }

                Monitor.Log($"Building {spousesWithRooms.Count} additional spouse rooms");

                List<string> sheets = new List<string>();
                for (int i = 0; i < farmHouse.map.TileSheets.Count; i++)
                {
                    sheets.Add(farmHouse.map.TileSheets[i].Id);
                }
                int unreplacedled = sheets.IndexOf("unreplacedled tile sheet");
                int floorsheet = sheets.IndexOf("walls_and_floors");
                int indoor = sheets.IndexOf("indoor");

                Monitor.Log($"Map has sheets: {string.Join(", ", sheets)}");

                int startx = 29;

                int ox = ModEntry.config.ExistingSpouseRoomOffsetX;
                int oy = ModEntry.config.ExistingSpouseRoomOffsetY;
                if (farmHouse.upgradeLevel > 1)
                {
                    ox += 6;
                    oy += 9;
                }

                Monitor.Log($"Preliminary adjustments");

                for (int i = 0; i < 7; i++)
                {
                    farmHouse.setMapTileIndex(ox + startx + i, oy + 11, 0, "Buildings", indoor);
                    farmHouse.removeTile(ox + startx + i, oy + 9, "Front");
                    farmHouse.removeTile(ox + startx + i, oy + 10, "Buildings");
                    farmHouse.setMapTileIndex(ox + startx - 1 + i, oy + 10, 165, "Front", indoor);
                    farmHouse.removeTile(ox + startx + i, oy + 10, "Back");
                }
                for (int i = 0; i < 8; i++)
                {
                    farmHouse.setMapTileIndex(ox + startx - 1 + i, oy + 10, 165, "Front", indoor);
                }
                for (int i = 0; i < 10; i++)
                {
                    farmHouse.removeTile(ox + startx + 6, oy + 0 + i, "Buildings");
                    farmHouse.removeTile(ox + startx + 6, oy + 0 + i, "Front");
                }
                for (int i = 0; i < 7; i++)
                {
                    // horiz hall
                    farmHouse.setMapTileIndex(ox + startx + i, oy + 10, (i % 2 == 0 ? 352: 336), "Back", floorsheet);
                }


                for (int i = 0; i < 7; i++)
                {
                    //farmHouse.removeTile(ox + startx - 1, oy + 4 + i, "Back");
                    //farmHouse.setMapTileIndex(ox + 28, oy + 4 + i, (i % 2 == 0 ? 352 : ModEntry.config.HallTileEven), "Back", 0);
                }


                farmHouse.removeTile(ox + startx - 1, oy + 9, "Front");
                farmHouse.removeTile(ox + startx - 1, oy + 10, "Buildings");
                
                if(farmHouse.upgradeLevel > 1) 
                    farmHouse.setMapTileIndex(ox + startx - 1, oy + 10, 163, "Front", indoor);
                farmHouse.removeTile(ox + startx + 6, oy + 0, "Front");
                farmHouse.removeTile(ox + startx + 6, oy + 0, "Buildings");



                int count = -1;

                ExtendMap(farmHouse, ox + startx + 8 + (7* spousesWithRooms.Count));

                // remove and rebuild spouse rooms
                for (int j = 0; j < spousesWithRooms.Count; j++)
                {
                    farmHouse.removeTile(ox + startx + 6 + (7 * count), oy + 0, "Buildings");
                    for (int i = 0; i < 10; i++)
                    {
                        farmHouse.removeTile(ox + startx + 6 + (7 * count), oy + 1 + i, "Buildings");
                    }
                    BuildOneSpouseRoom(farmHouse, spousesWithRooms[j], count++);
                }

                Monitor.Log($"Building far wall");

                // far wall
                farmHouse.setMapTileIndex(ox + startx + 6 + (7 * count), oy + 0, 11, "Buildings", indoor);
                for (int i = 0; i < 10; i++)
                {
                    farmHouse.setMapTileIndex(ox + startx + 6 + (7 * count), oy + 1 + i, 68, "Buildings", indoor);
                }
                farmHouse.setMapTileIndex(ox + startx + 6 + (7 * count), oy + 10, 130, "Front", indoor);
            }
            catch (Exception ex)
            {
                Monitor.Log($"Failed in {nameof(BuildSpouseRooms)}:\n{ex}", LogLevel.Error);
            }
            farmHouse.getWalls();
            farmHouse.getFloors();
        }

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

public static Vector2 GetSpouseBedPosition(FarmHouse fh, List<string> allBedmates, string name)
        {
            int bedWidth = GetBedWidth(fh);
            Point bedStart = GetBedStart(fh);
            int x = 64 + (int)((allBedmates.IndexOf(name) + 1) / (float)(allBedmates.Count + 1) * (bedWidth - 1) * 64);
            return new Vector2(bedStart.X * 64 + x, bedStart.Y * 64 + ModEntry.bedSleepOffset - (GetTopOfHeadSleepOffset(name) * 4));
        }

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

public static Point GetSpouseBedEndPoint(FarmHouse fh, string name)
        {
            var bedSpouses = GetBedSpouses(fh);

            Point bedStart = fh.GetSpouseBed().GetBedSpot();
            int bedWidth = GetBedWidth();
            bool up = fh.upgradeLevel > 1;

            int x = (int)(bedSpouses.IndexOf(name) / (float)(bedSpouses.Count) * (bedWidth - 1));
            return new Point(bedStart.X + x, bedStart.Y);
        }

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

public static Vector2 GetSpouseBedPosition(FarmHouse fh, string name)
        {
            var allBedmates = GetBedSpouses(fh);

            Point bedStart = GetBedStart(fh);
            int x = 64 + (int)((allBedmates.IndexOf(name) + 1) / (float)(allBedmates.Count + 1) * (GetBedWidth() - 1) * 64);
            return new Vector2(bedStart.X * 64 + x, bedStart.Y * 64 + ModEntry.bedSleepOffset - (GetTopOfHeadSleepOffset(name) * 4));
        }

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

public static async void SeaMonsterSay(string speech)
        {
            foreach (char c in speech)
            {
                string s = c.ToString().ToUpper();
                if (seaMonsterSounds.ContainsKey(s))
                {
                    Game1.playSoundPitched("junimoMeep1", (seaMonsterSounds.Keys.ToList().IndexOf(s) / 26) * 2 - 1);
                }
                await Task.Delay(100);
            }
        }

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

public static void FarmHouse_performTenMinuteUpdate_Postfix(FarmHouse __instance, int timeOfDay)
        {
            try
            {
                if (__instance.owner == null)
                    return;

                List<string> mySpouses = Misc.GetSpouses(__instance.owner, 1).Keys.ToList();
                if (Game1.IsMasterGame && Game1.timeOfDay >= 2200 && Game1.IsMasterGame)
                {
                    int upgradeLevel = __instance.upgradeLevel;
                    List<string> roomSpouses = mySpouses.FindAll((s) => Maps.roomIndexes.ContainsKey(s) || Maps.tmxSpouseRooms.ContainsKey(s));
                    List<string> bedSpouses = mySpouses.FindAll((s) => ModEntry.config.RoommateRomance || !__instance.owner.friendshipData[s].RoommateMarriage);
                    foreach (NPC c in __instance.characters)
                    {
                        if (c.isMarried())
                        {
                            string spouseName = c.Name;

                            if (Misc.GetSpouses(Game1.player,1).ContainsKey(spouseName))
                            {
                                c.checkForMarriageDialogue(timeOfDay, __instance);
                            }

                            Point bedSpot;
                            if (timeOfDay >= 2200)
                            {
                                if (!bedSpouses.Contains(c.Name))
                                {
                                    if (!roomSpouses.Exists((n) => n == spouseName))
                                    {
                                        bedSpot = __instance.getRandomOpenPointInHouse(ModEntry.myRand);
                                    }
                                    else
                                    {
                                        int offset = roomSpouses.IndexOf(spouseName) * 7;
                                        Vector2 spot = (upgradeLevel == 1) ? new Vector2(32f, 5f) : new Vector2(38f, 14f);
                                        bedSpot = new Point((int)spot.X + offset, (int)spot.Y);
                                    }

                                }
                                else
                                {
                                    int bedWidth = Misc.GetBedWidth(__instance);
                                    bool up = upgradeLevel > 1;

                                    Point bedStart = __instance.GetSpouseBed().GetBedSpot();
                                    int x = 1 + (int)(bedSpouses.IndexOf(spouseName) / (float)(bedSpouses.Count) * (bedWidth - 1));
                                    bedSpot = new Point(bedStart.X + x, bedStart.Y);

                                }

                                c.controller = null;
                                if (c.Position != Misc.GetSpouseBedPosition(__instance, bedSpouses, c.Name) && (!Misc.IsInBed(__instance,c.GetBoundingBox()) || !Kissing.kissingSpouses.Contains(c.Name)))
                                {
                                    c.controller = new PathFindController(c, __instance, bedSpot, 0, new PathFindController.endBehavior(FarmHouse.spouseSleepEndFunction));
                                    if (c.controller.pathToEndPoint == null || !__instance.isTileOnMap(c.controller.pathToEndPoint.Last<Point>().X, c.controller.pathToEndPoint.Last<Point>().Y))
                                    {
                                        c.controller = null;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Monitor.Log($"Failed in {nameof(FarmHouse_performTenMinuteUpdate_Postfix)}:\n{ex}", LogLevel.Error);
            }
        }

19 Source : CultistMod.cs
with Apache License 2.0
from Aeolic

public static bool IsCultist(String playerName)
        {
            return CultistNameList.IndexOf(playerName) != -1;
        }

19 Source : TocManage.cs
with MIT License
from Aeroblast

void GetPlainStructHelper(List<string> urls, TocItem p, ref string[] plain, string intro = "")
        {
            foreach (TocItem i in p.children)
            {
                if (i.url != null)
                {
                    string u = i.url.Split('#')[0];
                    int index = urls.IndexOf(u);
                    if (index >= 0)
                    {
                        if (plain[index] == null)
                            plain[index] = intro + i.name.Replace("\"", "\\\"");
                    }
                }
                if (i.children != null)
                    GetPlainStructHelper(urls, i, ref plain, intro + i.name.Replace("\"","\\\"") + " > ");
            }
        }

19 Source : EpubBuilder.cs
with GNU General Public License v3.0
from Aeroblast

void SetCover()//等KindlePosToUri不再使用后 关系到xhtml相关变量
        {
            if (azw3.mobi_header.extMeta.id_value.ContainsKey(201))
            {
                string cover;
                int off = (int)azw3.mobi_header.extMeta.id_value[201];//CoverOffset
                if (azw3.mobi_header.first_res_index + off < azw3.section_count)
                    if (azw3.sections[azw3.mobi_header.first_res_index + off].type == "Image")
                    {
                        cover_name = AddImage(off, "Cover");

                        if (NeedCreateCoverDoreplacedent())
                        {
                            Log.log("[Info]Adding a cover doreplacedent.");

                            string t = File.ReadAllText("template\\template_cover.txt");
                            var (w, h) = Util.GetImageSize(imgs[img_names.IndexOf(cover_name)]);
                            cover = t.Replace("{❕image}", cover_name).Replace("{❕w}", w.ToString()).Replace("{❕h}", h.ToString());

                            string coverDoreplacedentName = "cover.xhtml";
                            if (renameXhtmlWithId)
                            {
                                var id = azw3.resc.spine.GetElementsByTagName("itemref")[0].Attributes.GetNamedItem("idref").Value;
                                coverDoreplacedentName = id + ".xhtml";
                            }
                            xhtml_names.Insert(0, coverDoreplacedentName);
                            XmlDoreplacedent cover_ = new XmlDoreplacedent();
                            cover_.LoadXml(cover);
                            xhtmls.Insert(0, cover_);
                            extraCoverDocAdded = true;
                        }

                    }
                return;
            }
            //if (azw3.mobi_header.extMeta.id_string.ContainsKey(129)){}
            Log.log("[Warn]No Cover!");
        }

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

public int RegisterPlayer(string name)
        {
            deadPlayers.Remove(name);
            if (!players.Contains(name))
                players.Add(name);

            return players.IndexOf(name);
        }

19 Source : Modules.cs
with BSD 3-Clause "New" or "Revised" License
from airzero24

public static byte[] Getreplacedembly(List<string> Chunks, int TotalChunks)
        {
            byte[] Finalreplacedembly = new byte[] { };
            try
            {
                byte[][] replacedemblyArray = new byte[TotalChunks][];
                foreach (string chunk in Chunks)
                {
                    int index = Chunks.IndexOf(chunk);
                    replacedemblyArray[index] = Convert.FromBase64String(chunk);
                }
                Finalreplacedembly = Combine(replacedemblyArray);
                return Finalreplacedembly;
            }
            catch
            {
                return Finalreplacedembly;
            }
        }

19 Source : Popup.cs
with GNU General Public License v3.0
from Albo1125

public void Display()
        {
            if (!cleanGameFibersRunning)
            {
                cleanGameFibers();
            }
            hasDisplayed = false;
            IndexOfGivenAnswer = -1;
            popupQueue.Add(this);
            if (fiber != null && popupFibersToDelete.Contains(fiber))
            {
                popupFibersToDelete.Remove(fiber);
            }
            Game.LogTrivial("Adding " + Popupreplacedle + " popup to queue.");
            fiber = new GameFiber(delegate
            {
                
                while (!ForceDisplay)
                {
                    GameFiber.Yield();
                    if (!CommonVariables.DisplayTime && !Game.IsPaused)
                    {
                        if (popupQueue.Count > 0 && popupQueue[0] == this)
                        {
                            break;
                        }
                        else if (popupQueue.Count == 0)
                        {
                            break;
                        }
                    }
                }

                CommonVariables.DisplayTime = true;
                if (PauseGame)
                {
                    Game.IsPaused = true;
                }
                if (showEnterConfirmation)
                {
                    popupLines.AddRange(("Press Enter to close.").WrapText(720, "Arial Bold", 15.0f, out PopupTextLineHeight));
                }
                isDisplaying = true;
                GameFiber.Sleep(Delay);
                popupQueue.Remove(this);
                Game.RawFrameRender += DrawPopup;
                Game.LogTrivial("Drawing " + Popupreplacedle + " popup message");

                timer.Restart();
                if (showEnterConfirmation)
                {
                    while (isDisplaying)
                    {
                        if (PauseGame)
                        {
                            Game.IsPaused = true;
                        }
                        GameFiber.Yield();
                        if (timer.ElapsedMilliseconds > 25000)
                        {
                            Game.DisplayNotification("A textbox is currently being shown in the centre of your screen. If you can't see it, RPH had an issue initializing with DirectX and your RPH console won't work either - ask for support on the RPH Discord (link at www.ragepluginhook.net");
                            timer.Restart();
                        }
                        if (Game.IsKeyDown(Keys.Enter))
                        {
                            Game.LogTrivial("ClosePopup is pressed");
                            Hide();
                            break;
                        }
                    }
                }

                else if (Answers != null && Answers.Count > 0)
                {
                    while (isDisplaying)
                    {
                        if (PauseGame)
                        {
                            Game.IsPaused = true;
                        }
                        GameFiber.Yield();
                        if (timer.ElapsedMilliseconds > 25000)
                        {
                            Game.DisplayNotification("A textbox is currently being shown in the centre of your screen. If you can't see it, RPH had an issue initializing with DirectX and your RPH console won't work either - ask for support on the RPH Discord (link at www.ragepluginhook.net");
                            timer.Restart();
                        }

                        if (Game.IsKeyDown(Keys.D1))
                        {
                            if (answersAsDisplayed.Count >= 1)
                            {
                                IndexOfGivenAnswer = Answers.IndexOf(answersAsDisplayed[0]);
                                Hide();

                            }
                        }
                        if (Game.IsKeyDown(Keys.D2))
                        {
                            if (answersAsDisplayed.Count >= 2)
                            {
                                IndexOfGivenAnswer = Answers.IndexOf(answersAsDisplayed[1]);
                                Hide();
                            }
                        }
                        if (Game.IsKeyDown(Keys.D3))
                        {
                            if (answersAsDisplayed.Count >= 3)
                            {
                                IndexOfGivenAnswer = Answers.IndexOf(answersAsDisplayed[2]);
                                Hide();
                            }
                        }
                        if (Game.IsKeyDown(Keys.D4))
                        {
                            if (answersAsDisplayed.Count >= 4)
                            {
                                IndexOfGivenAnswer = Answers.IndexOf(answersAsDisplayed[3]);
                                Hide();
                            }
                        }
                        if (Game.IsKeyDown(Keys.D5))
                        {
                            if (answersAsDisplayed.Count >= 5)
                            {
                                IndexOfGivenAnswer = Answers.IndexOf(answersAsDisplayed[4]);
                                Hide();
                            }
                        }
                        if (Game.IsKeyDown(Keys.D6))
                        {
                            if (answersAsDisplayed.Count >= 6)
                            {
                                IndexOfGivenAnswer = Answers.IndexOf(answersAsDisplayed[5]);
                                Hide();
                            }
                        }
                    }
                }
                timer.Stop();
            });
            fiber.Start();
            
            
        }

19 Source : SpeechHandler.cs
with GNU General Public License v3.0
from Albo1125

public static int DisplayAnswers(List<string> PossibleAnswers)
        {
            Game.FrameRender += DrawAnswerWindow;
            DisplayTime = true;
            Answers = PossibleAnswers;
            string AnswerGiven = "";
            Game.LocalPlayer.Character.IsPositionFrozen = true;
            
            GameFiber.StartNew(delegate
            {
                while (DisplayTime)
                {
                    GameFiber.Yield();
                    
                    if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownComputerCheck(Keys.D1))
                    {
                        if (Answers.Count >= 1)
                        {
                            AnswerGiven = Answers[0];

                        }
                    }
                    if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownComputerCheck(Keys.D2))
                    {
                        if (Answers.Count >= 2)
                        {
                            AnswerGiven = Answers[1];
                        }
                    }
                    if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownComputerCheck(Keys.D3))
                    {
                        if (Answers.Count >= 3)
                        {
                            AnswerGiven = Answers[2];
                        }
                    }
                    if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownComputerCheck(Keys.D4))
                    {
                        if (Answers.Count >= 4)
                        {
                            AnswerGiven = Answers[3];
                        }
                    }
                    if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownComputerCheck(Keys.D5))
                    {
                        if (Answers.Count >= 5)
                        {
                            AnswerGiven = Answers[4];
                        }
                    }
                }
            });
            while (AnswerGiven == "")
            {
                GameFiber.Yield();
                if (!DisplayTime) { break; }
            }

            DisplayTime = false;
            Game.LocalPlayer.Character.IsPositionFrozen = false;

            return PossibleAnswers.IndexOf(AnswerGiven);


        }

19 Source : SpeechHandler.cs
with GNU General Public License v3.0
from Albo1125

public static int DisplayAnswers(List<string> PossibleAnswers, bool Shuffle=true)
        {
            Game.RawFrameRender += DrawAnswerWindow;
            DisplayTime = true;
            if (Shuffle)
            {
                Answers = new List<string>(PossibleAnswers.Shuffle());
            }
            else
            {
                Answers = new List<string>(PossibleAnswers);
            }
            
            string AnswerGiven = "";
            //Game.LocalPlayer.Character.IsPositionFrozen = true;
            
            GameFiber.StartNew(delegate
            {
                while (DisplayTime)
                {
                    GameFiber.Yield();
                    
                    if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownComputerCheck(Keys.D1))
                    {
                        if (Answers.Count >= 1)
                        {
                            AnswerGiven = Answers[0];
                            
                        }
                    }
                    if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownComputerCheck(Keys.D2))
                    {
                        if (Answers.Count >= 2)
                        {
                            AnswerGiven = Answers[1];
                        }
                    }
                    if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownComputerCheck(Keys.D3))
                    {
                        if (Answers.Count >= 3)
                        {
                            AnswerGiven = Answers[2];
                        }
                    }
                    if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownComputerCheck(Keys.D4))
                    {
                        if (Answers.Count >= 4)
                        {
                            AnswerGiven = Answers[3];
                        }
                    }
                    if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownComputerCheck(Keys.D5))
                    {
                        if (Answers.Count >= 5)
                        {
                            AnswerGiven = Answers[4];
                        }
                    }
                    if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownComputerCheck(Keys.D6))
                    {
                        if (Answers.Count >= 6)
                        {
                            AnswerGiven = Answers[5];
                        }
                    }
                }
            });
            NativeFunction.Natives.SET_PED_CAN_SWITCH_WEAPON(Game.LocalPlayer.Character, false);
            Vector3 PlayerPos = Game.LocalPlayer.Character.Position;
            float PlayerHeading = Game.LocalPlayer.Character.Heading;
            while (AnswerGiven == "")
            {
                GameFiber.Yield();
                if (Vector3.Distance(Game.LocalPlayer.Character.Position, PlayerPos) > 4f)
                {
                    Game.LocalPlayer.Character.Tasks.FollowNavigationMeshToPosition(PlayerPos, PlayerHeading, 1.2f).WaitForCompletion(1500);
                }
                if (Game.LocalPlayer.Character.IsInAnyVehicle(false))
                {
                    Game.LocalPlayer.Character.Tasks.LeaveVehicle(LeaveVehicleFlags.None).WaitForCompletion(1800);
                }
                if (!DisplayTime) { break; }
            }
            NativeFunction.Natives.SET_PED_CAN_SWITCH_WEAPON(Game.LocalPlayer.Character, true);
            DisplayTime = false;
            //Game.LocalPlayer.Character.IsPositionFrozen = false;
            
            return PossibleAnswers.IndexOf(AnswerGiven);


        }

19 Source : Menus.cs
with GNU General Public License v3.0
from Albo1125

private static void OnMenuClose(UIMenu sender)
        {
            if (OffenceCategoryMenus.Contains(sender))
            {
                CurrentEnhancedTrafficStop.SelectedOffences.Clear();
                foreach (UIMenu men in OffenceCategoryMenus)
                {
                    foreach (UIMenuItem it in men.MenuItems)
                    {
                        if (it is UIMenuCheckboxItem)
                        {
                            if (((UIMenuCheckboxItem)it).Checked)
                            {
                                CurrentEnhancedTrafficStop.SelectedOffences.Add(CheckboxItems_Offences.FirstOrDefault(x => x.Item1 == it).Item2);
                            }
                        }
                    }
                }
                int fine = CurrentEnhancedTrafficStop.SelectedOffences.Sum(x => x.fine);
                fine = fine - (fine % 5);
                if (fine >  5000) { fine = 5000; }
                else if (fine < 5) { fine = 5; }

                FineItem.Index = fine / 5 - 1;
                int points = CurrentEnhancedTrafficStop.SelectedOffences.Sum(x => x.points);
                points = points - (points % Offence.pointincstep);
                if (points > Offence.maxpoints) { points = Offence.maxpoints; }
                else if (points < Offence.minpoints) { points = Offence.minpoints; }
                PointsItem.Index = PointsList.IndexOf(points.ToString());
                SeizeVehicleTicketCheckboxItem.Checked = CurrentEnhancedTrafficStop.SelectedOffences.Any(x => x.seizeVehicle);

            }
        }

19 Source : BuildObject.cs
with MIT License
from alee12131415

public int next_node(string trigger) {
            if (!trigger.Contains(trigger)) {
                Debug.LogWarning("Trigger does not exist in this node!");
            }
            return next_index[triggers.IndexOf(trigger)];
        }

19 Source : ModSelectorInput.cs
with MIT License
from amazingalek

public void Initialize(string option, string[] options)
		{
			_count = options.Length;
			_options = options.ToList();
			var index = _options.IndexOf(option);
			index = Math.Max(index, 0);
			SelectorElement.Initialize(index, options);
		}

19 Source : ServerForm.cs
with MIT License
from AmazingDM

protected void CreateComboBox(string name, string remark, List<string> values, Action<string> save, string value, int width = InputBoxWidth)
        {
            _controlLines++;

            var comboBox = new ComboBox
            {
                Location = new Point(120, ControlLineHeight * _controlLines),
                Name = $"{name}ComboBox",
                Size = new Size(width, 23),
                DrawMode = DrawMode.OwnerDrawFixed,
                DropDownStyle = ComboBoxStyle.DropDownList,
                FormattingEnabled = true
            };
            comboBox.Items.AddRange(values.ToArray());
            comboBox.SelectedIndex = values.IndexOf(value);
            comboBox.DrawItem += Utils.Utils.DrawCenterComboBox;
            _saveActions.Add(comboBox, o => save.Invoke((string) o));
            ConfigurationGroupBox.Controls.AddRange(
                new Control[]
                {
                    comboBox,
                    new Label
                    {
                        AutoSize = true,
                        Location = new Point(10, ControlLineHeight * _controlLines),
                        Name = $"{name}Label",
                        Size = new Size(56, 17),
                        Text = remark
                    }
                }
            );
        }

19 Source : ArgumentHelper.cs
with MIT License
from amazingalek

public string GetArgument(string name)
		{
			var index = _arguments.IndexOf($"-{name}");
			if (index == -1 || index >= _arguments.Count - 1)
			{
				return null;
			}
			return _arguments[index + 1];
		}

19 Source : ArgumentHelper.cs
with MIT License
from amazingalek

public void RemoveArgument(string argument)
		{
			if (HasArgument(argument))
			{
				var index = _arguments.IndexOf($"-{argument}");
				_arguments.RemoveRange(index, 2);
			}
		}

19 Source : BuildDeployWindow.cs
with MIT License
from anderm

private void OnGUI()
        {
            GUILayout.Space(GUISectionOffset);

            // Setup
            int buttonWidth_Quarter = Screen.width / 4;
            int buttonWidth_Half = Screen.width / 2;
            int buttonWidth_Full = Screen.width - 25;
            var locatorHasData = XdeGuestLocator.HasData;
            var locatorIsSearching = XdeGuestLocator.IsSearching;
            var xdeGuestIpAddress = XdeGuestLocator.GuestIpAddress;

            // Quick Options
            GUILayout.BeginVertical();
            GUILayout.Label("Quick Options");

            EditorGUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            EditorGUILayout.EndHorizontal();

            // Build & Run button...
            using (new EditorGUILayout.HorizontalScope())
            {
                GUILayout.FlexibleSpace();
                GUI.enabled = ShouldBuildSLNBeEnabled;

                if (GUILayout.Button((!locatorIsSearching && locatorHasData || HoloLensUsbConnected)
                    ? "Build SLN, Build APPX, then Install"
                    : "Build SLN, Build APPX",
                    GUILayout.Width(buttonWidth_Half - 20)))
                {
                    // Build SLN
                    EditorApplication.delayCall += () => { BuildAll(!locatorIsSearching && locatorHasData || HoloLensUsbConnected); };
                }

                GUI.enabled = true;

                if (GUILayout.Button("Open Player Settings", GUILayout.Width(buttonWidth_Quarter)))
                {
                    EditorApplication.ExecuteMenuItem("Edit/Project Settings/Player");
                }

                if (GUILayout.Button(string.IsNullOrEmpty(wsaCertPath) ? "Select Certificate" : wsaCertPath, GUILayout.Width(buttonWidth_Quarter)))
                {
                    string path = EditorUtility.OpenFilePanel("Select Certificate", Application.dataPath, "pfx");
                    wsaCertPath = path.Substring(path.LastIndexOf("/", StringComparison.Ordinal) + 1);

                    if (!string.IsNullOrEmpty(path))
                    {
                        CertificatePreplacedwordWindow.Show(path);
                    }
                    else
                    {
                        PlayerSettings.WSA.SetCertificate(string.Empty, string.Empty);
                    }
                }
            }

            GUILayout.EndVertical();

            // Build section
            GUILayout.BeginVertical();
            GUILayout.Label("SLN");

            EditorGUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            EditorGUILayout.EndHorizontal();

            // Build directory (and save setting, if it's changed)
            string curBuildDirectory = BuildDeployPrefs.BuildDirectory;
            string newBuildDirectory = EditorGUILayout.TextField(GUIHorizSpacer + "Build directory", curBuildDirectory);

            if (newBuildDirectory != curBuildDirectory)
            {
                BuildDeployPrefs.BuildDirectory = newBuildDirectory;
                curBuildDirectory = newBuildDirectory;
            }

            // Build SLN button
            using (new EditorGUILayout.HorizontalScope())
            {
                GUILayout.FlexibleSpace();

                float previousLabelWidth = EditorGUIUtility.labelWidth;

                // Generate C# Project References
                EditorGUIUtility.labelWidth = 105;
                bool generateReferenceProjects = EditorUserBuildSettings.wsaGenerateReferenceProjects;
                bool shouldGenerateProjects = EditorGUILayout.Toggle("Unity C# Projects", generateReferenceProjects);

                if (shouldGenerateProjects != generateReferenceProjects)
                {
                    EditorUserBuildSettings.wsaGenerateReferenceProjects = shouldGenerateProjects;
                }

                // Restore previous label width
                EditorGUIUtility.labelWidth = previousLabelWidth;

                GUI.enabled = ShouldOpenSLNBeEnabled;

                if (GUILayout.Button("Open SLN", GUILayout.Width(buttonWidth_Quarter)))
                {
                    // Open SLN
                    string slnFilename = Path.Combine(curBuildDirectory, PlayerSettings.productName + ".sln");

                    if (File.Exists(slnFilename))
                    {
                        var slnFile = new FileInfo(slnFilename);
                        Process.Start(slnFile.FullName);
                    }
                    else if (EditorUtility.DisplayDialog("Solution Not Found", "We couldn't find the solution. Would you like to Build it?", "Yes, Build", "No"))
                    {
                        // Build SLN
                        EditorApplication.delayCall += () => { BuildDeployTools.BuildSLN(curBuildDirectory); };
                    }
                }

                GUI.enabled = ShouldBuildSLNBeEnabled;

                if (GUILayout.Button("Build Visual Studio SLN", GUILayout.Width(buttonWidth_Half)))
                {
                    // Build SLN
                    EditorApplication.delayCall += () => { BuildDeployTools.BuildSLN(curBuildDirectory); };
                }

                GUI.enabled = true;
            }

            // Appx sub-section
            GUILayout.BeginVertical();
            GUILayout.Label("APPX");

            // SDK and MS Build Version(and save setting, if it's changed)
            string curMSBuildVer = BuildDeployPrefs.MsBuildVersion;
            string currentSDKVersion = EditorUserBuildSettings.wsaUWPSDK;

            int currentSDKVersionIndex = 0;
            int defaultMSBuildVersionIndex = 0;

            for (var i = 0; i < windowsSdkPaths.Length; i++)
            {
                if (string.IsNullOrEmpty(currentSDKVersion))
                {
                    currentSDKVersionIndex = windowsSdkPaths.Length - 1;
                }
                else
                {
                    if (windowsSdkPaths[i].Equals(currentSDKVersion))
                    {
                        currentSDKVersionIndex = i;
                    }

                    if (windowsSdkPaths[i].Equals("10.0.14393.0"))
                    {
                        defaultMSBuildVersionIndex = i;
                    }
                }
            }

            currentSDKVersionIndex = EditorGUILayout.Popup(GUIHorizSpacer + "SDK Version", currentSDKVersionIndex, windowsSdkPaths);

            string newSDKVersion = windowsSdkPaths[currentSDKVersionIndex];

            if (!newSDKVersion.Equals(currentSDKVersion))
            {
                EditorUserBuildSettings.wsaUWPSDK = newSDKVersion;
            }

            string newMSBuildVer = currentSDKVersionIndex <= defaultMSBuildVersionIndex ? BuildDeployTools.DefaultMSBuildVersion : "15.0";
            EditorGUILayout.LabelField(GUIHorizSpacer + "MS Build Version", newMSBuildVer);

            if (!newMSBuildVer.Equals(curMSBuildVer))
            {
                BuildDeployPrefs.MsBuildVersion = newMSBuildVer;
                curMSBuildVer = newMSBuildVer;
            }

            // Build config (and save setting, if it's changed)
            string curBuildConfigString = BuildDeployPrefs.BuildConfig;

            BuildConfigEnum buildConfigOption;
            if (curBuildConfigString.ToLower().Equals("master"))
            {
                buildConfigOption = BuildConfigEnum.MASTER;
            }
            else if (curBuildConfigString.ToLower().Equals("release"))
            {
                buildConfigOption = BuildConfigEnum.RELEASE;
            }
            else
            {
                buildConfigOption = BuildConfigEnum.DEBUG;
            }

            buildConfigOption = (BuildConfigEnum)EditorGUILayout.EnumPopup(GUIHorizSpacer + "Build Configuration", buildConfigOption);

            string newBuildConfig = buildConfigOption.ToString();

            if (newBuildConfig != curBuildConfigString)
            {
                BuildDeployPrefs.BuildConfig = newBuildConfig;
                curBuildConfigString = newBuildConfig;
            }

            // Build APPX button
            using (new EditorGUILayout.HorizontalScope())
            {
                GUILayout.FlexibleSpace();

                float previousLabelWidth = EditorGUIUtility.labelWidth;

                // Force rebuild
                EditorGUIUtility.labelWidth = 50;
                bool curForceRebuildAppx = BuildDeployPrefs.ForceRebuild;
                bool newForceRebuildAppx = EditorGUILayout.Toggle("Rebuild", curForceRebuildAppx);

                if (newForceRebuildAppx != curForceRebuildAppx)
                {
                    BuildDeployPrefs.ForceRebuild = newForceRebuildAppx;
                    curForceRebuildAppx = newForceRebuildAppx;
                }

                // Increment version
                EditorGUIUtility.labelWidth = 110;
                bool curIncrementVersion = BuildDeployPrefs.IncrementBuildVersion;
                bool newIncrementVersion = EditorGUILayout.Toggle("Increment version", curIncrementVersion);

                if (newIncrementVersion != curIncrementVersion)
                {
                    BuildDeployPrefs.IncrementBuildVersion = newIncrementVersion;
                    curIncrementVersion = newIncrementVersion;
                }

                // Restore previous label width
                EditorGUIUtility.labelWidth = previousLabelWidth;

                // Build APPX
                GUI.enabled = ShouldBuildAppxBeEnabled;

                if (GUILayout.Button("Build APPX from SLN", GUILayout.Width(buttonWidth_Half)))
                {
                    // Open SLN
                    string slnFilename = Path.Combine(curBuildDirectory, PlayerSettings.productName + ".sln");

                    if (File.Exists(slnFilename))
                    {
                        // Build APPX
                        EditorApplication.delayCall += () =>
                            BuildDeployTools.BuildAppxFromSLN(
                                PlayerSettings.productName,
                                curMSBuildVer,
                                curForceRebuildAppx,
                                curBuildConfigString,
                                curBuildDirectory,
                                curIncrementVersion);
                    }
                    else if (EditorUtility.DisplayDialog("Solution Not Found", "We couldn't find the solution. Would you like to Build it?", "Yes, Build", "No"))
                    {
                        // Build SLN then APPX
                        EditorApplication.delayCall += () => BuildAll(install: false);
                    }
                }

                GUI.enabled = true;
            }

            GUILayout.EndVertical();
            GUILayout.EndVertical();

            GUILayout.Space(GUISectionOffset);

            // Deploy section
            GUILayout.BeginVertical();
            GUILayout.Label("Deploy");

            // Target IPs (and save setting, if it's changed)
            string curTargetIps = BuildDeployPrefs.TargetIPs;
            if (!LocalIPsOnly)
            {
                string newTargetIPs = EditorGUILayout.TextField(
                    new GUIContent(GUIHorizSpacer + "IP Address(es)", "IP(s) of target devices (e.g. 127.0.0.1;10.11.12.13)"),
                    curTargetIps);

                if (newTargetIPs != curTargetIps)
                {
                    BuildDeployPrefs.TargetIPs = newTargetIPs;
                    curTargetIps = newTargetIPs;
                }
            }
            else
            {
                // Queue up a repaint if we're still busy, or we'll get stuck
                // in a disabled state.

                if (locatorIsSearching)
                {
                    Repaint();
                }

                var addressesToPresent = new List<string> { "127.0.0.1" };

                if (!locatorIsSearching && locatorHasData)
                {
                    addressesToPresent.Add(xdeGuestIpAddress.ToString());
                }

                var previouslySavedAddress = addressesToPresent.IndexOf(curTargetIps);

                if (previouslySavedAddress == -1)
                {
                    previouslySavedAddress = 0;
                }

                EditorGUILayout.BeginHorizontal();

                if (locatorIsSearching && !locatorHasData)
                {
                    GUI.enabled = false;
                }

                var selectedAddressIndex = EditorGUILayout.Popup(GUIHorizSpacer + "IP Address", previouslySavedAddress, addressesToPresent.ToArray());

                if (GUILayout.Button(locatorIsSearching ? "Searching" : "Refresh", GUILayout.Width(buttonWidth_Quarter)))
                {
                    UpdateXdeStatus();
                }

                GUI.enabled = true;
                EditorGUILayout.EndHorizontal();

                var selectedAddress = addressesToPresent[selectedAddressIndex];

                if (curTargetIps != selectedAddress && !locatorIsSearching)
                {
                    BuildDeployPrefs.TargetIPs = selectedAddress;
                }
            }

            // Username/Preplacedword (and save seeings, if changed)
            string curUsername = BuildDeployPrefs.DeviceUser;
            string newUsername = EditorGUILayout.TextField(GUIHorizSpacer + "Username", curUsername);
            string curPreplacedword = BuildDeployPrefs.DevicePreplacedword;
            string newPreplacedword = EditorGUILayout.PreplacedwordField(GUIHorizSpacer + "Preplacedword", curPreplacedword);
            bool curFullReinstall = BuildDeployPrefs.FullReinstall;
            bool newFullReinstall = EditorGUILayout.Toggle(
                new GUIContent(GUIHorizSpacer + "Uninstall first", "Uninstall application before installing"), curFullReinstall);

            if (newUsername != curUsername ||
                newPreplacedword != curPreplacedword ||
                newFullReinstall != curFullReinstall)
            {
                BuildDeployPrefs.DeviceUser = newUsername;
                BuildDeployPrefs.DevicePreplacedword = newPreplacedword;
                BuildDeployPrefs.FullReinstall = newFullReinstall;
            }

            // Build list (with install buttons)
            if (builds.Count == 0)
            {
                GUILayout.Label(GUIHorizSpacer + "*** No builds found in build directory", EditorStyles.boldLabel);
            }
            else
            {
                GUILayout.BeginVertical();
                scrollPosition = GUILayout.BeginScrollView(scrollPosition, GUILayout.Width(buttonWidth_Full), GUILayout.Height(128));

                foreach (var fullBuildLocation in builds)
                {
                    int lastBackslashIndex = fullBuildLocation.LastIndexOf("\\", StringComparison.Ordinal);

                    var directoryDate = Directory.GetLastWriteTime(fullBuildLocation).ToString("yyyy/MM/dd HH:mm:ss");
                    string packageName = fullBuildLocation.Substring(lastBackslashIndex + 1);

                    EditorGUILayout.BeginHorizontal();
                    GUILayout.Space(GUISectionOffset + 15);

                    GUI.enabled = (!locatorIsSearching && locatorHasData || HoloLensUsbConnected);
                    if (GUILayout.Button("Install", GUILayout.Width(120.0f)))
                    {
                        string thisBuildLocation = fullBuildLocation;
                        string[] ipList = ParseIPList(curTargetIps);
                        EditorApplication.delayCall += () =>
                        {
                            InstallAppOnDevicesList(thisBuildLocation, ipList);
                        };
                    }

                    GUI.enabled = true;

                    GUILayout.Space(5);
                    GUILayout.Label(packageName + " (" + directoryDate + ")");
                    EditorGUILayout.EndHorizontal();
                }
                GUILayout.EndScrollView();
                GUILayout.EndVertical();

                EditorGUILayout.Separator();
            }

            GUILayout.EndVertical();
            GUILayout.Space(GUISectionOffset);

            // Utilities section
            GUILayout.BeginVertical();
            GUILayout.Label("Utilities");

            // Open AppX packages location
            using (new EditorGUILayout.HorizontalScope())
            {
                GUI.enabled = builds.Count > 0;

                GUILayout.FlexibleSpace();

                if (GUILayout.Button("Open APPX Packages Location", GUILayout.Width(buttonWidth_Full)))
                {
                    Process.Start("explorer.exe", "/open," + Path.GetFullPath(curBuildDirectory + "/" + PlayerSettings.productName + "/AppPackages"));
                }

                GUI.enabled = true;
            }

            // Open web portal
            using (new EditorGUILayout.HorizontalScope())
            {
                GUI.enabled = ShouldWebPortalBeEnabled && (!locatorIsSearching && locatorHasData || HoloLensUsbConnected);
                GUILayout.FlexibleSpace();

                if (GUILayout.Button("Open Device Portal", GUILayout.Width(buttonWidth_Full)))
                {
                    OpenWebPortalForIPs(curTargetIps);
                }

                GUI.enabled = true;
            }

            // Launch app..
            using (new EditorGUILayout.HorizontalScope())
            {
                GUI.enabled = ShouldLaunchAppBeEnabled && (!locatorIsSearching && locatorHasData || HoloLensUsbConnected);
                GUILayout.FlexibleSpace();

                if (GUILayout.Button("Launch Application", GUILayout.Width(buttonWidth_Full)))
                {
                    // If already running, kill it (button is a toggle)
                    if (IsAppRunning_FirstIPCheck(PlayerSettings.productName, curTargetIps))
                    {
                        KillAppOnIPs(curTargetIps);
                    }
                    else
                    {
                        LaunchAppOnIPs(curTargetIps);
                    }
                }

                GUI.enabled = true;
            }

            // Log file
            using (new EditorGUILayout.HorizontalScope())
            {
                GUI.enabled = ShouldLogViewBeEnabled && (!locatorIsSearching && locatorHasData || HoloLensUsbConnected);
                GUILayout.FlexibleSpace();

                if (GUILayout.Button("View Log File", GUILayout.Width(buttonWidth_Full)))
                {
                    OpenLogFileForIPs(curTargetIps);
                }

                GUI.enabled = true;
            }

            // Uninstall...
            using (new EditorGUILayout.HorizontalScope())
            {
                GUI.enabled = ShouldLogViewBeEnabled && (!locatorIsSearching && locatorHasData || HoloLensUsbConnected);
                GUILayout.FlexibleSpace();

                if (GUILayout.Button("Uninstall Application", GUILayout.Width(buttonWidth_Full)))
                {
                    EditorApplication.delayCall += () =>
                    {
                        UninstallAppOnDevicesList(ParseIPList(curTargetIps));
                    };
                }

                GUI.enabled = true;
            }

            //GUILayout.EndScrollView();
            GUILayout.EndVertical();
        }

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

public void RemoveOpened(string path)
        {
            int index = recent_files.IndexOf(path);

            if (index > -1)
            {
                recent_files.RemoveAt(index);

                ShowMenu();

                for (int i = 0; i < 12 && i < recent_files.Count; i++)
                {
                    General.Settings.WritePluginSetting("recentfiles" + i, recent_files[i]);
                }
            }
        }

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

public void AddOpened(string path)
        {
            int index = recent_files.IndexOf(path);

            if (index > -1)
            {
                recent_files.RemoveAt(index);
            }

            recent_files.Insert(0, path);

            ShowMenu();

            for (int i = 0; i < 12 && i < recent_files.Count; i++)
            {
                General.Settings.WritePluginSetting("recentfiles" + i, recent_files[i]);
            }
        }

19 Source : Program.cs
with MIT License
from anotherlab

static Operation ProcessArgs(List<string> args)
        {
            if (args.Contains("--help") || args.Contains("-?"))
                return Operation.Usage;

            if (args.Contains("--list-cameras") || args.Contains("-l"))
                return Operation.ListCameras;

            var nameArgIx = args.IndexOf("--camera-name");
            nameArgIx = nameArgIx != -1 ? nameArgIx : args.IndexOf("-n");
            if (nameArgIx != -1 && args.Count >= nameArgIx + 2)
            {
                _cameraName = args[nameArgIx + 1];
            }

            if (args.Contains("--focus-mode-manual") || args.Contains("-fm"))
                return Operation.ManualFocus;

            if (args.Contains("--focus-mode-auto") || args.Contains("-fa"))
                return Operation.AutoFocus;

            if (args.Contains("--exposure-mode-manual") || args.Contains("-em"))
                return Operation.ManualExposure;

            if (args.Contains("--exposure-mode-auto") || args.Contains("-ea"))
                return Operation.AutoExposure;

            var focusSetArgIx = args.IndexOf("--set-focus");
            focusSetArgIx = focusSetArgIx != -1 ? focusSetArgIx : args.IndexOf("-f");
            if (focusSetArgIx != -1 && args.Count >= focusSetArgIx + 2 && int.TryParse(args[focusSetArgIx + 1], out int focusVal))
            {
                _focusSetting = focusVal;
                return Operation.SetFocus;
            }

            var exposureSetArgIx = args.IndexOf("--set-exposure");
            exposureSetArgIx = exposureSetArgIx != -1 ? exposureSetArgIx : args.IndexOf("-e");
            if (exposureSetArgIx != -1 && args.Count >= exposureSetArgIx + 2 && int.TryParse(args[exposureSetArgIx + 1], out int expVal))
            {
                _exposureSetting = expVal;
                return Operation.SetExposure;
            }

            return Operation.Usage;
        }

19 Source : Options.cs
with MIT License
from aolszowka

public int IndexOf (string item)            {return values.IndexOf (item);}

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

public bool Remove(string item)
        {
            var index = _stringListImplementation.IndexOf(item);
            if (index < 0)
            {
                return false;
            }

            _regexList.RemoveAt(index);
            _stringListImplementation.RemoveAt(index);

            return true;
        }

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

public int IndexOf(string item)
        {
            return _stringListImplementation.IndexOf(item);
        }

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

private static async Task<(int, string)> ShowAttributeSelectionWindow(List<TreeNode> selectedNodes, int selectedTipsCount, Window window, TreeNode tree)
        {
            if (selectedNodes.Count == 0)
            {
                return (1, "Name");
            }
            else
            {
                ChildWindow attributeSelectionWindow = new ChildWindow() { FontFamily = window.FontFamily, FontSize = window.FontSize, Icon = window.Icon, Width = 350, Height = 190, replacedle = "Select attribute...", WindowStartupLocation = WindowStartupLocation.CenterOwner, Background = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.FromRgb(231, 231, 231)), CanMaximizeMinimize = false, SizeToContent = SizeToContent.Height };

                Grid grd = new Grid() { Margin = new Avalonia.Thickness(10) };
                attributeSelectionWindow.Content = grd;
                grd.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));
                grd.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));
                grd.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));
                grd.RowDefinitions.Add(new RowDefinition(1, GridUnitType.Star));
                grd.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));
                grd.RowDefinitions.Add(new RowDefinition(1, GridUnitType.Star));
                grd.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));
                grd.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                grd.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));

                {
                    Grid header = new Grid();
                    header.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                    header.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));

                    header.Children.Add(new DPIAwareBox(GetIconCopy) { Width = 32, Height = 32, Margin = new Avalonia.Thickness(0, 0, 10, 0) });

                    TextBlock blk = new TextBlock() { Text = "Copy attribute", HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Left, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, Margin = new Avalonia.Thickness(0, 0, 0, 10), FontSize = 16, Foreground = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.FromRgb(0, 114, 178)) };
                    Grid.SetColumn(blk, 1);
                    header.Children.Add(blk);

                    Grid.SetColumnSpan(header, 2);
                    grd.Children.Add(header);
                }

                {
                    TextBlock blk = new TextBlock() { Text = selectedTipsCount.ToString() + " tip" + (selectedTipsCount != 1 ? "s" : "") + ", " + selectedNodes.Count + " node" + (selectedTipsCount != 1 ? "s" : "") + " selected", HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Left, Margin = new Avalonia.Thickness(0, 5, 0, 10), FontSize = 13, Foreground = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.FromRgb(102, 102, 102)) };
                    Grid.SetColumnSpan(blk, 2);
                    Grid.SetRow(blk, 1);
                    grd.Children.Add(blk);
                }

                {
                    TextBlock blk = new TextBlock() { Text = "Select attribute to copy:", FontSize = 14, Margin = new Avalonia.Thickness(0, 0, 0, 10), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
                    Grid.SetRow(blk, 3);
                    grd.Children.Add(blk);
                }

                {
                    TextBlock blk = new TextBlock() { Text = "Copy attribute at:", FontSize = 14, Margin = new Avalonia.Thickness(0, 0, 0, 10), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
                    Grid.SetRow(blk, 2);
                    grd.Children.Add(blk);
                }

                ComboBox nodeBox = new ComboBox() { Items = new List<string>() { "Internal nodes", "Tips", "All nodes" }, SelectedIndex = 1, Margin = new Avalonia.Thickness(5, 0, 0, 10), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, MinWidth = 150, FontSize = 14, HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Stretch };
                Grid.SetRow(nodeBox, 2);
                Grid.SetColumn(nodeBox, 1);
                grd.Children.Add(nodeBox);

                Grid buttonGrid = new Grid();
                Grid.SetColumnSpan(buttonGrid, 2);

                buttonGrid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                buttonGrid.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                buttonGrid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                buttonGrid.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                buttonGrid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));

                Button okButton = new Button() { HorizontalContentAlignment = Avalonia.Layout.HorizontalAlignment.Center, Width = 100, Content = new TextBlock() { Text = "OK", FontSize = 14, Foreground = Avalonia.Media.Brushes.Black } };
                okButton.Clreplacedes.Add("SideBarButton");
                Grid.SetColumn(okButton, 1);
                buttonGrid.Children.Add(okButton);

                Button cancelButton = new Button() { HorizontalContentAlignment = Avalonia.Layout.HorizontalAlignment.Center, Width = 100, Content = new TextBlock() { Text = "Cancel", FontSize = 14, Foreground = Avalonia.Media.Brushes.Black }, Foreground = Avalonia.Media.Brushes.Black };
                cancelButton.Clreplacedes.Add("SideBarButton");
                Grid.SetColumn(cancelButton, 3);
                buttonGrid.Children.Add(cancelButton);

                Grid.SetRow(buttonGrid, 5);
                grd.Children.Add(buttonGrid);

                bool result = false;

                okButton.Click += (s, e) =>
                {
                    result = true;
                    attributeSelectionWindow.Close();
                };

                cancelButton.Click += (s, e) =>
                {
                    attributeSelectionWindow.Close();
                };

                HashSet<string> attributes = new HashSet<string>();

                foreach (TreeNode node in selectedNodes)
                {
                    foreach (KeyValuePair<string, object> nodeAttribute in node.Attributes)
                    {
                        attributes.Add(nodeAttribute.Key);
                    }
                }

                List<string> attributesList = attributes.ToList();

                ComboBox attributeBox = new ComboBox() { Items = attributesList, SelectedIndex = Math.Max(attributesList.IndexOf("Name"), 0), Margin = new Avalonia.Thickness(5, 0, 0, 10), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, MinWidth = 150, FontSize = 14, HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Stretch };
                Grid.SetRow(attributeBox, 3);
                Grid.SetColumn(attributeBox, 1);
                grd.Children.Add(attributeBox);


                await attributeSelectionWindow.ShowDialog2(window);

                if (result)
                {
                    return (nodeBox.SelectedIndex, attributesList[attributeBox.SelectedIndex]);
                }
                else
                {
                    return (2, null);
                }
            }

        }

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

public static async void PerformAction(int actionIndex, TreeNode selection, MainWindow window, InstanceStateData stateData)
        {
            if (actionIndex <= 0)
            {
                string text = NWKA.WriteTree(selection, true);
                if (!text.EndsWith(";"))
                {
                    text += ";";
                }
                _ = Avalonia.Application.Current.Clipboard.SetTextAsync(text);
            }
            else if (actionIndex == 1)
            {
                List<TreeNode> selectedTips = window.SelectedNode.GetLeaves();

                ChildWindow attributeSelectionWindow = new ChildWindow() { FontFamily = window.FontFamily, FontSize = window.FontSize, Icon = window.Icon, Width = 350, Height = 190, replacedle = "Select attribute...", WindowStartupLocation = WindowStartupLocation.CenterOwner, Background = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.FromRgb(231, 231, 231)), CanMaximizeMinimize = false };

                Grid grd = new Grid() { Margin = new Avalonia.Thickness(10) };
                attributeSelectionWindow.Content = grd;
                grd.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));
                grd.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));
                grd.RowDefinitions.Add(new RowDefinition(1, GridUnitType.Star));
                grd.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));
                grd.RowDefinitions.Add(new RowDefinition(1, GridUnitType.Star));
                grd.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));
                grd.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                grd.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));

                {
					Grid header = new Grid();
					header.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
					header.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
					
					header.Children.Add(new DPIAwareBox(GetIcon) { Width = 32, Height = 32, Margin = new Avalonia.Thickness(0, 0, 10, 0) });
					
                    TextBlock blk = new TextBlock() { Text = "Copy attribute at tips", HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Left, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, Margin = new Avalonia.Thickness(0, 0, 0, 10), FontSize = 16, Foreground = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.FromRgb(0, 114, 178)) };
                    Grid.SetColumn(blk, 1);
					header.Children.Add(blk);
					
					Grid.SetColumnSpan(header, 2);
                    grd.Children.Add(header);
                }

                {
                    TextBlock blk = new TextBlock() { Text = selectedTips.Count + " tips selected.", HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Left, Margin = new Avalonia.Thickness(0, 5, 0, 10), FontSize = 13, Foreground = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.FromRgb(102, 102, 102)) };
                    Grid.SetColumnSpan(blk, 2);
                    Grid.SetRow(blk, 1);
                    grd.Children.Add(blk);
                }

                {
                    TextBlock blk = new TextBlock() { Text = "Select attribute to copy:", FontSize = 14, Margin = new Avalonia.Thickness(0, 0, 0, 10), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
                    Grid.SetRow(blk, 2);
                    grd.Children.Add(blk);
                }

                Grid buttonGrid = new Grid();
                Grid.SetColumnSpan(buttonGrid, 2);

                buttonGrid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                buttonGrid.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                buttonGrid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                buttonGrid.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                buttonGrid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));

                Button okButton = new Button() { HorizontalContentAlignment = Avalonia.Layout.HorizontalAlignment.Center, Width = 100, Content = new TextBlock() { Text = "OK", FontSize = 14, Foreground = Avalonia.Media.Brushes.Black } };
                okButton.Clreplacedes.Add("SideBarButton");
                Grid.SetColumn(okButton, 1);
                buttonGrid.Children.Add(okButton);

                Button cancelButton = new Button() { HorizontalContentAlignment = Avalonia.Layout.HorizontalAlignment.Center, Width = 100, Content = new TextBlock() { Text = "Cancel", FontSize = 14, Foreground = Avalonia.Media.Brushes.Black }, Foreground = Avalonia.Media.Brushes.Black };
                cancelButton.Clreplacedes.Add("SideBarButton");
                Grid.SetColumn(cancelButton, 3);
                buttonGrid.Children.Add(cancelButton);

                Grid.SetRow(buttonGrid, 4);
                grd.Children.Add(buttonGrid);

                bool result = false;

                okButton.Click += (s, e) =>
                {
                    result = true;
                    attributeSelectionWindow.Close();
                };

                cancelButton.Click += (s, e) =>
                {
                    attributeSelectionWindow.Close();
                };

                HashSet<string> attributes = new HashSet<string>();

                foreach (TreeNode node in selectedTips)
                {
                    foreach (KeyValuePair<string, object> attribute in node.Attributes)
                    {
                        attributes.Add(attribute.Key);
                    }
                }

                List<string> attributesList = attributes.ToList();

                ComboBox attributeBox = new ComboBox() { Items = attributesList, SelectedIndex = Math.Max(attributesList.IndexOf("Name"), 0), Margin = new Avalonia.Thickness(5, 0, 0, 10), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, MinWidth = 150, FontSize = 14, HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Stretch };
                Grid.SetRow(attributeBox, 2);
                Grid.SetColumn(attributeBox, 1);
                grd.Children.Add(attributeBox);


                await attributeSelectionWindow.ShowDialog2(window);

                if (result)
                {
                    string attributeName = attributesList[attributeBox.SelectedIndex];

                    List<string> attributeValues = new List<string>();

                    if (attributeName != null)
                    {
                        foreach (TreeNode node in selectedTips)
                        {
                            if (node.Attributes.TryGetValue(attributeName, out object attributeValue))
                            {
                                if (attributeValue is string attributeString)
                                {
                                    attributeValues.Add(attributeString);
                                }
                                else if (attributeValue is double attributeDouble)
                                {
                                    attributeValues.Add(attributeDouble.ToString(System.Globalization.CultureInfo.InvariantCulture));
                                }
                            }
                        }
                    }

                    if (attributeValues.Count > 0)
                    {
                        _ = Avalonia.Application.Current.Clipboard.SetTextAsync(attributeValues.Aggregate((a, b) => a + "\n" + b));
                    }
                }
            }
            else if (actionIndex == 2)
            {
                List<TreeNode> selectedTips = window.SelectedNode.GetChildrenRecursive();

                ChildWindow attributeSelectionWindow = new ChildWindow() { FontFamily = window.FontFamily, FontSize = window.FontSize, Icon = window.Icon, Width = 350, Height = 190, replacedle = "Select attribute...", WindowStartupLocation = WindowStartupLocation.CenterOwner, Background = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.FromRgb(231, 231, 231)), CanMaximizeMinimize = false };

                Grid grd = new Grid() { Margin = new Avalonia.Thickness(10) };
                attributeSelectionWindow.Content = grd;
                grd.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));
                grd.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));
                grd.RowDefinitions.Add(new RowDefinition(1, GridUnitType.Star));
                grd.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));
                grd.RowDefinitions.Add(new RowDefinition(1, GridUnitType.Star));
                grd.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));
                grd.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                grd.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));

                {
					Grid header = new Grid();
					header.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
					header.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
					
					header.Children.Add(new DPIAwareBox(GetIcon) { Width = 32, Height = 32, Margin = new Avalonia.Thickness(0, 0, 10, 0) });
					
                    TextBlock blk = new TextBlock() { Text = "Copy attribute at nodes", HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Left, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, Margin = new Avalonia.Thickness(0, 0, 0, 10), FontSize = 16, Foreground = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.FromRgb(0, 114, 178)) };
                    Grid.SetColumn(blk, 1);
					header.Children.Add(blk);
					
					Grid.SetColumnSpan(header, 2);
                    grd.Children.Add(header);
                }

                {
                    TextBlock blk = new TextBlock() { Text = selectedTips.Count + " nodes selected.", HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Left, Margin = new Avalonia.Thickness(0, 5, 0, 10), FontSize = 13, Foreground = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.FromRgb(102, 102, 102)) };
                    Grid.SetColumnSpan(blk, 2);
                    Grid.SetRow(blk, 1);
                    grd.Children.Add(blk);
                }

                {
                    TextBlock blk = new TextBlock() { Text = "Select attribute to copy:", FontSize = 14, Margin = new Avalonia.Thickness(0, 0, 0, 10), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
                    Grid.SetRow(blk, 2);
                    grd.Children.Add(blk);
                }

                Grid buttonGrid = new Grid();
                Grid.SetColumnSpan(buttonGrid, 2);

                buttonGrid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                buttonGrid.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                buttonGrid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                buttonGrid.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                buttonGrid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));

                Button okButton = new Button() { HorizontalContentAlignment = Avalonia.Layout.HorizontalAlignment.Center, Width = 100, Content = new TextBlock() { Text = "OK", FontSize = 14, Foreground = Avalonia.Media.Brushes.Black } };
                okButton.Clreplacedes.Add("SideBarButton");
                Grid.SetColumn(okButton, 1);
                buttonGrid.Children.Add(okButton);

                Button cancelButton = new Button() { HorizontalContentAlignment = Avalonia.Layout.HorizontalAlignment.Center, Width = 100, Content = new TextBlock() { Text = "Cancel", FontSize = 14, Foreground = Avalonia.Media.Brushes.Black }, Foreground = Avalonia.Media.Brushes.Black };
                cancelButton.Clreplacedes.Add("SideBarButton");
                Grid.SetColumn(cancelButton, 3);
                buttonGrid.Children.Add(cancelButton);

                Grid.SetRow(buttonGrid, 4);
                grd.Children.Add(buttonGrid);

                bool result = false;

                okButton.Click += (s, e) =>
                {
                    result = true;
                    attributeSelectionWindow.Close();
                };

                cancelButton.Click += (s, e) =>
                {
                    attributeSelectionWindow.Close();
                };

                HashSet<string> attributes = new HashSet<string>();

                foreach (TreeNode node in selectedTips)
                {
                    foreach (KeyValuePair<string, object> attribute in node.Attributes)
                    {
                        attributes.Add(attribute.Key);
                    }
                }

                List<string> attributesList = attributes.ToList();

                ComboBox attributeBox = new ComboBox() { Items = attributesList, SelectedIndex = Math.Max(attributesList.IndexOf("Name"), 0), Margin = new Avalonia.Thickness(5, 0, 0, 10), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, MinWidth = 150, FontSize = 14, HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Stretch };
                Grid.SetRow(attributeBox, 2);
                Grid.SetColumn(attributeBox, 1);
                grd.Children.Add(attributeBox);


                await attributeSelectionWindow.ShowDialog2(window);

                if (result)
                {
                    string attributeName = attributesList[attributeBox.SelectedIndex];

                    List<string> attributeValues = new List<string>();

                    if (attributeName != null)
                    {
                        foreach (TreeNode node in selectedTips)
                        {
                            if (node.Attributes.TryGetValue(attributeName, out object attributeValue))
                            {
                                if (attributeValue is string attributeString)
                                {
                                    attributeValues.Add(attributeString);
                                }
                                else if (attributeValue is double attributeDouble)
                                {
                                    attributeValues.Add(attributeDouble.ToString(System.Globalization.CultureInfo.InvariantCulture));
                                }
                            }
                        }
                    }

                    if (attributeValues.Count > 0)
                    {
                        _ = Avalonia.Application.Current.Clipboard.SetTextAsync(attributeValues.Aggregate((a, b) => a + "\n" + b));
                    }
                }
            }
        }

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

private async void CopySelectionButtonClicked(object sender, Avalonia.Interactivity.RoutedEventArgs e)
        {
            if (this.SelectedNode != null)
            {
                List<TreeNode> selectedTips = this.SelectedNode.GetLeaves();

                Window attributeSelectionWindow = new Window() { FontFamily = this.FontFamily, FontSize = this.FontSize, Icon = this.Icon, Width = 300, Height = 180, replacedle = "Select attribute...", WindowStartupLocation = WindowStartupLocation.CenterOwner }; ;

                Grid grd = new Grid() { Margin = new Avalonia.Thickness(10) };
                attributeSelectionWindow.Content = grd;

                grd.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));
                grd.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));
                grd.RowDefinitions.Add(new RowDefinition(1, GridUnitType.Star));
                grd.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));
                grd.RowDefinitions.Add(new RowDefinition(1, GridUnitType.Star));
                grd.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));

                {
                    TextBlock blk = new TextBlock() { Text = selectedTips.Count + " tips selected.", HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center, Margin = new Avalonia.Thickness(0, 0, 0, 10) };
                    grd.Children.Add(blk);
                }

                {
                    TextBlock blk = new TextBlock() { Text = "Select attribute to copy:", FontWeight = Avalonia.Media.FontWeight.Bold, FontSize = 15, Margin = new Avalonia.Thickness(0, 0, 0, 10) };
                    Grid.SetRow(blk, 1);
                    grd.Children.Add(blk);
                }

                Grid buttonGrid = new Grid();

                buttonGrid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                buttonGrid.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                buttonGrid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                buttonGrid.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                buttonGrid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));

                Button okButton = new Button() { HorizontalContentAlignment = Avalonia.Layout.HorizontalAlignment.Center, Width = 100, Content = "OK" };
                Grid.SetColumn(okButton, 1);
                buttonGrid.Children.Add(okButton);

                Button cancelButton = new Button() { HorizontalContentAlignment = Avalonia.Layout.HorizontalAlignment.Center, Width = 100, Content = "Cancel" };
                Grid.SetColumn(cancelButton, 3);
                buttonGrid.Children.Add(cancelButton);

                Grid.SetRow(buttonGrid, 5);
                grd.Children.Add(buttonGrid);

                bool result = false;

                okButton.Click += (s, e) =>
                {
                    result = true;
                    attributeSelectionWindow.Close();
                };

                cancelButton.Click += (s, e) =>
                {
                    attributeSelectionWindow.Close();
                };

                HashSet<string> attributes = new HashSet<string>();

                foreach (TreeNode node in selectedTips)
                {
                    foreach (KeyValuePair<string, object> attribute in node.Attributes)
                    {
                        attributes.Add(attribute.Key);
                    }
                }

                List<string> attributesList = attributes.ToList();

                ComboBox attributeBox = new ComboBox() { Items = attributesList, SelectedIndex = Math.Max(attributesList.IndexOf("Name"), 0), Margin = new Avalonia.Thickness(0, 0, 0, 10), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center };
                Grid.SetRow(attributeBox, 3);
                grd.Children.Add(attributeBox);


                await attributeSelectionWindow.ShowDialog2(this);

                if (result)
                {
                    string attributeName = attributesList[attributeBox.SelectedIndex];

                    List<string> attributeValues = new List<string>();

                    if (attributeName != null)
                    {
                        foreach (TreeNode node in selectedTips)
                        {
                            if (node.Attributes.TryGetValue(attributeName, out object attributeValue))
                            {
                                if (attributeValue is string attributeString)
                                {
                                    attributeValues.Add(attributeString);
                                }
                                else if (attributeValue is double attributeDouble)
                                {
                                    attributeValues.Add(attributeDouble.ToString(System.Globalization.CultureInfo.InvariantCulture));
                                }
                            }
                        }
                    }

                    if (attributeValues.Count > 0)
                    {
                        _ = Avalonia.Application.Current.Clipboard.SetTextAsync(attributeValues.Aggregate((a, b) => a + "\n" + b));
                    }
                }
            }
        }

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

public override void Execute(string command)
        {
            command = command.Trim();

            if (command.Equals("info", StringComparison.OrdinalIgnoreCase))
            {
                if (Program.SelectedNode != null)
                {
                    ConsoleWrapper.WriteLine();

                    if (Program.SelectedNode.Children.Count > 0)
                    {
                        ConsoleWrapper.WriteLine(new ConsoleTextSpan("  LCA of:\n", 2));
                    }
                    else
                    {
                        ConsoleWrapper.WriteLine(new ConsoleTextSpan("  Leaf node:\n", 2));
                    }

                    List<string> childNodeNames = Program.SelectedNode.GetNodeNames();

                    ConsoleWrapper.WriteList(from el in childNodeNames select new ConsoleTextSpan[] { new ConsoleTextSpan("\"" + el + "\"", 4, ConsoleColor.Blue) }, "    ");

                    if (Program.SelectedNode.Children.Count > 0)
                    {
                        ConsoleWrapper.WriteLine();
                        ConsoleWrapper.WriteLine(new ConsoleTextSpan("  Descendants:\n", 2));

                        List<TreeNode> nodes = Program.TransformedTree.GetChildrenRecursive();
                        ConsoleWrapper.WriteList(from el in Enumerable.Range(0, nodes.Count) where nodes[el].Parent == Program.SelectedNode select new ConsoleTextSpan[] { new ConsoleTextSpan("#" + el.ToString(), 4, ConsoleColor.Blue) }, "    ");
                    }
                   

                    List<ConsoleTextSpan> message = new List<ConsoleTextSpan>()
                    {
                        new ConsoleTextSpan("    Direct descendants: ", 4),
                        new ConsoleTextSpan(Program.SelectedNode.Children.Count.ToString() + "\n", 4, ConsoleColor.Cyan),
                        new ConsoleTextSpan("    Total descendants: ", 4),
                        new ConsoleTextSpan(Program.SelectedNode.GetChildrenRecursiveLazy().Count().ToString() + "\n", 4, ConsoleColor.Cyan),
                        new ConsoleTextSpan("    Descendant leaves: ", 4),
                        new ConsoleTextSpan(Program.SelectedNode.GetLeaves().Count.ToString() + "\n", 4, ConsoleColor.Cyan)
                    };

                    if (childNodeNames.Count > 0 && Program.SelectedNode.Children.Count > 0)
                    {
                        message.AddRange(new ConsoleTextSpan[]
                        {
                            new ConsoleTextSpan("    Defining children: ", 4),
                            new ConsoleTextSpan("\"" + childNodeNames[0] + "\" \"" + childNodeNames[^1] + "\"\n", 4, ConsoleColor.Cyan)
                        });
                    }

                    ConsoleWrapper.WriteLine();

                    if (Program.SelectedNode.Children.Count > 0)
                    {
                        ConsoleWrapper.WriteLine(message);
                    }
                }
                else
                {
                    ConsoleWrapper.WriteLine();
                    ConsoleWrapper.WriteLine(new ConsoleTextSpan("No node has been selected!", ConsoleColor.Red));
                    ConsoleWrapper.WriteLine();
                }
            }
            else if (command.StartsWith("select"))
            {
                if (Program.TransformedTree != null)
                {
                    string argument = command.Substring(6).Trim(' ', '\t');
                    if (!string.IsNullOrWhiteSpace(argument))
                    {
                        bool valid = false;

                        if (argument == "root")
                        {
                            valid = true;
                            Program.SelectedNode = Program.TransformedTree;

                            List<ConsoleTextSpan> message = new List<ConsoleTextSpan>()
                            {
                                new ConsoleTextSpan("  Selected root node\n", 2),
                                new ConsoleTextSpan("    Direct descendants: ", 4),
                                new ConsoleTextSpan(Program.SelectedNode.Children.Count.ToString() + "\n", 4, ConsoleColor.Cyan),
                                new ConsoleTextSpan("    Total descendants: ", 4),
                                new ConsoleTextSpan(Program.SelectedNode.GetChildrenRecursiveLazy().Count().ToString() + "\n", 4, ConsoleColor.Cyan),
                                new ConsoleTextSpan("    Descendant leaves: ", 4),
                                new ConsoleTextSpan(Program.SelectedNode.GetLeaves().Count.ToString() + "\n", 4, ConsoleColor.Cyan),
                            };

                            List<string> childNodeNames = Program.SelectedNode.GetNodeNames();

                            if (childNodeNames.Count > 0)
                            {
                                message.AddRange(new ConsoleTextSpan[]
                                {
                                    new ConsoleTextSpan("    Defining children: ", 4),
                                    new ConsoleTextSpan("\"" + childNodeNames[0] + "\" \"" + childNodeNames[^1] + "\"\n", 4, ConsoleColor.Cyan)
                                });
                            }

                            ConsoleWrapper.WriteLine();
                            ConsoleWrapper.WriteLine(message);
                        }
                        else if (argument.StartsWith("#"))
                        {
                            int index;
                            if (int.TryParse(argument.Substring(1).Trim(), out index))
                            {
                                int count = 0;
                                bool found = false;

                                foreach (TreeNode node in Program.TransformedTree.GetChildrenRecursiveLazy())
                                {
                                    if (count == index)
                                    {
                                        Program.SelectedNode = node;
                                        found = true;
                                        break;
                                    }
                                    count++;
                                }

                                if (found)
                                {
                                    valid = true;

                                    List<ConsoleTextSpan> message = new List<ConsoleTextSpan>()
                                    {
                                        new ConsoleTextSpan("  Selected node #" + index.ToString() + "\n", 2),
                                        new ConsoleTextSpan("    Direct descendants: ", 4),
                                        new ConsoleTextSpan(Program.SelectedNode.Children.Count.ToString() + "\n", 4, ConsoleColor.Cyan),
                                        new ConsoleTextSpan("    Total descendants: ", 4),
                                        new ConsoleTextSpan(Program.SelectedNode.GetChildrenRecursiveLazy().Count().ToString() + "\n", 4, ConsoleColor.Cyan),
                                        new ConsoleTextSpan("    Descendant leaves: ", 4),
                                        new ConsoleTextSpan(Program.SelectedNode.GetLeaves().Count.ToString() + "\n", 4, ConsoleColor.Cyan),
                                    };

                                    List<string> childNodeNames = Program.SelectedNode.GetNodeNames();

                                    if (childNodeNames.Count > 0)
                                    {
                                        message.AddRange(new ConsoleTextSpan[]
                                        {
                                    new ConsoleTextSpan("    Defining children: ", 4),
                                    new ConsoleTextSpan("\"" + childNodeNames[0] + "\" \"" + childNodeNames[^1] + "\"\n", 4, ConsoleColor.Cyan)
                                        });
                                    }

                                    ConsoleWrapper.WriteLine();
                                    ConsoleWrapper.WriteLine(message);
                                }
                            }
                            else
                            {
                                valid = false;
                            }
                        }
                        else
                        {
                            List<string> names = new List<string>();

                            int position = 0;

                            StringBuilder currentNameBuilder = new StringBuilder();

                            while (position < argument.Length)
                            {
                                while (position < argument.Length && argument[position] != '\"')
                                {
                                    position++;
                                }

                                position++;

                                while (position < argument.Length && argument[position] != '\"')
                                {
                                    currentNameBuilder.Append(argument[position]);
                                    position++;
                                }

                                position++;

                                if (currentNameBuilder.Length > 0)
                                {
                                    names.Add(currentNameBuilder.ToString());
                                    currentNameBuilder.Clear();
                                }
                            }


                            if (names.Count > 0)
                            {
                                TreeNode referenceTree = Program.TransformedTree;

                                List<string> actualNames = referenceTree.GetNodeNames();

                                List<string> fixedNames = new List<string>();

                                bool missedMatch = false;

                                for (int i = 0; i < names.Count; i++)
                                {
                                    string[] matches = (from el in actualNames where el.Equals(names[i], StringComparison.OrdinalIgnoreCase) select el).ToArray();

                                    if (matches.Length == 0)
                                    {
                                        missedMatch = true;
                                        break;
                                    }
                                    else if (matches.Length == 1)
                                    {
                                        fixedNames.Add(matches[0]);
                                    }
                                    else
                                    {
                                        int index = actualNames.IndexOf(names[i]);
                                        if (index >= 0)
                                        {
                                            fixedNames.Add(actualNames[index]);
                                        }
                                        else
                                        {
                                            missedMatch = true;
                                            break;
                                        }
                                    }
                                }


                                if (!missedMatch)
                                {
                                    valid = true;
                                    Program.SelectedNode = referenceTree.GetLastCommonAncestor(fixedNames);

                                    List<ConsoleTextSpan> message = new List<ConsoleTextSpan>()
                            {
                                new ConsoleTextSpan("  Selected LCA of " + fixedNames.Count + " nodes\n", 2),
                                new ConsoleTextSpan("    Direct descendants: ", 4),
                                new ConsoleTextSpan(Program.SelectedNode.Children.Count.ToString() + "\n", 4, ConsoleColor.Cyan),
                                new ConsoleTextSpan("    Total descendants: ", 4),
                                new ConsoleTextSpan(Program.SelectedNode.GetChildrenRecursiveLazy().Count().ToString() + "\n", 4, ConsoleColor.Cyan),
                                new ConsoleTextSpan("    Descendant leaves: ", 4),
                                new ConsoleTextSpan(Program.SelectedNode.GetLeaves().Count.ToString() + "\n", 4, ConsoleColor.Cyan),
                            };

                                    List<string> childNodeNames = Program.SelectedNode.GetNodeNames();

                                    if (childNodeNames.Count > 0)
                                    {
                                        message.AddRange(new ConsoleTextSpan[]
                                        {
                                    new ConsoleTextSpan("    Defining children: ", 4),
                                    new ConsoleTextSpan("\"" + childNodeNames[0] + "\" \"" + childNodeNames[^1] + "\"\n", 4, ConsoleColor.Cyan)
                                        });
                                    }

                                    ConsoleWrapper.WriteLine();
                                    ConsoleWrapper.WriteLine(message);
                                }
                            }
                        }

                        if (!valid)
                        {
                            ConsoleWrapper.WriteLine();
                            ConsoleWrapper.WriteLine(new ConsoleTextSpan("Invalid node selection!", ConsoleColor.Red));
                            ConsoleWrapper.WriteLine();
                        }

                    }
                    else
                    {
                        ConsoleWrapper.WriteLine();
                        ConsoleWrapper.WriteLine(new ConsoleTextSpan("You need to specify a node to select!", ConsoleColor.Red));
                        ConsoleWrapper.WriteLine();
                    }

                }
                else
                {
                    ConsoleWrapper.WriteLine();
                    ConsoleWrapper.WriteLine(new ConsoleTextSpan("No tree has been loaded!", ConsoleColor.Red));
                    ConsoleWrapper.WriteLine();
                }
            }
            else
            {
                ConsoleWrapper.WriteLine();
                ConsoleWrapper.WriteLine(new ConsoleTextSpan("Unknown action: " + command, ConsoleColor.Red));
                ConsoleWrapper.WriteLine();
            }
        }

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

internal static void SetSetting(string settingName, string settingValue)
        {
            switch (settingName)
            {
                case "AutosaveInterval":
                    if (string.IsNullOrEmpty(settingValue))
                    {
                        GlobalSettings.Settings.AutosaveInterval = new TimeSpan(0, 10, 0);
                    }
                    else
                    {
                        GlobalSettings.Settings.AutosaveInterval = TimeSpan.Parse(settingValue);
                    }
                    break;
                case "DragInterval":
                    if (string.IsNullOrEmpty(settingValue))
                    {
                        GlobalSettings.Settings.DragInterval = 250;
                    }
                    else
                    {
                        GlobalSettings.Settings.DragInterval = int.Parse(settingValue);
                    }
                    break;
                case "KeepRecentFilesFor":
                    if (string.IsNullOrEmpty(settingValue))
                    {
                        GlobalSettings.Settings.KeepRecentFilesFor = 30;
                    }
                    else
                    {
                        GlobalSettings.Settings.KeepRecentFilesFor = int.Parse(settingValue);
                    }
                    break;
                case "DrawTreeWhenOpened":
                    if (string.IsNullOrEmpty(settingValue))
                    {
                        GlobalSettings.Settings.DrawTreeWhenOpened = true;
                    }
                    else
                    {
                        GlobalSettings.Settings.DrawTreeWhenOpened = Convert.ToBoolean(settingValue);
                    }
                    break;
                case "ShowLegacyUpDownArrows":
                    if (string.IsNullOrEmpty(settingValue))
                    {
                        GlobalSettings.Settings.ShowLegacyUpDownArrows = false;
                    }
                    else
                    {
                        GlobalSettings.Settings.ShowLegacyUpDownArrows = Convert.ToBoolean(settingValue);
                    }
                    break;
                case "SelectionColour":
                    if (string.IsNullOrEmpty(settingValue))
                    {
                        GlobalSettings.Settings.SelectionColour = Colour.FromRgb(35, 127, 255);
                    }
                    else
                    {
                        GlobalSettings.Settings.SelectionColour = Colour.FromCSSString(settingValue) ?? Colour.FromRgb(35, 127, 255);
                    }
                    break;
                case "BackgroundColour":
                    if (string.IsNullOrEmpty(settingValue))
                    {
                        GlobalSettings.Settings.BackgroundColour = Colour.FromRgb(240, 244, 250);
                    }
                    else
                    {
                        GlobalSettings.Settings.BackgroundColour = Colour.FromCSSString(settingValue) ?? Colour.FromRgb(240, 244, 250);
                    }
                    break;
                case "ModuleRepositoryBaseUri":
                    if (string.IsNullOrEmpty(settingValue))
                    {
                        GlobalSettings.Settings.ModuleRepositoryBaseUri = GlobalSettings.DefaultModuleRepository;
                    }
                    else
                    {
                        GlobalSettings.Settings.ModuleRepositoryBaseUri = settingValue;
                    }
                    break;
                case "UpdateCheckMode":
                    if (string.IsNullOrEmpty(settingValue))
                    {
                        GlobalSettings.Settings.UpdateCheckMode = GlobalSettings.UpdateCheckModes.ProgramAndAllModules;
                    }
                    else
                    {
                        GlobalSettings.Settings.UpdateCheckMode = (GlobalSettings.UpdateCheckModes)Enum.Parse(typeof(GlobalSettings.UpdateCheckModes), settingValue);
                    }
                    break;
                case "InterfaceStyle":
                    if (string.IsNullOrEmpty(settingValue))
                    {
                        GlobalSettings.Settings.InterfaceStyle = Modules.IsMac ? InterfaceStyles.MacOSStyle : InterfaceStyles.WindowsStyle;
                    }
                    else
                    {
                        GlobalSettings.Settings.InterfaceStyle = (GlobalSettings.InterfaceStyles)Enum.Parse(typeof(GlobalSettings.InterfaceStyles), settingValue);
                    }
                    break;
                case "RibbonStyle":
                    if (string.IsNullOrEmpty(settingValue))
                    {
                        GlobalSettings.Settings.RibbonStyle = Modules.IsWindows ? RibbonStyles.Colourful : RibbonStyles.Grey;
                    }
                    else
                    {
                        GlobalSettings.Settings.RibbonStyle = (GlobalSettings.RibbonStyles)Enum.Parse(typeof(GlobalSettings.RibbonStyles), settingValue);
                    }
                    break;
                default:
                    {
                        bool found = false;

                        foreach (KeyValuePair<string, string> kvp in GlobalSettings.Settings.AdditionalSettingsList)
                        {
                            string name = kvp.Key;
                            string data = kvp.Value;

                            if (name == settingName)
                            {
                                string controlType = data.Substring(0, data.IndexOf(":"));
                                string controlParameters = data.Substring(data.IndexOf(":") + 1);

                                if (controlType == "CheckBox")
                                {
                                    bool defaultValue = Convert.ToBoolean(controlParameters);

                                    if (string.IsNullOrEmpty(settingValue))
                                    {
                                        GlobalSettings.Settings.AdditionalSettings[name] = defaultValue;
                                    }
                                    else
                                    {
                                        GlobalSettings.Settings.AdditionalSettings[name] = Convert.ToBoolean(settingValue);
                                    }
                                }
                                else if (controlType == "ComboBox")
                                {
                                    int defaultIndex = int.Parse(controlParameters.Substring(0, controlParameters.IndexOf("[")));
                                    controlParameters = controlParameters.Substring(controlParameters.IndexOf("["));

                                    List<string> items = System.Text.Json.JsonSerializer.Deserialize<List<string>>(controlParameters, Modules.DefaultSerializationOptions);

                                    if (string.IsNullOrEmpty(settingValue))
                                    {
                                        GlobalSettings.Settings.AdditionalSettings[name] = defaultIndex;
                                    }
                                    else
                                    {
                                        int index = items.IndexOf(settingValue);
                                        if (index < 0)
                                        {
                                            index = defaultIndex;
                                        }

                                        GlobalSettings.Settings.AdditionalSettings[name] = index;
                                    }
                                }
                                else if (controlType == "TextBox")
                                {
                                    string defaultValue = controlParameters;

                                    if (string.IsNullOrEmpty(settingValue))
                                    {
                                        GlobalSettings.Settings.AdditionalSettings[name] = defaultValue;
                                    }
                                    else
                                    {
                                        GlobalSettings.Settings.AdditionalSettings[name] = settingValue;
                                    }
                                }
                                else if (controlType == "NumericUpDown")
                                {
                                    double defaultValue = double.Parse(controlParameters.Substring(0, controlParameters.IndexOf("[")));

                                    if (string.IsNullOrEmpty(settingValue))
                                    {
                                        GlobalSettings.Settings.AdditionalSettings[name] = defaultValue;
                                    }
                                    else
                                    {
                                        GlobalSettings.Settings.AdditionalSettings[name] = double.Parse(settingValue, System.Globalization.CultureInfo.InvariantCulture);
                                    }
                                }
                                else if (controlType == "FileSize")
                                {
                                    long defaultValue = long.Parse(controlParameters);

                                    if (string.IsNullOrEmpty(settingValue))
                                    {
                                        GlobalSettings.Settings.AdditionalSettings[name] = defaultValue;
                                    }
                                    else
                                    {
                                        GlobalSettings.Settings.AdditionalSettings[name] = long.Parse(settingValue, System.Globalization.CultureInfo.InvariantCulture);
                                    }
                                }
                                else if (controlType == "Slider")
                                {
                                    double defaultValue = double.Parse(controlParameters.Substring(0, controlParameters.IndexOf("[")));
                                    if (string.IsNullOrEmpty(settingValue))
                                    {
                                        GlobalSettings.Settings.AdditionalSettings[name] = defaultValue;
                                    }
                                    else
                                    {
                                        GlobalSettings.Settings.AdditionalSettings[name] = double.Parse(settingValue, System.Globalization.CultureInfo.InvariantCulture);
                                    }
                                }
                                else if (controlType == "Font")
                                {
                                    string[] font = System.Text.Json.JsonSerializer.Deserialize<string[]>(controlParameters, Modules.DefaultSerializationOptions);

                                    VectSharp.Font fnt = new VectSharp.Font(new VectSharp.FontFamily(font[0]), double.Parse(font[1], System.Globalization.CultureInfo.InvariantCulture));

                                    if (string.IsNullOrEmpty(settingValue))
                                    {
                                        GlobalSettings.Settings.AdditionalSettings[name] = fnt;
                                    }
                                    else
                                    {
                                        string[] splitSettingValue = settingValue.Split(',');
                                        VectSharp.Font newFont = new VectSharp.Font(new VectSharp.FontFamily(splitSettingValue[0]), double.Parse(splitSettingValue[1], System.Globalization.CultureInfo.InvariantCulture));

                                        GlobalSettings.Settings.AdditionalSettings[name] = double.Parse(settingValue, System.Globalization.CultureInfo.InvariantCulture);
                                    }
                                }
                                else if (controlType == "Point")
                                {
                                    double[] point = System.Text.Json.JsonSerializer.Deserialize<double[]>(controlParameters, Modules.DefaultSerializationOptions);
                                    VectSharp.Point pt = new VectSharp.Point(point[0], point[1]);

                                    if (string.IsNullOrEmpty(settingValue))
                                    {
                                        GlobalSettings.Settings.AdditionalSettings[name] = pt;
                                    }
                                    else
                                    {
                                        string[] splitSettingValue = settingValue.Split(',');
                                        VectSharp.Point newPoint = new VectSharp.Point(double.Parse(splitSettingValue[0], System.Globalization.CultureInfo.InvariantCulture), double.Parse(splitSettingValue[1], System.Globalization.CultureInfo.InvariantCulture));

                                        GlobalSettings.Settings.AdditionalSettings[name] = newPoint;
                                    }
                                }
                                else if (controlType == "Colour")
                                {
                                    int[] colour = System.Text.Json.JsonSerializer.Deserialize<int[]>(controlParameters, Modules.DefaultSerializationOptions);

                                    VectSharp.Colour col = VectSharp.Colour.FromRgba((byte)colour[0], (byte)colour[1], (byte)colour[2], (byte)colour[3]);

                                    if (string.IsNullOrEmpty(settingValue))
                                    {
                                        GlobalSettings.Settings.AdditionalSettings[name] = col;
                                    }
                                    else
                                    {
                                        GlobalSettings.Settings.AdditionalSettings[name] = Colour.FromCSSString(settingValue) ?? col;
                                    }
                                }
                                else if (controlType == "Dash")
                                {
                                    double[] dash = System.Text.Json.JsonSerializer.Deserialize<double[]>(controlParameters, Modules.DefaultSerializationOptions);

                                    VectSharp.LineDash lineDash = new VectSharp.LineDash(dash[0], dash[1], dash[2]);

                                    if (string.IsNullOrEmpty(settingValue))
                                    {
                                        GlobalSettings.Settings.AdditionalSettings[name] = lineDash;
                                    }
                                    else
                                    {
                                        string[] splitSettingValue = settingValue.Split(',');
                                        VectSharp.LineDash newDash = new VectSharp.LineDash(double.Parse(splitSettingValue[0], System.Globalization.CultureInfo.InvariantCulture), double.Parse(splitSettingValue[1], System.Globalization.CultureInfo.InvariantCulture), double.Parse(splitSettingValue[2], System.Globalization.CultureInfo.InvariantCulture));

                                        GlobalSettings.Settings.AdditionalSettings[name] = newDash;
                                    }
                                }

                                found = true;
                                break;
                            }
                        }

                        if (!found)
                        {
                            throw new ArgumentException("There is no global setting named \"" + settingName + "\"!");
                        }
                    }
                    break;
            }
        }

19 Source : WristMenuButtons.cs
with MIT License
from ash-hat

private IEnumerable<Button> CreateButtons(Transform canvas)
		{
			var source = canvas.Find("Button_3_ReloadScene").gameObject;
			Button CreateButton(string posName, string name, string text, Func<Button, UnityAction> callbackFactory)
			{
				// Move down source button
				var posTransform = canvas.Find(posName);
				posTransform.position += BUTTON_PLACEMENT_DIFF * Vector3.down;

				// Create our button
				var dest = GameObject.Instantiate(source, posTransform.position, posTransform.rotation, posTransform.parent);
				dest.transform.position += BUTTON_PLACEMENT_DIFF * Vector3.up;
				dest.name = name;
				dest.GetComponentInChildren<Text>().text = text;

				// Destroy base button to remove persistent onClick listener & add our own
				var button = dest.GetComponent<Button>();
				Component.DestroyImmediate(button);
				button = dest.AddComponent<Button>();

				button.onClick.AddListener(callbackFactory(button));

				// Shift all base buttons below down
				var btnIndex = _baseButtons.IndexOf(posName);
				for (var i = btnIndex + 1; i < _baseButtons.Count; i++)
				{
					MoveButton(_baseButtons[i]);
				}

				return button;
			}

			void MoveButton(string posName)
			{
				var posTransform = canvas.Find(posName);
				posTransform.position += BUTTON_PLACEMENT_DIFF * Vector3.down;
			}

			// Add new buttons from top to bottom
			yield return CreateButton("Button_1_OptionsPanel", _ourButtons[0], $"Spawn {Plugin.Instance.NAME} Panel", SpawnPanel);
			yield return CreateButton("Button_3_ReloadScene", _ourButtons[1], _privacy.Text, PrivacySelector);
			yield return CreateButton("Button_9_BackToMainMenu", _ourButtons[2], DISCONNECT_TEXT, LeaveLobby);
		}

19 Source : Themes.cs
with MIT License
from Assistant

public static void LoadThemes()
        {
            loadedThemes.Clear();

            /*
             * Begin by loading local themes. We should always load these first.
             * I am doing loading here to prevent the LoadTheme function from becoming too crazy.
             */
            foreach (string localTheme in preInstalledThemes)
            {
                string location = $"Themes/{localTheme}.xaml";
                Uri local = new Uri(location, UriKind.Relative);

                ResourceDictionary localDictionary = new ResourceDictionary
                {
                    Source = local
                };

                /*
                 * Load any Waifus that come with these built-in themes, too.
                 * The format must be: Background.png and Sidebar.png as a subfolder with the same name as the theme name.
                 * For example: "Themes/Dark/Background.png", or "Themes/Ugly Kulu-Ya-Ku/Sidebar.png"
                 */
                Waifus waifus = new Waifus
                {
                    Background = GetImageFromEmbeddedResources(localTheme, "Background"),
                    Sidebar = GetImageFromEmbeddedResources(localTheme, "Sidebar")
                };

                Theme theme = new Theme(localTheme, localDictionary)
                {
                    Waifus = waifus
                };

                loadedThemes.Add(localTheme, theme);
            }

            // Load themes from Themes subfolder if it exists.
            if (Directory.Exists(ThemeDirectory))
            {
                foreach (string file in Directory.EnumerateFiles(ThemeDirectory))
                {
                    FileInfo info = new FileInfo(file);
                    string name = Path.GetFileNameWithoutExtension(info.Name);

                    if (info.Extension.ToLower().Equals(".mat"))
                    {
                        Theme theme = LoadZipTheme(ThemeDirectory, name, ".mat");
                        if (theme is null) continue;

                        AddOrModifyTheme(name, theme);
                    }
                }

                // Finally load any loose theme files in subfolders.
                foreach (string directory in Directory.EnumerateDirectories(ThemeDirectory))
                {
                    string name = directory.Split('\\').Last();
                    Theme theme = LoadTheme(directory, name);

                    if (theme is null) continue;
                    AddOrModifyTheme(name, theme);
                }
            }

            // Refresh Themes dropdown in Options screen.
            if (Options.Instance != null && Options.Instance.ApplicationThemeComboBox != null)
            {
                Options.Instance.ApplicationThemeComboBox.ItemsSource = LoadedThemes;
                Options.Instance.ApplicationThemeComboBox.SelectedIndex = LoadedThemes.IndexOf(LoadedTheme);
            }
        }

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

private static void getCode (string path, List<string> result) {
      using (var reader = new BinaryReader (File.OpenRead (path))) {
        try {
          uint code = reader.ReadUInt32 ();

          string hex = code.ToHexString ();

          if (result.IndexOf (hex) < 0)
            result.Add (hex);

        } catch (EndOfStreamException) { }
      }
    }

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

private static IEnumerable<string> getBytes () {
      var activationBytes = new List<String> ();
      var rk = getKey ();
      if (rk is null)
        rk = getKey (true);
      if (rk is null)
        return null;
   
      using (rk) {
        var valNames = rk.GetValueNames ();

        for (int i = valNames.Length - 1; i >= 0; i--) {
          bool succ = uint.TryParse (valNames[i], out uint k);
          if (!succ)
            continue;
          if (k > 8)
            continue;
          byte[] bytes = rk.GetValue (valNames[i]) as byte[];
          if (bytes is null || bytes.Length < 4)
            continue;
          uint val = BitConverter.ToUInt32 (bytes, 0);
          if (val == 0xffffffff)
            continue;

          string hex = val.ToHexString ();

          if (activationBytes.IndexOf (hex) < 0)
            activationBytes.Add (hex);
        }

        return activationBytes;
      }
    }

19 Source : ModuleDependencySolverFixture.cs
with MIT License
from AvaloniaCommunity

[TestMethod]
        public void CanSolveForest()
        {
            solver.AddModule("ModuleA");
            solver.AddModule("ModuleB");
            solver.AddModule("ModuleC");
            solver.AddModule("ModuleD");
            solver.AddModule("ModuleE");
            solver.AddModule("ModuleF");
            solver.AddDependency("ModuleC", "ModuleB");
            solver.AddDependency("ModuleB", "ModuleA");
            solver.AddDependency("ModuleE", "ModuleD");
            string[] result = solver.Solve();
            replacedert.AreEqual(6, result.Length);
            List<string> test = new List<string>(result);
            replacedert.IsTrue(test.IndexOf("ModuleA") < test.IndexOf("ModuleB"));
            replacedert.IsTrue(test.IndexOf("ModuleB") < test.IndexOf("ModuleC"));
            replacedert.IsTrue(test.IndexOf("ModuleD") < test.IndexOf("ModuleE"));
        }

19 Source : MainWindow.xaml.cs
with MIT License
from bayoen

private void LauncherWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            if (IsGoogleOn)
            {
                this.CheckLocalVersion();

                this.UpdatorTextBlock.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
                {
                    this.UpdatorTextBlock.Text += string.Format(" {0}", this.currentVersion.ToString());
                }));
                Thread.Sleep(1);

                #region CheckReleases::
                ok::GitHubClient client;
                ok::Release latest;
                bool nextBigVersionFlag = false;

                try
                {
                    client = new ok::GitHubClient(new ok::ProductHeaderValue("bayoen"));
                    //latest = client.Repository.Release.GetLatest("bayoen", "bayoen-star-exe").Result;

                    List<ok.Release> releases = client.Repository.Release.GetAll("bayoen", "bayoen-star-exe").Result.ToList();

                    int nextBigVersion = releases.FindIndex(x => Version.Parse(x.TagName.GetVersionNumbers()) >= new Version(0, 2));

                    if (nextBigVersion == 0)
                    {
                        latest = null;
                    }
                    else if (nextBigVersion > 0)
                    {
                        nextBigVersionFlag = true;
                        latest = releases[nextBigVersion - 1];
                    }
                    else
                    {
                        latest = releases.First();
                    }                    
                }
                catch
                {
                    latest = null;
                }

                if (latest == null)
                {                    
                    MessageBox.Show("We can't find any latest version", "Warning");
                    Environment.Exit(0);
                }
                else
                {
                    Version latestVersion = Version.Parse(latest.TagName.GetVersionNumbers());
                    
                    if (currentVersion <= latestVersion)
                    {
                        this.UpdatorTextBlock.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
                        {
                            this.UpdatorTextBlock.Text += string.Format(" to {0}...", latestVersion.ToString());
                            if (nextBigVersionFlag)
                            {
                                this.UpdatorTextBlock.Text += $"\nWe can not update modules to upper versions!\nPlease visit 'https://bayoen.github.io/star/'";
                            }
                        }));
                        Thread.Sleep(1);

                        List<string> fileNameList = new List<string>();
                        foreach (ok::Releasereplacedet replacedetToken in latest.replacedets)
                        {
                            using (System.Net.WebClient web = new System.Net.WebClient())
                            {
                                string url = replacedetToken.BrowserDownloadUrl;
                                string fileName = url.Split('/').Last();
                                web.DownloadFile(url, fileName);
                                fileNameList.Add(fileName);
                            }
                        }

                        List<string> UpdaterList = File.ReadAllText(coreListName, Encoding.UTF8).Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).ToList();

                        string rootPath = System.IO.Path.GetDirectoryName(System.Reflection.replacedembly.GetEntryreplacedembly().Location);
                        string updatingFolderPath = System.IO.Path.Combine(rootPath, updatingFolderName);
                        if (Directory.Exists(updatingFolderPath)) Directory.Delete(updatingFolderPath, true);
                        foreach (string fileNameToken in fileNameList)
                        {
                            if (fileNameToken.EndsWith(".zip", StringComparison.OrdinalIgnoreCase))
                            {
                                using (ZipArchive readingToken = ZipFile.Open(fileNameToken, ZipArchiveMode.Update))
                                {                                    
                                    readingToken.ExtractToDirectory(updatingFolderPath);
                                }
                                if (File.Exists(fileNameToken)) File.Delete(fileNameToken);
                            }
                        }

                        if (Directory.Exists(updatingFolderPath))
                        {
                            List<string> fileList = Directory.GetFiles(updatingFolderPath, "*.*", SearchOption.AllDirectories).ToList();
                            bool updaterFlag = fileList.Remove(System.IO.Path.Combine(updatingFolderPath, UpdatarName));

                            foreach (string filePath in fileList)
                            {
                                string token = filePath.Replace(updatingFolderPath + '\\', "");
                                if (UpdaterList.IndexOf(token) > -1) continue;

                                if (File.Exists(filePath))
                                {
                                    string targetPath = System.IO.Path.Combine(rootPath, System.IO.Path.GetFileName(filePath));
                                    if (File.Exists(targetPath))
                                    {
                                        File.SetAttributes(targetPath, FileAttributes.Normal);
                                        File.Delete(targetPath);
                                    }
                                    File.Move(filePath, targetPath);
                                }
                            }

                            if (!updaterFlag) Directory.Delete(updatingFolderPath);
                        }

                        File.WriteAllText(versionDataName, latestVersion.ToString());
                    }
                    else //if (currentVersion > latestVersion)
                    {
                        MessageBox.Show("Hm... we are doing well, right?", "Warning");
                    }
                }

                #endregion

                if (File.Exists(bayoenStarName)) Process.Start(bayoenStarName);
                Environment.Exit(0);
            }
            else
            {
                System.Media.SystemSounds.Hand.Play();
            }

        }

19 Source : ItemIconLine.cs
with GNU General Public License v3.0
from berichan

public Vector2 Select(string itemIdIfWeHaveIt)
    {
        int index = Items.IndexOf(itemIdIfWeHaveIt);
        if (index > 0)
            SelectButton(MenuIconButtons[index]);

        return GetComponent<RectTransform>().ancreplaceddPosition;
    }

19 Source : LuaFileUtils.cs
with MIT License
from bjfumac

public bool AddSearchPath(string path, bool front = false)
        {
            int index = searchPaths.IndexOf(path);

            if (index >= 0)
            {
                return false;
            }

            if (front)
            {
                searchPaths.Insert(0, path);
            }
            else
            {
                searchPaths.Add(path);
            }

            return true;
        }

19 Source : LuaFileUtils.cs
with MIT License
from bjfumac

public bool RemoveSearchPath(string path)
        {
            int index = searchPaths.IndexOf(path);

            if (index >= 0)
            {
                searchPaths.RemoveAt(index);
                return true;
            }

            return false;
        }

19 Source : JSONObject.cs
with MIT License
from bonzaiferroni

public void RemoveField(string name) {
		if(keys.IndexOf(name) > -1) {
			list.RemoveAt(keys.IndexOf(name));
			keys.Remove(name);
		}
	}

See More Examples