static void OnSavedScene ()
	{
		var behaviours = GameObject.FindObjectsOfType(typeof(MonoBehaviour));
		var assemblers = new HashSet<PrefabAssembler>();
		foreach(MonoBehaviour b in behaviours)
		{
			if(b.GetType().GetCustomAttributes(typeof(AssembleOnSave), true).Length == 0)
			{
				continue;
			}
			Transform target = b.transform;
			while(target)
			{
				var a = target.GetComponent<PrefabAssembler>();
				if(a)
				{
					assemblers.Add(a);
				}
				target = target.parent;
			}
		}
		if(assemblers.Count != 0)
		{
			PrefabAssembler.IsSaving = true;
			PrefabAssemblerUtility.Assemble(assemblers.ToArray());
			PrefabAssembler.IsSaving = false;
		}
	}
Example #2
0
 public string GetSpecialAas()
 {
     Dictionary<char, int> count1 = new Dictionary<char, int>();
     Dictionary<char, int> count2 = new Dictionary<char, int>();
     foreach (string s in specificity){
         char c1 = s[0];
         char c2 = s[1];
         if (!count1.ContainsKey(c1)){
             count1.Add(c1, 0);
         }
         if (!count2.ContainsKey(c2)){
             count2.Add(c2, 0);
         }
         count1[c1]++;
         count2[c2]++;
     }
     HashSet<char> result = new HashSet<char>();
     foreach (char c in count1.Keys){
         if (count1[c] >= 17){
             result.Add(c);
         }
     }
     foreach (char c in count2.Keys){
         if (count2[c] >= 17){
             result.Add(c);
         }
     }
     return new string(result.ToArray());
 }
 public static void Run()
 {
     using (FastScanner fs = new FastScanner(new BufferedStream(Console.OpenStandardInput())))
     using (StreamWriter writer = new StreamWriter(new BufferedStream(Console.OpenStandardOutput())))
     {
         int n = fs.NextInt();
         HashSet<int> set = new HashSet<int>();
         for (int i = 0; i < n; i++)
         {
             int x = fs.NextInt();
             set.Add(x);
         }
         if (set.Count < 3)
         {
             writer.WriteLine("YES");
         }
         else if (set.Count > 3)
         {
             writer.WriteLine("NO");
         }
         else
         {
             int[] a = set.ToArray();
             Array.Sort(a);
             writer.WriteLine(a[1] - a[0] == a[2] - a[1] ? "YES" : "NO");
         }
     }
 }
Example #4
0
		public static uint[] GetInstructionOffsets(MethodDef method, IList<MethodSourceStatement> list) {
			if (method == null)
				return null;
			var body = method.Body;
			if (body == null)
				return null;

			var foundInstrs = new HashSet<uint>();
			// The instructions' offset field is assumed to be valid
			var instrs = body.Instructions.Select(a => a.Offset).ToArray();
			foreach (var binSpan in list.Select(a => a.Statement.BinSpan)) {
				int index = Array.BinarySearch(instrs, binSpan.Start);
				if (index < 0)
					continue;
				for (int i = index; i < instrs.Length; i++) {
					uint instrOffset = instrs[i];
					if (instrOffset >= binSpan.End)
						break;

					foundInstrs.Add(instrOffset);
				}
			}

			return foundInstrs.ToArray();
		}
        private UnitTestInfo[] GetTests(string path, string[] hintPaths)
        {
            var codeGenDllPath = Assembly.GetExecutingAssembly().Location;

            var codegenDir = Path.GetDirectoryName(codeGenDllPath);
            
            AppDomain loaderDomain = AppDomain.CreateDomain(path, AppDomain.CurrentDomain.Evidence, new AppDomainSetup() { ApplicationBase = codegenDir });
            
            var loader = (TestAssemblyLoader)loaderDomain.CreateInstanceFromAndUnwrap(codeGenDllPath, typeof(TestAssemblyLoader).FullName);

            loader.InitializeLifetimeService();

            HashSet<string> hints = new HashSet<string>(hintPaths) { Path.GetDirectoryName(path) };
            
            loader.Load(path, hints.ToArray());

            UnitTestInfo[] tests = loader.GetTests<XUnitTestDiscoverer>();

            //if no xunit tests were discovered and the assembly is an exe treat as a standalone exe test
            if ((tests == null || tests.Length == 0) && Path.GetExtension(path).ToLowerInvariant() == ".exe")
            {
                tests = loader.GetTests<StandAloneTestDiscoverer>();
            }

            AppDomain.Unload(loaderDomain);

            if (tests.Length > 0)
            {
                CodeGenOutput.Info($"{path}: {tests.Length} tests discovered");
            }

            return tests;
        }
Example #6
0
 public ScriptProjectGenerator(string[] _files, HashSet<string> assemblyReferences, ScriptSequence _sequence)
 {
     isCSharp = _sequence.Language.GetType().Name.Contains("CSharp");
     sequence = _sequence;
     files.AddRange(_files);
     references.AddRange(assemblyReferences.ToArray());
 }
Example #7
0
		QueryTableDialog(IEnumerable<string> tables)
		{
			this.tables = new HashSet<string>(tables);
			InitializeComponent();
			tablesList.AddSuggestions(tables.ToArray());
			tablesList.IsDropDownOpen = true;
		}
Example #8
0
        /// <summary>
        /// Creates a new object code file object.
        /// </summary>
        /// <param name="StartAddress">The load address of the object file.</param>
        /// <param name="Filename">The name of the object file.</param>
        /// <param name="Architecture">The targeted architecture of the object file.</param>
        /// <param name="Sections">The sections of the object file.</param>
        /// <param name="SymbolTable">The symbol table of the object file.</param>
        /// <param name="Code">The source code of the object file.</param>
        public ObjectCodeFile(long StartAddress, String Filename, String Architecture,
            Section[] Sections, SymbolTable SymbolTable, CodeUnit[] Code)
        {
            this.loadAddress  = StartAddress;
            this.Filepath     = Filename;
            this.Architecture = Architecture;
            this.Sections     = Sections;
            this.SymbolTable  = SymbolTable;
            this.Code         = Code;

            this.RequestedLoadAddress = StartAddress;

            // Sum loaded sections' sizes
            if (this.Sections != null)
            this.Size = this.Sections.Sum(
                sec => sec.Flags.HasFlag(SectionFlags.Load) ? (long)sec.Size : 0);

            // Get unique source file paths
            var tmpFiles = new HashSet<string>();

            foreach (CodeUnit unit in this.Code) {
                tmpFiles.Add(unit.SourceFilepath.Trim());
            }
            this.SourceFiles = tmpFiles.ToArray();
        }
Example #9
0
		private void InitAssemblyCache()
		{
			if (this.assemblies != null) return;

			// Retrieve a list of all loaded, non-disposed Assemblies
			Assembly[] loadedAssemblies = 
				DualityApp.PluginLoader.LoadedAssemblies
				.Where(a => !DualityApp.PluginManager.DisposedPlugins.Contains(a))
				.ToArray();

			// Aggregate selectable assemblies based on Duality core Assemblies and their dependencies
			HashSet<Assembly> selectableAssemblies = new HashSet<Assembly>();
			foreach (Assembly coreAssembly in DualityApp.GetDualityAssemblies())
			{
				selectableAssemblies.Add(coreAssembly);

				AssemblyName[] referencedAssemblies = coreAssembly.GetReferencedAssemblies();
				foreach (AssemblyName reference in referencedAssemblies)
				{
					string shortName = reference.GetShortAssemblyName();
					Assembly dependency = loadedAssemblies.FirstOrDefault(a => a.GetShortAssemblyName() == shortName);
					if (dependency != null)
						selectableAssemblies.Add(dependency);
				}
			}

			this.assemblies = selectableAssemblies.ToArray();
			this.namespaces = this.assemblies
				.SelectMany(a => { try { return a.GetExportedTypes(); } catch (Exception) { return new Type[0]; } })
				.Select(t => t.Namespace)
				.Distinct()
				.Where(n => !string.IsNullOrEmpty(n))
				.ToArray();
		}
Example #10
0
 private static BuildingInfo[] GetUniquePillars()
 {
     var pillarsTemp = new HashSet<BuildingInfo>();
     foreach (var buildingInfo in Util.GetAllPrefabs().SelectMany(prefab => prefab.GetPillars()))
     {
         pillarsTemp.Add(buildingInfo);
     }
     for (uint i = 0; i < PrefabCollection<BuildingInfo>.LoadedCount(); i++)
     {
         var prefab = PrefabCollection<BuildingInfo>.GetLoaded(i);
         if (prefab == null || prefab.m_buildingAI.GetType() != typeof(BuildingAI))
         {
             continue;
         }
         var asset = PackageManager.FindAssetByName(prefab.name);
         var crpPath = asset?.package?.packagePath;
         var directoryName = Path.GetDirectoryName(crpPath);
         if (directoryName == null)
         {
             continue;
         }
         var pillarConfigPath = Path.Combine(directoryName, "Pillar.xml");
         if (!File.Exists(pillarConfigPath))
         {
             continue;
         }
         pillarsTemp.Add(prefab);
     }
     return pillarsTemp.ToArray();
 }
        static void drawCodeGenerators(CodeGeneratorConfig codeGeneratorConfig, Type[] codeGenerators)
        {
            EditorGUILayout.Space();
            EditorGUILayout.LabelField("Code Generators", EditorStyles.boldLabel);

            var enabledCodeGenerators = new HashSet<string>(codeGeneratorConfig.enabledCodeGenerators);

            var availableGeneratorNames = new HashSet<string>();
            foreach (var codeGenerator in codeGenerators) {
                availableGeneratorNames.Add(codeGenerator.Name);
                var isEnabled = enabledCodeGenerators.Contains(codeGenerator.Name);
                isEnabled = EditorGUILayout.Toggle(codeGenerator.Name, isEnabled);
                if (isEnabled) {
                    enabledCodeGenerators.Add(codeGenerator.Name);
                } else {
                    enabledCodeGenerators.Remove(codeGenerator.Name);
                }
            }

            foreach (var generatorName in codeGeneratorConfig.enabledCodeGenerators.ToArray()) {
                if (!availableGeneratorNames.Contains(generatorName)) {
                    enabledCodeGenerators.Remove(generatorName);
                }
            }

            var sortedCodeGenerators = enabledCodeGenerators.ToArray();
            Array.Sort(sortedCodeGenerators);
            codeGeneratorConfig.enabledCodeGenerators = sortedCodeGenerators;
        }
        static string[] ExtractParameters(string script)
        {
            var ps = ParameterExtractor.Matches(script);
            if (ps.Count == 0) return null;

            var ret = new HashSet<string>();

            for (var i = 0; i < ps.Count; i++)
            {
                var c = ps[i];
                var ix = c.Index - 1;
                if (ix >= 0)
                {
                    var prevChar = script[ix];
                    
                    // don't consider this a parameter if it's in the middle of word (ie. if it's preceeded by a letter)
                    if (char.IsLetterOrDigit(prevChar) || prevChar == '_') continue;
                    
                    // this is an escape, ignore it
                    if (prevChar == '@') continue;
                }

                var n = c.Groups["paramName"].Value;
                if (!ret.Contains(n)) ret.Add(n);
            }

            return ret.ToArray();
        }
Example #13
0
 public static int[] many(int x)
 {
     ICollection<int> set = new HashSet<int>();
     while (set.Count < x)
         set.Add(RANDOM.Next(1, 50));
     return set.ToArray();
 }
Example #14
0
        public void run(int seconds)
        {
            var tsks = new HashSet<Task>();
            durationSeconds = seconds;
            var metrics = Metric.Context("shared");
            foreach (var t in tasks)
            {
                t.Duration = durationSeconds;

                if (sharedMetrics > 0)
                {
                    t.metrics = metrics;
                }
                else
                {
                    t.metrics = Metric.Context(t.ToString());
                }
                var task = new Task(() => t.Call(),TaskCreationOptions.LongRunning);
                task.Start();
                tsks.Add(task);
            }
            try
            {

                Task.WaitAll(tsks.ToArray());
            }
            catch (Exception)
            {
            }
            Console.WriteLine("TASKS COMPLETE ");
        }
 public override void Run(List<Point> points, List<Line> lines, List<Polygon> polygons, ref List<Point> outPoints, ref List<Line> outLines, ref List<Polygon> outPolygons)
 {
     HashSet<PointComparer> hashP = new HashSet<PointComparer>();
     for (int i = 0; i < points.Count; ++i)
         hashP.Add(new PointComparer(points[i]));
     PointComparer[] res = hashP.ToArray();
     points.Clear();
     for (int i = 0; i < res.Length; ++i)
         points.Add(res[i].p);
     List<bool> visited = new List<bool>();
     for (int i = 0; i < points.Count; ++i)
         visited.Add(false);
     for (int i = 0; i < points.Count; ++i)
     {
         for (int j = 0; j < points.Count; ++j)
             if (!visited[j])
                 for (int k = 0; k < points.Count; ++k)
                     if (!visited[k])
                         for (int l = 0; l < points.Count; ++l)
                             if (!visited[l] && (valid(i, j, k, l)))
                             {
                                 Enums.PointInPolygon state = HelperMethods.PointInTriangle(points[i], points[j], points[k], points[l]);
                                 if (state == Enums.PointInPolygon.Inside || state == Enums.PointInPolygon.OnEdge)
                                     visited[i] = true;
                             }
     }
     outPoints = new List<Point>();
     for (int i = 0; i < points.Count; ++i)
         if (!visited[i])
             outPoints.Add(points[i]);
     return;
 }
Example #16
0
        public override void IndexDocuments(
			AbstractViewGenerator viewGenerator, 
			IEnumerable<dynamic> documents, 
			WorkContext context, 
			IStorageActionsAccessor actions, 
			DateTime minimumTimestamp)
        {
            actions.Indexing.SetCurrentIndexStatsTo(name);
            var count = 0;
            Func<object, object> documentIdFetcher = null;
            var reduceKeys = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
            var documentsWrapped = documents.Select(doc =>
            {
                var documentId = doc.__document_id;
                foreach (var reduceKey in actions.MappedResults.DeleteMappedResultsForDocumentId((string)documentId, name))
                {
                    reduceKeys.Add(reduceKey);
                }
                return doc;
            });
            foreach (var doc in RobustEnumeration(documentsWrapped, viewGenerator.MapDefinition, actions, context))
            {
                count++;

                documentIdFetcher = CreateDocumentIdFetcherIfNeeded(documentIdFetcher, doc);

                var docIdValue = documentIdFetcher(doc);
                if (docIdValue == null)
                    throw new InvalidOperationException("Could not find document id for this document");

                var reduceValue = viewGenerator.GroupByExtraction(doc);
                if (reduceValue == null)
                {
                    logIndexing.DebugFormat("Field {0} is used as the reduce key and cannot be null, skipping document {1}", viewGenerator.GroupByExtraction, docIdValue);
                    continue;
                }
                var reduceKey = ReduceKeyToString(reduceValue);
                var docId = docIdValue.ToString();

                reduceKeys.Add(reduceKey);

                var data = GetMapedData(doc);

                logIndexing.DebugFormat("Mapped result for '{0}': '{1}'", name, data);

                var hash = ComputeHash(name, reduceKey);

                actions.MappedResults.PutMappedResult(name, docId, reduceKey, data, hash);

                actions.Indexing.IncrementSuccessIndexing();
            }

            actions.Tasks.AddTask(new ReduceTask
            {
                Index = name,
                ReduceKeys = reduceKeys.ToArray()
            }, minimumTimestamp);

            logIndexing.DebugFormat("Mapped {0} documents for {1}", count, name);
        }
Example #17
0
        public static string[] Build(string solutionFile)
        {
            Console.Error.Write("// Building '{0}'... ", Path.GetFileName(solutionFile));

            var pc = new ProjectCollection();
            var parms = new BuildParameters(pc);
            var globalProperties = new Dictionary<string, string>();
            var request = new BuildRequestData(solutionFile, globalProperties, null, new string[] { "Build" }, null);

            parms.Loggers = new[] {
                new ConsoleLogger(LoggerVerbosity.Quiet)
            };

            var result = BuildManager.DefaultBuildManager.Build(parms, request);
            var resultFiles = new HashSet<string>();

            Console.Error.WriteLine("done.");

            foreach (var kvp in result.ResultsByTarget) {
                var targetResult = kvp.Value;

                if (targetResult.Exception != null)
                    Console.Error.WriteLine("// Compilation failed for target '{0}':\r\n{1}", kvp.Key, targetResult.Exception.Message);
                else {
                    foreach (var filename in targetResult.Items)
                        resultFiles.Add(filename.ItemSpec);
                }
            }

            return resultFiles.ToArray();
        }
        public void fun1()
        {
            Dictionary<int, char> dt1 = new Dictionary<int, char>();
            dt1.Add(9, 'a');
            dt1.Add(5, 'a');
            dt1.Add(4, 'a');

            foreach (KeyValuePair<int, char> kvp in dt1)
            {
                //Console.WriteLine("key ={0} value = {1}", kvp.Key, kvp.Value);
            }
            int[] arr = { 3, 1, 8 };
            HashSet<int> hs = new HashSet<int>(arr);

            hs.Add(3);
            hs.Add(9);
            hs.Add(5);
            hs.Add(1);
            //hs.Add(1);
            //hs.Add(3);

            //hs.ExceptWith(arr);
            int[] arr1 = hs.ToArray();
               // hs.IntersectWith(arr);
            hs.UnionWith(arr);

            //Console.WriteLine(hs.Max());
               // Console.WriteLine(hs.Average());
            foreach (int kvp in hs)
            {
                Console.WriteLine(kvp);
            }
        }
	static PrefabAssembler[] GetSelectedAssemblers ()
	{
		HashSet<PrefabAssembler> assemblers = new HashSet<PrefabAssembler>();
		foreach(var go in Selection.gameObjects)
		{
			if(EditorUtility.IsPersistent(go))
			{
				continue;
			}
			
			// Seek assemblers in children
			foreach(var a in go.GetComponentsInChildren<PrefabAssembler>())
			{
				assemblers.Add(a);
			}
			
			// Seek assemblers in parents
			Transform t = go.transform.parent;
			while(t)
			{
				var a = t.GetComponent<PrefabAssembler>();
				if(a)
				{
					assemblers.Add(a);
				}
				t = t.parent;
			}
		}
		return assemblers.ToArray();
	}
        /// <summary>
        /// Starts the clustering.
        /// </summary>
        /// <param name="elements"></param>
        /// <param name="fusion"></param>
        /// <param name="metric"></param>
        /// <returns></returns>
        protected internal Cluster[] Cluster(List<Element> elements, Fusion fusion, IDistanceMetric metric)
        {
            HashSet<Cluster> clusters = new HashSet<Cluster>();
            ClusterPairs pairs = new ClusterPairs();

            // 1. Initialize each element as a cluster
            foreach (Element el in elements)
            {
                Cluster cl = new Cluster(fusion);
                cl.AddElement(el);
                clusters.Add(cl);
            }

            // 2. a) Calculate the distances of all clusters to all other clusters
            foreach (Cluster cl1 in clusters)
            {
                foreach (Cluster cl2 in clusters)
                {
                    if (cl1 == cl2)
                        continue;

                    ClusterPair pair = new ClusterPair(cl1, cl2, cl1.CalculateDistance(cl2));

                    pairs.AddPair(pair);
                }
            }

            // 2. b) Initialize the pair with the lowest distance to each other.
            ClusterPair lowestDistancePair = pairs.LowestDistancePair;

            // 3. Merge clusters to new clusters and recalculate distances in a loop until there are only countCluster clusters
            while (!isFinished(clusters, lowestDistancePair))
            {
                // a) Merge: Create a new cluster and add the elements of the two old clusters
                lowestDistancePair = pairs.LowestDistancePair;

                Cluster newCluster = new Cluster(fusion);
                newCluster.AddElements(lowestDistancePair.Cluster1.GetElements());
                newCluster.AddElements(lowestDistancePair.Cluster2.GetElements());

                // b)Remove the two old clusters from clusters
                clusters.Remove(lowestDistancePair.Cluster1);
                clusters.Remove(lowestDistancePair.Cluster2);

                // c) Remove the two old clusters from pairs
                pairs.RemovePairsByOldClusters(lowestDistancePair.Cluster1, lowestDistancePair.Cluster2);

                // d) Calculate the distance of the new cluster to all other clusters and save each as pair
                foreach (Cluster cluster in clusters)
                {
                    ClusterPair pair = new ClusterPair(cluster, newCluster, cluster.CalculateDistance(newCluster));
                    pairs.AddPair(pair);
                }

                // e) Add the new cluster to clusters
                clusters.Add(newCluster);
            }

            return clusters.ToArray<Cluster>();
        }
        public void Run() 
        {
            //if (!File.Exists("WordLookup.txt"))    // Contains about 150,000 words
            //    new WebClient().DownloadFile(
            //      "http://www.albahari.com/ispell/allwords.txt", "WordLookup.txt");

            var wordLookup = new HashSet<string>(
              File.ReadAllLines("WordLookup.txt"),
              StringComparer.InvariantCultureIgnoreCase);

            // Random is not thread-safe,所以無法簡單的使用AsParallel,
            // 解決方法,使用locks 的方式包住random.Next
            // 參考網址:http://csharpindepth.com/Articles/Chapter12/Random.aspx
            var random = new Random();
            string[] wordList = wordLookup.ToArray();

            // Fortunately, the new ThreadLocal<T> class in .NET 4 makes it very easy to write providers which need to have a single instance per thread
            // 使用ThreadLocal,建立分開的Random object 給每一個Thread

            //new Random(參數), 是為了確保如果兩個Random objects 被建立在很短的時間,會回傳不同的亂數序列
            var allocationRandom = new ThreadLocal<Random>(() => new Random(Guid.NewGuid().GetHashCode()));
            
            // 隨機取100W的值塞給wordsToTest
            string[] wordsToTest = Enumerable.Range(0, 1000000)
                .AsParallel()
              .Select(i => wordList[allocationRandom.Value.Next(0, wordList.Length)])
              .ToArray();            
                    
            var startTime = DateTime.Now.Ticks;

            var endTime = DateTime.Now.Ticks;
            Console.WriteLine("Time : " + (endTime - startTime).ToString());

        }
        private void DistributeComunicatToAll(Comunicat item)
        {
            var connectedUsers = listaPolaczec.Keys;
            String[] oldBlackList = item.NotToUser;
            // dodajemu użytkowników do czarnej listy
            HashSet<string> newBlackList = new HashSet<string>(item.NotToUser);
            foreach(var user in listaPolaczec.Keys)
            {
                if(!newBlackList.Contains(user))
                {
                    newBlackList.Add(user);
                }
            }

            item.NotToUser = newBlackList.ToArray<String>();
            // wysyłamy wiadomości do urzytkowników
            foreach(var user in listaPolaczec)
            {
                if(!oldBlackList.Contains(user.Key) && user.Key != UNKNOWN_USER)
                {
                    foreach(var modul in user.Value)
                    {
                        modul.addComunicatToSend(item);
                    }
                }
            }
        }
Example #23
0
 string[] GetEnabledSceneNames()
 {
     var scenes = (sceneNameAttribute.enableOnly ? EditorBuildSettings.scenes.Where(scene => scene.enabled) : EditorBuildSettings.scenes).ToList();
     var sceneNames = new HashSet<string>();
     scenes.ForEach(scene => sceneNames.Add(scene.path.Substring(scene.path.LastIndexOf("/") + 1).Replace(".unity", string.Empty)));
     return sceneNames.ToArray();
 }
		public Response.IResponse Execute( CommandArgs args )
		{
			var pa = args.As<parentsArgs>();

			if( string.IsNullOrWhiteSpace( pa.target ) )
				return new Response.ErrorResponse( "target not specified" );

			// get volume for our target
			var vol = _volumeManager.GetByHash( pa.target );
			// try to get directory for our target
			var cwd = ( vol != null ? vol.GetDirectoryByHash( pa.target ) : null );
			// if we still haven't got volume service, then something is wrong
			if( cwd == null || cwd.IsReadable.IsFalse() )
				return new Response.ErrorResponse( "target dir not found or access denied" );

			HashSet<Model.DirectoryModel> tree = new HashSet<Model.DirectoryModel>();
			tree.Add( cwd );
			var rootDir = vol.GetRootDirectory();
			// now get parent untill we reach root
			while( cwd != null && cwd.Hash != rootDir.Hash )
			{
				if( cwd.ParentHash == null )
					break;
				var parentDir = vol.GetDirectoryByHash( cwd.ParentHash );
				if( parentDir == null )
					return new Response.ErrorResponse( "error getting parent dir: not found or access denied" );
				tree.Add( parentDir );
				var subDirs = vol.GetSubdirectoriesFlat( parentDir, 0 );
				foreach( var sd in subDirs )
					tree.Add( sd );
				cwd = parentDir;
			}
			return new Response.TreeResponse( tree.ToArray() );
		}
        private static IEnumerable<Assembly> GetNancyReferencingAssemblies()
        {
#if DNX
            var libraryManager = Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default.LibraryManager;

            var results = new HashSet<Assembly>
            {
                typeof (INancyEngine).Assembly
            };

            var referencingLibraries = libraryManager.GetReferencingLibraries(NancyAssemblyName.Name);

            foreach (var assemblyName in referencingLibraries.SelectMany(referencingLibrary => referencingLibrary.Assemblies))
            {
                try
                {
                    results.Add(Assembly.Load(assemblyName));
                }
                catch
                {
                }
            }

            return results.ToArray();
#else
            return AppDomain.CurrentDomain.GetAssemblies().Where(IsNancyReferencing);
#endif
        }
        public void Install(RunningDeployment deployment)
        {
            var transformDefinitions = GetTransformDefinitions(deployment.Variables.Get(SpecialVariables.Package.AdditionalXmlConfigurationTransforms));

            var sourceExtensions = new HashSet<string>(
                  transformDefinitions
                    .Where(transform => transform.Advanced)
                    .Select(transform => "*" + Path.GetExtension(transform.SourcePattern))
                    .Distinct()
                );

            if (deployment.Variables.GetFlag(SpecialVariables.Package.AutomaticallyRunConfigurationTransformationFiles))
            {
                sourceExtensions.Add("*.config");
                transformDefinitions.Add(new XmlConfigTransformDefinition("Release"));

                var environment = deployment.Variables.Get(SpecialVariables.Environment.Name);
                if (!string.IsNullOrWhiteSpace(environment))
                {
                    transformDefinitions.Add(new XmlConfigTransformDefinition(environment));
                }
            }

            var transformsRun = new HashSet<string>();
            foreach (var configFile in fileSystem.EnumerateFilesRecursively(deployment.CurrentDirectory,
                sourceExtensions.ToArray()))
            {
                ApplyTransformations(configFile, transformDefinitions, transformsRun);

            }

            deployment.Variables.SetStrings(SpecialVariables.AppliedXmlConfigTransforms, transformsRun, "|");
        }
        /// <summary>
        /// Returns the CSS classes (if any) associated with the theme(s) of the content, as decided by its categories
        /// </summary>
        /// <param name="content"></param>
        /// <returns>CSS classes associated with the content's theme(s), or an empty string array if no theme is applicable</returns>
        /// <remarks>Content's categorization may map to more than one theme. This method assumes there are website categories called "Meet", "Track", and "Plan"</remarks>
        public static string[] GetThemeCssClassNames(this ICategorizable content)
        {
            if (content.Category == null)
            {
                return new string[0];
            }

            var cssClasses = new HashSet<string>(); // Although with some overhead, a HashSet allows us to ensure we never add a CSS class more than once

            foreach (var categoryName in content.Category.Select(category => content.Category.GetCategoryName(category).ToLower()))
            {
                switch (categoryName)
                {
                    case "meet":
                        cssClasses.Add("theme1");
                        break;
                    case "track":
                        cssClasses.Add("theme2");
                        break;
                    case "plan":
                        cssClasses.Add("theme3");
                        break;
                }
            }

            return cssClasses.ToArray();
        }
Example #28
0
        public IBrush MakeBrush(Player player, CommandReader cmd) {
            if (player == null) throw new ArgumentNullException("player");
            if (cmd == null) throw new ArgumentNullException("cmd");

            // read the block filter list
            HashSet<Block> blocks = new HashSet<Block>();
            while (cmd.HasNext) {
                Block block;
                if (!cmd.NextBlock(player, false, out block)) {
                    return null;
                }
                if (!blocks.Add(block)) {
                    // just a warning -- don't abort
                    player.Message("{0}: {1} was specified twice!", Name, block);
                }
            }

            // create a brush
            if (blocks.Count > 0) {
                return new PasteBrush(blocks.ToArray(), Not);
            } else if (Not) {
                player.Message("PasteNot brush requires at least 1 block.");
                return null;
            } else {
                return new PasteBrush();
            }
        }
Example #29
0
        static void Main()
        {
            //var numberOfShirtsK = int.Parse(Console.ReadLine());
            var numberOfShirtsK = 3;

            usedShirt = new int[numberOfShirtsK];

            //var skirts = Console.ReadLine();
            var skirtsL = "baca";
            var numberOfSkirtsL = skirtsL.Length;

            usedSkirt = new int[numberOfSkirtsL];

            //var numberOfGirls = int.Parse(Console.ReadLine());
            var numberOfGirls = 2;

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

            for (int i = 0; i < numberOfShirtsK; i++)
            {
                for (int j = 0; j < numberOfSkirtsL; j++)
                {
                    possibleCombos.Add(i.ToString() + j.ToString());
                }
            }

            GenerateCombinations(0, 0, numberOfGirls, possibleCombos.ToArray(), new string[numberOfGirls]);
        }
Example #30
-1
        public void Run()
        {
            var wordLookupFile = Path.Combine(Path.GetTempPath(), "WordLookup.txt");

            if (!File.Exists(wordLookupFile))
            {
                new WebClient().DownloadFile("http://www.albahari.com/ispell/allwords.txt", wordLookupFile);
            }

            var wordLookup = new HashSet<string>(File.ReadAllLines(wordLookupFile), StringComparer.InvariantCultureIgnoreCase);
            var wordList = wordLookup.ToArray();

            // Here, we're using ThreadLocal to generate a thread-safe random number generator,
            // so we can parallelize the building of the wordsToTest array.
            var localRandom = new ThreadLocal<Random>(() => new Random(Guid.NewGuid().GetHashCode()));
            var wordsToTest = Enumerable.Range(0, 1000000)
                .AsParallel()
                .Select(i => wordList[localRandom.Value.Next(0, wordList.Length)])
                .ToArray();

            wordsToTest[12345] = "woozsh";     // Introduce a couple
            wordsToTest[23456] = "wubsie";     // of spelling mistakes.

            var query = wordsToTest
                .AsParallel()
                //.Select((word, index) => new IndexedWord { Word = word, Index = index })
                .Select((word, index) => new { Word = word, Index = index })
                .Where(iword => !wordLookup.Contains(iword.Word))
                .OrderBy(iword => iword.Index);

            var result = query.ToList();
        }