public async Task AssignBatchActionResultsAsync(IODataClient client,
            ODataResponse batchResponse, IList<Func<IODataClient, Task>> actions, IList<int> responseIndexes)
        {
            var exceptions = new List<Exception>();
            for (var actionIndex = 0; actionIndex < actions.Count && !exceptions.Any(); actionIndex++)
            {
                var responseIndex = responseIndexes[actionIndex];
                if (responseIndex >= 0 && responseIndex < batchResponse.Batch.Count)
                {
                    var actionResponse = batchResponse.Batch[responseIndex];
                    if (actionResponse.Exception != null)
                    {
                        exceptions.Add(actionResponse.Exception);
                    }
                    else if (actionResponse.StatusCode >= (int)HttpStatusCode.BadRequest)
                    {
                        exceptions.Add(WebRequestException.CreateFromStatusCode((HttpStatusCode)actionResponse.StatusCode));
                    }
                    else
                    {
                        await actions[actionIndex](new ODataClient(client as ODataClient, actionResponse));
                    }
                }
            }

            if (exceptions.Any())
            {
                throw exceptions.First();
            }
        }
Example #2
0
        private static BaseWrapper CreateWrapperFromType(Type type, Type itemType)
        {
            BaseWrapper retval = null;
            if (type.IsArray)
            {
                retval = (BaseWrapper)Activator.CreateInstance(typeof(ArrayWrapper<>).MakeGenericType(itemType));
            }
            else
            {
                var types = new List<Type>(type.GetInterfaces()
                    .Select(h => h.IsGenericType ? h.GetGenericTypeDefinition() : h));
                types.Insert(0, type.IsGenericType ? type.GetGenericTypeDefinition() : type);

                if (types.Any(i => typeof(IList<>).IsAssignableFrom(i) || typeof(IList).IsAssignableFrom(i)))
                {
                    retval = new ListWrapper();
                }
                else if (types.Any(y => typeof(ICollection<>).IsAssignableFrom(y)))
                {
                    retval = (BaseWrapper)Activator.CreateInstance(typeof(CollectionWrapper<>).MakeGenericType(itemType));
                }
                else if (types.Any(i => typeof(IEnumerable<>).IsAssignableFrom(i) || typeof(IEnumerable).IsAssignableFrom(i)))
                {
                    retval = new ListWrapper();
                }
                else if (retval == null)
                {
                    //we gave it our best shot, but we couldn't figure out how to deserialize this badboy.
                    throw new MongoException(string.Format("Collection of type {0} cannot be deserialized.", type.FullName));
                }
            }
            return retval;
        }
    //method that finds word in text
    static string ForbiddenWord(string text, List<string> forbiddenWords)
    {
        string[] array = text.Split(new char[] { ' ' });
        StringBuilder sb = new StringBuilder();

        foreach (var word in array)
        {
            if (forbiddenWords.Any(x => x == word))
            {
                sb.Append(new String('*', word.Length) + " ");
                continue;
            }
            else if (forbiddenWords.Any(x => (x + ".") == word ))
            {
                sb.Append(new String('*', word.Length) + ".");
                continue;
            }
            else
            {
                sb.Append(word + " ");
            }
        }

        return sb.ToString();
    }
Example #4
0
		private static void AddActivitiesAndTransitions(ProcessDefinition processDefinition, List<ActivityDefinition> activities, List<TransitionDefinition> transitions, TransitionDefinition startingTransition, List<string> finalActivities, int cutoffNestingLevel)
		{
			if (transitions.Any<TransitionDefinition>((TransitionDefinition t) => t.Name.Equals(startingTransition.Name, StringComparison.InvariantCulture)))
			{
				return;
			}
			ActivityDefinition to = startingTransition.To;
			if (startingTransition.ForkType == TransitionForkType.ForkEnd)
			{
				int? nestingLevel = to.NestingLevel;
				if ((nestingLevel.GetValueOrDefault() > cutoffNestingLevel ? false : nestingLevel.HasValue))
				{
					TransitionDefinition transitionDefinition = startingTransition.Clone() as TransitionDefinition;
					transitionDefinition.IsFork = false;
					transitions.Add(transitionDefinition);
					if (!activities.Any<ActivityDefinition>((ActivityDefinition a) => a.Name.Equals(to.Name, StringComparison.InvariantCulture)))
					{
						ActivityDefinition activityDefinition = ActivityDefinition.Create(to.Name, to.State, false, true, false, false);
						activities.Add(activityDefinition);
						finalActivities.Add(to.Name);
					}
					return;
				}
			}
			transitions.Add(startingTransition);
			if (!activities.Any<ActivityDefinition>((ActivityDefinition a) => a.Name.Equals(to.Name, StringComparison.InvariantCulture)))
			{
				activities.Add(to.Clone() as ActivityDefinition);
			}
			foreach (TransitionDefinition possibleTransitionsForActivity in processDefinition.GetPossibleTransitionsForActivity(startingTransition.To, ForkTransitionSearchType.Both))
			{
				SubprocessUtils.AddActivitiesAndTransitions(processDefinition, activities, transitions, possibleTransitionsForActivity, finalActivities, cutoffNestingLevel);
			}
		}
Example #5
0
        public AssetFile(string file, string assetDir)
        {
            OriginalFile = file;
            File = file.NormalizePath();
            assetDir = assetDir.NormalizePath();
            Name = File.Remove(0, assetDir.Length).NormalizePath();
            int nameIndex = Name.LastIndexOf("/", System.StringComparison.Ordinal);
            Path = nameIndex == -1 ? "" : Name.Substring(0, nameIndex);
            Extensions = new List<string>();
            foreach (string extension in Name.Split('.').Reverse())
            {
                if (!AssetPipeline.KnownExtensions.Any(i => i.NormalizePath() == extension))
                    break;
                Extensions.Add(extension);
            }
            Extension = "." + string.Join(".", ((IEnumerable<string>)Extensions).Reverse());
            if (Extension.Length > 1)
            {
                Name = Name.Remove(Name.Length - Extension.Length, Extension.Length);
            }

            if (Extensions.Any(i => AssetPipeline.JavascriptExtensions.Contains(i)))
            {
                Type = AssetType.Js;
            }
            else if (Extensions.Any(i => AssetPipeline.CssExtensions.Contains(i)))
            {
                Type = AssetType.Css;
            }
        }
 private bool CardsAreConsecutiveWithAce(List<PokerCard> cards)
 {
     var aceHasPartner = cards.Any(c => c.CardFace.Value == Card.Face.Two) ||
                         cards.Any(c => c.CardFace.Value == Card.Face.King);
     var cardsWithoutAce = cards.Where(c => c.CardFace.Value != Card.Face.Ace).ToList();
     return aceHasPartner && CardsAreConsecutive(cardsWithoutAce);
 }
Example #7
0
        public void PrintGeneration()
        {
            var orderedFirstGeneration =
                new List<Cell>(_thisGeneration.OrderBy(criteria => criteria.Line).ThenBy(criteria => criteria.Column));

            for (int i = 0; i < 20; i++)
            {
                for (int j = 0; j < 20; j++)
                {
                    if (orderedFirstGeneration.Any(x => x.Line == i && x.Column == j && x.State == State.Head))
                    {
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.Write("*");
                    }
                    else if (orderedFirstGeneration.Any(x => x.Line == i && x.Column == j && x.State == State.Tail))
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.Write("*");
                    }
                    else if (orderedFirstGeneration.Any(x => x.Line == i && x.Column == j && x.State == State.Conductor))
                    {
                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.Write("*");
                    }
                    else
                        Console.Write(" ");
                }
                Console.WriteLine();
            }
        }
        private List<int> MakeListOfFileTypesThatUseJustTheseTabs(List<int> listOfTabTypesUsedInThisFile)
        {
            List<int> possibleFileTypes = new List<int>();

            foreach (var tabType in listOfTabTypesUsedInThisFile)
            { // all of these tab types are real non zero types
                var thisTabFileTypes = from x in db.WhichTabsInWhichFiles
                                         where x.TabTypeID == tabType
                                         select x.FileTypeID;
                // now we have a list of the file types that use this tab type
                if (possibleFileTypes.Any())
                { // we have started building a list
                    foreach (var fileType in possibleFileTypes)
                    { // let's look at the list we have built of potential file types
                        if (!thisTabFileTypes.Contains(fileType)) possibleFileTypes.Remove(fileType);
                        // if the list of file types that matches the current tab type
                        // does not include the file type from our current list then remove
                        // that file type from our current list
                        if (!possibleFileTypes.Any()) return possibleFileTypes;
                        // if our current list is empty bail out
                    }
                }
                else
                { // this is the first time through
                    foreach (var fileType in thisTabFileTypes)
                    { // let's add all of the results for this column to our comparison list
                        possibleFileTypes.Add(fileType);
                    }
                }

            }

            return possibleFileTypes;
        }
Example #9
0
		public static List<Plan> GetPlans()
		{
			if (LayoutUID == Guid.Empty)
			{
				return ClientManager.PlansConfiguration.AllPlans.Where(x => !x.IsNotShowPlan).ToList();
			}
			else
			{
				var plans = new List<Guid>();
				var layout = ClientManager.LayoutsConfiguration.Layouts.FirstOrDefault(x => x.UID == LayoutUID);
				if (layout != null)
				{
					foreach (var part in layout.Parts)
					{
						if (part.Properties != null && part.Properties is LayoutPartPlansProperties)
						{
							var layoutPartPlansProperties = part.Properties as LayoutPartPlansProperties;
							if (layoutPartPlansProperties.Type == LayoutPartPlansType.All)
							{
								return ClientManager.PlansConfiguration.AllPlans.Where(x=> !x.IsNotShowPlan).ToList();
							}
							foreach (var planUID in layoutPartPlansProperties.Plans)
							{
								if (!plans.Any(x => x == planUID))
								{
									plans.Add(planUID);
								}
							}
						}
					}
				}
				return ClientManager.PlansConfiguration.AllPlans.Where(x => plans.Any(w => w == x.UID)).ToList();
			}
		}
Example #10
0
        protected void btnBuscar_Click(object sender, EventArgs e)
        {
            List<string> lista = new List<string>();

            if (string.IsNullOrEmpty(txtDataDe.Text))
                lista.Add("<b>Data Inicial</b> precisa ser preenchida");

            if (string.IsNullOrEmpty(txtDataDe.Text))
                lista.Add("<b>Data Final</b> precisa ser preenchida");

            if (!lista.Any())
            {
                try
                {
                    if (Convert.ToDateTime(txtDataDe.Text) > Convert.ToDateTime(txtDataAte.Text))
                        lista.Add("<b>Data Inicial</b> deve ser menor que <b>Data Final</b>");
                }
                catch
                {
                    lista.Add("Data deve estar incorreta");
                }
            }

            if (lista.Any())
                CRB.BOSS.UI.Controle.Popup.Mensagem.Alerta(lista);
            else
                Buscar();
        }
Example #11
0
        public IEnumerable<QuickFix> CodeCheck(Request request)
        {
            var errors = new List<QuickFix>();

            var syntaxErrors =
                _syntaxErrorsHandler.FindSyntaxErrors(request)
                    .Errors.Select(
                        x => new QuickFix {Column = x.Column, FileName = x.FileName, Line = x.Line, Text = x.Message, LogLevel = "Error"});
            errors.AddRange(syntaxErrors);

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

            var semanticErrors =
                _semanticErrorsHandler.FindSemanticErrors(request)
                    .Errors.Select(
                        x => new QuickFix {Column = x.Column, FileName = x.FileName, Line = x.Line, Text = x.Message , LogLevel = "Error"});
            errors.AddRange(semanticErrors);

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

            var codeErrors = _codeIssuesHandler.GetCodeIssues(request).QuickFixes;
            errors.AddRange(codeErrors);

            return errors;
        }
        public static void TrySeveralTimesIfException(uint numTries, int timeSleepInMs, Action<int> action,
                                                      List<Type> ignoredExceptions = null)
        {
            bool ignoreAll = ignoredExceptions == null || ignoredExceptions.Count == 0;
            if (!ignoreAll && ignoredExceptions.Any(type => !type.IsSubclassOf(typeof(Exception))))
                throw new ArgumentException("Elements must be subclass of 'Exception'", nameof(ignoredExceptions));
            if (action == null) throw new ArgumentNullException(nameof(action));

            int tries = 0;
            while (true)
            {
                try
                {
                    ++tries;
                    action(tries);

                    break;
                }
                catch (Exception e)
                {
                    if (ignoreAll || ignoredExceptions.Any(ignored => e.GetType() == ignored))
                    {
                        if (tries > numTries) throw;

                        // Wait and retry
                        Thread.Sleep(timeSleepInMs);
                    }
                    else throw;
                }
            }
        }
Example #13
0
        public Cbr GenerateCbr(List<KeyInfo> keys, bool isExport = false, KeyStoreContext context = null)
        {
            if (keys.Count == 0 || keys.Count > Constants.BatchLimit)
                throw new ArgumentOutOfRangeException("Keys are invalid to generate CBR.");
            string soldTo = keys.First().SoldToCustomerId;
            if (keys.Any(k => k.SoldToCustomerId != soldTo))
                throw new ApplicationException("Keys are not sold to the same customer.");
            string shipTo = keys.First().ShipToCustomerId;
            if (keys.Any(k => k.ShipToCustomerId != shipTo))
                throw new ApplicationException("Keys are not shipped to the same customer.");

            Guid customerReportId = Guid.NewGuid();
            Cbr cbr = new Cbr()
            {
                CbrUniqueId = customerReportId,
                CbrStatus = (isExport ? CbrStatus.Reported : CbrStatus.Generated),
                SoldToCustomerId = soldTo,
                ReceivedFromCustomerId = shipTo,
                CbrKeys = keys.Select(k => new CbrKey()
                {
                    CustomerReportUniqueId = customerReportId,
                    KeyId = k.KeyId,
                    HardwareHash = k.HardwareHash,
                    OemOptionalInfo = k.OemOptionalInfo.ToString(),
                }).ToList()
            };
            cbrRepository.InsertCbrAndCbrKeys(cbr, context = null);
            return cbr;
        }
        public SendGridMessage Send(string from, IList<string> to, string subject, string body)
        {
            var message = SendGrid.GenerateInstance();
            var errors = new List<string>();

            if (to.Count > 0)
            {
                foreach(var recipient in to)
                    message.AddTo(recipient);
            }
            else
                errors.Add("Please add at least one recipient to the email.");

            message.From = new MailAddress(from);
            message.Subject = subject;
            message.Html = body;

            try
            {
                if (!errors.Any())
                {
                    var transportInstance = SMTP.GenerateInstance(new NetworkCredential(_username, _password));
                        transportInstance.Deliver(message);
                }
            }
            catch(Exception ex)
            {
                throw ex;
            }

            return new SendGridMessage { Success = !errors.Any(), ErrorMessages = errors };
        }
Example #15
0
 protected override bool? AdditionalVerify(Player source, List<Card> cards, List<Player> players)
 {
     if (source[DuWuUsed] != 0) return false;
     if ((players == null || players.Count == 0) && (cards != null && cards.Count > 0)) return false;
     if (players == null || players.Count == 0) return null;
     int req = players[0].Health;
     if (players.Any(p => Game.CurrentGame.DistanceTo(source, p) > source[Player.AttackRange] + 1))
     {
         return false;
     }
     if (req > 0 && (cards == null || cards.Count < req)) return null;
     if (req > 0 && (cards != null && cards.Count > req)) return false;
     if (req > 0 && cards != null && cards.Count > 0)
     {
         var temp = new Sha();
         temp.HoldInTemp(cards);
         if (players.Any(p => Game.CurrentGame.DistanceTo(source, p) > source[Player.AttackRange] + 1))
         {
             temp.ReleaseHoldInTemp();
             return false;
         }
         temp.ReleaseHoldInTemp();
     }
     return true;
 }
 private IEnumerable<Section> BreakDownSection(IEnumerable<string> lines, int level)
 {
     var headingMarker = new String('#', level) + " ";
     var currentSection = new List<string>();
     foreach (var line in lines)
     {
         if (!line.StartsWith(headingMarker))
         {
             currentSection.Add(line);
         }
         else
         {
             if (currentSection.Any(x => !string.IsNullOrWhiteSpace(x)))
             {
                 yield return CreateSection(currentSection, level);
                 currentSection.Clear();
             }
             currentSection.Add(line);
         }
     }
     if (currentSection.Any(x => !string.IsNullOrWhiteSpace(x)))
     {
         yield return CreateSection(currentSection, level);
     }
 }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="packages"></param>
        public static void Load(List<Package> packages)
        {
            try
            {
                var themes = GetThemes();
                var widgets = GetWidgets();
                
                if(themes != null && themes.Count > 0)
                {
                    foreach (var theme in from theme in themes
                        let found = packages.Any(pkg => theme.Id.ToLower() == pkg.Id.ToLower())
                        where !found select theme)
                    {
                        packages.Add(theme);
                    }
                }

                if (widgets != null && widgets.Count > 0)
                {
                    foreach (var wdg in from wdg in widgets
                        let found = packages.Any(pkg => wdg.Id.ToLower() == pkg.Id.ToLower())
                        where !found select wdg)
                    {
                        packages.Add(wdg);
                    }
                }
            }
            catch (Exception ex)
            {
                Utils.Log(System.Reflection.MethodBase.GetCurrentMethod().Name, ex);
            }
        }
		public static void InternalExecute(ProjectItem projectItem)
		{
			var ctors = new List<CodeFunction>();

			foreach (CodeFunction constructor in projectItem.FindContructors().Where(m => m.Parameters.Count > 0))
			{
				var codeElement = constructor.As<CodeElement>();
				string ctorText = codeElement.InnerText();
				var editPoint = codeElement.AtTheFirstLineAfterTheOpeningBrakect();

				bool lineAdded = false;
				foreach (var param in constructor.Parameters().Reverse())
				{
					if (param.Type.CodeType.Kind != vsCMElement.vsCMElementStruct && !ctorText.Contains($"ArgumentNullException(\"{param.Name}\")"))
					{
						lineAdded = true;
						projectItem.AddLine(editPoint, param.Name.ToCtorNullCheck());
					}
				}

				if (lineAdded)
				{
					ctors.Add(constructor);
				}
			}

			if (ctors.Any())
			{
				if (!projectItem.Contains("using System;"))
				{
					projectItem.AddLine(projectItem.FindNameSpace().As<CodeElement>().AtTheFirstLineAfterTheOpeningBrakect(), "using System;");
				}
			}

			foreach (CodeFunction constructor in projectItem.FindContructors().Where(m => m.Parameters.Count > 0))
			{
				if (string.IsNullOrWhiteSpace(constructor.DocComment))
				{
					AddCommentsToCodeElements.AddDocCommentToCtor(constructor);
				}

				var docComment = constructor.DocComment;
				var codeElement = constructor.As<CodeElement>();
				if ((codeElement.Contains("throw new ArgumentNullException") || codeElement.Contains("throw new System.ArgumentNullException"))
					&& (!docComment.Contains(exceptionMessage1) && !docComment.Contains(exceptionMessage2)))
				{
					codeElement.AppendToDocComment(exceptionMessage1);
				}
			}

			if (ctors.Any())
			{
				var dte = (DTE)Package.GetGlobalService(typeof(SDTE));
				try
				{
					dte.ExecuteCommand("Edit.FormatDocument");
				}
				catch { }
			}
		}
        public List<Post> Search(string searchParameters, List<string> searchEnginesName)
        {
            var results = new List<Post>();

            if (!string.IsNullOrEmpty(searchParameters))
            {
                // Si indica que busque post guardados, primero agrego esos posts.
                if (searchEnginesName.Any(y => y == "SavedPosts"))
                    results.AddRange(SearchSavedPosts(searchParameters));

                foreach (var searchEngine in _searchEngines.Where(x => searchEnginesName.Any(y => y == x.Name)))
                {
                    try
                    {
                        if (searchEngine.Instance != null)
                        {
                            var socialNetworkingSearchResult = searchEngine.Instance.Search(searchParameters, 1);
                            if (socialNetworkingSearchResult != null)
                            {
                                results.AddRange(ConvertFromSocialNetworkingItemToPosts(socialNetworkingSearchResult.SocialNetworkingItems, searchParameters));
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Log.Error(ex.Message, ex);
                    }
                }
            }

            return results;
        }
        private void InitRepositories(List<Type> entities)
        {
            _errorsRepository = _dataRepositoryFactory.GetDataRepository<Error>(RequestMessage);

            if (entities.Any(e => e.FullName == typeof(Movie).FullName))
            {
                _moviesRepository = _dataRepositoryFactory.GetDataRepository<Movie>(RequestMessage);
            }

            if (entities.Any(e => e.FullName == typeof(Rental).FullName))
            {
                _rentalsRepository = _dataRepositoryFactory.GetDataRepository<Rental>(RequestMessage);
            }

            if (entities.Any(e => e.FullName == typeof(Customer).FullName))
            {
                _customersRepository = _dataRepositoryFactory.GetDataRepository<Customer>(RequestMessage);
            }

            if (entities.Any(e => e.FullName == typeof(Stock).FullName))
            {
                _stocksRepository = _dataRepositoryFactory.GetDataRepository<Stock>(RequestMessage);
            }

            if (entities.Any(e => e.FullName == typeof(User).FullName))
            {
                _stocksRepository = _dataRepositoryFactory.GetDataRepository<Stock>(RequestMessage);
            }
        }
        public IReadOnlyList<object> Read()
        {
            Row += 1;
            position = 0;

            if (reader.Peek() <= 0)
                return null;

            var result = new List<object>();

            var readingValue = true;
            var value = new StringBuilder();
            char character;
            while (ReadNext(out character))
            {
                switch (character)
                {
                    case '\r':
                        break;
                    case '\n':
                        if (readingValue)
                            result.Add(ConvertUnquotedValue(value.ToString()));

                        if (!result.Any())
                            // Skip empty row and continue
                            break;

                        return result;
                    case ',':
                        if (readingValue)
                            result.Add(ConvertUnquotedValue(value.ToString()));
                        value.Clear();
                        readingValue = true;
                        break;
                    case '"':
                        if (value.Length > 0 || !readingValue)
                            throw UnexpectedCharacter(character);
                        result.Add(ReadQuotedValue());
                        readingValue = false;
                        break;
                    case ' ':
                    case '\t':
                        // Trim spaces and tabs at the beginning of unquoted values
                        if (value.Length > 0)
                            value.Append(character);
                        break;
                    default:
                        if (!readingValue)
                            throw UnexpectedCharacter(character);
                        value.Append(character);
                        break;
                }
            }

            // At the EOF, only append a value if it actualy has anything in it, or we had values before it
            if (readingValue && (value.Length > 0 || result.Any()))
                result.Add(ConvertUnquotedValue(value.ToString()));

            return result.Any() ? result : null;
        }
        /// <summary>
        /// 作者:Beta 
        /// 时间:2014.03.17
        /// 描述:获取样式列表(需求展示)
        /// </summary>
        /// <param name="list"></param>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string GetStudentClassList(List<Model.Eme.BookRequirement> list, DateTime dt)
        {
            var classlist = " select-item";

            if (dt.AddHours(-1) < DateTime.Now)
            {
                if (list.Any(p => p.BookStartTime <= dt && p.BookEndTime >= dt.AddMinutes(30) && p.IsSuccessful))
                {
                    classlist = classlist + " successful";
                }
                else if (list.Any(p => p.BookStartTime <= dt && p.BookEndTime >= dt.AddMinutes(30) && !p.IsSuccessful))
                {
                    classlist = classlist + " pass";
                }
                else
                {
                    classlist = classlist + " unavailable";
                }
            }
            else
            {
                if (list.Any(p => p.BookStartTime <= dt && p.BookEndTime >= dt.AddMinutes(30) && p.IsSuccessful))
                {
                    classlist = classlist + " successful";
                }
                else if (list.Any(p => p.BookStartTime <= dt && p.BookEndTime >= dt.AddMinutes(30) && !p.IsSuccessful))
                {
                    classlist = classlist + " normal oking";
                }
            }
            return classlist;
        }
            public BodyDeposits(GeneratorConfiguration resource, ConfigNode node)
            {
                if (node == null) { node = new ConfigNode(); }

                this.deposits = new List<Deposit>();
                this.seed = Misc.Parse(node.GetValue("Seed"), seedGenerator.Next());

                var random = new System.Random(seed);

                for (int i = 0; i < resource.DepositCount; i++)
                {
                    float R = random.Range(resource.MinRadius, resource.MaxRadius);
                    for (int j = 0; j < resource.NumberOfTries; j++)
                    {
                        Vector2 Pos = new Vector2(random.Range(R, 360 - R), random.Range(R, 180 - R));
                        var deposit = Deposit.Generate(Pos, R, random, resource);
                        if (!deposits.Any(d => d.Shape.Vertices.Any(v => deposit.Shape.PointInPolygon(new Vector2(v.x, v.y)))) && !deposit.Shape.Vertices.Any(v => deposits.Any(d => d.Shape.PointInPolygon(new Vector2(v.x, v.y)))))
                        {
                            deposits.Add(deposit);
                            break;
                        }
                    }
                }

                var depositValues = node.GetValues("Deposit");
                for (int i = 0; i < Math.Min(deposits.Count, depositValues.Length); i++)
                {
                    deposits[i].Quantity = Misc.Parse(depositValues[i], deposits[i].InitialQuantity);
                }

                MaxQuantity = resource.MaxQuantity;
            }
Example #24
0
        public void UpdateImages(List<ScannedImage> images, List<int> selection = null)
        {
            int delta = images.Count - Items.Count;
            for (int i = 0; i < delta; i++)
            {
                Items.Add("", i);
                Debug.Assert(selection == null);
            }
            for (int i = 0; i < -delta; i++)
            {
                Items.RemoveAt(Items.Count - 1);
                ilThumbnailList.Images.RemoveAt(ilThumbnailList.Images.Count - 1);
                Debug.Assert(selection == null);
            }

            // Determine the smallest range that contains all images in the selection
            int min = selection == null || !selection.Any() ? 0 : selection.Min();
            int max = selection == null || !selection.Any() ? images.Count : selection.Max() + 1;

            for (int i = min; i < max; i++)
            {
                if (i >= ilThumbnailList.Images.Count)
                {
                    ilThumbnailList.Images.Add(thumbnails[images[i]]);
                    Debug.Assert(selection == null);
                }
                else
                {
                    ilThumbnailList.Images[i] = thumbnails[images[i]];
                }
            }

            thumbnails.TrimCache(images);
            Invalidate();
        }
Example #25
0
		private IList<ClassificationSpan> DoGetClassificationSpans(SnapshotSpan span)
		{
			List<ClassificationSpan> spans = null;

			object prop;
			if (span.Snapshot.TextBuffer.Properties.TryGetProperty(typeof(ITextDocument), out prop))
			{
				var doc = (ITextDocument)prop;
				string fileName = System.IO.Path.GetFileName(doc.FilePath);
				Language lang = Languages.FindLanguage(fileName);

				if (lang != null)
				{
					List<ClassificationSpan> strings = new List<ClassificationSpan>();
					List<ClassificationSpan> comments = new List<ClassificationSpan>();
					DoGetStringSpans(lang, span, strings, comments);

					spans = new List<ClassificationSpan>();
					if (!strings.Any(s => s.Span.Contains(span) && !comments.Any(t => t.Span.Contains(span))))
					{
						IEnumerable<ClassificationSpan> mine = lang.GetClassificationSpans(span);
						spans.AddRange(from c in mine where !strings.Any(d => d.Span.OverlapsWith(c.Span)) && !comments.Any(d => d.Span.OverlapsWith(c.Span)) select c);
					}
					spans.AddRange(strings);
					spans.AddRange(comments);
				}
			}

			return spans ?? ms_noSpans;
		}
Example #26
0
        public void RunTests(string resultDirectory)
        {
            var results = new List<PerformanceMetric>();
            var failedRunResult = new List<Exception>();
            var performanceCaseResult = new PerformanceCaseResult();
            performanceCaseResult.StartTimer();

            foreach (var testDefinition in _tests)
            {
                var result = Run(testDefinition);
                PrintSummary(result);
                results.AddRange(ConvertResultToMetrics(result));
                if (!result.Successful)
                {
                    failedRunResult.Add(result.ReportedException);
                }
            }

            performanceCaseResult.StopTimer();
            performanceCaseResult.Metrics = results.ToArray();

            Assert.False(failedRunResult.Any(), failedRunResult.Any() ? failedRunResult.First().Message : string.Empty);
            Assert.False(results.Count == 0, "tests returned no results");

            WriteResultFiles(resultDirectory, results, performanceCaseResult);
        }
Example #27
0
        public static async Task<BackupResultHelper> StartBackup(List<Game> games, BackupType backupType, bool backupEnabled, BackupSyncOptions backupSyncOptions, int intervalMinute = 0, int intervalHour = 0) {
            //Check for problems with parameters
            if (!games.Any() && backupType == BackupType.Autobackup && backupEnabled) {
                _resultHelper = new BackupResultHelper {Message = @"Auto-backup disabled", AutobackupEnabled = false};
                return _resultHelper;
            }
            if (!games.Any()) {
                ErrorResultHelper.Message = @"No games selected";
                return ErrorResultHelper;
            }

            var gamesToBackup= new List<Game>();
            if (!backupEnabled) {
                if (!GetDirectoryOrFile(backupType)) return ErrorResultHelper;
                gamesToBackup = ModifyGamePaths(games);
            }

            switch (backupType) {                  
                case BackupType.ToZip:
                   return await BackupToZip.BackupAndZip(gamesToBackup, _specifiedFile);
                case BackupType.ToFolder:
                    return BackupToFolder.BackupSaves(gamesToBackup, _specifiedFolder);
                case BackupType.Autobackup:
                    return BackupAuto.ToggleAutoBackup(gamesToBackup, backupEnabled, backupSyncOptions, intervalMinute, intervalHour, _specifiedFolder);
            }

            return ErrorResultHelper;
        }
Example #28
0
        private static IDictionary<string, string[]> SplitSections(string[] lines)
        {
            var ret = new Dictionary<string, string[]>();
            var currentSegmentEntries = new List<string>();
            string currentSegment = "";
            for (int i = 0; i < lines.Length; i++)
            {
                string line = lines[i];
                if (string.IsNullOrEmpty(line))
                {
                    if (currentSegmentEntries.Any())
                    {
                        ret[currentSegment] = currentSegmentEntries.ToArray();
                        currentSegmentEntries.Clear();
                    }
                }
                else if (line[0] != ' ')
                {
                    currentSegment = line.Trim();
                }
                else
                {
                    currentSegmentEntries.Add(line);
                }
            }

            if (currentSegmentEntries.Any())
            {
                ret[currentSegment] = currentSegmentEntries.ToArray();
            }

            return ret;
        }
Example #29
0
        /// <summary>
        /// Returns a list of visual branches which are around the given commit.
        /// </summary>
        /// <param name="commit"></param>
        /// <param name="repo"></param>
        /// <returns></returns>
        public static List<Branch> GetBranchesAroundCommit(Commit commit, ObservableCollection<Branch> branches)
        {
            List<Branch> list = new List<Branch>();

            // Loop through all branches and determine if they are around the specified commit.
            foreach (Branch branch in branches)
            {
                // Tip has to be found and in case multiple branches share the tree, get rid of the others -- messes up visual position counting.
                if (branch.Tip == null || list.Any(b => branch.Tip.Branches.Contains(b)) || list.Any(b => b.Tip.Branches.Contains(branch)))
                    continue;

                // The branch's tip must be newer/same than the commit.
                if (branch.Tip.Date >= commit.Date) // TODO: && first commit-ever must be older? We might not need to do that... ... ?
                {
                    list.Add(branch);
                }
                else
                {
                    // If there's a branch with a tip commit older than commit.Date, then it's around this commit if they don't share a single branch.
                    bool foundThisBranch = branch.Tip.Branches.Any(b => commit.Branches.Contains(b));

                    if (foundThisBranch == false)
                        list.Add(branch);
                }
            }

            return list;
        }
Example #30
0
        public static List<int> Merge(List<int> left, List<int> right)
        {
            var ret = new List<int>();

            while (left.Any() || right.Any())
            {
                if (left.Any() && right.Any())
                {
                    if (left.First() <= right.First())
                    {
                        ret.Add(left.First());
                        left.Remove(left.First());
                    }
                    else
                    {
                        ret.Add(right.First());
                        right.Remove(right.First());
                    }
                } else if (left.Any())
                {
                    ret.Add(left.First());
                    left.Remove(left.First());
                } else if (right.Any())
                {
                    ret.Add(right.First());
                    right.Remove(right.First());
                }
            }
            return ret;
        }