System.Collections.Generic.List.Sort()

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

1481 Examples 7

19 View Source File : UtilsTest.cs
License : GNU General Public License v3.0
Project Creator : aloopkin

[TestMethod()]
        public void DomainsToHostIdTest()
        {
            List<string> domains = new List<string>();
            domains.Add("test2.example.com");
            domains.Add("test.example.com");
            domains.Sort();
            string hostId = Utils.DomainsToHostId(domains);
            if (!hostId.Equals("_6fb23d16b162f18a")) {
                // we're not ok
                replacedert.Fail();
            }
        }

19 View Source File : AdaptiveHistogramBuilder.cs
License : MIT License
Project Creator : AndreyAkinshin

public Histogram Build(IReadOnlyList<double> values, double binSize)
        {
            const double eps = 1e-9;
            const double margin = 0.1;
            const double adaptiveFactor = 0.02;

            if (binSize < eps)
                throw new ArgumentException(
                    $"binSize ({binSize.ToString("0.##", DefaultCultureInfo.Instance)}) should be a positive number",
                    nameof(binSize));
            if (binSize < Resolution)
                binSize = Resolution;
            binSize = NiceCeiling(binSize);

            var list = values.ToList();
            if (list.Count == 0)
                throw new ArgumentException("Values should be non-empty", nameof(values));

            list.Sort();
            if (list.Last() - list.First() < binSize)
            {
                double center = (list.First() + list.Last()) / 2;
                double lower = center - binSize / 2;
                double upper = center + binSize / 2;
                return new Histogram(binSize, new[] {new HistogramBin(lower, upper, list.ToArray())});
            }

            var points = new List<double> {NiceFloor(list.Min() - binSize / 2), NiceCeiling(list.Max() + binSize / 2)};
            int processedPointCount = 0;
            while (true)
            {
                if (points.Count > 10 * list.Count)
                {
                    var errorMessage = new StringBuilder();
                    errorMessage.AppendLine("Failed to run AdaptiveHistogramBuilder.BuildWithFixedBinSize");
                    errorMessage.AppendLine("BinSize: " + binSize.ToString("N12", DefaultCultureInfo.Instance));
                    errorMessage.AppendLine("Values: ");
                    foreach (double value in list)
                        errorMessage.AppendLine("  " + value.ToString("N12", DefaultCultureInfo.Instance));
                    throw new InvalidOperationException(errorMessage.ToString());
                }

                int pointIndex = -1;
                for (int i = processedPointCount; i < points.Count - 1; i++)
                {
                    double adaptiveBinSize = (points[i] + points[i + 1]) / 2.0 * adaptiveFactor;
                    double maxSize = Math.Max(binSize * (1.0 + 2 * margin), adaptiveBinSize);
                    if (points[i + 1] - points[i] > maxSize)
                    {
                        pointIndex = i;
                        break;
                    }
                }

                if (pointIndex == -1)
                    break;

                double lower = points[pointIndex];
                double upper = points[pointIndex + 1];

                int bestIndex1 = -1;
                int bestIndex2 = -1;
                int bestCount = -1;
                double bestDist = double.MaxValue;

                bool Inside(double x) => x > lower - eps && x < upper - eps;

                for (int i = 0; i < list.Count; i++)
                    if (Inside(list[i]))
                    {
                        int j = i;
                        while (j < list.Count && Inside(list[j]) && list[j] - list[i] < binSize)
                            j++;
                        int count = j - i;
                        double dist = list[j - 1] - list[i];
                        if (count > bestCount || count == bestCount && dist < bestDist)
                        {
                            bestCount = count;
                            bestIndex1 = i;
                            bestIndex2 = j - 1;
                            bestDist = dist;
                        }
                    }

                if (bestIndex1 != -1)
                {
                    double center = (list[bestIndex1] + list[bestIndex2]) / 2.0;
                    double adaptiveBinSize = Math.Max(binSize, center * adaptiveFactor);
                    double left = NiceFloor(center - adaptiveBinSize / 2);
                    double right = NiceFloor(Math.Min(center + adaptiveBinSize / 2, upper));

                    if (left > lower + binSize * margin)
                        points.Insert(pointIndex + 1, left);
                    else if (right < upper - binSize * margin && right > lower + binSize * margin)
                    {
                        points.Insert(pointIndex + 1, right);
                        processedPointCount++;
                    }
                    else
                        processedPointCount++;
                }
                else
                {
                    points.Insert(pointIndex + 1, NiceFloor(lower + binSize));
                    processedPointCount++;
                }
            }

            var bins = new List<HistogramBin>(points.Count - 1);
            int counter = 0;
            for (int i = 0; i < points.Count - 1; i++)
            {
                var bin = new List<double>();
                double lower = points[i];
                double upper = points[i + 1];

                while (counter < list.Count && (list[counter] < upper || i == points.Count - 1))
                    bin.Add(list[counter++]);

                bins.Add(new HistogramBin(lower, upper, bin.ToArray()));
            }

            // Trim
            while (bins.Any() && bins.First().IsEmpty)
                bins.RemoveAt(0);
            while (bins.Any() && bins.Last().IsEmpty)
                bins.RemoveAt(bins.Count - 1);

            // Join small bins to neighbors
            counter = 0;
            double lastValue = 0;
            while (counter < bins.Count)
            {
                if (bins[counter].HasAny)
                    lastValue = Math.Max(lastValue, bins[counter].Values.Last());
                double adaptiveThreshold = Math.Max(binSize / 3, lastValue * adaptiveFactor);
                if (bins[counter].Gap < adaptiveThreshold)
                {
                    double leftGap = counter > 0 ? bins[counter - 1].Gap : double.MaxValue;
                    double rightGap = counter < bins.Count - 1 ? bins[counter + 1].Gap : double.MaxValue;
                    if (leftGap < rightGap && counter > 0)
                    {
                        bins[counter - 1] = HistogramBin.Union(bins[counter - 1], bins[counter]);
                        bins.RemoveAt(counter);
                    }
                    else if (counter < bins.Count - 1)
                    {
                        bins[counter] = HistogramBin.Union(bins[counter], bins[counter + 1]);
                        bins.RemoveAt(counter + 1);
                    }
                    else
                        counter++;
                }
                else
                    counter++;
            }

            return new Histogram(binSize, bins.ToArray());
        }

19 View Source File : TxtMapExporter.cs
License : MIT License
Project Creator : Alan-FGR

public void Save(string filename, Dictionary<string, Rectangle> map)
		{
			// copy the files list and sort alphabetically
			string[] keys = new string[map.Count];
			map.Keys.CopyTo(keys, 0);
			List<string> outputFiles = new List<string>(keys);
			outputFiles.Sort();

			using (StreamWriter writer = new StreamWriter(filename))
			{
				foreach (var image in outputFiles)
				{
					// get the destination rectangle
					Rectangle destination = map[image];

					// write out the destination rectangle for this bitmap
					writer.WriteLine(string.Format(
	                 	"{0} = {1} {2} {3} {4}", 
	                 	Path.GetFileNameWithoutExtension(image), 
	                 	destination.X, 
	                 	destination.Y, 
	                 	destination.Width, 
	                 	destination.Height));
				}
			}
		}

19 View Source File : PhysicsSceneManager.cs
License : Apache License 2.0
Project Creator : allenai

public IEnumerable<SimObjPhysics> IterShuffleSimObjPhysicsDictList(
        Dictionary<SimObjType, List<SimObjPhysics>> dict,
        System.Random rng
    ) {
        List<SimObjType> types = new List<SimObjType>();
        Dictionary<SimObjType, int> indDict = new Dictionary<SimObjType, int>();
        foreach (KeyValuePair<SimObjType, List<SimObjPhysics>> pair in dict) {
            types.Add(pair.Key);
            indDict[pair.Key] = pair.Value.Count - 1;
        }
        types.Sort();
        types.Shuffle_(rng);
        foreach (SimObjType t in types) {
            dict[t].Shuffle_(rng);
        }

        bool changed = true;
        List<SimObjPhysics> shuffledSopList = new List<SimObjPhysics>();
        while (changed) {
            changed = false;
            foreach (SimObjType type in types) {
                int i = indDict[type];
                if (i >= 0) {
                    changed = true;
                    yield return dict[type][i];
                    indDict[type]--;
                }
            }
        }
    }

19 View Source File : AMD10CPU.cs
License : MIT License
Project Creator : AlexGyver

private double estimateTimeStampCounterMultiplier() {
      // preload the function
      estimateTimeStampCounterMultiplier(0);
      estimateTimeStampCounterMultiplier(0);

      // estimate the multiplier
      List<double> estimate = new List<double>(3);
      for (int i = 0; i < 3; i++)
        estimate.Add(estimateTimeStampCounterMultiplier(0.025));
      estimate.Sort();
      return estimate[1];
    }

19 View Source File : Scheduler.cs
License : GNU General Public License v3.0
Project Creator : aenemenate

public static void HandleCraftingScheduling(int secondsToAdvance)
        {
            int counter = 0;
            int interval = 60;

            Point worldIndex = Program.Player.WorldIndex;

            while (counter < secondsToAdvance) {
                Program.TimeHandler.CurrentTime.AddTime( interval );
                counter += interval;

                int currentFloor = Program.Player.CurrentFloor;
                UpdateCreatureList(Program.WorldMap[worldIndex.X, worldIndex.Y]);
                List<Creature> creatures = currentFloor >= 0 ? Program.WorldMap[worldIndex.X, worldIndex.Y].Dungeon.Floors[currentFloor].Creatures : Program.WorldMap[worldIndex.X, worldIndex.Y].Creatures;
                creatures.Sort();
                for (int i = 0; i < creatures.Count; i++)
                    if (creatures[i].NextActionTime.IsLessThan( Program.TimeHandler.CurrentTime ) || creatures[i].NextActionTime.Equals( Program.TimeHandler.CurrentTime )) {
                        if (creatures[i] is Player == false)
                            creatures[i].DetermineAction();
                        else {
                            creatures[i].Wait();
                        }
                    }
                CheckUpdates();
            }

            InitCreatureListScheduling(Program.WorldMap[worldIndex.X, worldIndex.Y]);
        }

19 View Source File : SvnSccProvider.Projects.cs
License : Apache License 2.0
Project Creator : AmpScm

public void ScheduleSvnRefresh(List<SvnClientAction> sccRefrereplacedems)
        {
            if (sccRefrereplacedems == null)
                throw new ArgumentNullException("sccRefrereplacedems");

            CommandService.PostIdleAction(
                delegate
                {
                    bool sorted = false;
                    foreach (SccProjectData project in ProjectMap.AllSccProjects)
                    {
                        if (project.WebLikeFileHandling && !string.IsNullOrEmpty(project.ProjectDirectory))
                        {
                            string dir = project.ProjectDirectory;

                            foreach (SvnClientAction action in sccRefrereplacedems)
                            {
                                if (SvnItem.IsBelowRoot(action.FullPath, dir))
                                {
                                    if (!sorted)
                                    {
                                        sorted = true;
                                        sccRefrereplacedems.Sort();
                                    }

                                    project.PerformRefresh(sccRefrereplacedems);
                                    break;
                                }
                            }
                        }
                    }
                });
        }

19 View Source File : TextFormattingConverterBase.cs
License : MIT License
Project Creator : ABTSoftware

public string HighlightTermsBase(string text, string[] terms)
        {
            var set = new HashSet<int>();
            foreach (var term in terms)
            {
                var indexes = text.ToLower().AllIndexesOf(term).Reverse().ToList();
                foreach (var index in indexes)
                {
                    for (int j = 0; j < term.Length; j++)
                    {
                        set.Add(j + index);
                    }
                }
            }

            if (set.Count > 0)
            {
                var list = set.ToList();
                list.Sort();

                var ranges = GetRanges(list.ToArray());
                ranges.Reverse();

                var color = HighlightColor ?? Colors.Black;
                string colorString = string.Format("#{0:X2}{1:X2}{2:X2}{3:X2}", color.A, color.R, color.G, color.B);

                foreach (var range in ranges)
                {
                    text = text.Insert(range.Item1 + range.Item2, "</Run>");
                    text = text.Insert(range.Item1, string.Format("<Run Foreground=\"{0}\">", colorString));
                }
            }

            return text;
        }

19 View Source File : PlanarPolygon.cs
License : Apache License 2.0
Project Creator : anmcgrath

public double[] GetFixedYLineIntersections(double y)
        {
            List<double> intersectingXCoords = new List<double>();
            int j = Vertices.Length - 2;
            double x0, x1, y0, y1, m;
            for (int i = 0; i < Vertices.Length; i += 2, j = i - 2)
            {
                x0 = Vertices[j];
                y0 = Vertices[j + 1];
                x1 = Vertices[i];
                y1 = Vertices[i + 1];
                if (y0 < y && y1 < y || y0 > y && y1 > y)
                    continue;
                if (y1 == y)
                    continue;

                // handle the case that the edge is a straight line parallel to our line
                if (y0 == y1)
                {
                    intersectingXCoords.Add(x0);
                    intersectingXCoords.Add(x1);
                }
                else if (x0 == x1)
                {
                    // we add the x coord because we know the y values of the edge cross the line
                    intersectingXCoords.Add(x0);
                }
                else
                {
                    m = (y1 - y0) / (x1 - x0);
                    intersectingXCoords.Add((y - y0) / m + x0);
                }
            }

            intersectingXCoords.Sort();

            if (intersectingXCoords.Count % 2 == 0)
                return intersectingXCoords.ToArray();
            else
                return intersectingXCoords.Distinct().ToArray(); // Remove repeating x coords when we return as an array
        }

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

private void HandleMappingWithWellKnownProperties(
            DefinitionInfo definition,
            List<MappingDefinition> mappingDefinitions,
            MappingToken mapping)
        {
            // Check if loose properties are allowed
            String looseKeyType = null;
            String looseValueType = null;
            DefinitionInfo? looseKeyDefinition = null;
            DefinitionInfo? looseValueDefinition = null;
            if (!String.IsNullOrEmpty(mappingDefinitions[0].LooseKeyType))
            {
                looseKeyType = mappingDefinitions[0].LooseKeyType;
                looseValueType = mappingDefinitions[0].LooseValueType;
            }

            var keys = new HashSet<String>(StringComparer.OrdinalIgnoreCase);
            var hasExpressionKey = false;

            while (m_unraveler.AllowScalar(definition.Expand, out ScalarToken nextKeyScalar))
            {
                // Expression
                if (nextKeyScalar is ExpressionToken)
                {
                    hasExpressionKey = true;
                    var anyDefinition = new DefinitionInfo(definition, TemplateConstants.Any);
                    mapping.Add(nextKeyScalar, Evaluate(anyDefinition));
                    continue;
                }

                // Not a string, convert
                if (!(nextKeyScalar is StringToken nextKey))
                {
                    nextKey = new StringToken(nextKeyScalar.FileId, nextKeyScalar.Line, nextKeyScalar.Column, nextKeyScalar.ToString());
                }

                // Duplicate
                if (!keys.Add(nextKey.Value))
                {
                    m_context.Error(nextKey, TemplateStrings.ValueAlreadyDefined(nextKey.Value));
                    m_unraveler.SkipMappingValue();
                    continue;
                }

                // Well known
                if (m_schema.TryMatchKey(mappingDefinitions, nextKey.Value, out String nextValueType))
                {
                    var nextValueDefinition = new DefinitionInfo(definition, nextValueType);
                    var nextValue = Evaluate(nextValueDefinition);
                    mapping.Add(nextKey, nextValue);
                    continue;
                }

                // Loose
                if (looseKeyType != null)
                {
                    if (looseKeyDefinition == null)
                    {
                        looseKeyDefinition = new DefinitionInfo(definition, looseKeyType);
                        looseValueDefinition = new DefinitionInfo(definition, looseValueType);
                    }

                    Validate(nextKey, looseKeyDefinition.Value);
                    var nextValue = Evaluate(looseValueDefinition.Value);
                    mapping.Add(nextKey, nextValue);
                    continue;
                }

                // Error
                m_context.Error(nextKey, TemplateStrings.UnexpectedValue(nextKey.Value));
                m_unraveler.SkipMappingValue();
            }

            // Only one
            if (mappingDefinitions.Count > 1)
            {
                var hitCount = new Dictionary<String, Int32>();
                foreach (MappingDefinition mapdef in mappingDefinitions)
                {
                    foreach (String key in mapdef.Properties.Keys)
                    {
                        if (!hitCount.TryGetValue(key, out Int32 value))
                        {
                            hitCount.Add(key, 1);
                        }
                        else
                        {
                            hitCount[key] = value + 1;
                        }
                    }
                }

                List<String> nonDuplicates = new List<String>();
                foreach (String key in hitCount.Keys)
                {
                    if (hitCount[key] == 1)
                    {
                        nonDuplicates.Add(key);
                    }
                }
                nonDuplicates.Sort();

                String listToDeDuplicate = String.Join(", ", nonDuplicates);
                m_context.Error(mapping, TemplateStrings.UnableToDetermineOneOf(listToDeDuplicate));
            }
            else if (mappingDefinitions.Count == 1 && !hasExpressionKey)
            {
                foreach (var property in mappingDefinitions[0].Properties)
                {
                    if (property.Value.Required)
                    {
                        if (!keys.Contains(property.Key))
                        {
                            m_context.Error(mapping, $"Required property is missing: {property.Key}");
                        }
                    }
                }
            }

            m_unraveler.ReadMappingEnd();
        }

19 View Source File : GenericListExtensions.cs
License : MIT License
Project Creator : AlFasGD

public static List<T> CloneSort<T>(this List<T> l)
        {
            var result = l.Clone();
            result.Sort();
            return result;
        }

19 View Source File : SpeedSegmentCollection.cs
License : MIT License
Project Creator : AlFasGD

public List<double> ConvertXToTime(List<double> x)
        {
            x.Sort();
            double time = 0;
            int i = 1;
            var result = new List<double>();
            foreach (var k in x)
            {
                for (; i < Count && this[i].X < k; i++)
                    time += (this[i].X - this[i - 1].X) / GetSpeed(this[i - 1].Speed);
                int final = Math.Min(i, Count - 1);
                result.Add(time + (k - this[final].X) / GetSpeed(this[final].Speed));
            }
            return result;
        }

19 View Source File : UISpriteAnimation.cs
License : GNU General Public License v3.0
Project Creator : aelariane

private void RebuildSpriteList()
    {
        if (this.mSprite == null)
        {
            this.mSprite = base.GetComponent<UISprite>();
        }
        this.mSpriteNames.Clear();
        if (this.mSprite != null && this.mSprite.atlas != null)
        {
            List<UIAtlas.Sprite> spriteList = this.mSprite.atlas.spriteList;
            int i = 0;
            int count = spriteList.Count;
            while (i < count)
            {
                UIAtlas.Sprite sprite = spriteList[i];
                if (string.IsNullOrEmpty(this.mPrefix) || sprite.name.StartsWith(this.mPrefix))
                {
                    this.mSpriteNames.Add(sprite.name);
                }
                i++;
            }
            this.mSpriteNames.Sort();
        }
    }

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

public static string DomainsToHostId(List<string> domains)
        {
            List<string> wDomains = new List<string>(domains);
            wDomains.Sort();
            string domainList = String.Join("-", wDomains);
            return "_" + GetMD5Hash(new MD5(), domainList).Substring(0, 16).ToLower();
        }

19 View Source File : ExampleLoader.cs
License : MIT License
Project Creator : ABTSoftware

private IDictionary<ExampleKey, string> DiscoverAllExampleDefinitions()
        {
            var dict = new Dictionary<ExampleKey, string>();
            replacedembly replacedembly = typeof (ExampleLoader).replacedembly;

            var names = replacedembly.GetManifestResourceNames();

            var allXmlManifestResources = names.Where(x => x.Contains("ExampleDefinitions")).ToList();
            allXmlManifestResources.Sort();

            foreach(var xmlResource in allXmlManifestResources)
            {
                using (var s = replacedembly.GetManifestResourceStream(xmlResource))
                using (var sr = new StreamReader(s))
                {
                    string exampleKeyString = xmlResource.Replace("SciChart.Examples.Resources.ExampleDefinitions.", string.Empty)
                        .Replace("SciChart.Examples.SL.Resources.ExampleDefinitions.", string.Empty);

                    string[] chunks = exampleKeyString.Split('.');
                    var exampleKey = new ExampleKey()
                    {
                        ExampleCategory = Trim(chunks[0], true),
                        ChartGroup = Trim(chunks[1]),
                        Examplereplacedle = Trim(chunks[2])
                    };
                    dict.Add(exampleKey, sr.ReadToEnd());
                }
            }
            return dict;
        }

19 View Source File : Map.cs
License : MIT License
Project Creator : amidos2006

public List<int[]> getDungeonPath(Cell from, Cell to, int accessLevel){
            List<TreeNode> queue = new List<TreeNode>();
            queue.Add(new TreeNode(from.x, from.y, null, to.x, to.y));
            HashSet<string> visited = new HashSet<string>();
            while (queue.Count > 0)
            {
                queue.Sort();
                TreeNode current = queue[0];
                queue.Remove(current);
                if (current.x == to.x && current.y == to.y)
                {
                    return current.getPath();
                }
                if (from.parent != null && current.x == from.parent.x && current.y == from.parent.y){
                    continue;
                }
                if (visited.Contains(current.x + "," + current.y))
                {
                    continue;
                }
                if (!this.usedSpaces.ContainsKey(current.x + "," + current.y)){
                    continue;
                }
                if(this.usedSpaces[current.x + "," + current.y].type == CellType.Connection){
                        continue;
                }
                if (this.usedSpaces[current.x + "," + current.y].node.accessLevel != accessLevel)
                {
                    continue;
                }
                
                visited.Add(current.x + "," + current.y);
                foreach (int[] dir in directions)
                {
                    if(this.usedSpaces[current.x + "," + current.y].getDoor(-dir[0], -dir[1]) != 0){
                        int newX = current.x + dir[0];
                        int newY = current.y + dir[1];
                        queue.Add(new TreeNode(newX, newY, current, to.x, to.y));
                    }
                }
            }
            return new List<int[]>();
        }

19 View Source File : TextureConverter.cs
License : MIT License
Project Creator : Alan-FGR

private List<float> SearchCrossingEdgesHoles(Vertices polygon, int y)
        {
            if (polygon == null)
                throw new ArgumentNullException("polygon", "'polygon' can't be null.");

            if (polygon.Count < 3)
                throw new ArgumentException("'polygon.MainPolygon.Count' can't be less then 3.");

            List<float> result = SearchCrossingEdges(polygon, y);

            if (polygon.Holes != null)
            {
                for (int i = 0; i < polygon.Holes.Count; i++)
                {
                    result.AddRange(SearchCrossingEdges(polygon.Holes[i], y));
                }
            }

            result.Sort();
            return result;
        }

19 View Source File : Bus.cs
License : MIT License
Project Creator : ancientproject

public void Add(IDevice device)
        {
            device.startAddress = scheme.getOffsetByDevice(device.name, device.startAddress);

            if (Devices.FirstOrDefault(x => x.startAddress == device.startAddress) != null)
            {
                cpu.halt(0x4, $"<0x{device.startAddress:X}>");
                return;
            }
            Devices.Add(device);
            Devices.Sort();
            device.replacedignBus(this);
            if(WarmUpDevices) device.warmUp();
        }

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

public void Initialize (DynamicCharacterAvatar Avatar) 
		{

		foreach(GameObject go in CreatedObjects) UMAUtils.DestroySceneObject(go);
		CreatedObjects.Clear();

			UMADnaBase[] DNA = Avatar.GetAllDNA();

			List<DNAHolder> ValidDNA = new List<DNAHolder>();

			foreach (UMADnaBase d in DNA)
			{
				string[] names = d.Names;
				float[] values = d.Values;

				for (int i=0;i<names.Length;i++)
				{
					string name = names[i];
					if (IsThisCategory(name.ToLower()))
					{
						ValidDNA.Add(new DNAHolder(name,values[i],i,d));
					}
				}

			}

			ValidDNA.Sort( );
			
			foreach(DNAHolder dna in ValidDNA)
			{
				GameObject go = GameObject.Instantiate(DnaEditor);
				go.transform.SetParent(ContentArea.transform);
				go.transform.localScale = new Vector3(1f, 1f, 1f);//Set the scale back to 1
				DNAEditor de = go.GetComponentInChildren<DNAEditor>();
			de.Initialize(dna.name.BreakupCamelCase(),dna.index,dna.dnaBase,Avatar,dna.value);
				go.SetActive(true);
				CreatedObjects.Add(go);
			}
		}

19 View Source File : GridMath.cs
License : Apache License 2.0
Project Creator : anmcgrath

public List<Offset> CreateOffsets(double diameterMM, double stepMM, Point3d gridSizes)
        {
            List<Offset> offsets = new List<Offset>();
            //First surround with offset that correspond to grid points
            for(double i = -gridSizes.X*2; i<gridSizes.X*2;i++)
            {
                for(double j = -gridSizes.Y*2; j < gridSizes.Y * 2; j++)
                {
                    for(double k = -gridSizes.Z*2; k < gridSizes.Z; k++)
                    {
                        offsets.Add(new Offset() { Displacement = new Point3d(i, j, k) });
                    }
                }
            }

            offsets.Add(new Offset() { Displacement = new Point3d(0, 0, 0) });

            int n = (int)((diameterMM) / stepMM);
            if (n % 2 != 0)
                n++;
            var c0 = 0 - stepMM * (n/2); //ensure we go through 0
            for (int i = 0; i < n; i++)
                for (int j = 0; j < n; j++)
                    for (int k = 0; k < n; k++)
                    {
                        var xo = c0 + i * stepMM;
                        var yo = c0 + j * stepMM;
                        var zo = c0 + k * stepMM;
                        offsets.Add(new Offset() { Displacement = new Point3d(xo, yo, zo) });
                    }

            offsets.Sort();
            return offsets;
        }

19 View Source File : TileJsonData.cs
License : MIT License
Project Creator : alen-smajic

public void ProcessTileJSONData(TileJSONResponse tjr)
		{
			tileJSONLoaded = true;
			List<string> layerPropertiesList = new List<string>();

			if (tjr == null || tjr.VectorLayers == null || tjr.VectorLayers.Length == 0)
			{
				return;
			}

			ClearData();

			var propertyName = "";
			var propertyDescription = "";
			var layerSource = "";

			foreach (var layer in tjr.VectorLayers)
			{
				//load layer names
				var layerName = layer.Id;
				layerPropertiesList = new List<string>();
				layerSource = layer.Source;

				//loading layer sources
				if (LayerSourcesDictionary.ContainsKey(layerName))
				{
					LayerSourcesDictionary[layerName].Add(layerSource);
				}
				else
				{
					LayerSourcesDictionary.Add(layerName, new List<string>() { layerSource });
				}

				//loading layers to a data source
				if (SourceLayersDictionary.ContainsKey(layerSource))
				{
					List<string> sourceList = new List<string>();
					LayerSourcesDictionary.TryGetValue(layerName, out sourceList);

					if (sourceList.Count > 1 && sourceList.Contains(layerSource)) // the current layerName has more than one source
					{
						if (SourceLayersDictionary.ContainsKey(commonLayersKey))
						{
							SourceLayersDictionary[commonLayersKey].Add(layerName);
						}
						else
						{
							SourceLayersDictionary.Add(commonLayersKey, new List<string>() { layerName });
						}

						if (LayerDisplayNames.Contains(layerName))
						{
							LayerDisplayNames.Remove(layerName);
						}
						LayerDisplayNames.Add(layerName);
					}
					else
					{
						SourceLayersDictionary[layerSource].Add(layerName);
						LayerDisplayNames.Add(layerName);
					}
				}
				else
				{
					SourceLayersDictionary.Add(layerSource, new List<string>() { layerName });
					LayerDisplayNames.Add(layerName);
				}


				//Load properties
				foreach (var property in layer.Fields)
				{
					propertyName = property.Key;
					propertyDescription = property.Value;
					layerPropertiesList.Add(propertyName);

					//adding property descriptions
					if (LayerPropertyDescriptionDictionary.ContainsKey(layerName))
					{
						if (!LayerPropertyDescriptionDictionary[layerName].ContainsKey(propertyName))
						{
							LayerPropertyDescriptionDictionary[layerName].Add(propertyName, propertyDescription);
						}
					}
					else
					{
						LayerPropertyDescriptionDictionary.Add(layerName, new Dictionary<string, string>() { { propertyName, propertyDescription } });
					}

					//Loading display names for properties
					if (PropertyDisplayNames.ContainsKey(layerName))
					{
						if (!PropertyDisplayNames[layerName].Contains(propertyName))
						{
							PropertyDisplayNames[layerName].Add(propertyName);

							//logic to add the list of masked properties from all sources that are not #1
							if (LayerSourcesDictionary[layerName].Count > 1 && !string.IsNullOrEmpty(tjr.Source))
							{
								var firstSource = tjr.Source.Split(new string[] { "," }, System.StringSplitOptions.None)[0].Trim();
								if (layerSource != firstSource)
								{
									if (PropertyDisplayNames[layerName].Contains(propertyName))
									{
										PropertyDisplayNames[layerName].Remove(propertyName);
									}

									PropertyDisplayNames[layerName].Add(propertyName);
								}
							}
						}
					}
					else
					{
						PropertyDisplayNames.Add(layerName, new List<string> { propertyName });
					}
				}

				if (PropertyDisplayNames.ContainsKey(layerName) && PropertyDisplayNames[layerName].Count > 1)
				{
					PropertyDisplayNames[layerName].Sort();
				}
			}


			if (LayerDisplayNames.Count > 1)
			{
				LayerDisplayNames.Sort();
			}
		}

19 View Source File : MKMDatabaseManager.cs
License : GNU Affero General Public License v3.0
Project Creator : alexander-pick

public List<string> GetAllExpansionNames(bool sortByName)
    {
      List<string> exp = new List<string>(Expansions.Rows.Count);
      foreach (DataRow nExpansion in Expansions.Rows)
      {
        exp.Add(nExpansion[ExpansionsFields.Name].ToString());
      }
      if (sortByName)
        exp.Sort();
      return exp;
    }

19 View Source File : HighlightedLine.cs
License : MIT License
Project Creator : Abdesol

internal void WriteTo(RichTextWriter writer, int startOffset, int endOffset)
		{
			if (writer == null)
				throw new ArgumentNullException("writer");
			int doreplacedentLineStartOffset = this.DoreplacedentLine.Offset;
			int doreplacedentLineEndOffset = doreplacedentLineStartOffset + this.DoreplacedentLine.Length;
			if (startOffset < doreplacedentLineStartOffset || startOffset > doreplacedentLineEndOffset)
				throw new ArgumentOutOfRangeException("startOffset", startOffset, "Value must be between " + doreplacedentLineStartOffset + " and " + doreplacedentLineEndOffset);
			if (endOffset < startOffset || endOffset > doreplacedentLineEndOffset)
				throw new ArgumentOutOfRangeException("endOffset", endOffset, "Value must be between startOffset and " + doreplacedentLineEndOffset);
			ISegment requestedSegment = new SimpleSegment(startOffset, endOffset - startOffset);

			List<HtmlElement> elements = new List<HtmlElement>();
			for (int i = 0; i < this.Sections.Count; i++) {
				HighlightedSection s = this.Sections[i];
				if (SimpleSegment.GetOverlap(s, requestedSegment).Length > 0) {
					elements.Add(new HtmlElement(s.Offset, i, false, s.Color));
					elements.Add(new HtmlElement(s.Offset + s.Length, i, true, s.Color));
				}
			}
			elements.Sort();

			IDoreplacedent doreplacedent = this.Doreplacedent;
			int textOffset = startOffset;
			foreach (HtmlElement e in elements) {
				int newOffset = Math.Min(e.Offset, endOffset);
				if (newOffset > startOffset) {
					doreplacedent.WriteTextTo(writer, textOffset, newOffset - textOffset);
				}
				textOffset = Math.Max(textOffset, newOffset);
				if (e.IsEnd)
					writer.EndSpan();
				else
					writer.BeginSpan(e.Color);
			}
			doreplacedent.WriteTextTo(writer, textOffset, endOffset - textOffset);
		}

19 View Source File : TreeViewAdv.cs
License : MIT License
Project Creator : AlexGyver

private void _model_NodesRemoved(object sender, TreeModelEventArgs e)
		{
			TreeNodeAdv parent = FindNode(e.Path);
			if (parent != null)
			{
				if (e.Indices != null)
				{
					List<int> list = new List<int>(e.Indices);
					list.Sort();
					for (int n = list.Count - 1; n >= 0; n--)
					{
						int index = list[n];
						if (index >= 0 && index <= parent.Nodes.Count)
							parent.Nodes.RemoveAt(index);
						else
							throw new ArgumentOutOfRangeException("Index out of range");
					}
				}
				else
				{
					for (int i = parent.Nodes.Count - 1; i >= 0; i--)
					{
						for (int n = 0; n < e.Children.Length; n++)
							if (parent.Nodes[i].Tag == e.Children[n])
							{
								parent.Nodes.RemoveAt(i);
								break;
							}
					}
				}
			}
			UpdateSelection();
			SmartFullUpdate();
		}

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

private void HandleMappingWithWellKnownProperties(
            DefinitionInfo definition,
            List<MappingDefinition> mappingDefinitions,
            MappingToken mapping)
        {
            // Check if loose properties are allowed
            String looseKeyType = null;
            String looseValueType = null;
            DefinitionInfo? looseKeyDefinition = null;
            DefinitionInfo? looseValueDefinition = null;
            if (!String.IsNullOrEmpty(mappingDefinitions[0].LooseKeyType))
            {
                looseKeyType = mappingDefinitions[0].LooseKeyType;
                looseValueType = mappingDefinitions[0].LooseValueType;
            }

            var keys = new HashSet<String>(StringComparer.OrdinalIgnoreCase);
            var hasExpressionKey = false;

            while (m_objectReader.AllowLiteral(out LiteralToken rawLiteral))
            {
                var nextKeyScalar = ParseScalar(rawLiteral, definition.AllowedContext);
                // Expression
                if (nextKeyScalar is ExpressionToken)
                {
                    hasExpressionKey = true;
                    // Legal
                    if (definition.AllowedContext.Length > 0)
                    {
                        m_memory.AddBytes(nextKeyScalar);
                        var anyDefinition = new DefinitionInfo(definition, TemplateConstants.Any);
                        mapping.Add(nextKeyScalar, ReadValue(anyDefinition));
                    }
                    // Illegal
                    else
                    {
                        m_context.Error(nextKeyScalar, TemplateStrings.ExpressionNotAllowed());
                        SkipValue();
                    }

                    continue;
                }

                // Not a string, convert
                if (!(nextKeyScalar is StringToken nextKey))
                {
                    nextKey = new StringToken(nextKeyScalar.FileId, nextKeyScalar.Line, nextKeyScalar.Column, nextKeyScalar.ToString());
                }

                // Duplicate
                if (!keys.Add(nextKey.Value))
                {
                    m_context.Error(nextKey, TemplateStrings.ValueAlreadyDefined(nextKey.Value));
                    SkipValue();
                    continue;
                }

                // Well known
                if (m_schema.TryMatchKey(mappingDefinitions, nextKey.Value, out String nextValueType))
                {
                    m_memory.AddBytes(nextKey);
                    var nextValueDefinition = new DefinitionInfo(definition, nextValueType);
                    var nextValue = ReadValue(nextValueDefinition);
                    mapping.Add(nextKey, nextValue);
                    continue;
                }

                // Loose
                if (looseKeyType != null)
                {
                    if (looseKeyDefinition == null)
                    {
                        looseKeyDefinition = new DefinitionInfo(definition, looseKeyType);
                        looseValueDefinition = new DefinitionInfo(definition, looseValueType);
                    }

                    Validate(nextKey, looseKeyDefinition.Value);
                    m_memory.AddBytes(nextKey);
                    var nextValue = ReadValue(looseValueDefinition.Value);
                    mapping.Add(nextKey, nextValue);
                    continue;
                }

                // Error
                m_context.Error(nextKey, TemplateStrings.UnexpectedValue(nextKey.Value));
                SkipValue();
            }

            // Only one
            if (mappingDefinitions.Count > 1)
            {
                var hitCount = new Dictionary<String, Int32>();
                foreach (MappingDefinition mapdef in mappingDefinitions)
                {
                    foreach (String key in mapdef.Properties.Keys)
                    {
                        if (!hitCount.TryGetValue(key, out Int32 value))
                        {
                            hitCount.Add(key, 1);
                        }
                        else
                        {
                            hitCount[key] = value + 1;
                        }
                    }
                }

                List<String> nonDuplicates = new List<String>();
                foreach (String key in hitCount.Keys)
                {
                    if(hitCount[key] == 1)
                    {
                        nonDuplicates.Add(key);
                    }
                }
                nonDuplicates.Sort();

                String listToDeDuplicate = String.Join(", ", nonDuplicates);
                m_context.Error(mapping, TemplateStrings.UnableToDetermineOneOf(listToDeDuplicate));
            }
            else if (mappingDefinitions.Count == 1 && !hasExpressionKey)
            {
                foreach (var property in mappingDefinitions[0].Properties)
                {
                    if (property.Value.Required)
                    {
                        if (!keys.Contains(property.Key))
                        {
                            m_context.Error(mapping, $"Required property is missing: {property.Key}");
                        }
                    }
                }
            }
            ExpectMappingEnd();
        }

19 View Source File : GenericArrayExtensions.cs
License : MIT License
Project Creator : AlFasGD

public static T[] Sort<T>(this T[] ar)
        {
            var sorted = ar.ToList();
            sorted.Sort();
            return sorted.ToArray();
        }

19 View Source File : SpeedSegmentCollection.cs
License : MIT License
Project Creator : AlFasGD

public List<double> ConvertTimeToX(List<double> times)
        {
            times.Sort();
            double t = 0;
            int i = 1;
            var result = new List<double>();
            foreach (var k in times)
            {
                for (; i < Count && t < k; i++)
                    t += (this[i].X - this[i - 1].X) / GetSpeed(this[i - 1].Speed);
                int final = Math.Min(i, Count) - 1;
                result.Add(this[final].X + (t - k) * GetSpeed(this[final].Speed));
            }
            return result;
        }

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

private void LogColors()
        {
            for (int j = 1; j < 13; j++)
            {
                Texture2D sprite = this.Helper.Content.Load<Texture2D>("replacedets/work/hairs/" + j + ".png");
                Color[] data = new Color[sprite.Width * sprite.Height];
                sprite.GetData(data);
                Dictionary<int,string> tempList = new Dictionary<int,string>();
                for (int i = 0; i < data.Length; i++)
                {
                    if (data[i] != Color.Transparent)
                    {
                        int total = (int)data[i].R + (int)data[i].G + (int)data[i].B;
                        string c = string.Join(" ", new string[] { data[i].R.ToString(), data[i].G.ToString(), data[i].B.ToString() });
                        if (!tempList.ContainsKey(total))
                        {
                            tempList.Add(total,c);
                        }
                        else if(tempList[total] != c)
                        {
                            while (tempList.ContainsKey(total))
                            {
                                total++;
                                if (!tempList.ContainsKey(total))
                                {
                                    tempList.Add(total, c);
                                }
                                else if (tempList[total] == c)
                                    break;
                            }
                        }
                    }

                }
                var keys = tempList.Keys.ToList();
                keys.Sort();
                keys.Reverse();

                var outList = new List<string>();
                foreach(var key in keys)
                {
                    outList.Add(tempList[key]);
                }
                Alert(string.Join("^", outList));
            }
        }

19 View Source File : ObjectLists.cs
License : MIT License
Project Creator : AlFasGD

public static int[] GetNotGeneralObjectList()
        {
            List<int> objects = new List<int>();
            foreach (var f in typeof(ObjectLists).GetFields().Where(f => f.FieldType == typeof(int[]) && f.IsStatic))
                objects.AddRange((int[])f.GetRawConstantValue());
            objects.Sort();
            return objects.ToArray();
        }

19 View Source File : P2PManager.cs
License : MIT License
Project Creator : absurd-joy

void ReadTimeSyncMessage(ulong remoteID, byte[] msg)
		{
			if (!m_remoteSentTimeCache.ContainsKey(remoteID))
			{
				SendTimeSyncMessage(remoteID);
				return;
			}

			int offset = 1;
			float remoteTime = UnpackFloat(msg, ref offset);
			float now = Time.realtimeSinceStartup;
			float latency = (now - m_remoteSentTimeCache[remoteID]) / 2;
			float remoteTimeOffset = now - (remoteTime + latency);

			m_remoteSyncTimeCache[remoteID].Add(remoteTimeOffset);

			if (m_remoteSyncTimeCache[remoteID].Count < TIME_SYNC_MESSAGE_COUNT)
			{
				SendTimeSyncMessage(remoteID);
			}
			else
			{
				if (PlatformManager.MyID < remoteID)
				{
					// this client started the sync, need to send one last message to
					// the remote so they can finish their sync calculation
					SendTimeSyncMessage(remoteID);
				}

				// sort the times and remember the median
				m_remoteSyncTimeCache[remoteID].Sort();
				float median = m_remoteSyncTimeCache[remoteID][TIME_SYNC_MESSAGE_COUNT/2];

				// calucate the mean and standard deviation
				double mean = 0;
				foreach (var time in m_remoteSyncTimeCache[remoteID])
				{
					mean += time;
				}
				mean /= TIME_SYNC_MESSAGE_COUNT;

				double std_dev = 0;
				foreach (var time in m_remoteSyncTimeCache[remoteID])
				{
					std_dev += (mean-time)*(mean-time);
				}
				std_dev = Math.Sqrt(std_dev)/TIME_SYNC_MESSAGE_COUNT;

				// time delta is the mean of the values less than 1 standard deviation from the median
				mean = 0;
				int meanCount = 0;
				foreach (var time in m_remoteSyncTimeCache[remoteID])
				{
					if (Math.Abs(time-median) < std_dev)
					{
						mean += time;
						meanCount++;
					}
				}
				mean /= meanCount;
				Debug.LogFormat("Time offset to {0} is {1}", remoteID, mean);

				m_remoteSyncTimeCache.Remove(remoteID);
				m_remoteSentTimeCache.Remove(remoteID);
				m_remotePlayers[remoteID].remoteTimeOffset = (float)mean;

				// now that times are synchronized, lets try to coordinate the
				// start time for the match
				OfferMatchStartTime();
			}
		}

19 View Source File : PhysicsSceneManager.cs
License : Apache License 2.0
Project Creator : allenai

public List<SimObjPhysics> ShuffleSimObjPhysicsDictList(
        Dictionary<SimObjType, List<SimObjPhysics>> dict,
        int seed
    ) {
        List<SimObjType> types = new List<SimObjType>();
        Dictionary<SimObjType, int> indDict = new Dictionary<SimObjType, int>();
        foreach (KeyValuePair<SimObjType, List<SimObjPhysics>> pair in dict) {
            types.Add(pair.Key);
            indDict[pair.Key] = pair.Value.Count - 1;
        }
        types.Sort();
        types.Shuffle_(seed);
        foreach (SimObjType t in types) {
            dict[t].Shuffle_(seed);
        }

        bool changed = true;
        List<SimObjPhysics> shuffledSopList = new List<SimObjPhysics>();
        while (changed) {
            changed = false;
            foreach (SimObjType type in types) {
                int i = indDict[type];
                if (i >= 0) {
                    changed = true;
                    shuffledSopList.Add(dict[type][i]);
                    indDict[type]--;
                }
            }
        }
        return shuffledSopList;
    }

19 View Source File : Scheduler.cs
License : GNU General Public License v3.0
Project Creator : aenemenate

public static void HandleRoguelikeScheduling(Player player)
        {
            int currentFloor = player.CurrentFloor;
            Point worldIndex = player.WorldIndex;

            UpdateCreatureList(Program.WorldMap[worldIndex.X, worldIndex.Y]);
            List<Creature> creatures = currentFloor >= 0 ? Program.WorldMap[worldIndex.X, worldIndex.Y].Dungeon.Floors[currentFloor].Creatures : Program.WorldMap[worldIndex.X, worldIndex.Y].Creatures;
            List<Projectile> projectiles = currentFloor >= 0 ? Program.WorldMap[worldIndex.X, worldIndex.Y].Dungeon.Floors[currentFloor].Projectiles : Program.WorldMap[worldIndex.X, worldIndex.Y].Projectiles;
            
            if (creatures.Count == 0)
                return;
            creatures.Sort();
            
            for (int i = 0; i < creatures.Count; i++) {
                Program.TimeHandler.CurrentTime = creatures[i].NextActionTime;
                if (projectiles.Count > 0)
                    break;
                if (creatures[i] is Player) {
                    player.DetermineAction();
                    if (creatures.Count != 0 && creatures[i] is Player)
                        creatures[i] = player;
                    break;
                }
                creatures[i].DetermineAction();
            }
            UpdateProjectiles(currentFloor, worldIndex);
            CheckUpdates();
        }

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

public static string DomainsToFriendlyName(List<string> domains)
        {
            if (domains.Count == 0)
            {
                return "WinCertes";
            }
            List<string> wDomains = new List<string>(domains);
            wDomains.Sort();
            wDomains.Sort();
            string friendly = wDomains[0].Replace(@"*", "").Replace("-", "").Replace(":", "").Replace(".", "");
            friendly += "0000000000000000";
            return friendly.Substring(0, 16);
        }

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

public bool ShowArray(System.Type CurrentType, string Filter)
		{
			bool HasFilter = false;
			bool NotFound = false;
			string actFilter = Filter.Trim().ToLower();
			if (actFilter.Length > 0)
				HasFilter = true;

			Dictionary<string, replacedereplacedem> TypeDic = UAI.GetreplacedetDictionary(CurrentType);

			if (!TypeCheckboxes.ContainsKey(CurrentType))
			{
				TypeCheckboxes.Add(CurrentType, new List<bool>());
			}

			List<replacedereplacedem> Items = new List<replacedereplacedem>();
			Items.AddRange(TypeDic.Values);

			int NotInBuild = 0;
			int VisibleItems = 0;
			foreach (replacedereplacedem ai in Items)
			{
				if (ai._SerializedItem == null)
				{
					NotInBuild++;
				}
				string Displayed = ai.ToString(UMAreplacedetIndexer.SortOrder);
				if (HasFilter && (!Displayed.ToLower().Contains(actFilter)))
				{
					continue;
				}
				VisibleItems++;
			}

			if (TypeCheckboxes[CurrentType].Count != VisibleItems)
			{
				TypeCheckboxes[CurrentType].Clear();
				TypeCheckboxes[CurrentType].AddRange(new bool[VisibleItems]);
			}

			NotInBuildCount += NotInBuild;
			GUILayout.BeginHorizontal(EditorStyles.toolbarButton);
			GUILayout.Space(10);
			Toggles[CurrentType] = EditorGUILayout.Foldout(Toggles[CurrentType], CurrentType.Name + ":  "+VisibleItems+ "/" + TypeDic.Count + " Item(s). "+NotInBuild+" Not in build.");
			GUILayout.EndHorizontal();



			if (Toggles[CurrentType])
			{
				Items.Sort();
				GUIHelper.BeginVerticalPadded(5, new Color(0.75f, 0.875f, 1f));
				GUILayout.BeginHorizontal();
				GUILayout.Label("Sorted By: " + UMAreplacedetIndexer.SortOrder, GUILayout.MaxWidth(160));
				foreach (string s in UMAreplacedetIndexer.SortOrders)
				{
					if (GUILayout.Button(s, GUILayout.Width(80)))
					{
						UMAreplacedetIndexer.SortOrder = s;
					}
				}
				GUILayout.EndHorizontal();

				int CurrentVisibleItem = 0;
				foreach (replacedereplacedem ai in Items)
				{
					string lblBuild = "B-";
					string lblVal = ai.ToString(UMAreplacedetIndexer.SortOrder);
					if (HasFilter && (!lblVal.ToLower().Contains(actFilter)))
						continue;

					if (ai._Name == "< Not Found!>")
					{
						NotFound = true;
					}
					GUILayout.BeginHorizontal(EditorStyles.textField);

					TypeCheckboxes[CurrentType][CurrentVisibleItem] = EditorGUILayout.Toggle(TypeCheckboxes[CurrentType][CurrentVisibleItem++],GUILayout.Width(20));
					if (ai._SerializedItem == null)
					{
						lblVal += "<Not in Build>";
						lblBuild = "B+";
					}

					if (GUILayout.Button(lblVal /* ai._Name + " (" + ai._replacedetBaseName + ")" */, EditorStyles.label))
					{
						EditorGUIUtility.PingObject(replacedetDatabase.LoadMainreplacedetAtPath(ai._Path));
					}

					if (GUILayout.Button(lblBuild,GUILayout.Width(35)))
					{
						if (ai._SerializedItem == null)
						{
							if (!ai.IsreplacedetBundle)
								ai.CachSerializedItem();
						}
						else
						{
							ai.ReleaseItem();
						}

					}
					if (GUILayout.Button("-", GUILayout.Width(20.0f)))
					{
						DeletedDuringGUI.Add(ai);
					}
					GUILayout.EndHorizontal();
				}

				GUILayout.BeginHorizontal();
				if (NotFound)
				{
					GUILayout.Label("Warning - Some items not found!");
				}
				else
				{
					GUILayout.Label("All Items appear OK");
				}
				GUILayout.EndHorizontal();
				if (CurrentType == typeof(SlotDatareplacedet) || CurrentType == typeof(OverlayDatareplacedet))
				{
					GUIHelper.BeginVerticalPadded(5, new Color(0.65f, 0.65f, 0.65f));
					GUILayout.Label("Utilities");
					GUILayout.Space(10);

					EditorGUILayout.BeginHorizontal();
					if (GUILayout.Button("Select All"))
					{
						ProcessItems(CurrentType, null, HasFilter, actFilter, Items, Selecreplacedems);
					}
					if (GUILayout.Button("Select None"))
					{
						ProcessItems(CurrentType, null, HasFilter, actFilter, Items, Deselecreplacedems);
					}
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.BeginHorizontal();
					if (GUILayout.Button("Remove Checked"))
					{
						ProcessItems(CurrentType, TypeCheckboxes[CurrentType], HasFilter, actFilter, Items, RemoveChecked);
					}
					EditorGUILayout.EndHorizontal();



					EditorGUILayout.BeginHorizontal();
					SelectedMaterial = (UMAMaterial)EditorGUILayout.ObjectField(SelectedMaterial, typeof(UMAMaterial), false);
					GUILayout.Label("Apply to checked: ");
					if (GUILayout.Button("Unreplacedigned"))
					{
						ProcessItems(CurrentType, TypeCheckboxes[CurrentType], HasFilter, actFilter, Items, SereplacedemNullMaterial);
					}
					if (GUILayout.Button("All"))
					{
						ProcessItems(CurrentType, TypeCheckboxes[CurrentType], HasFilter, actFilter, Items, SereplacedemMaterial);
					}
					EditorGUILayout.EndHorizontal();
					GUIHelper.EndVerticalPadded(5);
				}

				GUIHelper.EndVerticalPadded(5);
			}
			return NotFound;
		}

19 View Source File : UtilsTest.cs
License : GNU General Public License v3.0
Project Creator : aloopkin

[TestMethod]
        public void DomainsToFriendlyNameTest()
        {
            List<string> domains = new List<string>();
            domains.Add("test2.example.com");
            domains.Add("test.example.com");
            domains.Sort();
            string friendlyName = Utils.DomainsToFriendlyName(domains);
            if (!friendlyName.Equals("testexamplecom00")) {
                // we're not ok
                replacedert.Fail();
            }
        }

19 View Source File : AtlasPacker.cs
License : MIT License
Project Creator : Alan-FGR

public void Save(string filename, Dictionary<string, Rectangle> map)
    {
//        Packer.GetSpriteName = (spriteName,fullpath) =>
//        {
//            if (fullpath.Contains("PLAYABLE")) return "Plr_"+spriteName; 
//            if (fullpath.Contains("CHARACTER")) return "Char_"+spriteName;
//            if (fullpath.Contains("WALLS")) return "Wall_"+spriteName;
//            if (fullpath.Contains("BLUEPRINT")) return "BPS_"+spriteName;
//            return "Obj_"+spriteName;
//        };

        // copy the files list and sort alphabetically
        string[] keys = new string[map.Count];
        map.Keys.CopyTo(keys, 0);
        List<string> outputFiles = new List<string>(keys);
        outputFiles.Sort();

        List<IdRect> IDs = new List<IdRect>();
        bool hasMissing = false;
        foreach (var fullpath in outputFiles)
        {
            // get the destination rectangle
            Rectangle destination = map[fullpath];

            string spriteName;
            if (fullpath.Contains("MISSING_SPRITE"))
            {
                spriteName = "MISSING_SPRITE";
                hasMissing = true;
            }
            else
                spriteName = namerFunc(fullpath);
                
            //sanitize string
            const string regexPattern = @"[^a-zA-Z0-9]";
            spriteName = Regex.Replace(spriteName, regexPattern, "_");
            IDs.Add(new IdRect {varName = spriteName, rect = destination});
        }

        if (!hasMissing)
        {
            Dbg.Write("No missing sprite image provided! Please make an image called MISSING_SPRITE.png in your atlas directory for meaningful visual debugging helper");
            IDs.Add(new IdRect {varName = "MISSING_SPRITE", rect = new Rectangle(0,0,32,32)});
        }


        using (StreamWriter writer = new StreamWriter(filename))
        {
            writer.Write("public static clreplaced Atlas {");

            foreach (IdRect idRect in IDs)
            {
                float x = idRect.rect.X/atlreplacedize;
                float y = idRect.rect.Y/atlreplacedize;
                float w = idRect.rect.Width/atlreplacedize;
                float h = idRect.rect.Height/atlreplacedize;
                if (idRect.varName == "MISSING_SPRITE")
                    writer.WriteLine($" public const int {idRect.varName} = 0;");
                else
                    writer.WriteLine($" public const int {idRect.varName} = {idRect.varName.GetHashCode()};");
            }

            writer.WriteLine("public static void RegisterPipelinereplacedets() {");

            foreach (IdRect idRect in IDs)
            {
                float x = idRect.rect.X/atlreplacedize;
                float y = idRect.rect.Y/atlreplacedize;
                float w = idRect.rect.Width/atlreplacedize;
                float h = idRect.rect.Height/atlreplacedize;
                if (idRect.varName == "MISSING_SPRITE")//TODO don't use add
                    writer.WriteLine($" Sheet.Sprites[{idRect.varName}] = new RectF({x}f,{y}f,{w}f,{h}f);");
                else
                    writer.WriteLine($" Sheet.Sprites.Add({idRect.varName}, new RectF({x}f,{y}f,{w}f,{h}f));");
            }

            writer.Write("}}");
        }


        #region oldreplaced
        /*
        using (StreamWriter writer = new StreamWriter(filename))
        {
            writer.Write(@"
            using System.Collections.Generic;

            public static clreplaced Sheet
            {
                public static readonly Dictionary<ID, RectF> Sprites = new Dictionary<ID, RectF>();

                public enum ID
                {
            ");
            foreach (IdRect idRect in IDs)
            {
                writer.WriteLine("        "+idRect.varName+",");
            }

            writer.Write(@"
            }

            static Sheet()
            {
            ");

            foreach (IdRect idRect in IDs)
            {
                float x = idRect.rect.X/atlreplacedize;
                float y = idRect.rect.Y/atlreplacedize;
                float w = idRect.rect.Width/atlreplacedize;
                float h = idRect.rect.Height/atlreplacedize;

                writer.WriteLine($"        Sprites[ID.{idRect.varName}] = new RectF({x}f,{y}f,{w}f,{h}f);");
            }

            writer.Write(@"
            }
            public static RectF Get(ID id)
            {
                return Sprites[id];
            }
            }
            ");
        }
        */
        #endregion
    }

19 View Source File : Map.cs
License : MIT License
Project Creator : amidos2006

private List<int[]> getConnectionPoints(Cell from, Cell to, int maxIterations){
            int accessLevel = Math.Min(from.node.accessLevel, to.node.accessLevel);
            List<TreeNode> queue = new List<TreeNode>();
            foreach (int[] dir in directions)
            {
                int newX = from.x + dir[0];
                int newY = from.y + dir[1];
                queue.Add(new TreeNode(newX, newY, new TreeNode(from.x, from.y, null, to.x, to.y), to.x, to.y));
            }
            HashSet<string> visited = new HashSet<string>();
            visited.Add(from.x + "," + from.y);
            while (queue.Count > 0)
            {
                queue.Sort();
                TreeNode current = queue[0];
                queue.Remove(current);
                if (current.x == to.x && current.y == to.y){
                    return current.getPath();
                }
                if(this.usedSpaces.ContainsKey(current.x + "," + current.y) && 
                    this.usedSpaces[current.x + "," + current.y].type == CellType.Normal){
                    if(this.usedSpaces[current.x + "," + current.y].node.accessLevel > accessLevel){
                        continue;
                    }
                    List<int[]> dungeonPath = this.getDungeonPath(this.usedSpaces[current.x + "," + current.y], to, accessLevel);
                    if(dungeonPath.Count > 0){
                        return current.getPath();
                    }
                }
                if(from.parent != null && current.x == from.parent.x && current.y == from.parent.y){
                    continue;
                }
                if (visited.Contains(current.x + "," + current.y)){
                    continue;
                }
                if(visited.Count > maxIterations){
                    return new List<int[]>();
                }
                visited.Add(current.x + "," + current.y);
                foreach (int[] dir in directions)
                {
                    int newX = current.x + dir[0];
                    int newY = current.y + dir[1];
                    queue.Add(new TreeNode(newX, newY, current, to.x, to.y));
                }
            }
            return new List<int[]>();
        }

19 View Source File : ExampleManager.cs
License : MIT License
Project Creator : ABTSoftware

public static IDictionary<string, string> GetAllExampleDefinitions()
        {
            var dictionary = new Dictionary<string, string>();
            var replacedembly = typeof(ExampleManager).replacedembly;

            var exampleNames = replacedembly.GetManifestResourceNames().Where(x => x.Contains("ExampleSourceFiles")).ToList();
            exampleNames.Sort();

            foreach (var example in exampleNames)
            {
                using (var s = replacedembly.GetManifestResourceStream(example))
                using (var sr = new StreamReader(s))
                {
                    dictionary.Add(example.Replace("SciChart.Example.Resources.ExampleDefinitions.", string.Empty),
                                   sr.ReadToEnd());
                }
            }
            return dictionary;
        }

19 View Source File : CopyRevision.cs
License : Apache License 2.0
Project Creator : AmpScm

public void OnExecute(CommandEventArgs e)
        {
            StringBuilder sb = new StringBuilder();

            List<long> revs = new List<long>();

            foreach (ISvnLogItem li in e.Selection.GetSelection<ISvnLogItem>())
            {
                revs.Add(li.Revision);
            }

            revs.Sort();

            foreach(long r in revs)
            {
                if (sb.Length > 0)
                    sb.Append(",");

                sb.Append(r);
            }

            Clipboard.SetText(sb.ToString(), TextDataFormat.Text);
        }

19 View Source File : TextureConverter.cs
License : MIT License
Project Creator : Alan-FGR

private List<float> SearchCrossingEdges(Vertices polygon, int y)
        {
            // sick-o-note:
            // Used to search the x coordinates of edges in the polygon for a specific y coordinate.
            // (Usualy comming from the texture data, that's why it's an int and not a float.)

            List<float> edges = new List<float>();

            // current edge
            Vector2 slope;
            Vector2 vertex1;    // i
            Vector2 vertex2;    // i - 1

            // next edge
            Vector2 nextSlope;
            Vector2 nextVertex; // i + 1

            bool addFind;

            if (polygon.Count > 2)
            {
                // There is a gap between the last and the first vertex in the vertex list.
                // We will bridge that by setting the last vertex (vertex2) to the last 
                // vertex in the list.
                vertex2 = polygon[polygon.Count - 1];

                // We are moving along the polygon edges.
                for (int i = 0; i < polygon.Count; i++)
                {
                    vertex1 = polygon[i];

                    // Approx. check if the edge crosses our y coord.
                    if ((vertex1.Y >= y && vertex2.Y <= y) ||
                        (vertex1.Y <= y && vertex2.Y >= y))
                    {
                        // Ignore edges that are parallel to y.
                        if (vertex1.Y != vertex2.Y)
                        {
                            addFind = true;
                            slope = vertex2 - vertex1;

                            // Special threatment for edges that end at the y coord.
                            if (vertex1.Y == y)
                            {
                                // Create preview of the next edge.
                                nextVertex = polygon[(i + 1) % polygon.Count];
                                nextSlope = vertex1 - nextVertex;

                                // Ignore peaks. 
                                // If thwo edges are aligned like this: /\ and the y coordinate lies on the top,
                                // then we get the same x coord twice and we don't need that.
                                if (slope.Y > 0)
                                    addFind = (nextSlope.Y <= 0);
                                else
                                    addFind = (nextSlope.Y >= 0);
                            }

                            if (addFind)
                                edges.Add((y - vertex1.Y) / slope.Y * slope.X + vertex1.X); // Calculate and add the x coord.
                        }
                    }

                    // vertex1 becomes vertex2 :).
                    vertex2 = vertex1;
                }
            }

            edges.Sort();
            return edges;
        }

19 View Source File : SessionExtensions.cs
License : MIT License
Project Creator : anderm

public static string GetUnusedName(this Session session, string baseName, int excludedUserId, List<string> cachedList)
        {
            cachedList.Clear();

            for (int i = 0; i < session.GetUserCount(); i++)
            {
                using (var user = session.GetUser(i))
                using (var userName = user.GetName())
                {
                    string userNameString = userName.GetString();
                    if (user.GetID() != excludedUserId && userNameString.StartsWith(baseName))
                    {
                        cachedList.Add(userNameString);
                    }
                }
            }

            cachedList.Sort();

            int counter = 0;
            string currentName = baseName;
            while (cachedList.Contains(currentName))
            {
                currentName = baseName + (++counter);
            }

            return currentName;
        }

19 View Source File : BaseApiClient.cs
License : MIT License
Project Creator : 4egod

protected AuthenticationHeaderValue GetAuthorizationHeader(string uri, HttpMethod method)
        {
            string nonce = DateTime.Now.Ticks.ToString();
            string timestamp = DateTime.Now.ToUnixTimestamp().ToString();

            List<string> authParams = new List<string>();
            authParams.Add("oauth_consumer_key=" + ConsumerKey);
            authParams.Add("oauth_nonce=" + nonce);
            authParams.Add("oauth_signature_method=HMAC-SHA1");
            authParams.Add("oauth_timestamp=" + timestamp);
            authParams.Add("oauth_token=" + AccessToken);
            authParams.Add("oauth_version=1.0");

            SplitUri(uri, out string url, out string[] queryParams);

            List<string> requestParams = new List<string>(authParams);
            requestParams.AddRange(queryParams);
            requestParams.Sort();

            string signatureBaseString = string.Join("&", requestParams);
            signatureBaseString = string.Concat(method.Method.ToUpper(), "&", Uri.EscapeDataString(url), "&", Uri.EscapeDataString(signatureBaseString));

            string signature = GetSignature(signatureBaseString);

            string hv = string.Join(", ", authParams.Select(x => x.Replace("=", " = \"") + '"'));
            hv += $", oauth_signature=\"{Uri.EscapeDataString(signature)}\"";      

            return new AuthenticationHeaderValue("OAuth", hv);
        }

19 View Source File : State.cs
License : Apache License 2.0
Project Creator : AnkiUniversal

public List<char> GetAllTransitionStrings()
        {
            List<char> retList = new List<char>();

            foreach (Arc arc in arcs)
            {
                retList.Add(arc.GetLabel());
            }
            retList.Sort();
            return retList;
        }

19 View Source File : Common.cs
License : MIT License
Project Creator : AlaricGilbert

public static string GetSign(string url)
        {
            string result;
            string str = url.Substring(url.IndexOf("?", 4) + 1);
            List<string> list = str.Split('&').ToList();
            list.Sort();
            StringBuilder stringBuilder = new StringBuilder();
            foreach (string str1 in list)
            {
                stringBuilder.Append((stringBuilder.Length > 0 ? "&" : string.Empty));
                stringBuilder.Append(str1);
            }
            stringBuilder.Append(AppSecret);
            result = MD5.GetMd5String(stringBuilder.ToString()).ToLower();
            return result;
        }

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

private static void AutoApplyWorldCustomizations()
        {
            var content_folders_search_option = ConfigManager.Config.Offline.RecurseWorldCustomizationPaths ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
            var content_folders = new List<string> { GetContentFolder() };
            content_folders.AddRange(ConfigManager.Config.Offline.WorldCustomizationAddedPaths);
            content_folders.Sort();

            Console.WriteLine($"Searching for World Customization SQL scripts .... ");

            content_folders.ForEach(path =>
            {
                var contentDI = new DirectoryInfo(path);
                if (contentDI.Exists)
                {
                    Console.Write($"Searching for SQL files within {path} .... ");

                    foreach (var file in contentDI.GetFiles("*.sql", content_folders_search_option).OrderBy(f => f.FullName))
                    {
                        Console.Write($"Found {file.FullName} .... ");
                        var sqlDBFile = File.ReadAllText(file.FullName);
                        var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection($"server={ConfigManager.Config.MySql.World.Host};port={ConfigManager.Config.MySql.World.Port};user={ConfigManager.Config.MySql.World.Username};preplacedword={ConfigManager.Config.MySql.World.Preplacedword};database={ConfigManager.Config.MySql.World.Database};DefaultCommandTimeout=120");
                        sqlDBFile = sqlDBFile.Replace("ace_world", ConfigManager.Config.MySql.World.Database);
                        var script = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, sqlDBFile);

                        Console.Write($"Importing into World database on SQL server at {ConfigManager.Config.MySql.World.Host}:{ConfigManager.Config.MySql.World.Port} .... ");
                        try
                        {
                            script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
                            var count = script.Execute();
                            //Console.Write($" {count} database records affected ....");
                            Console.WriteLine(" complete!");
                        }
                        catch (MySql.Data.MySqlClient.MySqlException ex)
                        {
                            Console.WriteLine($" error!");
                            Console.WriteLine($" Unable to apply patch due to following exception: {ex}");
                        }
                    }
                }
            });

            Console.WriteLine($"World Customization SQL scripts import complete!");
        }

19 View Source File : YmlFormatUtil.cs
License : Apache License 2.0
Project Creator : 214175590

public static List<YmlLine> FormatYml(string content, bool beautify = false)
        {
            List<YmlLine> list = new List<YmlLine>();
            string[] lines = content.Split('\n');
            YmlLine ylText = null;
            int index1 = -1, index2 = -1, count = 0, num = 0;
            string startStr = null, endStr = null, line = "";
            string key = null, value = null, mh = ":";
            List<int> levels = new List<int>();
            for(int i = 0, k = lines.Length; i < k; i++){
                line = lines[i];

                if(line.TrimStart().StartsWith("#")){
                    ylText = new YmlLine()
                    {
                        Text = line + "\n",
                        Color = Color.Gray
                    };
                    list.Add(ylText);
                }
                else
                {
                    // 非整行注释

                    // 美化
                    if (beautify)
                    {
                        count = StartSpaceCount(line);
                        if (count == 0)
                        {
                            levels.Clear();
                        }
                        // level
                        if (!levels.Contains(count))
                        {
                            levels.Add(count);
                            levels.Sort();
                        }
                        num = levels.IndexOf(count) * 4;
                        if (num > count)
                        {
                            line = GetSpace(num - count) + line;
                        }
                    }                    

                    // 行中有井号,但不是首位#
                    index2 = line.IndexOf("#");
                    if(index2 > 0){
                        startStr = line.Substring(0, index2);

                        index1 = startStr.IndexOf(":");
                        if (index1 > 0)
                        {
                            // key
                            key = startStr.Substring(0, index1);
                            ylText = new YmlLine()
                            {
                                Text = key,
                                Color = Color.OrangeRed
                            };
                            list.Add(ylText);
                            // :
                            ylText = new YmlLine()
                            {
                                Text = mh,
                                Color = Color.Violet
                            };
                            list.Add(ylText);
                            // value
                            value = startStr.Substring(index1 + 1);
                            ylText = new YmlLine()
                            {
                                Text = value,
                                Color = getTextColor(value)
                            };
                            list.Add(ylText);
                        }
                        else
                        {
                            ylText = new YmlLine()
                            {
                                Text = "#" + startStr,
                                Color = Color.Gray
                            };
                            list.Add(ylText);
                        }

                        // 注释掉的部分
                        endStr = line.Substring(index2);
                        ylText = new YmlLine()
                        {
                            Text = endStr + "\n",
                            Color = Color.Gray
                        };
                        list.Add(ylText);
                    }
                    else
                    {
                        // 行中无井号
                        startStr = line;

                        index1 = startStr.IndexOf(":");
                        if (index1 > 0)
                        {
                            // key
                            key = startStr.Substring(0, index1);
                            ylText = new YmlLine()
                            {
                                Text = key,
                                Color = Color.OrangeRed
                            };
                            list.Add(ylText);
                            // :
                            ylText = new YmlLine()
                            {
                                Text = mh,
                                Color = Color.Violet
                            };
                            list.Add(ylText);
                            // value
                            value = startStr.Substring(index1 + 1);
                            ylText = new YmlLine()
                            {
                                Text = value + "\n",
                                Color = getTextColor(value)
                            };
                            list.Add(ylText);
                        }
                        else
                        {
                            // 行中无井号,且是不合规的配置值
                            if (string.IsNullOrWhiteSpace(line))
                            {
                                ylText = new YmlLine()
                                {
                                    Text = line + "\n",
                                    Color = Color.OrangeRed
                                };
                            }
                            else
                            {
                                ylText = new YmlLine()
                                {
                                    Text = "#" + line + "\n",
                                    Color = Color.Gray
                                };
                            }                            
                            list.Add(ylText);                            
                        }
                    }
                }
            }
            return list;
        }

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

private void Init()
		{
			if (_skelModPropDrawer == null)
				_skelModPropDrawer = new SkeletonModifierPropertyDrawer();

			hashNames.Clear();
			hashes.Clear();
			SerializedProperty hashList = serializedObject.FindProperty("hashList");
			for (int i = 0; i < hashList.arraySize; i++)
			{
				hashNames.Add(hashList.GetArrayElementAtIndex(i).FindPropertyRelative("hashName").stringValue);
				hashes.Add(hashList.GetArrayElementAtIndex(i).FindPropertyRelative("hash").intValue);
			}
			if (minimalMode == false)
			{
				bonesInSkeleton = new List<string>(hashNames.ToArray());
			}
			else
			{
				bonesInSkeleton = new List<string>(umaData.skeleton.BoneNames);
			}
			bonesInSkeleton.Sort();
			UpdateDnaNames();
			initialized = true;
		}

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : abishekaditya

static void Main()
        {
            var tea = new Tea();
            var coffee = new Coffee();
            tea.WantsCondiments = true;
            tea.AddSugar = 5;
            tea.Prepare();

            Console.WriteLine();
            coffee.WantsCondiments = true;
            coffee.Prepare();

            var people = new List<Person> { new Person("Ram", 25), new Person("Abishek", 12), new Person("Ram", 18), new Person("Abishek", 18) };
            foreach (var person in people)
            {
                Console.Write(person);
            }
            people.Sort();
            Console.WriteLine();
            foreach (var person in people)
            {
                Console.Write(person);
            }
        }

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

private Texture2D CreateCustomCharacter(RNPC npc, string type)
        {
            Texture2D sprite = this.Helper.Content.Load<Texture2D>("replacedets/body/" + npc.bodyType + "_" + type + ".png", ContentSource.ModFolder);
            Texture2D hairT = this.Helper.Content.Load<Texture2D>("replacedets/hair/" + npc.hairStyle + "_" + type + ".png", ContentSource.ModFolder);
            Texture2D eyeT = this.Helper.Content.Load<Texture2D>("replacedets/body/" + npc.gender + "_eyes_" + type + ".png", ContentSource.ModFolder);

            Texture2D eyeBackT = null;
            Texture2D noseT = null;
            Texture2D mouthT = null;
            if (type == "portrait")
            {
                eyeBackT = this.Helper.Content.Load<Texture2D>("replacedets/body/" + npc.gender + "_eyes_back.png", ContentSource.ModFolder);
                noseT = this.Helper.Content.Load<Texture2D>("replacedets/body/" + npc.gender + "_nose.png", ContentSource.ModFolder);
                mouthT = this.Helper.Content.Load<Texture2D>("replacedets/body/" + npc.gender + "_mouth.png", ContentSource.ModFolder);
            }
            Texture2D topT = this.Helper.Content.Load<Texture2D>("replacedets/transparent_" + type + ".png", ContentSource.ModFolder);
            Texture2D bottomT = topT;
            Texture2D shoesT = topT;

            // clothes

            // try and share with other type (char/portrait)
            string[] clothes;
            if (npc.clothes != null)
            {
                clothes = npc.clothes;
            }
            else
            {
                string npcString = string.Join("/", npc.npcString.Split('/').Take(7)) + "/" + npc.bodyType;
                List<string> potentialClothes = GetHighestRankedStrings(npcString, RNPCclothes.data, 8);

                clothes = potentialClothes[Game1.random.Next(0, potentialClothes.Count)].Split('^');
                //base.Monitor.Log(string.Join(" | ", clothes), LogLevel.Debug);
                npc.clothes = clothes;
                npc.topRandomColour = new string[] { Game1.random.Next(0, 255).ToString(), Game1.random.Next(0, 255).ToString(), Game1.random.Next(0, 255).ToString() };
            }

            if (clothes[0] != "")
            {
                topT = this.Helper.Content.Load<Texture2D>("replacedets/clothes/" + clothes[0] + "_" + type + ".png", ContentSource.ModFolder);
            }
            if (clothes[1] != "" && type == "character")
            {
                bottomT = this.Helper.Content.Load<Texture2D>("replacedets/clothes/" + clothes[1] + ".png", ContentSource.ModFolder);
            }
            if (clothes[2] != "" && type == "character")
            {
                shoesT = this.Helper.Content.Load<Texture2D>("replacedets/clothes/" + clothes[2] + ".png", ContentSource.ModFolder);
            }

            Color[] data = new Color[sprite.Width * sprite.Height];
            Color[] dataH = new Color[hairT.Width * hairT.Height];
            Color[] dataE = new Color[eyeT.Width * eyeT.Height];
            Color[] dataEB = null;
            Color[] dataN = null;
            Color[] dataM = null;
            if (type == "portrait")
            {
                dataEB = new Color[eyeBackT.Width * eyeBackT.Height];
                dataN = new Color[noseT.Width * noseT.Height];
                dataM = new Color[mouthT.Width * mouthT.Height];
            }
            Color[] dataT = new Color[topT.Width * topT.Height];
            Color[] dataB = new Color[bottomT.Width * bottomT.Height];
            Color[] dataS = new Color[shoesT.Width * shoesT.Height];
            sprite.GetData(data);
            hairT.GetData(dataH);
            eyeT.GetData(dataE);
            if (type == "portrait")
            {
                eyeBackT.GetData(dataEB);
                noseT.GetData(dataN);
                mouthT.GetData(dataM);
            }
            topT.GetData(dataT);
            bottomT.GetData(dataB);
            shoesT.GetData(dataS);

            string[] skinRBG = npc.skinColour.Split(' ');
            string[] eyeRBG = npc.eyeColour.Split(' ');
            List<string> hairRBGs = npc.hairColour.Split('^').ToList();

            string[] baseColourT = clothes[3] == "any" ? npc.topRandomColour : null;

            string[] baseColourB;
            switch (clothes[4])
            {
                case "any":
                    baseColourB = new string[] { Game1.random.Next(0, 255).ToString(), Game1.random.Next(0, 255).ToString(), Game1.random.Next(0, 255).ToString() };
                    break;
                case "top":
                    baseColourB = baseColourT;
                    break;
                default:
                    baseColourB = null;
                    break;
            }
            string[] baseColourS;
            switch (clothes[5])
            {
                case "any":
                    baseColourS = new string[] { Game1.random.Next(0, 255).ToString(), Game1.random.Next(0, 255).ToString(), Game1.random.Next(0, 255).ToString() };
                    break;
                case "top":
                    baseColourS = baseColourT;
                    break;
                case "bottom":
                    baseColourS = baseColourB;
                    break;
                default:
                    baseColourS = null;
                    break;
            }

            // make hair gradient

            List<string> hairGreyStrings = new List<string>();
            for (int i = 0; i < dataH.Length; i++)
            {
                if (dataH[i].R == dataH[i].G && dataH[i].R == dataH[i].B && dataH[i].G == dataH[i].B) // greyscale
                {
                    if (!hairGreyStrings.Contains(dataH[i].R.ToString()))
                    { // only add one of each grey
                        hairGreyStrings.Add(dataH[i].R.ToString());
                    }
                }
            }

            // make same number of greys as colours in gradient

            if (hairRBGs.Count > hairGreyStrings.Count) // ex 9 and 6
            {
                hairGreyStrings = LengthenToMatch(hairGreyStrings, hairRBGs);
            }
            else if (hairRBGs.Count < hairGreyStrings.Count)
            {
                hairRBGs = LengthenToMatch(hairRBGs, hairGreyStrings);

            }
            List<byte> hairGreys = new List<byte>();
            foreach (string str in hairGreyStrings)
            {
                hairGreys.Add(byte.Parse(str));
            }
            hairGreys.Sort();
            hairGreys.Reverse(); // lightest to darkest
            //Alert(hairGreys.Count+ " " +hairRBGs.Count);
            
            // start putting it together

            for (int i = 0; i < data.Length; i++)
            {
                if (dataH.Length > i && dataH[i] != Color.Transparent)
                {
                    if (dataH[i].R == dataH[i].G && dataH[i].R == dataH[i].B && dataH[i].G == dataH[i].B) // greyscale
                    {
                        // hair gradient

                        // for cases where fewer greys than colours (multiple of same grey)
                        List<int> greyMatches = new List<int>();
                        for (int j = 0; j < hairGreys.Count; j++)
                        {
                            if (hairGreys[j] == dataH[i].R)
                            {
                                greyMatches.Add(j);
                            }
                        }

                        string[] hairRBG;
                        int rnd = Game1.random.Next(0, greyMatches.Count);
                        int match = greyMatches[rnd];
                        hairRBG = hairRBGs[match].Split(' '); // turns single grey into set of colours

                        data[i] = new Color(byte.Parse(hairRBG[0]), byte.Parse(hairRBG[1]), byte.Parse(hairRBG[2]), dataH[i].A);
                    }
                    else // ignore already coloured parts
                    {
                        data[i] = dataH[i];
                    }
                }
                else if (dataT.Length > i && dataT[i] != Color.Transparent)
                {
                    data[i] = baseColourT != null ? ColorizeGrey(baseColourT, dataT[i]) : dataT[i];
                }
                else if (dataB.Length > i && dataB[i] != Color.Transparent)
                {
                    data[i] = baseColourB != null ? ColorizeGrey(baseColourB, dataB[i]) : dataB[i];
                }
                else if (dataS.Length > i && dataS[i] != Color.Transparent)
                {
                    data[i] = baseColourS != null ? ColorizeGrey(baseColourS, dataS[i]) : dataS[i];
                }
                else if (dataE.Length > i && dataE[i] != Color.Transparent)
                {
                    if (dataE[i] != Color.White)
                    {
                        data[i] = ColorizeGrey(eyeRBG, dataE[i]);
                    }
                    else
                    {
                        data[i] = Color.White;
                    }
                }
                else if (type == "portrait" && dataEB.Length > i && dataEB[i] != Color.Transparent)
                {
                    data[i] = ColorizeGrey(skinRBG, dataEB[i]);
                }
                else if (type == "portrait" && dataN.Length > i && dataN[i] != Color.Transparent)
                {
                    data[i] = ColorizeGrey(skinRBG, dataN[i]);
                }
                else if (type == "portrait" && dataM.Length > i && dataM[i] != Color.Transparent)
                {
                    if (dataM[i] != Color.White)
                    {
                        data[i] = ColorizeGrey(skinRBG, dataM[i]);
                    }
                    else
                    {
                        data[i] = Color.White;
                    }
                }
                else if (data[i] != Color.Transparent)
                {
                    data[i] = ColorizeGrey(skinRBG, data[i]);
                }
            }
            sprite.SetData<Color>(data);
            return sprite;
        }

19 View Source File : Extensions.cs
License : MIT License
Project Creator : AlFasGD

public static int GetNextAvailableNumber(this List<int> numbers)
        {
            int n = 0;
            numbers.Sort();
            while (n < numbers.Count && n == numbers[n])
                n++;
            return n;
        }

See More Examples