Example #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;
        }
Example #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);
        }
Example #3
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;
        }
Example #4
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;
        }
Example #5
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);
        }
        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());
        }
Example #7
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;
    }
Example #10
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;
        }
   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);
       }
         }
   }
Example #12
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));
                    }
                }
            }
        }
        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));
            }
        }
Example #14
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);
        }
Example #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( ) ) );
        }
Example #16
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));
        }
Example #17
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;
        }
Example #18
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++;
                }
            }
        }
Example #19
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("-");
        }
Example #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);
        }
        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);
                }
            }
        }
Example #22
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;
            }
        }
Example #23
0
        private List<IPackage> GetRootPackagesInDependencyOrder()
        {
            var packagesInOrder = new List<IPackage>();

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

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

            return packagesInOrder;
        }
Example #24
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 };
        }
Example #25
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));
            }
        }
		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);
			}
		}
 /// <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;
 }
Example #28
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;
 }
Example #29
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));
                }
            }
        }
Example #30
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;
        }