Ejemplo n.º 1
0
        private static Dictionary<string, AssemblyToExtract> FindAssembliesToExtract(Assembly currentAssembly, HashSet<string> assembliesToFind)
        {
            var resources = currentAssembly.GetManifestResourceNames();
            var assembliesToExtract = new Dictionary<string, AssemblyToExtract>();

            foreach (var resource in resources)
            {
                if (!resource.StartsWith("costura"))
                    continue;

                var compressed = false;

                var assembly = assembliesToFind.FirstOrDefault(x => resource.EndsWith(x + CompressedAssemblySuffix, StringComparison.InvariantCultureIgnoreCase));
                if (assembly != null)
                    compressed = true;
                else
                    assembly = assembliesToFind.FirstOrDefault(x => resource.EndsWith(x + AssemblySuffix, StringComparison.InvariantCultureIgnoreCase));

                if (assembly == null)
                    continue;

                assembliesToExtract.Add(resource, new AssemblyToExtract { Compressed = compressed, Name = assembly });
            }

            return assembliesToExtract;
        }
Ejemplo n.º 2
0
        public DataManager()
        {
            var currencies = new HashSet<Currency>
            {
                new Currency
                {
                    Id = 1,
                    Name = "BGN",
                    BgExacaneRate = 1
                },

                new Currency
                {
                    Id = 2,
                    Name = "USD",
                    BgExacaneRate = 1.53M
                },
            };

            var nomenclatures = new HashSet<Nomenclature>
            {
                new Nomenclature
                {
                    Id = 1,
                    Name = "Sample Articels",
                    Price = 100M,
                    Currency = currencies.FirstOrDefault(x => x.Name == "BGN"),
                },

                new Nomenclature
                {
                    Id = 1,
                    Name = "Sample Articels 12",
                    Price = 200M,
                    Currency = currencies.FirstOrDefault(x => x.Name == "BGN"),
                },

                new Nomenclature
                {
                    Id = 1,
                    Name = "Sample Articels 23",
                    Price = 300M,
                    Currency = currencies.FirstOrDefault(x => x.Name == "BGN"),
                },
            };

            this.nomenclatureRepository = new NomenclatureRepository(nomenclatures);
            this.currencyRepository = new CurrencyRepository(currencies);
        }
Ejemplo n.º 3
0
        public void InitializeOnce()
        {
            if (_wasFirstInitialize)
            {
                return;
            }
            _wasFirstInitialize = true;
            if (ProjectOptions.Localize)
            {
                ProjectOptions.InitializeTranslationDb();
            }

            var bbTslint = DevDependencies?.FirstOrDefault(s => s.StartsWith("bb-tslint"));

            if (bbTslint != null)
            {
                var srcTsLint = PathUtils.Join(Owner.FullPath, $"node_modules/{bbTslint}/tslint.json");
                var srcFile   = DiskCache.TryGetItem(srcTsLint) as IFileCache;
                var dstTsLint = PathUtils.Join(Owner.FullPath, "tslint.json");
                if (srcFile != null && (!(DiskCache.TryGetItem(dstTsLint) is IFileCache dstFile) ||
                                        !dstFile.HashOfContent.SequenceEqual(srcFile.HashOfContent)))
                {
                    File.WriteAllBytes(dstTsLint, srcFile.ByteContent);
                    Console.WriteLine($"Updated tslint.json from {srcTsLint}");
                }
            }
        }
Ejemplo n.º 4
0
        public static string FindArtist(string szArtistName)
        {
            if (IsInDB(szArtistName))
            {
                return szArtistName;
            }
            HashSet<string> artistNames = Metadata.GetAllArtistNames();
            HashSet<string> possibleMatches = new HashSet<string>();
            bool matchFound = false;
            string query = szArtistName;
            string matchingArtist = string.Empty;
            foreach (string artistName in artistNames)
            {
                if (artistName.Equals(query, StringComparison.OrdinalIgnoreCase))
                {
                    matchingArtist = artistName;
                    matchFound = true;
                    break;
                }
                else if (artistName.ToLower().Contains(query))
                {
                    possibleMatches.Add(artistName);
                }
            }
            if (matchFound == false && possibleMatches.Count == 1)
            {
                matchingArtist = possibleMatches.FirstOrDefault();
            }/*
            else if (possibleMatches.Count > 1)
            {

            }*/
            return matchingArtist;
        }
Ejemplo n.º 5
0
        public void RemoveRoom(string roomId)
        {
            var roomToRemove = _privateRooms?.FirstOrDefault(room => room?.Id == roomId);

            if (roomToRemove != null)
            {
                _privateRooms.Remove(roomToRemove);
            }
        }
Ejemplo n.º 6
0
        public object Solve()
        {
            var levelsToComplete = new HashSet<Level>(levels);
            var levelsPartialyCompleted = new HashSet<Level>();
            int earnedStars = 0;
            int completionCount = 0;

            while (levelsToComplete.Any() || levelsPartialyCompleted.Any())
            {
                // 2-star in one shot
                {
                    var level = levelsToComplete.FirstOrDefault(x => x.RequiredFor2 <= earnedStars);

                    if (level != null)
                    {
                        levelsToComplete.Remove(level);
                        earnedStars += 2;
                        completionCount++;
                        continue;
                    }
                }

                // second star when the first is already earned
                {
                    var level = levelsPartialyCompleted.FirstOrDefault(x => x.RequiredFor2 <= earnedStars);

                    if (level != null)
                    {
                        levelsPartialyCompleted.Remove(level);
                        earnedStars++;
                        completionCount++;
                        continue;
                    }
                }

                // first star
                {
                    var level = levelsToComplete.Where(x => x.RequiredFor1 <= earnedStars).OrderByDescending(x=>x.RequiredFor2).FirstOrDefault();

                    if (level != null)
                    {
                        levelsToComplete.Remove(level);
                        levelsPartialyCompleted.Add(level);
                        earnedStars++;
                        completionCount++;
                        continue;
                    }
                }

                return "Too Bad";
            }

            return completionCount;
        }
Ejemplo n.º 7
0
        public static Solution Solve(Puzzle puzzle)
        {
            HashSet<State> reachedStates = new HashSet<State>(new StateComparer());
            State start = StartState(puzzle);
            Bfs(puzzle, reachedStates, start);
            State finish = reachedStates.FirstOrDefault(Final);

            //Preprocess(puzzle);
            //State exit =

            return new Solution(puzzle, finish, reachedStates);
        }
Ejemplo n.º 8
0
        private IManager GetManager(Type type)
        {
            IManager manager = _managers?.FirstOrDefault(o => o.GetType() == type);

            if (manager == null)
            {
                manager = (IManager)Activator.CreateInstance(type, this);

                AttachManager(manager);
            }

            return(manager);
        }
        public void TesteVelocidade10()
        {
            Random gen = new Random();
            int number = 10;

            HashSet<Vaga> vagas = new HashSet<Vaga>();
            HashSet<Usuario> usuarios = new HashSet<Usuario>();

            for (int i = 1; i <= number; ++i)
            {
                vagas.Add(new Vaga
                {
                    ID = i,
                    avaliacoes = new HashSet<Avaliacao>()
                });

                usuarios.Add(new Usuario
                {
                    ID = i,
                    avaliacoes = new HashSet<Avaliacao>()
                });
            }

            int j = 0;

            foreach (Usuario usuario in usuarios)
            {
                foreach (Vaga vaga in vagas)
                {
                    Avaliacao tempAvaliacao = new Avaliacao {
                        usuario = usuario,
                        vaga = vaga,
                        ID = ++j,
                        Gostou = gen.Next(100) > 49
                    };

                    usuario.avaliacoes.Add(tempAvaliacao);
                    vaga.avaliacoes.Add(tempAvaliacao);
                }
            }

            jaccardService.OrdenaVagasPorCoeficienteDeJaccard(vagas, usuarios.FirstOrDefault());
        }
Ejemplo n.º 10
0
 public static IList<Interval> Merge(IList<Interval> intervals)
 {
     var result = new HashSet<Interval>();
     foreach (var interval in intervals)
     {
         var temp = interval;
         while (true)
         {
             var found = result.FirstOrDefault(i => i.start <= temp.end && i.end >= temp.start);
             if (found == null)
             {
                 break;
             }
             result.Remove(found);
             temp = new Interval(Math.Min(found.start, temp.start), Math.Max(found.end, temp.end));
         }
         result.Add(temp);
     }
     return result.ToList();
 }
		static void PrepareZones()
		{
			foreach (var zone in DeviceConfiguration.Zones)
			{
				zone.KauDatabaseParent = null;
				zone.GkDatabaseParent = null;

				var gkParents = new HashSet<XDevice>();
				foreach (var device in zone.Devices)
				{
					var gkParent = device.AllParents.FirstOrDefault(x => x.DriverType == XDriverType.GK);
					gkParents.Add(gkParent);
				}

				var gkDevice = gkParents.FirstOrDefault();
				if (gkDevice != null)
				{
					zone.GkDatabaseParent = gkDevice;
				}
			}
		}
    /// <summary>
    /// Asynchronously returns a collection of IPHostEntries of all computers found in the NetworkNeighborhood
    /// </summary>
    /// <returns></returns>
    private async Task<ICollection<IPHostEntry>> DoGetHostsAsync()
    {
      var stopWatch = System.Diagnostics.Stopwatch.StartNew();
      var networks = NetworkUtils.GetAllLocalIPv4Networks();
      ServiceRegistration.Get<ILogger>().Debug("NetbiosNameServiceNeighborhoodBrowser: Found {0} local IPv4 network(s) with IP address(es) {1}", networks.Count, String.Join(" / ", networks.Select(i => i.Address + " (" + i.IPv4Mask + ")")));

      networks = RemoveLargeSubnets(networks);
      ServiceRegistration.Get<ILogger>().Debug("NetbiosNameServiceNeighborhoodBrowser: {0} local IPv4 network(s) are used: {1}", networks.Count, String.Join(" / ", networks.Select(i => i.Address + " (" + i.IPv4Mask + ")")));

      var tasks = new Dictionary<IPAddress, Task<NbNsNodeStatusResponse>>();
      using (var client = new NbNsClient())
      {
        foreach (var target in networks.SelectMany(NetworkUtils.GetAllAddressesInSubnet))
          tasks.Add(target, client.SendUnicastNodeStatusRequestAsync(NbNsNodeStatusRequest.WildCardNodeStatusRequest, target));
        await Task.WhenAll(tasks.Values);

        // Uncomment the following two lines for extensive logging
        // foreach (var kvp in tasks.Where(kvp => kvp.Value.Result != null))
        //   ServiceRegistration.Get<ILogger>().Debug("NetbiosNameServiceNeighborhoodBrowser: Found {0} ({1})\r\n{2}", kvp.Value.Result.WorkstationName, kvp.Key, kvp.Value.Result);
      }
      
      // If the computer has multiple network interfaces, it is found multiple times - once for each network interface.
      // Every occurence of the computer then has a different IP address (the one of the respective network interface).
      // As result we want this computer only as one IPHostEntry, but IPHostEntry.AddressList should show all IP addresses.
      var result = new HashSet<IPHostEntry>();
      var responses = tasks.Where(kvp => kvp.Value.Result != null);
      foreach (var kvp in responses)
      {
        var alreadyPresentHost = result.FirstOrDefault(host => host.HostName == kvp.Value.Result.WorkstationName);
        if (alreadyPresentHost == null)
          result.Add(new IPHostEntry { AddressList = new[] { kvp.Key }, HostName = kvp.Value.Result.WorkstationName });
        else
        {
          if (!alreadyPresentHost.AddressList.Any(address => address.Equals(kvp.Key)))
            alreadyPresentHost.AddressList = alreadyPresentHost.AddressList.Union(new[] { kvp.Key }).ToArray();
        }
      }
      NeighborhoodBrowserHelper.LogResult(result, GetType().Name, stopWatch.ElapsedMilliseconds);
      return result;
    }
Ejemplo n.º 13
0
        public IEnumerable<ExcelFileItem> GetEmailData(ExcelPostFileDto fileOptions)
        {
            var worksheet = Workbook.Worksheets(fileOptions.FilePath).ToArray()[fileOptions.WorkSheetNumber - 1];

            var list = new HashSet<ExcelFileItem>();

            for (var i = fileOptions.HasHeader ? 1 : 0; i < worksheet.Rows.Length; i++)
            {
                if (worksheet.Rows[i].Cells[0] != null)
                {
                    var item = new ExcelFileItem
                    {
                        Email = worksheet.Rows[i].Cells[fileOptions.EmailPosition - 1].Text,
                        Name = worksheet.Rows[i].Cells[fileOptions.NamePosition - 1].Text,
                        LastName = worksheet.Rows[i].Cells[fileOptions.LastNamePosition - 1].Text
                    };
                    if(list.FirstOrDefault(x => x.Email == item.Email) == null)
                        list.Add(item);

                }
            }
            return list;
        }
Ejemplo n.º 14
0
    async Task OnAddedToCart(string productId)
    {
        var product = _products?.FirstOrDefault(p => p.Id == productId);

        if (product is null)
        {
            return;
        }

        if (await ShoppingCartService.AddOrUpdateItemAsync(1, product))
        {
            _products = await InventoryService.GetAllProductsAsync();

            _cartItems = await ShoppingCartService.GetAllItemsAsync();

            await ToastService.ShowToastAsync(
                "Added to cart",
                $"The '{product.Name}' for {product.UnitPrice:C2} was added to your cart...");

            await Observer.NotifyStateChangedAsync();

            StateHasChanged();
        }
    }
Ejemplo n.º 15
0
        public static IMyEntity Find( string displayName )
        {
            HashSet<IMyEntity> entities = new HashSet<IMyEntity>( );

            Wrapper.GameAction( ( ) =>
            {
                MyAPIGateway.Entities.GetEntities( entities, x => x is IMyCubeGrid );
            } );

            return entities.FirstOrDefault( entity => entity.DisplayName.ToLower( ).Contains( displayName.ToLower( ) ) );
        }
Ejemplo n.º 16
0
 /// <summary>
 /// Gets a device configuration bit-field given its position in this device configuration register.
 /// </summary>
 /// <param name="bitpos">The bit position (zero-based).</param>
 /// <returns>
 /// A <see cref="DevConfigField"/> instance or null.
 /// </returns>
 public DevConfigField GetField(int bitpos) => fields.FirstOrDefault(f => f.BitPos == bitpos);
Ejemplo n.º 17
0
 private int GetOptionSortValue(OptionInfo optionInfo, HashSet<ProductOptionValueSort> sorts, ProductOption option, List<OptionInfo> values)
 {
     var productOptionValueSort =
         sorts.FirstOrDefault(sort => sort.ProductOption == option && sort.Value == optionInfo.Value);
     return productOptionValueSort != null
         ? productOptionValueSort.DisplayOrder
         : values.Count;
 }
Ejemplo n.º 18
0
    /// <summary>
    /// Two cases:
    ///   1) ToRightOf.  we can exclude the known left hand attribute from house 5 and the right hand attribute from house 1
    ///   2) NextTo.  If we get lucky and one of the neighbours has a known house we can fix the other
    /// TODO: ToRightOf should take advantage of similar logic to NextTo.
    /// </summary>
    /// <param name="clues">this will change if the method is called multiple times</param>
    /// <returns>a new cloned list of clues</returns>
    private static (bool, ISet <Clue>) InferNeighbours(ISet <Clue> clues)
    {
        var  cluesOut = new HashSet <Clue>();
        bool modified = false;

        foreach (var clue in clues)
        {
            var clueOut = clue.Clone();
            cluesOut.Add(clueOut);
        }
        foreach (var neighbour in Neighbour.neighbours)
        {
            // assert there are clues for all attributes
            // assert that setter is accustomed to a left-to-right culture
            Clue clueA, clueB;
            try
            {
                clueA = cluesOut.First(c => c.attributes[neighbour.attributeTypeA] == neighbour.attrivubuteValueA);
                clueB = cluesOut.First(c => c.attributes[neighbour.attributeTypeB] == neighbour.attrivubuteValueB);
            }
            catch (Exception e)
            {
                throw;
            }
            if (neighbour.Relation == Relation.ToRightOf)
            {
                var clueC = cluesOut.FirstOrDefault(c => c.attributes[AttributeType.Position] == Position.One);
                // left most house is to the right of nothing
                var clueD = cluesOut.FirstOrDefault(c => c.attributes[AttributeType.Position] == Position.Five);
                // right most house is to the left of nothing
                byte?oldC = clueC?.attributes[neighbour.attributeTypeA], oldD = clueD?.attributes[neighbour.attributeTypeB];
                if (clueC != null)
                {
                    clueC.attributes[neighbour.attributeTypeA]
                        = TurnOffBit(clueC.attributes[neighbour.attributeTypeA], neighbour.attrivubuteValueA);
                }

                if (clueD != null)
                {
                    clueD.attributes[neighbour.attributeTypeB]
                        = TurnOffBit(clueD.attributes[neighbour.attributeTypeB], neighbour.attrivubuteValueB);
                }
                modified = oldC != clueC?.attributes[neighbour.attributeTypeA] || oldD != clueD?.attributes[neighbour.attributeTypeB];
            }
            else if (neighbour.Relation == Relation.NextTo)
            {
                if (IsResolvedAttribute(clueA.attributes[AttributeType.Position]))
                {
                    // we know the position of clue A we may be able to infer the position of clue B
                    if (clueA.attributes[AttributeType.Position] == Position.One)
                    {
                        if (clueB.attributes[AttributeType.Position] != Position.Two)
                        {
                            MyDebug.Assert(!IsResolvedAttribute(clueB.attributes[AttributeType.Position]));
                            clueB.attributes[AttributeType.Position] = Position.Two;
                            modified = true;
                        }
                    }
                    else if (clueA.attributes[AttributeType.Position] == Position.Five)
                    {
                        if (clueB.attributes[AttributeType.Position] != Position.Four)
                        {
                            MyDebug.Assert(!IsResolvedAttribute(clueB.attributes[AttributeType.Position]));
                            clueB.attributes[AttributeType.Position] = Position.Four;
                            modified = true;
                        }
                    }
                }
                if (IsResolvedAttribute(clueB.attributes[AttributeType.Position]))
                {
                    // we know the position of clue B we may be able to infer the position of clue B
                    if (clueB.attributes[AttributeType.Position] == Position.One)
                    {
                        if (clueA.attributes[AttributeType.Position] != Position.Two)
                        {
                            MyDebug.Assert(!IsResolvedAttribute(clueA.attributes[AttributeType.Position]));
                            clueA.attributes[AttributeType.Position] = Position.Two;
                            modified = true;
                        }
                    }
                    else if (clueB.attributes[AttributeType.Position] == Position.Five)
                    {
                        if (clueA.attributes[AttributeType.Position] != Position.Four)
                        {
                            MyDebug.Assert(!IsResolvedAttribute(clueA.attributes[AttributeType.Position]));
                            clueA.attributes[AttributeType.Position] = Position.Four;
                            modified = true;
                        }
                    }
                }
            }
        }

        return(modified, cluesOut);
    }
Ejemplo n.º 19
0
        public static IEnumerable <Type> LoadFrom(this IServiceCollection collection, Assembly assembly)
        {
            // list of all the types which are added with this method
            List <Type> addedTypes = new List <Type>();

            Type[] allTypes;
            try
            {
                // first, get all types in te assembly
                allTypes = assembly.GetTypes();
            }
            catch (ReflectionTypeLoadException ex)
            {
                Console.WriteLine(ex.LoaderExceptions[0]);
                return(Enumerable.Empty <Type>());
            }
            // all types which have INService implementation are services
            // which are supposed to be loaded with this method
            // ignore all interfaces and abstract classes
            var services = new Queue <Type>(allTypes
                                            .Where(x => x.GetInterfaces().Contains(typeof(INService)) &&
                                                   !x.GetTypeInfo().IsInterface&& !x.GetTypeInfo().IsAbstract
#if GLOBAL_NADEKO
                                                   && x.GetTypeInfo().GetCustomAttribute <NoPublicBotAttribute>() == null
#endif
                                                   )
                                            .ToArray());

            // we will just return those types when we're done instantiating them
            addedTypes.AddRange(services);

            // get all interfaces which inherit from INService
            // as we need to also add a service for each one of interfaces
            // so that DI works for them too
            var interfaces = new HashSet <Type>(allTypes
                                                .Where(x => x.GetInterfaces().Contains(typeof(INService)) &&
                                                       x.GetTypeInfo().IsInterface));

            // keep instantiating until we've instantiated them all
            while (services.Count > 0)
            {
                var serviceType = services.Dequeue();                                     //get a type i need to add

                if (collection.FirstOrDefault(x => x.ServiceType == serviceType) != null) // if that type is already added, skip
                {
                    continue;
                }

                //also add the same type
                var interfaceType = interfaces.FirstOrDefault(x => serviceType.GetInterfaces().Contains(x));
                if (interfaceType != null)
                {
                    addedTypes.Add(interfaceType);
                    collection.AddSingleton(interfaceType, serviceType);
                }
                else
                {
                    collection.AddSingleton(serviceType, serviceType);
                }
            }

            return(addedTypes);
        }
Ejemplo n.º 20
0
        private void AddPackageRecursive(List<IPackage> packagesOut, HashSet<IPackage> packages, IPackage packageToTrack)
        {
            // Go first recursively with all dependencies resolved
            var dependencies = packageToTrack.DependencySets.SelectMany(deps => deps.Dependencies);
            foreach (var dependency in dependencies)
            {
                var nextPackage = packages.FirstOrDefault(p => p.Id == dependency.Id);
                if (nextPackage != null)
                {
                    AddPackageRecursive(packagesOut, packages, nextPackage);
                }
            }

            // This package is now resolved, add it to the ordered list
            packagesOut.Add(packageToTrack);

            // Remove it from the list of packages to process
            packages.Remove(packageToTrack);
        }
        /// <inheritdoc />
        public virtual ICompressionProvider GetCompressionProvider(HttpContext context)
        {
            // e.g. Accept-Encoding: gzip, deflate, sdch
            var accept = context.Request.Headers[HeaderNames.AcceptEncoding];

            // Note this is already checked in CheckRequestAcceptsCompression which _should_ prevent any of these other methods from being called.
            if (StringValues.IsNullOrEmpty(accept))
            {
                Debug.Assert(false, "Duplicate check failed.");
                _logger.NoAcceptEncoding();
                return(null);
            }

            if (!StringWithQualityHeaderValue.TryParseList(accept, out var encodings) || !encodings.Any())
            {
                _logger.NoAcceptEncoding();
                return(null);
            }

            var candidates = new HashSet <ProviderCandidate>();

            foreach (var encoding in encodings)
            {
                var encodingName = encoding.Value;
                var quality      = encoding.Quality.GetValueOrDefault(1);

                if (quality < double.Epsilon)
                {
                    continue;
                }

                for (int i = 0; i < _providers.Length; i++)
                {
                    var provider = _providers[i];

                    if (StringSegment.Equals(provider.EncodingName, encodingName, StringComparison.OrdinalIgnoreCase))
                    {
                        candidates.Add(new ProviderCandidate(provider.EncodingName, quality, i, provider));
                    }
                }

                // Uncommon but valid options
                if (StringSegment.Equals("*", encodingName, StringComparison.Ordinal))
                {
                    for (int i = 0; i < _providers.Length; i++)
                    {
                        var provider = _providers[i];

                        // Any provider is a candidate.
                        candidates.Add(new ProviderCandidate(provider.EncodingName, quality, i, provider));
                    }

                    break;
                }

                if (StringSegment.Equals("identity", encodingName, StringComparison.OrdinalIgnoreCase))
                {
                    // We add 'identity' to the list of "candidates" with a very low priority and no provider.
                    // This will allow it to be ordered based on its quality (and priority) later in the method.
                    candidates.Add(new ProviderCandidate(encodingName.Value, quality, priority: int.MaxValue, provider: null));
                }
            }

            ICompressionProvider selectedProvider = null;

            if (candidates.Count <= 1)
            {
                selectedProvider = candidates.FirstOrDefault().Provider;
            }
            else
            {
                selectedProvider = candidates
                                   .OrderByDescending(x => x.Quality)
                                   .ThenBy(x => x.Priority)
                                   .First().Provider;
            }

            if (selectedProvider == null)
            {
                // "identity" would match as a candidate but not have a provider implementation
                _logger.NoCompressionProvider();
                return(null);
            }

            _logger.CompressingWith(selectedProvider.EncodingName);
            return(selectedProvider);
        }
Ejemplo n.º 22
0
        public static void LVCache(IDictionary <string, string> dict, string[] args)
        {
            //
            // Last value cache
            // Uses XPUB subscription messages to re-send data
            //
            // Author: metadings
            //

            using (var context = new ZContext())
                using (var frontend = new ZSocket(context, ZSocketType.SUB))
                    using (var backend = new ZSocket(context, ZSocketType.XPUB))
                    {
                        // Subscribe to every single topic from publisher
                        frontend.Bind("tcp://*:5557");
                        frontend.SubscribeAll();

                        backend.Bind("tcp://*:5558");

                        // Store last instance of each topic in a cache
                        var cache = new HashSet <LVCacheItem>();

                        // We route topic updates from frontend to backend, and
                        // we handle subscriptions by sending whatever we cached,
                        // if anything:
                        var      p = ZPollItem.CreateReceiver();
                        ZMessage msg;
                        ZError   error;
                        while (true)
                        {
                            // Any new topic data we cache and then forward
                            if (frontend.PollIn(p, out msg, out error, TimeSpan.FromMilliseconds(1)))
                            {
                                using (msg)
                                {
                                    string topic   = msg[0].ReadString();
                                    string current = msg[1].ReadString();

                                    LVCacheItem previous = cache.FirstOrDefault(item => topic == item.Topic);
                                    if (previous != null)
                                    {
                                        cache.Remove(previous);
                                    }
                                    cache.Add(new LVCacheItem {
                                        Topic = topic, Current = current
                                    });

                                    backend.Send(msg);
                                }
                            }
                            else
                            {
                                if (error == ZError.ETERM)
                                {
                                    break;                      // Interrupted
                                }
                                if (error != ZError.EAGAIN)
                                {
                                    throw new ZException(error);
                                }
                            }

                            // When we get a new subscription, we pull data from the cache:
                            if (backend.PollIn(p, out msg, out error, TimeSpan.FromMilliseconds(1)))
                            {
                                using (msg)
                                {
                                    // Event is one byte 0=unsub or 1=sub, followed by topic
                                    byte subscribe = msg[0].ReadAsByte();
                                    if (subscribe == 0x01)
                                    {
                                        string      topic    = msg[0].ReadString();
                                        LVCacheItem previous = cache.FirstOrDefault(item => topic == item.Topic);
                                        if (previous != null)
                                        {
                                            Console.WriteLine("Sending cached topic {0}", topic);
                                            backend.SendMore(new ZFrame(previous.Topic));
                                            backend.Send(new ZFrame(previous.Current));
                                        }
                                        else
                                        {
                                            Console.WriteLine("Failed to send cached topic {0}!", topic);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                if (error == ZError.ETERM)
                                {
                                    break;                      // Interrupted
                                }
                                if (error != ZError.EAGAIN)
                                {
                                    throw new ZException(error);
                                }
                            }
                        }
                    }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Selects a composite to be run
        /// This is called every tick and returns a composite
        /// Which composite is returned changes based on the QueueItem currently being processed.
        /// </summary>
        private static Composite Next()
        {
            // 1. No active node
            if (_active == null)
            {
                // 1.1 Nothing in the Queue.
                if (!Q.Any())
                {
                    return(Continue);
                }

                // 1.2 Start the next QueueItem that has passed its condition
                var nextItem = Q.FirstOrDefault(n => n.ConditionPassed);
                if (nextItem != null)
                {
                    Logger.Verbose("Starting QueueItem");
                    if (Q.Remove(nextItem))
                    {
                        _active = nextItem;
                        if (_active.OnStart != null)
                        {
                            _active.OnStart.Invoke(_active);
                        }
                        return(Loop);
                    }
                    ;
                }

                // 1.3 Nothing has passed condition yet.
                return(Continue);
            }

            // 2. We're currently processing a QueueItem
            // But havent started processing its nodes.
            if (_active.ActiveNode == null)
            {
                // 2.1 Handle starting the first Node
                _active.ActiveNode = _active.Nodes.First();
                _active.ActiveNode.Run();
                if (_active.OnNodeStart != null)
                {
                    _active.OnNodeStart.Invoke(_active);
                }
                return(_active.ActiveNode.Behavior);
            }

            BotMain.StatusText = _active.ActiveNode.StatusText;

            // 3. We're currently processing a QueueItem
            // And the current node is Done
            if (_active.ActiveNode.IsDone)
            {
                // 3.1 Handle ActiveNode has finished
                _active.CompletedNodes++;
                _active.ActiveNode.OnDone();
                Logger.Verbose("[{0}] Complete {1}/{2} ({3})", _active.Name, _active.CompletedNodes, _active.Nodes.Count, _active.ActiveNode.GetType());
                if (_active.OnNodeDone != null)
                {
                    _active.OnNodeDone.Invoke(_active);
                }

                // 3.2 All nodes are finished, so the QueueItem is now Done.
                if (_active.IsComplete)
                {
                    // 3.2.1 Handle all nodes are finished
                    if (_active.OnDone != null)
                    {
                        _active.OnDone.Invoke(_active);
                    }
                    Logger.Verbose("[{1}] Completed {0}", _active.CompletedNodes, _active.Name);

                    // 3.2.2 Traverse Upwards
                    // If this QueueItem is a child, we need to continue with its parent
                    // Parent gets taken off the shelf (unpaused) and set as the new active Queueitem.
                    var parent = Shelf.FirstOrDefault(i => i.ParentOf == _active.Id);
                    Logger.Verbose("All Nodes Complete ParentId={0} ThisId={1}", parent != null ? parent.Id.ToString() : "Null", _active.Id);
                    if (parent != null)
                    {
                        _active = parent;
                        Shelf.Remove(parent);
                        Logger.Verbose("ShelfCount={0}", Shelf.Count);
                        return(Loop);
                    }

                    // 3.2.3 Shove it back at the bottom of the queue if it should be repeated
                    if (_active.Repeat)
                    {
                        var temp = _active;
                        _active.Reset();
                        _active = null;
                        Queue(temp);
                        return(Loop);
                    }

                    // 3.2.4 No parent, No Repeat, so just end the QueueItem
                    _active = null;
                    return(Loop);
                }

                // 3.3 Handle start of next node
                var currentPosition = _active.Nodes.IndexOf(_active.ActiveNode);
                _active.ActiveNode = _active.Nodes.ElementAt(currentPosition + 1);
                _active.ActiveNode.Run();
                if (_active.OnNodeStart != null)
                {
                    _active.OnNodeStart.Invoke(_active);
                }
                return(_active.ActiveNode.Behavior);
            }

            // 4.1 Traverse Downwards
            // We're currently processing a QueueItem
            // And the current node is NOT Done
            // And the current node has children
            Logger.Verbose("ShelfCount={0}", Shelf.Count);
            var children = _active.ActiveNode.GetChildren();

            if (children.Count > 0)
            {
                Logger.Log("Processing {0} Children of '{1}' ({2})", children.Count, _active.Name, _active.Id);

                // Copy QueueItem so we can resume it later.
                var queueItemToShelve = _active;

                // Wrap the children as a new QueueItem
                var childQueueItem = new QueueItem
                {
                    Name  = string.Format("Children of {0}", _active.Name),
                    Nodes = _active.ActiveNode.GetChildren()
                };

                // Store a references between parent and child
                queueItemToShelve.ParentOf = childQueueItem.Id;
                childQueueItem.ChildOf     = _active.Id;

                // Pause the active QueueItem by moving it to the shelf
                Shelf.Add(queueItemToShelve);

                // Start working on the children.
                _active = childQueueItem;
                return(Loop);
            }

            // Handle continuing an in-progress Node
            LogBehavior(_active);
            return(_active.ActiveNode.Behavior);
        }
Ejemplo n.º 24
0
        private static void ClientOnDataReceived(object sender, Message message)
        {
            try
            {
                var messages = message.MessageString.Split('\u0013');
                foreach (var msg in messages)
                {
                    if (msg == "ping" || String.IsNullOrWhiteSpace(msg))
                    {
                        return;                                                  //ignore
                    }
                    string t = null;
                    try
                    {
                        dynamic m = JsonConvert.DeserializeObject(msg);
                        t = m.JType?.ToString();
                    }
                    catch (Exception)
                    {
                        //Bot.SendTextMessage(Settings.MainChatId, e.Message);
                        continue;
                    }
                    Werewolf game;
                    if (t != null)
                    {
                        Console.WriteLine(t);
                        switch (t)
                        {
                        case "PlayerJoinInfo":
                            var pji = JsonConvert.DeserializeObject <PlayerJoinInfo>(msg);
                            game = Games.FirstOrDefault(x => x.Guid == pji.GameId);
                            game?.AddPlayer(pji.User);
                            break;

                        case "GameStartInfo":
                            var gsi = JsonConvert.DeserializeObject <GameStartInfo>(msg);
                            try
                            {
                                //double check we don't already have a game...
                                game = Games.FirstOrDefault(x => x.ChatId == gsi.Chat.Id);
                                if (game != null)
                                {
                                    game.ShowJoinButton();
                                }
                                else
                                {
                                    game = new Werewolf(gsi.Chat.Id, gsi.User, gsi.Chat.Title,
                                                        gsi.Chaos);
                                    Games.Add(game);
                                    GamesStarted++;
                                }
                            }
                            catch (Exception e)
                            {
                                Bot.SendTextMessageAsync(ErrorGroup, $"Error Occured during Node <code>{ClientId}</code> processing <code>GameStartInfo</code>:\n\n{e.ToString()}\n\nData:\n{gsi.ToString()}", ParseMode.Html);
                            }
                            break;

                        case "ForceStartInfo":
                            var fsi = JsonConvert.DeserializeObject <ForceStartInfo>(msg);
                            game = Games.FirstOrDefault(x => x.ChatId == fsi.GroupId);
                            game?.ForceStart();
                            break;

                        //case "ReplyInfo":
                        //    var ri = JsonConvert.DeserializeObject<ReplyInfo>(msg);
                        //    game =
                        //        Games.FirstOrDefault(
                        //            x => x.Players.Any(p => p.TeleUser.Id == ri.Update.Message.From.Id && !p.IsDead));
                        //    game?.HandleReply(ri.Update);
                        //    break;
                        case "CallbackInfo":
                            var ci = JsonConvert.DeserializeObject <CallbackInfo>(msg);
                            game =
                                Games.FirstOrDefault(
                                    x =>     //x.Players?.Any(p => p != null && !p.IsDead && p.TeleUser.Id == ci.Query.From.Id) ?? false);
                                    x.Guid == ci.GameId);
                            game?.HandleReply(ci.Query);
                            break;

                        case "PlayerListRequestInfo":
                            var plri = JsonConvert.DeserializeObject <PlayerListRequestInfo>(msg);
                            game = Games.FirstOrDefault(x => x.ChatId == plri.GroupId);
                            game?.OutputPlayers();
                            break;

                        case "PlayerFleeInfo":
                            var pfi = JsonConvert.DeserializeObject <PlayerFleeInfo>(msg);
                            game = Games.FirstOrDefault(x => x.ChatId == pfi.GroupId);
                            game?.RemovePlayer(pfi.User);
                            break;

                        case "LoadLangInfo":
                            var lli = JsonConvert.DeserializeObject <LoadLangInfo>(msg);
                            game = Games.FirstOrDefault(x => x.ChatId == lli.GroupId);
                            game?.LoadLanguage(lli.FileName);
                            break;

                        case "PlayerSmiteInfo":
                            var psi = JsonConvert.DeserializeObject <PlayerSmiteInfo>(msg);
                            game = Games.FirstOrDefault(x => x.ChatId == psi.GroupId);
                            game?.FleePlayer(psi.UserId);
                            break;

                        case "UpdateNodeInfo":
                            var uni = JsonConvert.DeserializeObject <UpdateNodeInfo>(msg);
                            IsShuttingDown = true;
                            if (uni.Kill)
                            {
                                //force kill
                                Environment.Exit(1);
                            }
                            break;

                        case "SkipVoteInfo":
                            var svi = JsonConvert.DeserializeObject <SkipVoteInfo>(msg);
                            game = Games.FirstOrDefault(x => x.ChatId == svi.GroupId);
                            game?.SkipVote();
                            break;

                        case "GameKillInfo":
                            var gki = JsonConvert.DeserializeObject <GameKillInfo>(msg);
                            game = Games.FirstOrDefault(x => x.ChatId == gki.GroupId);
                            game?.Kill();
                            break;

                        case "GetGameInfo":
                            var ggi = JsonConvert.DeserializeObject <GetGameInfo>(msg);
                            var g   = Games.FirstOrDefault(x => x.ChatId == ggi.GroupId);
                            if (g == null)
                            {
                                message.Reply("null");
                            }
                            //build our response
                            var gi = new GameInfo
                            {
                                Language  = g.Language,
                                ChatGroup = g.ChatGroup,
                                GroupId   = g.ChatId,
                                NodeId    = ClientId,
                                Guid      = g.Guid,
                                Cycle     = g.Time,
                                State     = g.IsRunning ? GameState.Running : g.IsJoining ? GameState.Joining : GameState.Dead,
                                Users     = new HashSet <int>(g.Players?.Where(x => !x.IsDead)?.Select(x => x.TeleUser.Id) ?? new[] { 0 }),
                                Players   = g.Players?.Select(x => new
                                {
                                    Bitten = x.Bitten?"Yes":"No",
                                    x.Bullet,
                                    Choice          = g.Players.FirstOrDefault(p => p.Id == x.Choice)?.Name,
                                    CurrentQuestion = x.CurrentQuestion?.QType.ToString(),
                                    x.DonationLevel,
                                    IsDead = x.IsDead?"Yes":"No",
                                    x.Name,
                                    LoverId    = g.Players.FirstOrDefault(p => p.Id == x.LoverId)?.Name,
                                    PlayerRole = x.PlayerRole.ToString(),
                                    Team       = x.Team.ToString(),
                                    x.Votes,
                                    x.Id
                                })
                            };
                            message.Reply(JsonConvert.SerializeObject(gi));
                            break;

                        case "ExtendTimeInfo":
                            var eti = JsonConvert.DeserializeObject <ExtendTimeInfo>(msg);
                            game = Games.FirstOrDefault(x => x.ChatId == eti.GroupId);
                            game?.ExtendTime(eti.User, eti.Admin, eti.Seconds);
                            break;

                        case "JoinButtonRequestInfo":
                            var jbri = JsonConvert.DeserializeObject <JoinButtonRequestInfo>(msg);
                            game = Games.FirstOrDefault(x => x.ChatId == jbri.GroupId);
                            game?.ShowJoinButton();
                            Console.ForegroundColor = ConsoleColor.Green;
                            Console.WriteLine(jbri.GroupId);
                            Console.ForegroundColor = ConsoleColor.Gray;
                            break;

                        case "ReloadLangInfo":
                            var rli = JsonConvert.DeserializeObject <ReloadLangInfo>(msg);
                            ReloadLang(rli.LangName);
                            Console.ForegroundColor = ConsoleColor.Yellow;
                            Console.WriteLine("Reloaded language file: " + rli.LangName);
                            Console.ForegroundColor = ConsoleColor.Gray;
                            break;

                        default:
                            Console.WriteLine(msg);
                            break;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message + "\n" + message.MessageString);
                try
                {
                    Directory.CreateDirectory(Path.Combine(RootDirectory, "ReceiveErrors"));
                    using (var sw = new StreamWriter(Path.Combine(RootDirectory, "ReceiveErrors", "error.log"), true))
                    {
                        sw.WriteLine(e.Message + Environment.NewLine + message.MessageString + Environment.NewLine +
                                     e.StackTrace);
                    }
                }
                catch
                {
                    // ignored
                }
            }
        }
Ejemplo n.º 25
0
 public T GetCurrentItem()
 {
     return(set.FirstOrDefault());
 }
Ejemplo n.º 26
0
 Player GetPlayerById(int id)
 => _players.FirstOrDefault(p => p.Id == id);
Ejemplo n.º 27
0
        public async Task HandleAsync(AddDScan command)
        {
            var    shipList           = new List <Ship>();
            var    uniqueShips        = new HashSet <string>();
            var    uniqueTypes        = new HashSet <string>();
            var    uniqueClasses      = new HashSet <string>();
            var    interestingTargets = new HashSet <Ship>();
            string sysName            = "";
            int    ctr = 0;

            if (command.content != "")
            {
                var DScanLines = FormatRawHtmlTextString(command.content);

                var entries = SeparateDScanColumnsByTabs(DScanLines);

                sysName = CheckForSystemName(entries);

                foreach (var entry in entries)
                {
                    var ship = ShipFetcher.ReturnShip(entry[2]);
                    if (ship.Type != "Unknown")
                    {
                        shipList.Add(ship);
                        uniqueShips.Add(ship.Name);
                        uniqueClasses.Add(ship.Class);
                        uniqueTypes.Add(ship.Type);
                    }
                    if (interestingTargets.FirstOrDefault(x => x.Name == ship.Name) == null)
                    {
                        if (ship.Class == "Unique" || ship.Type == "Combat Scanner Probe")
                        {
                            interestingTargets.Add(ship);
                            ctr++;
                        }
                    }
                }

                var shipCount  = PrepareSetForCounting(uniqueShips);
                var typeCount  = PrepareSetForCounting(uniqueTypes);
                var classCount = PrepareSetForCounting(uniqueClasses);

                foreach (var ship in shipList)
                {
                    var sc = shipCount.FirstOrDefault(x => x.Name == ship.Name);
                    var tc = typeCount.FirstOrDefault(x => x.Name == ship.Type);
                    var cc = classCount.FirstOrDefault(x => x.Name == ship.Class);

                    sc.Count += 1;
                    tc.Count += 1;
                    cc.Count += 1;
                }

                var sortedSC = SortSet(shipCount);
                var sortedTC = SortSet(typeCount);
                var sortedCC = SortSet(classCount);

                var dscan = new TP_EveTools.Core.Domain.DScan
                {
                    id         = command.id,
                    SystemName = sysName,
                    Ships      = sortedSC,
                    Types      = sortedTC,
                    Classes    = sortedCC,
                };
                if (ctr != 0)
                {
                    dscan.InterestingTargets = interestingTargets;
                }

                await _dScanService.AddAsync(dscan);
            }
            else
            {
                var dscan = new TP_EveTools.Core.Domain.DScan
                {
                    id         = command.id,
                    SystemName = "Unknown"
                };
                await _dScanService.AddAsync(dscan);
            }
        }
Ejemplo n.º 28
0
        private void OnCorePreUpdate(EventArgs args)
        {
            try
            {
                if (Orbwalker.ActiveMode != Orbwalking.OrbwalkingMode.Combo &&
                    Orbwalker.ActiveMode != Orbwalking.OrbwalkingMode.Flee)
                {
                    var eBig = Menu.Item(Menu.Name + ".lasthit.e-big").GetValue<bool>();
                    var eTurret = Menu.Item(Menu.Name + ".lasthit.e-turret").GetValue<bool>();
                    var eReset = Menu.Item(Menu.Name + ".miscellaneous.e-reset").GetValue<bool>();

                    IEnumerable<Obj_AI_Minion> minions = new HashSet<Obj_AI_Minion>();
                    if (eBig || eTurret || eReset)
                    {
                        minions =
                            GameObjects.EnemyMinions.Where(e => e.IsValidTarget(E.Range) && Rend.IsKillable(e, true));
                    }

                    if (E.IsReady())
                    {
                        if (eBig)
                        {
                            var creeps =
                                GameObjects.Jungle.Where(e => e.IsValidTarget(E.Range) && Rend.IsKillable(e, false))
                                    .Concat(minions)
                                    .ToList();
                            if (
                                creeps.Any(
                                    m =>
                                        (m.CharData.BaseSkinName.Contains("MinionSiege") ||
                                         m.CharData.BaseSkinName.Contains("Super") ||
                                         m.CharData.BaseSkinName.StartsWith("SRU_Dragon") ||
                                         m.CharData.BaseSkinName.StartsWith("SRU_Baron"))))
                            {
                                E.Cast();
                                return;
                            }
                        }

                        if (eTurret && ManaManager.Check("lasthit"))
                        {
                            var minion =
                                minions.FirstOrDefault(
                                    m => Utils.UnderAllyTurret(m.Position) && Rend.IsKillable(m, false));
                            if (minion != null)
                            {
                                E.Cast();
                                return;
                            }
                        }
                    }

                    if (eReset && E.IsReady() && ManaManager.Check("misc") &&
                        GameObjects.EnemyHeroes.Any(e => Rend.HasBuff(e) && e.IsValidTarget(E.Range)))
                    {
                        if (minions.Any())
                        {
                            E.Cast();
                            return;
                        }
                    }
                }
                if (Menu.Item(Menu.Name + ".ultimate.save").GetValue<bool>() && SoulBound.Unit != null && R.IsReady() &&
                    !SoulBound.Unit.InFountain())
                {
                    SoulBound.Clean();
                    var enemies = SoulBound.Unit.CountEnemiesInRange(500);
                    if ((SoulBound.Unit.HealthPercent <= 10 && SoulBound.Unit.CountEnemiesInRange(500) > 0) ||
                        (SoulBound.Unit.HealthPercent <= 5 && SoulBound.TotalDamage > SoulBound.Unit.Health &&
                         enemies == 0) ||
                        (SoulBound.Unit.HealthPercent <= 50 && SoulBound.TotalDamage > SoulBound.Unit.Health &&
                         enemies > 0))
                    {
                        R.Cast();
                    }
                }
                if (Menu.Item(Menu.Name + ".miscellaneous.w-baron").GetValue<KeyBind>().Active && W.IsReady() &&
                    Player.Distance(SummonersRift.River.Baron) <= W.Range)
                {
                    W.Cast(SummonersRift.River.Baron);
                }
                if (Menu.Item(Menu.Name + ".miscellaneous.w-dragon").GetValue<KeyBind>().Active && W.IsReady() &&
                    Player.Distance(SummonersRift.River.Dragon) <= W.Range)
                {
                    W.Cast(SummonersRift.River.Dragon);
                }

                if (SoulBound.Unit == null)
                {
                    SoulBound.Unit =
                        GameObjects.AllyHeroes.FirstOrDefault(
                            a =>
                                a.Buffs.Any(
                                    b =>
                                        b.Caster.IsMe &&
                                        b.Name.Equals("kalistacoopstrikeally", StringComparison.OrdinalIgnoreCase)));
                }
                if (SoulBound.Unit != null && SoulBound.Unit.Distance(Player) < R.Range && R.IsReady())
                {
                    var blitz = Menu.Item(Menu.Name + ".ultimate.blitzcrank.r").GetValue<bool>();
                    var tahm = Menu.Item(Menu.Name + ".ultimate.tahm-kench.r").GetValue<bool>();
                    foreach (var enemy in
                        GameObjects.EnemyHeroes.Where(e => (blitz || tahm) && !e.IsDead && e.Distance(Player) < 3000))
                    {
                        if (blitz)
                        {
                            var blitzBuff =
                                enemy.Buffs.FirstOrDefault(
                                    b =>
                                        b.IsActive && b.Caster.NetworkId.Equals(SoulBound.Unit.NetworkId) &&
                                        b.Name.Equals("rocketgrab2", StringComparison.OrdinalIgnoreCase));
                            if (blitzBuff != null)
                            {
                                if (!HeroListManager.Check("blitzcrank", enemy))
                                {
                                    if (!SoulBound.Unit.UnderTurret(false) && SoulBound.Unit.Distance(enemy) > 750f &&
                                        SoulBound.Unit.Distance(Player) > R.Range / 3f)
                                    {
                                        R.Cast();
                                    }
                                }
                                return;
                            }
                        }
                        if (tahm)
                        {
                            var tahmBuff =
                                enemy.Buffs.FirstOrDefault(
                                    b =>
                                        b.IsActive && b.Caster.NetworkId.Equals(SoulBound.Unit.NetworkId) &&
                                        b.Name.Equals("tahmkenchwdevoured", StringComparison.OrdinalIgnoreCase));
                            if (tahmBuff != null)
                            {
                                if (!HeroListManager.Check("tahm-kench", enemy))
                                {
                                    if (!SoulBound.Unit.UnderTurret(false) &&
                                        (SoulBound.Unit.Distance(enemy) > Player.AttackRange ||
                                         GameObjects.AllyHeroes.Where(
                                             a =>
                                                 a.NetworkId != SoulBound.Unit.NetworkId &&
                                                 a.NetworkId != Player.NetworkId).Any(t => t.Distance(Player) > 600) ||
                                         GameObjects.AllyTurrets.Any(t => t.Distance(Player) < 600)))
                                    {
                                        R.Cast();
                                    }
                                }
                                return;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Global.Logger.AddItem(new LogItem(ex));
            }
        }
        internal void ProcessComplexModel(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext, ComplexModel complexModel) {
            HashSet<string> requiredProperties;
            HashSet<string> skipProperties;
            GetRequiredPropertiesCollection(bindingContext.ModelType, out requiredProperties, out skipProperties);

            // Are all of the required fields accounted for?
            HashSet<string> missingRequiredProperties = new HashSet<string>(requiredProperties);
            missingRequiredProperties.ExceptWith(complexModel.Results.Select(r => r.Key.PropertyName));
            string missingPropertyName = missingRequiredProperties.FirstOrDefault();
            if (missingPropertyName != null) {
                string fullPropertyKey = ModelBinderUtil.CreatePropertyModelName(bindingContext.ModelName, missingPropertyName);
                throw Error.BindingBehavior_ValueNotFound(fullPropertyKey);
            }

            // for each property that was bound, call the setter, recording exceptions as necessary
            foreach (var entry in complexModel.Results) {
                ModelMetadata propertyMetadata = entry.Key;

                ComplexModelResult complexModelResult = entry.Value;
                if (complexModelResult != null) {
                    SetProperty(modelBindingExecutionContext, bindingContext, propertyMetadata, complexModelResult);
                    bindingContext.ValidationNode.ChildNodes.Add(complexModelResult.ValidationNode);
                }
            }
        }
Ejemplo n.º 30
0
 internal static bool IsInTrustedHostList(string host)
 {
     return
         (!string.IsNullOrEmpty(
              TrustedHostList.FirstOrDefault(a => string.Compare(host, a, StringComparison.OrdinalIgnoreCase) == 0)));
 }
Ejemplo n.º 31
0
        private void AddLanguagesMenuItem(ContextMenuStrip menu, ListViewItem[] listViewItems)
        {
            // Only allow users to change the language on video tracks
            var tracks = listViewItems.Select(item => item.Tag as Track).ToArray();
            var isVideo = tracks.All(track => track.IsVideo);
            if (!isVideo)
                return;

            var selectedLanguages = new HashSet<Language>();
            foreach (var track2 in tracks)
            {
                selectedLanguages.Add(track2.Language);
            }
            var selectedLanguage = selectedLanguages.Count == 1 ? selectedLanguages.FirstOrDefault() : null;

            var languagesMenuItem = new ToolStripMenuItem("Language");
            foreach (var language in _allLanguages.OrderBy(language => language.Name))
            {
                var lang = language;
                var langMenuItem = new ToolStripMenuItem(language.Name);

                langMenuItem.Click += (s, e) => LanguageMenuItemOnClick(listViewItems, lang);

                if (language.Equals(selectedLanguage))
                {
                    langMenuItem.Checked = true;
                    langMenuItem.Enabled = false;
                }

                languagesMenuItem.DropDownItems.Add(langMenuItem);
            }

            menu.Items.Add(languagesMenuItem);
            menu.Items.Add("-");
        }
Ejemplo n.º 32
0
 public static IUserCategory Resolve(char code)
 {
     return(_categories.FirstOrDefault(x => x.Code.Equals(code)));
 }
 private PropertyGroup FindParentPropertyGroup(PropertyNode node)
 {
     return(_knownGroups.FirstOrDefault(x => x.Children.Contains(node)));
 }
Ejemplo n.º 34
0
 public void CorrectPointer(HashSet <AdvancedObject> objects)
 {
     Orbits     = objects.FirstOrDefault(o => o.Equals(Orbits));
     Satellites = Satellites.Select(o => objects.First(o.Equals)).ToHashSet();
 }
Ejemplo n.º 35
0
        public static FncFile Parse(string sourceFile)
        {
            var sourceText = File.ReadAllText(sourceFile);
            var boxes = new List<Box>();

            // Turn into array of characters
            var lines = (sourceText.Replace("\r", "") + "\n\n").Split('\n');
            var source = new SourceAsChars(lines);

            if (lines.Length == 0)
                return new FncFile { Boxes = boxes, Source = source };

            var visited = new Dictionary<int, HashSet<int>>();

            // Find boxes
            for (int y = 0; y < source.NumLines; y++)
            {
                for (int x = 0; x < source[y].Length; x++)
                {
                    // Go looking for a box only if this is a top-left corner of a box
                    if (source.TopLine(x, y) != LineType.None || source.LeftLine(x, y) != LineType.None || source.RightLine(x, y) == LineType.None || source.BottomLine(x, y) == LineType.None)
                        continue;

                    if (visited.Contains(x, y))
                        continue;

                    // Find width of box by walking along top edge
                    var top = source.RightLine(x, y);
                    var index = x + 1;
                    while (index < source[y].Length && source.RightLine(index, y) == top)
                        index++;
                    if (index == source[y].Length || source.BottomLine(index, y) == LineType.None || source.TopLine(index, y) != LineType.None || source.RightLine(index, y) != LineType.None)
                        continue;
                    var width = index - x;

                    // Find height of box by walking along left edge
                    var left = source.BottomLine(x, y);
                    index = y + 1;
                    while (index < source.NumLines && source.BottomLine(x, index) == left)
                        index++;
                    if (index == source.NumLines || source.RightLine(x, index) == LineType.None || source.LeftLine(x, index) != LineType.None || source.BottomLine(x, index) != LineType.None)
                        continue;
                    var height = index - y;

                    // Verify the bottom edge
                    var bottom = source.RightLine(x, y + height);
                    index = x + 1;
                    while (index < source[y].Length && source.RightLine(index, y + height) == bottom)
                        index++;
                    if (index == source[y].Length || source.TopLine(index, y + height) == LineType.None || source.BottomLine(index, y + height) != LineType.None || source.RightLine(index, y + height) != LineType.None)
                        continue;
                    if (index - x != width)
                        continue;

                    // Verify the right edge
                    var right = source.BottomLine(x + width, y);
                    index = y + 1;
                    while (index < source.NumLines && source.BottomLine(x + width, index) == right)
                        index++;
                    if (index == source.NumLines || source.LeftLine(x + width, index) == LineType.None || source.RightLine(x + width, index) != LineType.None || source.BottomLine(x + width, index) != LineType.None)
                        continue;
                    if (index - y != height)
                        continue;

                    // If all edges are single lines, this is not a box
                    if (top == LineType.Single && right == LineType.Single && bottom == LineType.Single && left == LineType.Single)
                        continue;

                    for (int xx = 0; xx <= width; xx++)
                    {
                        visited.AddSafe(x + xx, y);
                        visited.AddSafe(x + xx, y + height);
                    }
                    for (int yy = 0; yy <= height; yy++)
                    {
                        visited.AddSafe(x, y + yy);
                        visited.AddSafe(x + width, y + yy);
                    }

                    boxes.Add(new Box
                    {
                        X = x,
                        Y = y,
                        Width = width,
                        Height = height,
                        LineTypes = Helpers.MakeDictionary(top, right, bottom, left)
                    });
                }
            }

            // Determine the location of text lines within every box
            foreach (var box in boxes)
            {
                var curTextLines = new HashSet<TextLine>();
                for (int by = 1; by < box.Height; by++)
                {
                    var y = box.Y + by;
                    TextLine curTextLine = null;
                    var curLineText = new StringBuilder();
                    for (int bx = 1; bx < box.Width; bx++)
                    {
                        var x = box.X + bx;

                        if (source.AnyLine(x, y))
                        {
                            if (curTextLine != null)
                            {
                                curTextLine.Content = curLineText.ToString();
                                curTextLines.Add(curTextLine);
                                curTextLine = null;
                                curLineText.Clear();
                            }
                        }
                        else
                        {
                            if (curTextLine == null)
                                curTextLine = new TextLine { X = x, Y = y };
                            curLineText.Append(source[y][x]);
                        }
                    }
                    if (curTextLine != null)
                    {
                        curTextLine.Content = curLineText.ToString();
                        curTextLines.Add(curTextLine);
                    }
                }

                // Group text lines by vertical adjacency
                var textAreas = new List<TextLine[]>();
                while (curTextLines.Count > 0)
                {
                    var first = curTextLines.First();
                    curTextLines.Remove(first);
                    var curGroup = new List<TextLine> { first };
                    while (true)
                    {
                        var next = curTextLines.FirstOrDefault(one => curGroup.Any(two => (one.Y == two.Y + 1 || one.Y == two.Y - 1) && one.X + one.Content.Length > two.X && one.X < two.X + two.Content.Length));
                        if (next == null)
                            break;
                        curGroup.Add(next);
                        curTextLines.Remove(next);
                    }
                    curGroup.Sort(CustomComparer<TextLine>.By(l => l.Y).ThenBy(l => l.X));
                    textAreas.Add(curGroup.ToArray());
                }
                box.TextAreas = textAreas.ToArray();
            }

            return new FncFile { Boxes = boxes, Source = source };
        }
Ejemplo n.º 36
0
 public virtual UnturnedUser?GetUser(CSteamID id)
 {
     return(m_Users.FirstOrDefault(d => d.SteamId == id));
 }
		private void GridListCleanup()
		{
			if (DateTime.Now - _lastCleanup < TimeSpan.FromSeconds(120))
				return;

			_lastCleanup = DateTime.Now;

			HashSet<IMyEntity> entities = new HashSet<IMyEntity>();
			MyAPIGateway.Entities.GetEntities(entities);

			lock (GridDisabled)
			{
				int removed = GridDisabled.RemoveWhere(x => entities.FirstOrDefault(y => y.EntityId == x) == null);
				if(removed > 0)
					Log.Info(string.Format("Removed {0} entities from Disabled Grid List", removed));

				HashSet<long> removeSet = new HashSet<long>();
				foreach (KeyValuePair<long, HashSet<long>> p in GridBlocksDisabled)
				{
					if (entities.FirstOrDefault(x => x.EntityId == p.Key) == null)
						removeSet.Add(p.Key);
				}

				foreach (long item in removeSet)
					GridBlocksDisabled.Remove(item);
			}
		}
Ejemplo n.º 38
0
        /// <summary>
        /// Ensures that only approved component types are present in lighting scenes.
        /// </summary>
        /// <param name="scene"></param>
        private void EditorEnforceLightingSceneTypes(Scene scene)
        {
            if (EditorSceneManager.sceneCount == 1)
            {   // There's nowhere to move invalid objects to.
                return;
            }

            List <Component> violations = new List <Component>();

            if (EditorSceneUtils.EnforceSceneComponents(scene, profile.PermittedLightingSceneComponentTypes, violations))
            {
                Scene targetScene = default(Scene);
                for (int i = 0; i < EditorSceneManager.sceneCount; i++)
                {
                    targetScene = EditorSceneManager.GetSceneAt(i);
                    if (targetScene.path != scene.path)
                    {   // We'll move invalid items to this scene
                        break;
                    }
                }

                if (!targetScene.IsValid() || !targetScene.isLoaded)
                {   // Something's gone wrong - don't proceed
                    return;
                }

                HashSet <Transform> rootObjectsToMove = new HashSet <Transform>();
                foreach (Component component in violations)
                {
                    rootObjectsToMove.Add(component.transform.root);
                }

                List <string> rootObjectNames = new List <string>();
                // Build a list of root objects so they know what's being moved
                foreach (Transform rootObject in rootObjectsToMove)
                {
                    rootObjectNames.Add(rootObject.name);
                }

                EditorUtility.DisplayDialog(
                    "Invalid components found in " + scene.name,
                    "Only lighting-related componets are permitted. The following gameobjects will be moved to another scene:\n\n"
                    + String.Join("\n", rootObjectNames)
                    + "\n\nTo disable this warning, un-check 'EditorEnforceLightingSceneTypes' in your SceneSystem profile.", "OK");

                try
                {
                    foreach (Transform rootObject in rootObjectsToMove)
                    {
                        EditorSceneManager.MoveGameObjectToScene(rootObject.gameObject, targetScene);
                    }

                    EditorGUIUtility.PingObject(rootObjectsToMove.FirstOrDefault());
                }
                catch (Exception)
                {
                    // This can happen if the move object operation fails. No big deal, we'll try again next time.
                    return;
                }
            }
        }
Ejemplo n.º 39
0
        /// <summary>
        /// Returns only assemblies found in the bin folder that have been loaded into the app domain.
        /// </summary>
        /// <returns>
        /// The collection of assemblies.
        /// </returns>
        internal static HashSet<Assembly> GetBinAssemblies()
        {
            if (binFolderAssemblies == null)
            {
                using (new WriteLock(Locker))
                {
                    Assembly[] assemblies = GetAssembliesWithKnownExclusions().ToArray();
                    DirectoryInfo binFolder = Assembly.GetExecutingAssembly().GetAssemblyFile().Directory;
                    // ReSharper disable once PossibleNullReferenceException
                    List<string> binAssemblyFiles = Directory.GetFiles(binFolder.FullName, "*.dll", SearchOption.TopDirectoryOnly).ToList();
                    IEnumerable<AssemblyName> domainAssemblyNames = binAssemblyFiles.Select(AssemblyName.GetAssemblyName);
                    HashSet<Assembly> safeDomainAssemblies = new HashSet<Assembly>();
                    HashSet<Assembly> binFolderAssemblyList = new HashSet<Assembly>();

                    foreach (Assembly assembly in assemblies)
                    {
                        safeDomainAssemblies.Add(assembly);
                    }

                    foreach (AssemblyName assemblyName in domainAssemblyNames)
                    {
                        Assembly foundAssembly = safeDomainAssemblies
                                 .FirstOrDefault(a => a.GetAssemblyFile() == assemblyName.GetAssemblyFile());

                        if (foundAssembly != null)
                        {
                            binFolderAssemblyList.Add(foundAssembly);
                        }
                    }

                    binFolderAssemblies = new HashSet<Assembly>(binFolderAssemblyList);
                }
            }

            return binFolderAssemblies;
        }
Ejemplo n.º 40
0
        /// <summary>
        /// This method repeatedly takes a selected node in the combined graph and
        /// uses breadth-first search to find all other nodes in the same subgraph
        /// until all selected nodes have been processed.
        /// </summary>
        /// <param name="nodes">A cluster of nodes to be separated into subgraphs.</param>
        private void GenerateSeparateSubgraphs(HashSet<GraphLayout.Node> nodes)
        {
            int processed = 0;
            var combinedGraph = LayoutSubgraphs.First();
            GraphLayout.Graph graph = new GraphLayout.Graph();
            Queue<GraphLayout.Node> queue = new Queue<GraphLayout.Node>();

            while (nodes.Count(n => n.IsSelected) > 0)
            {
                GraphLayout.Node currentNode;

                if (queue.Count == 0)
                {
                    if (graph.Nodes.Count > 0)
                    {
                        // Save the subgraph and subtract these nodes from the combined graph

                        LayoutSubgraphs.Add(graph);
                        nodes.ExceptWith(graph.Nodes);
                        combinedGraph.Nodes.ExceptWith(graph.Nodes);
                        graph = new GraphLayout.Graph();
                    }
                    if (nodes.Count(n => n.IsSelected) == 0) break;

                    currentNode = nodes.FirstOrDefault(n => n.IsSelected);
                    graph.Nodes.Add(currentNode);
                }
                else
                {
                    currentNode = queue.Dequeue();
                }

                // Find all nodes in the selection which are connected directly
                // to the left or to the right to the currentNode

                var selectedNodes = currentNode.RightEdges.Select(e => e.EndNode)
                    .Union(currentNode.LeftEdges.Select(e => e.StartNode))
                    .Where(x => nodes.Contains(x) && x.IsSelected)
                    .Except(graph.Nodes).ToList();
                graph.Nodes.UnionWith(selectedNodes);
                graph.Edges.UnionWith(currentNode.RightEdges);
                graph.Edges.UnionWith(currentNode.LeftEdges);

                // If any of the incident edges are connected to unselected (outside) nodes
                // then mark these edges as anchors.

                graph.AnchorRightEdges.UnionWith(currentNode.RightEdges.Where(e => !e.EndNode.IsSelected));
                graph.AnchorLeftEdges.UnionWith(currentNode.LeftEdges.Where(e => !e.StartNode.IsSelected));

                foreach (var node in selectedNodes)
                {
                    queue.Enqueue(node);
                    processed++;
                }
            }
        }
Ejemplo n.º 41
0
        protected virtual ConstructorBindResult BindConstructor(ConstructorInfo cons, IList<EntityAssignment> assignments)
        {
            var ps = cons.GetParameters();
            var args = new Expression[ps.Length];
            var mis = new MemberInfo[ps.Length];
            HashSet<EntityAssignment> members = new HashSet<EntityAssignment>(assignments);
            HashSet<EntityAssignment> used = new HashSet<EntityAssignment>();

            for (int i = 0, n = ps.Length; i < n; i++)
            {
                ParameterInfo p = ps[i];
                var assignment = members.FirstOrDefault(a =>
                    p.Name == a.Member.Name
                    && p.ParameterType.IsAssignableFrom(a.Expression.Type));
                if (assignment == null)
                {
                    assignment = members.FirstOrDefault(a =>
                        string.Compare(p.Name, a.Member.Name, true) == 0
                        && p.ParameterType.IsAssignableFrom(a.Expression.Type));
                }
                if (assignment != null)
                {
                    args[i] = assignment.Expression;
                    if (mis != null)
                        mis[i] = assignment.Member;
                    used.Add(assignment);
                }
                else
                {
                    MemberInfo[] mems = cons.DeclaringType.GetMember(p.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase);
                    if (mems != null && mems.Length > 0)
                    {
                        args[i] = Expression.Constant(TypeHelper.GetDefault(p.ParameterType), p.ParameterType);
                        mis[i] = mems[0];
                    }
                    else
                    {
                        // unknown parameter, does not match any member
                        return null;
                    }
                }
            }

            members.ExceptWith(used);

            return new ConstructorBindResult(Expression.New(cons, args, mis), members);
        }
Ejemplo n.º 42
0
        public static void ValidateFrontDoor(this PSFrontDoor frontDoor, string resourceGroup, string subId)
        {
            //Create Resource ID for existing subresources.
            HashSet <string> routingRuleIds = new HashSet <string>();

            foreach (var routingRule in frontDoor.RoutingRules)
            {
                string id = string.Format("/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Network/frontDoors/{2}/RoutingRules/{3}",
                                          subId, resourceGroup, frontDoor.Name, routingRule.Name).ToLower();
                if (routingRuleIds.FirstOrDefault(x => x.Equals(id)) != null)
                {
                    throw new PSArgumentException(string.Format(
                                                      "Routingrule name need to be identical. {0}",
                                                      routingRule.Name
                                                      ));
                }
                routingRuleIds.Add(id);
            }

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

            foreach (var hpSetting in frontDoor.HealthProbeSettings)
            {
                string id = string.Format("/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Network/frontDoors/{2}/HealthProbeSettings/{3}",
                                          subId, resourceGroup, frontDoor.Name, hpSetting.Name).ToLower();
                if (healthProbeSettingIds.FirstOrDefault(x => x.Equals(id)) != null)
                {
                    throw new PSArgumentException(string.Format(
                                                      "HealthProbeSettings name need to be identical. {0}",
                                                      hpSetting.Name
                                                      ));
                }
                healthProbeSettingIds.Add(id);
            }

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

            foreach (var lbSetting in frontDoor.LoadBalancingSettings)
            {
                string id = string.Format("/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Network/frontDoors/{2}/LoadBalancingSettings/{3}",
                                          subId, resourceGroup, frontDoor.Name, lbSetting.Name).ToLower();
                if (loadBalancingSettingIds.FirstOrDefault(x => x.Equals(id)) != null)
                {
                    throw new PSArgumentException(string.Format(
                                                      "LoadBalancingSettings name need to be identical. {0}",
                                                      lbSetting.Name
                                                      ));
                }
                loadBalancingSettingIds.Add(id);
            }

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

            foreach (var frontendEndpoint in frontDoor.FrontendEndpoints)
            {
                string id = string.Format("/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Network/frontDoors/{2}/FrontendEndpoints/{3}",
                                          subId, resourceGroup, frontDoor.Name, frontendEndpoint.Name).ToLower();
                if (frontendEndpointIds.FirstOrDefault(x => x.Equals(id)) != null)
                {
                    throw new PSArgumentException(string.Format(
                                                      "FrontendEndpoint name need to be identical. {0}",
                                                      frontendEndpoint.Name
                                                      ));
                }
                frontendEndpointIds.Add(id.ToLower());
            }

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

            foreach (var backendPool in frontDoor.BackendPools)
            {
                string id = string.Format("/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Network/frontDoors/{2}/BackendPools/{3}",
                                          subId, resourceGroup, frontDoor.Name, backendPool.Name).ToLower();
                if (backendPoolIds.FirstOrDefault(x => x.Equals(id)) != null)
                {
                    throw new PSArgumentException(string.Format(
                                                      "BackendPool name need to be identical. {0}",
                                                      backendPool.Name
                                                      ));
                }
                backendPoolIds.Add(id.ToLower());
            }

            // Validate reference in each resources
            foreach (var routingRule in frontDoor.RoutingRules)
            {
                foreach (var id in routingRule.FrontendEndpointIds)
                {
                    if (frontendEndpointIds.FirstOrDefault(x => x.Equals(id.ToLower())) == null)
                    {
                        throw new PSArgumentException(string.Format(
                                                          "Invalid FrontendEndpointId {0} in {1}. Target doesn't exist",
                                                          id, routingRule.Name
                                                          ));
                    }
                }

                if (routingRule.RouteConfiguration is PSForwardingConfiguration)
                {
                    var forwardingConfiguration = routingRule.RouteConfiguration as PSForwardingConfiguration;
                    if (backendPoolIds.FirstOrDefault(x => x.Equals(forwardingConfiguration.BackendPoolId.ToLower())) == null)
                    {
                        throw new PSArgumentException(string.Format(
                                                          "Invalid BackendPollId {0} in {1}. Target doesn't exist",
                                                          forwardingConfiguration.BackendPoolId, routingRule.Name
                                                          ));
                    }
                }
            }

            foreach (var backendPool in frontDoor.BackendPools)
            {
                if (healthProbeSettingIds.FirstOrDefault(x => x.Equals(backendPool.HealthProbeSettingRef.ToLower())) == null)
                {
                    throw new PSArgumentException(string.Format(
                                                      "Invalid HealthProbeSetting {0} in {1}. Target doesn't exist",
                                                      backendPool.HealthProbeSettingRef, backendPool.Name
                                                      ));
                }

                if (loadBalancingSettingIds.FirstOrDefault(x => x.Equals(backendPool.LoadBalancingSettingRef.ToLower())) == null)
                {
                    throw new PSArgumentException(string.Format(
                                                      "Invalid HealthProbeSetting {0} in {1}. Target doesn't exist",
                                                      backendPool.LoadBalancingSettingRef, backendPool.Name
                                                      ));
                }
            }
        }
Ejemplo n.º 43
0
        /// <summary>
        /// Resolve a relationship stanza (a list of relationships).
        /// This will add modules to be installed, if required.
        /// May recurse back to Resolve for those new modules.
        ///
        /// If `soft_resolve` is true, we warn rather than throw exceptions on mods we cannot find.
        /// If `soft_resolve` is false (default), we throw a ModuleNotFoundKraken if we can't find a dependency.
        ///
        /// Throws a TooManyModsProvideKraken if we have too many choices and
        /// options.without_toomanyprovides_kraken is not set.
        ///
        /// See RelationshipResolverOptions for further adjustments that can be made.
        ///
        /// </summary>
        private void ResolveStanza(IEnumerable<RelationshipDescriptor> stanza, SelectionReason reason,
            RelationshipResolverOptions options, bool soft_resolve = false)
        {
            if (stanza == null)
            {
                return;
            }

            foreach (var descriptor in stanza)
            {
                string dep_name = descriptor.name;
                log.DebugFormat("Considering {0}", dep_name);

                // If we already have this dependency covered, skip.
                // If it's already installed, skip.

                if (modlist.ContainsKey(dep_name))
                {
                    if (descriptor.version_within_bounds(modlist[dep_name].version))
                        continue;
                    //TODO Ideally we could check here if it can be replaced by the version we want.
                    throw new InconsistentKraken(
                        string.Format(
                            "{0} requires a version {1}. However a incompatible version, {2}, is in the resolver",
                            dep_name, descriptor.RequiredVersion, modlist[dep_name].version));

                }

                if (registry.IsInstalled(dep_name))
                {
                    if(descriptor.version_within_bounds(registry.InstalledVersion(dep_name)))
                    continue;
                    //TODO Ideally we could check here if it can be replaced by the version we want.
                    throw new InconsistentKraken(
                        string.Format(
                            "{0} requires a version {1}. However a incompatible version, {2}, is already installed",
                            dep_name, descriptor.RequiredVersion, registry.InstalledVersion(dep_name)));
                }

                List<CkanModule> candidates = registry.LatestAvailableWithProvides(dep_name, kspversion, descriptor)
                    .Where(mod=>MightBeInstallable(mod)).ToList();

                if (candidates.Count == 0)
                {
                    if (!soft_resolve)
                    {
                        log.ErrorFormat("Dependency on {0} found, but nothing provides it.", dep_name);
                        throw new ModuleNotFoundKraken(dep_name);
                    }
                    log.InfoFormat("{0} is recommended/suggested, but nothing provides it.", dep_name);
                    continue;
                }
                if (candidates.Count > 1)
                {
                    // Oh no, too many to pick from!
                    // TODO: It would be great if instead we picked the one with the
                    // most recommendations.
                    if (options.without_toomanyprovides_kraken)
                    {
                        continue;
                    }

                    throw new TooManyModsProvideKraken(dep_name, candidates);
                }

                CkanModule candidate = candidates[0];

                // Finally, check our candidate against everything which might object
                // to it being installed; that's all the mods which are fixed in our
                // list thus far, as well as everything on the system.

                var fixed_mods = new HashSet<Module>(modlist.Values);
                fixed_mods.UnionWith(installed_modules);

                var conflicting_mod = fixed_mods.FirstOrDefault(mod => mod.ConflictsWith(candidate));
                if (conflicting_mod == null)
                {
                    // Okay, looks like we want this one. Adding.
                    Add(candidate, reason);
                    Resolve(candidate, options);
                }
                else if (soft_resolve)
                {
                    log.InfoFormat("{0} would cause conflicts, excluding it from consideration", candidate);
                }
                else
                {
                    if (options.procede_with_inconsistencies)
                    {
                        Add(candidate, reason);
                        conflicts.Add(new KeyValuePair<Module, Module>(conflicting_mod, candidate));
                        conflicts.Add(new KeyValuePair<Module, Module>(candidate, conflicting_mod));
                    }
                    else
                    {
                        throw new InconsistentKraken(string.Format("{0} conflicts with {1}, can't install both.", conflicting_mod,
                            candidate));
                    }
                }
            }
        }
Ejemplo n.º 44
0
        /// <summary>
        /// Get the module mixin based on the ShaderSource
        /// </summary>
        /// <param name="shaderSource">the ShaderSource</param>
        /// <returns>the ModuleMixin</returns>
        public ModuleMixin GetModuleMixinFromShaderSource(ShaderSource shaderSource)
        {
            var found = MixinInfos.FirstOrDefault(x => x.ShaderSource.Equals(shaderSource));

            return(found == null ? null : found.Mixin);
        }
Ejemplo n.º 45
0
   private void CopyIsExpanded(HashSet<HierarchyEntry> src,
 HashSet<HierarchyEntry> dest)
   {
       foreach (var entry in src)
         {
       HierarchyEntry newEntry = null;
       if ((newEntry = dest.FirstOrDefault(e => e.Transform == entry.Transform))
         != null)
       {
         newEntry.IsExpanded = entry.IsExpanded;
         CopyIsExpanded(entry.Children, newEntry.Children);
       }
         }
   }
Ejemplo n.º 46
0
        /// <summary>
        ///     Collapse a set of nodes in a given workspace.  Has the side effects of prompting the user
        ///     first in order to obtain the name and category for the new node, 
        ///     writes the function to a dyf file, adds it to the FunctionDict, adds it to search, and compiles and 
        ///     places the newly created symbol (defining a lambda) in the Controller's FScheme Environment.  
        /// </summary>
        /// <param name="selectedNodes"> The function definition for the user-defined node </param>
        /// <param name="currentWorkspace"> The workspace where</param>
        public static void Collapse(IEnumerable<NodeModel> selectedNodes, WorkspaceModel currentWorkspace, FunctionNamePromptEventArgs args=null)
        {
            var selectedNodeSet = new HashSet<NodeModel>(selectedNodes);

            if (args == null || !args.Success)
            {
                args = new FunctionNamePromptEventArgs();
                dynSettings.Controller.DynamoModel.OnRequestsFunctionNamePrompt(null, args);

                //if (!dynSettings.Controller.DynamoViewModel.ShowNewFunctionDialog(ref newNodeName, ref newNodeCategory))
                if (!args.Success)
                {
                    return;
                }
            }

            var newNodeWorkspace = new CustomNodeWorkspaceModel(args.Name, args.Category, args.Description, 0, 0)
            {
                WatchChanges = false,
                HasUnsavedChanges = true
            };

            var newNodeDefinition = new FunctionDefinition(Guid.NewGuid())
            {
                WorkspaceModel = newNodeWorkspace
            };

            currentWorkspace.DisableReporting();

            #region Determine Inputs and Outputs

            //Step 1: determine which nodes will be inputs to the new node
            var inputs = new HashSet<Tuple<NodeModel, int, Tuple<int, NodeModel>>>(
                selectedNodeSet.SelectMany(
                    node => Enumerable.Range(0, node.InPortData.Count).Where(node.HasConnectedInput)
                        .Select(data => Tuple.Create(node, data, node.Inputs[data]))
                        .Where(input => !selectedNodeSet.Contains(input.Item3.Item2))));

            var outputs = new HashSet<Tuple<NodeModel, int, Tuple<int, NodeModel>>>(
                selectedNodeSet.SelectMany(
                    node => Enumerable.Range(0, node.OutPortData.Count).Where(node.HasOutput).SelectMany(
                        data => node.Outputs[data]
                                    .Where(output => !selectedNodeSet.Contains(output.Item2))
                                    .Select(output => Tuple.Create(node, data, output)))));

            #endregion

            #region Detect 1-node holes (higher-order function extraction)

            var curriedNodeArgs =
                new HashSet<NodeModel>(
                    inputs
                        .Select(x => x.Item3.Item2)
                        .Intersect(outputs.Select(x => x.Item3.Item2)))
                    .Select(
                        outerNode =>
                        {
                            var node = new Apply1();

                            //MVVM : Don't make direct reference to view here
                            //MVVM: no reference to view here
                            //dynNodeView nodeUI = node.NodeUI;

                            var elNameAttrib =
                                node.GetType().GetCustomAttributes(typeof(NodeNameAttribute), true)[0] as
                                NodeNameAttribute;
                            if (elNameAttrib != null)
                            {
                                node.NickName = elNameAttrib.Name;
                            }

                            node.GUID = Guid.NewGuid();

                            //store the element in the elements list
                            newNodeWorkspace.Nodes.Add(node);
                            node.WorkSpace = newNodeWorkspace;

                            node.DisableReporting();

                            //MVVM : Can't set view location here

                            //dynSettings.Bench.WorkBench.Children.Add(nodeUI);

                            //Place it in an appropriate spot
                            //Canvas.SetLeft(nodeUI, Canvas.GetLeft(outerNode.NodeUI));
                            //Canvas.SetTop(nodeUI, Canvas.GetTop(outerNode.NodeUI));
                            node.X = outerNode.X;
                            node.Y = outerNode.Y;

                            //Fetch all input ports
                            // in order
                            // that have inputs
                            // and whose input comes from an inner node
                            List<int> inPortsConnected = Enumerable.Range(0, outerNode.InPortData.Count)
                                                                   .Where(
                                                                       x =>
                                                                       outerNode.HasInput(x) &&
                                                                       selectedNodeSet.Contains(
                                                                           outerNode.Inputs[x].Item2))
                                                                   .ToList();

                            var nodeInputs = outputs
                                .Where(output => output.Item3.Item2 == outerNode)
                                .Select(
                                    output =>
                                    new
                                    {
                                        InnerNodeInputSender = output.Item1,
                                        OuterNodeInPortData = output.Item3.Item1
                                    }).ToList();

                            nodeInputs.ForEach(_ => node.AddInput());

                            node.RegisterAllPorts();

                            return new
                            {
                                OuterNode = outerNode,
                                InnerNode = node,
                                Outputs = inputs.Where(input => input.Item3.Item2 == outerNode)
                                                .Select(input => input.Item3.Item1),
                                Inputs = nodeInputs,
                                OuterNodePortDataList = inPortsConnected
                            };
                        }).ToList();

            #endregion

            #region UI Positioning Calculations

            double avgX = selectedNodeSet.Average(node => node.X);
            double avgY = selectedNodeSet.Average(node => node.Y);

            double leftMost = selectedNodeSet.Min(node => node.X);
            double topMost = selectedNodeSet.Min(node => node.Y);
            double rightMost = selectedNodeSet.Max(node => node.X + node.Width);

            #endregion

            #region Move selection to new workspace

            var connectors = new HashSet<ConnectorModel>(currentWorkspace.Connectors.Where(
                                                                conn => selectedNodeSet.Contains(conn.Start.Owner)
                                                                    && selectedNodeSet.Contains(conn.End.Owner)));

            //Step 2: move all nodes to new workspace
            //  remove from old
            foreach (var ele in selectedNodeSet)
            {
                ele.SaveResult = false;
                currentWorkspace.Nodes.Remove(ele);
                ele.WorkSpace = newNodeWorkspace;
            }
            foreach (var ele in connectors)
            {
                currentWorkspace.Connectors.Remove(ele);
            }

            //  add to new
            newNodeWorkspace.Nodes.AddRange(selectedNodeSet);
            newNodeWorkspace.Connectors.AddRange(connectors);

            double leftShift = leftMost - 250;
            foreach (NodeModel node in newNodeWorkspace.Nodes)
            {
                node.X = node.X - leftShift;
                node.Y = node.Y - topMost;
            }

            #endregion

            #region Insert new node into the current workspace

            //Step 5: insert new node into original workspace
            //var collapsedNode = dynSettings.Controller.DynamoViewModel.CreateFunction(
            //    inputs.Select(x => x.Item1.InPortData[x.Item2].NickName),
            //    outputs
            //        .Where(x => !curriedNodeArgs.Any(y => y.OuterNode == x.Item3.Item2))
            //        .Select(x => x.Item1.OutPortData[x.Item2].NickName),
            //    newNodeDefinition);

            //collapsedNode.GUID = Guid.NewGuid();

            //currentWorkspace.Nodes.Add(collapsedNode);
            //collapsedNode.WorkSpace = currentWorkspace;

            //collapsedNode.X = avgX;
            //collapsedNode.Y = avgY;

            #endregion

            #region Destroy all hanging connectors

            //Step 6: connect inputs and outputs

            var removeConnectors = currentWorkspace.Connectors.Where(c =>
                                                                     selectedNodeSet.Contains(c.Start.Owner) ||
                                                                     selectedNodeSet.Contains(c.End.Owner))
                                                   .ToList();
            foreach (ConnectorModel connector in removeConnectors)
            {
                connector.NotifyConnectedPortsOfDeletion();
                currentWorkspace.Connectors.Remove(connector);
            }

            #endregion

            newNodeWorkspace.Nodes.ToList().ForEach(x => x.DisableReporting());

            var inConnectors = new List<Tuple<NodeModel, int, int>>();

            #region Process inputs

            var uniqueInputSenders = new Dictionary<Tuple<NodeModel, int>, Symbol>();

            //Step 3: insert variables (reference step 1)
            foreach (var input in Enumerable.Range(0, inputs.Count).Zip(inputs, Tuple.Create))
            {
                int inputIndex = input.Item1;

                NodeModel inputReceiverNode = input.Item2.Item1;
                int inputReceiverData = input.Item2.Item2;

                NodeModel inputNode = input.Item2.Item3.Item2;
                int inputData = input.Item2.Item3.Item1;

                Symbol node;

                var key = Tuple.Create(inputNode, inputData);
                if (uniqueInputSenders.ContainsKey(key))
                {
                    node = uniqueInputSenders[key];
                }
                else
                {
                    //MVVM : replace NodeUI reference with node
                    inConnectors.Add(Tuple.Create(inputNode, inputData, inputIndex));

                    //Create Symbol Node
                    node = new Symbol
                    {
                        InputSymbol = inputReceiverNode.InPortData[inputReceiverData].NickName
                    };

                    //MVVM : Don't make direct reference to view here
                    //dynNodeView nodeUI = node.NodeUI;

                    var elNameAttrib =
                        node.GetType().GetCustomAttributes(typeof(NodeNameAttribute), true)[0] as NodeNameAttribute;
                    if (elNameAttrib != null)
                    {
                        node.NickName = elNameAttrib.Name;
                    }

                    node.GUID = Guid.NewGuid();

                    //store the element in the elements list
                    newNodeWorkspace.Nodes.Add(node);
                    node.WorkSpace = newNodeWorkspace;

                    node.DisableReporting();

                    node.X = 0;
                    node.Y = inputIndex * (50 + node.Height);

                    uniqueInputSenders[key] = node;
                }

                var curriedNode = curriedNodeArgs.FirstOrDefault(x => x.OuterNode == inputNode);

                if (curriedNode == null)
                {
                    var conn1 = ConnectorModel.Make(node,
                                                  inputReceiverNode,
                                                  0,
                                                  inputReceiverData,
                                                  PortType.INPUT);

                    if (conn1 != null)
                        newNodeWorkspace.Connectors.Add(conn1);
                }
                else
                {
                    //Connect it to the applier
                    var conn = ConnectorModel.Make(node,
                                                     curriedNode.InnerNode,
                                                     0,
                                                     0,
                                                     PortType.INPUT);
                    if (conn != null)
                        newNodeWorkspace.Connectors.Add(conn);

                    //Connect applier to the inner input receive
                    var conn2 = ConnectorModel.Make(
                        curriedNode.InnerNode,
                        inputReceiverNode,
                        0,
                        inputReceiverData,
                        PortType.INPUT);

                    if (conn2 != null)
                        newNodeWorkspace.Connectors.Add(conn2);
                }
            }

            #endregion

            #region Process outputs

            //List of all inner nodes to connect an output. Unique.
            var outportList = new List<Tuple<NodeModel, int>>();

            var outConnectors = new List<Tuple<NodeModel, int, int>>();

            int i = 0;
            foreach (var output in outputs)
            {
                if (outportList.All(x => !(x.Item1 == output.Item1 && x.Item2 == output.Item2)))
                {
                    NodeModel outputSenderNode = output.Item1;
                    int outputSenderData = output.Item2;
                    NodeModel outputReceiverNode = output.Item3.Item2;

                    if (curriedNodeArgs.Any(x => x.OuterNode == outputReceiverNode))
                        continue;

                    outportList.Add(Tuple.Create(outputSenderNode, outputSenderData));

                    //Create Symbol Node
                    var node = new Output
                    {
                        Symbol = outputSenderNode.OutPortData[outputSenderData].NickName
                    };

                    //dynNodeView nodeUI = node.NodeUI;

                    var elNameAttrib =
                        node.GetType().GetCustomAttributes(typeof(NodeNameAttribute), false)[0] as NodeNameAttribute;
                    if (elNameAttrib != null)
                    {
                        node.NickName = elNameAttrib.Name;
                    }

                    node.GUID = Guid.NewGuid();

                    //store the element in the elements list
                    newNodeWorkspace.Nodes.Add(node);
                    node.WorkSpace = newNodeWorkspace;

                    node.DisableReporting();

                    node.X = rightMost + 75 - leftShift;
                    node.Y = i*(50 + node.Height);

                    var conn = ConnectorModel.Make(
                                outputSenderNode,
                                node,
                                outputSenderData,
                                0,
                                PortType.INPUT);

                    if (conn != null)
                        newNodeWorkspace.Connectors.Add(conn);

                    i++;
                }
            }

            //Connect outputs to new node
            foreach (var output in outputs)
            {
                //Node to be connected to in CurrentWorkspace
                NodeModel outputSenderNode = output.Item1;

                //Port to be connected to on outPutNode_outer
                int outputSenderData = output.Item2;

                int outputReceiverData = output.Item3.Item1;
                NodeModel outputReceiverNode = output.Item3.Item2;

                var curriedNode = curriedNodeArgs.FirstOrDefault(
                    x => x.OuterNode == outputReceiverNode);

                if (curriedNode == null)
                {
                    // we create the connectors in the current space later
            //MVVM : replaced multiple dynNodeView refrences with dynNode
                    outConnectors.Add(
                        Tuple.Create(
                            outputReceiverNode,
                            outportList.FindIndex(
                                x => x.Item1 == outputSenderNode && x.Item2 == outputSenderData),
                            outputReceiverData));
                }
                else
                {
                    int targetPort = curriedNode.Inputs
                                                .First(
                                                    x => x.InnerNodeInputSender == outputSenderNode)
                                                .OuterNodeInPortData;

                    int targetPortIndex = curriedNode.OuterNodePortDataList.IndexOf(targetPort);

                    //Connect it (new dynConnector)

                    var conn = ConnectorModel.Make(
                        outputSenderNode,
                        curriedNode.InnerNode,
                        outputSenderData,
                        targetPortIndex + 1,
                        PortType.INPUT);

                    if (conn != null)
                        newNodeWorkspace.Connectors.Add(conn);
                }
            }

            #endregion

            // save and load the definition from file
            newNodeDefinition.SyncWithWorkspace(true, true);
            dynSettings.Controller.DynamoModel.Workspaces.Add(newNodeWorkspace);

            string name = newNodeDefinition.FunctionId.ToString();
            var collapsedNode = dynSettings.Controller.DynamoModel.CreateNode(avgX, avgY, name);

            // place the node as intended, not centered
            collapsedNode.X = avgX;
            collapsedNode.Y = avgY;

            collapsedNode.DisableReporting();

            foreach (var nodeTuple in inConnectors)
            {
                var conn = ConnectorModel.Make(
                                    nodeTuple.Item1,
                                    collapsedNode,
                                    nodeTuple.Item2,
                                    nodeTuple.Item3,
                                    PortType.INPUT);

                if (conn != null)
                    currentWorkspace.Connectors.Add(conn);
            }

            foreach (var nodeTuple in outConnectors)
            {

                var conn = ConnectorModel.Make(
                                    collapsedNode,
                                    nodeTuple.Item1,
                                    nodeTuple.Item2,
                                    nodeTuple.Item3,
                                    PortType.INPUT);

                if (conn != null)
                    currentWorkspace.Connectors.Add(conn);
            }

            collapsedNode.EnableReporting();
            currentWorkspace.EnableReporting();

            newNodeWorkspace.WatchChanges = true;
        }
Ejemplo n.º 47
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;
        }
Ejemplo n.º 48
0
        //metoda - wywołanie algorytmu KPP
        public void KPP(int nadawca, int[] odbiorcy, int ile_PC, siec[] graf, int n, int delta)
        {
            int licz = (ile_PC * (ile_PC - 1)) / 2, sc = 0;
            double koszt, opuzn;
            siec[] lista_sciezek = new siec[licz];
            siec pomoc = new siec();
            siec nowy2;
            odbiorcy[0] = nadawca;

            ///////////////////////////////////////// Krok 1 ////////////////////////////////////////////////
            #region
            /////////////////konstrukcja spujnego nieskierowanego grafu N' //////////////////////////
            ///skladajacego sie z wszystkich odbiorcow i nadawcowi sciezek o najnizszym koszczie////

            for (int i = 0; i < ile_PC; i++)
            {
                for (int j = i + 1; j < ile_PC; j++)
                {
                    lista_sciezek[sc] = pomoc.sciezka(odbiorcy[i], odbiorcy[j], n, graf,"cost");		//obliczam sciezki
                    sc++;
                }
            }

            /////////////////////////rozwijam graf do grafu pełnego nieskierowanego//////////////////
            int b = 0, c = 0;
            siec[] graf_kpp = new siec[n];
            for (int i = 0; i < n; i++)
                graf_kpp[i] = null;

            for (int i = 0; i < licz; i++)
            {
                pomoc = lista_sciezek[i];

                b = pomoc.to;
                koszt = 0;
                opuzn = 0;

                while (pomoc != null)
                {
                    koszt = koszt + pomoc.cost;
                    opuzn = opuzn + pomoc.delay;

                    if (pomoc.next == null) c = pomoc.from;
                    pomoc = pomoc.next;

                }

                siec nowy1 = new siec(koszt, opuzn, c, b, i, graf_kpp[b]);
                graf_kpp[b] = nowy1;
            }
            ///////////////////////////////////////////KROK 1 koniec/////////////////////////////////////////
            #endregion

            ////////////////////////////////////////// KROK 2 //////////////////////////////////////////////
            #region
            //////////////////////obliczenie minimalnego drzewa spinajacego z grafu kpp
            //////////////////////metryka jest delay

            bool[] vis = new bool [n] ;	     //wierzcholek odwiedzony
            double[] waga = new double[n];  //delay polaczenia
            double[] waga_k = new double[n];      //koszt

            HashSet<siec>kopiec = new HashSet<siec>();
            //Dictionary<siec, siec> kopiec = new Dictionary<siec,siec>(n);

            for(int i=0; i<n; i++)
                {
                 waga_k[i]=0;
                 waga[i]= 0;				//inicjowanie tablic
                 vis[i]= false;
                }

            int v = 0;
            double waga_mst = 0;

            siec[] mst = new siec[n];

            for (int i = 0; i < n; i++)
                 mst[i] = null;

            vis[0] = true;				//wierzcholek startowy (nadawca)
            waga[odbiorcy[0]] = 0;
            waga_k[odbiorcy[0]] = 0;

            kopiec.Clear();

            for (pomoc = graf_kpp[odbiorcy[0]]; pomoc != null; pomoc = pomoc.next) //dodanie nie odwiedzonych sasiadow do kopca
            {
                nowy2 = new siec(pomoc);
                kopiec.Add(nowy2);
            }

            while (kopiec.Count >0) //glowna petla mst
            {

                pomoc = kopiec.FirstOrDefault().ja;

                if (vis[pomoc.to]==false)
                {
                    if (waga[pomoc.to] + pomoc.delay < delta)
                    {
                        vis[pomoc.to] = true;				//dodaje nowa krawedz do drzewa
                        waga[pomoc.to] = pomoc.delay;
                        waga_k[pomoc.to] = waga_k[pomoc.to] + pomoc.cost;

                        //nowy2 = new wezel(pomoc->koszt, pomoc->delay, pomoc->pi, pomoc->v, pomoc->id, mst[pomoc->v] );
                        //mst[pomoc->v]=nowy2;
                        nowy2 = new siec(pomoc.cost, pomoc.delay, pomoc.to, pomoc.from, pomoc.id, mst[pomoc.from]);
                        mst[pomoc.from] = nowy2;
                        v = pomoc.to;
                    }//else
                    //{
                    //kopiec.erase(kopiec.begin()); //usowam 1 element kopca
                    // warunek = false;
                    //}
                }

                //if(warunek){

                kopiec.Remove(kopiec.FirstOrDefault());
                //kopiec.erase(kopiec.begin()); //usowam 1 element kopca
                for (pomoc = graf_kpp[v]; pomoc != null; pomoc = pomoc.next)	//dodaje nie odwiedzonych sasiadow do kopca
                {
                    if (vis[pomoc.to]==false)
                    {
                        nowy2 = new siec(pomoc);

                        kopiec.Add(nowy2);
                    }
                }
                //}
                //warunek=true;
            }
            ///////////////////////////////////////////KROK 2 KONIEC///////////////////////////////////////////////////////
            #endregion

            ////////////////////////////////////////// KROK 3 //////////////////////////////////////////////
            #region
            ///////////////Zastąp krawędzie powstałego drzewa oryginalnymi z grafu z modelem sieci/////////////////////////
            bool [][] kontrolka = new bool[n][];
            for (int i = 0; i < n; i++)
            {
                kontrolka[i] = new bool[n];
            }

            //zerowanie kontrolki
            for(int f=0; f<n; f++)
                {
                    for(int h=0; h<n; h++)
                    {
                        kontrolka[f][h]=false;
                    }
                }

            siec pomoc2=new siec();
            siec[] mst2 = new siec[n];
            int iterator;

            for(int i=0; i<n; i++)
            {
                mst2[i]= null;
            }

            for (int i = 0; i < n; i++)	//odtwarzam pierwotne mst
            {
                for (pomoc = mst[i]; pomoc != null; pomoc = pomoc.next)	//dla kazdego graf_mst
                {
                    iterator = 0;
                    b = pomoc.from;
                    c = -1;

                    while (lista_sciezek[iterator].to != b || pomoc.to != c)
                    {
                        if (lista_sciezek[iterator].to != b)
                        {
                            iterator++;
                        }
                        else
                        {
                            for (pomoc2 = lista_sciezek[iterator]; pomoc2 != null; pomoc2 = pomoc2.next)	//wyszukiwanie krawedzi w liscie sciezek
                            {
                                if (pomoc2.next == null && pomoc2.from == pomoc.to) c = pomoc2.from;

                            }
                            if (c == -1)
                            {
                                iterator++;
                            }
                        }
                    }

                    for (pomoc2 = lista_sciezek[iterator]; pomoc2 != null; pomoc2 = pomoc2.next)
                    {
                        if (kontrolka[pomoc2.from][pomoc2.to] != true && kontrolka[pomoc2.to][pomoc2.from] != true)
                        {

                            nowy2 = new siec(pomoc2.cost, pomoc2.delay, pomoc2.from, pomoc2.to, pomoc2.id, mst2[pomoc2.to]); //tworzenie nowej krawedzi
                            mst2[pomoc2.to] = nowy2;
                            nowy2 = new siec(pomoc2.cost, pomoc2.delay, pomoc2.to, pomoc2.from, pomoc2.id, mst2[pomoc2.from]);
                            mst2[pomoc2.from] = nowy2;
                            kontrolka[pomoc2.to][pomoc2.from] = true;
                            kontrolka[pomoc2.from][pomoc2.to] = true;

                        }
                    }

                }
            }
            //////////////////////////////////////////////////KROK 3 KONIEC//////////////////////////////////////////////////////////////
            #endregion

            ///////////////////////////////////Zapis wyniku do pliku////////////////////////////////////////
            #region
            double delay_mst = 0;
            System.IO.StreamWriter plik = new System.IO.StreamWriter(@"KPP.txt");

            for (int f = 0; f < n; f++)
                { //zerowanie kontrolki
                    for (int h = 0; h < n; h++)
                        {
                            kontrolka[f][h] = false;
                        }
                }

            for (int i = 0; i < n; i++) //wyswietla Lsonsiadow graf_kpp
                {
                    pomoc = mst2[i];
                    if (pomoc!=null)
                        {
                        while (pomoc !=null)
                            {
                                if (kontrolka[pomoc.from][pomoc.to] != true && kontrolka[pomoc.to][pomoc.from] != true)
                                    {
                                    waga_mst = waga_mst + pomoc.cost;
                                    delay_mst = delay_mst + pomoc.delay;
                                    kontrolka[pomoc.to][pomoc.from] = true;
                                    kontrolka[pomoc.from][pomoc.to] = true;
                                    }
                               pomoc = pomoc.next;
                            }
                    }
                }

            Debug.Write("\n");
            Debug.Write("Koszt drzewa multicast wynosi = ");
            Debug.Write(waga_mst);
            Debug.Write("\n");
            Debug.Write("\n");

            Debug.Write("\n");
            Debug.Write("DRZEWO MULTICAST ");
            Debug.Write("\n");
            Debug.Write("\n");
            plik.WriteLine("\n" + "delta = " + delta+ "\n");
            plik.WriteLine( "\n" + "Koszt drzewa multicast wynosi = "+waga_mst + "\n");
            plik.WriteLine("\n" + "Nadawca = " + odbiorcy[0] + "\n");
            plik.Write("Odbiorcy = ");
            for (int i = 1; i < odbiorcy.Count(); i++)
            {
                plik.Write(odbiorcy[i] + ", ");
            }
            plik.WriteLine("");
            plik.WriteLine("");
            plik.WriteLine("\n" + "DRZEWO MULTICAST " + "\n");

            for (int i = 0; i < n; i++) //wyswietla Lsonsiadow graf_kpp
                {
                    pomoc = mst2[i];
                    if (pomoc!=null)
                        {
                        Debug.Write("DTM[");
                        Debug.Write(i);
                        Debug.Write("] =");

                        plik.Write("DTM[" + i + "] ->");

                        while (pomoc!=null)
                            {
                                Debug.Write(" "+ pomoc.to+" ");
                                plik.Write(" "+pomoc.to+" ");

                                pomoc = pomoc.next;
                            }

                        Debug.Write( "\n");
                        plik.WriteLine("");
                        }
                }

            Debug.Write("\n");

            plik.Close();
            #endregion
            MessageBox.Show("Koszt drzewa transmisji grupowej wynosi:  " + Convert.ToString(waga_mst) + "  \n " + Convert.ToString(delay_mst));
        }
Ejemplo n.º 49
0
        private void OnCorePreUpdate(EventArgs args)
        {
            try
            {
                if (Orbwalker.ActiveMode != Orbwalking.OrbwalkingMode.Combo &&
                    Orbwalker.ActiveMode != Orbwalking.OrbwalkingMode.Flee)
                {
                    var eBig = Menu.Item(Menu.Name + ".lasthit.e-big").GetValue<bool>();
                    var eTurret = Menu.Item(Menu.Name + ".lasthit.e-turret").GetValue<bool>();
                    var eReset = Menu.Item(Menu.Name + ".miscellaneous.e-reset").GetValue<bool>();

                    IEnumerable<Obj_AI_Minion> minions = new HashSet<Obj_AI_Minion>();
                    if (eBig || eTurret || eReset)
                    {
                        minions =
                            GameObjects.EnemyMinions.Where(e => e.IsValidTarget(E.Range) && Rend.IsKillable(e, true));
                    }

                    if (E.IsReady())
                    {
                        if (eBig)
                        {
                            var creeps =
                                GameObjects.Jungle.Where(e => e.IsValidTarget(E.Range) && Rend.IsKillable(e, false))
                                    .Concat(minions)
                                    .ToList();
                            if (
                                creeps.Any(
                                    m =>
                                        (m.CharData.BaseSkinName.Contains("MinionSiege") ||
                                         m.CharData.BaseSkinName.Contains("Super") ||
                                         m.CharData.BaseSkinName.StartsWith("SRU_Dragon") ||
                                         m.CharData.BaseSkinName.StartsWith("SRU_Baron"))))
                            {
                                E.Cast();
                                return;
                            }
                        }

                        if (eTurret && ManaManager.Check("lasthit"))
                        {
                            var minion = minions.FirstOrDefault(m => Utils.UnderAllyTurret(m.Position));
                            if (minion != null)
                            {
                                E.Cast();
                                return;
                            }
                        }
                    }

                    if (eReset && E.IsReady() && ManaManager.Check("misc") &&
                        GameObjects.EnemyHeroes.Any(e => Rend.HasBuff(e) && e.IsValidTarget(E.Range)))
                    {
                        if (minions.Any())
                        {
                            E.Cast();
                            return;
                        }
                    }
                }
                if (Menu.Item(Menu.Name + ".ultimate.save").GetValue<bool>() && SoulBound.Unit != null && R.IsReady())
                {
                    SoulBound.Clean();
                    if (SoulBound.Unit.HealthPercent <= 10 && SoulBound.Unit.CountEnemiesInRange(500) > 0 ||
                        (SoulBound.Unit.HealthPercent <= 45 && SoulBound.TotalDamage * 1.1f > SoulBound.Unit.Health))
                    {
                        R.Cast();
                    }
                }
                if (Menu.Item(Menu.Name + ".miscellaneous.w-baron").GetValue<KeyBind>().Active && W.IsReady() &&
                    Player.Distance(SummonersRift.River.Baron) <= W.Range)
                {
                    W.Cast(SummonersRift.River.Baron);
                }
                if (Menu.Item(Menu.Name + ".miscellaneous.w-dragon").GetValue<KeyBind>().Active && W.IsReady() &&
                    Player.Distance(SummonersRift.River.Dragon) <= W.Range)
                {
                    W.Cast(SummonersRift.River.Dragon);
                }
            }
            catch (Exception ex)
            {
                Global.Logger.AddItem(new LogItem(ex));
            }
        }
Ejemplo n.º 50
0
        /// <summary>
        ///     Collapse a set of nodes in a given workspace.
        /// </summary>
        /// <param name="dynamoModel">The current DynamoModel</param>
        /// <param name="selectedNodes"> The function definition for the user-defined node </param>
        /// <param name="currentWorkspace"> The workspace where</param>
        /// <param name="args"></param>
        public static void Collapse(DynamoModel dynamoModel, IEnumerable<NodeModel> selectedNodes, WorkspaceModel currentWorkspace, FunctionNamePromptEventArgs args = null)
        {
            var selectedNodeSet = new HashSet<NodeModel>(selectedNodes);

            if (args == null || !args.Success)
            {
                args = new FunctionNamePromptEventArgs();
                dynamoModel.OnRequestsFunctionNamePrompt(null, args);

                
                if (!args.Success)
                {
                    return;
                }
            }

            // Note that undoable actions are only recorded for the "currentWorkspace", 
            // the nodes which get moved into "newNodeWorkspace" are not recorded for undo,
            // even in the new workspace. Their creations will simply be treated as part of
            // the opening of that new workspace (i.e. when a user opens a file, she will 
            // not expect the nodes that show up to be undoable).
            // 
            // After local nodes are moved into "newNodeWorkspace" as the result of 
            // conversion, if user performs an undo, new set of nodes will be created in 
            // "currentWorkspace" (not moving those nodes in the "newNodeWorkspace" back 
            // into "currentWorkspace"). In another word, undo recording is on a per-
            // workspace basis, it does not work across different workspaces.
            // 
            UndoRedoRecorder undoRecorder = currentWorkspace.UndoRecorder;
            using (undoRecorder.BeginActionGroup())
            {

                var newNodeWorkspace = new CustomNodeWorkspaceModel(
                    dynamoModel,
                    args.Name,
                    args.Category,
                    args.Description,
                    0,
                    0) { WatchChanges = false, HasUnsavedChanges = true };

                var newNodeDefinition = new CustomNodeDefinition(Guid.NewGuid())
                {
                    WorkspaceModel = newNodeWorkspace
                };

                currentWorkspace.DisableReporting();

                #region Determine Inputs and Outputs

                //Step 1: determine which nodes will be inputs to the new node
                var inputs =
                    new HashSet<Tuple<NodeModel, int, Tuple<int, NodeModel>>>(
                        selectedNodeSet.SelectMany(
                            node =>
                                Enumerable.Range(0, node.InPortData.Count)
                                .Where(node.HasConnectedInput)
                                .Select(data => Tuple.Create(node, data, node.Inputs[data]))
                                .Where(input => !selectedNodeSet.Contains(input.Item3.Item2))));

                var outputs =
                    new HashSet<Tuple<NodeModel, int, Tuple<int, NodeModel>>>(
                        selectedNodeSet.SelectMany(
                            node =>
                                Enumerable.Range(0, node.OutPortData.Count)
                                .Where(node.HasOutput)
                                .SelectMany(
                                    data =>
                                        node.Outputs[data].Where(
                                            output => !selectedNodeSet.Contains(output.Item2))
                                        .Select(output => Tuple.Create(node, data, output)))));

                #endregion

                #region Detect 1-node holes (higher-order function extraction)

                var curriedNodeArgs =
                    new HashSet<NodeModel>(
                        inputs.Select(x => x.Item3.Item2)
                            .Intersect(outputs.Select(x => x.Item3.Item2))).Select(
                                outerNode =>
                                {
                                    //var node = new Apply1();
                                    var node = newNodeWorkspace.AddNode<Apply1>();
                                    node.SetNickNameFromAttribute();

                                    node.DisableReporting();

                                    node.X = outerNode.X;
                                    node.Y = outerNode.Y;

                                    //Fetch all input ports
                                    // in order
                                    // that have inputs
                                    // and whose input comes from an inner node
                                    List<int> inPortsConnected =
                                        Enumerable.Range(0, outerNode.InPortData.Count)
                                            .Where(
                                                x =>
                                                    outerNode.HasInput(x)
                                                        && selectedNodeSet.Contains(
                                                            outerNode.Inputs[x].Item2))
                                            .ToList();

                                    var nodeInputs =
                                        outputs.Where(output => output.Item3.Item2 == outerNode)
                                            .Select(
                                                output =>
                                                    new
                                                    {
                                                        InnerNodeInputSender = output.Item1,
                                                        OuterNodeInPortData = output.Item3.Item1
                                                    })
                                            .ToList();

                                    nodeInputs.ForEach(_ => node.AddInput());

                                    node.RegisterAllPorts();

                                    return
                                        new
                                        {
                                            OuterNode = outerNode,
                                            InnerNode = node,
                                            Outputs =
                                                inputs.Where(
                                                    input => input.Item3.Item2 == outerNode)
                                                    .Select(input => input.Item3.Item1),
                                            Inputs = nodeInputs,
                                            OuterNodePortDataList = inPortsConnected
                                        };
                                }).ToList();

                #endregion

                #region UI Positioning Calculations

                double avgX = selectedNodeSet.Average(node => node.X);
                double avgY = selectedNodeSet.Average(node => node.Y);

                double leftMost = selectedNodeSet.Min(node => node.X);
                double topMost = selectedNodeSet.Min(node => node.Y);
                double rightMost = selectedNodeSet.Max(node => node.X + node.Width);

                #endregion

                #region Handle full selected connectors

                // Step 2: Determine all the connectors whose start/end owners are 
                // both in the selection set, and then move them from the current 
                // workspace into the new workspace.

                var fullySelectedConns =
                    new HashSet<ConnectorModel>(
                        currentWorkspace.Connectors.Where(
                            conn =>
                            {
                                bool startSelected = selectedNodeSet.Contains(conn.Start.Owner);
                                bool endSelected = selectedNodeSet.Contains(conn.End.Owner);
                                return startSelected && endSelected;
                            }));

                foreach (var ele in fullySelectedConns)
                {
                    undoRecorder.RecordDeletionForUndo(ele);
                    currentWorkspace.Connectors.Remove(ele);
                }

                #endregion

                #region Handle partially selected connectors

                // Step 3: Partially selected connectors (either one of its start 
                // and end owners is in the selection) are to be destroyed.

                var partiallySelectedConns =
                    currentWorkspace.Connectors.Where(
                        conn =>
                            selectedNodeSet.Contains(conn.Start.Owner)
                                || selectedNodeSet.Contains(conn.End.Owner)).ToList();

                foreach (ConnectorModel connector in partiallySelectedConns)
                {
                    undoRecorder.RecordDeletionForUndo(connector);
                    connector.NotifyConnectedPortsOfDeletion();
                    currentWorkspace.Connectors.Remove(connector);
                }

                #endregion

                #region Transfer nodes and connectors to new workspace

                // Step 4: move all nodes to new workspace remove from old
                // PB: This could be more efficiently handled by a copy paste, but we
                // are preservering the node 
                foreach (var ele in selectedNodeSet)
                {
                    undoRecorder.RecordDeletionForUndo(ele);
                    ele.SaveResult = false;
                    currentWorkspace.Nodes.Remove(ele);
                    ele.Workspace = newNodeWorkspace;
                }

                //  add to new
                newNodeWorkspace.Nodes.AddRange(selectedNodeSet);
                newNodeWorkspace.Connectors.AddRange(fullySelectedConns);

                foreach (var node in newNodeWorkspace.Nodes)
                    node.DisableReporting();

                double leftShift = leftMost - 250;
                foreach (NodeModel node in newNodeWorkspace.Nodes)
                {
                    node.X = node.X - leftShift;
                    node.Y = node.Y - topMost;
                }

                #endregion


                #region Process inputs

                var inConnectors = new List<Tuple<NodeModel, int>>();
                var uniqueInputSenders = new Dictionary<Tuple<NodeModel, int>, Symbol>();

                //Step 3: insert variables (reference step 1)
                foreach (var input in Enumerable.Range(0, inputs.Count).Zip(inputs, Tuple.Create))
                {
                    int inputIndex = input.Item1;

                    NodeModel inputReceiverNode = input.Item2.Item1;
                    int inputReceiverData = input.Item2.Item2;

                    NodeModel inputNode = input.Item2.Item3.Item2;
                    int inputData = input.Item2.Item3.Item1;

                    Symbol node;

                    var key = Tuple.Create(inputNode, inputData);
                    if (uniqueInputSenders.ContainsKey(key))
                    {
                        node = uniqueInputSenders[key];
                    }
                    else
                    {
                        inConnectors.Add(Tuple.Create(inputNode, inputData));

                        node = newNodeWorkspace.AddNode<Symbol>();
                        node.InputSymbol = inputReceiverNode.InPortData[inputReceiverData].NickName;

                        node.SetNickNameFromAttribute();

                        node.DisableReporting();

                        node.X = 0;
                        node.Y = inputIndex*(50 + node.Height);

                        uniqueInputSenders[key] = node;
                    }

                    var curriedNode = curriedNodeArgs.FirstOrDefault(x => x.OuterNode == inputNode);

                    if (curriedNode == null)
                    {
                        newNodeWorkspace.AddConnection(
                            node,
                            inputReceiverNode,
                            0,
                            inputReceiverData);
                    }
                    else
                    {
                        //Connect it to the applier
                        newNodeWorkspace.AddConnection(node, curriedNode.InnerNode, 0, 0);

                        //Connect applier to the inner input receive
                        newNodeWorkspace.AddConnection(
                            curriedNode.InnerNode,
                            inputReceiverNode,
                            0,
                            inputReceiverData);
                    }
                }

                #endregion

                #region Process outputs

                //List of all inner nodes to connect an output. Unique.
                var outportList = new List<Tuple<NodeModel, int>>();

                var outConnectors = new List<Tuple<NodeModel, int, int>>();

                int i = 0;
                if (outputs.Any())
                {
                    foreach (var output in outputs)
                    {
                        if (
                            outportList.All(
                                x => !(x.Item1 == output.Item1 && x.Item2 == output.Item2)))
                        {
                            NodeModel outputSenderNode = output.Item1;
                            int outputSenderData = output.Item2;
                            NodeModel outputReceiverNode = output.Item3.Item2;

                            if (curriedNodeArgs.Any(x => x.OuterNode == outputReceiverNode))
                                continue;

                            outportList.Add(Tuple.Create(outputSenderNode, outputSenderData));

                            //Create Symbol Node
                            var node = newNodeWorkspace.AddNode<Output>();
                            node.Symbol = outputSenderNode.OutPortData[outputSenderData].NickName;

                            node.SetNickNameFromAttribute();
                            node.DisableReporting();

                            node.X = rightMost + 75 - leftShift;
                            node.Y = i*(50 + node.Height);

                            newNodeWorkspace.AddConnection(
                                outputSenderNode,
                                node,
                                outputSenderData,
                                0);

                            i++;
                        }
                    }

                    //Connect outputs to new node
                    foreach (var output in outputs)
                    {
                        //Node to be connected to in CurrentWorkspace
                        NodeModel outputSenderNode = output.Item1;

                        //Port to be connected to on outPutNode_outer
                        int outputSenderData = output.Item2;

                        int outputReceiverData = output.Item3.Item1;
                        NodeModel outputReceiverNode = output.Item3.Item2;

                        var curriedNode =
                            curriedNodeArgs.FirstOrDefault(x => x.OuterNode == outputReceiverNode);

                        if (curriedNode == null)
                        {
                            // we create the connectors in the current space later
                            outConnectors.Add(
                                Tuple.Create(
                                    outputReceiverNode,
                                    outportList.FindIndex(
                                        x =>
                                            x.Item1 == outputSenderNode
                                                && x.Item2 == outputSenderData),
                                    outputReceiverData));
                        }
                        else
                        {
                            int targetPort =
                                curriedNode.Inputs.First(
                                    x => x.InnerNodeInputSender == outputSenderNode)
                                    .OuterNodeInPortData;

                            int targetPortIndex =
                                curriedNode.OuterNodePortDataList.IndexOf(targetPort);

                            //Connect it (new dynConnector)
                            newNodeWorkspace.AddConnection(
                                outputSenderNode,
                                curriedNode.InnerNode,
                                outputSenderData,
                                targetPortIndex + 1);

                        }
                    }
                }
                else
                {
                    foreach (var hanging in
                        selectedNodeSet.SelectMany(
                            node =>
                                Enumerable.Range(0, node.OutPortData.Count)
                                .Where(port => !node.HasOutput(port))
                                .Select(port => new { node, port })).Distinct())
                    {
                        //Create Symbol Node
                        var node = newNodeWorkspace.AddNode<Output>();
                        node.Symbol = hanging.node.OutPortData[hanging.port].NickName;

                        node.SetNickNameFromAttribute();

                        //store the element in the elements list
                        node.DisableReporting();

                        node.X = rightMost + 75 - leftShift;
                        node.Y = i*(50 + node.Height);

                        newNodeWorkspace.AddConnection(hanging.node, node, hanging.port, 0);

                        i++;
                    }
                }

                #endregion

                // save and load the definition from file
                newNodeDefinition.SyncWithWorkspace(dynamoModel, true, true);
                dynamoModel.Workspaces.Add(newNodeWorkspace);

                string name = newNodeDefinition.FunctionId.ToString();
                var collapsedNode = currentWorkspace.AddNode(avgX, avgY, name);
                undoRecorder.RecordCreationForUndo(collapsedNode);

                // place the node as intended, not centered
                collapsedNode.X = avgX;
                collapsedNode.Y = avgY;

                collapsedNode.DisableReporting();

                foreach (
                    var nodeTuple in
                        inConnectors.Select(
                            (x, idx) => new { node = x.Item1, from = x.Item2, to = idx }))
                {
                    var conn = currentWorkspace.AddConnection(
                        nodeTuple.node,
                        collapsedNode,
                        nodeTuple.from,
                        nodeTuple.to);

                    if (conn != null)
                    {
                        undoRecorder.RecordCreationForUndo(conn);
                    }
                }

                foreach (var nodeTuple in outConnectors)
                {

                    var conn = currentWorkspace.AddConnection(
                        collapsedNode,
                        nodeTuple.Item1,
                        nodeTuple.Item2,
                        nodeTuple.Item3);

                    if (conn != null)
                    {
                        undoRecorder.RecordCreationForUndo(conn);
                    }
                }

                collapsedNode.EnableReporting();
                currentWorkspace.EnableReporting();

                foreach (var node in newNodeWorkspace.Nodes)
                    node.EnableReporting();

                newNodeWorkspace.WatchChanges = true;
            }
        }
 /// <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;
 }
Ejemplo n.º 52
0
        /// <summary>
        /// Retrieves an entity from the collection by its primary key.
        /// </summary>
        /// <param name="id">The primary key of the entity.</param>
        /// <returns>The entity.</returns>
        public Task <TAggregateRoot> GetByIdAsync(TKey id)
        {
            var entity = entitySet.FirstOrDefault(e => e.Id.Equals(id));

            return(Task.FromResult(entity));
        }
Ejemplo n.º 53
0
        internal void GetUTDCheckOutputs(HashSet<string> inputs, HashSet<string> outputs, out List<Tuple<string, string>> preserveNewestOutputs)
        {
            preserveNewestOutputs = new List<Tuple<string, string>>();

            // Output groups give us the paths to the following outputs
            //   result EXE or DLL in "obj" dir
            //   PDB file in "obj" dir (if project is configured to create this)
            //   XML doc file in "bin" dir (if project is configured to create this)
            foreach (var output in OutputGroups
                                    .Where(g => IsPossibleOutputGroup(g.CanonicalName))
                                    .SelectMany(x => x.Outputs)
                                    .Select(o => Utilities.CanonicalizeFileNameNoThrow(o.CanonicalName))
                                    .Where((path) => !inputs.Contains(path)))  // some "outputs" are really inputs (e.g. app.config files)
            {
                outputs.Add(output);
            }

            // final binplace of built assembly
            var outputAssembly = this.project.GetOutputAssembly(this.ConfigCanonicalName);
            outputs.Add(Utilities.CanonicalizeFileNameNoThrow(outputAssembly));

            bool isExe = outputAssembly.EndsWith(".exe", StringComparison.OrdinalIgnoreCase);

            // final PDB path
            if (this.DebugSymbols &&
                (isExe || outputAssembly.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)))
            {
                var pdbPath = outputAssembly.Remove(outputAssembly.Length - 4) + ".pdb";
                outputs.Add(Utilities.CanonicalizeFileNameNoThrow(pdbPath));
            }

            if (isExe)
            {
                var appConfig = inputs.FirstOrDefault(x => String.Compare(Path.GetFileName(x), "app.config", StringComparison.OrdinalIgnoreCase) == 0);
                if (appConfig != null)
                {
                    // the app.config is not removed from the inputs to maintain 
                    // the same behavior of a C# project:
                    // When a app.config is changed, after the build, the project 
                    // is not up-to-date until a rebuild
                    var exeConfig = Utilities.CanonicalizeFileNameNoThrow(outputAssembly + ".config");
                    preserveNewestOutputs.Add(Tuple.Create(appConfig, exeConfig));
                }
            }
        }
Ejemplo n.º 54
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="rawPacket"></param>
        /// <param name="hostId"></param>
        /// <param name="connectionId"></param>
        private void OnPlayerConnectPacket(IPacket rawPacket, int hostId, int connectionId)
        {
            var packet = rawPacket as Client.Packet.PlayerConnectPacket;

            if (packet == null)
            {
                return;
            }

            var allowConnection = true;
            var errorMessage    = "None";

            // Check for already existing username
            if (m_players.Any(x => x.Username.Equals(packet.Username, StringComparison.OrdinalIgnoreCase)))
            {
                // Username already in use.
                allowConnection = false;
                errorMessage    = string.Format("The username {0} is already in use.", packet.Username);
                Debug.LogError(string.Format("Server: {0}", errorMessage));
            }

            var spawnPoint = new Vector3(-280.0f, 47.5f, 338.0f);

            if (allowConnection)
            {
                // Try get an offline player and get their location
                var offlinePlayer = m_offlinePlayers.FirstOrDefault(x => x.Username.Equals(packet.Username, StringComparison.OrdinalIgnoreCase));
                if (offlinePlayer != null)
                {
                    spawnPoint = offlinePlayer.CurrentPosition;
                }

                // Player is valid, store them
                var newPlayerData = new PlayerData(connectionId, packet.Username, spawnPoint);

                // Player is valid, tell all other players about them.
                var playerJoinPacket = new Server.Packet.PlayerJoinPacket(connectionId, newPlayerData.Username, newPlayerData.CurrentPosition);
                QueuePacketAllExcluding(playerJoinPacket, new int[] { connectionId });

                foreach (var player in m_players)
                {
                    var otherPlayerJoinPack = new Server.Packet.PlayerJoinPacket(player.ConnectionId, player.Username, player.CurrentPosition);
                    QueuePacket(otherPlayerJoinPack, connectionId);
                }

                m_players.Add(newPlayerData);

                if (offlinePlayer != null)
                {
                    m_offlinePlayers.Remove(offlinePlayer);
                }

                SendMobSpawnPackets(newPlayerData.ConnectionId);
            }

            var handShakePacket = new Server.Packet.PlayerHandshakePacket(allowConnection, errorMessage, spawnPoint);

            QueuePacket(handShakePacket, connectionId);

            Debug.Log(string.Format("Server: Revieved player connection from {0}", packet.Username));
        }