Esempio n. 1
1
		public override string ToString()
		{
			StringBuilder builder = new StringBuilder();
			builder.Append("args");//it will be skipped by Urho;

			if (WindowedMode)
				builder.Append(" -w");

			if (!LimitFps)
				builder.Append(" -nolimit");

			if (Width > 0)
				builder.AppendFormat(" -x {0}", Width);

			if (Height > 0)
				builder.AppendFormat(" -y {0}", Height);

			if (ResizableWindow)
				builder.Append(" -s");

			var resourcePathes = new[] {"CoreData"}.Concat(ResourcePaths ?? new string[0]);
			builder.AppendFormat(" -p \"{0}\"", string.Join(";", resourcePathes.Distinct()));

			if (ResourcePackagesPaths?.Length > 0)
				builder.AppendFormat(" -pf \"{0}\"", string.Join(";", ResourcePackagesPaths));

			if (ResourcePrefixPath != null)
				builder.AppendFormat(" -pp \"{0}\"", ResourcePrefixPath);

			if (TouchEmulation)
				builder.Append(" -touch");

			builder.AppendFormat(" -{0}", Orientation.ToString().ToLower());

			return builder + " " + AdditionalFlags;
		}
Esempio n. 2
1
        public void DifferentHashAlgoritmsGiveUniqueHashes()
        {
            var passwords = new[]
                                {
                                    _passwordHashMD5,
                                    _passwordHashSha1,
                                    _passwordHashSha256,
                                    _passwordHashSha384,
                                    _passwordHashSha512

                                };

            int uniquePasswords = passwords.Distinct().Count();
            Assert.That(uniquePasswords, Is.EqualTo(passwords.Length));
        }
        public static Type[] GetLanguageNeutralTypes()
        {
            var types = new[]
            {
                // ROSLYN
                typeof(Microsoft.CodeAnalysis.Editor.Implementation.Workspaces.WorkspaceTaskSchedulerFactoryFactory),
                typeof(Microsoft.CodeAnalysis.Host.WorkspaceTaskSchedulerFactoryFactory),
                typeof(Microsoft.CodeAnalysis.Formatting.Rules.DefaultFormattingRuleFactoryServiceFactory),
                typeof(Microsoft.CodeAnalysis.Host.PersistentStorageServiceFactory),
                typeof(Microsoft.CodeAnalysis.Text.Implementation.TextBufferFactoryService.TextBufferCloneServiceFactory),
                typeof(Microsoft.CodeAnalysis.Host.MetadataServiceFactory),
                typeof(Microsoft.CodeAnalysis.Host.TemporaryStorageServiceFactory),
                typeof(Microsoft.CodeAnalysis.Host.TextFactoryService),
                typeof(Microsoft.CodeAnalysis.Editor.Implementation.Workspaces.ProjectCacheHostServiceFactory),
                typeof(Solution), // ServicesCore
                typeof(Microsoft.CodeAnalysis.Options.GlobalOptionService),
                typeof(Microsoft.CodeAnalysis.Options.OptionServiceFactory),
                typeof(Microsoft.CodeAnalysis.Options.Providers.ExportedOptionProvider),
                typeof(Microsoft.CodeAnalysis.Editor.Implementation.SmartIndent.SmartIndentProvider),
                typeof(Microsoft.CodeAnalysis.Editor.Implementation.ForegroundNotification.ForegroundNotificationService),
                typeof(Microsoft.CodeAnalysis.Editor.UnitTests.TestOptionsServiceFactory),
                typeof(SymbolMapping.SymbolMappingServiceFactory),
                typeof(TestWaitIndicator),
                typeof(TestExtensionErrorHandler)
            };

            return types//.Concat(TestHelpers.GetAllTypesWithStaticFieldsImplementingType(typeof(InternalSolutionCrawlerOptions).Assembly, typeof(Microsoft.CodeAnalysis.Options.IOption)))
                        //.Concat(TestHelpers.GetAllTypesWithStaticFieldsImplementingType(typeof(EditorComponentOnOffOptions).Assembly, typeof(Microsoft.CodeAnalysis.Options.IOption)))
                        //.Concat(TestHelpers.GetAllTypesWithStaticFieldsImplementingType(typeof(ServiceComponentOnOffOptions).Assembly, typeof(Microsoft.CodeAnalysis.Options.IOption)))
                        //.Concat(TestHelpers.GetAllTypesWithStaticFieldsImplementingType(typeof(Microsoft.CodeAnalysis.Formatting.FormattingOptions).Assembly, typeof(Microsoft.CodeAnalysis.Options.IOption)))
                        .Distinct()
                        .ToArray();
        }
Esempio n. 4
0
            public void DuplicatesAreNotReturnedWhenSourceContainsDuplicates()
            {
                var source = new[] { 1, 2, 3, 3 };
                var expected = new[] { 1, 2, 3 };

                Assert.That(source.Distinct(), Is.EqualTo(expected));
            }
        public void ValueIsCorrectWhenInitializedByCtorWithReferences()
        {
            var references = new[] { typeof(object).Assembly, typeof(object).Assembly, typeof(Enumerable).Assembly };
            var sut = new MemberReferenceCollector(references);

            var actual = sut.Value;

            Assert.Equal(references.Distinct(), actual);
        }
        public void ArrayByValueComparerAllTheSame()
        {
            var a = new[]
            {
                new [] { 1,2,3 },
                new [] { 1,2,3 },
                new [] { 1,2,3 },
                new [] { 1,2,3 },
                new [] { 1,2,3 },
            };

            Assert.AreEqual(1, a.Distinct(ArrayByValuesComparer<int>.Instance).Count());
        }
        public void ArrayByValueComparerDifferentLenSequences()
        {
            var a = new[]
            {
                new [] { 1, 2, 3},
                new [] { 1, 2, 3, 4},
                new [] { 1, 2, 3},
                new [] { 1, 2, 3, 4},
                new [] { 1, 2, 3, 4, 5},
            };

            Assert.AreEqual(3, a.Distinct(ArrayByValuesComparer<int>.Instance).Count());
        }
        public void ArrayByValueComparer1()
        {
            var a = new[]
            {
                new [] { 1,2,3 },
                new [] { 1,3,1 },
                new [] { 1,2,2 },
                new [] { 1,2,3 },
                new [] { 1,3,1 },
            };

            Assert.AreEqual(3, a.Distinct(ArrayByValuesComparer<int>.Instance).Count());
        }
Esempio n. 9
0
        public void Equality_comparers_are_useful_when_using_certain_apis_such_as_linq()
        {
            var items = new[]
                            {
                                new ObjectWithoutEqualsOverride(1),
                                new ObjectWithoutEqualsOverride(1),
                                new ObjectWithoutEqualsOverride(2)
                            };

            var comparer = new ObjectWithoutEqualsOverrideComparer();

            var distinctItems = items.Distinct(comparer);

            Assert.AreEqual(2, distinctItems.Count());
        }
Esempio n. 10
0
        public void TestSelectDescendantsAndSelves()
        {
            var graphs = Enumerable.Range(1, 5)
                                   .Select(i => new Graph(i.ToString()))
                                   .ToArray();

            Action<int, int> link = (index1, index2) =>
                graphs[index1 - 1].Links.Add(graphs[index2 - 1]);

            link(1, 2);
            link(1, 3);
            link(2, 1);
            link(2, 4);
            link(3, 2);
            link(3, 4);
            link(4, 5);
            link(4, 5);

            var descendants = new[] { graphs[0] }.SelectDescendantsAndSelves(g => g.Links).ToArray();

            Assert.AreElementsEqualIgnoringOrder(graphs, descendants);
            Assert.AreElementsEqualIgnoringOrder(descendants.Distinct(), descendants);
        }
        private Task UpdatePhpIni(Version version)
        {
            return Task.Run(() =>
            {
                var files = new[]
                {
                    version.Major + ".x.x.ini",
                    version.Major + "." + version.Minor + ".x.ini",
                    version.Major + "." + version.Minor + "." + version.Patch + ".ini",
                    version.Label + ".ini"
                };

                var dir = this.GetVersionDir(version);
                var ini = new StringBuilder();
                foreach (var file in files.Distinct())
                {
                    var path = this.ConfigurationDir + "\\" + file;
                    if (File.Exists(path))
                    {
                        var content = File.ReadAllText(path);
                        content = content.Replace("%phpDir%", dir);
                        ini.AppendLine();
                        ini.AppendLine(content);
                    }
                }

                File.WriteAllText(dir + "\\php.ini", ini.ToString());
            });
        }
        public static void ExtractEmbeddedResources(DirectoryInfo dir, Assembly e, Action<string, string, string, string> handler)
        {
            //System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
            //   at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet)
            //   at System.Security.CodeAccessPermission.Demand()
            //   at System.Reflection.Assembly.VerifyCodeBaseDiscovery(String codeBase)
            //   at System.Reflection.Assembly.GetName(Boolean copiedName)
            //   at System.Reflection.Assembly.GetName()
            //   at ScriptCoreLib.CSharp.Extensions.EmbeddedResourcesExtensions.ExtractEmbeddedResources(DirectoryInfo dir, Assembly e, Action`4 handler)

            // http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/b92c1f6a-9160-42fe-ad2c-4961814d044d/

            // to support partial trust - this workaround should be implemented:
            //Assembly assembly = Assembly.GetEntryAssembly();
            //AssemblyName[] names = assembly.GetReferencedAssemblies();
            //foreach (AssemblyName name in names)
            //{
            //    MessageBox.Show(name.Name + " " + name.Version.ToString());
            //}
            var DefaultResources = new ScriptResourcesAttribute("assets/" + e.GetName().Name);

            ScriptResourcesAttribute[] a =
                GetScriptResourcesAttributes(e)
                .Concat(
                new[] { 
                    // default
                    DefaultResources
                }).OrderByDescending(i => i.Value.Length).ToArray();

            string[] r = e.GetManifestResourceNames();

            AssemblyName n = new AssemblyName(e.FullName);

            var dir_Name = dir == null ? "web" : dir.Name;

            var prefix1 = n.Name + "." + dir_Name;

            Func<AssemblyName, string> GetTopMostNamespace =
                an =>
                {
                    var x = an.Name;
                    var i = x.IndexOf(".");

                    if (i == -1)
                        return x;

                    return x.Substring(0, i);
                };

            var prefix2 = GetTopMostNamespace(n) + "." + dir_Name;

            // fixme: empty directory or overlapping directories with files containing "." .
            // fixme: 
            // "ScriptCoreLib.web.assets.Controls.NatureBoy.dude6.274.png"
            // "ScriptCoreLib.Controls.NatureBoy.web"

            Func<string, string, string> EnsureStartsWith =
                (_prefix, _subject) =>
                {
                    if (_subject.StartsWith(_prefix))
                        return _subject;

                    return _prefix + _subject;
                };

            Func<string, string, string> EnsureNotStartsWith =
               (_prefix, _subject) =>
               {
                   if (_subject.StartsWith(_prefix))
                       return _subject.Substring(_prefix.Length);

                   return _subject;
               };

            var prefixes = new[] { prefix1, prefix2 };

            var query = from v in r
                        from prefix in prefixes.Distinct()
                        where v.StartsWith(prefix)
                        let z = (
                                    from av in a
                                    let ap = prefix + EnsureStartsWith(".", av.Value.Replace('/', '.'))
                                    where v.StartsWith(ap)
                                    select new { ap, av }
                                  ).FirstOrDefault()
                        where z != null
                        let NewSubDir = EnsureNotStartsWith("/", z.av.Value)
                        let t = (string.IsNullOrEmpty(NewSubDir) || dir == null) ? dir : dir.CreateSubdirectory(NewSubDir)
                        let f = string.IsNullOrEmpty(NewSubDir) ? v.Substring(z.ap.Length) : v.Substring(z.ap.Length + 1)
                        // FileInfo cannot be used in partial trust
                        let tf = (t == null ? "" : t.FullName) + "/" + f
                        select new { v, tf, File = f, Path = z.av.Value };

            foreach (var p in query)
            {
                handler(p.v, p.tf, p.Path, p.File);

                //CopyStream(e.GetManifestResourceStream(p.v), p.tf.OpenWrite());
            }
        }
Esempio n. 13
0
 public void AllElementsAreReturnedWhenSourceContainsNoDuplicates()
 {
     var source = new[] { 1, 2, 3 };
     Assert.That(source, Is.EqualTo(source.Distinct()));
 }
Esempio n. 14
0
        static void Main(string[] args)
        {
            var numbers = new[]
            {
            "Gumbi",
            "Nyawo",
            "Dube",
            "Xabadiya",
            "Nyembe",
            "Dlamini",
            "mabaso",
            "Shozi",
            "NGCOBO",
            "Makhanya",
            "Mkhize",
            "Gumede",
            "Xulu",
            "Mkhize",
            "Mbele",
            "Ntinga",
            "Base",
            "MTshali",
            "Madlala",
            "Ngwazi",
            "Sosibo",
            "Sithole",
            "Tobo",
            "MShololo",
            "Mahlanze",
            "Mohloba",
            "Dlamini",
            "Ngcemu",
            "Ngcobo",
            "Bhengu",
            "Khanyile",
            "Mbatha",
            "Masuku",
            "Masuku",
            "Majozi",
            "Mthembu",
            "Gumede",
            "Ngwane",
            "Mashaba",
            "Magwaza",
            "Ngcobo",
            "Khumalo",
            "Khumalo",
            "Luthuli",
            "Bombo",
            "Sibiya",
            "Dlamini",
            "Mzimela",
            "Mkhize",
            "Dlamini",
            "Luthuli",
            "Chamane",
            "Ndlovu",
            "Ndlovu",
            "Dlamini",
            "Zondi",
            "Dlamini",
            "Mhlongo",
            "Ndayile",
            "Magwaza",
            "Hansi",
            "Mthelezi",
            "Xaba",
            "Cele",
            "Mhlongo",
            "Ndlomo",
            "Myeza",
            "Nzimande",
            "Ngcobo",
            "Zuma",
            "Madziba",
            "Khanyeze",
            "Mthembu",
            "NGUSE",
            "NTshiza",
            "Mthimkhulu",
            "Makhathini",
            "Makhathini",
            "Mthembu",
            "MGadi",
            "Nxumalo",
            "Zulu",
            "Zulu",
            "Msizi",
            "Nxumalo",
            "Ngcobo",
            "Sibaliyoni",
            "Zololo",
            "Sibiya",
            "Zama",
            "Qwabe",
            "Xama",
            "Gwane",
            "Dlamini",
            "Maphumulo",
            "Buthelezi",
            "Innes",
            "Mkhwanazi",
            "Mabhushua",
            "MAGENU",
            "Ngcobo",
            "DUBE",
            "Mbatha",
            "Mtshali",
            "Sithole",
            "CELE",
            "Khumalo",
            "Mbatha",
            "Ali",
            "Hadebe",
            "Ngwane",
            "Chili",
            "Mqhokwane",
            "Njaca",
            "Ndelu",
            "Kweyama",
            "Nathe",
            "Makhathini",
            "Ntshangase",
            "Kunene",
            "Mgadi",
            "Ngidi",
            "Mhlongo",
            "Phungula",
            "Mzobe",
            "Ngcobo",
            "Mncwabe",
            "Gcwensa",
            "Nzimande",
            "Luthuli",
            "Khoza",

            };
            var closeNumbers = 0;

            var query = numbers
             .Distinct()
             .SelectMany((val1, j) => numbers.Select((val2, i) => new { v1 = val1, v2 = val2, i = i, j = j }))
             .Where(x => x.i < x.j).ToArray();

            var result = query.Select(x => new {Distance = LevenshteinDistance.Compute(x.v1 , x.v2),x.v1,x.v2,x.i,x.j})
                              .OrderBy(x=>x.Distance)
                              .ToArray();

            Console.WriteLine(closeNumbers);

            Console.ReadLine();
        }
Esempio n. 15
0
 public IHttpActionResult Roles()
 {
     var roles = new[] {"User", "Administrator"};
     return Ok(roles.Distinct().Select(t => new { Name = t }));
 }
Esempio n. 16
0
 public IHttpActionResult Levels()
 {
     var levels = new[] { "100", "200", "300" };
     return Ok(levels.Distinct().Select(t => new { Name = t }));
 }
Esempio n. 17
0
        /// <summary>
        /// Gets the mode of a Color[]
        /// </summary>
        /// <param name="colors">Array of Colors</param>
        /// <returns>Index of mode, -1 if non found</returns>
        private int GetModeOfColorArray(System.Drawing.Color[] colors)
        {
            System.Drawing.Color[] distinctcolors = colors.Distinct().ToArray();
            int[] countcolors = new int[distinctcolors.Length];
            int highest = 1;
            int highestindex = -1;
            Boolean mode = false;

            //count how many time distinct values are in colors
            for (int i = 0; i < distinctcolors.Length; i++)
            {
                for (int x = 0; x < colors.Length; x++)
                {
                    if (colors[x] == distinctcolors[i])
                        countcolors[i]++;
                }
            }
            //check what the highest value is
            for (int i = 0; i < countcolors.Length; i++)
            {
                if (countcolors[i] > highest)
                {
                    highest = countcolors[i];
                    highestindex = i;
                    mode = true;
                }
            }

            if (mode)
                return Array.IndexOf(colors, distinctcolors[highestindex]);
            else
                return -1;
        }
Esempio n. 18
0
 public IEnumerable<string> GetAllPossibleWordsInFile(IDeclaredElement element)
 {
     var res = new[] {element.ShortName, element.ShortName.ToLowerInvariant(), element.ShortName.ToUpperInvariant()};
       return res.Distinct();
 }
Esempio n. 19
0
        static void Main(string[] args)
        {
            var data = Enumerable.Range(1, 50);

            var method = // IEnumerable<string>
                 data.Where(x => x % 2 == 0)
                 .Select(x => x.ToString());

            var query = // IEnumerable<string>
                from d in data
                where d % 2 == 0
                select d.ToString();

            Debugger.Break();

            var projection =
                from d in data
                select new
                {
                    Even = (d % 2 == 0),
                    Odd = !(d % 2 == 0),
                    Value = d,
                };

            var letters = new[] { "A", "C", "B", "E", "Q" };

            Debugger.Break();

            var sortAsc =
                from d in data
                orderby d ascending
                select d;

            var sortDesc =
                data.OrderByDescending(x => x);

            Debugger.Break();

            // candy

            var values = new[] { "A", "B", "A", "C", "A", "D" };

            var distinct = values.Distinct();
            var first = values.First();
            var firstOr = values.FirstOrDefault();
            var last = values.Last();
            var page = values.Skip(2).Take(2);

            Debugger.Break();

            // aggregates

            var numbers = Enumerable.Range(1, 50);
            var any = numbers.Any(x => x % 2 == 0);
            var count = numbers.Count(x => x % 2 == 0);
            var sum = numbers.Sum();
            var max = numbers.Max();
            var min = numbers.Min();
            var avg = numbers.Average();

            Debugger.Break();

            var dictionary = new Dictionary<string, string>()
            {
                 {"1", "B"}, {"2", "A"}, {"3", "B"}, {"4", "A"},
            };

            var group = // IEnumerable<string, IEnumerable<string>>
                from d1 in dictionary
                group d1 by d1.Value into g
                select new
                {
                    Key = g.Key,
                    Members = g,
                };

            Debugger.Break();

            var dictionary1 = new Dictionary<string, string>()
            {
                 {"1", "B"}, {"2", "A"}, {"3", "B"}, {"4", "A"},
            };

            var dictionary2 = new Dictionary<string, string>()
            {
                 {"5", "B"}, {"6", "A"}, {"7", "B"}, {"8", "A"},
            };

            var join =
                from d1 in dictionary1
                join d2 in dictionary2 on d1.Value equals d2.Value
                select new
                {
                    Key1 = d1.Key,
                    Key2 = d2.Key,
                    Value = d1.Value
                };

            Debugger.Break();
        }
        public void Distinct()
        {
            var objs = new { A = 1, B = 2 }
                .And(new { A = 1, B = 42 });

            Assert.AreEqual("(2,42)", objs.Distinct(o => o.B).Print());
            Assert.AreEqual("(1)", objs.Distinct(o => o.A).Print());
        }
        public void Distinct_WithSelector()
        {
            var items = new[]
                            {
                                new TestSubject { Number =1, Text = "Foo"},
                                new TestSubject { Number =1, Text = "Bar"},
                                new TestSubject { Number =2, Text = "Foo"},
                                new TestSubject { Number =3, Text = "Baz"}
                            };

            Assert.IsTrue(items.Distinct(x => x.Number).Select(x => x.Text).SequenceEqual(new[] { "Foo", "Foo", "Baz" }));
            Assert.IsTrue(items.Distinct(x => x.Text).Select(x => x.Text).SequenceEqual(new[] { "Foo", "Bar", "Baz" }));
        }
            public void RemoveDuplicateKeys()
            {
                var items = new[] { new Item { Key = "Key1" }, new Item { Key = "Key2" }, new Item { Key = "Key1" }, new Item { Key = "Key3" } };
                var distinctItems = items.Distinct(item => item.Key).ToArray();

                Assert.Equal(3, distinctItems.Count());
                Assert.Same(items[0], distinctItems[0]);
                Assert.Same(items[1], distinctItems[1]);
                Assert.Same(items[3], distinctItems[2]);
            }
        /// <summary>
        /// Gets the additional namespaces that should be imported for queries using this driver
        /// </summary>
        /// <param name="props">the deserialized ConnectionProperties object.</param>
        /// <returns>The namespaces that should be imported as strings</returns>
        public static IEnumerable<string> GetNamespacesToAdd(ConnectionProperties props)
        {
            IEnumerable<string> ret = new[]
                {
                    "MongoDB.Driver.Builders",
                    "MongoDB.Driver",
                };

            if(!string.IsNullOrEmpty(props.SelectedDatabase))
            {
                ret = ret.Concat(
                props.CollectionTypeMappings[props.SelectedDatabase].Select(x => x.CollectionType)
                    .Where(x => !string.IsNullOrEmpty(x))
                    .Select(name =>
                    {
                        name = name.Split(',').First();
                        int lastDot = name.LastIndexOf('.');
                        if (lastDot <= -1)
                            return null;

                        return name.Substring(0, lastDot);
                    }).Where(x => !string.IsNullOrEmpty(x)));
            }

            return ret.Distinct();
        }
            public void ReturnFirstInstanceOfKey()
            {
                var items = new[] { new Item { Key = "Key1" }, new Item { Key = "Key2" }, new Item { Key = "Key1" } };
                var distinct = items.Distinct(item => item.Key);

                Assert.Same(items[0], distinct.First());
            }
Esempio n. 25
0
    public void CreateQueryModel_AppliesResultOperators ()
    {
      IQueryable<int> value = new[] { 1, 2, 3 }.AsQueryable ();
      var expressionTree = (MethodCallExpression) ExpressionHelper.MakeExpression (() => value.Distinct().Count ());

      QueryModel queryModel = _queryParser.GetParsedQuery (expressionTree);

      Assert.That (queryModel.ResultOperators.Count, Is.EqualTo (2));
      Assert.That (queryModel.ResultOperators[0], Is.InstanceOf (typeof (DistinctResultOperator)));
      Assert.That (queryModel.ResultOperators[1], Is.InstanceOf (typeof (CountResultOperator)));
    }
Esempio n. 26
0
 public void Distinct()
 {
     var items = new[] { 1, 3, 6, 3, 4, 1 };
     var distinct = items.Distinct().ToArray();
     AssertEquals(distinct.Length, 4);
     AssertEquals(distinct[0], 1);
     AssertEquals(distinct[1], 3);
     AssertEquals(distinct[2], 6);
     AssertEquals(distinct[3], 4);
 }
        private void MapTypeToCollectionName(Type type, CollectionData collectionData)
        {
            var byUserConvention = userSuppliedConventions(type);
            var ravenDefault = Raven.Client.Document.DocumentConvention.DefaultTypeTagName(type);
            var byLegacy = LegacyFindTypeTagName(type);

            var mappingsInPriorityOrder = new[]
            {
                byUserConvention,
                ravenDefault,
                byLegacy
            };

            var configuredName = mappingsInPriorityOrder
                .Distinct()
                .SingleOrDefault(name => collectionData.Collections.Contains(name));

            if (configuredName == null)
            {
                if (collectionData.IndexResults == null)
                {
                    collectionData.IndexResults = GetTerms();
                }

                var collectionsThatExist = mappingsInPriorityOrder
                    .Distinct()
                    .Where(name => collectionData.IndexResults.Contains(name))
                    .ToArray();


                if (collectionsThatExist.Length > 1)
                {
                    var options = string.Join(", ", collectionsThatExist);
                    throw new InvalidOperationException($"Multiple RavenDB collection names ({options}) found for type `{type.FullName}`. Unable to determine DocumentId naming strategy for this type. Remove or modify the documents that were mapped incorrectly.");
                }

                configuredName = collectionsThatExist.FirstOrDefault() ?? ravenDefault;
                collectionData.Collections.Add(configuredName);
                collectionData.Changed = true;
            }

            collectionData.Mappings.Add(type, configuredName);
        }
Esempio n. 28
-1
        public void OptimizeChunks()
        {
            var textures = chunks.SelectMany(x => new[] { x.Texture0, x.Texture1, x.Texture2, x.Texture3 }).Distinct().ToList();
            var textureCombos = 0;

            for (int i = 0; i < textures.Count; i++)
            {
                for (int j = i; j < textures.Count; j++)
                {
                    for (int k = j; k < textures.Count; k++)
                    {
                        for (int l = k; l < textures.Count; l++)
                        {
                            var similarChunks = 0;
                            var textureCombo = new[] { textures[i], textures[j], textures[k], textures[l] }.ToArray();

                            foreach (var chunk in chunks)
                            {
                                var chunkCombo = new[] { chunk.Texture0, chunk.Texture1, chunk.Texture2, chunk.Texture3 };
                                var chunkTextures = chunkCombo.Distinct();

                                var valid = true;
                                foreach (var chunkTexture in chunkTextures)
                                {
                                    if (chunkCombo.Count(x => x == chunkTexture) != textureCombo.Count(x => x == chunkTexture))
                                        valid = false;
                                }
                                if (valid)
                                    similarChunks++;
                            }

                            //System.Diagnostics.Debug.WriteLine(string.Join(", ", textureCombo) + ": " + similarChunks + " chunks.");
                            if (similarChunks > 0)
                                textureCombos++;
                        }
                    }
                }
            }
            System.Diagnostics.Debug.WriteLine(textureCombos + " texture combinations.");

            System.Diagnostics.Debug.WriteLine("Optimizing " + chunks.Count + " chunks (" + chunks.Average(x => x.Vertices.Count).ToString("0") + " avg verts.)");

            var newChunks = new List<MapChunk>();

            while (chunks.Any())
            {
                var chunk = chunks.First();

                newChunks.Add(chunk);
                chunks.Remove(chunk);

                var identicalChunks = chunks
                    .Where(x => x.Texture0 == chunk.Texture0 && x.Texture1 == chunk.Texture1 && x.Texture2 == chunk.Texture2 && x.Texture3 == chunk.Texture3)
                    .ToList();

                foreach (var otherChunk in identicalChunks)
                {
                    chunk.Vertices.AddRange(otherChunk.Vertices);
                    chunks.Remove(otherChunk);
                }

                MergeSimilarChunks(chunk,
                    chunk.Texture1, chunk.Texture0, chunk.Texture2, chunk.Texture3,
                    x => new Vector4(x.Y, x.X, x.Z, x.W));

                MergeSimilarChunks(chunk,
                    chunk.Texture2, chunk.Texture1, chunk.Texture0, chunk.Texture3,
                    x => new Vector4(x.Z, x.Y, x.X, x.W));

                MergeSimilarChunks(chunk,
                    chunk.Texture3, chunk.Texture1, chunk.Texture2, chunk.Texture0,
                    x => new Vector4(x.W, x.Y, x.Z, x.X));

                MergeSimilarChunks(chunk,
                    chunk.Texture1, chunk.Texture0, chunk.Texture3, chunk.Texture2,
                    x => new Vector4(x.Y, x.X, x.W, x.Z));

                MergeSimilarChunks(chunk,
                    chunk.Texture0, chunk.Texture1, chunk.Texture3, chunk.Texture2,
                    x => new Vector4(x.X, x.Y, x.W, x.Z));

                MergeSimilarChunks(chunk,
                    chunk.Texture0, chunk.Texture2, chunk.Texture1, chunk.Texture3,
                    x => new Vector4(x.X, x.Z, x.Y, x.W));
            }

            chunks = newChunks;

            System.Diagnostics.Debug.WriteLine(newChunks.Count + " total chunks (" + newChunks.Average(x => x.Vertices.Count).ToString("0") + " avg verts.)");
        }