Example #1
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 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;
        }
 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());
     }
 }
Example #9
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();
        }
        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;
        }
Example #11
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 #12
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);
            }
        }
        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( "}" );
        }
        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);
        }
        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());
        }
        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);
            }
        }
		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;
		}
		/// <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();
		}
        /// <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 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 #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);
        }
        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);
        }
Example #24
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();
 }
Example #25
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;
        }
        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);
            });
        }
Example #27
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;
        }
        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;
        }
        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();
        }
        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;
        }