public void FilterData(ZusaarJson zusaarResult, ObservableCollection<AllEventsInfo> allEventsInfo, HashSet<string> ngWordsList, HashSet<string> cities)
 {
     if (zusaarResult != null)
     {
         var zusaaarInfo = from evnt in zusaarResult._event
                           where evnt.started_at <= DateTime.Now.AddMonths(5)
                           where evnt.started_at > DateTime.Now
                           join city in cities on SpecifyCity.GetCity(evnt.address) equals city
                           where ngWordsList.All(word => !evnt.title.Contains(word))
                           select new AllEventsInfo
                           {
                               Site = "site_zusaar.png",
                               Title = evnt.title,
                               Event_uri = evnt.event_url,
                               Start_at = evnt.started_at,
                               End_at = evnt.ended_at,
                               Description = evnt.description,
                               Overview = HtmlToString.GetString(evnt.description, 50),
                               Address = evnt.address,
                               City = SpecifyCity.GetCity(evnt.address),
                               Accepted = evnt.accepted,
                               Limit = evnt.limit,
                               Organizer = evnt.owner_nickname,
                           };
         foreach (var item in zusaaarInfo)
         {
             allEventsInfo.Add(item);
         }
     }
 }
Example #2
0
        //Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        //{
        //    throw new NotImplementedException();
        //}

        private static string ImportsFor(HashSet<string> namespaces)
        {
            StringBuilder builder = new StringBuilder();
            namespaces.All(s => { builder.AppendFormat("using {0};{1}", s, Environment.NewLine); return true; });
            
            return builder.ToString();
        }
 public void FilterData(List<DoorkeeperJson> doorkeeperResult, ObservableCollection<AllEventsInfo> allEventsInfo, HashSet<string> ngWordsList, HashSet<string> cities)
 {
     if (doorkeeperResult != null)
     {
         var doorkeeperInfo = from evnt in doorkeeperResult
                              join city in cities on SpecifyCity.GetCity(evnt._event.address) equals city
                              where evnt._event.starts_at <= DateTime.Now.AddMonths(5)
                              where evnt._event.starts_at > DateTime.Now
                              where ngWordsList.All(word => !evnt._event.title.Contains(word))
                              select new AllEventsInfo
                              {
                                  Site = "site_doorkeeper.png",
                                  Title = evnt._event.title,
                                  Event_uri = evnt._event.public_url,
                                  Start_at = evnt._event.starts_at,
                                  End_at = evnt._event.ends_at,
                                  Description = evnt._event.description,
                                  Overview = HtmlToString.GetString(evnt._event.description, 50),
                                  Address = evnt._event.address,
                                  City = SpecifyCity.GetCity(evnt._event.address),
                                  Accepted = evnt._event.participants,
                                  Limit = evnt._event.ticket_limit,
                                  Organizer = [email protected],
                              };
         foreach (var item in doorkeeperInfo)
         {
             allEventsInfo.Add(item);
         }
     }
 }
        public void HashSetExtensions_All_ReturnsTrueIfHashSetIsEmpty()
        {
            var set = new HashSet<Int32>();

            var result = set.All(x => x % 2 == 0);

            TheResultingValue(result).ShouldBe(true);
        }
        public void HashSetExtensions_All_ReturnsTrueIfAllItemsMatchPredicate()
        {
            var set = new HashSet<Int32>() { 2, 4, 6 };

            var result = set.All(x => x % 2 == 0);

            TheResultingValue(result).ShouldBe(true);
        }
        public void HashSetExtensions_All_ReturnsFalseIfOneItemDoesNotMatchPredicate()
        {
            var set = new HashSet<Int32>() { 1, 2, 4, 6 };

            var result = set.All(x => x % 2 == 0);

            TheResultingValue(result).ShouldBe(false);
        }
        public bool IsInGeneratedCodeDocument([NotNull] ISymbol symbol, CancellationToken cancellationToken)
        {
            Guard.NotNull(symbol, nameof(symbol));

            // Return false when not all locations have generated comment; for example, partial classes.

            IEnumerable<Location> locations = symbol.Locations.Where(location => location.IsInSource);
            var trees = new HashSet<SyntaxTree>(locations.Select(location => location.SourceTree));

            return trees.Any() && trees.All(tree => IsGeneratedCodeDocument(tree, cancellationToken));
        }
Example #8
0
        public void TrimExcess()
        {
            var set = new HashSet<int>();
              foreach (int item in Enumerable.Range(100, 1000))
            set.Add(item);

              Assert.AreEqual(1000, set.Count);

              set.TrimExcess();

              Assert.AreEqual(1000, set.Count);
              foreach (int item in Enumerable.Range(100, 1000))
            Assert.IsTrue(set.Contains(item));

              foreach (int item in Enumerable.Range(100, 1000).Where(i => i % 2 == 0))
            set.Remove(item);

              set.TrimExcess();
              Assert.AreEqual(500, set.Count);
              Assert.IsTrue(set.All(i => i % 2 == 1));
        }
Example #9
0
        public void RemoteRouter_must_deploy_remote_routers_based_on_explicit_deployment()
        {
            var probe = CreateTestProbe(masterActorSystem);
            var router = masterActorSystem.ActorOf(new RoundRobinPool(2).Props(Props.Create<Echo>())
                .WithDeploy(
                new Deploy(new RemoteScope(intendedRemoteAddress))), "remote-blub2");

            router.Path.Address.ShouldBe(intendedRemoteAddress);

            var replies = new HashSet<ActorPath>();
            for (var i = 0; i < 5; i++)
            {
                router.Tell("", probe.Ref);
                var expected = probe.ExpectMsg<IActorRef>(GetTimeoutOrDefault(null));
                replies.Add(expected.Path);
            }

            Assert.Equal(2, replies.Count);
            var parents = replies.Select(x => x.Parent).Distinct().ToList();
            parents.Head().ShouldBe(router.Path);

            Assert.True(replies.All(x => x.Address.Equals(intendedRemoteAddress)));
            masterActorSystem.Stop(router);
        }
Example #10
0
        public void RemoteRouter_must_deploy_its_children_on_remote_host_driven_by_programmatic_definition()
        {
            var probe = CreateTestProbe(masterActorSystem);
            var router = masterActorSystem.ActorOf(new RemoteRouterConfig(new RoundRobinPool(2), new[] { new Address("akka.tcp", sysName, "localhost", port) })
                .Props(Props.Create<Echo>()), "blub2");
            var replies = new HashSet<ActorPath>();
            for (var i = 0; i < 5; i++)
            {
                router.Tell("", probe.Ref);
                var expected = probe.ExpectMsg<IActorRef>(GetTimeoutOrDefault(null));
                replies.Add(expected.Path);
            }

            Assert.Equal(2, replies.Count);
            Assert.Equal(1, replies.Select(x => x.Parent).Distinct().Count());
            Assert.True(replies.All(x => x.Address.Equals(intendedRemoteAddress)));
            masterActorSystem.Stop(router);
        }
Example #11
0
        private List<IPackage> GetRootPackagesInDependencyOrder()
        {
            var packagesInOrder = new List<IPackage>();

            // Get all packages
            var packages = new HashSet<IPackage>();
            foreach (var package in LocalRepository.GetPackages().OrderBy(p => p.Id).ThenByDescending(p => p.Version))
            {
                if (packages.All(p => p.Id != package.Id))
                {
                    packages.Add(package);
                }
            }

            while (packages.Count > 0)
            {
                var nextPackage = packages.FirstOrDefault();
                AddPackageRecursive(packagesInOrder, packages, nextPackage);
            }

            return packagesInOrder;
        }
Example #12
0
        /// <summary>
        /// Returns a sequence of ModulePaths for all modules importable from
        /// the specified library.
        /// </summary>
        public static IEnumerable<ModulePath> GetModulesInLib(
            string interpreterPath,
            string libraryPath,
            string sitePath = null,
            bool requireInitPyFiles = true
        ) {
            if (File.Exists(interpreterPath)) {
                interpreterPath = Path.GetDirectoryName(interpreterPath);
            }
            if (!Directory.Exists(libraryPath)) {
                return Enumerable.Empty<ModulePath>();
            }
            if (string.IsNullOrEmpty(sitePath)) {
                sitePath = Path.Combine(libraryPath, "site-packages");
            }
            var pthDirs = ExpandPathFiles(sitePath);
            var excludedPthDirs = new HashSet<string>() {
                sitePath,
                libraryPath
            };

            // Get modules in stdlib
            var modulesInStdLib = GetModulesInPath(libraryPath, true, true, requireInitPy: requireInitPyFiles);

            // Get files in site-packages
            var modulesInSitePackages = GetModulesInPath(sitePath, true, false, requireInitPy: requireInitPyFiles);

            // Get directories in site-packages
            // This is separate from getting files to ensure that each package
            // gets its own library path.
            var packagesInSitePackages = GetModulesInPath(sitePath, false, true, requireInitPy: requireInitPyFiles);

            // Get modules in DLLs directory
            IEnumerable<ModulePath> modulesInDllsPath;

            // Get modules in interpreter directory
            IEnumerable<ModulePath> modulesInExePath;

            if (Directory.Exists(interpreterPath)) {
                modulesInDllsPath = GetModulesInPath(Path.Combine(interpreterPath, "DLLs"), true, false);
                modulesInExePath = GetModulesInPath(interpreterPath, true, false);
                excludedPthDirs.Add(interpreterPath);
                excludedPthDirs.Add(Path.Combine(interpreterPath, "DLLs"));
            } else {
                modulesInDllsPath = Enumerable.Empty<ModulePath>();
                modulesInExePath = Enumerable.Empty<ModulePath>();
            }

            // Get directories referenced by pth files
            var modulesInPath = GetModulesInPath(
                pthDirs.Where(p1 => excludedPthDirs.All(p2 => !PathUtils.IsSameDirectory(p1, p2))),
                true,
                true,
                requireInitPy: requireInitPyFiles
            );

            return modulesInPath
                .Concat(modulesInDllsPath)
                .Concat(modulesInStdLib)
                .Concat(modulesInExePath)
                .Concat(modulesInSitePackages)
                .Concat(packagesInSitePackages);
        }
Example #13
0
        public void RemoteRouter_must_deploy_its_children_on_remote_host_driven_by_configuration()
        {
            var probe = CreateTestProbe(masterActorSystem);
            var router = masterActorSystem.ActorOf(new RoundRobinPool(2).Props(Props.Create<Echo>()), "blub");
            var replies = new HashSet<ActorPath>();
            for (var i = 0; i < 5; i++)
            {
                router.Tell("", probe.Ref);
                var expected = probe.ExpectMsg<ActorRef>();
                replies.Add(expected.Path);
            }

            Assert.Equal(2, replies.Count);
            Assert.Equal(1, replies.Select(x => x.Parent).Distinct().Count());
            Assert.True(replies.All(x => x.Address.Equals(intendedRemoteAddress)));
            masterActorSystem.Stop(router);
        }
Example #14
0
        public void RemoteRouter_must_let_remote_deployment_router_be_overriden_by_local_configuration()
        {
            var probe = CreateTestProbe(masterActorSystem);
            var router = masterActorSystem.ActorOf(new RoundRobinPool(2).Props(Props.Create<Echo>())
                .WithDeploy(
                new Deploy(new RemoteScope(intendedRemoteAddress.Copy()))), "local-blub2");

            // This line was subject to a bug in the original Akka - this router should be locally-deployed.
            router.Path.Address.ToString().ShouldBe(string.Format("akka://{0}", masterActorSystem.Name));

            var replies = new HashSet<ActorPath>();
            for (var i = 0; i < 5; i++)
            {
                router.Tell("", probe.Ref);
                var expected = probe.ExpectMsg<ActorRef>();
                replies.Add(expected.Path);
            }

            Assert.Equal(4, replies.Count);
            var parents = replies.Select(x => x.Parent).Distinct().ToList();
            parents.Head().Address.ShouldBe(new Address("akka.tcp", sysName, "localhost", port));

            Assert.True(replies.All(x => x.Address.Equals(intendedRemoteAddress)));
            masterActorSystem.Stop(router);
        }
Example #15
0
        public void RemoteRouter_must_deploy_remote_routers_based_on_configuration()
        {
            var probe = CreateTestProbe(masterActorSystem);
            var router = masterActorSystem.ActorOf(Props.Create<Echo>().WithRouter(FromConfig.Instance), "remote-blub");
            router.Path.Address.ShouldBe(intendedRemoteAddress);

            var replies = new HashSet<ActorPath>();
            for (var i = 0; i < 5; i++)
            {
                router.Tell("", probe.Ref);
                var expected = probe.ExpectMsg<ActorRef>();
                replies.Add(expected.Path);
            }

            Assert.Equal(2, replies.Count);
            var parents = replies.Select(x => x.Parent).Distinct().ToList();
            parents.Head().ShouldBe(router.Path);

            Assert.True(replies.All(x => x.Address.Equals(intendedRemoteAddress)));
            masterActorSystem.Stop(router);
        }
        // Looks up a member of given name and arity in a particular type.
        private LookupResult MemberLookup(TypeSymbol type, string name, int arity, bool invoked)
        {
            LookupResult result;

            switch (type.TypeKind) {
                case TypeKind.RefType:
                    return MemberLookup(((RefTypeSymbol)type).ReferencedType, name, arity, invoked);

                case TypeKind.TypeParameter:
                    result = MemberLookupInTypeParameter(type, name, arity, invoked); break;

                case TypeKind.Interface:
                    result = MemberLookupInInterface(type, name, arity, invoked); break;

                case TypeKind.Class:
                case TypeKind.Struct:
                case TypeKind.Enum:
                case TypeKind.Delegate:
                case TypeKind.ArrayType:
                    result = MemberLookupInClass(type, name, arity, invoked); break;

                case TypeKind.Error:
                case TypeKind.PointerType:
                    return LookupResult.Empty;

                case TypeKind.Unknown:
                default:
                    Debug.Fail("Unknown type kind");
                    return LookupResult.Empty;
            }

            // TODO: Diagnose ambiguity problems here, and conflicts between non-method and method? Or is that
            // done in the caller?
            return result;


#if SLOW
            // A member lookup is the process whereby the meaning of a name in the context of
            // a type is determined. A member lookup can occur as part of evaluating a 
            // simple-name or a member-access in an expression. If the 
            // simple-name or member-access occurs as the simple-expression of an 
            // invocation-expression, the member is said to be invoked.

            // If a member is a method or event, or if it is a constant, field or property 
            // of a delegate type, then the member is said to be invocable.

            // Member lookup considers not only the name of a member but also the number of
            // type parameters the member has and whether the member is accessible. For the 
            // purposes of member lookup, generic methods and nested generic types have the 
            // number of type parameters indicated in their respective declarations and all 
            // other members have zero type parameters.

            // A member lookup of a name N with K type parameters in a type T is processed as follows:

            // First, a set of accessible members named N is determined.

            // If T is a type parameter, then the set is the union of the sets of accessible 
            // members named N in each of the types specified as a primary constraint or secondary 
            // constraint for T, along with the set of accessible members named N in object.

            // Otherwise, the set consists of all accessible members named N in T, 
            // including inherited members and the accessible members named N in object. If T is 
            // a constructed type, the set of members is obtained by substituting type arguments 
            // as described in §10.3.2. Members that include an override modifier are excluded 
            // from the set.

            var results = new HashSet<Symbol>();
            var inaccessible = new HashSet<Symbol>();
            var notInvocable = new HashSet<Symbol>();
            var hidden1 = new HashSet<Symbol>();
            var hidden2 = new HashSet<Symbol>();

            var types = new HashSet<TypeSymbol>(type.TypeAndAllBaseTypes());
            types.Add(System_Object);

            foreach (TypeSymbol t in types)
            {
                results.UnionWith(
                    from s in t.GetMembers(name)
                    where !s.IsOverride
                    select s);
            }

            inaccessible.UnionWith(from s in results where !IsMemberAccessible(s) select s);
            results.ExceptWith(inaccessible);

            var badArity = new HashSet<Symbol>();

            // Next, if K is zero, all nested types whose declarations include type parameters are removed. 
            // If K is not zero, all members with a different number of type parameters are removed. 
            // Note that when K is zero, methods having type parameters are not removed, since the 
            // type inference process might be able to infer the type arguments.

            if (arity == 0)
            {
                badArity.UnionWith(from s in results where s.IsNestedType() && ((NamedTypeSymbol)s).Arity != 0 select s);
            }
            else
            {
                badArity.UnionWith(from s in results where s is NamedTypeSymbol && ((NamedTypeSymbol)s).Arity != arity select s);
                badArity.UnionWith(from s in results where s is MethodSymbol && ((MethodSymbol)s).TypeParameters.Count != arity select s);
            }

            results.ExceptWith(badArity);

            // Next, if the member is invoked, all non-invocable members are removed from the set.
            if (invoked)
            {
                notInvocable.UnionWith(from s in results where !IsInvocable(s) select s);
            }

            results.ExceptWith(notInvocable);

            // Next, members that are hidden by other members are removed from the set. 
            // For every member S.M in the set, where S is the type in which the member M is declared, 
            // the following rules are applied:
            foreach (var member in results)
            {
                var declaringType = member.ContainingType;

                // If M is a constant, field, property, event, or enumeration member, 
                // then all members declared in a base type of S are removed from the set.
                if (member is FieldSymbol || member is PropertySymbol /* UNDONE || member is EventSymbol */)
                {
                    foreach (var baseType in declaringType.AllBaseTypeDefinitions())
                    {
                        hidden1.UnionWith(
                            from s in results
                            where s.ContainingType.OriginalDefinition == baseType
                            select s);
                    }
                }
                else if (member is NamedTypeSymbol)
                {
                    // If M is a type declaration, then all non-types declared in a base type of S 
                    // are removed from the set, and all type declarations with the same number of
                    // type parameters as M declared in a base type of S are removed from the set.
                    foreach (var baseType in declaringType.AllBaseTypeDefinitions())
                    {
                        hidden1.UnionWith(
                            from s in results
                            where s.ContainingType.OriginalDefinition == baseType
                            where !(s is NamedTypeSymbol) || ((NamedTypeSymbol)s).Arity == ((NamedTypeSymbol)member).Arity
                            select s);
                    }
                }
                else if (member is MethodSymbol)
                {
                    // If M is a method, then all non-method members declared in a base type of S
                    // are removed from the set.
                    foreach (var baseType in declaringType.AllBaseTypeDefinitions())
                    {
                        hidden1.UnionWith(
                            from m in results
                            where m.ContainingType.OriginalDefinition == baseType && !(m is MethodSymbol)
                            select m);
                    }
                }
            }

            results.ExceptWith(hidden1);

            // Next, interface members that are hidden by class members are removed from the set. 
            // This step only has an effect if T is a type parameter and T has both an effective base 
            // class other than object and a non-empty effective interface set. For every 
            // member S.M in the set, where S is the type in which the member M is declared, the 
            // following rules are applied if S is a class declaration other than object:

            foreach (var member in results)
            {
                var declaringType = member.ContainingType;
                if (!declaringType.IsClassType() || declaringType == System_Object)
                {
                    continue;
                }

                // If M is a constant, field, property, event, enumeration member, or type declaration, 
                // then all members declared in an interface declaration are removed from the set.
                if (member is FieldSymbol || member is PropertySymbol /* UNDONE || member is EventSymbol */ || member is NamedTypeSymbol)
                {
                    hidden2.UnionWith(
                        from m in results
                        where m.ContainingType.IsInterfaceType()
                        select m);
                }
                else if (member is MethodSymbol)
                {
                    // If M is a method, then all non-method members declared in an interface declaration 
                    // are removed from the set, and all methods with the same signature as M declared 
                    // in an interface declaration are removed from the set.
                    hidden2.UnionWith(
                        from m in results
                        where m.ContainingType.IsInterfaceType() && (!(m is MethodSymbol) || HaveSameSignature((MethodSymbol)m, (MethodSymbol)member))
                        select m);
                }
            }

            results.ExceptWith(hidden2);
            hidden1.UnionWith(hidden2);

            // Finally, having removed hidden members, the result of the lookup is determined:

            // If the set consists of a single member that is not a method, then this member is the result of the lookup.
            // Otherwise, if the set contains only methods, then this group of methods is the result of the lookup.

            // Otherwise, the lookup is ambiguous, and a compile-time error occurs.

            // For member lookups in types other than type parameters and interfaces, and member lookups in interfaces 
            // that are strictly single-inheritance (each interface in the inheritance chain has exactly zero or one direct 
            // base interface), the effect of the lookup rules is simply that derived members hide base members with the 
            // same name or signature. Such single-inheritance lookups are never ambiguous. The ambiguities that can possibly 
            // arise from member lookups in multiple-inheritance interfaces are described in §13.2.5.

            // UNDONE: Make this match what the original compiler does.
            if (results.Count == 0 || 
                (results.Count > 1 && !results.All(m => m is MethodSymbol)))
            {
                if (inaccessible.Count != 0)
                {
                    return LookupResult.Inaccessible(inaccessible.First());
                }
                else if (badArity.Count != 0)
                {
                    return LookupResult.WrongArity(badArity.First(), null);
                }
                else
                {
                    return LookupResult.Bad((DiagnosticInfo)null);
                }
            }
            else
            {
                return LookupResult.ForSymbols(results);
            }
#endif
        }
            internal override FunctionUpdateCommand Translate(
                UpdateTranslator translator, 
                ExtractedStateEntry stateEntry)
            {
                var mapping = GetFunctionMapping(stateEntry);
                StorageEntityTypeModificationFunctionMapping typeMapping = mapping.Item1;
                StorageModificationFunctionMapping functionMapping = mapping.Item2;
                EntityKey entityKey = stateEntry.Source.EntityKey;

                var stateEntries = new HashSet<IEntityStateEntry> { stateEntry.Source };

                // gather all referenced association ends
                var collocatedEntries =
                    // find all related entries corresponding to collocated association types
                    from end in functionMapping.CollocatedAssociationSetEnds
                    join candidateEntry in translator.GetRelationships(entityKey)
                    on end.CorrespondingAssociationEndMember.DeclaringType equals candidateEntry.EntitySet.ElementType
                    select Tuple.Create(end.CorrespondingAssociationEndMember, candidateEntry);

                var currentReferenceEnds = new Dictionary<AssociationEndMember, IEntityStateEntry>();
                var originalReferenceEnds = new Dictionary<AssociationEndMember, IEntityStateEntry>();

                foreach (var candidate in collocatedEntries)
                {
                    ProcessReferenceCandidate(entityKey, stateEntries, currentReferenceEnds, originalReferenceEnds, candidate.Item1, candidate.Item2);
                }
                
                // create function object
                FunctionUpdateCommand command;

                // consider the following scenario, we need to loop through all the state entries that is correlated with entity2 and make sure it is not changed.
                // entity1 <-- Independent Association <-- entity2 <-- Fk association <-- entity 3
                //                                           |
                //              entity4 <-- Fk association <--
                if (stateEntries.All(e => e.State == EntityState.Unchanged))
                {
                    // we shouldn't update the entity if it is unchanged, only update when referenced association is changed.
                    // if not, then this will trigger a fake update for principal end as describe in bug 894569.
                    command = null;
                }
                else
                {
                    command = new FunctionUpdateCommand(functionMapping, translator, stateEntries.ToList().AsReadOnly(), stateEntry);

                    // bind all function parameters
                    BindFunctionParameters(translator, stateEntry, functionMapping, command, currentReferenceEnds, originalReferenceEnds);

                    // interpret all result bindings
                    if (null != functionMapping.ResultBindings)
                    {
                        foreach (StorageModificationFunctionResultBinding resultBinding in functionMapping.ResultBindings)
                        {
                            PropagatorResult result = stateEntry.Current.GetMemberValue(resultBinding.Property);
                            command.AddResultColumn(translator, resultBinding.ColumnName, result);
                        }
                    }
                }

                return command;
            }
 //if the activities has any relation where they are the target and the source is not in activities
 private static bool HasIngoingConnections(DcrGraph graph, HashSet<Activity> activities) =>
      graph.IncludeExcludes.Any(keyValuePair => activities.All(a => !Equals(a, keyValuePair.Key)) &&
                                                      activities.Any(a => keyValuePair.Value.ContainsKey(a)))
            || graph.Conditions.Any(keyValuePair => activities.All(a => !Equals(a, keyValuePair.Key)) &&
                                                 activities.Any(a => keyValuePair.Value.Contains(a)))
            || graph.Responses.Any(keyValuePair => activities.All(a => !Equals(a, keyValuePair.Key)) &&
                                                activities.Any(a => keyValuePair.Value.Contains(a)))
            || graph.Milestones.Any(keyValuePair => activities.All(a => !Equals(a, keyValuePair.Key)) &&
                                                    activities.Any(a => keyValuePair.Value.Contains(a)));
Example #19
0
        public static void Main(string[] args)
        {
            if (args.Count() != 6)
            {
                Console.WriteLine("usage DependencyDumper assemblyFolder assemblyName typePattern minDepth roots absoluteOutputPath");
                Console.WriteLine("you provided: " + Environment.CommandLine);
                Console.ReadLine();
                return;
            }

            string assemblyFolder = args[0];
            string assemblyName = args[1];
            Regex typePattern = new Regex(args[2]);
            int minDepth = int.Parse(args[3]);
            string[] roots = string.IsNullOrEmpty(args[4]) ? new string[] { } : args[4].Split(',');
            string outputPath = args[5];

            RegisterAssemblyResolveHandler(assemblyFolder);

            types = new HashSet<Type>();
            dependencies = new HashSet<Tuple<Type, Type>>();
            allTypes = new HashSet<Type>();

            Console.WriteLine("dumping dependencies of " + assemblyName + " and all its referenced assemblies.");
            Console.WriteLine("using assemblies from folder " + assemblyFolder);
            Console.WriteLine("using only types matching " + typePattern);
            Console.WriteLine("dumping only dependency chains longer or equal to " + minDepth);
            Console.WriteLine("treating the following classes as roots (even if they are used by other classes): " + string.Join(", ", roots));
            Console.WriteLine("writing output to (should be a .tgf file)" + outputPath);
            Console.WriteLine();

            Console.WriteLine();
            Console.WriteLine("loading types from assemblies...");
            Assembly assembly = Assembly.LoadFrom(Path.Combine(assemblyFolder, assemblyName));

            var allAssemblies = new List<Assembly>();
            AddAssemblies(assembly, allAssemblies);

            foreach (var a in allAssemblies)
            {
                var t = a.GetTypes();
                foreach (var type in t)
                {
                    if (typePattern.IsMatch(type.FullName))
                    {
                        if (!type.Name.Contains("__"))
                        {
                            allTypes.Add(type);
                        }
                    }
                }
            }

            Console.WriteLine();
            Console.WriteLine("processing types:");
            foreach (Type type in allTypes)
            {
                Console.WriteLine("processing type " + type.FullName);

                Step(type);
            }

            // explicit roots
            Console.WriteLine();
            Console.WriteLine("processing explicit roots:");
            foreach (string root in roots)
            {
                Console.WriteLine("removing dependencies on " + root);
                var regex = new Regex(root);
                var toBreak = dependencies.Where(t => t.Item2.FullName != null && regex.IsMatch(t.Item2.FullName)).ToList();

                foreach (Tuple<Type, Type> tuple in toBreak)
                {
                    dependencies.Remove(tuple);
                }
            }

            Console.WriteLine();
            Console.WriteLine("calculating dependency depths");
            Dictionary<Type, int> levels = CalculateNodeDepth();

            Console.WriteLine();
            Console.WriteLine("removing types that are not in a deep enough dependency chain:");
            List<Type> remove = new List<Type>();
            do
            {
                remove.Clear();
                foreach (Type type in types)
                {
                    // root type and not enough depth
                    if (dependencies.All(t => t.Item2 != type) && levels[type] < minDepth)
                    {
                        remove.Add(type);
                    }
                }

                foreach (Type type in remove)
                {
                    Console.WriteLine("removing type " + type);
                    types.Remove(type);
                    dependencies.RemoveWhere(t => t.Item1 == type);
                }
            }
            while (remove.Count > 0);

            Console.WriteLine();
            Console.WriteLine("writing output file...");
            var list = new List<Type>(types);
            using (StreamWriter writer = new StreamWriter(outputPath))
            {
                foreach (var type in list)
                {
                    var i = levels.ContainsKey(type) ? levels[type] : 0;
                    writer.WriteLine(new List<Type>(types).IndexOf(type) + " " + type.NameToString() + " " + i);
                }

                writer.WriteLine("#");

                foreach (var dependency in dependencies)
                {
                    if (list.IndexOf(dependency.Item1) >= 0 && list.IndexOf(dependency.Item2) >= 0)
                    {
                        writer.WriteLine(
                            list.IndexOf(dependency.Item1) + " " +
                            list.IndexOf(dependency.Item2));
                    }
                }
            }

            Console.WriteLine();
            Console.WriteLine(@"opening yEd (C:\Program Files (x86)\yWorks\yEd\yEd.exe)");
            Process yEd = new Process
            {
                StartInfo =
                {
                    FileName = @"C:\Program Files (x86)\yWorks\yEd\yEd.exe",
                    Arguments = outputPath
                }
            };
            yEd.Start();

            Console.WriteLine("done. Output file is at " + outputPath);
        }
 private static bool AllOrNoneInThisSet(HashSet<Activity> activities, HashSet<Activity> set) => 
     activities.All(set.Contains) 
     ||
     !set.Any(activities.Contains);
Example #21
0
            public void Execute()
            {
                //We only want to run the base query once, so we capture all of the facet-ing terms then run the query
                //	once through the collector and pull out all of the terms in one shot
                var allCollector = new GatherAllCollector();
                var facetsByName = new Dictionary<string, Dictionary<string, FacetValue>>();


                using (var currentState = Database.IndexStorage.GetCurrentStateHolder(Index))
                {
                    var currentIndexSearcher = currentState.IndexSearcher;

                    var baseQuery = Database.IndexStorage.GetLuceneQuery(Index, IndexQuery, Database.IndexQueryTriggers);
                    currentIndexSearcher.Search(baseQuery, allCollector);
                    var fields = Facets.Values.Select(x => x.Name)
                            .Concat(Ranges.Select(x => x.Key));
                    var fieldsToRead = new HashSet<string>(fields);

                    FieldTermVector fieldTermVector;
                    var allVectoredTerms =
                        fieldsToRead.All(s => indexDefinition.TermVectors.TryGetValue(s, out fieldTermVector) && fieldTermVector != FieldTermVector.No);

                    if (allVectoredTerms)
                    {
                        IndexedTerms.ReadEntriesForFieldsFromTermVectors(currentState,
                            fieldsToRead,
                            allCollector.Documents,
                            (field,value, doc) => HandleFacets(field,value, facetsByName, doc));
                    }
                    else
                    {
                        IndexedTerms.ReadEntriesForFields(currentState,
                            fieldsToRead,
                            allCollector.Documents,
                            (field, value, doc) => HandleFacets(field,value, facetsByName, doc));
                    }
                    UpdateFacetResults(facetsByName);

                    CompleteFacetCalculationsStage1(currentState, allVectoredTerms);
                    CompleteFacetCalculationsStage2();
                }
            }
Example #22
0
        private static void EnsureFieldsAreInCache(IndexSearcherHolder.IndexSearcherHoldingState state, HashSet<string> fieldsToRead, IndexReader reader)
        {
            if (fieldsToRead.All(state.IsInCache))
                return;

            state.Lock.ExitReadLock();
            state.Lock.EnterWriteLock();
            try
            {
                var fieldsNotInCache = fieldsToRead.Where(field => state.IsInCache(field) == false).ToList();
                if (fieldsToRead.Count > 0)
                    FillCache(state, fieldsNotInCache, reader);
            }
            finally
            {
                state.Lock.ExitWriteLock();
            }
            state.Lock.EnterReadLock();
        }
Example #23
0
        /// <summary>
        /// Build a dictionary of mixins
        /// </summary>
        /// <param name="finalMixins">a list of mixins</param>
        /// <returns>a dictionary of all the necessary mixins</returns>
        private Dictionary<string, ModuleMixin> BuildMixinDictionary(IEnumerable<ModuleMixin> finalMixins)
        {
            var allMixins = new HashSet<ModuleMixin>();
            foreach (var mixin in finalMixins)
            {
                if (allMixins.All(x => x.MixinName != mixin.MixinName))
                    allMixins.Add(mixin);
            }

            return allMixins.ToDictionary(x => x.MixinName, x => x);
        }
Example #24
0
        /// <summary>
        /// Unite filename casing between git index and host OS
        /// </summary>
        /// <param name="repo"></param>
        /// <param name="gitPathInfo"></param>
        /// <param name="folders"></param>
        private static void UniteFilenameCasing(this UniteRepository repo, DirectoryInfo gitPathInfo, List<DirectoryInfo> folders)
        {
            var files = folders.GetAllFileInfos(gitPathInfo);
            var filesFullPathMap = new HashSet<String>(files.ConvertAll(s => s.FullName));
            var indexFileEntries = repo.Index.Where(f => filesFullPathMap.All(s => s.Replace(repo.Info.WorkingDirectory, string.Empty) != f.Path));

            foreach (var entry in indexFileEntries)
            {
                var sourcePath = repo.Info.WorkingDirectory + entry.Path;

                // Match host OS filename based on full pathname ignoring case
                var target = files.FirstOrDefault(f => String.Equals(f.FullName, sourcePath, StringComparison.CurrentCultureIgnoreCase));
                if (target == null) continue;

                // Unite the git index with the correct OS folder
                repo.Unite(sourcePath, target.FullName);
            }
        }
 /// <summary>
 /// Combines several collections of <see cref="IPHostEntry"/> objects into one deduplicated list
 /// </summary>
 /// <param name="collections">Collections to combine</param>
 /// <returns>Deduplicated list of <see cref="IPHostEntry"/> objects</returns>
 private static ICollection<IPHostEntry> Combine(IEnumerable<ICollection<IPHostEntry>> collections)
 {
   var result = new HashSet<IPHostEntry>();
   if (collections == null)
     return result;
   foreach (var collection in collections.Where(collection => collection != null))
     foreach (var host in collection.Where(host => host != null))
     {
       if (String.IsNullOrEmpty(host.HostName))
       {
         if (host.AddressList == null || !host.AddressList.Any())
           continue;
         
         // We only have one or more IP addresses - no HostName. We consider this host the same as a host we
         // already have in our result, when at least one IP address in this host equals one IP address of the result host.
         host.HostName = String.Empty;
         host.AddressList = host.AddressList.Where(address => address != null).ToArray();
         var alreadyPresentHost = result.FirstOrDefault(presentHost => presentHost.AddressList.Intersect(host.AddressList).Any());
         if (alreadyPresentHost == null)
           result.Add(host);
         else
           alreadyPresentHost.AddressList = alreadyPresentHost.AddressList.Union(host.AddressList).ToArray();
       }
       else
       {
         host.HostName = host.HostName.ToUpperInvariant();
         if (host.AddressList == null || !host.AddressList.Any())
         {
           // We only have a HostName - no IP addresses. We consider this host the same as a host we already have in our
           // result, wenn the HostName is the same
           host.AddressList = new IPAddress[0];
           if (result.All(presentHost => presentHost.HostName != host.HostName))
             result.Add(host);
         }
         else
         {
           // We have both, HostName and one or more IP addresses.
           // If there is already a host with the same HostName, we combine the IP addresses.
           // If there is a host with a different HostName, but at least one identical IP address,
           //   if the already present HostName is String.Empty, we replace the empty string with the new HostName
           //     and combine the IP addresses;
           //   if the already present HostName is not String.Empty, we log a warning,
           //     combine the IP addresses of the already present host and discard the HostName of the new host.
           // If there is no host with the same HostName and no host with one or more identical IP addresses, we
           //   add the new host to the result.
           host.AddressList = host.AddressList.Where(address => address != null).ToArray();
           var alreadyPresentHost = result.FirstOrDefault(presentHost => presentHost.HostName == host.HostName);
           if (alreadyPresentHost != null)
             alreadyPresentHost.AddressList = alreadyPresentHost.AddressList.Union(host.AddressList).ToArray();
           else
           {
             alreadyPresentHost = result.FirstOrDefault(presentHost => presentHost.AddressList.Intersect(host.AddressList).Any());
             if (alreadyPresentHost != null)
             {
               if (alreadyPresentHost.HostName == String.Empty)
               {
                 alreadyPresentHost.HostName = host.HostName;
                 alreadyPresentHost.AddressList = alreadyPresentHost.AddressList.Union(host.AddressList).ToArray();
               }
               else
               {
                 ServiceRegistration.Get<ILogger>().Warn("NeighborhoodBrowserService: Found two computers with different HostNames but at least one identical IP-Address:");
                 ServiceRegistration.Get<ILogger>().Warn("NeighborhoodBrowserService:   HostName: '{0}', IP-Addresses {1}", alreadyPresentHost.HostName, String.Join(" / ", alreadyPresentHost.AddressList.Select(adress => adress.ToString())));
                 ServiceRegistration.Get<ILogger>().Warn("NeighborhoodBrowserService:   HostName: '{0}', IP-Addresses {1}", host.HostName, String.Join(" / ", host.AddressList.Select(adress => adress.ToString())));
                 ServiceRegistration.Get<ILogger>().Warn("NeighborhoodBrowserService:   Discarding the second HostName and adding its IP-Addresses to the first host.");
                 alreadyPresentHost.AddressList = alreadyPresentHost.AddressList.Union(host.AddressList).ToArray();
               }
             }
             else
               result.Add(host);
           }
         }
       }
     }
   return result;
 }
 private static bool Assignable(HashSet<int> arg)
 {
     return arg.All(a => !arg.Contains(-a));
 }
Example #27
0
        public void RemoteRouter_must_deploy_dynamic_resizable_number_of_children_on_remote_host_driven_by_configuration
            ()
        {
            var probe = CreateTestProbe(masterActorSystem);
            var router = masterActorSystem.ActorOf(Props.Create<Echo>().WithRouter(FromConfig.Instance), "elastic-blub");
            var replies = new HashSet<ActorPath>();
            for (var i = 0; i < 5000; i++)
            {
                router.Tell("", probe.Ref);
                var expected = probe.ExpectMsg<IActorRef>(GetTimeoutOrDefault(null));
                replies.Add(expected.Path);
            }

            Assert.True(replies.Count >= 2);
            Assert.Equal(1, replies.Select(x => x.Parent).Distinct().Count());
            Assert.True(replies.All(x => x.Address.Equals(intendedRemoteAddress)));
            masterActorSystem.Stop(router);
        }
      public bool CreatePMRoom(HashSet<int> newUsers, int creator, out string error)
      {
         error = "";
         bool result = false;

         lock(managerLock)
         {
            Log("Enter createpmroom lock", MyExtensions.Logging.LogLevel.Locks);

            if (newUsers.Count < 2)
            {
               error = "There's not enough people to make the room";
            }
            else if (rooms.Any(x => x.Value.Users.SetEquals(newUsers)))
            {
               error = "There's already a room with this exact set of people!";
            }
            else if (!newUsers.All(x => users.ContainsKey(x)))
            {
               error = "One or more of the given users doesn't exist!";
            }
            /*else if (newUsers.Any(x => users[x].IrcUser))
            {
               error = "You can't include IRC users in a PM room!";
            }*/
            else if (!users.ContainsKey(creator))
            {
               error = "You don't seem to exist... I'm not sure how to create the room";
            }
            else if (users[creator].Banned || users[creator].Blocked)
            {
               error = "You are banned or blocked and cannot create a room";
            }
            else
            {
               PMRoom newRoom = new PMRoom(newUsers, creator, TimeSpan.FromDays(1));
               rooms.Add(newRoom.Name, newRoom);
               result = true;
            }

            Log("Exit createpmroom lock", MyExtensions.Logging.LogLevel.Locks);
         }

         if (result)
            BroadcastUserList();

         return result;
      }
Example #29
0
        public void RemoteRouter_must_let_remote_deployment_be_overridden_by_remote_configuration()
        {
            var probe = CreateTestProbe(masterActorSystem);
            var router = masterActorSystem.ActorOf(new RoundRobinPool(2).Props(Props.Create<Echo>())
                .WithDeploy(
                new Deploy(new RemoteScope(intendedRemoteAddress))), "remote-override");

            router.Path.Address.ShouldBe(intendedRemoteAddress);

            var replies = new HashSet<ActorPath>();
            for (var i = 0; i < 5; i++)
            {
                router.Tell("", probe.Ref);
                var expected = probe.ExpectMsg<IActorRef>(GetTimeoutOrDefault(null));
                replies.Add(expected.Path);
            }

            Assert.Equal(4, replies.Count);
            var parents = replies.Select(x => x.Parent).Distinct().ToList();
            parents.Count.ShouldBe(1);
            parents.Head().Address.ShouldBe(new Address("akka.tcp", sysName, "localhost", port));

            Assert.True(replies.All(x => x.Address.Equals(intendedRemoteAddress)));
            masterActorSystem.Stop(router);
        }
Example #30
0
        public void RemoveWhere()
        {
            var set = new HashSet<int>(Enumerable.Range(0, 10));
              Assert.That(() => { set.RemoveWhere(null); }, Throws.TypeOf(typeof(ArgumentNullException)));

              set.RemoveWhere(i => i % 2 == 0);
              Assert.AreEqual(5, set.Count);
              Assert.IsTrue(set.All(i => i % 2 == 1));
        }