Example #1
0
        public async Task ValidNotes_Handle_ReturnsTrue()
        {
            IReadOnlyCollection <INote> notes = new List <INote>
            {
                this.Note,
                this.Note,
                this.Note,
                this.Note,
                this.Note,
                new Note(101, "last note", "some text", DateTime.UtcNow, null)
            };

            IReadOnlyCollection <INote> page2 = notes.TakeLast(3).ToList();

            this.NoteRepository
            .GetAsync(Arg.Any <int>(), Arg.Any <int>())
            .Returns(Result.Ok(page2));

            var sut = await new GetNotesHandler(this.NoteRepository, this.Mapper).Handle(
                new GetNotesRequest(2, 3), CancellationToken.None);

            Assert.True(sut.IsSuccess);
            Assert.Equal(3, sut.ValueOrDefault.Count);
            Assert.Equal(notes?.LastOrDefault()?.Id, sut?.ValueOrDefault?.LastOrDefault()?.Id);
            Assert.Equal(notes?.LastOrDefault()?.Title, sut?.ValueOrDefault?.LastOrDefault()?.Title);
            Assert.Equal(notes?.LastOrDefault()?.Text, sut?.ValueOrDefault?.LastOrDefault()?.Text);
            Assert.Equal(notes?.LastOrDefault()?.ModifiedOn, sut?.ValueOrDefault?.LastOrDefault()?.ModifiedOn);
            Assert.Equal(notes?.LastOrDefault()?.CreatedOn, sut?.ValueOrDefault?.LastOrDefault()?.CreatedOn);
        }
Example #2
0
        /// <summary>
        /// Brute force approach that checks every odd number.
        /// By dividing the number to every prime number before that, we can check whether the number is prime or not.
        /// </summary>
        /// <returns>Returns the 10001th prime number</returns>
        public static int Solition1()
        {
            int counter = 0, number = 2;

            var primes = new List<int>();

            while (counter != PRIME_NO)
            {
                bool isPrime = true;

                // If remainder is 0, it is not a prime
                foreach (var p in primes)
                {
                    if (number % p == 0)
                        isPrime = false;
                }

                if (isPrime)
                {
                    primes.Add(number);
                    counter++;
                }

                // For any number different than 2, increment by 2, since other primes are all odd
                if (number == 2)
                    number += 1;
                else
                    number += 2;
            }

            return primes.LastOrDefault();
        }
        public void LazyLoadOperationWillHandleIncludes()
        {
            var ids = new List<string>();
            using (var session = ShardedDocumentStore.OpenSession())
            {
                for (int i = 1; i <= 4; i++)
                {
                    var entity = new User {Name = ids.LastOrDefault()};
                    session.Store(entity);
                    ids.Add(entity.Id);
                }
                session.SaveChanges();
            }
            using (var session = ShardedDocumentStore.OpenSession())
            {
                var result1 = session.Advanced.Lazily
                    .Include("Name")
                    .Load<User>(ids[1]);
                var result2 = session.Advanced.Lazily
                    .Include("Name")
                    .Load<User>(ids[3]);

                Assert.NotNull(result1.Value);
                Assert.NotNull(result2.Value);
                Assert.True(session.Advanced.IsLoaded(result1.Value.Name));
                Assert.True(session.Advanced.IsLoaded(result2.Value.Name));
            }
        }
Example #4
0
        internal static List<Block> CheckPostImport(List<Block> ret)
        {
            if (ret == null) return null;

            var lastImport = ret.LastOrDefault(r => r is Model.Import);
            var firstNonImport = ret.FirstOrDefault(r => !(r is Model.Import));

            if (lastImport == null || firstNonImport == null)
            {
                return ret;
            }

            var lix = ret.IndexOf(lastImport);
            var fnix = ret.IndexOf(firstNonImport);

            if (lix != -1 && fnix != -1)
            {
                if (fnix < lix)
                {
                    for (int i = fnix; i < ret.Count; i++)
                    {
                        if (ret[i] is Model.Import)
                        {
                            Current.RecordWarning(ErrorType.Parser, ret[i], "@import should appear before any other statements.  Statement will be moved.");
                        }
                    }
                }
            }

            return ret;
        }
        public BlogRelatedViewModel(string title)
        {
            using (var context = new DataContext())
            {
                // Try permalink first
                TheBlog = context.Blogs.FirstOrDefault(x => x.PermaLink == title);

                MaxBlogCount = BlogListModel.GetBlogSettings().MaxBlogsOnHomepageBeforeLoad;

                // If no go then try title as a final back up
                if (TheBlog == null)
                {
                    title = title.Replace(Utils.ContentGlobals.BLOGDELIMMETER, " ");
                    TheBlog = context.Blogs.FirstOrDefault(x => x.Title == title);
                }

                if (TheBlog != null && TheBlog.Tags != null)
                {
                    List<string> tags = TheBlog.Tags.Split(',').ToList();
                    RelatedPosts = context.Blogs.Where(x => x.BlogId != TheBlog.BlogId && tags.Contains(x.Tags) && x.MainCategory == TheBlog.MainCategory)
                                    .OrderByDescending(blog => blog.Date)
                                    .Take(MaxBlogCount)
                                    .ToList();

                    if (RelatedPosts.Count > 0)
                    {
                        LastBlogId = RelatedPosts.LastOrDefault().BlogId;
                    }
                }
            }
        }
Example #6
0
 /// <summary>
 /// Did scanned method
 /// </summary>
 /// <param name="scannedCodes"></param>
 void OnDidScanned(List <string> scannedCodes)
 {
     Device.BeginInvokeOnMainThread(() =>
     {
         ScanResultLabel.Text = scannedCodes?.LastOrDefault();
     });
 }
        private static System.Windows.Window GetActiveWindowForApplication(this System.Windows.Application application)
        {
            System.Windows.Window activeWindow = null;

            // CTL-687: Only allow windows that have an actual size (been shown at least once)
            Func<System.Windows.Window, bool> predicate = x => x.ActualWidth > 0d && x.ActualHeight > 0d;

            if (application != null && application.Windows.Count > 0)
            {
                var windowList = new List<System.Windows.Window>(application.Windows.Cast<System.Windows.Window>());

                activeWindow = windowList.FirstOrDefault(x => x.IsActive && predicate(x));
                if (activeWindow == null && windowList.Count == 1 && windowList[0].Topmost)
                {
                    activeWindow = windowList[0];
                }

                if (activeWindow == null)
                {
                    activeWindow = windowList.LastOrDefault(predicate);
                }
            }

            return activeWindow;
        }
        internal static EnumDeclarationSyntax AddEnumMemberTo(EnumDeclarationSyntax destination, IFieldSymbol enumMember, CodeGenerationOptions options)
        {
            var members = new List<SyntaxNodeOrToken>();
            members.AddRange(destination.Members.GetWithSeparators());

            var member = GenerateEnumMemberDeclaration(enumMember, destination, options);

            if (members.Count == 0)
            {
                members.Add(member);
            }
            else if (members.LastOrDefault().CSharpKind() == SyntaxKind.CommaToken)
            {
                members.Add(member);
                members.Add(SyntaxFactory.Token(SyntaxKind.CommaToken));
            }
            else
            {
                var lastMember = members.Last();
                var trailingTrivia = lastMember.GetTrailingTrivia();
                members[members.Count - 1] = lastMember.WithTrailingTrivia();
                members.Add(SyntaxFactory.Token(SyntaxKind.CommaToken).WithTrailingTrivia(trailingTrivia));
                members.Add(member);
            }

            return destination.EnsureOpenAndCloseBraceTokens()
                .WithMembers(SyntaxFactory.SeparatedList<EnumMemberDeclarationSyntax>(members));
        }
        public List<Station> Process(StationDirection direction)
        {
            var stationDirectionList = new List<List<Station>>();
            var stationsHtmlDocument = GetHtmlDocument();
            var stationsTable = GetStationTables(stationsHtmlDocument);

            if (stationsTable != null && stationsTable.Count > 0)
            {
                foreach (var tbl in stationsTable)
                {
                    var stationsForward = new List<Station>();
                    var rows = GetRows(tbl);
                    if (rows != null && rows.Count > 0)
                    {
                        stationDirectionList.Add(GetStations(rows));
                    }
                }
            }

            switch (direction)
            {
                case StationDirection.Backward:
                    return stationDirectionList.LastOrDefault();

                case StationDirection.Forward:
                default:
                    return stationDirectionList.FirstOrDefault();
            }
        }
Example #10
0
        private void ShowMissingFields()
        {
            var missingFields = new List<string>(3);

            if (string.IsNullOrEmpty(_userRegisterModel.Email))
                missingFields.Add("email");

            if (string.IsNullOrEmpty(_userRegisterModel.Password))
                missingFields.Add("password");

            if (string.IsNullOrEmpty(_userRegisterModel.ConfirmPassword))
                missingFields.Add("password confirmation");

            string joinedFields = string.Join(", ", missingFields.Take(missingFields.Count - 1)) + (missingFields.Count <= 1 ? "" : " and ") + missingFields.LastOrDefault();

            var messageBuilder = new StringBuilder("Field");

            if (missingFields.Count > 1)
                messageBuilder.Append("s");

            messageBuilder.Append($" {joinedFields} ");

            messageBuilder.Append(missingFields.Count > 1 ? "are" : "is");

            messageBuilder.Append(" missing.");
            
            _notifyPage.DisplayAlert(missingFields.Count > 1 ? "Missing fields" : "Mising field", messageBuilder.ToString());
        }
        public BlogArchiveViewModel()
        {
            using (var context = new DataContext())
            {
                Blogs = context.Blogs.Where(x => x.IsActive)
                            .OrderByDescending(blog => blog.Date)
                            .ToList();

                Grouped = (from p in Blogs
                    group p by
                        new {month = p.Date.ToString("MMM"), year = p.Date.ToString("yyyy"), dateString = p.Date.ToString("MM/yyyy")}
                        into d
                    select
                        String.Format(
                            "<a href=\"/blog?date={3}\" class=\"archive\">" +
                            "<span class=\"dateRef\" data-date=\"{3}\">{0} {1}</span>  ({2}) </a>",
                            d.Key.month, d.Key.year, d.Count(), d.Key.dateString)
                ).Take(MaxArchiveCount);

                if (Grouped.Any())
                {
                    LastMonth = Blogs.LastOrDefault().Date.ToString("MM/yyyy");
                }

            }
        }
Example #12
0
        public static IEnumerable<Page> Breadcrumb()
        {
            List<Page> breadcrumbPages = new List<Page>();
            var defaultPage = ServiceFactory.PageManager.GetDefaultPage(Page_Context.Current.PageRequestContext.Page.Site);
            if (defaultPage == Page_Context.Current.PageRequestContext.Page)
            {
                return breadcrumbPages;
            }
            var currentPage = Page_Context.Current.PageRequestContext.Page.Parent;
            while (currentPage != null)
            {
                currentPage = currentPage.LastVersion(Page_Context.Current.PageRequestContext.Site).AsActual();

                if (currentPage.Navigation != null
                    && currentPage.Navigation.ShowInCrumb.Value == true && currentPage.Published.HasValue && currentPage.Published.Value == true)
                {
                    breadcrumbPages.Add(currentPage);
                }

                currentPage = currentPage.Parent;
            }
            if (breadcrumbPages.LastOrDefault() != defaultPage)
            {
                defaultPage = defaultPage.AsActual();

                if (defaultPage.Navigation != null
                && defaultPage.Navigation.ShowInCrumb.Value == true && defaultPage.Published.HasValue && defaultPage.Published.Value == true)
                {
                    breadcrumbPages.Add(defaultPage);
                }
            }

            breadcrumbPages.Reverse();
            return breadcrumbPages;
        }
Example #13
0
        public static void CalculateStatistics(this StatisticsItem item, List<LocationTrack> dayTrackList, LocationTrack lastTrack)
        {
            dayTrackList.Sort((t1, t2) => t1.TimeStamp.CompareTo(t2.TimeStamp));
            LocationTrack lastSaved = dayTrackList.LastOrDefault();
            if (lastSaved == null)
            {
                return;
            }

            if (lastSaved.TimeStamp.AddMinutes(10) < lastTrack.TimeStamp)
            {
                //Difference too much
                return;
            }

            double? distance = lastTrack.Location.Distance(lastSaved.Location);
            if (!distance.HasValue)
            {
                return;
            }

            decimal co2Index = GetCo2Index(lastTrack.Speed);
            decimal distanceValue = Convert.ToDecimal(distance.Value);
            decimal co2InKilograms = 0.15m * co2Index * distanceValue / (1000.0m);
            const decimal co2RecycleInOneDay = 44.0m / 365.0m;

            decimal result = co2InKilograms/co2RecycleInOneDay;
            item.Day = lastTrack.TimeStamp.Date;
            item.UserProfile = lastTrack.UserProfile;
            item.Value += result;
            item.Consumer = "Car";
        }
        public decimal CalculateEma(List <TickerFormattedDto> tickers, Domain.Dtos.EcoIndex.EcoIndex lastEMA)
        {
            if (tickers.Count > 0)
            {
                decimal SMA        = tickers.Average(t => t.Last);
                decimal multiplier = 2M / (tickers.Count + 1M);

                TickerFormattedDto lastTickerFormattedDto = tickers?.LastOrDefault();

                if (lastTickerFormattedDto == null)
                {
                    return(0M);
                }

                decimal lastEMAValue = 0M;

                if (lastEMA != null)
                {
                    lastEMAValue = lastEMA.Value;
                }

                decimal EMA = (lastTickerFormattedDto.Last - lastEMAValue) * multiplier + lastEMAValue;

                if (EMA < 0)
                {
                    return(0M);
                }

                return(EMA);
            }

            return(0M);
        }
Example #15
0
 /// <summary>
 /// Beginning at the end, of the set, return all elements until the element after the element which satifies the condition [stopAt]
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="orderedSet"></param>
 /// <param name="stopAt"></param>
 /// <returns></returns>
 static IEnumerable<TestBuilder> Filter(List<TestBuilder> orderedSet, Func<TestBuilder, bool> stopAt)
 {
     var first = orderedSet.LastOrDefault(stopAt);
     return first == null ?
         orderedSet :
         orderedSet.Skip(orderedSet.LastIndexOf(first));
 }
Example #16
0
        internal static OrderItem FromValuePaths(List <ValuePath> paths)
        {
            var last = paths?.LastOrDefault();

            if (last != null && last.IsFunction)
            {
                if (string.Equals(last.Name, nameof(Desc), StringComparison.InvariantCultureIgnoreCase))
                {
                    return(new OrderItem
                    {
                        NavigatePaths = paths.SkipLast(1).ToList(),
                        OrderType = OrderType.Desc
                    });
                }
                else if (string.Equals(last.Name, nameof(Asc), StringComparison.InvariantCultureIgnoreCase))
                {
                    return(new OrderItem
                    {
                        NavigatePaths = paths.SkipLast(1).ToList(),
                        OrderType = OrderType.Asc
                    });
                }
            }
            return(new OrderItem
            {
                NavigatePaths = paths,
                OrderType = OrderType.Asc
            });
        }
Example #17
0
        public async Task<IEnumerable<IGameServer>> GetServersAsync(MasterServerRequest masterServerRequest)
        {
            var endPoints = new List<IPEndPoint>();

            var packet = 0;
            using (var client = SteamAgent.GetUdpClient(_endpoint))
            {
                while (!masterServerRequest.MaximumPackets.HasValue || packet < masterServerRequest.MaximumPackets.Value)
                {
                    var request = GetRequest(endPoints.LastOrDefault(), masterServerRequest.Region, masterServerRequest.Filters);
                    var response = await SteamAgent.RequestResponseAsync(client, request, IpEndPointLength);

                    packet++;

                    var packetEndPoints = ReadEndPointsFromPacket(response);
                    endPoints.AddRange(packetEndPoints);

                    if (endPoints.Last().IsEmpty())
                    {
                        break;
                    }
                }
            }

            return endPoints.Take(endPoints.Count - 1).Select(e => new GameServer(e));
        }
Example #18
0
        /// <summary>
        /// Проверяет, будут или есть сегодня занятия
        /// Если их сегодня не было или не будет позже текущего времени
        /// то будет выводится расписание на следующий день
        /// </summary>
        public bool IsTherePeriods(List<Period> sheduleToday, DateTime selectedDate)
        {
            if (sheduleToday != null)
            {
                Period lastPeriod = sheduleToday.LastOrDefault();
                if (lastPeriod != null)
                {
                    string endLastPeriod = lastPeriod.Time;
                    int index = endLastPeriod.IndexOf('-');
                    string[] list = endLastPeriod.Substring(index + 1, endLastPeriod.Length - index - 1).Split(':');

                    DateTime endStudyTime;
                    try
                    {
                        endStudyTime = new DateTime(selectedDate.Year, selectedDate.Month, selectedDate.Day,
                            Convert.ToInt32(list[0]), Convert.ToInt32(list[1]), 0);
                    }
                    catch (FormatException)
                    {
                        endStudyTime = new DateTime();
                    }

                    return (endStudyTime >= DateTime.Now);
                }
                return false;
            }
            return false;
        }
Example #19
0
        public ProgressEstimator(IEnumerable<ProgressSampleUnit> samples)
        {
            _samples = samples.ToList();
            _lastSample = _samples.LastOrDefault();

            Calculate();
        }
        /// <summary>
        /// Adds the original instructions to a given method body.
        /// </summary>
        /// <param name="IL">The <see cref="CilWorker"/> responsible for the target method body.</param>
        public void Emit(CilWorker IL)
        {
            var originalInstructions = new List<Instruction>(_oldInstructions);
            Instruction lastInstruction = originalInstructions.LastOrDefault();

            if (lastInstruction != null && lastInstruction.OpCode == OpCodes.Ret)
            {
                // HACK: Convert the Ret instruction into a Nop
                // instruction so that the code will
                // fall through to the epilog
                lastInstruction.OpCode = OpCodes.Br;
                lastInstruction.Operand = _endLabel;
            }

            foreach (Instruction instruction in (IEnumerable<Instruction>) originalInstructions)
            {
                if (instruction.OpCode != OpCodes.Ret || instruction == lastInstruction)
                    continue;

                if (lastInstruction == null)
                    continue;

                // HACK: Modify all ret instructions to call
                // the epilog after execution
                instruction.OpCode = OpCodes.Br;
                instruction.Operand = lastInstruction;
            }

            // Emit the original instructions
            foreach (Instruction instruction in originalInstructions)
            {
                IL.Append(instruction);
            }
        }
        public BlogsByUserViewModel(string username)
        {
            // Get back to the original name before url conversion
            BlogUsername = username.Replace(ContentGlobals.BLOGDELIMMETER, " ");

            using (var context = new DataContext())
            {

                // Get User based on authorid
                TheBlogUser = context.BlogUsers.FirstOrDefault(x => x.Username == BlogUsername);

                MaxBlogCount = BlogListModel.GetBlogSettings().MaxBlogsOnHomepageBeforeLoad;
                BlogTitle = BlogListModel.GetBlogSettings().BlogTitle;

                BlogsByUser = context.Blogs.Where(x => x.Author == BlogUsername && x.IsActive)
                            .OrderByDescending(blog => blog.Date)
                            .Take(MaxBlogCount)
                            .ToList();

                // Try permalink first
                TheBlog = BlogsByUser.FirstOrDefault(x => x.Author == BlogUsername);

                if (BlogsByUser.Count > 0)
                {
                    LastBlogId = BlogsByUser.LastOrDefault().BlogId;
                }
            }
        }
		public void default_when_sequence_has_multiple_items()
		{
			var expectedResult = 5;
			var sequence = new List<Int32> { 1, 3, 7, 9, expectedResult }.NotNull();

			var actualResult = sequence.LastOrDefault();

			Assert.Equal(expectedResult, actualResult);
		}
Example #23
0
        private dynamic GetMultipleJsonValue(List <Answer> answers, Question question, List <QnA.Config.Preview.ApplyTypes.ValidationErrorDetail> errorMessages)
        {
            if (errorMessages != null && errorMessages.Any())
            {
                return(JsonConvert.SerializeObject(answers?.LastOrDefault(a => a?.QuestionId == question.QuestionId)?.Value));
            }

            return(null);
        }
Example #24
0
        static void Main(string[] args) {

            var redditApi = new RedditSharp.Reddit();
            var dailyProgrammer = redditApi.GetSubreddit("dailyprogrammer");

            var blankList = new[] { DailyProgrammerPost.Blank, DailyProgrammerPost.Blank, DailyProgrammerPost.Blank, };

            var grid = @"Easy | Intermediate | Hard | Weekly/Bonus

---- -| --------------| ------| -------------
| []() | []() | []() | **-** |
";

            var postsQuery = dailyProgrammer.Posts
                //.Take(20) // Used for development to speed things up
                //.ToList()
                //.OrderBy(p => p.Created)
                .Select(p => new DailyProgrammerPost(p.Title, p.Url.AbsoluteUri));

            List<DailyProgrammerPost> allPosts = new List<DailyProgrammerPost>();

            foreach (var post in postsQuery) {
                if (post.IsChallenge) {

                    allPosts.Add(post);
                }
                else if (post.IsWeekly || post.IsBonus) {

                    var week = allPosts.LastOrDefault()?.WeekNumber;

                    allPosts.Add(new DailyProgrammerPost(post.Title, post.Url, week));
                }
            }

            foreach (var weekOfPosts in allPosts.GroupBy(p => p.WeekNumber)) {

                var orderedPosts = weekOfPosts
                    .Where(p => p.IsChallenge)
                    .OrderBy(p => p.ChallengeDifficulty)
                    .Concat(weekOfPosts.Where(p => !p.IsChallenge))
                    .ToList();

                if (orderedPosts.Count() < 3) {

                    orderedPosts = orderedPosts.Concat(blankList).Take(3).ToList();
                }
                string extraAppend = orderedPosts.Count == 4 ? " |" : " | **-** |";

                var line = "| " + string.Join(" | ", orderedPosts) + extraAppend;

                grid += line + Environment.NewLine;
            }

            File.WriteAllText("c:\\\\temp\\DailyProgrammerReditOutput.txt", grid);
            Console.WriteLine("Done!");
            Console.ReadLine();
        }
Example #25
0
    /// <summary>
    /// Get sub-square (i.e. layered obstacles)
    /// </summary>
    /// <returns></returns>
    public Square GetSubSquare()
    {
        if (subSquares.Count == 0)
        {
            return(this);
        }

        return(subSquares?.LastOrDefault());
    }
 /// <summary>
 /// Gets the last LengthOfStay entry for the hospital. The last entry is the most recent quarter for which data is available.
 /// </summary>
 /// <param name="hospital"></param>
 /// <param name="lengthsOfStay"></param>
 /// <returns></returns>
 private double? GetLengthOfStay(myhospitals_contact_data hospital, List<emergencydept4hourlengthofstaymetadata> lengthsOfStay)
 {
     var los = lengthsOfStay.LastOrDefault(a => a.MyHospitalsId == hospital.Id);
     if (los != null && los.LessThan4HrsPct.HasValue)
     {
         return (double)los.LessThan4HrsPct.Value;
     }
     return null;
 }
Example #27
0
        private string GetMultipleValue(List <Answer> answers, Question question, List <ValidationErrorDetail> errorMessages)
        {
            if (errorMessages != null && errorMessages.Any())
            {
                return(answers?.LastOrDefault(a => a?.QuestionId == question.QuestionId)?.Value);
            }

            return(null);
        }
Example #28
0
 private static string ToCsv(List<string> items)
 {
     var csvBuilder = new StringBuilder();
     for (int i = 0; i < items.Count() - 1; i++)
     {
         csvBuilder.Append("'" + items[i] + "', ");
     }
     csvBuilder.Append("'" + items.LastOrDefault() + "'");
     return csvBuilder.ToString();
 }
 public static int getSMSPoint()
 {
     s26web.Models.s26webDataContext db = new s26web.Models.s26webDataContext();
     int point = 0;
     var result = db.SMS.Where(w=>w.sms_id.Equals("000")).OrderByDescending(o => o.CreateTime).FirstOrDefault();
     List<string> sms_content = new List<string>();
     if(result != null)
         sms_content = result.content.Split('|').ToList();
     point = Convert.ToInt32(sms_content.LastOrDefault());
     return point;
 }
 public string sendLastSoundCommentFromIdLocation(int idLocation, string code)
 {
     List<Comments> comments = new List<Comments>();
     Comments lastComment = new Comments();
     comments = commentServices.findCommentByIdLocation(idLocation);
     lastComment = comments.LastOrDefault();
     if (lastComment != null)
         return lastComment.sound;
     else
         return null;
 }
        public ProcessOutboundRulesResult(List<OutboundRuleResult> processedResults)
        {
            _processedResults = processedResults;
            var lastMatchedResult = _processedResults.LastOrDefault(r => r.RuleMatched);

            if (lastMatchedResult != null)
            {
                _rewrittenResponseString = lastMatchedResult.RewrittenResponseString;
                //_finalAction = lastMatchedResult.ResultAction;
            }

        }
Example #32
0
 public int CheckForBloodNeccesity(List <DSNeedRequest> needRequests)
 {
     if (needRequests?.LastOrDefault() != null)
     {
         //TODO time sorted blood requests
         if (blood_type == needRequests.LastOrDefault().blood_type.title)
         {
             return(needRequests.LastOrDefault().intensity);
         }
     }
     return(49);
 }
		public async static Task<APISyncTracking> GetServerSyncTrackingByGetServiceType(string getServiceType)
		{
			List<APISyncTracking> returnRecordList = new List<APISyncTracking>();

			var db = DependencyService.Get<ISQLite>().GetAsyncConnection();

			await db.CreateTableAsync<APISyncTracking>();

			returnRecordList = await db.Table<APISyncTracking>().Where(row => row.GetServiceType == getServiceType).ToListAsync();

			return returnRecordList.LastOrDefault();
		}
Example #34
0
        public void ProcessFrames(List<Rectangle> rectangles)
        {
            // deltafying Frames ( Last - First )
            var fRect = rectangles.FirstOrDefault();
            var lRect = rectangles.LastOrDefault();

            _dh = lRect.Height - fRect.Height;
            _dw = lRect.Width - fRect.Width;

            _dx = lRect.X - fRect.X;
            _dy = lRect.Y - fRect.Y;
        }
        public ProcessInboundRulesResult(Uri originalUri, List<InboundRuleResult> processedResults)
        {
            _originalUri = originalUri;
            _processedResults = processedResults;
            var lastMatchedResult = _processedResults.LastOrDefault(r => r.RuleMatched);

            if (lastMatchedResult != null)
            {
                _rewrittenUri = lastMatchedResult.RewrittenUri;
                _finalAction = lastMatchedResult.ResultAction;
                _itemId = lastMatchedResult.ItemId;
            }
        }
        public static JSObject Closest(this JSObject self, String selector)
        {
            List<JSObject> parents = new List<JSObject>();

            // Run the selector on the whole document
            self.Document().QuerySelectorAll(selector).Each(node => {
                // Test each node and see if it contains the child
                if(node.Contains(self)) parents.Add(node);
            });

            // Return the item on the end
            return parents.LastOrDefault();
        }
Example #37
0
 private void ExtractJumpedFieldsAndEndField(List<Field> jumpedFieldsAndLastWhite)
 {
     if (jumpedFieldsAndLastWhite.Any() && jumpedFieldsAndLastWhite.Last().HasStone == false)
     {
         _endField = jumpedFieldsAndLastWhite.LastOrDefault();
         jumpedFieldsAndLastWhite.RemoveAt(jumpedFieldsAndLastWhite.Count - 1);
         _jumpedFields = jumpedFieldsAndLastWhite;
     }
     else
     {
         _jumpedFields = new List<Field>();
     }
 }
Example #38
0
 private async void FillIconTickAsync(object sender, EventArgs e, List <string> urls)
 {
     (sender as DispatcherTimer).Stop();
     if (HIOStaticValues.SYNC_ON == false && HIOStaticValues.IMPORT_ON == false && HIOStaticValues.CONNECTIONBHIO && HIOStaticValues.commandQ.IsEmpty)
     {
         var url = urls?.LastOrDefault();
         if (url != null)
         {
             urls.Remove(url);
             await Task.Run(new Action(() => { db.FillIcon(url); }));
         }
     }
     (sender as DispatcherTimer).Start();
 }
Example #39
0
        /// <summary>
        /// Resolves a default action of the given type for a given data item
        /// </summary>
        /// <param name="data">The data item</param>
        /// <param name="actionIdentifier">The action identifier</param>
        /// <returns></returns>
        public ActionToken ResolveDefault(IData data, ActionIdentifier actionIdentifier)
        {
            var interfaces = GetOrderedInterfaces(data.DataSourceId.InterfaceType);

            foreach (var type in interfaces)
            {
                var defaultAction = _defaultActions?.LastOrDefault(f => f.Check(type, data, actionIdentifier));
                if (defaultAction != null)
                {
                    return defaultAction.GetActionToken(data);
                }
            }
            return null;
        }
Example #40
0
        public void MapperFuncListTest()
        {
            var sourceList = new List <ComplexModels>();

            sourceList.Add(Temp);
            sourceList.Add(new ComplexModels
            {
                Int = 234
            });
            var targetObj = Mapper <ComplexModels, TargetModels> .MapList(sourceList);

            Assert.AreEqual(sourceList.Count, targetObj.Count);
            Assert.AreEqual(sourceList?.LastOrDefault()?.Int, targetObj?.LastOrDefault()?.Int);
        }
        public void CreateRestriction(string requestor, string restrictee, bool strict, bool makeReverse)
        {
            MatchRestriction restrict = new MatchRestriction()
            {
                Id                = _restrictions?.LastOrDefault()?.Id + 1 ?? 1,
                RequestorName     = requestor,
                RestrictedName    = restrictee,
                StrictRestriction = strict
            };

            _restrictions.Add(restrict);

            if (makeReverse)
            {
                MatchRestriction restrictReverse = new MatchRestriction()
                {
                    Id                = _restrictions?.LastOrDefault()?.Id + 1 ?? 1,
                    RequestorName     = restrictee,
                    RestrictedName    = requestor,
                    StrictRestriction = strict
                };
                _restrictions.Add(restrictReverse);
            }
        }
Example #42
0
        private void CheckChatForCommands()
        {
            if (messages?.LastOrDefault() == null)
            {
                return;
            }
            var idx = messages.Count < 10 ? messages.Count - 1 : 0; // After 10 messages, message at idx 0 is removed for new messages

            if (messages[idx] == prevMessage)
            {
                return;
            }

            prevMessage = messages[idx];
            var lastMsg    = ChatMessage.makeMessagePlaintext(messages.LastOrDefault().message);
            var farmerName = lastMsg.Substring(0, lastMsg.IndexOf(':'));

            lastMsg = lastMsg.Replace($"{farmerName}: ", ""); // Remove sender name from text
            string command = null;

            foreach (var commands in petCommands.Commands)
            {
                if (commands.Value.Any(lastMsg.Contains))
                {
                    command = commands.Key;
                }
            }

            if (command == null)
            {
                return;
            }
            if (command != livelyPet.commandBehavior)
            {
                livelyPet.commandBehavior = command;
                commandTimer = 4;
            }
        }
Example #43
0
        private void btn_TinhLaiSuat_Click(object sender, EventArgs e)
        {
            if (IsInValid())
            {
                return;
            }
            foreach (DataGridViewRow row in grid_TienDoThanhToan.Rows)
            {
                if (row.Cells[0].Value == null)
                {
                    continue;
                }
                var tienDoTruoc   = tienDos.LastOrDefault();
                var tongTienTruoc = tienDoTruoc != null ? tienDoTruoc.TongTienVay : 0;
                var tienDo        = new TienDo();
                tienDo.Name             = row.Cells[0].Value.ToString();
                tienDo.TiLeThanhToan    = row.Cells[1].Value.ToString().ParseDouble();
                tienDo.SoTien           = row.Cells[2].Value.ToString().ParseDouble();
                tienDo.ThoiHanThanhToan = row.Cells[3].Value.ToString().ParseDatetime();
                tienDo.TongTienVay      = tongTienTruoc + tienDo.SoTien;

                tienDos.Add(tienDo);
            }

            var tongTien      = double.Parse(txt_TongTien.Text);
            var phanTramVay   = double.Parse(txt_PhanTramVay.Text);
            var soTienVay     = double.Parse(txt_SoTienVay.Text);
            var soThangVay    = Int32.Parse(txt_SoThangVay.Text);
            var soThangConLai = soThangVay;
            var laiSuatUuDai1 = double.Parse(txt_LaiSuatUuDai1.Text) / 100;
            var sothangUuDai1 = Int32.Parse(txt_SoThangUuDai1.Text);
            var laiSuatThaNoi = double.Parse(txt_LaiSuatThaNoi.Text) / 100;
            var ngayGiaiNgan  = dateTimeNgayGiaiNgan.Value;
            var ngayHetHan    = ngayGiaiNgan.AddMonths(soThangVay);
            var tongTra       = 0.0;

            DataRow   dw;
            DataTable dt = new DataTable();

            dt.Columns.Add("STT", typeof(int));
            dt.Columns.Add("KyTraNo", typeof(DateTime));
            dt.Columns.Add("SoGocConLai", typeof(string));
            dt.Columns.Add("Goc", typeof(string));
            dt.Columns.Add("Lai", typeof(string));
            dt.Columns.Add("TienLai", typeof(string));
            dt.Columns.Add("Tong", typeof(string));

            for (int i = 1; i < soThangVay; i++)
            {
                double lai     = 0;
                double laisuat = 0;
                var    kyTraNo = ngayGiaiNgan.AddMonths(i);
                var    tienDo  = GetTienDo(kyTraNo);
                if (tienDo != null)
                {
                    RemoveTienDo(tienDo);
                }
                soTienVay = tienDo != null ? tienDo.TongTienVay - tongTra : soTienVay;
                var goc = Math.Round(soTienVay / (soThangVay - i), 0);

                if (sothangUuDai1 > 0)
                {
                    lai     = Math.Round(soTienVay * laiSuatUuDai1 / 12, 0);
                    laisuat = laiSuatUuDai1 * 100;
                    sothangUuDai1--;
                }
                else
                {
                    lai     = Math.Round(soTienVay * laiSuatThaNoi / 12, 0);
                    laisuat = laiSuatThaNoi * 100;
                }
                soTienVay -= goc;
                tongTra   += goc;

                dw                = dt.NewRow();
                dw["STT"]         = i;
                dw["KyTraNo"]     = kyTraNo;
                dw["SoGocConLai"] = soTienVay.AddSeparator();
                dw["Goc"]         = goc.AddSeparator();
                dw["Lai"]         = $"{laisuat}%";
                dw["TienLai"]     = lai.AddSeparator();
                dw["Tong"]        = (goc + lai).AddSeparator();
                dt.Rows.Add(dw);
            }

            grid_KetQua.DataSource = dt;
        }
Example #44
0
    public void LoadDb()
    {
        List <TranslateMessageDataLister> messages = new List <TranslateMessageDataLister>();

        using (var reader = new StreamReader(AssetDatabase.GetAssetPath(Database)))
        {
            while (!reader.EndOfStream)
            {
                string[] columns = reader.ReadLine().Split('\t');
                if (columns.Length != 5)
                {
                    Debug.LogWarning("A line in the file '" + Database + "' didn't contain 5 columns!");
                    continue;
                }

                if (!String.IsNullOrEmpty(columns[(int)DatabaseColumn.MessageText]))
                {
                    // Skip the entire line if it has the column name.
                    if (columns[(int)DatabaseColumn.MessageText] == "MessageText")
                    {
                        continue;
                    }

                    messages.Add(new TranslateMessageDataLister
                    {
                        Text = columns[(int)DatabaseColumn.MessageText]
                    });
                }

                var currentMessage = messages.LastOrDefault();
                if (currentMessage == null)
                {
                    continue;
                }

                if (!String.IsNullOrEmpty(columns[(int)DatabaseColumn.OptionKey]))
                {
                    currentMessage.OptionSet.Add(new TranslateMessageDataLister.TranslateOptionSet()
                    {
                        Name = columns[(int)DatabaseColumn.OptionKey]
                    });
                }

                var currentOptionSet = currentMessage.OptionSet.LastOrDefault();

                if (currentOptionSet != null && !String.IsNullOrEmpty(columns[(int)DatabaseColumn.OptionText]))
                {
                    currentOptionSet.Options.Add(new TranslateMessageDataLister.TranslateOption()
                    {
                        Text = columns[(int)DatabaseColumn.OptionText]
                    });
                }

                var currentMoodModifiers = currentOptionSet != null && currentOptionSet.Options.Count > 0 ?
                                           currentOptionSet.Options[currentOptionSet.Options.Count - 1].MoodSet :
                                           currentMessage.MoodSet;

                if (!String.IsNullOrEmpty(columns[(int)DatabaseColumn.OptionMoodKey]) &&
                    !String.IsNullOrEmpty(columns[(int)DatabaseColumn.OptionMoodValue]))
                {
                    currentMoodModifiers.Add(new MoodModifier()
                    {
                        Name         = columns[(int)DatabaseColumn.OptionMoodKey],
                        Modification = float.Parse(columns[(int)DatabaseColumn.OptionMoodValue])
                    });
                }
            }
        }
        m_Messages = new TranslateMessageData[messages.Count];
        for (int i = 0; i < messages.Count; i++)
        {
            TranslateMessageDataLister output = messages[i];
            m_Messages[i] = new TranslateMessageData()
            {
                Text      = output.Text,
                MoodSet   = output.MoodSet.ToArray(),
                OptionSet = new TranslateMessageData.TranslateOptionSet[output.OptionSet.Count]
            };

            for (int j = 0; j < output.OptionSet.Count; j++)
            {
                // Note: Implicit conversion.
                m_Messages[i].OptionSet[j] = output.OptionSet[j];
            }
        }
    }
Example #45
0
        /// <summary>
        /// The actual scheduling procedure
        /// </summary>
        private void Runner()
        {
            var scheduled = new Dictionary <long, KeyValuePair <long, DateTime> >();

            while (!m_terminate)
            {
                //TODO: As this is executed repeatedly we should cache it
                // to avoid frequent db lookups

                //Determine schedule list
                var lst = Program.DataConnection.Schedules;
                foreach (var sc in lst)
                {
                    if (!string.IsNullOrEmpty(sc.Repeat))
                    {
                        KeyValuePair <long, DateTime> startkey;

                        DateTime last = new DateTime(0, DateTimeKind.Utc);
                        DateTime start;
                        var      scticks = sc.Time.Ticks;

                        if (!scheduled.TryGetValue(sc.ID, out startkey) || startkey.Key != scticks)
                        {
                            start = new DateTime(scticks, DateTimeKind.Utc);
                            last  = sc.LastRun;
                        }
                        else
                        {
                            start = startkey.Value;
                        }

                        try
                        {
                            start = GetNextValidTime(start, last, sc.Repeat, sc.AllowedDays);
                        }
                        catch (Exception ex)
                        {
                            Program.DataConnection.LogError(sc.ID.ToString(), "Scheduler failed to find next date", ex);
                        }

                        //If time is exceeded, run it now
                        if (start <= DateTime.UtcNow)
                        {
                            var jobsToRun = new List <Server.Runner.IRunnerData>();
                            //TODO: Cache this to avoid frequent lookups
                            foreach (var id in Program.DataConnection.GetBackupIDsForTags(sc.Tags).Distinct().Select(x => x.ToString()))
                            {
                                //See if it is already queued
                                var tmplst = from n in m_worker.CurrentTasks
                                             where n.Operation == Duplicati.Server.Serialization.DuplicatiOperation.Backup
                                             select n.Backup;
                                var tastTemp = m_worker.CurrentTask;
                                if (tastTemp != null && tastTemp.Operation == Duplicati.Server.Serialization.DuplicatiOperation.Backup)
                                {
                                    tmplst.Union(new [] { tastTemp.Backup });
                                }

                                //If it is not already in queue, put it there
                                if (!tmplst.Any(x => x.ID == id))
                                {
                                    var entry = Program.DataConnection.GetBackup(id);
                                    if (entry != null)
                                    {
                                        jobsToRun.Add(Server.Runner.CreateTask(Duplicati.Server.Serialization.DuplicatiOperation.Backup, entry));
                                    }
                                }
                            }

                            //Caluclate next time, by finding the first entry later than now
                            try
                            {
                                start = GetNextValidTime(start, new DateTime(Math.Max(DateTime.UtcNow.AddSeconds(1).Ticks, start.AddSeconds(1).Ticks), DateTimeKind.Utc), sc.Repeat, sc.AllowedDays);
                            }
                            catch (Exception ex)
                            {
                                Program.DataConnection.LogError(sc.ID.ToString(), "Scheduler failed to find next date", ex);
                                continue;
                            }

                            Server.Runner.IRunnerData lastJob = jobsToRun.LastOrDefault();
                            if (lastJob != null && lastJob != null)
                            {
                                lock (m_lock)
                                    m_updateTasks[lastJob] = new Tuple <ISchedule, DateTime, DateTime>(sc, start, DateTime.UtcNow);
                            }

                            foreach (var job in jobsToRun)
                            {
                                m_worker.AddTask(job);
                            }

                            if (start < DateTime.UtcNow)
                            {
                                //TODO: Report this somehow
                                continue;
                            }
                        }

                        scheduled[sc.ID] = new KeyValuePair <long, DateTime>(scticks, start);
                    }
                }

                var existing = lst.ToDictionary(x => x.ID);
                //Sort them, lock as we assign the m_schedule variable
                lock (m_lock)
                    m_schedule = (from n in scheduled
                                  where existing.ContainsKey(n.Key)
                                  orderby n.Value.Value
                                  select new KeyValuePair <DateTime, ISchedule>(n.Value.Value, existing[n.Key])).ToArray();

                // Remove unused entries
                foreach (var c in (from n in scheduled where !existing.ContainsKey(n.Key) select n.Key).ToArray())
                {
                    scheduled.Remove(c);
                }

                //Raise event if needed
                if (NewSchedule != null)
                {
                    NewSchedule(this, null);
                }

                int waittime = 0;

                //Figure out a sensible amount of time to sleep the thread
                if (scheduled.Count > 0)
                {
                    //When is the next run scheduled?
                    TimeSpan nextrun = scheduled.Values.Min((x) => x.Value) - DateTime.UtcNow;
                    if (nextrun.TotalMilliseconds < 0)
                    {
                        continue;
                    }

                    //Don't sleep for more than 5 minutes
                    waittime = (int)Math.Min(nextrun.TotalMilliseconds, 60 * 1000 * 5);
                }
                else
                {
                    //No tasks, check back later
                    waittime = 60 * 1000;
                }

                //Waiting on the event, enables a wakeup call from termination
                // never use waittime = 0
                m_event.WaitOne(Math.Max(100, waittime), false);
            }
        }
Example #46
0
        //this should only be used for files in a directory, it will not behave properly if the files are in different or sub directories
        public void MakeZipForDirectory(string zipPath, List <FileStream> files,
                                        Dictionary <string, int> existingFileSizes, Dictionary <string, DateTime> existingFileDates, bool forceOverride)
        {
            using var archive = new ZipFile();

            foreach (var file in files)
            {
                try
                {
                    var      fileName    = Path.GetFileName(file.Name);
                    var      lastMatcher = FileAttributeList?.LastOrDefault(tpl => tpl.Item1.IsMatch(file.Name));
                    ZipEntry entry       = null;
                    using var reader = new StreamReader(file, WindowsEncoding, leaveOpen: true);
                    var targetFileSize = file.Length;
                    int longestLine    = 0;
                    var wholeFile      = reader.ReadToEnd();

                    if (lastMatcher.Item2.RecordType == RecordTypes.C_STREAM)
                    {
                        targetFileSize = EncodeStreamBinary(existingFileSizes, existingFileDates, forceOverride, archive, file.Name, ref entry, file, ref longestLine);
                    }
                    else
                    {
                        var newlineSplit = Environment.NewLine;
                        if (newlineSplit != "\r\n" && wholeFile.Contains("\r\n"))
                        {
                            Logger.WriteLine(8, $"warning: {fileName} looks like it has wrong line endings for the platform");
                            newlineSplit = "\r\n";
                        }

                        var splitFile = SplitBytes(file, newlineSplit);

                        if (wholeFile.Contains('\uFEFF'))
                        {
                            Logger.WriteLine(10, "BOM detected");
                        }

                        if (splitFile.Length < 3 && wholeFile.Length > 512 && string.Compare(Path.GetExtension(fileName), ".ddf", true) != 0)
                        {
                            lastMatcher = FileAttributeList?.LastOrDefault(tpl => tpl.Item1.IsMatch("this_is_a_binary_file"));
                            Logger.WriteLine(10, $"warning: {fileName} looks like it is either binary or has wrong line endings for the platform");
                        }
                        longestLine = splitFile.OrderByDescending(s => s.Length).FirstOrDefault()?.Length ?? 512;

                        //no need to translate if its already the same
                        if (lastMatcher == null || ((string.IsNullOrEmpty(lastMatcher.Item2.LineEndingOverride) ||
                                                     lastMatcher.Item2.LineEndingOverride == Environment.NewLine) && lastMatcher.Item2.RecordType != RecordTypes.C_VARIABLE))
                        {
                            if (ShouldSyncFile(existingFileSizes, existingFileDates, file.Name, (int)file.Length, forceOverride))
                            {
                                entry = archive.AddFile(fileName);
                                entry.CompressionLevel = CompressionLevel.Level9;
                                entry.EmitTimesInWindowsFormatWhenSaving = false;
                            }
                        }
                        else if (lastMatcher.Item2.RecordType == RecordTypes.C_VARIABLE)
                        {
                            try
                            {
                                var translatedFile = MakeVariableRecord(splitFile);
                                targetFileSize = translatedFile.Length - 2;
                                if (ShouldSyncFile(existingFileSizes, existingFileDates, file.Name, (int)targetFileSize, forceOverride))
                                {
                                    entry                  = archive.AddEntry(fileName, translatedFile);
                                    entry.IsText           = true;
                                    entry.CompressionLevel = CompressionLevel.Level9;
                                    entry.EmitTimesInWindowsFormatWhenSaving = false;
                                }
                            }
                            catch
                            {
                                Logger.WriteLine(10, $"failed to encode variable record {fileName} fallback to STREAM");
                                lastMatcher    = FileAttributeList?.LastOrDefault(tpl => tpl.Item1.IsMatch("this_is_a_binary_file"));
                                targetFileSize = EncodeStreamBinary(existingFileSizes, existingFileDates, forceOverride, archive, file.Name, ref entry, file, ref longestLine);
                            }
                        }
                        else
                        {
                            var translatedFile = JoinBytes(splitFile, lastMatcher.Item2.LineEndingOverride);
                            targetFileSize = translatedFile.Length;
                            if (ShouldSyncFile(existingFileSizes, existingFileDates, file.Name, (int)targetFileSize, forceOverride))
                            {
                                entry = archive.AddEntry(fileName, translatedFile);
                                entry.CompressionLevel = CompressionLevel.Level9;
                                entry.EmitTimesInWindowsFormatWhenSaving = false;
                            }
                        }
                    }

                    if (entry != null && lastMatcher != null)
                    {
                        entry._Extra = MakeVMSExtraBlock(
                            lastMatcher.Item2.RecordType,
                            lastMatcher.Item2.RecordLayout,
                            FileAttributes.M_IMPLIEDCC,
                            (ushort)longestLine,
                            (uint)targetFileSize,
                            0,
                            (ushort)lastMatcher.Item2.RecordSize,
                            0,
                            entry.CreationTime,
                            entry.ModifiedTime,
                            lastMatcher.Item2.OwnerId,
                            lastMatcher.Item2.System,
                            lastMatcher.Item2.Owner,
                            lastMatcher.Item2.Group,
                            lastMatcher.Item2.World
                            );
                    }
                }
                catch (Exception ex)
                {
                    Logger.WriteLine(10, $"failed with {ex} while operating on {file.Name}");
                }
            }

            archive.Save(zipPath);
        }
        private void OnTouchEffectAction(object sender, TouchActionEventArgs args)
        {
            var location = ConvertToPixel(args.Location);

            _editingInOuts.Clear();
            _editingSquares.Clear();
            _editingEllipses.Clear();
            switch (args.Type)
            {
            case TouchActionType.Pressed:
            {
                _pressPoint = location;
                switch (_mode)
                {
                case Mode.InOut:
                    _selectedFigure = _completedInOuts.LastOrDefault(q => q.IsIn(_pressPoint));
                    break;

                case Mode.Square:
                    _selectedFigure = _completedSquares.LastOrDefault(q => q.IsIn(_pressPoint));
                    break;

                case Mode.Ellipse:
                    _selectedFigure = _completedEllipses.LastOrDefault(q => q.IsIn(_pressPoint));
                    break;
                }
                canvasView.InvalidateSurface();
                break;
            }

            case TouchActionType.Moved:
                if (_selectedFigure != null)
                {
                    _selectedFigure.MoveTo(location);
                }
                else
                {
                    switch (_mode)
                    {
                    case Mode.InOut:
                        _editingInOuts.Add(CreateInOut(_pressPoint, location));
                        break;

                    case Mode.Square:
                        _editingSquares.Add(CreateSquare(_pressPoint, location));
                        break;

                    case Mode.Ellipse:
                        _editingEllipses.AddRange(CreateEllipses(_pressPoint, location));
                        break;
                    }
                }
                canvasView.InvalidateSurface();
                break;

            case TouchActionType.Released:
            case TouchActionType.Cancelled:
                switch (_mode)
                {
                case Mode.InOut:
                    if (_selectedFigure == null)
                    {
                        PutInOut(CreateInOut(_pressPoint, location));
                    }
                    break;

                case Mode.Square:
                    if (_selectedFigure == null)
                    {
                        PutSquare(CreateSquare(_pressPoint, location));
                    }
                    break;

                case Mode.Ellipse:
                    if (_selectedFigure == null)
                    {
                        PutEllipses(CreateEllipses(_pressPoint, location));
                    }
                    break;
                }
                _selectedFigure = null;
                canvasView.InvalidateSurface();
                break;
            }
        }
Example #48
0
 public void Load()
 {
     if (Servers is null || Servers.Count == 0)
     {
         Servers = new List <Server>()
         {
             new Server {
                 Host = "smtp.yandex.ru", Port = 565
             },
             new Server {
                 Host = "smtp.mail.ru", Port = 25
             },
             new Server {
                 Host = "smtp.gmail.com", Port = 467
             }
         }
     }
     ;
     if (Senders is null || Senders.Count == 0)
     {
         Senders = new List <Sender>()
         {
             new Sender {
                 Name = "Ivan Ivanov", Address = "*****@*****.**"
             },
             new Sender {
                 Name = "Petr Petrov", Address = "*****@*****.**"
             },
             new Sender {
                 Name = "Sidor Sidorov", Address = "*****@*****.**"
             }
         }
     }
     ;
     if (Recipients is null || Recipients.Count == 0)
     {
         Recipients = new List <Recipient>()
         {
             new Recipient {
                 Id = 1, Name = "John Lennon", Address = "*****@*****.**"
             },
             new Recipient {
                 Id = 2, Name = "Lady Gaga", Address = "*****@*****.**"
             },
             new Recipient {
                 Id = 3, Name = "Katy Perry", Address = "*****@*****.**"
             }
         }
     }
     ;
     if (Emails is null || Emails.Count == 0)
     {
         Emails = new List <Email>()
         {
             new Email {
                 Subject = "Test Email #1", Message = "Test... 1"
             },
             new Email {
                 Subject = "Test Email #2", Message = "Test... 2"
             },
             new Email {
                 Subject = "Test Email #3", Message = "Test... 3"
             }
         }
     }
     ;
     if (Schedules is null || Schedules.Count == 0)
     {
         Schedules = new List <Schedule>()
         {
             new Schedule()
             {
                 Server    = Servers.FirstOrDefault(),
                 Sender    = Senders.FirstOrDefault(),
                 Recipient = Recipients.FirstOrDefault(),
                 Email     = Emails.FirstOrDefault()
             },
             new Schedule()
             {
                 Server    = Servers.LastOrDefault(),
                 Sender    = Senders.LastOrDefault(),
                 Recipient = Recipients.LastOrDefault(),
                 Email     = Emails.LastOrDefault()
             }
         }
     }
     ;
 }
Example #49
0
        public static void Executar()
        {
            var alunos = new List <Aluno>
            {
                new Aluno()
                {
                    Nome = "Pedro", Idade = 24, Nota = 8.0
                },
                new Aluno()
                {
                    Nome = "Andre", Idade = 23, Nota = 4.3
                },
                new Aluno()
                {
                    Nome = "Ana", Idade = 22, Nota = 8.5
                },
                new Aluno()
                {
                    Nome = "Jose", Idade = 27, Nota = 7.7
                },
                new Aluno()
                {
                    Nome = "Tulio", Idade = 18, Nota = 6.8
                },
                new Aluno()
                {
                    Nome = "Marcio", Idade = 29, Nota = 8.7
                }
            };

            var pedro = alunos.Single(aluno => aluno.Nome.Equals("Pedro"));

            Console.WriteLine($"{pedro.Nome} {pedro.Nota}");

            var fulano = alunos.SingleOrDefault(
                aluno => aluno.Nome.Equals("Fulano"));

            if (fulano == null)
            {
                Console.WriteLine("Aluno Inexistente!");
            }

            var ana = alunos.First(Aluno => Aluno.Nome.Equals("Ana! "));

            Console.WriteLine(ana.Nota);

            var sicrano = alunos.FirstOrDefault(
                aluno => aluno.Nota.Equals("Sicrano"));

            if (sicrano == null)
            {
                Console.WriteLine("Aluno Inexistente");
            }

            var outraAna = alunos.LastOrDefault(aluno => aluno.Nome.Equals("Ana"));

            Console.WriteLine(outraAna.Nota);

            var exemploSkip = alunos.Skip(1).Take(3);

            foreach (var item in exemploSkip)
            {
                Console.WriteLine(item.Nome);
            }

            var maiorNota = alunos.Max(aluno => aluno.Nota);

            Console.WriteLine(maiorNota);

            var menorNota = alunos.Min(aluno => aluno.Nota);

            Console.WriteLine(menorNota);

            var somatorioNotas = alunos.Sum(aluno => aluno.Nota);

            Console.WriteLine(somatorioNotas);

            var mediaDaTurma = alunos.Where(a => a.Nota >= 7).Average(aluno => aluno.Nota);

            Console.WriteLine(mediaDaTurma);
        }
Example #50
0
        public ActionResult Index1(string text, string Schols, string date1, string date2, string DeliveredName, string Recipedname, bool update = false)


        {
            //if (date1 != null)
            //{
            //    DateTime dt = DateTime.ParseExact(date1.ToString(), "MM.dd.yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
            //    string s = dt.ToString("dd.M.yyyy", CultureInfo.InvariantCulture);
            //}
            //if (date2 != null)
            //{
            //    DateTime dt1 = DateTime.ParseExact(date2.ToString(), "MM.dd.yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
            //    string s1 = dt1.ToString("dd.M.yyyy", CultureInfo.InvariantCulture);

            //}



            if (string.IsNullOrEmpty(text))
            {
                text = Schols;
            }


            ViewBag.KayıtHata1 = "";
            ViewBag.KayıtHata2 = "";
            ViewBag.KayıtHata3 = "";

            //ViewBag.SchoolName = "";
            //date1 = TempData["date1"] != null ? (DateTime)TempData["date1"] : DateTime.Now;
            //date2 = TempData["date2"] != null ? (DateTime)TempData["date2"] : DateTime.Now;
            //ekrandan göndermede sıkıntı olduğu için şimdilik default değer atandı sorun çözülene kadar böyle devam edilecek

            ViewBag.selected = text;
            List <Book> bk = new List <Book>();

            bk = db.Books.ToList();
            List <BooksDelivery>          bkn            = db.BooksDeliverys.Where(x => x.SchoolsName == text).ToList();
            List <SchoolsCategory>        sc             = db.SchoolsCategorys.ToList();
            List <BooksCategory>          _booksCategory = db.BooksCategorys.ToList();
            List <BooksDelivery>          bkstk          = db.BooksDeliverys.ToList();
            List <BooksDeliveryViewModel> wmlist         = new List <BooksDeliveryViewModel>();
            List <LookUpDto> LookUpDto = new List <LookUpDto>();
            var    Bookneed            = db.BooksNeeds.Select(x => x.ShoolName).Distinct().ToList();
            string parameters          = Bookneed[0];

            ViewBag.ShoolListViewBag = Bookneed;

            foreach (var item in bkn)
            {
                // bu model foreach içinde eklenmeli
                BooksDeliveryViewModel wm = new BooksDeliveryViewModel();
                wm.Id         = item.Id;
                wm.BookId     = item.BookId;
                wm.CreateDate = item.CreateDate;
                //wm.UserId = item.UserId;
                wm.SchoolsName = item.SchoolsName;
                wm.Deliverer   = bkn.LastOrDefault(x => x.BookId == item.BookId).Deliverer;
                wm.Recipient   = bkn.LastOrDefault(x => x.BookId == item.BookId).Recipient;
                //ViewBag.SchoolName = item.SchoolsName;
                //ViewBag.TeslimEden = wm.Deliverer;
                //ViewBag.TeslimAlan = wm.Recipient;
                wm.Name = bk.FirstOrDefault(x => x.Id == item.BookId).Name;
                //wm.DemandDate = item.DemandDate;
                wm.Class = bk.FirstOrDefault(x => x.Id == item.BookId).Class;

                //wm.BookCategory = bk.FirstOrDefault(x => x.Id == item.BookId).BookType;
                // stoktaki kitap sayısını bulmak için çalışıldı.
                if ((bkstk.FirstOrDefault(x => x.BookId == item.BookId)) == null)
                {
                    wm.BookCount = 0;
                }
                else
                {
                    //burası birden fazla kayıt gelebileceğinden dolayı liste olrak tanımlanmalı.
                    //wm.BookCount = bkstk.FirstOrDefault(x => x.BookId == item.BookId).BookCount;
                    wm.BookCount = bkstk.FirstOrDefault(x => x.Id == item.Id && x.CreateDate == item.CreateDate).BookCount;
                }

                //wm.BookCount = item.BookCount;
                wm.SchoolsCategory = db.Books.FirstOrDefault(x => x.Id == item.BookId).BookType;
                wmlist.Add(wm);
            }
            if (text != null && text != string.Empty)
            {
                parameters = text;
            }

            var DateFilte1  = new DateTime();
            var DateFilter2 = new DateTime();

            DateFilte1  = DateTime.Now;
            DateFilter2 = DateTime.Now;

            // Sorun olduğu için yoruma alınmıştı.
            DateFilte1 = new DateTime(DateFilte1.Year, DateFilte1.Month, DateFilte1.Day, 0, 0, 0);


            if (!string.IsNullOrEmpty(date1))
            {
                string[] words = date1.Split('.');
                DateFilte1 = new DateTime(Convert.ToInt32(words[2].Split(' ')[0]), Convert.ToInt32(words[1]), Convert.ToInt32(words[0]), 0, 0, 0);
            }
            if (!string.IsNullOrEmpty(date2))
            {
                string[] words = date2.Split('.');
                DateFilter2 = new DateTime(Convert.ToInt32(words[2].Split(' ')[0]), Convert.ToInt32(words[1]), Convert.ToInt32(words[0]), 0, 0, 0);
            }

            DateFilte1  = new DateTime(DateFilte1.Year, DateFilte1.Month, DateFilte1.Day, 0, 0, 0);
            DateFilter2 = new DateTime(DateFilter2.Year, DateFilter2.Month, DateFilter2.Day, 23, 59, 59);
            //DateTime temp = DateTime.ParseExact("11/02/16", "dd/MM/yy", CultureInfo.InvariantCulture);

            TempData["date1"] = DateFilte1;
            TempData["date2"] = DateFilter2;
            //parameters.Trim()
            //wmlist içindeki veriler hatalı geliyor.
            var BooksDeliveryList = wmlist.Where(x => x.SchoolsName.Trim() == text && x.CreateDate >= DateFilte1 && x.CreateDate <= DateFilter2);

            if (update)
            {
                foreach (var UpdateItem in BooksDeliveryList)
                {
                    BooksDelivery updateEntity = new BooksDelivery();
                    var           Entity       = db.BooksDeliverys.FirstOrDefault(x => x.Id == UpdateItem.Id);
                    Entity.Id              = UpdateItem.Id;
                    Entity.Recipient       = Recipedname;
                    Entity.Deliverer       = DeliveredName;
                    Entity.UpdateDate      = DateTime.Now;
                    db.Entry(Entity).State = EntityState.Modified;
                    db.SaveChanges();
                }
            }
            //Aynı kitaptan istenirse gruplama yapılıyor
            var results = (from ssi in BooksDeliveryList
                           group ssi by new { ssi.Class, ssi.Name } into g
                           select new { Class = g.Key.Class, Name = g.Key.Name, BookCount = g.Sum(x => x.BookCount) }).ToList();

            List <BooksDeliveryViewModel> wmlistresult = new List <BooksDeliveryViewModel>();

            foreach (var item in results)
            {
                BooksDeliveryViewModel wmresult = new BooksDeliveryViewModel();

                wmresult.BookCount = item.BookCount;
                wmresult.Class     = item.Class;
                wmresult.Name      = item.Name;
                wmlistresult.Add(wmresult);
            }
            List <BooksDelivery> ResultBookDeliveries = db.BooksDeliverys.Where(x => x.SchoolsName == text).ToList();

            if (ResultBookDeliveries.Count() != 0 && !string.IsNullOrEmpty(text))
            {
                ViewBag.SchoolName = ResultBookDeliveries.Where(x => x.SchoolsName == text).OrderByDescending(x => x.UpdateDate).FirstOrDefault().SchoolsName;
                ViewBag.TeslimEden = ResultBookDeliveries.Where(x => x.SchoolsName == text).OrderByDescending(x => x.UpdateDate).FirstOrDefault().Deliverer;
                ViewBag.TeslimAlan = ResultBookDeliveries.Where(x => x.SchoolsName == text).OrderByDescending(x => x.UpdateDate).FirstOrDefault().Recipient;
            }

            return(View(wmlistresult));
            //kişinin kendi eklediği kayıtları görmesi sağlandı
            //return View(wmlist.Where(x => x.SchoolsName.Trim() == parameters.Trim() && x.CreateDate >= DateFilte1 && x.CreateDate <= DateFilter2));
        }
Example #51
0
        /// <summary>МЕТОД Изменяем логи xLog</summary>
        /// <param name="pUser">Кто создал/изменил протокол</param>
        /// <param name="pTipLog">Тип лога Создан, Изменён, Удалён</param>
        public void MET_ChangeLogs1(int pUser, string pTipLog)
        {
            string  _jLog     = PROP_xLog;
            var     _ListLogs = new List <UserLog>();
            UserLog _Log;

            // Если нет логов и это НЕ создание протокола
            if (string.IsNullOrEmpty(_jLog) && pTipLog != "Создан")
            {
                // Если изменили протокол (вытаскиваем информацию из xDateUp, pDate)
                _Log = new UserLog
                {
                    Cod                        = 1,
                    Date                       = PROP_pDate < PROP_xDateUp?PROP_pDate.ToString("dd.MM.yyyy H:mm") : PROP_xDateUp.ToString("dd.MM.yyyy H:mm"),
                                          Tip  = "Создан",
                                          User = PROP_xUserUp,
                                          Ver  = ""
                };
                _ListLogs.Add(_Log);
                // Если ВОЗМОЖНО менялся протокол
                if (PROP_xDateUp > PROP_pDate)
                {
                    _Log = new UserLog
                    {
                        Cod  = 2,
                        Date = PROP_xDateUp.ToString("dd.MM.yyyy H:mm"),
                        Tip  = "Изменён",
                        User = PROP_xUserUp,
                        Ver  = ""
                    };
                    _ListLogs.Add(_Log);
                }
            }
            else
            {
                // Заполняем старые логи
                JObject _Json = JObject.Parse(_jLog);
                foreach (var i in _Json["Log"].Children())
                {
                    _Log = new UserLog
                    {
                        Cod  = (int)i["Cod"],
                        Date = (string)i["Date"],
                        Tip  = (string)i["Tip"],
                        User = (int)i["User"],
                        Ver  = (string)i["Ver"]
                    };
                    _ListLogs.Add(_Log);
                }
            }
            // Берем последний лог и смотрим тип, кто и когда его менял
            _Log = _ListLogs.LastOrDefault();
            if (_Log != null && _Log.Tip == pTipLog && _Log.User == pUser && _Log.Ver == MyMet.MET_Ver() &&
                (DateTime.Now - DateTime.ParseExact(_Log.Date, "dd.MM.yyyy H:mm", CultureInfo.InvariantCulture)).Hours < 6)
            {
                // Если прошло менее 6 часов просто меняем время редактирования у последнего лога
                _Log.Date = DateTime.Now.ToString("dd.MM.yyyy H:mm");
            }
            else
            {
                // Иначе добавляем новый логи
                _Log = new UserLog
                {
                    Cod  = _ListLogs.Count + 1,
                    Date = DateTime.Now.ToString("dd.MM.yyyy H:mm"),
                    Tip  = pTipLog,
                    User = pUser,
                    Ver  = MyMet.MET_Ver()
                };
                _ListLogs.Add(_Log);
            }
            PROP_xLog = JsonConvert.SerializeObject(_ListLogs,
                                                    Formatting.None,
                                                    new JsonSerializerSettings {
                DefaultValueHandling = DefaultValueHandling.Ignore
            });
            PROP_xLog = "{ \"Log\":" + PROP_xLog + "}";
        }
Example #52
0
        private void ChooseRandomItems(List <TaskItem> allItems, int count, string[] fromCategory, List <TaskItem> targetList, bool negateFromCategory = false)
        {
            IEnumerable <TaskItem> sourceList;

            // Restrict only to the required categories
            if (fromCategory == null || fromCategory.Contains("*"))
            {
                sourceList = new List <TaskItem>(allItems);
            }
            else
            if (negateFromCategory)
            {
                sourceList = allItems.Where(x => x.Categories?.Any(c => fromCategory.Contains(c)) != true);
            }
            else
            {
                sourceList = allItems.Where(x => x.Categories?.Any(c => fromCategory.Contains(c)) == true);
            }

            // Prepare items for sorting
            sourceList = sourceList.Where(x => !targetList.Contains(x)); // Skip items that are already in the selection
            var lastChoosedItems = previousChoosedCombinations?.LastOrDefault();

            sourceList.ForEach(x => x.OrderData = new TaskItemOrderData()
            {
                CountOfPreviousUsing = countOfTaskPreviousleyChoosed.Get(x.Index) ?? 0,
                WasInPreviousRound   = lastChoosedItems?.Contains(x) == true,
                CountOfPreviousRoundWhenWasInPairWithOtherItem = 0,
                RandomValue = random.NextDouble(),
            });

            // Anonymous method for sorting of sourceList
            void sortSourceList() => sourceList = sourceList
                                                  .OrderBy(x => x.OrderData.CountOfPreviousUsing)                          // Sort by the number of previous uses
                                                  .ThenBy(x => x.OrderData.WasInPreviousRound)                             // Penalise items chosen in the last round
                                                  .ThenBy(x => x.OrderData.CountOfPreviousRoundWhenWasInPairWithOtherItem) // Only required number (first N)
                                                  .ThenBy(x => x.OrderData.RandomValue);                                   // At last level, sort randomly

            sortSourceList();                                                                                              // 1st sort

            // TODO: stejné kombinace úloh (count > 1), jako v minulsoti při se snažit "rozhodit"
            if (Setting.SeparatePreviousPairs && count > 1 && previousChoosedCombinations.Count > 0)
            {
                var selectedItems = new List <TaskItem>();
                selectedItems.Add(sourceList.First());
                sourceList = sourceList.Skip(1); // Remove first item
                while (selectedItems.Count < count && sourceList.Count() > 0)
                {
                    sourceList.ForEach(x => x.OrderData.CountOfPreviousRoundWhenWasInPairWithOtherItem =
                                           previousChoosedCombinations
                                           .Where(y => y.Contains(x))
                                           .Count(y => y.Intersect(selectedItems).Any()));
                    //.Sum(y => prvItems.Count(z => y.Contains(y))));
                    sortSourceList();
                    selectedItems.Add(sourceList.First());
                    sourceList = sourceList.Skip(1); // Remove first item
                }
                sourceList = selectedItems;
            }

            sourceList = sourceList.Take(count).ToList();

            targetList.AddRange(sourceList);

            foreach (var item in sourceList)
            {
                if (countOfTaskPreviousleyChoosed.ContainsKey(item.Index))
                {
                    countOfTaskPreviousleyChoosed[item.Index]++;
                }
                else
                {
                    countOfTaskPreviousleyChoosed[item.Index] = 1;
                }
            }
        }
Example #53
0
 /// <summary>
 /// What is my current occupation?
 /// If there is more than one only the last one will be returned
 /// </summary>
 /// <returns>current occupation</returns>
 public Occupation GetCurrentOccupation()
 {
     return(_occupations?.LastOrDefault(o => o.Ended == null));
 }
Example #54
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="page"></param>
        /// <param name="cancellationToken"></param>
        /// <exception cref="InvalidFeedSettingsException">Thrown when the feed's settings aren't valid.</exception>
        /// <returns></returns>
        public async Task <PageReadResult> GetSongsAsync(Uri uri, CancellationToken cancellationToken)
        {
            string pageText = "";
            Dictionary <string, ScrapedSong> songs = new Dictionary <string, ScrapedSong>();

            Logger.Debug($"Getting songs from '{uri}'");
            IWebResponseMessage?response = null;

            try
            {
                response = await WebUtils.WebClient.GetAsync(uri, cancellationToken).ConfigureAwait(false);

                response.EnsureSuccessStatusCode();
                pageText = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
            }
            catch (OperationCanceledException ex)
            {
                return(PageReadResult.CancelledResult(uri, ex));
            }
            catch (WebClientException ex)
            {
                string errorText  = string.Empty;
                int    statusCode = ex?.Response?.StatusCode ?? 0;
                if (statusCode != 0)
                {
                    switch (statusCode)
                    {
                    case 404:
                        errorText = $"{uri.ToString()} was not found.";
                        break;

                    case 408:
                        errorText = $"Timeout getting first page in ScoreSaberReader: {uri}: {ex.Message}";
                        break;

                    default:
                        errorText = $"Site Error getting first page in ScoreSaberReader: {uri}: {ex.Message}";
                        break;
                    }
                }
                Logger?.Debug(errorText);
                // No need for a stacktrace if it's one of these errors.
                if (!(statusCode == 404 || statusCode == 408 || statusCode == 500))
                {
                    Logger?.Debug($"{ex.Message}\n{ex.StackTrace}");
                }
                return(PageReadResult.FromWebClientException(ex, uri));
            }
            catch (Exception ex)
            {
                string message = $"Uncaught error getting the first page in ScoreSaberReader.GetSongsFromScoreSaberAsync(): {ex.Message}";
                return(new PageReadResult(uri, new List <ScrapedSong>(), null, null, 0, new FeedReaderException(message, ex, FeedReaderFailureCode.SourceFailed), PageErrorType.Unknown));
            }
            finally
            {
                response?.Dispose();
                response = null;
            }
            bool        isLastPage;
            ScrapedSong?firstSong   = null;
            ScrapedSong?lastSong    = null;
            int         songsOnPage = 0;

            try
            {
                List <ScrapedSong>?diffs = GetSongsFromPageText(pageText, uri, Settings.StoreRawData || StoreRawData);
                firstSong   = diffs?.FirstOrDefault();
                lastSong    = diffs?.LastOrDefault();
                songsOnPage = diffs?.Count ?? 0;
                isLastPage  = (diffs?.Count ?? 0) < SongsPerPage;
                foreach (ScrapedSong?diff in diffs)
                {
                    if (!songs.ContainsKey(diff.Hash) && (Settings.Filter == null || Settings.Filter(diff)))
                    {
                        songs.Add(diff.Hash, diff);
                    }
                    if (Settings.StopWhenAny != null && Settings.StopWhenAny(diff))
                    {
                        isLastPage = true;
                    }
                }
            }
            catch (JsonReaderException ex)
            {
                string message = "Unable to parse JSON from text";
                Logger?.Debug($"{message}: {ex.Message}\n{ex.StackTrace}");
                return(new PageReadResult(uri, null, firstSong, lastSong, songsOnPage, new FeedReaderException(message, ex, FeedReaderFailureCode.PageFailed), PageErrorType.ParsingError));
            }
            catch (Exception ex)
            {
                string message = $"Unhandled exception from GetSongsFromPageText() while parsing {uri}";
                Logger?.Debug($"{message}: {ex.Message}\n{ex.StackTrace}");
                return(new PageReadResult(uri, null, firstSong, lastSong, songsOnPage, new FeedReaderException(message, ex, FeedReaderFailureCode.PageFailed), PageErrorType.ParsingError));
            }

            return(new PageReadResult(uri, songs.Values.ToList(), firstSong, lastSong, songsOnPage, isLastPage));
        }
        /// <summary>
        /// Holds the editor configuration for a file, please use <see cref="EditorConfigParser.Parse"/> to get an instance
        /// </summary>
        internal FileConfiguration(Version version, string fileName, List <ConfigSection> sections)
        {
            if (version == null)
            {
                throw new ArgumentNullException(nameof(version));
            }
            if (string.IsNullOrWhiteSpace(fileName))
            {
                throw new ArgumentException("file should not be null or whitespace", nameof(fileName));
            }

            FileName = fileName;
            Version  = version;
            Sections = sections;

            var allProperties = sections.SelectMany(section => section);
            var properties    = new Dictionary <string, string>();

            foreach (var kv in allProperties)
            {
                properties[kv.Key] = kv.Value;
            }

            IndentStyle            = Sections.FirstOrDefault(s => s.IndentStyle.HasValue)?.IndentStyle;
            IndentSize             = Sections.LastOrDefault(s => s.IndentSize != null)?.IndentSize;
            TabWidth               = Sections.FirstOrDefault(s => s.TabWidth.HasValue)?.TabWidth;
            EndOfLine              = Sections.FirstOrDefault(s => s.EndOfLine.HasValue)?.EndOfLine;
            Charset                = Sections.FirstOrDefault(s => s.Charset.HasValue)?.Charset;
            TrimTrailingWhitespace = Sections.FirstOrDefault(s => s.TrimTrailingWhitespace.HasValue)?.TrimTrailingWhitespace;
            InsertFinalNewline     = Sections.FirstOrDefault(s => s.InsertFinalNewline.HasValue)?.InsertFinalNewline;
            MaxLineLength          = Sections.FirstOrDefault(s => s.MaxLineLength.HasValue)?.MaxLineLength;

            //default tab_width to indent_size when indent size is a number
            if (IndentSize != null && IndentSize.NumberOfColumns.HasValue)
            {
                TabWidth = IndentSize.NumberOfColumns.Value;
                properties["tab_width"] = TabWidth.Value.ToString();
            }

            // Set indent_size to "tab" if indent_size is unspecified and indent_style is set to "tab".
            if (IndentStyle.HasValue && IndentStyle == Core.IndentStyle.Tab && IndentSize == null &&
                Version >= new Version(0, 10))
            {
                IndentSize = IndentSize.Tab;
                properties["indent_size"] = "tab";
            }

            // Set tab_width to indent_size if indent_size is specified and tab_width is unspecified
            if (IndentSize != null && !TabWidth.HasValue && !IndentSize.UseTabWidth)
            {
                //only set tab_width to indent_size if indent size holds a positive integer
                if (IndentSize.NumberOfColumns.HasValue && IndentSize.NumberOfColumns.Value >= 0)
                {
                    TabWidth = IndentSize.NumberOfColumns.Value;
                    properties["tab_width"] = TabWidth.Value.ToString();
                }

                // unset carries over see:
                //  ctest . -R "unset_indent_size"
                else if (IndentSize.IsUnset)
                {
                    TabWidth = new int?();
                    properties["tab_width"] = "unset";
                }
            }

            // Set indent_size to tab_width if indent_size is "tab"
            if (IndentSize != null && TabWidth != null && IndentSize.UseTabWidth)
            {
                IndentSize = IndentSize.Columns(TabWidth.Value);
                properties["indent_size"] = TabWidth.Value.ToString();
            }

            Properties = new ReadOnlyDictionary <string, string>(properties);
        }
Example #56
0
 internal static TView GetLastOrDefault <TView>()
     where TView : class, IView <IViewModel>
 {
     return((TView)_viewsWeakReferences?.LastOrDefault()?.GetTarget());
 }
Example #57
0
        public static void Executar()
        {
            List <Aluno> alunos = new List <Aluno>
            {
                new Aluno()
                {
                    Nome = "Pedro", Idade = 24, Nota = 8.0
                },
                new Aluno()
                {
                    Nome = "Betao", Idade = 25, Nota = 9.0
                },
                new Aluno()
                {
                    Nome = "Lucas", Idade = 27, Nota = 10.0
                },
                new Aluno()
                {
                    Nome = "Ana", Idade = 27, Nota = 10.0
                },
                new Aluno()
                {
                    Nome = "Ana", Idade = 21, Nota = 7.5
                },
                new Aluno()
                {
                    Nome = "Julia", Idade = 18, Nota = 6.8
                },
            };


            var pedro = alunos.Single(aluno => aluno.Nome.Equals("Pedro"));

            Console.WriteLine($"{pedro.Nome} {pedro.Nota}");

            var fulano = alunos.SingleOrDefault(aluno => aluno.Nome.Equals("Pedro"));

            Console.WriteLine($"{pedro.Nome} {pedro.Nota}");

            if (fulano == null)
            {
                Console.WriteLine("Aluno inexistente!");
            }

            var ana = alunos.First(aluno => aluno.Nome.Equals("Ana"));

            Console.WriteLine(ana.Nota);

            var sicrano = alunos.FirstOrDefault(aluno => aluno.Nota.Equals("Sicrano"));

            if (sicrano == null)
            {
                Console.WriteLine("Sicrano inexistente!");
            }

            var outraAna = alunos.LastOrDefault(aluno => aluno.Nota.Equals("Ana"));

            if (sicrano == null)
            {
                Console.WriteLine("Outra ana inexistente!");
            }
            else
            {
                Console.WriteLine(outraAna.Nota);
            }

            var exemploSkip = alunos.Skip(1).Take(3);

            foreach (var item in exemploSkip)
            {
                Console.WriteLine(item.Nome);
            }

            var menorNota = alunos.Min(aluno => aluno.Nota);

            Console.WriteLine(menorNota);

            var somatorioNotas = alunos.Sum(aluno => aluno.Nota);

            Console.WriteLine(somatorioNotas);

            var mediaNotas = alunos.Where(a => a.Nota >= 7).Average(aluno => aluno.Nota);

            Console.WriteLine(mediaNotas);
        }
Example #58
0
 internal Parameter LastOrNull() => parameters?.LastOrDefault();
Example #59
0
 private int pairsScore(List <int> pairs)
 {
     return(pairs?.LastOrDefault() * 2 ?? 0);
 }
Example #60
-2
        public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
        {
            var tcs = new TaskCompletionSource<object>();

            context.ApplicationInstance.CompleteRequest();
            var clientId = new Guid(context.Request["clientId"]);

            var jsons = new List<CommandMessage>();

            var bus = SheepJaxComet.PollingCommandBus;
            var obs = bus.GetObservable(clientId).Replay();
            var subscription = obs.Connect();
            obs.TakeUntil(Observable.Interval(LongPollTimeout))
                .TakeUntil(obs.Take(1).Delay(BatchInterval))
                .Subscribe(jsons.Add, context.AddError, ()=>
                    {
                        try
                        {
                            subscription.Dispose();
                            context.Response.Write("[" + string.Join(",", jsons.Select(x => x.Message)) + "]");
                            bus.Consumed(jsons.LastOrDefault());
                        }
                        catch (Exception ex)
                        {
                            _logger.Error("SheepJax exception thrown while writing to long-polling connection", ex);
                        }
                        finally
                        {
                            tcs.SetResult(null);
                            cb(tcs.Task);
                        }
                    });

            return tcs.Task;
        }