public IEnumerable<IBe> Evolve(Action<IEnumerable<IBe>, int> perIteractionAction)
        {
            currentIteration = 0;
            while (currentIteration <= god.maximunIteration)
            {
                List<IBe> currentPopulation = new List<IBe>();

                for (int i = 0; i < god.maximunOffspring; i++)
                {
                    var operation = randomOperation.GetOperation();

                    switch (operation)
                    {
                        case Operations.Mutation:
                            currentPopulation = currentPopulation.Concat(darwin.Mutate(god.GetSingle(population, i))).ToList();
                            break;
                        case Operations.CrossOver:
                            var couple = god.GetCouple(population, i);
                            currentPopulation = currentPopulation.Concat(darwin.Conceive(couple.Item1, couple.Item2)).ToList();
                            break;
                    }
                }

                population = population.Union(darwin.CalculateSolution(currentPopulation)).OrderBy(n => -n.Solution).Distinct(comparer).Take(god.maximunOffspring).ToList();

                if (perIteractionAction != null) perIteractionAction.Invoke(population, currentIteration);

                currentIteration++;
            }

            return population;
        }
Example #2
0
        public void TercerRonda(Jugador dealer)
        {
            List<Cartas> listaTercerRondaDealer = dealer.RepartirCartasRonda(1);
            cartasDealer = cartasDealer.Concat(listaTercerRondaDealer).ToList();

            for (int i = 0; i < listaTercerRondaDealer.Count; i++)
            {
                cartaVista7.Nombre = listaTercerRondaDealer[i].Nombre;
                cartaVista7.Palo = listaTercerRondaDealer[i].Palo;
            }
            ronda = 3;
            jugDealer = dealer;
            //sACAR LALISTA DE CARTAS DEL JUGADOR 1
            List<Cartas> cartasJug1Total = cartasDealer.Concat(cartasJ1).ToList();
            //Sacar la lista de las cartas del jugador 2
            List<Cartas> cartasJug2Total = cartasDealer.Concat(cartasJ2).ToList();
            int jugada1 = new Jugador().ValidarJugadaGanadora(cartasJug1Total.OrderBy(x => x.Valor).ToList());
            int jugada2 = new Jugador().ValidarJugadaGanadora(cartasJug2Total.OrderBy(x => x.Valor).ToList());
            for (int i = 0; i < cartasJ2.Count; i++)
            {
                if (i == 0)
                {
                    cartaVista8.Nombre = cartasJ2[i].Nombre;
                    cartaVista8.Palo = cartasJ2[i].Palo;
                }
                if (i == 1)
                {
                    cartaVista9.Nombre = cartasJ2[i].Nombre;
                    cartaVista9.Palo = cartasJ2[i].Palo;
                }
            }

            MessageBox.Show("Jugador 1:" + MostrarJugada(jugada1) + Environment.NewLine + Environment.NewLine + " Jugador 2:" + MostrarJugada(jugada2));
        }
        public PartialViewResult Menu()
        {
            var user = CurrentUser;
            IEnumerable<NavigationItem> navItems = new List<NavigationItem>();
            var pages = RolePagesMap.Pages;
            navItems = navItems.Concat(RolePagesMap.CommonPages).Distinct();
            if (user.IsAlumni())
            {
                navItems = navItems.Concat(pages[UserRoleType.Alumni]);
            }
            if (user.IsStudent())
            {
                navItems = navItems.Concat(pages[UserRoleType.Student]);
            }
            if (user.IsAdmin())
            {
                navItems = navItems.Concat(pages[UserRoleType.Admin]);
            }

            var txtItems = navItems.Where(n => string.IsNullOrEmpty(n.ImageUrl));
            var imgItems = navItems.Where(n => !string.IsNullOrEmpty(n.ImageUrl));

            var vm = new NavigationVm
            {
                TextItems = txtItems,
                ImageItems = imgItems,
                SelectePage = CurrentPage,
            };
            return PartialView(vm);
        }
 public void ConcatWorks()
 {
     var list = new List<string> { "a", "b" };
     Assert.AreEqual(list.Concat("c"), new[] { "a", "b", "c" });
     Assert.AreEqual(list.Concat("c", "d"), new[] { "a", "b", "c", "d" });
     Assert.AreEqual(list, new[] { "a", "b" });
 }
        public ActionResult Index()
        {
            string userId = User.Identity.GetUserId();
            List<string> userRolesList = UserManager.GetRoles(userId).ToList();

            IEnumerable<IWorkListItems> workListItemsToDisplay = new List<IWorkListItems>();
            workListItemsToDisplay = workListItemsToDisplay.Concat(GetWorkOrders(userId, userRolesList));
            workListItemsToDisplay = workListItemsToDisplay.Concat(GetWidgets(userId, userRolesList));

            return View(workListItemsToDisplay.OrderByDescending(wl => wl.PriorityScore));
        }
        public IEnumerable<ClientConnection> GetWPFConnectionsForProject(int projectId)
        {
            IList<ClientConnection> connections = new List<ClientConnection>();
            var users = projectRepository.GetAllUsersInProject(projectId);
            foreach (var user in users)
            {
                connections.Concat(SignalRClients.Connections.Where(x => x.UserName == user.UserName).ToList());
            }
            var creator = projectRepository.GetCreatorForProject(projectId);
            List<ClientConnection> creatorConnections =
                SignalRClients.Connections.Where(x => x.UserName == creator.UserName && x.IsWPFClient).ToList();

            return connections.Concat(creatorConnections); 
        }
        protected void GenerateAbilitiesFile(LegionDatabase Database)
        {
            // Load ability templates
            string SummonAbilityTemplate = LoadTemplateFile(SPAWN_UNIT_TEMPLATE);
            string UpgradeAbilityTemplate = LoadTemplateFile(UPGRADE_UNIT_TEMPLATE);

            // Generate data from each unit
            List<string> SummonAbilities = GenerateDataForList<LegionUnit>(SummonAbilityTemplate, GetSummonableUnits(Database), "Unit");
            List<string> UpgradeAbilities = GenerateDataForList<LegionUnit>(UpgradeAbilityTemplate, GetUpgradeUnits(Database), "Unit");

            // Generate data for unit abilities
            List<string> UnitAbilities = new List<string>();
            foreach (LegionUnit Unit in Database.GetUnits())
            {
                foreach (LegionAbility Ability in Unit.LegionAbilities)
                {
                    string AbilityFilePath = string.Format(UNIT_ABILITIES_TEMPLATE, Ability.AbilityFile);
                    string AbilityTemplate = LoadTemplateFile(AbilityFilePath);
                    AbilityTemplate = ProcessTemplate<LegionUnit>(AbilityTemplate, Unit, "Unit");
                    AbilityTemplate = ProcessTemplate<LegionAbility>(AbilityTemplate, Ability, "Ability");
                    UnitAbilities.Add(AbilityTemplate);
                }
            }

            // Merge all data
            List<string> GeneratedAbilitiesData = new List<string>();
            GeneratedAbilitiesData = GeneratedAbilitiesData.Concat(SummonAbilities).ToList();
            GeneratedAbilitiesData = GeneratedAbilitiesData.Concat(UpgradeAbilities).ToList();
            GeneratedAbilitiesData = GeneratedAbilitiesData.Concat(UnitAbilities).ToList();

            // Generate sell abilities for all heroes
            foreach(LegionHero Hero in Database.GetHeroes())
            {
                string SellUnitTemplate = LoadTemplateFile(SELL_UNIT_ABILITY_TEMPLATE);
                SellUnitTemplate = ProcessTemplate<LegionHero>(SellUnitTemplate, Hero, "Hero");
                GeneratedAbilitiesData.Add(SellUnitTemplate);
            }

            // Add external data
            foreach (string ExternalPath in EXTERNAL_ABILITIES)
            {
                string UnitData = LoadTemplateFile(ExternalPath);
                GeneratedAbilitiesData.Add(UnitData);
            }

            // Generate file and save
            string AbilityBuildFile = GenerateBuildFile(CUSTOM_ABILITIES_FILE, GeneratedAbilitiesData, "{Abilities}");
            SaveDataToFile(CUSTOM_ABILITIES_OUTPUT, AbilityBuildFile);
        }
 private List<long> GetFactors(long number, long first, List<long> acc)
 {
     if (first > (number / first) || first > (number / 2))
     {
         return acc;
     }
     else if (number % first == 0)
     {
         return GetFactors(number, first + 1, acc.Concat(new List<long>() {first,(number / first)}).ToList());
     }
     else
     {
         return GetFactors(number, first + 1, acc.Concat(Enumerable.Empty<long>()).ToList());
     }
 }
        private void ok_button_Click(object sender, EventArgs e)
        {
            ok_button.Enabled = false;
            Scanner scanner = new Scanner(new Credential(username_textbox.Text, password_textbox.Text));
            scanner.global_handler += this.HandleEvent;

            List<List<string>> data = new List<List<string>>();
            data.Add(new List<string>(new string[] { "Server", "Volume", "Capacity", "Free Space" }));
            List<string> servers = new RDGReader("nksd_servers.rdg").read("name");
            foreach (string server in servers)
            {
                data = data.Concat(scanner.scan(server)).ToList();
            }
            new XLSWriter("Server Spaces.xlsx").overwrite(data);
            Hide();

            string message = "Operation complete.";
            if (scanner.getErrors().Count() > 0)
            {
                message += "\n\nCannot connect to:";
                foreach (string server in scanner.getErrors())
                {
                    message += "\n" + server;
                }
            }
            MessageBox.Show(message);

            System.Diagnostics.Process.Start(@"Server Spaces.xlsx");
            Close();
        }
Example #10
0
    static void Main()
    {
        string line1 = Console.ReadLine();
        string[] firstLine = line1.Split(' ');
        string line2 = Console.ReadLine();
        string[] secondLine = line2.Split(' ');

        List<int> firstList = new List<int>();
        List<int> secondList = new List<int>();
        List<int> joinedList = new List<int>();

        for (int i = 0; i < firstLine.Length; i++)
        {
            firstList.Add(int.Parse(firstLine[i]));
        }
        for (int i = 0; i < secondLine.Length; i++)
        {
            secondList.Add(int.Parse(secondLine[i]));
        }

        joinedList = firstList.Concat(secondList).Distinct().ToList();
        joinedList.Sort();

        foreach (var item in joinedList)
        {
            Console.Write(item+" ");
        }
        Console.WriteLine();
    }
Example #11
0
        /// <summary>
        /// Get a number of messages from a channel.
        /// </summary>
        /// <param name="c">The channel</param>
        /// <param name="numReq">The number of messages requested</param>
        /// <returns></returns>
        public static async Task<IEnumerable<Message>> GetMessages(Channel c, int numReq)
        {
            int currentCount = 0;
            int numToGetThisLoop = 100;
            int newMsgCount = 100;
            ulong lastMsgId;
            IEnumerable<Message> allMsgs = new List<Message>();
            IEnumerable<Message> newMsgs = new List<Message>();
            if (numReq <= 0) return null;                                         //Quit on bad request

            lastMsgId = (await c.DownloadMessages(1))[0].Id;                        //Start from last message (will be excluded)

            while (currentCount < numReq && newMsgCount == numToGetThisLoop)      //Keep going while we don't have enough, and haven't reached end of channel
            {
                if (numReq - currentCount < 100)                                  //If we need less than 100 to achieve required number
                    numToGetThisLoop = numReq - currentCount;                     //Reduce number to get this loop

                newMsgs = await c.DownloadMessages(numToGetThisLoop, lastMsgId, Relative.Before, false);    //Get N messages before that id
                newMsgCount = newMsgs.Count();                                      //Get the count we downloaded, usually 100
                currentCount += newMsgCount;                                        //Add new messages to count
                lastMsgId = newMsgs.Last().Id;                                      //Get the id to start from on next iteration
                allMsgs = allMsgs.Concat(newMsgs);                                  //Add messages to the list
            }

            return allMsgs;
        }
		protected override string GenerateCode(ITypeDefinition currentClass)
		{
//			string[] fields = listBox.SelectedItems.OfType<PropertyOrFieldWrapper>().Select(f2 => f2.MemberName).ToArray();
			string[] fields = parameterList.Where(f => f.IsIncluded).Select(f2 => f2.MemberName).ToArray();
			
			PrimitiveExpression formatString = new PrimitiveExpression(GenerateFormatString(currentClass, editor.Language.CodeGenerator, fields));
			List<Expression> param = new List<Expression>() { formatString };
			ReturnStatement ret = new ReturnStatement(new InvocationExpression(
				new MemberReferenceExpression(new TypeReferenceExpression(ConvertType(KnownTypeCode.String)), "Format"),
				param.Concat(fields.Select(f => new IdentifierExpression(f))).ToList()
			));
			
			if (baseCallNode != null) {
				MethodDeclaration insertedOverrideMethod = refactoringContext.GetNode().PrevSibling as MethodDeclaration;
				if (insertedOverrideMethod == null) {
					// We are not inside of a method declaration
					return null;
				}
				
				using (Script script = refactoringContext.StartScript()) {
					NewLineNode nextNewLineNode = insertedOverrideMethod.NextSibling as NewLineNode;
					
					// Find base method call and replace it by return statement
					script.AddTo(insertedOverrideMethod.Body, ret);
					AppendNewLine(script, insertedOverrideMethod, nextNewLineNode);
				}
			}
			
			return null;
		}
Example #13
0
        private CacheModel GetCacheEntries()
        {
            List<string> cachePrefixes = new List<string>();

            Cache cache = HttpContext.Cache;

            var enumerator = cache.GetEnumerator();

            while (enumerator.MoveNext())
                cachePrefixes.Add(enumerator.Key.ToString().Split('$')[0]);

            HttpApplicationStateBase app = this.ControllerContext.RequestContext.HttpContext.Application;
            var disabledPrefixes = app["DisabledCachePrefixes"] as List<string>;

            disabledPrefixes = disabledPrefixes ?? new List<string>();

            var model = new CacheModel
            {
                CachePrefixes = cachePrefixes
                    .Concat(disabledPrefixes)
                    .Distinct()
                    .OrderBy(x => x)
                    .ToList(),
                DisabledPrefixes = disabledPrefixes
            };

            return model;
        }
        protected override void OnBeforeInstall(IDictionary savedState)
        {
            base.OnBeforeInstall(savedState);

            var missing = new List<string>();

            var required = new List<string>()
            {
                "MACHINE_IP"
            };

            var optional = new List<string>
            {
                "CONTAINER_DIRECTORY",
                "MACHINE_NAME",
                "SYSLOG_HOST_IP",
                "SYSLOG_PORT"
            };

            foreach (var key in required)
            {
                if (Context.Parameters[key] == null || Context.Parameters[key] == "")
                    missing.Add(key);
            }

            if (missing.Count > 0)
            {
                throw new Exception("Please provide all of the following msiexec properties: " +
                                    string.Join(", ", missing));
            }

            var presentOptional = optional.Where(key => Context.Parameters[key] != null && Context.Parameters[key] != "");
            var keys = required.Concat(presentOptional).ToList();
            WriteParametersFile(keys);
        }
        public ActionResult AddSelectedKnowledgesAsCurrentCompetencies(GaTask task)
        {
            string stringOfKnowledgesIds = Request["selectedIds"];
            if (!stringOfKnowledgesIds.IsEmpty())
            {
                List<Competence> competencies = new List<Competence>();
                HashSet<string> listOfKnIds = new HashSet<string>(stringOfKnowledgesIds.Split(',').ToList());
                foreach (var id in listOfKnIds)
                {
                    var kn = _dbContext.Ontology.Find(x => x.Id == ObjectId.Parse(id)).SingleOrDefaultAsync().Result;
                    if (kn != null)
                    {
                        competencies.Add(new Competence(kn.Id, BloomLevel.None));
                    }
                }

                if (task.Prerequisites == null)
                {
                    task.Prerequisites = competencies.ToArray();
                }
                else
                {
                    List<Competence> tmpList = new List<Competence>(task.Prerequisites);
                    tmpList.Concat(competencies);
                    task.Prerequisites = tmpList.ToArray();
                }
            }
            return View("NewTask", task);
        }
		/// <summary>
		/// Orders the extensions according to the order specified by the XML document.
		/// </summary>
		public IList<ExtensionInfo> OrderExtensions(IEnumerable<ExtensionInfo> extensions)
		{
			var ordered = new List<ExtensionInfo>();
			var remainder = new List<ExtensionInfo>(extensions);

			// order the items based on the order in the XML
			foreach (XmlElement element in ListExtensionNodes())
			{
				var className = element.GetAttribute("class");

				// ignore entries that don't specify the "class" attribute
				// (these shouldn't exist in a well-formed doc)
				if (string.IsNullOrEmpty(className))
					continue;

				// find the extensions corresponding to this class
				// (yes, it is possible that that are multiple extensions implemented by the same class)
				var typeRef = TypeRef.Get(className);
				var items = remainder.Where(x => Equals(typeRef, x.ExtensionClass)).ToList();

				// add these to the ordered list and remove them from the remainder
				foreach (var ext in items)
				{
					ordered.Add(ext);
					remainder.Remove(ext);
				}

				// if all known extensions are now ordered, we are done
				if (remainder.Count == 0)
					break;
			}

			// return the unified, ordered list, starting with those whose order was explicitly specified in the settings, followed by the rest in order of discovery
			return ordered.Concat(remainder).ToList();
		}
Example #17
0
        public IoDeviceRunTarget(io_devices ioDevice, IIoDeviceWrapperFactory wrapperFactory, INotificationReporter reporter)
        {
            _reporter = reporter;
            Name = string.Format(Res.IoDeviceWithName, ioDevice.name);
            _filePath = GetFilePath(ioDevice.type);
            _options = ioDevice.options;
            _wrapperFactory = wrapperFactory;

            var digReadParameters = new List<ReadParameter>();
            var digReadValueHolders = new List<ITagValueHolder>();
            foreach (var t in ioDevice.dig_tags)
            {
                var holder = new DigTagValueHolder(t);
                _digValueHolders.Add(t.id, holder);
                if (t.can_read)
                {
                    digReadValueHolders.Add(holder);
                    digReadParameters.Add(new ReadParameter(t.device, typeof(bool)));
                }
            }
            var numReadParameters = new List<ReadParameter>();
            var numReadValueHolders = new List<ITagValueHolder>();
            foreach (var t in ioDevice.num_tags)
            {
                var holder = new NumTagValueHolder(t);
                _numValueHolders.Add(t.id, holder);
                if (t.can_read)
                {
                    numReadValueHolders.Add(holder);
                    numReadParameters.Add(new ReadParameter(t.device, t.TagType));
                }
            }
            _readParameters = digReadParameters.Concat(numReadParameters).ToArray();
            _readValueHolders = digReadValueHolders.Concat(numReadValueHolders).ToArray();
        }
        /// <summary>
        /// 根据登录名取学院
        /// </summary>
        /// <param name="loginName"></param>
        /// <returns></returns>
        public IEnumerable<School> GetSchoolByLoginName(string loginName)
        {
            //登录名取书商ID
            var booksellerId = new TbmisUserAppl(loginName).GetUser().SchoolId;
            //取当前学期
            var term = new TermAppl().GetCurrentTerm().SchoolYearTerm;
            //取学生用书申报的ID集合
            var declarations = _repo.First(t =>
                t.ID == booksellerId
                ).Subscriptions.Where(t =>
                    t.SchoolYearTerm.Year == term.Year &&
                    t.SchoolYearTerm.Term == term.Term &&
                    t.FeedbackState == FeedbackState.征订成功 &&
                    t.Feedback.ApprovalState == ApprovalState.终审通过
                    ).SelectMany(t =>
                        t.StudentDeclarations
                        ).Select(t =>
                            t.ID
                            );
            //取学生班级
            var repo = ServiceLocator.Current.GetInstance<IStudentDeclarationRepository>();

            //取学院
            var schools = new List<School>();
            foreach (var item in declarations)
            {
                var schoolsOfDeclaration = repo.GetSchools(item).ToList();
                if (schoolsOfDeclaration.Count > 0)
                    schools.Concat(schoolsOfDeclaration);
            }

            return schools.Distinct();
        }
        public NHLPlayerSelectionForm(List<Player> centerList, List<Player> wingerList,
         List<Player> defenseList, List<Player> goalieList, int salaryCap, int salaryThreshold)
        {
            InitializeComponent();

            mCenterList = centerList;
            mWingerList = wingerList;
            mDefenseList = defenseList;
            mGoalieList = goalieList;
            mUtilList = centerList.Concat(wingerList).Concat(defenseList).ToList();

            fillComboBox(goalieBox, mGoalieList);
            fillComboBox(centerBox1, mCenterList);
            fillComboBox(centerBox2, mCenterList);
            fillComboBox(defenseBox1, mDefenseList);
            fillComboBox(defenseBox2, mDefenseList);
            fillComboBox(wingerBox1, mWingerList);
            fillComboBox(wingerBox2, mWingerList);
            fillComboBox(wingerBox3, mWingerList);
            fillComboBox(utilBox, mUtilList);

            mTeamList = new List<Team>();
            mSalaryCap = salaryCap;
            mSalaryThreshold = salaryThreshold;
        }
        public static void Main()
        {
            List<Student> students = new List<Student>()
            {
                new Student("Pesho","Peshov",5),
                new Student("Ivan", "Georgiev", 2),
                new Student("Dragan", "Petkanov", 1),
                new Student("Ralica", "Rashkova", 2),
                new Student("Angel", "Angelov", 5),
                new Student("Katq", "Kirilova", 3),
                new Student("Iveta", "Iordanova", 1),
                new Student("Georgi","Dimitrov", 3),
                new Student("Vladimir", "Kolev", 4),
                new Student("Teodor", "Todorov", 4)
            };

            var sortedStudents = students.OrderBy(st => st.Grade)
                .Select(st => st);

            foreach (Student student in sortedStudents)
            {
                Console.WriteLine("{0} -> {1} grade", student.FirstName + " " + student.LastName, student.Grade);
            }
            Console.WriteLine();

            List<Worker> workers = new List<Worker>()
            {
                new Worker("Kiro","Kirov",5, 8),
                new Worker("Petyr", "Petrov", 2,7),
                new Worker("Dimityr", "Ivanov", 1,5),
                new Worker("Georgi", "Kamenov", 2,4),
                new Worker("Kamen", "Nedqlkov", 5,1),
                new Worker("Vasko", "Vasilev", 3,2),
                new Worker("Kremena", "Ivanova", 1,3),
                new Worker("Vasilena","Vasielva", 3,8),
                new Worker("Iordan", "Ivanov", 4,8),
                new Worker("Misho", "Vasilev", 4,10)
            };

            var sortedWorkers = workers.OrderBy(w => w.MoneyPerHour())
                .Select(w => w);

            foreach (Worker worker in sortedWorkers)
            {
                Console.WriteLine("Worker: {0}", worker.FirstName + " " + worker.LastName);
                Console.WriteLine("Money per hour: {0:F2}", worker.MoneyPerHour());
                Console.WriteLine();
            }

            List<dynamic> allPersons = new List<dynamic>(workers.Concat<dynamic>(students));

            Console.WriteLine("Sorting students and workers by name: ");

            var result = allPersons.OrderBy(x => x.FirstName).ThenBy(x => x.LastName);

            foreach (var person in result)
            {
                Console.WriteLine(person.FirstName + " " + person.LastName);
            }
        }
Example #21
0
        public IEnumerable<Context> CreateContexts(MethodCall methodCall, IEnumerable<Step> steps)
        {
            Guard.AgainstNullArgument("steps", steps);

            var sharedContext = new List<Step>();
            var pendingYield = false;
            foreach (var step in steps)
            {
                if (step.InIsolation)
                {
                    yield return new Context(methodCall, sharedContext.Concat(new[] { step }));
                    pendingYield = false;
                }
                else
                {
                    sharedContext.Add(step);
                    pendingYield = true;
                }
            }

            if (pendingYield)
            {
                yield return new Context(methodCall, sharedContext);
            }
        }
        protected override void OnBeforeInstall(IDictionary savedState)
        {
            base.OnBeforeInstall(savedState);

            var missing = new List<string>();

            var required = new List<string>()
            {
                "CONSUL_IPS",
                "CF_ETCD_CLUSTER",
                "LOGGREGATOR_SHARED_SECRET",
                "REDUNDANCY_ZONE",
                "STACK",
                "MACHINE_IP",
            };

            var optional = new List<string>
            {
                "CONSUL_ENCRYPT_FILE",
                "CONSUL_CA_FILE",
                "CONSUL_AGENT_CERT_FILE",
                "CONSUL_AGENT_KEY_FILE",
                "BBS_CA_FILE",
                "BBS_CLIENT_CERT_FILE",
                "BBS_CLIENT_KEY_FILE",
                "METRON_CA_FILE",
                "METRON_AGENT_CERT_FILE",
                "METRON_AGENT_KEY_FILE",
                "MACHINE_NAME",
                "SYSLOG_HOST_IP",
                "SYSLOG_PORT"
            };

            foreach (var key in required)
            {
                if (Context.Parameters[key] == null || Context.Parameters[key] == "")
                    missing.Add(key);
            }

            if (missing.Count > 0)
            {
                throw new Exception("Please provide all of the following msiexec properties: " +
                                    string.Join(", ", missing));
            }

            try
            {
                new Uri(Context.Parameters["CF_ETCD_CLUSTER"]);
            }
            catch (UriFormatException)
            {
                throw new Exception(
                    "CF_ETCD_CLUSTER values must be URIs (i.e. http://192.168.0.1:4001 instead of 192.168.0.1:4001).");
            }

            var presentOptional = optional.Where(key => Context.Parameters[key] != null && Context.Parameters[key] != "");
            var keys = required.Concat(presentOptional).ToList();
            CopyMiscellaneousFiles(keys);
            WriteParametersFile(keys);
        }
        public GeoJsonToSqlGeographyObjectWalker()
        {
            _bld.SetSrid(GeoToSql.ReferenceId);
            _constructedGeography = new Lazy<SqlGeography>(() =>
            {
                if (_pendingCircles.Count == 0)
                    return _bld.ConstructedGeography;

                // Decompose the geo collection, add the pending circles, wrap as geometry
                // collection and reparse as geo collection.
                var geos = new List<SqlGeography>();
                var geoRoot = _bld.ConstructedGeography;
                for (var i = 1; i <= geoRoot.STNumGeometries(); i++)
                {
                    geos.Add(geoRoot.STGeometryN(i));
                }
                var sb = new StringBuilder();
                sb.Append("GEOMETRYCOLLECTION (");
                sb.Append(string.Join(",", geos.Concat(_pendingCircles)));
                sb.Append(")");
                Debug.WriteLine(sb.ToString());

                return SqlGeography.STGeomCollFromText(new SqlChars(new SqlString(sb.ToString())), GeoToSql.ReferenceId);
            });
        }
        public override void Analyze(SymbolAnalysisContext context, List<IncludeAttributeData> includeTags, List<ProtobufAttributeData> memberTags, List<ContractAttributeData> contractAttributes)
        {
            if (!includeTags.Any())
            {
                return;
            }

            var allTags = includeTags.Concat(memberTags);
           
            // Group it by tag
            var groupedByTag = allTags
                .GroupBy(m => m.Tag)
                .ToList();

            // Any group with more than one element is suspicious
            foreach (var group in groupedByTag.Where(g => g.Count() > 1))
            {
                // Any group with an include means an error
                if (group.Any(a => a is ProtoIncludeAttributeData))
                {
                    var symbolList = string.Join(", ", group.Select(g => g.GetRelevantSymbolName()));
                    foreach (var a in group)
                    {
                        var diagnostic = Diagnostic.Create(GetDescriptor(), a.GetLocation(), a.Tag, context.Symbol.Name, symbolList);
                        context.ReportDiagnostic(diagnostic);
                    }
                }
            }
        }
Example #25
0
 static void Main()
 {
     string input;
     string[] inputSplit;
     char[] separator = new char[] { ' ' };
     input = Console.ReadLine();
     inputSplit = input.Split(separator, StringSplitOptions.RemoveEmptyEntries);
     List<int> list1 = new List<int>();
     foreach (string num in inputSplit)
     {
         list1.Add(int.Parse(num));
     }
     input = Console.ReadLine();
     inputSplit = input.Split(separator, StringSplitOptions.RemoveEmptyEntries);
     List<int> list2 = new List<int>();
     foreach (string num in inputSplit)
     {
         list2.Add(int.Parse(num));
     }
     var combined = list1.Concat(list2).Distinct().ToList();
     combined.Sort();
     foreach (int num in combined)
     {
         Console.Write(num + " ");
     }
     Console.WriteLine();
 }
        public IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> GetExports(ImportDefinition definition, IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> exports)
        {
            var contractDef = (ContractBasedImportDefinition)definition;
            var returnedExports = new List<Tuple<ComposablePartDefinition, ExportDefinition>>();
            var importDefinitionType = TypeHelper.GetImportDefinitionType(definition);

            if (exports.Any())
            {
                return exports;
            }

            returnedExports.Concat(exports);

            if (this.manufacturedParts.Contains(importDefinitionType))
            {
                returnedExports.AddRange(this.catalog.GetExports(definition));
            }
            else if (TypeHelper.ShouldCreateClosedGenericPart(contractDef, importDefinitionType))
            {
                CreateGenericPart(importDefinitionType);
                returnedExports.AddRange(this.catalog.GetExports(definition));
            }

            return returnedExports;
        }
        public string GetFile(string path)
        {
            string[] pathElements = path.Split('/');

            if (pathElements.Length == 3)
            {
                List<ISong> songs = new List<ISong>();
                var album = MusicLibrary.GetAlbumsByArtist(pathElements[0]).Where<IAlbum>(a => a.Name.Equals(pathElements[1]));
                foreach (IAlbum a in album)
                {
                    songs = songs.Concat<ISong>(a.Songs).ToList<ISong>();
                }
                int startIndex = pathElements[2].IndexOf('-');
                // add the white space
                startIndex = startIndex+1;
                int endIndex = pathElements[2].LastIndexOf('.');
                string songTitle = pathElements[2].Substring(startIndex+1, endIndex - startIndex - 1);
                foreach (ISong s in songs)
                {
                    if (s.Title.Equals(songTitle))
                    {
                        return s.MediaFilePath;

                    }
                }
            }
            return null;
        }
        public string Autosuggest(string autocomplete)
        {
            const string autocompletionName = "destination-suggest";
            var response =
                _elasticClient.Suggest<string>(suggest => suggest.Completion(autocompletionName, c => c.Size(100).OnField("suggest").Text(autocomplete).Fuzzy(fuzzy=> fuzzy.Fuzziness(1).Transpositions(false))));

            var options = response.Suggestions[autocompletionName][0].Options;

            var fuzzySuggestions = new List<Suggestion>();

            var exactMatchSuggestions = new List<Suggestion>();

            foreach (var option in options)
            {
                var suggestion = new Suggestion
                {
                    Text = option.Text,
                    Payload = option.Payload,
                    Score = option.Score
                };

                if (option.Text.ToUpperInvariant().StartsWith(autocomplete.ToUpperInvariant()))
                    exactMatchSuggestions.Add(suggestion);
                else fuzzySuggestions.Add(suggestion);
            }

            var suggestions = exactMatchSuggestions.Concat(fuzzySuggestions);

            return JsonConvert.SerializeObject(suggestions.Select(y => y.Text).ToList());
        }
        internal static void WriteCreateInfoFromQueryStringMethod(
            TextWriter writer, List<VariableSpecification> requiredParameters, List<VariableSpecification> optionalParameters, string methodNamePrefix,
            string infoConstructorArgPrefix)
        {
            writer.WriteLine( methodNamePrefix + ( methodNamePrefix.Contains( "protected" ) ? "c" : "C" ) + "reateInfoFromQueryString() {" );

            writer.WriteLine( "try {" );
            var allParameters = requiredParameters.Concat( optionalParameters );

            // Create a local variable for all query parameters to hold their raw query value.
            foreach( var parameter in allParameters ) {
                // If a query parameter is not specified, Request.QueryString[it] returns null. If it is specified as blank (&it=), Request.QueryString[it] returns the empty string.
                writer.WriteLine(
                    "var " + getLocalQueryValueVariableName( parameter ) + " = HttpContext.Current.Request.QueryString[ \"" + parameter.PropertyName + "\" ];" );
            }

            // Enforce specification of all required parameters.
            foreach( var parameter in requiredParameters ) {
                // Blow up if a required parameter was not specified.
                writer.WriteLine(
                    "if( " + getLocalQueryValueVariableName( parameter ) + " == null ) throw new ApplicationException( \"Required parameter not included in query string: " +
                    parameter.Name + "\" );" );
            }

            // Build up the call to the info constructor.
            var infoCtorArguments = new List<string> { infoConstructorArgPrefix };
            infoCtorArguments.AddRange( requiredParameters.Select( rp => getChangeTypeExpression( rp ) ) );

            // If there are optional parameters, build an optional paramater package, populate it, and include it in the call to the info constructor.
            if( optionalParameters.Count > 0 ) {
                infoCtorArguments.Add( "optionalParameterPackage: optionalParameterPackage" );
                writer.WriteLine( "var optionalParameterPackage = new OptionalParameterPackage();" );
                foreach( var parameter in optionalParameters ) {
                    // If the optional parameter was not specified, do not set its value (let it remain its default value).
                    writer.WriteLine(
                        "if( " + getLocalQueryValueVariableName( parameter ) + " != null ) optionalParameterPackage." + parameter.PropertyName + " = " +
                        getChangeTypeExpression( parameter ) + ";" );
                }
            }

            // Construct the info object.
            writer.WriteLine( "info = new Info( " + StringTools.ConcatenateWithDelimiter( ", ", infoCtorArguments.ToArray() ) + " );" );
            writer.WriteLine( "}" ); // Try block

            writer.WriteLine( "catch( Exception e ) {" );
            writer.WriteLine( "if( e is UserDisabledByPageException )" );
            writer.WriteLine( "throw;" );
            writer.WriteLine(
                "throw new ResourceNotAvailableException( \"Query parameter values or non URL elements of the request prevented the creation of the page or entity setup info object.\", e );" );
            writer.WriteLine( "}" ); // Catch block

            // Initialize the parameters modification object.
            if( allParameters.Any() ) {
                writer.WriteLine( "parametersModification = new ParametersModification();" );
                foreach( var parameter in allParameters )
                    writer.WriteLine( "parametersModification." + parameter.PropertyName + " = info." + parameter.PropertyName + ";" );
            }

            writer.WriteLine( "}" );
        }
Example #30
0
        /// <summary>
        /// Visits the payload element
        /// </summary>
        /// <param name="payloadElement">The payload element to visit</param>
        public override void Visit(EntityInstance payloadElement)
        {
            ExceptionUtilities.CheckArgumentNotNull(payloadElement, "payloadElement");

            var properties = new List<PropertyInstance>();
            var navprops = new List<PropertyInstance>();
            foreach (var propertyInstance in payloadElement.Properties)
            {
                this.Recurse(propertyInstance);
                var isnavprop = propertyInstance as NavigationPropertyInstance;
                if (isnavprop != null)
                {
                    navprops.Add(propertyInstance);
                }
                else
                {
                    properties.Add(propertyInstance);
                }
            }
            payloadElement.Properties = navprops.Concat(properties);

            foreach (var serviceOperationDescriptor in payloadElement.ServiceOperationDescriptors)
            {
                this.Recurse(serviceOperationDescriptor);
            }
        }
Example #31
0
        /// <summary>
        /// Adds the specified ranges to this list.	Overlapped ranges are combined.
        /// </summary>
        /// <param name="ranges">The ranges to add.</param>
        /// <returns>A new list with the elements added.</returns>
        public ImmutableRangeList <TValue> AddRanges(IEnumerable <Range <TValue> > ranges)
        {
            if (ranges == null)
            {
                return(this);
            }

            // ReSharper disable PossibleMultipleEnumeration
            return(Values?.Concat(ranges).ToRangeList() ?? ranges.ToRangeList());
            // ReSharper restore PossibleMultipleEnumeration
        }
Example #32
0
        // Create separate TM for each TM file on which user set penalty. The penalty is applied on top of any penalty that might be applied by the translation provider itself.
        // The name of the new TM will be the same with the one from StarTransit package
        // We'll create a single project which will contain all the tms and mt.
        private void CreateSeparateTms(LanguagePair pair, IProject project, PackageModel package)
        {
            var allTransitTms = _penaltiesTmsList?.Concat(_machineTransList).ToList();

            if (allTransitTms != null && !allTransitTms.Any())
            {
                return;
            }
            var tpReference = CreateTpReference(allTransitTms, pair, project, package);

            foreach (var tpRef in tpReference)
            {
                _tmConfig.Entries.Add(new TranslationProviderCascadeEntry(tpRef.Key, true, true, true, tpRef.Value));
            }
        }
Example #33
0
 public List <string> ReplaceFieldColumns(Context context)
 {
     if (ReplaceFieldColumnsCache == null)
     {
         var targetColumns = Columns
                             ?.Where(o => o.Value.Changed())
                             .Select(o => o.Key)
                             .ToList();
         ReplaceFieldColumnsCache = context.Forms.List("ReplaceFieldColumns")
                                    .ToList();
         if (targetColumns != null)
         {
             ReplaceFieldColumnsCache = ReplaceFieldColumnsCache
                                        ?.Concat(targetColumns)
                                        .Distinct()
                                        .ToList();
         }
     }
     return(ReplaceFieldColumnsCache);
 }
        /// <summary>
        /// Sets up a dictionaries indexed by PowerShell version/edition and OS
        /// </summary>
        private void SetupCmdletsDictionary()
        {
            // If the method encounters any error, it returns early
            // which implies there is an initialization error
            hasInitializationError = true;
            Dictionary <string, object> ruleArgs = Helper.Instance.GetRuleArguments(GetName());

            if (ruleArgs == null)
            {
                return;
            }

            if (!RuleParamsValid(ruleArgs))
            {
                return;
            }

            var compatibilityObjectArr = ruleArgs["compatibility"] as object[];
            var compatibilityList      = new List <string>();

            if (compatibilityObjectArr == null)
            {
                compatibilityList = ruleArgs["compatibility"] as List <string>;
                if (compatibilityList == null)
                {
                    return;
                }
            }
            else
            {
                foreach (var compatItem in compatibilityObjectArr)
                {
                    var compatString = compatItem as string;
                    if (compatString == null)
                    {
                        // ignore (warn) non-string invalid entries
                        continue;
                    }

                    compatibilityList.Add(compatString);
                }
            }

            ruleParameters.compatibility = compatibilityList.ToArray();
            reference = defaultReference;
#if DEBUG
            // Setup reference file
            object referenceObject;
            if (ruleArgs.TryGetValue("reference", out referenceObject))
            {
                reference = referenceObject as string;
                if (reference == null)
                {
                    reference = GetStringArgFromListStringArg(referenceObject);
                    if (reference == null)
                    {
                        return;
                    }
                }
            }
#endif
            ruleParameters.reference = reference;

            // check if the reference file has valid platformSpec
            if (!IsValidPlatformString(reference))
            {
                return;
            }

            string settingsPath = Settings.GetShippedSettingsDirectory();
#if DEBUG
            object modeObject;
            if (ruleArgs.TryGetValue("mode", out modeObject))
            {
                // This is for testing only. User should not be specifying mode!
                var mode = GetStringArgFromListStringArg(modeObject);
                ruleParameters.mode = mode;
                switch (mode)
                {
                case "offline":
                    settingsPath = GetStringArgFromListStringArg(ruleArgs["uri"]);
                    break;

                case "online":     // not implemented yet.
                case null:
                default:
                    return;
                }
            }
#endif
            if (settingsPath == null ||
                !ContainsReferenceFile(settingsPath))
            {
                return;
            }

            var extentedCompatibilityList = compatibilityList.Concat(Enumerable.Repeat(reference, 1));
            foreach (var compat in extentedCompatibilityList)
            {
                string psedition, psversion, os;

                // ignore (warn) invalid entries
                if (GetVersionInfoFromPlatformString(compat, out psedition, out psversion, out os))
                {
                    platformSpecMap.Add(compat, new { PSEdition = psedition, PSVersion = psversion, OS = os });
                    curCmdletCompatibilityMap.Add(compat, true);
                }
            }

            ProcessDirectory(
                settingsPath,
                extentedCompatibilityList);
            if (psCmdletMap.Keys.Count != extentedCompatibilityList.Count())
            {
                return;
            }

            // reached this point, so no error
            hasInitializationError = false;
        }
        public GermanDateExtractorConfiguration(IDateTimeOptionsConfiguration config)
            : base(config)
        {
            var numOptions = NumberOptions.None;

            if ((config.Options & DateTimeOptions.NoProtoCache) != 0)
            {
                numOptions = NumberOptions.NoProtoCache;
            }

            var numConfig = new BaseNumberOptionsConfiguration(config.Culture, numOptions);

            IntegerExtractor = Number.German.IntegerExtractor.GetInstance();
            OrdinalExtractor = Number.German.OrdinalExtractor.GetInstance();
            NumberParser     = new BaseNumberParser(new GermanNumberParserConfiguration(new BaseNumberOptionsConfiguration(numConfig)));

            DurationExtractor    = new BaseDurationExtractor(new GermanDurationExtractorConfiguration(this));
            UtilityConfiguration = new GermanDatetimeUtilityConfiguration();

            // 3-23-2017
            var dateRegex4 = new Regex(DateTimeDefinitions.DateExtractor4, RegexFlags);

            // 23-3-2015
            var dateRegex5 = new Regex(DateTimeDefinitions.DateExtractor5, RegexFlags);

            // am 1.3
            var dateRegex6 = new Regex(DateTimeDefinitions.DateExtractor6, RegexFlags);

            // am 24-12
            var dateRegex8 = new Regex(DateTimeDefinitions.DateExtractor8, RegexFlags);

            // 7/23
            var dateRegex7 = new Regex(DateTimeDefinitions.DateExtractor7, RegexFlags);

            // 23/7
            var dateRegex9 = new Regex(DateTimeDefinitions.DateExtractor9, RegexFlags);

            // Nächstes Jahr (im Sommer)?
            var dateRegex10 = new Regex(DateTimeDefinitions.DateExtractor10, RegexFlags);

            // 2015-12-23
            var dateRegexA = new Regex(DateTimeDefinitions.DateExtractorA, RegexFlags);

            DateRegexList = new List <Regex>
            {
                // (Sonntag,)? 5. April
                new Regex(DateTimeDefinitions.DateExtractor1, RegexFlags),

                // (Sonntag,)? 5. April, 2016
                new Regex(DateTimeDefinitions.DateExtractor2, RegexFlags),

                // (Sonntag,)? der 6. April, 2016
                new Regex(DateTimeDefinitions.DateExtractor3, RegexFlags),
            };

            var enableDmy = DmyDateFormat ||
                            DateTimeDefinitions.DefaultLanguageFallback == Constants.DefaultLanguageFallback_DMY;

            DateRegexList = DateRegexList.Concat(enableDmy ?
                                                 new[] { dateRegex5, dateRegex8, dateRegex9, dateRegex4, dateRegex6, dateRegex7, dateRegex10, dateRegexA } :
                                                 new[] { dateRegex4, dateRegex6, dateRegex7, dateRegex5, dateRegex8, dateRegex9, dateRegex10, dateRegexA });
        }
Example #36
0
        /// <summary>
        /// Executes a multi-record insert query clause with <em>SELECT UNION ALL</em>.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="storage">The storage to use.</param>
        /// <param name="tableName">The table name to against which to execute the query.</param>
        /// <param name="parameters">The parameters to insert.</param>
        /// <param name="cancellationToken">The cancellation token. Defaults to <see cref="CancellationToken.None"/>.</param>
        /// <param name="nameMap">If provided, maps property names from <typeparamref name="T"/> to ones provided in the map.</param>
        /// <param name="onlyOnceColumns">If given, SQL parameter values for the given <typeparamref name="T"/> property types are generated only once. Effective only when <paramref name="useSqlParams"/> is <em>TRUE</em>.</param>
        /// <param name="useSqlParams"><em>TRUE</em> if the query should be in parameterized form. <em>FALSE</em> otherwise.</param>
        /// <returns>The rows affected.</returns>
        public static Task <int> ExecuteMultipleInsertIntoAsync <T>(this IRelationalStorage storage, string tableName, IEnumerable <T> parameters, CancellationToken cancellationToken = default(CancellationToken), IReadOnlyDictionary <string, string> nameMap = null, IEnumerable <string> onlyOnceColumns = null, bool useSqlParams = true)
        {
            if (string.IsNullOrWhiteSpace(tableName))
            {
                throw new ArgumentException("The name must be a legal SQL table name", "tableName");
            }

            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            var storageConsts = DbConstantsStore.GetDbConstants(storage.InvariantName);

            var startEscapeIndicator = storageConsts.StartEscapeIndicator;
            var endEscapeIndicator   = storageConsts.EndEscapeIndicator;

            //SqlParameters map is needed in case the query needs to be parameterized in order to avoid two
            //reflection passes as first a query needs to be constructed and after that when a database
            //command object has been created, parameters need to be provided to them.
            var          sqlParameters            = new Dictionary <string, object>();
            const string insertIntoValuesTemplate = "INSERT INTO {0} ({1}) SELECT {2};";
            var          columns = string.Empty;
            var          values  = new List <string>();

            if (parameters.Any())
            {
                //Type and property information are the same for all of the objects.
                //The following assumes the property names will be retrieved in the same
                //order as is the index iteration done.
                var onlyOnceRow = new List <string>();
                var properties  = parameters.First().GetType().GetTypeInfo().GetProperties();
                columns = string.Join(",", nameMap == null ? properties.Select(pn => string.Format("{0}{1}{2}", startEscapeIndicator, pn.Name, endEscapeIndicator)) : properties.Select(pn => string.Format("{0}{1}{2}", startEscapeIndicator, (nameMap.ContainsKey(pn.Name) ? nameMap[pn.Name] : pn.Name), endEscapeIndicator)));
                if (onlyOnceColumns != null && onlyOnceColumns.Any())
                {
                    var onlyOnceProperties = properties.Where(pn => onlyOnceColumns.Contains(pn.Name)).Select(pn => pn).ToArray();
                    var onlyOnceData       = parameters.First();
                    for (int i = 0; i < onlyOnceProperties.Length; ++i)
                    {
                        var currentProperty = onlyOnceProperties[i];
                        var parameterValue  = currentProperty.GetValue(onlyOnceData, null);
                        if (useSqlParams)
                        {
                            var parameterName = string.Format("@{0}", (nameMap.ContainsKey(onlyOnceProperties[i].Name) ? nameMap[onlyOnceProperties[i].Name] : onlyOnceProperties[i].Name));
                            onlyOnceRow.Add(parameterName);
                            sqlParameters.Add(parameterName, parameterValue);
                        }
                        else
                        {
                            onlyOnceRow.Add(string.Format(adoNetFormatProvider, "{0}", parameterValue));
                        }
                    }
                }

                var dataRows        = new List <string>();
                var multiProperties = onlyOnceColumns == null ? properties : properties.Where(pn => !onlyOnceColumns.Contains(pn.Name)).Select(pn => pn).ToArray();
                int parameterCount  = 0;
                foreach (var row in parameters)
                {
                    for (int i = 0; i < multiProperties.Length; ++i)
                    {
                        var currentProperty = multiProperties[i];
                        var parameterValue  = currentProperty.GetValue(row, null);
                        if (useSqlParams)
                        {
                            var parameterName = string.Format(indexedParameterTemplate, parameterCount);
                            dataRows.Add(parameterName);
                            sqlParameters.Add(parameterName, parameterValue);
                            ++parameterCount;
                        }
                        else
                        {
                            dataRows.Add(string.Format(adoNetFormatProvider, "{0}", parameterValue));
                        }
                    }

                    values.Add(string.Format("{0}", string.Join(",", onlyOnceRow.Concat(dataRows))));
                    dataRows.Clear();
                }
            }

            var query = string.Format(insertIntoValuesTemplate, tableName, columns, string.Join(storageConsts.UnionAllSelectTemplate, values));

            return(storage.ExecuteAsync(query, command =>
            {
                if (useSqlParams)
                {
                    foreach (var sp in sqlParameters)
                    {
                        var p = command.CreateParameter();
                        p.ParameterName = sp.Key;
                        p.Value = sp.Value ?? DBNull.Value;
                        p.Direction = ParameterDirection.Input;
                        command.Parameters.Add(p);
                    }
                }
            }, cancellationToken));
        }
        public async Task IndexOperationsAsyncTest()
        {
            // AddObject with ID
            var objectOne = new AlgoliaStub {
                ObjectId = "one"
            };
            var addObject = _index.SaveObjectAsync(objectOne);

            // AddObject without ID
            var objectWoId    = new AlgoliaStub();
            var addObjectWoId = _index.SaveObjectAsync(objectWoId, autoGenerateObjectId: true);

            // Save two objects with objectID
            var objectsWithIds = new List <AlgoliaStub>
            {
                new AlgoliaStub {
                    ObjectId = "two"
                }, new AlgoliaStub {
                    ObjectId = "three"
                }
            };

            var addObjects = _index.SaveObjectsAsync(objectsWithIds);

            // Save two objects w/o objectIDs
            var objectsWoId = new List <AlgoliaStub>
            {
                new AlgoliaStub {
                    Property = "addObjectsWoId"
                }, new AlgoliaStub {
                    Property = "addObjectsWoId"
                }
            };

            var addObjectsWoId = _index.SaveObjectsAsync(objectsWoId, autoGenerateObjectId: true);

            // Batch 1000 objects
            var objectsToBatch = new List <AlgoliaStub>();
            var ids            = new List <string>();

            for (int i = 0; i < 1000; i++)
            {
                var id = (i + 1).ToString();
                objectsToBatch.Add(new AlgoliaStub {
                    ObjectId = id, Property = $"Property{id}"
                });
                ids.Add(id);
            }

            var batch = _index.SaveObjectsAsync(objectsToBatch);

            // Wait for all http call to finish
            var responses = await Task.WhenAll(new[] { addObject, addObjectWoId, addObjects, addObjectsWoId, batch })
                            .ConfigureAwait(false);

            // Wait for Algolia's task to finish (indexing)
            responses.Wait();

            // Six first records
            var generatedId = addObjectWoId.Result.Responses[0].ObjectIDs.ToList();

            objectWoId.ObjectId = generatedId.ElementAt(0);

            var generatedIDs = addObjectsWoId.Result.Responses[0].ObjectIDs.ToList();

            objectsWoId[0].ObjectId = generatedIDs.ElementAt(0);
            objectsWoId[1].ObjectId = generatedIDs.ElementAt(1);

            var settedIds = new List <string> {
                "one", "two", "three"
            };

            var sixFirstRecordsIds = settedIds.Concat(generatedId).Concat(generatedIDs).ToList();
            var sixFirstRecords    = (await _index.GetObjectsAsync <AlgoliaStub>(sixFirstRecordsIds)).ToList();

            Assert.That(sixFirstRecords, Has.Exactly(6).Items);

            var objectsToCompare = new List <AlgoliaStub> {
                objectOne
            }.Concat(objectsWithIds)
            .Concat(new List <AlgoliaStub> {
                objectWoId
            })
            .Concat(objectsWoId)
            .ToList();

            // Check retrieved objects againt original content
            Parallel.For(0, sixFirstRecords.Count, i =>
            {
                Assert.True(TestHelper.AreObjectsEqual(sixFirstRecords[i], objectsToCompare[i]));
            });

            // 1000 records
            var batchResponse = (await _index.GetObjectsAsync <AlgoliaStub>(ids)).ToList();

            Assert.That(batchResponse, Has.Exactly(1000).Items);

            // Check retrieved objects againt original content
            Parallel.For(0, batchResponse.Count, i =>
            {
                Assert.True(TestHelper.AreObjectsEqual(objectsToBatch[i], batchResponse[i]));
            });

            // Browse all index to assert that we have 1006 objects
            var objectsBrowsed = new List <AlgoliaStub>();

            foreach (var item in _index.Browse <AlgoliaStub>(new BrowseIndexQuery()))
            {
                objectsBrowsed.Add(item);
            }

            Assert.That(objectsBrowsed, Has.Exactly(1006).Items);

            // Update one object
            var objectToPartialUpdate = objectsToBatch.ElementAt(0);

            objectToPartialUpdate.Property = "PartialUpdated";

            var partialUpdateObject = await _index.PartialUpdateObjectAsync(objectToPartialUpdate);

            partialUpdateObject.Wait();

            var getUpdatedObject = await _index.GetObjectAsync <AlgoliaStub>(objectToPartialUpdate.ObjectId);

            Assert.That(getUpdatedObject.Property, Is.EqualTo(objectToPartialUpdate.Property));

            // Update two objects
            var objectToPartialUpdate1 = objectsToBatch.ElementAt(1);

            objectToPartialUpdate1.Property = "PartialUpdated1";
            var objectToPartialUpdate2 = objectsToBatch.ElementAt(2);

            objectToPartialUpdate2.Property = "PartialUpdated2";

            var partialUpdateObjects = await _index.PartialUpdateObjectsAsync(new List <AlgoliaStub>
            {
                objectToPartialUpdate1, objectToPartialUpdate2
            });

            partialUpdateObjects.Wait();

            var getUpdatedObjects = (await _index.GetObjectsAsync <AlgoliaStub>(new List <string>
            {
                objectToPartialUpdate1.ObjectId, objectToPartialUpdate2.ObjectId
            })).ToList();

            Assert.That(getUpdatedObjects.ElementAt(0).Property, Is.EqualTo(objectToPartialUpdate1.Property));
            Assert.That(getUpdatedObjects.ElementAt(1).Property, Is.EqualTo(objectToPartialUpdate2.Property));

            // Add 1 record with saveObject with an objectID and a tag algolia and wait for the task to finish
            AlgoliaStub taggedRecord = new AlgoliaStub {
                ObjectId = "taggedObject", Tags = new List <string> {
                    "algolia"
                }
            };
            var saveTaggedObject = await _index.SaveObjectAsync(taggedRecord);

            saveTaggedObject.Wait();

            // Delete the record containing the tag algolia with deleteBy and the tagFilters option
            var deleteByTaggedObject = await _index.DeleteByAsync(new Query { Filters = "algolia" });

            deleteByTaggedObject.Wait();

            // Delete six first objects
            var deleteObjects = await _index.DeleteObjectsAsync(sixFirstRecordsIds);

            // Assert that the objects were deleted
            var objectsBrowsedAfterDelete = new List <AlgoliaStub>();

            deleteObjects.Wait();
            foreach (var item in _index.Browse <AlgoliaStub>(new BrowseIndexQuery()))
            {
                objectsBrowsedAfterDelete.Add(item);
            }

            Assert.That(objectsBrowsedAfterDelete, Has.Exactly(1000).Items);

            // Delete remaining objects
            var deleteRemainingObjects = await _index.DeleteObjectsAsync(ids);

            deleteRemainingObjects.Wait();

            // Assert that all objects were deleted
            var search = await _index.SearchAsync <AlgoliaStub>(new Query(""));

            Assert.That(search.Hits, Is.Empty);
        }
Example #38
0
            /// <summary>
            /// 1 Pass & CRF Arguments
            /// </summary>
            public static String Arguments()
            {
                // -------------------------
                //  Single Pass (1 Pass & CRF)
                // -------------------------
                if (VM.VideoView.Video_Pass_SelectedItem == "1 Pass" ||
                    VM.VideoView.Video_Pass_SelectedItem == "CRF" ||
                    VM.VideoView.Video_Pass_SelectedItem == "none" ||
                    VM.VideoView.Video_Pass_SelectedItem == "auto" //||
                    //VM.FormatView.Format_Container_SelectedItem == "ogv" //ogv (special rule)
                    )
                {
                    // -------------------------
                    // FFmpeg Initialize
                    // -------------------------
                    IEnumerable <string> ffmpegInitializeList = new List <string>()
                    {
                        Sys.Shell.ShellTitle() +
                        Sys.Shell.ProcessPriority() +
                        MainWindow.FFmpegPath() +
                        Sys.Shell.ProcessPriority_PowerShell_Flags(),
                    };

                    // -------------------------
                    // Options
                    // -------------------------
                    IEnumerable <string> optionsList = new List <string>()
                    {
                        "\r\n\r\n" +
                        OutputOverwrite(), //-y, -n
                    };

                    // -------------------------
                    // HW Accel Decode
                    // -------------------------
                    // Log Console Message /////////
                    Log.WriteAction = () =>
                    {
                        Log.logParagraph.Inlines.Add(new LineBreak());
                        Log.logParagraph.Inlines.Add(new LineBreak());
                        Log.logParagraph.Inlines.Add(new Bold(new Run("HW Accel"))
                        {
                            Foreground = Log.ConsoleAction
                        });
                    };
                    Log.LogActions.Add(Log.WriteAction);

                    IEnumerable <string> hwAccelDecodeList = new List <string>()
                    {
                        "\r\n\r\n" +
                        Video.Encoding.HWAccelerationDecode(VM.FormatView.Format_MediaType_SelectedItem,
                                                            VM.VideoView.Video_Codec_SelectedItem,
                                                            VM.VideoView.Video_HWAccel_Decode_SelectedItem
                                                            ),
                    };

                    // -------------------------
                    // Input
                    // -------------------------
                    IEnumerable <string> inputList = new List <string>()
                    {
                        "\r\n\r\n" +
                        "-i " + MainWindow.WrapWithQuotes(MainWindow.InputPath("pass 1")),

                        "\r\n\r\n" +
                        Audio.Audio.AudioMux(VM.AudioView.Audio_Codec_SelectedItem,
                                             VM.AudioView.Audio_Stream_SelectedItem
                                             ),

                        "\r\n\r\n" +
                        Subtitle.Subtitle.SubtitlesMux(VM.SubtitleView.Subtitle_Codec_SelectedItem,
                                                       VM.SubtitleView.Subtitle_Stream_SelectedItem
                                                       ),
                    };


                    // -------------------------
                    // HW Accel Transcode
                    // -------------------------
                    IEnumerable <string> hwAccelTranscodeList = new List <string>()
                    {
                        "\r\n\r\n" +
                        Video.Encoding.HWAccelerationTranscode(VM.FormatView.Format_MediaType_SelectedItem,
                                                               VM.VideoView.Video_Codec_SelectedItem,
                                                               VM.VideoView.Video_HWAccel_Transcode_SelectedItem
                                                               ),
                    };

                    // -------------------------
                    // Format
                    // -------------------------
                    // Log Console Message /////////
                    Log.WriteAction = () =>
                    {
                        Log.logParagraph.Inlines.Add(new LineBreak());
                        Log.logParagraph.Inlines.Add(new LineBreak());
                        Log.logParagraph.Inlines.Add(new Bold(new Run("Format"))
                        {
                            Foreground = Log.ConsoleAction
                        });
                        Log.logParagraph.Inlines.Add(new LineBreak());
                        Log.logParagraph.Inlines.Add(new Run("Extension: " + MainWindow.outputExt)
                        {
                            Foreground = Log.ConsoleDefault
                        });                                                                                                              // output Extension
                    };
                    Log.LogActions.Add(Log.WriteAction);

                    IEnumerable <string> formatList = new List <string>()
                    {
                        "\r\n\r\n" +
                        Format.CutStart(VM.MainView.Input_Text,
                                        VM.MainView.Batch_IsChecked,
                                        VM.FormatView.Format_Cut_SelectedItem,
                                        VM.FormatView.Format_CutStart_Hours_Text,
                                        VM.FormatView.Format_CutStart_Minutes_Text,
                                        VM.FormatView.Format_CutStart_Seconds_Text,
                                        VM.FormatView.Format_CutStart_Milliseconds_Text,
                                        VM.FormatView.Format_FrameStart_Text
                                        ),
                        Format.CutEnd(VM.MainView.Input_Text,
                                      VM.MainView.Batch_IsChecked,
                                      VM.FormatView.Format_MediaType_SelectedItem,
                                      VM.FormatView.Format_Cut_SelectedItem,
                                      VM.FormatView.Format_CutEnd_Hours_Text,
                                      VM.FormatView.Format_CutEnd_Minutes_Text,
                                      VM.FormatView.Format_CutEnd_Seconds_Text,
                                      VM.FormatView.Format_CutEnd_Milliseconds_Text,
                                      VM.FormatView.Format_FrameEnd_Text
                                      ),
                    };

                    // -------------------------
                    // Video
                    // -------------------------
                    // Log Console Message /////////
                    Log.WriteAction = () =>
                    {
                        Log.logParagraph.Inlines.Add(new LineBreak());
                        Log.logParagraph.Inlines.Add(new LineBreak());
                        Log.logParagraph.Inlines.Add(new Bold(new Run("Video"))
                        {
                            Foreground = Log.ConsoleAction
                        });
                    };
                    Log.LogActions.Add(Log.WriteAction);

                    //System.Windows.MessageBox.Show(string.Join("\n",VM.VideoView.Video_PixelFormat_Items)); //debug

                    IEnumerable <string> videoList = new List <string>();

                    if (VM.FormatView.Format_MediaType_SelectedItem != "Audio" &&
                        VM.VideoView.Video_Codec_SelectedItem != "None" &&
                        VM.VideoView.Video_Quality_SelectedItem != "None"
                        )
                    {
                        videoList = new List <string>()
                        {
                            "\r\n\r\n" +
                            Video.Codec.VideoCodec(VM.VideoView.Video_HWAccel_Transcode_SelectedItem,
                                                   VM.VideoView.Video_Codec_SelectedItem,
                                                   VM.VideoView.Video_Codec
                                                   ),

                            // No PassParams() for 1 Pass / CRF

                            "\r\n" +
                            Video.Encoding.VideoEncodeSpeed(VM.VideoView.Video_EncodeSpeed_Items,
                                                            VM.VideoView.Video_EncodeSpeed_SelectedItem,
                                                            VM.VideoView.Video_Codec_SelectedItem,
                                                            VM.VideoView.Video_Pass_SelectedItem
                                                            ),

                            Video.Quality.VideoQuality(VM.MainView.Batch_IsChecked,
                                                       (bool)VM.VideoView.Video_VBR_IsChecked,
                                                       VM.FormatView.Format_Container_SelectedItem,
                                                       VM.FormatView.Format_MediaType_SelectedItem,
                                                       VM.VideoView.Video_Codec_SelectedItem,
                                                       VM.VideoView.Video_Quality_Items,
                                                       VM.VideoView.Video_Quality_SelectedItem,
                                                       VM.VideoView.Video_Pass_SelectedItem,
                                                       VM.VideoView.Video_CRF_Text,
                                                       VM.VideoView.Video_BitRate_Text,
                                                       VM.VideoView.Video_MinRate_Text,
                                                       VM.VideoView.Video_MaxRate_Text,
                                                       VM.VideoView.Video_BufSize_Text,
                                                       VM.MainView.Input_Text
                                                       ),

                            "\r\n" +
                            Video.Params.QualityParams(VM.VideoView.Video_Quality_SelectedItem,
                                                       VM.VideoView.Video_Codec_SelectedItem,
                                                       VM.FormatView.Format_MediaType_SelectedItem
                                                       ),

                            "\r\n" +
                            Video.Quality.PixFmt(VM.VideoView.Video_Codec_SelectedItem,
                                                 VM.VideoView.Video_PixelFormat_SelectedItem
                                                 ),

                            "\r\n" +
                            Video.Color.Color_Range(VM.VideoView.Video_Color_Range_SelectedItem),
                            "\r\n" +
                            Video.Color.Color_Space(VM.VideoView.Video_Color_Space_SelectedItem),
                            "\r\n" +
                            Video.Color.Color_Primaries(VM.VideoView.Video_Color_Primaries_SelectedItem),
                            "\r\n" +
                            Video.Color.Color_TransferCharacteristics(VM.VideoView.Video_Color_TransferCharacteristics_SelectedItem),

                            "\r\n" +
                            Video.Quality.Optimize(VM.VideoView.Video_Codec_SelectedItem,
                                                   VM.VideoView.Video_Optimize_Items,
                                                   VM.VideoView.Video_Optimize_SelectedItem,
                                                   VM.VideoView.Video_Optimize_Tune_SelectedItem,
                                                   VM.VideoView.Video_Optimize_Profile_SelectedItem,
                                                   VM.VideoView.Video_Optimize_Level_SelectedItem
                                                   ),

                            "\r\n" +
                            Video.Video.FPS(VM.VideoView.Video_Codec_SelectedItem,
                                            VM.VideoView.Video_FPS_SelectedItem,
                                            VM.VideoView.Video_FPS_Text
                                            ),

                            "\r\n" +
                            Filters.Video.VideoFilter(),

                            "\r\n" +
                            Video.Video.Vsync(VM.VideoView.Video_Codec_SelectedItem, // vsync after filters
                                              VM.VideoView.Video_Vsync_SelectedItem
                                              ),

                            "\r\n" +
                            Video.Size.AspectRatio(VM.VideoView.Video_AspectRatio_SelectedItem),

                            "\r\n" +
                            Video.Video.Images(VM.FormatView.Format_MediaType_SelectedItem,
                                               VM.VideoView.Video_Codec_SelectedItem
                                               ),
                            "\r\n" +
                            Streams.VideoStreamMaps(),
                        };
                    }
                    // Disable Video
                    else
                    {
                        videoList = new List <string>()
                        {
                            "\r\n\r\n" +
                            "-vn",
                        };
                    }

                    // -------------------------
                    // Audio
                    // -------------------------
                    // Log Console Message /////////
                    Log.WriteAction = () =>
                    {
                        Log.logParagraph.Inlines.Add(new LineBreak());
                        Log.logParagraph.Inlines.Add(new LineBreak());
                        Log.logParagraph.Inlines.Add(new Bold(new Run("Audio"))
                        {
                            Foreground = Log.ConsoleAction
                        });
                    };
                    Log.LogActions.Add(Log.WriteAction);

                    IEnumerable <string> audioList = new List <string>();

                    if (VM.FormatView.Format_MediaType_SelectedItem != "Image" &&
                        VM.FormatView.Format_MediaType_SelectedItem != "Sequence" &&
                        VM.AudioView.Audio_Codec_SelectedItem != "None" &&
                        VM.AudioView.Audio_Stream_SelectedItem != "none" &&
                        VM.AudioView.Audio_Quality_SelectedItem != "None" &&
                        VM.AudioView.Audio_Quality_SelectedItem != "Mute"
                        )
                    {
                        audioList = new List <string>()
                        {
                            "\r\n\r\n" +
                            Audio.Codec.AudioCodec(VM.AudioView.Audio_Codec_SelectedItem,
                                                   VM.AudioView.Audio_Codec
                                                   ),
                            "\r\n" +
                            Audio.Quality.AudioQuality(VM.MainView.Input_Text,
                                                       VM.MainView.Batch_IsChecked,
                                                       VM.FormatView.Format_MediaType_SelectedItem,
                                                       VM.AudioView.Audio_Stream_SelectedItem,
                                                       VM.AudioView.Audio_Codec_SelectedItem,
                                                       VM.AudioView.Audio_Quality_Items,
                                                       VM.AudioView.Audio_Quality_SelectedItem,
                                                       VM.AudioView.Audio_BitRate_Text,
                                                       (bool)VM.AudioView.Audio_VBR_IsChecked
                                                       ),
                            Audio.Quality.CompressionLevel(VM.AudioView.Audio_Codec_SelectedItem,
                                                           VM.AudioView.Audio_CompressionLevel_SelectedItem
                                                           ),
                            Audio.Quality.SampleRate(VM.AudioView.Audio_Codec_SelectedItem,
                                                     VM.AudioView.Audio_SampleRate_Items,
                                                     VM.AudioView.Audio_SampleRate_SelectedItem
                                                     ),
                            Audio.Quality.BitDepth(VM.AudioView.Audio_Codec_SelectedItem,
                                                   VM.AudioView.Audio_BitDepth_Items,
                                                   VM.AudioView.Audio_BitDepth_SelectedItem
                                                   ),
                            Audio.Channels.Channel(VM.AudioView.Audio_Codec_SelectedItem,
                                                   VM.AudioView.Audio_Channel_SelectedItem
                                                   ),
                            "\r\n" +
                            Filters.Audio.AudioFilter(),
                            "\r\n" +
                            Streams.AudioStreamMaps(),

                            "\r\n\r\n" +
                            Audio.Metadata.Audio(),
                        };
                    }
                    // Disable Audio
                    else
                    {
                        audioList = new List <string>()
                        {
                            "\r\n\r\n" +
                            "-an",
                        };
                    }

                    // -------------------------
                    // Subtitle
                    // -------------------------
                    // Log Console Message /////////
                    Log.WriteAction = () =>
                    {
                        Log.logParagraph.Inlines.Add(new LineBreak());
                        Log.logParagraph.Inlines.Add(new LineBreak());
                        Log.logParagraph.Inlines.Add(new Bold(new Run("Subtitle"))
                        {
                            Foreground = Log.ConsoleAction
                        });
                    };
                    Log.LogActions.Add(Log.WriteAction);

                    IEnumerable <string> subtitleList = new List <string>();

                    if (VM.FormatView.Format_MediaType_SelectedItem != "Audio" &&
                        VM.VideoView.Video_Codec_SelectedItem != "None" &&
                        VM.VideoView.Video_Quality_SelectedItem != "None"
                        )
                    {
                        subtitleList = new List <string>()
                        {
                            "\r\n\r\n" +
                            Subtitle.Subtitle.SubtitleCodec(VM.SubtitleView.Subtitle_Codec_SelectedItem,
                                                            VM.SubtitleView.Subtitle_Codec
                                                            ),
                            "\r\n" +
                            Streams.SubtitleMaps(),

                            "\r\n\r\n" +
                            Subtitle.Metadata.Subtitles(),
                        };
                    }
                    // Disable Subtitles
                    else
                    {
                        subtitleList = new List <string>()
                        {
                            "\r\n\r\n" +
                            "-sn",
                        };
                    }

                    // -------------------------
                    // Chapters
                    // -------------------------
                    // Log Console Message /////////
                    Log.WriteAction = () =>
                    {
                        Log.logParagraph.Inlines.Add(new LineBreak());
                        Log.logParagraph.Inlines.Add(new LineBreak());
                        Log.logParagraph.Inlines.Add(new Bold(new Run("Chapters"))
                        {
                            Foreground = Log.ConsoleAction
                        });
                    };
                    Log.LogActions.Add(Log.WriteAction);

                    IEnumerable <string> chaptersList = new List <string>();

                    if (VM.FormatView.Format_MediaType_SelectedItem != "Image" &&
                        VM.FormatView.Format_MediaType_SelectedItem != "Sequence"
                        )
                    {
                        chaptersList = new List <string>()
                        {
                            "\r\n\r\n" +
                            Streams.ChaptersMaps(),
                        };
                    }
                    // Disable Chapters
                    //else
                    //{
                    //    chaptersList = new List<string>()
                    //    {
                    //        "\r\n\r\n" +
                    //        "-cn",
                    //    };
                    //}

                    // -------------------------
                    // Output
                    // -------------------------
                    IEnumerable <string> outputList = new List <string>()
                    {
                        "\r\n\r\n" +
                        Streams.FormatMaps(),

                        "\r\n\r\n" +
                        Format.ForceFormat(VM.FormatView.Format_Container_SelectedItem),

                        "\r\n\r\n" +
                        MainWindow.ThreadDetect(),

                        "\r\n\r\n" +
                        MainWindow.WrapWithQuotes(MainWindow.OutputPath()),
                    };


                    // --------------------------------------------------
                    // Combine Lists
                    // --------------------------------------------------
                    // -------------------------
                    // FFmpeg Arguments
                    // -------------------------
                    IEnumerable <string> FFmpegArgs_SinglePass_List = optionsList
                                                                      .Concat(hwAccelDecodeList)
                                                                      .Concat(inputList)
                                                                      .Concat(hwAccelTranscodeList)
                                                                      .Concat(formatList)
                                                                      .Concat(videoList)
                                                                      .Concat(audioList)
                                                                      .Concat(subtitleList)
                                                                      .Concat(chaptersList)
                                                                      .Concat(outputList)
                                                                      .ToList();

                    // -------------------------
                    // Shell Arguments
                    // -------------------------
                    IEnumerable <string> ShellArgs_List = // Process Priority
                                                          Sys.Shell.ProcessPriority_PowerShell_Set(
                        // FFmpeg Init
                        ffmpegInitializeList
                        // FFmpeg PowerShell -ArgsList
                        .Concat(Sys.Shell.ProcessPriority_PowerShell_ArgumentsListWrap(
                                    // FFmpeg Arguments
                                    FFmpegArgs_SinglePass_List
                                    )
                                )
                        )
                                                          .ToList();

                    // Join List with Spaces
                    // Remove: Empty, Null, Line Breaks
                    Video.Quality.passSingle = string.Join(" ", ShellArgs_List
                                                           .Where(s => !string.IsNullOrWhiteSpace(s))
                                                           .Where(s => !s.Equals(Environment.NewLine))
                                                           .Where(s => !s.Equals("\r\n\r\n"))
                                                           .Where(s => !s.Equals("\r\n"))
                                                           .Where(s => !s.Equals("\n"))
                                                           .Where(s => !s.Equals("\u2028"))
                                                           .Where(s => !s.Equals("\u000A"))
                                                           .Where(s => !s.Equals("\u000B"))
                                                           .Where(s => !s.Equals("\u000C"))
                                                           .Where(s => !s.Equals("\u000D"))
                                                           .Where(s => !s.Equals("\u0085"))
                                                           .Where(s => !s.Equals("\u2028"))
                                                           .Where(s => !s.Equals("\u2029"))
                                                           );
                }


                // Return Value
                return(Video.Quality.passSingle);
            }
Example #39
0
        /// <summary>
        /// Wrap input geometry into module cages.
        /// </summary>
        /// <param name="DA">The DA object can be used to retrieve data from
        ///     input parameters and to store data in output parameters.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var modules    = new List <Module>();
            var allowed    = new List <Rule>();
            var disallowed = new List <Rule>();

            if (!DA.GetDataList(0, modules))
            {
                return;
            }

            if (!DA.GetDataList(1, allowed))
            {
                return;
            }

            DA.GetDataList(2, disallowed);

            var modulesClean = new List <Module>();

            foreach (var module in modules)
            {
                if (module == null || !module.IsValid)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "The module is null or invalid.");
                }
                else
                {
                    modulesClean.Add(module);
                }
            }

            Module.GenerateEmptySingleModule(Config.OUTER_MODULE_NAME,
                                             Config.INDIFFERENT_TAG,
                                             new Rhino.Geometry.Vector3d(1, 1, 1),
                                             out var moduleOut,
                                             out var rulesOut);

            var allowedClean = allowed.Concat(
                rulesOut.Select(ruleExplicit => new Rule(ruleExplicit))
                );

            modulesClean.Add(moduleOut);


            if (allowed.Any(rule => rule == null || !rule.IsValid))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error,
                                  "Some of the allowed Rules are null or invalid.");
            }

            var allowedOriginalClean = allowedClean
                                       .Where(rule => rule.IsValidWithModules(modulesClean))
                                       .Distinct();

            if (disallowed == null || !disallowed.Any())
            {
                var earlyRules = allowedOriginalClean.ToList();
                earlyRules.Sort();
                DA.SetDataList(0, earlyRules);
                return;
            }

            if (disallowed.Any(rule => rule == null || !rule.IsValid))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error,
                                  "Some of the disallowed rules are null or invalid.");
            }

            var allowedExplicit = allowedOriginalClean
                                  .Where(rule => rule.IsExplicit)
                                  .Select(rule => rule.Explicit)
                                  .ToList();
            var allowedTyped = allowedOriginalClean
                               .Where(rule => rule.IsTyped)
                               .Select(rule => rule.Typed);

            var disallowedOriginalClean = disallowed
                                          .Where(rule => rule.IsValidWithModules(modulesClean))
                                          .Distinct();

            var disallowedExplicit = disallowedOriginalClean
                                     .Where(rule => rule.IsExplicit)
                                     .Select(rule => rule.Explicit)
                                     .ToList();
            var disallowedTyped = disallowedOriginalClean
                                  .Where(rule => rule.IsTyped)
                                  .Select(rule => rule.Typed);

            var allTypedRules = allowedTyped.Concat(disallowedTyped);

            var allTypedByType = new Dictionary <string, List <RuleTyped> >();

            foreach (var rule in allTypedRules)
            {
                var type = rule.ConnectorType;
                if (allTypedByType.ContainsKey(type))
                {
                    allTypedByType[type].Add(rule);
                }
                else
                {
                    allTypedByType.Add(type, new List <RuleTyped>()
                    {
                        rule
                    });
                }
            }

            var disallowedTypedByType = new Dictionary <string, List <RuleTyped> >();

            foreach (var rule in disallowedTyped)
            {
                var type = rule.ConnectorType;
                if (disallowedTypedByType.ContainsKey(type))
                {
                    disallowedTypedByType[type].Add(rule);
                }
                else
                {
                    disallowedTypedByType.Add(type, new List <RuleTyped>()
                    {
                        rule
                    });
                }
            }

            // unwrap disallowed typed rules and add them to disallowedExplicit
            foreach (var entry in allTypedByType)
            {
                var type  = entry.Key;
                var rules = entry.Value;
                if (disallowedTypedByType.ContainsKey(type))
                {
                    var rulesExplicit   = rules.SelectMany(rule => rule.ToRulesExplicit(rules, modulesClean));
                    var disallowedRules = disallowedTypedByType[type];
                    foreach (var rule in rulesExplicit)
                    {
                        if (disallowedRules.Any(disallowedRule =>
                                                (disallowedRule.ModuleName == rule.SourceModuleName &&
                                                 disallowedRule.ConnectorIndex == rule.SourceConnectorIndex) ||
                                                (disallowedRule.ModuleName == rule.TargetModuleName &&
                                                 disallowedRule.ConnectorIndex == rule.TargetConnectorIndex)))
                        {
                            disallowedExplicit.Add(rule);
                        }
                    }
                }
            }

            // unwrap all typed rules
            foreach (var rule in allTypedRules)
            {
                var rulesExplicit = rule.ToRulesExplicit(allTypedRules, modulesClean);
                allowedExplicit.AddRange(rulesExplicit);
            }

            var finalExplicit = new List <RuleExplicit>();

            foreach (var rule in allowedExplicit)
            {
                if (!disallowedExplicit.Any(disallowedRule => disallowedRule.Equals(rule)))
                {
                    finalExplicit.Add(rule);
                }
            }

            var outputRules = finalExplicit
                              .Where(rule => !(rule.SourceModuleName == Config.OUTER_MODULE_NAME && rule.TargetModuleName == Config.OUTER_MODULE_NAME))
                              .Distinct()
                              .Select(explicitRule => new Rule(explicitRule))
                              .ToList();

            outputRules.Sort();

            foreach (var rule in outputRules)
            {
                if (!rule.IsValid)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, rule.IsValidWhyNot);
                }
            }

            DA.SetDataList(0, outputRules);
        }
 private IEnumerable <PtInfo> GetAllVisibleTrackers()
 {
     return(m_FilteredTrackers.Concat(m_PinnedTrackers));
 }
Example #41
0
        /// <summary>
        /// Fills the CurrentItems property for display in ItemsControl
        /// based view (ListBox, ListView etc.)
        ///
        /// This version is parameterized since the filterstring can be parsed
        /// seperately and does not need to b parsed each time when this method
        /// executes.
        /// </summary>

        /*
         * internal static Response GetSubFolderItems(string[] filterString,
         *                                          bool IsFiltered,
         *                                          PathModel folder,
         *                                          bool showfolders,
         *                                          bool showHidden,
         *                                          bool showFiles)
         *      {
         *          List<Base.FileSystemModel> ret = new List<Base.FileSystemModel>();
         *
         *
         *          if (folder == null)
         *              return new Response("internal error");
         *
         *          if (folder.DirectoryPathExists() == false)
         *              return new Response(string.Format("'{0}' is not accessible.", folder.Path ));
         *
         *  try
         *  {
         *              DirectoryInfo cur = new DirectoryInfo(folder.Path);
         *
         *              // Retrieve and add (filtered) list of directories
         *              if (showfolders == true)
         *              {
         *                  string[] directoryFilter = null;
         *
         *                  //// if (filterString != null)
         *                  ////  directoryFilter = new ArrayList(filterString).ToArray() as string[];
         *                  directoryFilter = null;
         *
         *                  foreach (DirectoryInfo dir in SelectDirectoriesByFilter(cur, directoryFilter))
         *                  {
         *                      if (dir.Attributes.HasFlag(FileAttributes.Hidden) == true)
         *                      {
         *                          if (showHidden == false)
         *                          {
         *                              if ((dir.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
         *                                  continue;
         *                          }
         *                      }
         *
         *                      FolderModel info = new FolderModel(new PathModel(dir.FullName, FSItemType.Folder));
         *
         *                      ret.Add(info);
         *                  }
         *              }
         *
         *              if (showFiles == true)
         *              {
         *                  if (IsFiltered == false) // Do not apply the filter if it is not enabled
         *                      filterString = null;
         *
         *                  // Retrieve and add (filtered) list of files in current directory
         *                  foreach (FileInfo f in SelectFilesByFilter(cur, filterString))
         *                  {
         *                      if (showHidden == false)
         *                      {
         *                          if (f.Attributes.HasFlag(FileAttributes.Hidden) == true)
         *                          {
         *                              if ((f.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
         *                                  continue;
         *                          }
         *                      }
         *
         *                      FileModel info = new FileModel(new PathModel(f.FullName, FSItemType.File));
         *
         *                      ret.Add(info);
         *                  }
         *              }
         *          }
         *          catch
         *          {
         *              return new Response("internal error");
         *          }
         *
         *          return new Response(ResponseType.Data, ret);
         *      }
         */
        /// <summary>
        /// Method implements an extension that lets us filter files
        /// with multiple filter aruments.
        /// </summary>
        /// <param name="dir">Points at the folder that is queried for files and folder entries.</param>
        /// <param name="extensions">Contains the extension that we want to filter for, eg: string[]{"*.*"} or string[]{"*.tex", "*.txt"}</param>
        public static IEnumerable <FileInfo> SelectFilesByFilter(DirectoryInfo dir,
                                                                 params string[] extensions)
        {
            if (dir.Exists == false)
            {
                yield break;
            }

            IEnumerable <FileSystemInfo> matches = new List <FileSystemInfo>();

            if (extensions == null)
            {
                try
                {
                    matches = dir.EnumerateFiles("*.*", SearchOption.TopDirectoryOnly);
                }
                catch
                {
                    yield break;
                }

                foreach (var file in matches)
                {
                    if (file as FileInfo != null)
                    {
                        yield return(file as FileInfo);
                    }
                }

                yield break;
            }

            List <string> patterns = new List <string>(extensions);

            try
            {
                foreach (var pattern in patterns)
                {
                    matches = matches.Concat(dir.EnumerateFiles(pattern, SearchOption.TopDirectoryOnly));
                }
            }
            catch (UnauthorizedAccessException)
            {
                Console.WriteLine("Unable to access '{0}'. Skipping...", dir.FullName);
                yield break;
            }
            catch (PathTooLongException ptle)
            {
                Console.WriteLine(@"Could not process path '{0}\{1} ({2})'.", dir.Parent.FullName, dir.Name, ptle.Message);
                yield break;
            }


            ////      try
            ////      {
            ////        foreach (var pattern in patterns)
            ////        {
            ////          matches = matches.Concat(dir.EnumerateFiles(pattern, SearchOption.TopDirectoryOnly));
            ////        }
            ////      }
            ////      catch (UnauthorizedAccessException)
            ////      {
            ////        Console.WriteLine("Unable to access '{0}'. Skipping...", dir.FullName);
            ////        yield break;
            ////      }
            ////      catch (PathTooLongException ptle)
            ////      {
            ////        Console.WriteLine(@"Could not process path '{0}\{1} ({2})'.", dir.Parent.FullName, dir.Name, ptle.Message);
            ////        yield break;
            ////      }
            ////
            ////      Console.WriteLine("Returning all objects that match the pattern(s) '{0}'", string.Join(",", patterns));

            foreach (var file in matches)
            {
                if (file as FileInfo != null)
                {
                    yield return(file as FileInfo);
                }
            }
        }
Example #42
0
 private void CalculateStringCounts()
 {
     CalculatePixelsPerString();
     MaxPixelsPerString = StringPixelCounts.Concat(new[] { 0 }).Max();
     StringCount        = CalculateMaxStringCount();
 }
Example #43
0
    private async Task MvcTemplateCore(string languageOverride, string[] args = null)
    {
        var project = await ProjectFactory.CreateProject(Output);

        var createResult = await project.RunDotNetNewAsync("mvc", language : languageOverride, args : args);

        Assert.True(0 == createResult.ExitCode, ErrorMessages.GetFailedProcessMessage("create/restore", project, createResult));

        var noHttps = args?.Contains(ArgConstants.NoHttps) ?? false;
        var expectedLaunchProfileNames = noHttps
            ? new[] { "http", "IIS Express" }
            : new[] { "http", "https", "IIS Express" };
        await project.VerifyLaunchSettings(expectedLaunchProfileNames);

        var projectExtension    = languageOverride == "F#" ? "fsproj" : "csproj";
        var projectFileContents = project.ReadFile($"{project.ProjectName}.{projectExtension}");

        Assert.DoesNotContain(".db", projectFileContents);
        Assert.DoesNotContain("Microsoft.EntityFrameworkCore.Tools", projectFileContents);
        Assert.DoesNotContain("Microsoft.VisualStudio.Web.CodeGeneration.Design", projectFileContents);
        Assert.DoesNotContain("Microsoft.EntityFrameworkCore.Tools.DotNet", projectFileContents);
        Assert.DoesNotContain("Microsoft.Extensions.SecretManager.Tools", projectFileContents);

        // Avoid the F# compiler. See https://github.com/dotnet/aspnetcore/issues/14022
        if (languageOverride != null)
        {
            return;
        }

        var publishResult = await project.RunDotNetPublishAsync();

        Assert.True(0 == publishResult.ExitCode, ErrorMessages.GetFailedProcessMessage("publish", project, publishResult));

        // Run dotnet build after publish. The reason is that one uses Config = Debug and the other uses Config = Release
        // The output from publish will go into bin/Release/netcoreappX.Y/publish and won't be affected by calling build
        // later, while the opposite is not true.

        var buildResult = await project.RunDotNetBuildAsync();

        Assert.True(0 == buildResult.ExitCode, ErrorMessages.GetFailedProcessMessage("build", project, buildResult));

        IEnumerable <string> menuLinks = new List <string> {
            PageUrls.HomeUrl,
            PageUrls.HomeUrl,
            PageUrls.PrivacyFullUrl
        };

        var footerLinks = new string[] { PageUrls.PrivacyFullUrl };

        var pages = new List <Page>
        {
            new Page
            {
                Url   = PageUrls.HomeUrl,
                Links = menuLinks.Append(PageUrls.DocsUrl).Concat(footerLinks)
            },
            new Page
            {
                Url   = PageUrls.PrivacyFullUrl,
                Links = menuLinks.Concat(footerLinks)
            }
        };

        using (var aspNetProcess = project.StartBuiltProjectAsync())
        {
            Assert.False(
                aspNetProcess.Process.HasExited,
                ErrorMessages.GetFailedProcessMessageOrEmpty("Run built project", project, aspNetProcess.Process));

            await aspNetProcess.AssertPagesOk(pages);
        }

        using (var aspNetProcess = project.StartPublishedProjectAsync())
        {
            Assert.False(
                aspNetProcess.Process.HasExited,
                ErrorMessages.GetFailedProcessMessageOrEmpty("Run published project", project, aspNetProcess.Process));

            await aspNetProcess.AssertPagesOk(pages);
        }
    }
Example #44
0
        public void RunTestJobs(string jobName = "")
        {
            if (jobName != "")
            {
                JobName = jobName;
            }

            // Unpack jobs
            var JobNames         = new List <string>();
            var JobAssemblySpecs = new List <string>();
            var JobCategories    = new List <string>();

            if (!string.IsNullOrEmpty(JobName) && string.IsNullOrEmpty(MergeDotCoverSnapshotsInDirectory))
            {
                foreach (var Job in JobName.Split(','))
                {
                    var TrimJobName = Job.TrimEnd('1', '2', '3', '4', '5', '6', '7', '8', '9', '0', ' ');
                    if (JobSpecs.ContainsKey(TrimJobName))
                    {
                        JobNames.Add(TrimJobName);
                        if (JobSpecs[TrimJobName].Item2 == null)
                        {
                            JobAssemblySpecs.Add(JobSpecs[TrimJobName].Item1);
                            JobCategories.Add("");
                        }
                        else
                        {
                            JobAssemblySpecs.Add(JobSpecs[Job].Item1);
                            JobCategories.Add(JobSpecs[Job].Item2);
                        }
                    }
                    else
                    {
                        Console.WriteLine($"Unrecognized Job {Job} was ignored from the run");
                    }
                }
            }
            if (!string.IsNullOrEmpty(ProjectName))
            {
                JobNames.Add(ProjectName);
                JobAssemblySpecs.Add(ProjectName);
                if (!string.IsNullOrEmpty(Category))
                {
                    JobCategories.Add(Category);
                }
                else
                {
                    JobCategories.Add("");
                }
            }
            if (!File.Exists(TestRunner.Path))
            {
                throw new ArgumentException("Error cannot find VSTest.console.exe or MSTest.exe. Use either --VSTestPath or --MSTestPath parameters to pass paths to one of those files.");
            }

            if (ApplyDotCover && DotCoverPath != "" && !(File.Exists(DotCoverPath)))
            {
                throw new ArgumentException("Error cannot find dotcover.exe. Use --DotCoverPath parameter to pass a path to that file.");
            }

            if (!string.IsNullOrEmpty(DoServerStart) || !string.IsNullOrEmpty(DoStudioStart))
            {
                InstallServer();
            }

            TestRunner.ReadPlaylist();

            for (var i = 0; i < JobNames.Count; i++)
            {
                var ThisJobName               = JobNames[i].ToString();
                var ProjectSpec               = JobAssemblySpecs[i].ToString();
                var TestCategories            = JobCategories[i].ToString();
                var TestAssembliesList        = "";
                var TestAssembliesDirectories = new List <string>();
                if (!TestRunner.TestsPath.EndsWith("\\"))
                {
                    TestRunner.TestsPath += "\\";
                }
                foreach (var Project in ProjectSpec.Split(','))
                {
                    Tuple <string, List <string> > UnPackTestAssembliesListAndDirectories = ResolveTestAssemblyFileSpecs(TestRunner.TestsPath + Project + ".dll");
                    TestAssembliesList += UnPackTestAssembliesListAndDirectories.Item1;
                    if (UnPackTestAssembliesListAndDirectories.Item2.Count > 0)
                    {
                        TestAssembliesDirectories = TestAssembliesDirectories.Concat(UnPackTestAssembliesListAndDirectories.Item2).ToList();
                    }
                    if (TestAssembliesList == "")
                    {
                        UnPackTestAssembliesListAndDirectories = ResolveProjectFolderSpecs(TestRunner.TestsPath + Project);
                        TestAssembliesList += UnPackTestAssembliesListAndDirectories.Item1;
                        if (UnPackTestAssembliesListAndDirectories.Item2.Count > 0)
                        {
                            TestAssembliesDirectories = TestAssembliesDirectories.Concat(UnPackTestAssembliesListAndDirectories.Item2).ToList();
                        }
                    }
                }
                if (string.IsNullOrEmpty(TestAssembliesList))
                {
                    throw new Exception($"Cannot find any {ProjectSpec} project folders or assemblies at {TestRunner.TestsPath}.");
                }

                // Setup for screen recording
                var TestSettingsFile = ScreenRecordingTestSettingsFile(ThisJobName);

                string TestRunnerPath = TestRunner.WriteTestRunner(ThisJobName, ProjectSpec, TestCategories, TestAssembliesList, TestSettingsFile, TestRunner.TestsResultsPath, RecordScreen != null, JobSpecs);

                string TrxFile;
                if (string.IsNullOrEmpty(RetryFile))
                {
                    //Run Tests
                    TrxFile = RunTests(JobName, TestAssembliesList, TestAssembliesDirectories, TestSettingsFile, TestRunnerPath);
                }
                else
                {
                    TrxFile = RetryFile;
                }
                if (!string.IsNullOrEmpty(TrxFile))
                {
                    //Re-try Failures
                    for (var count = 0; count < RetryCount; count++)
                    {
                        RetryTestFailures(ThisJobName, TestAssembliesList, TestAssembliesDirectories, TestSettingsFile, TrxFile, count + 1);
                    }
                }
            }
            if (ApplyDotCover && JobName.Split(',').Count() > 1)
            {
                MergeDotCoverSnapshots();
            }
        }
Example #45
0
        /// <summary>
        /// Create the categorised nodes, including the Categories and Dataflows
        /// </summary>
        /// <param name="categories">
        /// The list of CategorySchemes
        /// </param>
        /// <param name="categorisedDataflowIndex">
        /// A dictionary with a string with the format "Agency+Id+Version", <see cref="Utils.MakeKey(RefBean)"/> to DataflowBean map
        /// </param>
        /// <returns>
        /// The create categorised nodes.
        /// The tree with the categorized nodes
        /// </returns>
        private IEnumerable <JsTreeNode> CreateCategorisedNodes(
            IEnumerable <ICategorySchemeObject> categories, IDictionary <string, IDataflowObject> categorisedDataflowIndex)
        {
            int categoryCount       = 0;
            var categorySchemeNodes = new List <JsTreeNode>();
            var childToParent       = new Dictionary <JsTreeNode, JsTreeNode>();
            var leafCategories      = new Queue <JsTreeNode>();

            foreach (ICategorySchemeObject categoryScheme in categories)
            {
                JsTreeNode categorySchemeNode = CreateCategorySchemeNode(categoryScheme);
                categorySchemeNodes.Add(categorySchemeNode);
                var remainingCategoryNodes = new Stack <JsTreeNode>();
                var remainingCategories    = new Stack <ICategoryObject>();

                IList <ICategoryObject> categoriesWithAnnotation    = new List <ICategoryObject>();
                IList <ICategoryObject> categoriesWithoutAnnotation = new List <ICategoryObject>();

                /*foreach (var category in categoryScheme.Items)
                 * {
                 *  if (category.Annotations.Count > 0 && category.Annotations[0].FromAnnotation() == CustomAnnotationType.CategorySchemeNodeOrder)
                 *  {
                 *      categoriesWithAnnotation.Add(category);
                 *  }
                 *  else
                 *  {
                 *      categoriesWithoutAnnotation.Add(category);
                 *  }
                 * }*/

                IEnumerable <ICategoryObject> categoriesWithAnnotationOrderedBy = categoriesWithAnnotation.OrderBy(category => Convert.ToInt64(category.Annotations[0].ValueFromAnnotation()));

                IEnumerable <ICategoryObject> categoriesWithAndWithoutAnnotations = categoriesWithoutAnnotation.Concat(categoriesWithAnnotationOrderedBy);

                foreach (ICategoryObject c in categoriesWithAndWithoutAnnotations)
                {
                    JsTreeNode parent = CreateCategoryNode(c, ref categoryCount);

                    categorySchemeNode.children.Add(parent);
                    remainingCategoryNodes.Push(parent);
                    remainingCategories.Push(c);
                    childToParent.Add(parent, categorySchemeNode);
                }

                while (remainingCategoryNodes.Count > 0)
                {
                    JsTreeNode      currentNode     = remainingCategoryNodes.Pop();
                    ICategoryObject currentCategory = remainingCategories.Pop();

                    IList <ICategoryObject> categoriesParentWithAnnotation    = new List <ICategoryObject>();
                    IList <ICategoryObject> categoriesParentWithoutAnnotation = new List <ICategoryObject>();

                    foreach (var category in currentCategory.Items)
                    {
                        if (category.Annotations.Count > 0 && category.Annotations[0].FromAnnotation() == CustomAnnotationType.CategorySchemeNodeOrder)
                        {
                            categoriesParentWithAnnotation.Add(category);
                        }
                        else
                        {
                            categoriesParentWithoutAnnotation.Add(category);
                        }
                    }

                    IEnumerable <ICategoryObject> categoriesParentWithAnnotationOrderedBy = categoriesParentWithAnnotation.OrderBy(category => Convert.ToInt64(category.Annotations[0].ValueFromAnnotation()));

                    IEnumerable <ICategoryObject> categoriesParentWithAndWithoutAnnotations = categoriesParentWithoutAnnotation.Concat(categoriesParentWithAnnotationOrderedBy);

                    foreach (ICategoryObject cc in categoriesParentWithAndWithoutAnnotations)
                    {
                        JsTreeNode childNode = CreateCategoryNode(cc, ref categoryCount);
                        remainingCategoryNodes.Push(childNode);
                        remainingCategories.Push(cc);

                        currentNode.children.Add(childNode);
                        childToParent.Add(childNode, currentNode);
                    }

                    foreach (IMaintainableRefObject dataflowRef in GetDataFlows(currentCategory, _categorisations))
                    {
                        string          key = "";// Utils.MakeKey(dataflowRef);
                        IDataflowObject dataflow;
                        if (categorisedDataflowIndex.TryGetValue(key, out dataflow))
                        {
                            JsTreeNode dataflowNode = CreateDataflowNode(dataflow);
                            currentNode.children.Add(dataflowNode);
                        }
                    }

                    if (currentNode.children.Count == 0)
                    {
                        leafCategories.Enqueue(currentNode);
                    }
                }
            }

            while (leafCategories.Count > 0)
            {
                JsTreeNode current = leafCategories.Dequeue();
                JsTreeNode parent;
                if (childToParent.TryGetValue(current, out parent))
                {
                    parent.children.Remove(current);
                    if (parent.children.Count == 0)
                    {
                        leafCategories.Enqueue(parent);
                    }
                }
                else
                {
                    categorySchemeNodes.Remove(current);
                }
            }

            return(categorySchemeNodes);
        }
        void SyncBuildProject(Dictionary <string, MSBuildItem> currentItems, MSBuildEngine e, object project)
        {
            evaluatedItemsIgnoringCondition.Clear();
            evaluatedItems.Clear();

            if (!OnlyEvaluateProperties)
            {
                var evalItems = new Dictionary <string, MSBuildItemEvaluated> ();
                foreach (var it in e.GetEvaluatedItems(project))
                {
                    var xit = it as MSBuildItemEvaluated;
                    if (xit == null)
                    {
                        xit = CreateEvaluatedItem(e, it);
                        var itemId = e.GetItemMetadata(it, NodeIdPropertyName);
                        var key    = itemId + " " + xit.Include;
                        if (evalItems.ContainsKey(key))
                        {
                            continue;                             // xbuild seems to return duplicate items when using wildcards. This is a workaround to avoid the duplicates.
                        }
                        MSBuildItem pit;
                        if (!string.IsNullOrEmpty(itemId) && currentItems.TryGetValue(itemId, out pit))
                        {
                            xit.AddSourceItem(pit);
                            xit.Condition   = pit.Condition;
                            evalItems [key] = xit;
                        }
                    }
                    evaluatedItems.Add(xit);
                }

                var evalItemsNoCond = new Dictionary <string, MSBuildItemEvaluated> ();
                foreach (var it in e.GetEvaluatedItemsIgnoringCondition(project))
                {
                    var xit = it as MSBuildItemEvaluated;
                    if (xit == null)
                    {
                        xit = CreateEvaluatedItem(e, it);
                        var itemId = e.GetItemMetadata(it, NodeIdPropertyName);
                        MSBuildItemEvaluated evItem;
                        var key = itemId + " " + xit.Include;
                        if (evalItemsNoCond.ContainsKey(key))
                        {
                            continue;                             // xbuild seems to return duplicate items when using wildcards. This is a workaround to avoid the duplicates.
                        }
                        if (!string.IsNullOrEmpty(itemId) && evalItems.TryGetValue(key, out evItem))
                        {
                            evaluatedItemsIgnoringCondition.Add(evItem);
                            evalItemsNoCond [key] = evItem;
                            continue;
                        }
                        MSBuildItem pit;
                        if (!string.IsNullOrEmpty(itemId) && currentItems.TryGetValue(itemId, out pit))
                        {
                            xit.AddSourceItem(pit);
                            xit.Condition         = pit.Condition;
                            evalItemsNoCond [key] = xit;
                        }
                    }
                    evaluatedItemsIgnoringCondition.Add(xit);
                }

                // Clear the node id metadata
                foreach (var it in evaluatedItems.Concat(evaluatedItemsIgnoringCondition))
                {
                    ((MSBuildPropertyGroupEvaluated)it.Metadata).RemoveProperty(NodeIdPropertyName);
                }

                targets = e.GetTargets(project).ToArray();
                targetsIgnoringCondition = e.GetTargetsIgnoringCondition(project).ToArray();
            }

            var props = new MSBuildEvaluatedPropertyCollection(msproject);

            evaluatedProperties = props;
            props.SyncCollection(e, project);

            conditionedProperties = engine.GetConditionedProperties(project);
        }
Example #47
0
        static void Main(string[] args)
        {
            string fileName = @"C:\Users\wolfg\source\repos\AdventofCode2020\AdventofCode-16\input-16.txt";

            System.IO.StreamReader file         = new System.IO.StreamReader(fileName);
            List <string>          column_names = new List <string>();
            List <Tuple <Tuple <int, int>, Tuple <int, int> > > stats = new List <Tuple <Tuple <int, int>, Tuple <int, int> > >();
            List <int>         invalid     = new List <int>();
            List <List <int> > good_values = new List <List <int> >();
            List <int>         my_ticket   = new List <int>();

            string   line;
            RuleType type = RuleType.invalid;

            Console.WriteLine(fileName);
            Console.WriteLine(file);

            while ((line = file.ReadLine()) != null)
            {
                if (string.IsNullOrEmpty(line))
                {
                    continue;
                }

                if (line.Contains("or"))
                {
                    type = RuleType.stat;
                }
                else if (line.StartsWith("your ticket:"))
                {
                    type = RuleType.your;
                }
                else if (line.StartsWith("nearby tickets:"))
                {
                    type = RuleType.others;
                }

                switch (type)
                {
                case RuleType.stat:
                    Console.WriteLine(line);
                    string[]         data      = line.Split(":");
                    string[]         limits    = data[1].Split("or");
                    string[]         limit1    = limits[0].Split("-");
                    string[]         limit2    = limits[1].Split("-");
                    Tuple <int, int> limit1int = new Tuple <int, int>(int.Parse(limit1[0]), int.Parse(limit1[1]));
                    Tuple <int, int> limit2int = new Tuple <int, int>(int.Parse(limit2[0]), int.Parse(limit2[1]));
                    stats.Add(new Tuple <Tuple <int, int>, Tuple <int, int> >(limit1int, limit2int));
                    column_names.Add(data[0]);
                    break;

                case RuleType.your:
                    Console.WriteLine(line);
                    if (line.Contains(","))
                    {
                        string[]   yourdata = line.Split(",");
                        List <int> values   = new List <int>();
                        foreach (string value in yourdata)
                        {
                            values.Add(int.Parse(value));
                        }
                        my_ticket = values;
                        invalid.Concat(validate_numbers(values, stats));
                    }
                    break;

                case RuleType.others:
                    Console.WriteLine(line);
                    if (line.Contains(","))
                    {
                        string[]   otherdata = line.Split(",");
                        List <int> values    = new List <int>();
                        foreach (string value in otherdata)
                        {
                            values.Add(int.Parse(value));
                        }
                        List <int> invalids = validate_numbers(values, stats);
                        invalid = invalid.Concat(invalids).ToList();
                        if (invalids.Count == 0)
                        {
                            good_values.Add(values);
                        }
                    }
                    break;

                case RuleType.invalid:
                default:
                    throw new Exception();
                }
            }

            int error_rate = 0;

            foreach (int error in invalid)
            {
                error_rate += error;
            }
            Console.WriteLine($"Ticket Scanning Error Rate: {error_rate}");

            /* PART 2 */

            // Is the position valid for the field
            var positions = valid_positions(good_values, stats);
            // Solve such that a single position is left true for each field
            var solved_positions = solve_positions(positions);

            print_positions(stats, column_names, positions);
            print_positions(stats, column_names, solved_positions);
            List <int> fields      = find_positions("departure", column_names, solved_positions);
            long       accumulator = 1;

            foreach (int field in fields)
            {
                Console.WriteLine($"Departure Field: {field}");
                Console.WriteLine($"my_ticket[field] == {my_ticket[field]}");
                accumulator *= my_ticket[field];
            }

            Console.WriteLine($"Multiplied together: {accumulator}");
        }
Example #48
0
 //链接两个序列
 public IEnumerable <TEntity> Concat(IEnumerable <TEntity> second)
 {
     return(classList.Concat(second));
 }
Example #49
0
        public DutchDateExtractorConfiguration(IDateTimeOptionsConfiguration config)
            : base(config)
        {
            var numOptions = NumberOptions.None;

            if ((config.Options & DateTimeOptions.NoProtoCache) != 0)
            {
                numOptions = NumberOptions.NoProtoCache;
            }

            var numConfig = new BaseNumberOptionsConfiguration(config.Culture, numOptions);

            IntegerExtractor = Number.Dutch.IntegerExtractor.GetInstance(numConfig);
            OrdinalExtractor = Number.Dutch.OrdinalExtractor.GetInstance(numConfig);

            NumberParser = new BaseNumberParser(new DutchNumberParserConfiguration(numConfig));

            DurationExtractor    = new BaseDurationExtractor(new DutchDurationExtractorConfiguration(this));
            HolidayExtractor     = new BaseHolidayExtractor(new DutchHolidayExtractorConfiguration(this));
            UtilityConfiguration = new DutchDatetimeUtilityConfiguration();

            ImplicitDateList = new List <Regex>
            {
                // extract "12" from "on 12"
                OnRegex,

                // extract "12th" from "on/at/in 12th"
                RelaxedOnRegex,

                // "the day before yesterday", "previous day", "today", "yesterday", "tomorrow"
                SpecialDayRegex,

                // "this Monday", "Tuesday of this week"
                ThisRegex,

                // "last/previous Monday", "Monday of last week"
                LastDateRegex,

                // "next/following Monday", "Monday of next week"
                NextDateRegex,

                // "Sunday", "Weds"
                SingleWeekDayRegex,

                // "2nd Monday of April"
                WeekDayOfMonthRegex,

                // "on the 12th"
                SpecialDate,

                // "two days from today", "five days from tomorrow"
                SpecialDayWithNumRegex,

                // "three Monday from now"
                RelativeWeekDayRegex,
            };

            if ((Options & DateTimeOptions.CalendarMode) != 0)
            {
                ImplicitDateList = ImplicitDateList.Concat(new[] { DayRegex });
            }

            // 3-23-2017
            var dateRegex4 = RegexCache.Get(DateTimeDefinitions.DateExtractor4, RegexFlags);

            // 23-3-2015
            var dateRegex5 = RegexCache.Get(DateTimeDefinitions.DateExtractor5, RegexFlags);

            // on (Sunday,)? 1.3
            var dateRegex6 = RegexCache.Get(DateTimeDefinitions.DateExtractor6, RegexFlags);

            // on (Sunday,)? 24-12
            var dateRegex8 = RegexCache.Get(DateTimeDefinitions.DateExtractor8, RegexFlags);

            // "(Sunday,)? 7/23, 2018", year part is required
            var dateRegex7L = RegexCache.Get(DateTimeDefinitions.DateExtractor7L, RegexFlags);

            // "(Sunday,)? 7/23", year part is not required
            var dateRegex7S = RegexCache.Get(DateTimeDefinitions.DateExtractor7S, RegexFlags);

            // "(Sunday,)? 23/7, 2018", year part is required
            var dateRegex9L = RegexCache.Get(DateTimeDefinitions.DateExtractor9L, RegexFlags);

            // "(Sunday,)? 23/7", year part is not required
            var dateRegex9S = RegexCache.Get(DateTimeDefinitions.DateExtractor9S, RegexFlags);

            // (Sunday,)? 2015-12-23
            var dateRegexA = RegexCache.Get(DateTimeDefinitions.DateExtractorA, RegexFlags);

            DateRegexList = new List <Regex>
            {
                // (Sunday,)? April 5 or (Sunday,)? April 5, 2016
                RegexCache.Get(DateTimeDefinitions.DateExtractor1, RegexFlags),

                // (Sunday,)? 6th of April
                RegexCache.Get(DateTimeDefinitions.DateExtractor3, RegexFlags),
            };

            var enableDmy = DmyDateFormat ||
                            DateTimeDefinitions.DefaultLanguageFallback == Constants.DefaultLanguageFallback_DMY;

            DateRegexList = DateRegexList.Concat(enableDmy ?
                                                 new[] { dateRegex5, dateRegex8, dateRegex9L, dateRegex9S, dateRegex4, dateRegex6, dateRegex7L, dateRegex7S, dateRegexA } :
                                                 new[] { dateRegex4, dateRegex6, dateRegex7L, dateRegex7S, dateRegex5, dateRegex8, dateRegex9L, dateRegex9S, dateRegexA });
        }
Example #50
0
        // ISendCommand
        public Type[] GetAvailableCommands(string[] asmPaths, CommandDefinition commandDef, bool suppressErrors)
        {
            List <Type> arr = new List <Type>();


            List <string> nonExistingPaths = new List <string>();


            foreach (var path in asmPaths)
            {
                if (Directory.Exists(path))
                {
                    foreach (var dll in Directory.GetFiles(path, "*.dll"))
                    {
                        if (IGNORE_DLL.Any(a => dll.EndsWith(a)))
                        {
                            continue;
                        }

                        try {
                            var asm = Assembly.LoadFrom(dll);
                            //var asm = Assembly.ReflectionOnlyLoadFrom(dll);

                            foreach (Type t in asm.GetTypes())
                            {
                                if (commandDef.IsCommand(t))
                                {
                                    arr.Add(t);
                                }
                            }
                        } catch (ReflectionTypeLoadException fte) {
                            if (suppressErrors)
                            {
                                continue;
                            }

                            StringBuilder sb = new StringBuilder();
                            if (fte.LoaderExceptions != null)
                            {
                                if (fte.LoaderExceptions.All(a => a.Message.EndsWith("does not have an implementation.")))
                                {
                                    continue;
                                }

                                string lastMsg = null;
                                foreach (var ex in fte.LoaderExceptions)
                                {
                                    if (ex.Message != lastMsg)
                                    {
                                        sb.AppendFormat(" - {0}\n\n", lastMsg = ex.Message);
                                    }
                                }

                                sb.Append("Try adding these libraries to your Assembly Folder");
                            }

                            OnWarning("Could not search for Commands in Assembly '{0}'".With(Path.GetFileName(dll)), sb.ToString());
                        } catch { }
                    }
                }
                else
                {
                    nonExistingPaths.Add(path);
                }
            }

            if (nonExistingPaths.Count > 0)
            {
                OnError("The paths '{0}' doesn't exist, could not search for commands.".With(nonExistingPaths.Concat()));
            }


            return(arr.ToArray());
        }
Example #51
0
        public override IAccountStateDelta Execute(IActionContext context)
        {
            IActionContext ctx                     = context;
            var            states                  = ctx.PreviousStates;
            var            inventoryAddress        = avatarAddress.Derive(LegacyInventoryKey);
            var            worldInformationAddress = avatarAddress.Derive(LegacyWorldInformationKey);
            var            questListAddress        = avatarAddress.Derive(LegacyQuestListKey);

            if (ctx.Rehearsal)
            {
                states = states.SetState(RankingMapAddress, MarkChanged);
                states = states.SetState(avatarAddress, MarkChanged);
                states = states.SetState(WeeklyArenaAddress, MarkChanged);
                states = states
                         .SetState(inventoryAddress, MarkChanged)
                         .SetState(worldInformationAddress, MarkChanged)
                         .SetState(questListAddress, MarkChanged);
                return(states.SetState(ctx.Signer, MarkChanged));
            }

            CheckObsolete(BlockChain.Policy.BlockPolicySource.V100080ObsoleteIndex, context);

            var addressesHex = GetSignerAndOtherAddressesHex(context, avatarAddress);

            var sw = new Stopwatch();

            sw.Start();
            var started = DateTimeOffset.UtcNow;

            Log.Verbose("{AddressesHex}HAS exec started", addressesHex);

            if (!states.TryGetAvatarStateV2(ctx.Signer, avatarAddress, out AvatarState avatarState))
            {
                throw new FailedLoadStateException($"{addressesHex}Aborted as the avatar state of the signer was failed to load.");
            }

            sw.Stop();
            Log.Verbose("{AddressesHex}HAS Get AgentAvatarStates: {Elapsed}", addressesHex, sw.Elapsed);
            sw.Restart();

            if (avatarState.RankingMapAddress != RankingMapAddress)
            {
                throw new InvalidAddressException($"{addressesHex}Invalid ranking map address");
            }

            // worldId와 stageId가 유효한지 확인합니다.
            var worldSheet = states.GetSheet <WorldSheet>();

            if (!worldSheet.TryGetValue(worldId, out var worldRow, false))
            {
                throw new SheetRowNotFoundException(addressesHex, nameof(WorldSheet), worldId);
            }

            if (stageId < worldRow.StageBegin ||
                stageId > worldRow.StageEnd)
            {
                throw new SheetRowColumnException(
                          $"{addressesHex}{worldId} world is not contains {worldRow.Id} stage: " +
                          $"{worldRow.StageBegin}-{worldRow.StageEnd}");
            }

            var stageSheet = states.GetSheet <StageSheet>();

            if (!stageSheet.TryGetValue(stageId, out var stageRow))
            {
                throw new SheetRowNotFoundException(addressesHex, nameof(StageSheet), stageId);
            }

            var worldInformation = avatarState.worldInformation;

            if (!worldInformation.TryGetWorld(worldId, out var world))
            {
                // NOTE: Add new World from WorldSheet
                worldInformation.AddAndUnlockNewWorld(worldRow, ctx.BlockIndex, worldSheet);
            }

            if (!world.IsUnlocked)
            {
                throw new InvalidWorldException($"{addressesHex}{worldId} is locked.");
            }

            if (world.StageBegin != worldRow.StageBegin ||
                world.StageEnd != worldRow.StageEnd)
            {
                worldInformation.UpdateWorld(worldRow);
            }

            if (world.IsStageCleared && stageId > world.StageClearedId + 1 ||
                !world.IsStageCleared && stageId != world.StageBegin)
            {
                throw new InvalidStageException(
                          $"{addressesHex}Aborted as the stage ({worldId}/{stageId}) is not cleared; " +
                          $"cleared stage: {world.StageClearedId}"
                          );
            }

            avatarState.ValidateEquipmentsV2(equipments, context.BlockIndex);
            avatarState.ValidateConsumable(foods, context.BlockIndex);
            avatarState.ValidateCostume(costumes);

            var costumeStatSheet = states.GetSheet <CostumeStatSheet>();

            sw.Restart();
            if (avatarState.actionPoint < stageRow.CostAP)
            {
                throw new NotEnoughActionPointException(
                          $"{addressesHex}Aborted due to insufficient action point: " +
                          $"{avatarState.actionPoint} < {stageRow.CostAP}"
                          );
            }

            avatarState.actionPoint -= stageRow.CostAP;

            var items = equipments.Concat(costumes);

            avatarState.EquipItems(items);
            sw.Stop();
            Log.Verbose("{AddressesHex}HAS Unequip items: {Elapsed}", addressesHex, sw.Elapsed);
            sw.Restart();

            // Update QuestList only when QuestSheet.Count is greater than QuestList.Count
            var questList  = avatarState.questList;
            var questSheet = states.GetQuestSheet();

            if (questList.Count() < questSheet.Count)
            {
                questList.UpdateListV1(
                    2,
                    questSheet,
                    states.GetSheet <QuestRewardSheet>(),
                    states.GetSheet <QuestItemRewardSheet>(),
                    states.GetSheet <EquipmentItemRecipeSheet>());
            }

            sw.Stop();
            Log.Verbose("{AddressesHex}HAS Update QuestList: {Elapsed}", addressesHex, sw.Elapsed);
            sw.Restart();

            var characterSheet = states.GetSheet <CharacterSheet>();
            var simulator      = new StageSimulator(
                ctx.Random,
                avatarState,
                foods,
                worldId,
                stageId,
                states.GetStageSimulatorSheets(),
                costumeStatSheet,
                StageSimulator.ConstructorVersionV100025);

            sw.Stop();
            Log.Verbose("{AddressesHex}HAS Initialize Simulator: {Elapsed}", addressesHex, sw.Elapsed);

            sw.Restart();
            simulator.SimulateV3();
            sw.Stop();
            Log.Verbose("{AddressesHex}HAS Simulator.SimulateV2(): {Elapsed}", addressesHex, sw.Elapsed);

            Log.Verbose(
                "{AddressesHex}Execute HackAndSlash({AvatarAddress}); worldId: {WorldId}, stageId: {StageId}, result: {Result}, " +
                "clearWave: {ClearWave}, totalWave: {TotalWave}",
                addressesHex,
                avatarAddress,
                worldId,
                stageId,
                simulator.Log.result,
                simulator.Log.clearedWaveNumber,
                simulator.Log.waveCount
                );

            sw.Restart();
            if (simulator.Log.IsClear)
            {
                var worldUnlockSheet = states.GetSheet <WorldUnlockSheet>();
                simulator.Player.worldInformation.ClearStage(
                    worldId,
                    stageId,
                    ctx.BlockIndex,
                    worldSheet,
                    worldUnlockSheet
                    );
            }

            sw.Stop();
            Log.Verbose("{AddressesHex}HAS ClearStage: {Elapsed}", addressesHex, sw.Elapsed);
            sw.Restart();

            avatarState.Update(simulator);

            var materialSheet = states.GetSheet <MaterialItemSheet>();

            avatarState.UpdateQuestRewards2(materialSheet);

            avatarState.updatedAt = ctx.BlockIndex;
            avatarState.mailBox.CleanUp();
            states = states
                     .SetState(avatarAddress, avatarState.SerializeV2())
                     .SetState(inventoryAddress, avatarState.inventory.Serialize())
                     .SetState(worldInformationAddress, avatarState.worldInformation.Serialize())
                     .SetState(questListAddress, avatarState.questList.Serialize());

            sw.Stop();
            Log.Verbose("{AddressesHex}HAS Set AvatarState: {Elapsed}", addressesHex, sw.Elapsed);

            sw.Restart();
            if (states.TryGetState(RankingMapAddress, out Dictionary d) && simulator.Log.IsClear)
            {
                var ranking = new RankingMapState(d);
                ranking.Update(avatarState);

                sw.Stop();
                Log.Verbose("{AddressesHex}HAS Update RankingState: {Elapsed}", addressesHex, sw.Elapsed);
                sw.Restart();

                var serialized = ranking.Serialize();

                sw.Stop();
                Log.Verbose("{AddressesHex}HAS Serialize RankingState: {Elapsed}", addressesHex, sw.Elapsed);
                sw.Restart();
                states = states.SetState(RankingMapAddress, serialized);
            }

            sw.Stop();
            Log.Verbose("{AddressesHex}HAS Set RankingState: {Elapsed}", addressesHex, sw.Elapsed);

            sw.Restart();
            if (simulator.Log.stageId >= GameConfig.RequireClearedStageLevel.ActionsInRankingBoard &&
                simulator.Log.IsClear &&
                states.TryGetState(WeeklyArenaAddress, out Dictionary weeklyDict))
            {
                var weekly = new WeeklyArenaState(weeklyDict);
                if (!weekly.Ended)
                {
                    if (weekly.ContainsKey(avatarAddress))
                    {
                        var info = weekly[avatarAddress];
                        info.UpdateV2(avatarState, characterSheet, costumeStatSheet);
                        weekly.Update(info);
                    }
                    else
                    {
                        weekly.SetV2(avatarState, characterSheet, costumeStatSheet);
                    }

                    sw.Stop();
                    Log.Verbose("{AddressesHex}HAS Update WeeklyArenaState: {Elapsed}", addressesHex, sw.Elapsed);

                    sw.Restart();
                    var weeklySerialized = weekly.Serialize();
                    sw.Stop();
                    Log.Verbose("{AddressesHex}HAS Serialize RankingState: {Elapsed}", addressesHex, sw.Elapsed);

                    states = states.SetState(weekly.address, weeklySerialized);
                }
            }

            var ended = DateTimeOffset.UtcNow;

            Log.Verbose("{AddressesHex}HAS Total Executed Time: {Elapsed}", addressesHex, ended - started);
            return(states);
        }
Example #52
0
        protected override ItemPlacementResult DoSanePlacement(MT19337 rng, ItemPlacementContext ctx)
        {
            _sanityCounter = 0;
            var incentiveLocationPool   = _incentivesData.IncentiveLocations.ToList();
            var preBlackOrbLocationPool = _incentivesData.AllValidPreBlackOrbItemLocations.ToList();
            var preBlackOrbUnincentivizedLocationPool = preBlackOrbLocationPool.Where(x => !incentiveLocationPool.Any(y => y.Address == x.Address)).ToList();

            Dictionary <MapLocation, Tuple <List <MapChange>, AccessRequirement> > fullLocationRequirements = _overworldMap.FullLocationRequirements;
            Dictionary <MapLocation, OverworldTeleportIndex> overridenOverworld = _overworldMap.OverriddenOverworldLocations;

            List <IRewardSource> placedItems  = null;
            List <Item>          treasurePool = null;
            var itemShopItem = Item.Bottle;

            do
            {
                _sanityCounter++;
                if (_sanityCounter > 20)
                {
                    throw new InsaneException("Item Placement could not meet incentivization requirements!");
                }
                // 1. (Re)Initialize lists inside of loop
                placedItems = ctx.Forced.ToList();
                var incentives    = ctx.Incentivized.ToList();
                var nonincentives = ctx.Unincentivized.ToList();
                treasurePool = ctx.AllTreasures.ToList();
                incentives.Shuffle(rng);
                nonincentives.Shuffle(rng);

                while (incentives.Count() > incentiveLocationPool.Count())
                {
                    nonincentives.Add(incentives.SpliceRandom(rng));
                }

                if (_flags.NPCItems || _flags.NPCFetchItems)
                {
                    // Identify but don't place caravan item first because among incentive locations it has the smallest set of possible items
                    itemShopItem = SelectVendorItem(incentives, nonincentives, treasurePool, incentiveLocationPool, rng);

                    // unrestricted items can get placed anywhere in the game. Everything else will only be placed where we can reach at this point.
                    List <Item> unrestricted = new List <Item> {
                        Item.Key, Item.Canoe, Item.Floater
                    };

                    // We will place these items in this very order so that we can ensure the bridge is early, and we don't need the floater to find the ship.
                    List <Item> fixedPlacements = new List <Item> {
                        Item.Key, Item.Bridge, Item.Canoe
                    };
                    List <Item> nextPlacements = new List <Item> {
                        Item.Ship, Item.Canal
                    };
                    List <Item> lastPlacements = new List <Item> {
                        Item.Floater, Item.Lute, Item.Crown, Item.Crystal, Item.Herb, Item.Tnt, Item.Adamant,
                        Item.Slab, Item.Ruby, Item.Rod, Item.Chime, Item.Tail, Item.Cube, Item.Bottle, Item.Oxyale
                    };

                    nextPlacements.Shuffle(rng);
                    lastPlacements.Shuffle(rng);
                    var allPlacements = fixedPlacements.Concat(nextPlacements).Concat(lastPlacements);

                    foreach (var item in allPlacements)
                    {
                        if (placedItems.Any(x => x.Item == item))
                        {
                            continue;
                        }

                        if (item == itemShopItem)
                        {
                            placedItems.Add(new ItemShopSlot(_caravanItemLocation, itemShopItem));
                            itemShopItem = Item.None;
                            continue;
                        }

                        var(_, mapLocations, requirements) = CheckSanity(placedItems, fullLocationRequirements, _flags);
                        var isIncentive  = incentives.Contains(item);
                        var locationPool = isIncentive ? incentiveLocationPool : preBlackOrbUnincentivizedLocationPool;
                        var itemPool     = isIncentive ? incentives : nonincentives;

                        System.Diagnostics.Debug.Assert(itemPool.Contains(item));

                        // Can we find a home for this item at this point in the exploration?
                        var rewardSources = locationPool.Where(x => !placedItems.Any(y => y.Address == x.Address) &&
                                                               x.Address != ItemLocations.CaravanItemShop1.Address &&
                                                               (unrestricted.Contains(item) || IsRewardSourceAccessible(x, requirements, mapLocations)))
                                            .ToList();

                        // If we can great, if not, we'll revisit after we get through everything.
                        if (rewardSources.Any())
                        {
                            itemPool.Remove(item);
                            placedItems.Add(NewItemPlacement(rewardSources.PickRandom(rng), item));
                        }
                    }
                }

                // This is a junk item that didn't get placed in the above loop.
                if (!placedItems.Any(item => item.Address == _caravanItemLocation.Address))
                {
                    placedItems.Add(new ItemShopSlot(_caravanItemLocation, itemShopItem));
                }

                // 5. Then place all incentive locations that don't have special logic
                var incentiveLocations = incentiveLocationPool.Where(x => !placedItems.Any(y => y.Address == x.Address) && x.Address != ItemLocations.CaravanItemShop1.Address).ToList();
                incentiveLocations.Shuffle(rng);
                foreach (var incentiveLocation in incentiveLocations)
                {
                    if (!incentives.Any())
                    {
                        break;
                    }
                    placedItems.Add(NewItemPlacement(incentiveLocation, incentives.SpliceRandom(rng)));
                }

                // 6. Then place remanining incentive items and unincentivized quest items in any other chest before ToFR
                var leftoverItems = incentives.Concat(nonincentives).ToList();
                leftoverItems.Shuffle(rng);
                var leftoverItemLocations = preBlackOrbLocationPool.Where(x => !placedItems.Any(y => y.Address == x.Address)).ToList();
                foreach (var leftoverItem in leftoverItems)
                {
                    placedItems.Add(NewItemPlacement(leftoverItemLocations.SpliceRandom(rng), leftoverItem));
                }

                // 7. Check sanity and loop if needed
            } while (!CheckSanity(placedItems, fullLocationRequirements, _flags).Complete);

            return(new ItemPlacementResult {
                PlacedItems = placedItems, RemainingTreasures = treasurePool
            });
        }
Example #53
0
    /// <summary>
    /// Generate the specified oper.
    /// </summary>
    /// <param name="oper">Oper.</param>
    void Generate(OpDef oper)
    {
        SetupArguments(oper);
        GenDocs(oper);

        var    name = oper.name;
        string retType;

        if (have_return_value)
        {
            if (oper.output_arg.Count > 1)
            {
                var rb = new StringBuilder("(");
                foreach (var arg in oper.output_arg)
                {
                    rb.AppendFormat("TFOutput{0} {1}, ", IsListArg(arg) ? "[]" : "", ParamMap(arg.name));
                }
                rb.Remove(rb.Length - 2, 2);
                rb.Append(")");
                retType = rb.ToString();
            }
            else
            {
                retType = "TFOutput" + (IsListArg(oper.output_arg.First()) ? "[]" : "");
            }
        }
        else
        {
            retType = "TFOperation";
        }

        p($"public {retType} {name} ({FillArguments(oper)}string operName = null)");
        pi("{");
        bool needStatus = required_attrs.Concat(optional_attrs).Any(attr => attr.type.Contains("TFTensor"));

        p($"var desc = new TFOperationDesc (this, \"{oper.name}\", MakeName (\"{oper.name}\", operName));");
        foreach (var arg in oper.input_arg)
        {
            if (IsListArg(arg))
            {
                p($"desc.AddInputs ({ParamMap (arg.name)});");
            }
            else
            {
                p($"desc.AddInput ({ParamMap (arg.name)});");
            }
        }

        pi("foreach ( TFOperation control in CurrentDependencies )");
        p("desc.AddControlInput (control);");
        pd("");

        // If we have attributes
        if (required_attrs.Count > 0 || optional_attrs.Count > 0)
        {
            foreach (var attr in required_attrs)
            {
                SetAttribute(attr.type, attr.name, ParamMap(attr.name));
            }

            foreach (var attr in optional_attrs)
            {
                var reftype = IsReferenceType(attr.type);
                var csattr  = ParamMap(attr.name);
                if (reftype)
                {
                    pi($"if ({csattr} != null)");
                }
                else
                {
                    pi($"if ({csattr}.HasValue)");
                }
                SetAttribute(attr.type, attr.name, csattr + (reftype ? "" : ".Value"));
                pd("");
            }
        }

        p("var op = desc.FinishOperation ();");
        if (oper.output_arg.Count() > 0)
        {
            p("int _idx = 0;");
        }
        if (oper.output_arg.Any(x => IsListArg(x)))
        {
            p("int _n = 0;");
        }
        foreach (var arg in oper.output_arg)
        {
            if (IsListArg(arg))
            {
                var outputs = new StringBuilder();
                p($"_n = op.OutputListLength (\"{ParamMap (arg.name)}\");");
                p($"var {ParamMap (arg.name)} = new TFOutput [_n];");
                pi("for (int i = 0; i < _n; i++)");
                p($"{ParamMap (arg.name)} [i] = new TFOutput (op, _idx++);");
                pd("");
            }
            else
            {
                p($"var {ParamMap (arg.name)} = new TFOutput (op, _idx++);");
            }
        }

        if (have_return_value)
        {
            if (oper.output_arg.Count == 1)
            {
                p($"return {ParamMap (oper.output_arg.First ().name)};");
            }
            else
            {
                ;
                p("return (" + oper.output_arg.Select(x => ParamMap(x.name)).Aggregate((i, j) => (i + ", " + j)) + ");");
            }
        }
        else
        {
            p("return op;");
        }
        pd("}\n");
    }
    protected internal override Expression VisitProjection(ProjectionExpression proj)
    {
        if (currentSource == null)
        {
            currentSource = WithoutOrder(proj.Select);

            Expression projector = this.Visit(proj.Projector);

            if (projector != proj.Projector)
            {
                proj = new ProjectionExpression(proj.Select, projector, proj.UniqueFunction, proj.Type);
            }

            currentSource = null;
            return(proj);
        }
        else
        {
            HashSet <ColumnExpression> columns = ExternalColumnGatherer.Gatherer(proj, currentSource.Alias);

            if (columns.Count == 0)
            {
                Expression projector = Visit(proj.Projector);

                ConstantExpression key   = Expression.Constant(0);
                Type            kvpType  = typeof(KeyValuePair <,>).MakeGenericType(key.Type, projector.Type);
                ConstructorInfo ciKVP    = kvpType.GetConstructor(new[] { key.Type, projector.Type }) !;
                Type            projType = proj.UniqueFunction == null ? typeof(IEnumerable <>).MakeGenericType(kvpType) : kvpType;

                var childProj = new ProjectionExpression(proj.Select,
                                                         Expression.New(ciKVP, key, projector), proj.UniqueFunction, projType);

                return(new ChildProjectionExpression(childProj,
                                                     Expression.Constant(0), inMList != null, inMList ?? proj.Type, new LookupToken()));
            }
            else
            {
                SelectExpression external;
                IEnumerable <ColumnExpression> externalColumns;

                if (!IsKey(currentSource, columns))
                {
                    Alias           aliasDistinct     = aliasGenerator.GetUniqueAlias(currentSource.Alias.Name + "D");
                    ColumnGenerator generatorDistinct = new ColumnGenerator();

                    List <ColumnDeclaration> columnDistinct = columns.Select(ce => generatorDistinct.MapColumn(ce)).ToList();
                    external = new SelectExpression(aliasDistinct, true, null, columnDistinct, currentSource, null, null, null, 0);


                    Dictionary <ColumnExpression, ColumnExpression> distinctReplacements = columnDistinct.ToDictionary(
                        cd => (ColumnExpression)cd.Expression,
                        cd => cd.GetReference(aliasDistinct));

                    proj = (ProjectionExpression)ColumnReplacer.Replace(proj, distinctReplacements);

                    externalColumns = distinctReplacements.Values.ToHashSet();
                }
                else
                {
                    external        = currentSource;
                    externalColumns = columns;
                }

                ColumnGenerator          generatorSM       = new ColumnGenerator();
                List <ColumnDeclaration> columnsSMExternal = externalColumns.Select(ce => generatorSM.MapColumn(ce)).ToList();
                List <ColumnDeclaration> columnsSMInternal = proj.Select.Columns.Select(cd => generatorSM.MapColumn(cd.GetReference(proj.Select.Alias))).ToList();

                SelectExpression @internal = ExtractOrders(proj.Select, out List <OrderExpression>?innerOrders);

                Alias            aliasSM    = aliasGenerator.GetUniqueAlias(@internal.Alias.Name + "SM");
                SelectExpression selectMany = new SelectExpression(aliasSM, false, null, columnsSMExternal.Concat(columnsSMInternal),
                                                                   new JoinExpression(JoinType.CrossApply,
                                                                                      external,
                                                                                      @internal, null), null, innerOrders, null, 0);

                SelectExpression old = currentSource;
                currentSource = WithoutOrder(selectMany);

                var selectManyReplacements = selectMany.Columns.ToDictionary(
                    cd => (ColumnExpression)cd.Expression,
                    cd => cd.GetReference(aliasSM));

                Expression projector = ColumnReplacer.Replace(proj.Projector, selectManyReplacements);

                projector = Visit(projector);

                currentSource = old;

                Expression      key      = TupleReflection.TupleChainConstructor(columnsSMExternal.Select(cd => MakeEquatable(cd.GetReference(aliasSM))));
                Type            kvpType  = typeof(KeyValuePair <,>).MakeGenericType(key.Type, projector.Type);
                ConstructorInfo ciKVP    = kvpType.GetConstructor(new[] { key.Type, projector.Type }) !;
                Type            projType = proj.UniqueFunction == null ? typeof(IEnumerable <>).MakeGenericType(kvpType) : kvpType;

                var childProj = new ProjectionExpression(selectMany,
                                                         Expression.New(ciKVP, key, projector), proj.UniqueFunction, projType);

                return(new ChildProjectionExpression(childProj,
                                                     TupleReflection.TupleChainConstructor(columns.Select(a => MakeEquatable(a))), inMList != null, inMList ?? proj.Type, new LookupToken()));
            }
        }
    }
Example #55
0
        public byte[] BuildSwaggerJson()
        {
            try
            {
                var xmlList = new List <XmlCommentStructure>();
                foreach (var srvXml in handlers.SrvGroup)
                {
                    var xmlDocumentPath = srvXml.Value;
                    xmlDocumentPath = xmlDocumentPath.Substring(0, xmlDocumentPath.Length - 4) + ".xml";
                    if (File.Exists(xmlDocumentPath))
                    {
                        var lookUp = BuildXmlMemberCommentStructureList(xmlDocumentPath);
                        xmlList = xmlList.Concat(lookUp).ToList();
                    }
                }
                var methodList = handlers.MethodList();
                xDocLookup = xmlList.ToLookup(x => Tuple.Create(x.ClassName, x.MethodName));

                var doc = new SwaggerDocument();
                doc.info        = options.Info;
                doc.host        = (options.CustomHost != null) ? options.CustomHost(httpContext) : httpContext.Request.Headers["Host"][0];
                doc.basePath    = options.ApiBasePath;
                doc.schemes     = (options.ForceSchemas.Length == 0) ? new[] { httpContext.Request.IsHttps ? "https" : httpContext.Request.Scheme } : options.ForceSchemas;
                doc.paths       = new Dictionary <string, PathItem>();
                doc.definitions = new Dictionary <string, Schema>();

                // tags.
                var xmlServiceName = (options.XmlDocumentPath != null)
                    ? BuildXmlTypeSummary(options.XmlDocumentPath)
                    : null;

                doc.tags = methodList.Select(t => t.Service.FullName).Distinct()
                           .Select(x =>
                {
                    string desc = null;
                    if (xmlServiceName != null)
                    {
                        xmlServiceName.TryGetValue(x, out desc);
                    }
                    return(new Tag()
                    {
                        name = x,
                        description = desc
                    });
                })
                           .ToArray();

                foreach (var item in handlers.MethodList())
                {
                    XmlCommentStructure xmlComment = null;
                    if (xDocLookup != null)
                    {
                        xmlComment = xDocLookup[Tuple.Create(item.Service.Name, item.Name)].FirstOrDefault();
                    }

                    var parameters = BuildParameters(doc.definitions, xmlComment, item);
                    var operation  = new Operation
                    {
                        tags        = new[] { item.Service.FullName },
                        summary     = (xmlComment != null) ? xmlComment.Summary : "",
                        description = (xmlComment != null) ? xmlComment.Remarks : "",
                        parameters  = parameters
                    };

                    doc.paths.Add("/" + item.Service.FullName + "/" + item.Name, new PathItem {
                        post = operation
                    });                                                                                              // everything post.
                }

                using (var ms = new MemoryStream())
                    using (var sw = new StreamWriter(ms, new UTF8Encoding(false)))
                    {
                        var serializer = new JsonSerializer()
                        {
                            NullValueHandling = NullValueHandling.Ignore,
                            ContractResolver  = IgnoreEmptyEnumerablesResolver.Instance // omit empty collection.
                        };
                        serializer.Serialize(sw, doc);

                        sw.Flush();
                        return(ms.ToArray());
                    }
            }
            catch (Exception ex)
            {
                return(Encoding.UTF8.GetBytes(ex.ToString()));
            }
        }
        public async Task <IActionResult> RobotsTextFile()
        {
            #region DisallowPaths

            // TODO: (mh) (core) Check if routes are still the same, when everything is finished.
            var disallowPaths = new List <string>()
            {
                "/bin/",
                "/Exchange/",
                "/Country/GetStatesByCountryId",
                "/Install$",
                "/Product/SetReviewHelpfulness",
            };

            // TODO: (mh) (core) Check if routes are still the same, when everything is finished.
            // TODO: (mh) (core) Some kind of provider is needed here to include module paths here (e.g. Boards, Polls etc.).
            var localizableDisallowPaths = new List <string>()
            {
                "/Boards/ForumWatch",
                "/Boards/PostEdit",
                "/Boards/PostDelete",
                "/Boards/PostCreate",
                "/Boards/TopicEdit",
                "/Boards/TopicDelete",
                "/Boards/TopicCreate",
                "/Boards/TopicMove",
                "/Boards/TopicWatch",
                "/Cart$",
                "/Checkout",
                "/Product/ClearCompareList",
                "/CompareProducts",
                "/Customer/Avatar",
                "/Customer/Activation",
                "/Customer/Addresses",
                "/Customer/BackInStockSubscriptions",
                "/Customer/ChangePassword",
                "/Customer/CheckUsernameAvailability",
                "/Customer/DownloadableProducts",
                "/Customer/ForumSubscriptions",
                "/Customer/DeleteForumSubscriptions",
                "/Customer/Info",
                "/Customer/Orders",
                "/Customer/ReturnRequests",
                "/Customer/RewardPoints",
                "/PrivateMessages",
                "/Newsletter/SubscriptionActivation",
                "/Order$",
                "/PasswordRecovery",
                "/Poll/Vote",
                "/ReturnRequest",
                "/Newsletter/Subscribe",
                "/Topic/Authenticate",
                "/Wishlist",
                "/Product/AskQuestion",
                "/Product/EmailAFriend",
                "/Cookiemanager",
                //"/Search",
                "/Config$",
                "/Settings$",
                "/Login$",
                "/Login?*",
                "/Register$",
                "/Register?*"
            };

            #endregion

            const string newLine = "\r\n"; //Environment.NewLine
            using var psb = StringBuilderPool.Instance.Get(out var sb);
            sb.Append("User-agent: *");
            sb.Append(newLine);
            sb.AppendFormat("Sitemap: {0}", Url.RouteUrl("XmlSitemap", null, Services.StoreContext.CurrentStore.ForceSslForAllPages ? "https" : "http"));
            sb.AppendLine();

            var disallows = disallowPaths.Concat(localizableDisallowPaths);

            if (_localizationSettings.SeoFriendlyUrlsForLanguagesEnabled)
            {
                var languages = await _db.Languages
                                .AsNoTracking()
                                .ApplyStandardFilter(storeId: Services.StoreContext.CurrentStore.Id)
                                .ToListAsync();

                // URLs are localizable. Append SEO code
                foreach (var language in languages)
                {
                    // TODO: (mh) (core) Master language may not have SEO prefixes if localization settings say so. This way a bug in classic also. Please fix.
                    disallows = disallows.Concat(localizableDisallowPaths.Select(x => $"/{language.UniqueSeoCode}{x}"));
                }
            }

            // Append extra allows & disallows.
            disallows = disallows.Concat(_seoSettings.ExtraRobotsDisallows.Select(x => x.Trim()));

            AddRobotsLines(sb, disallows, false);
            AddRobotsLines(sb, _seoSettings.ExtraRobotsAllows.Select(x => x.Trim()), true);

            return(Content(sb.ToString(), "text/plain"));
        }
Example #57
0
    static void Main()
    {
        var departmentsDoctorsPatients = new Dictionary <string, Dictionary <string, List <string> > >();
        var departmentsPatients        = new Dictionary <string, List <string> >();
        var departmentsRoomsPatients   = new Dictionary <string, List <List <string> > >();

        string input;
        var    waitingForOutput = false;

        while ((input = ReadLine()) != "End")
        {
            if (input != "Output" && !waitingForOutput)
            {
                var data       = input.Split().Where(i => i != "").ToArray();
                var department = data[0];
                var doctor     = data[1] + " " + data[2];
                var patient    = data[3];

                if (!departmentsDoctorsPatients.ContainsKey(department))
                {
                    departmentsDoctorsPatients[department] = new Dictionary <string, List <string> >();
                    departmentsPatients[department]        = new List <string>();
                    departmentsRoomsPatients[department]   = new List <List <string> >();
                }

                if (departmentsRoomsPatients[department].Count <= 20)
                {
                    var room = departmentsRoomsPatients[department].LastOrDefault();
                    if (room is null || (room.Count == 3 && departmentsRoomsPatients[department].Count < 20))
                    {
                        room = new List <string>();
                        departmentsRoomsPatients[department].Add(room);
                    }

                    if (room.Count < 3)
                    {
                        room.Add(patient);
                        departmentsPatients[department].Add(patient);

                        if (!departmentsDoctorsPatients[department].ContainsKey(doctor))
                        {
                            departmentsDoctorsPatients[department][doctor] = new List <string>();
                        }

                        departmentsDoctorsPatients[department][doctor].Add(patient);
                    }
                }
            }
            else if (input == "Output")
            {
                waitingForOutput = true;
                continue;
            }
            else
            {
                input = input.Trim(' ');

                //If the input exists as a department key it is probably a department
                if (departmentsPatients.ContainsKey(input))
                {
                    WriteLine(string.Join("\n", departmentsPatients[input]));
                }

                //If the input exists as a Doctor name it is probably a doctor
                else if (departmentsDoctorsPatients.Values.Any(v => v.ContainsKey(input)))
                {
                    //Get all the patients of this toctor
                    IEnumerable <string> patients = new List <string>();
                    foreach (var department in departmentsDoctorsPatients)
                    {
                        foreach (var doctor in department.Value)
                        {
                            if (doctor.Key == input)
                            {
                                patients = patients.Concat(doctor.Value);
                            }
                        }
                    }

                    patients = patients.OrderBy(p => p);
                    WriteLine(string.Join("\n", patients));
                }
                //Otherwise it is probably a query for room
                else
                {
                    var data       = input.Split().Where(i => i != "").ToArray();
                    var department = data[0];
                    var roomNumber = int.Parse(data[1]);

                    if (departmentsRoomsPatients.ContainsKey(department) && departmentsRoomsPatients[department].Count >= roomNumber)
                    {
                        WriteLine(string.Join("\n", departmentsRoomsPatients[department][roomNumber - 1].OrderBy(p => p)));
                    }
                }
            }
        }
    }
Example #58
0
        /// <summary>
        /// Adds all the checkpoints existing in the <see cref="Grid"/> to the current checkpoint's reachables.
        /// Also adds the current checkpoint to those others' reachables. The addition goes through only if their
        /// <see cref="ParentCellType"/>s allow it. Does the same with the landing strip.
        /// </summary>
        /// <param name="allCheckpoints">The list of all other checkpoints already on the <see cref="Grid"/>.</param>
        /// <param name="strip">The <see cref="Airstrip"/> on which the <see cref="Airplane"/> will be landing.</param>
        /// <param name="exitCheckpoints">The list of checkpoints, for which an <see cref="Airplane"/> can be aiming in order
        /// to exit the airspace.</param>
        public void AddReachables(List <Checkpoint> allCheckpoints, Airstrip strip, List <Checkpoint> exitCheckpoints)
        {
            switch (ParentCellType)
            {
            case CellType.BORDER:
            case CellType.UNASSIGNED:
                foreach (Checkpoint point in allCheckpoints)
                {
                    if (point.ParentCellType == CellType.BORDER ||
                        point.ParentCellType == CellType.UNASSIGNED ||
                        point.ParentCellType == CellType.UPPER)
                    {
                        this.AddSingleDestination(point, CalculateDistanceBetweenPoints(point));
                        point.AddSingleDestination(this, CalculateDistanceBetweenPoints(this));
                    }
                }

                break;

            case CellType.UPPER:
                foreach (Checkpoint point in allCheckpoints.Concat(exitCheckpoints))
                {
                    if (point.ParentCellType == CellType.BORDER ||
                        point.ParentCellType == CellType.UNASSIGNED ||
                        point.ParentCellType == CellType.UPPER ||
                        point.ParentCellType == CellType.MIDDLE)
                    {
                        this.AddSingleDestination(point, CalculateDistanceBetweenPoints(point));
                        point.AddSingleDestination(this, CalculateDistanceBetweenPoints(this));
                    }
                }

                break;

            case CellType.MIDDLE:
                foreach (Checkpoint point in allCheckpoints)
                {
                    if (point.ParentCellType == CellType.UPPER ||
                        point.ParentCellType == CellType.MIDDLE ||
                        point.ParentCellType == CellType.LOWER)
                    {
                        this.AddSingleDestination(point, CalculateDistanceBetweenPoints(point));
                        point.AddSingleDestination(this, CalculateDistanceBetweenPoints(this));
                    }
                }

                break;

            case CellType.LOWER:
                foreach (Checkpoint point in allCheckpoints)
                {
                    if (point.ParentCellType == CellType.MIDDLE ||
                        point.ParentCellType == CellType.LOWER ||
                        point.ParentCellType == CellType.FINAL)
                    {
                        this.AddSingleDestination(point, CalculateDistanceBetweenPoints(point));
                        point.AddSingleDestination(this, CalculateDistanceBetweenPoints(this));
                    }
                }

                break;

            case CellType.FINAL:

                foreach (Checkpoint point in allCheckpoints)
                {
                    if (point.ParentCellType == CellType.LOWER ||
                        point.ParentCellType == CellType.FINAL)
                    {
                        this.AddSingleDestination(point, CalculateDistanceBetweenPoints(point));
                        point.AddSingleDestination(this, CalculateDistanceBetweenPoints(this));
                    }
                }

                try
                {
                    this.AddSingleDestination(strip, CalculateDistanceBetweenPoints(strip));
                    strip.AddSingleDestination(this, CalculateDistanceBetweenPoints(this));
                }
                catch (System.NullReferenceException e)
                {
                    MessageBox.Show(
                        $"A strip needs to be added before{Environment.NewLine}adding a checkpoint in the final zone.",
                        "No strip found.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }

                break;

            default:
                break;
            }
        }
Example #59
0
        public ActionResult RobotsTextFile()
        {
            var disallowPaths = new List <string>()
            {
                "/bin/",
                "/Content/files/",
                "/Content/files/ExportImport/",
                "/Exchange/",
                "/Country/GetStatesByCountryId",
                "/Install",
                "/Article/SetReviewHelpfulness",
            };
            var localizableDisallowPaths = new List <string>()
            {
                "/Member/Avatar",
                "/Member/Activation",
                "/Member/Addresses",
                "/Member/BackInStockSubscriptions",
                "/Member/ChangePassword",
                "/Member/CheckUsernameAvailability",
                "/Member/DownloadableProducts",
                "/Member/ForumSubscriptions",
                "/Member/DeleteForumSubscriptions",
                "/Member/Info",
                "/Member/Orders",
                "/Member/ReturnRequests",
                "/Member/RewardPoints",
                "/PrivateMessages",
                "/PasswordRecovery",
                "/Poll/Vote",
                "/Topic/Authenticate",
                "/Article/AskQuestion",
                "/Article/EmailAFriend",
                "/Search",
                "/Config",
                "/Settings"
            };


            const string newLine = "\r\n"; //Environment.NewLine
            var          sb      = new StringBuilder();

            sb.Append("User-agent: *");
            sb.Append(newLine);
            sb.AppendFormat("Sitemap: {0}", Url.RouteUrl("SitemapSEO", (object)null, _securitySettings.Value.ForceSslForAllPages ? "https" : "http"));
            sb.AppendLine();

            var disallows = disallowPaths.Concat(localizableDisallowPaths);

            if (_localizationSettings.SeoFriendlyUrlsForLanguagesEnabled)
            {
                // URLs are localizable. Append SEO code
                foreach (var language in _languageService.Value.GetAllLanguages(siteId: _services.SiteContext.CurrentSite.Id))
                {
                    disallows = disallows.Concat(localizableDisallowPaths.Select(x => "/{0}{1}".FormatInvariant(language.UniqueSeoCode, x)));
                }
            }

            var seoSettings = EngineContext.Current.Resolve <SeoSettings>();

            // append extra disallows
            disallows = disallows.Concat(seoSettings.ExtraRobotsDisallows.Select(x => x.Trim()));

            // Append all lowercase variants (at least Google is case sensitive)
            disallows = disallows.Concat(GetLowerCaseVariants(disallows));

            foreach (var disallow in disallows)
            {
                sb.AppendFormat("Disallow: {0}", disallow);
                sb.Append(newLine);
            }

            Response.ContentType = "text/plain";
            Response.Write(sb.ToString());
            return(null);
        }
        /// <summary>
        /// Initializes the <paramref name="typeBuilder"/> using the provided <paramref name="baseType"/>.
        /// </summary>
        /// <param name="typeBuilder">The type builder to initialize.</param>
        /// <param name="baseType">The base type of the type currently under construction.</param>
        public static void InitializeTypeBuilderFromType([NotNull] TypeBuilder typeBuilder, [NotNull] Type baseType)
        {
            if (typeBuilder == null)
            {
                throw new ArgumentNullException(nameof(typeBuilder));
            }
            if (baseType == null)
            {
                throw new ArgumentNullException(nameof(baseType));
            }

            // Inherit expected base type
            if (baseType.IsInterface)
            {
                typeBuilder.AddInterfaceImplementation(baseType);
            }
            else
            {
                typeBuilder.SetParent(baseType);
            }

            // Build list of class hierarchy (from deeper to closer)
            var currentType       = baseType;
            var abstractBaseTypes = new List <Type>();

            while (currentType != null)
            {
                abstractBaseTypes.Add(currentType);
                currentType = currentType.BaseType;
            }
            abstractBaseTypes.Reverse();

            // Check that all interfaces are implemented
            var interfaceMethods = new List <MethodInfo>();

            foreach (var @interface in baseType.GetInterfaces())
            {
                interfaceMethods.AddRange(@interface.GetMethods(BindingFlags.Public | BindingFlags.Instance));
            }

            // Build list of abstract methods
            var abstractMethods = new List <MethodInfo>();

            foreach (var currentBaseType in abstractBaseTypes)
            {
                foreach (var method in currentBaseType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
                {
                    if ((method.Attributes & MethodAttributes.Abstract) != 0)
                    {
                        // abstract: add it
                        abstractMethods.Add(method);
                    }
                    else if ((method.Attributes & MethodAttributes.Virtual) != 0 && (method.Attributes & MethodAttributes.NewSlot) == 0)
                    {
                        // override: check if it overrides a previously described abstract method
                        for (var index = 0; index < abstractMethods.Count; index++)
                        {
                            var abstractMethod = abstractMethods[index];
                            if (abstractMethod.Name == method.Name && CompareMethodSignature(abstractMethod, method))
                            {
                                // Found a match, let's remove it from list of method to reimplement
                                abstractMethods.RemoveAt(index);
                                break;
                            }
                        }
                    }

                    // Remove interface methods already implemented
                    // override: check if it overrides a previously described abstract method
                    for (var index = 0; index < interfaceMethods.Count; index++)
                    {
                        var interfaceMethod = interfaceMethods[index];
                        if ((interfaceMethod.Name == method.Name
                             // explicit interface implementation
                             || $"{interfaceMethod.DeclaringType?.FullName}.{interfaceMethod.Name}" == method.Name) &&
                            CompareMethodSignature(interfaceMethod, method))
                        {
                            // Found a match, let's remove it from list of method to reimplement
                            interfaceMethods.RemoveAt(index--);
                        }
                    }
                }
            }

            // Note: It seems that C# also creates a Property/Event for each override; but it doesn't seem to fail when creating the type with only non-abstract getter/setter -- so we don't recreate the property/event
            // Implement all abstract methods
            foreach (var method in abstractMethods.Concat(interfaceMethods))
            {
                // Updates MethodAttributes for override method
                var attributes = method.Attributes;
                attributes &= ~MethodAttributes.Abstract;
                attributes &= ~MethodAttributes.NewSlot;
                attributes |= MethodAttributes.HideBySig;

                var overrideMethod   = typeBuilder.DefineMethod(method.Name, attributes, method.CallingConvention, method.ReturnType, method.GetParameters().Select(x => x.ParameterType).ToArray());
                var overrideMethodIL = overrideMethod.GetILGenerator();

                // TODO: For properties, do we want get { return default(T); } set { } instead?
                //       And for events, add { } remove { } too?
                overrideMethodIL.ThrowException(typeof(NotImplementedException));
            }
        }