System.Func.Invoke(System.DateTime)

Here are the examples of the csharp api System.Func.Invoke(System.DateTime) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

55 Examples 7

19 Source : CallIncident.cs
with Apache License 2.0
from AantCoder

public static void IncidentLogAppend(string record, ModelMailStartIncident mail, string data, int fromWorth = 0, int toWorth = 0)
        {
            Func<DateTime, string> dateTimeToStr = dt => dt == DateTime.MinValue ? "" : dt.ToString("yyyy-MM-dd hh:mm:ss", CultureInfo.InvariantCulture);

            var fileName = Path.Combine(Path.GetDirectoryName(Repository.Get.SaveFileName)
                , $"Incidents_{DateTime.Now.ToString("yyyy-MM")}.csv");
            if (!File.Exists(fileName))
            { 
                File.WriteAllText(fileName, $"time;record" +
                    $";fromLogin;toLogin;fromDay;toDay;fromWorth;toWorth;paramIncident;serverId" +
                    //структура data:
                    $";worthTarget;delayAfterMail;numberOrder;countInOrder" + 
                    Environment.NewLine, Encoding.UTF8);
            }

            if (fromWorth == 0) fromWorth = (int)Repository.GetPlayerByLogin(mail.From.Login).AllCostWorldObjects();
            if (toWorth == 0) toWorth = (int)Repository.GetPlayerByLogin(mail.To.Login).AllCostWorldObjects();

            var param = $"{mail.IncidentType} lvl:{mail.IncidentMult} mode:{mail.IncidentArrivalMode} who:{mail.IncidentFaction}";

            var contentLog = dateTimeToStr(DateTime.Now) + ";" + record
                + $";{mail.From.Login};{mail.To.Login};{mail.From.LastTick / 60000};{mail.To.LastTick / 60000};{fromWorth};{toWorth};{param};{mail.PlaceServerId}"
                + ";" + data + Environment.NewLine;

            Loger.Log("IncidentLogAppend. " + contentLog);

            try
            {
                File.AppendAllText(fileName, contentLog, Encoding.UTF8);
            }
            catch
            {
                try
                {
                    File.AppendAllText(fileName + "add", contentLog, Encoding.UTF8);
                }
                catch
                {
                    Loger.Log("IncidentLogAppend. Error write file " + fileName);
                }
            }
        }

19 Source : ServerManager.cs
with Apache License 2.0
from AantCoder

public void SavePlayerStatisticsFile()
        {
            try
            {
                var msg = "Command SaveListPlayerFileStats";
                Loger.Log(msg);

                Func<DateTime, string> dateTimeToStr = dt => dt == DateTime.MinValue ? "" : dt.ToString("yyyy-MM-dd hh:mm:ss", CultureInfo.InvariantCulture);

                var content = $"Login;LastOnlineTime;LastOnlineDay;GameDays;BaseCount;CaravanCount;MarketValue;MarketValuePawn" +
                    $";AttacksWonCount;AttacksInitiatorCount;ColonistsCount;ColonistsDownCount;ColonistsBleedCount;PawnMaxSkill" +
                    $";KillsHumanlikes;KillsMechanoids;KillsBestPawnHN;KillsBestPawnH;KillsBestPawnMN;KillsBestPawnM" +
                    $";Grants;EnablePVP;EMail;DiscordUserName;IntruderKeys;StartMarketValue;StartMarketValuePawn" +
                    $";MarketValueBy15Day;MarketValuePawnBy15Day;MarketValueByHour;MarketValuePawnByHour;TicksByHour;HourInGame" + Environment.NewLine;
                foreach (var player in Repository.GetData.PlayersAll)
                {
                    var costAll = player.CostWorldObjects();

                    var newLine = $"{player.Public.Login};" +
                        $"{dateTimeToStr(player.Public.LastOnlineTime)};" +
                        $"{(int)(DateTime.UtcNow - player.Public.LastOnlineTime).TotalDays};" +
                        $"{(int)(player.Public.LastTick / 60000)};" +
                        $"{costAll.BaseCount};" +
                        $"{costAll.CaravanCount};" +
                        $"{costAll.MarketValue};" +
                        $"{costAll.MarketValuePawn};" +
                        $"{player.AttacksWonCount};" +
                        $"{player.AttacksInitiatorCount};" +
                        $"{player.GameProgress?.ColonistsCount};" +
                        $"{player.GameProgress?.ColonistsDownCount};" +
                        $"{player.GameProgress?.ColonistsBleedCount};" +
                        $"{player.GameProgress?.PawnMaxSkill};" +
                        $"{player.GameProgress?.KillsHumanlikes};" +
                        $"{player.GameProgress?.KillsMechanoids};" +
                        $"{player.GameProgress?.KillsBestHumanlikesPawnName};" +
                        $"{player.GameProgress?.KillsBestHumanlikes};" +
                        $"{player.GameProgress?.KillsBestMechanoidsPawnName};" +
                        $"{player.GameProgress?.KillsBestMechanoids};" +
                        $"{player.Public.Grants.ToString()};" +
                        $"{(player.Public.EnablePVP ? 1 : 0)};" +
                        $"{player.Public.EMail};" +
                        $"{player.Public.DiscordUserName};" +
                        $"{player.IntruderKeys};" +
                        $"{player.StartMarketValue};" +
                        $"{player.StartMarketValuePawn};" +
                        $"{player.StatMaxDeltaGameMarketValue};" +
                        $"{player.StatMaxDeltaGameMarketValuePawn};" +
                        $"{player.StatMaxDeltaRealMarketValue};" +
                        $"{player.StatMaxDeltaRealMarketValuePawn};" +
                        $"{player.StatMaxDeltaRealTicks};" +
                        $"{player.TotalRealSecond / 60f / 60f};"
                        ;
                    newLine = newLine.Replace(Environment.NewLine, " ")
                        .Replace("/r", "").Replace("/n", "");

                    content += newLine + Environment.NewLine;
                }

                var fileName = Path.Combine(Path.GetDirectoryName(Repository.Get.SaveFileName)
                    , $"Players_{DateTime.Now.ToString("yyyy-MM-dd_hh-mm")}.csv");
                File.WriteAllText(fileName, content, Encoding.UTF8);
            }
            catch (Exception e)
            {
                Loger.Log("Command Exception " + e.ToString());
            }
        }

19 Source : DatePicker.razor.cs
with MIT License
from BlazorFluentUI

public override Task SetParametersAsync(ParameterView parameters)
        {
            if (!parameters.TryGetValue("MinDate", out DateTime nextMinDate))
                nextMinDate = MinDate;
            if (!parameters.TryGetValue("MaxDate", out DateTime nextMaxDate))
                nextMaxDate = MaxDate;
            if (!parameters.TryGetValue("Value", out DateTime? nextValue))
                nextValue = Value;
            if (!parameters.TryGetValue("InitialPickerDate", out DateTime nextInitialPickerDate))
                nextInitialPickerDate = InitialPickerDate;
            if (!parameters.TryGetValue("IsRequired", out bool nextIsRequired))
                nextIsRequired = IsRequired;
            if (!parameters.TryGetValue("FormatDate", out Func<DateTime, string>? nextFormatDate))
                nextFormatDate = FormatDate;

            if (DateTime.Compare(MinDate, nextMinDate) == 0 &&
                DateTime.Compare(MaxDate, nextMaxDate) == 0 &&
                IsRequired == nextIsRequired &&
                DateTimeCompareNullable(SelectedDate, nextValue) == 0 &&
                FormatDate != null &&
                (FormatDate.Equals(nextFormatDate) || nextFormatDate == null))  //since FormatDate may not be set as a parameter, it's ok for nextFormatDate to be null
            {
                return base.SetParametersAsync(parameters);
            }

            SetErrorMessage(true, nextIsRequired, nextValue, nextMinDate, nextMaxDate, nextInitialPickerDate);

            DateTime? oldValue = SelectedDate;
            if (DateTimeCompareNullable(oldValue, nextValue) != 0
                || (FormatDate != null
                && nextFormatDate != null
                && ((nextValue != null ? FormatDate((DateTime)nextValue) : null) != (nextValue != null ? nextFormatDate((DateTime)nextValue) : null))))
            {
                SelectedDate = nextValue;
                FormattedDate = FormatDateInternal(nextValue);
            }

            return base.SetParametersAsync(parameters);
        }

19 Source : DatePicker.razor.cs
with MIT License
from BlazorFluentUI

private string FormatDateInternal(DateTime? dateTime)
        {
            if (dateTime != null)
            {
                if (FormatDate != null)
                {
                    return FormatDate((DateTime)dateTime);
                }
            }
            return "";
        }

19 Source : ItAssetService.cs
with GNU General Public License v3.0
from Caijt

public List<Dictionary<string, object>> GetTimeStatistic(TimeStatisticQueryDto timeStatisticQueryDto, ItreplacedetQueryDto queryDto)
        {
            Expression<Func<Itreplacedet, dynamic>> groupExp = null;
            Func<DateTime, int, DateTime> dateFunc = null;
            Func<DateTime, DateTime> beginDateFunc = null;
            Func<DateTime, DateTime> endDateFunc = null;
            string format = "";
            switch (timeStatisticQueryDto.unit)
            {
                case "year":
                    format = "yyyy";
                    dateFunc = (datetime, i) => datetime.Date.AddYears(i);
                    beginDateFunc = datetime => new DateTime(datetime.Year, 1, 1);
                    endDateFunc = datetime => new DateTime(datetime.Year + 1, 1, 1);
                    groupExp = e => new
                    {
                        unit = e.inbound_date.Year.ToString()
                    };
                    break;
                case "day":
                    format = "yyyy-M-d";
                    dateFunc = (datetime, i) => datetime.AddDays(i);
                    beginDateFunc = datetime => datetime.Date;
                    endDateFunc = datetime => datetime.AddDays(1).Date;
                    groupExp = e => new
                    {
                        unit = e.inbound_date.Year.ToString() + "-" + e.inbound_date.Month + "-" + e.inbound_date.Day
                    };
                    break;
                case "month":
                default:
                    format = "yyyy-M";
                    dateFunc = (datetime, i) => datetime.AddMonths(i);
                    beginDateFunc = datetime => new DateTime(datetime.Year, datetime.Month, 1);
                    endDateFunc = datetime =>
                    {
                        datetime = datetime.AddMonths(1);
                        return new DateTime(datetime.Year, datetime.Month, 1);
                    };
                    groupExp = e => new
                    {
                        unit = e.inbound_date.Year.ToString() + "-" + e.inbound_date.Month.ToString()
                    };

                    break;
            }
            if (!timeStatisticQueryDto.time_end.HasValue)
            {
                timeStatisticQueryDto.time_end = DateTime.Today;
            }
            if (!timeStatisticQueryDto.time_begin.HasValue)
            {
                timeStatisticQueryDto.time_begin = dateFunc(timeStatisticQueryDto.time_end.Value, -8);
            }
            DateTime beginTime = beginDateFunc(timeStatisticQueryDto.time_begin.Value);
            DateTime endTime = endDateFunc(timeStatisticQueryDto.time_end.Value);
            List<Dictionary<string, object>> unitDataList = new List<Dictionary<string, object>>();
            DateTime timeTemp = beginTime;
            while (timeTemp < endTime)
            {
                Dictionary<string, object> dict = new Dictionary<string, object>();
                dict.Add("unit", timeTemp.ToString(format));
                dict.Add("price", 0);
                dict.Add("amount", 0);
                unitDataList.Add(dict);
                timeTemp = dateFunc(timeTemp, 1);
            }
            var query = buildWhere(this.dbQuery, queryDto);
            if (onWhere != null)
            {
                query = onWhere(query, queryDto);
            }
            var data = query.Where(e => e.inbound_date >= beginTime && e.inbound_date < endTime)
                .GroupBy(groupExp)
                .Select(g => new
                {
                    Key = g.Key,
                    price = g.Sum(e => e.price),
                    amount = g.Sum(e => e.amount)
                }).ToList();
            unitDataList.ForEach(i =>
            {
                data.ForEach(i2 =>
                {
                    if (string.Equals(i["unit"], i2.Key.unit))
                    {
                        i["price"] = i2.price;
                        i["amount"] = i2.amount;
                    }
                });
            });
            return unitDataList;
        }

19 Source : ItContractPayRecordService.cs
with GNU General Public License v3.0
from Caijt

public List<Dictionary<string, object>> GetTimeStatistic(TimeStatisticQueryDto timeStatisticQueryDto, ItContractPayRecordQueryDto queryDto)
        {
            Expression<Func<ItContractPayRecord, dynamic>> groupExp = null;
            Func<DateTime, int, DateTime> dateFunc = null;
            Func<DateTime, DateTime> beginDateFunc = null;
            Func<DateTime, DateTime> endDateFunc = null;
            string format = "";
            switch (timeStatisticQueryDto.unit)
            {
                case "year":
                    format = "yyyy";
                    dateFunc = (datetime, i) => datetime.Date.AddYears(i);
                    beginDateFunc = datetime => new DateTime(datetime.Year, 1, 1);
                    endDateFunc = datetime => new DateTime(datetime.Year + 1, 1, 1);
                    groupExp = e => new
                    {
                        unit = e.pay_date.Year.ToString()
                    };
                    break;
                case "day":
                    format = "yyyy-M-d";
                    dateFunc = (datetime, i) => datetime.AddDays(i);
                    beginDateFunc = datetime => datetime.Date;
                    endDateFunc = datetime => datetime.AddDays(1).Date;
                    groupExp = e => new
                    {
                        unit = e.pay_date.Year.ToString() + "-" + e.pay_date.Month + "-" + e.pay_date.Day
                    };
                    break;
                case "month":
                default:
                    format = "yyyy-M";
                    dateFunc = (datetime, i) => datetime.AddMonths(i);
                    beginDateFunc = datetime => new DateTime(datetime.Year, datetime.Month, 1);
                    endDateFunc = datetime =>
                    {
                        datetime = datetime.AddMonths(1);
                        return new DateTime(datetime.Year, datetime.Month, 1);
                    };
                    groupExp = e => new
                    {
                        unit = e.pay_date.Year.ToString() + "-" + e.pay_date.Month.ToString()
                    };

                    break;
            }
            if (!timeStatisticQueryDto.time_end.HasValue)
            {
                timeStatisticQueryDto.time_end = DateTime.Today;
            }
            if (!timeStatisticQueryDto.time_begin.HasValue)
            {
                timeStatisticQueryDto.time_begin = dateFunc(timeStatisticQueryDto.time_end.Value, -8);
            }
            DateTime beginTime = beginDateFunc(timeStatisticQueryDto.time_begin.Value);
            DateTime endTime = endDateFunc(timeStatisticQueryDto.time_end.Value);
            List<Dictionary<string, object>> unitDataList = new List<Dictionary<string, object>>();
            DateTime timeTemp = beginTime;
            while (timeTemp < endTime)
            {
                Dictionary<string, object> dict = new Dictionary<string, object>();
                dict.Add("unit", timeTemp.ToString(format));
                dict.Add("price", 0);
                dict.Add("amount", 0);
                unitDataList.Add(dict);
                timeTemp = dateFunc(timeTemp, 1);
            }
            var query = buildWhere(this.dbQuery, queryDto);
            if (onWhere != null)
            {
                query = onWhere(query, queryDto);
            }
            var data = query.Where(e => e.pay_date >= beginTime && e.pay_date < endTime)
                .GroupBy(groupExp)
                .Select(g => new
                {
                    Key = g.Key,
                    price = g.Sum(e => e.pay_price),
                    amount = g.Count()
                }).ToList();
            unitDataList.ForEach(i =>
            {
                data.ForEach(i2 =>
                {
                    if (string.Equals(i["unit"], i2.Key.unit))
                    {
                        i["price"] = i2.price;
                        i["amount"] = i2.amount;
                    }
                });
            });
            return unitDataList;
        }

19 Source : ItContractService.cs
with GNU General Public License v3.0
from Caijt

public List<Dictionary<string, object>> GetTimeStatistic(TimeStatisticQueryDto timeStatisticQueryDto, ItContractQueryDto queryDto)
        {
            Expression<Func<ItContractView, dynamic>> groupExp = null;
            Func<DateTime, int, DateTime> dateFunc = null;
            Func<DateTime, DateTime> beginDateFunc = null;
            Func<DateTime, DateTime> endDateFunc = null;
            string format = "";
            switch (timeStatisticQueryDto.unit)
            {
                case "year":
                    format = "yyyy";
                    dateFunc = (datetime, i) => datetime.Date.AddYears(i);
                    beginDateFunc = datetime => new DateTime(datetime.Year, 1, 1);
                    endDateFunc = datetime => new DateTime(datetime.Year + 1, 1, 1);
                    groupExp = e => new
                    {
                        unit = e.sign_date.Year.ToString()
                    };
                    break;
                case "day":
                    format = "yyyy-M-d";
                    dateFunc = (datetime, i) => datetime.AddDays(i);
                    beginDateFunc = datetime => datetime.Date;
                    endDateFunc = datetime => datetime.AddDays(1).Date;
                    groupExp = e => new
                    {
                        unit = e.sign_date.Year.ToString() + "-" + e.sign_date.Month + "-" + e.sign_date.Day
                    };
                    break;
                case "month":
                default:
                    format = "yyyy-M";
                    dateFunc = (datetime, i) => datetime.AddMonths(i);
                    beginDateFunc = datetime => new DateTime(datetime.Year, datetime.Month, 1);
                    endDateFunc = datetime =>
                    {
                        datetime = datetime.AddMonths(1);
                        return new DateTime(datetime.Year, datetime.Month, 1);
                    };
                    groupExp = e => new
                    {
                        unit = e.sign_date.Year.ToString() + "-" + e.sign_date.Month.ToString()
                    };

                    break;
            }
            if (!timeStatisticQueryDto.time_end.HasValue)
            {
                timeStatisticQueryDto.time_end = DateTime.Today;
            }
            if (!timeStatisticQueryDto.time_begin.HasValue)
            {
                timeStatisticQueryDto.time_begin = dateFunc(timeStatisticQueryDto.time_end.Value, -8);
            }
            DateTime beginTime = beginDateFunc(timeStatisticQueryDto.time_begin.Value);
            DateTime endTime = endDateFunc(timeStatisticQueryDto.time_end.Value);
            List<Dictionary<string, object>> unitDataList = new List<Dictionary<string, object>>();
            DateTime timeTemp = beginTime;
            while (timeTemp < endTime)
            {
                Dictionary<string, object> dict = new Dictionary<string, object>();
                dict.Add("unit", timeTemp.ToString(format));
                dict.Add("price", 0);
                dict.Add("amount", 0);
                unitDataList.Add(dict);
                timeTemp = dateFunc(timeTemp, 1);
            }
            var query = buildWhere(this.dbQuery, queryDto);
            if (onWhere != null)
            {
                query = onWhere(query, queryDto);
            }
            var data = query.Where(e => e.sign_date >= beginTime && e.sign_date < endTime)
                .GroupBy(groupExp)
                .Select(g => new
                {
                    Key = g.Key,
                    price = g.Sum(e => e.price),
                    amount = g.Count()
                }).ToList();
            unitDataList.ForEach(i =>
            {
                data.ForEach(i2 =>
                {
                    if (string.Equals(i["unit"], i2.Key.unit))
                    {
                        i["price"] = i2.price;
                        i["amount"] = i2.amount;
                    }
                });
            });
            return unitDataList;
        }

19 Source : PortfolioConstructionModel.cs
with Apache License 2.0
from Capnode

protected virtual bool IsRebalanceDue(Insight[] insights, DateTime algorithmUtc)
        {
            // if there is no rebalance func set, just return true but refresh state
            // just in case the rebalance func is going to be set.
            if (_rebalancingFunc == null)
            {
                RefreshRebalance(algorithmUtc);
                return true;
            }

            // we always get the next expiry time
            // we don't know if a new insight was added or removed
            var nextInsightExpiryTime = InsightCollection.GetNextExpiryTime();

            if (_rebalancingTime == null)
            {
                _rebalancingTime = _rebalancingFunc(algorithmUtc);

                if (_rebalancingTime != null && _rebalancingTime <= algorithmUtc)
                {
                    // if the rebalancing time stopped being null and is current time
                    // we will ask for the next rebalance time in the next loop.
                    // we don't want to call the '_rebalancingFunc' twice in the same loop,
                    // since its internal state machine will probably be in the same state.
                    _rebalancingTime = null;
                    _securityChanges = false;
                    return true;
                }
            }

            if (_rebalancingTime != null && _rebalancingTime <= algorithmUtc
                || RebalanceOnSecurityChanges && _securityChanges
                || RebalanceOnInsightChanges
                    && (insights.Length != 0
                        || nextInsightExpiryTime != null && nextInsightExpiryTime < algorithmUtc))
            {
                RefreshRebalance(algorithmUtc);
                return true;
            }

            return false;
        }

19 Source : PortfolioConstructionModel.cs
with Apache License 2.0
from Capnode

protected void RefreshRebalance(DateTime algorithmUtc)
        {
            if (_rebalancingFunc != null)
            {
                _rebalancingTime = _rebalancingFunc(algorithmUtc);
            }
            _securityChanges = false;
        }

19 Source : CustomUniverseSelectionModel.cs
with Apache License 2.0
from Capnode

public virtual IEnumerable<string> Select(QCAlgorithm algorithm, DateTime date)
        {
            if (_selector == null)
            {
                throw new ArgumentNullException(nameof(_selector));
            }

            return _selector(date);
        }

19 Source : FutureUniverseSelectionModel.cs
with Apache License 2.0
from Capnode

public override IEnumerable<Universe> CreateUniverses(QCAlgorithm algorithm)
        {
            _nextRefreshTimeUtc = algorithm.UtcTime + _refreshInterval;

            var uniqueSymbols = new HashSet<Symbol>();
            foreach (var futureSymbol in _futureChainSymbolSelector(algorithm.UtcTime))
            {
                if (futureSymbol.SecurityType != SecurityType.Future)
                {
                    throw new ArgumentException("FutureChainSymbolSelector must return future symbols.");
                }

                // prevent creating duplicate future chains -- one per symbol
                if (uniqueSymbols.Add(futureSymbol))
                {
                    yield return CreateFutureChain(algorithm, futureSymbol);
                }
            }
        }

19 Source : OptionUniverseSelectionModel.cs
with Apache License 2.0
from Capnode

public override IEnumerable<Universe> CreateUniverses(QCAlgorithm algorithm)
        {
            _nextRefreshTimeUtc = algorithm.UtcTime + _refreshInterval;

            var uniqueUnderlyingSymbols = new HashSet<Symbol>();
            foreach (var optionSymbol in _optionChainSymbolSelector(algorithm.UtcTime))
            {
                if (!optionSymbol.SecurityType.IsOption())
                {
                    throw new ArgumentException("optionChainSymbolSelector must return option, index options, or futures options symbols.");
                }

                // prevent creating duplicate option chains -- one per underlying
                if (uniqueUnderlyingSymbols.Add(optionSymbol.Underlying))
                {
                    yield return algorithm.CreateOptionChain(optionSymbol, Filter, _universeSettings);
                }
            }
        }

19 Source : FluentScheduledEventBuilder.cs
with Apache License 2.0
from Capnode

IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.Where(Func<DateTime, bool> predicate)
        {
            _predicate = _predicate == null
                ? predicate
                : (time => _predicate(time) && predicate(time));
            return this;
        }

19 Source : FluentScheduledEventBuilder.cs
with Apache License 2.0
from Capnode

IFluentSchedulingTimeSpecifier IFluentSchedulingTimeSpecifier.Where(Func<DateTime, bool> predicate)
        {
            _predicate = _predicate == null
                ? predicate
                : (time => _predicate(time) && predicate(time));
            return this;
        }

19 Source : FluentScheduledEventBuilder.cs
with Apache License 2.0
from Capnode

IFluentSchedulingRunnable IFluentSchedulingRunnable.Where(Func<DateTime, bool> predicate)
        {
            _predicate = _predicate == null
                ? predicate
                : (time => _predicate(time) && predicate(time));
            return this;
        }

19 Source : FluentScheduledEventBuilder.cs
with Apache License 2.0
from Capnode

IFluentSchedulingRunnable IFluentSchedulingRunnable.DuringMarketHours(Symbol symbol, bool extendedMarket)
        {
            var security = GetSecurity(symbol);
            Func<DateTime, bool> predicate = time =>
            {
                var localTime = time.ConvertFromUtc(security.Exchange.TimeZone);
                return security.Exchange.IsOpenDuringBar(localTime, localTime, extendedMarket);
            };
            _predicate = _predicate == null
                ? predicate
                : (time => _predicate(time) && predicate(time));
            return this;
        }

19 Source : FuncBenchmark.cs
with Apache License 2.0
from Capnode

public decimal Evaluate(DateTime time)
        {
            return _benchmark(time);
        }

19 Source : UserDefinedUniverse.cs
with Apache License 2.0
from Capnode

public override IEnumerable<Symbol> SelectSymbols(DateTime utcTime, BaseDataCollection data)
        {
            return _selector(utcTime);
        }

19 Source : FuturesOptionsExpiryFunctions.cs
with Apache License 2.0
from Capnode

public static DateTime FuturesOptionExpiry(Symbol canonicalFutureOptionSymbol, DateTime futureContractMonth)
        {
            if (!canonicalFutureOptionSymbol.IsCanonical() || !canonicalFutureOptionSymbol.Underlying.IsCanonical())
            {
                canonicalFutureOptionSymbol = Symbol.CreateOption(
                    Symbol.Create(canonicalFutureOptionSymbol.Underlying.ID.Symbol, SecurityType.Future, canonicalFutureOptionSymbol.Underlying.ID.Market),
                    canonicalFutureOptionSymbol.ID.Market,
                    default(OptionStyle),
                    default(OptionRight),
                    default(decimal),
                    SecurityIdentifier.DefaultDate);
            }

            Func<DateTime, DateTime> expiryFunction;
            if (!_futuresOptionExpiryFunctions.TryGetValue(canonicalFutureOptionSymbol, out expiryFunction))
            {
                // No definition exists for this FOP. Let's default to futures expiry.
                return FuturesExpiryFunctions.FuturesExpiryFunction(canonicalFutureOptionSymbol.Underlying)(futureContractMonth);
            }

            return expiryFunction(futureContractMonth);
        }

19 Source : Insight.cs
with Apache License 2.0
from Capnode

public void SetPeriodAndCloseTime(Insight insight, SecurityExchangeHours exchangeHours)
            {
                var closeTimeLocal = insight.GeneratedTimeUtc.ConvertFromUtc(exchangeHours.TimeZone);
                closeTimeLocal = _expiryFunc(closeTimeLocal);

                // Prevent close time to be defined to a date/time in closed market
                if (!exchangeHours.IsOpen(closeTimeLocal, false))
                {
                    closeTimeLocal = exchangeHours.GetNextMarketOpen(closeTimeLocal, false);
                }

                insight.CloseTimeUtc = closeTimeLocal.ConvertToUtc(exchangeHours.TimeZone);
                insight.Period = insight.CloseTimeUtc - insight.GeneratedTimeUtc;
            }

19 Source : PeriodCountConsolidatorBase.cs
with Apache License 2.0
from Capnode

public DateTime GetRoundedBarTime(DateTime time)
            {
                var calendarInfo = _calendarInfoFunc(time);
                Period = calendarInfo.Period;
                return calendarInfo.Start;
            }

19 Source : FuturesListings.cs
with Apache License 2.0
from Capnode

public static List<Symbol> ListedContracts(string futureTicker, DateTime time)
        {
            if (!_futuresListingRules.ContainsKey(futureTicker))
            {
                // No entries found. This differs from entries being returned as an empty array, where
                // that would mean that no listings were found.
                return null;
            }

            return _futuresListingRules[futureTicker](time);
        }

19 Source : Sales.cs
with MIT License
from charlessolar

public async Task Handle(Events.Drafted e, IMessageHandlerContext ctx)
        {
            var day = e.Stamp.FromUnix().Date;

            // get all items in basket
            var itemIds = await ctx.Service<Basket.Basket.Enreplacedies.Item.Services.ItemsInBasket, string[]>(x => { x.BasketId = e.BasketId; })
                .ConfigureAwait(false);

            var items = await itemIds.SelectAsync(id =>
            {
                return ctx.UoW().Get<Basket.Basket.Enreplacedies.Item.Models.BaskereplacedemIndex>(id);
            }).ConfigureAwait(false);

            var existing = await ctx.UoW().TryGet<Models.SalesChart>(IdGenerator(day)).ConfigureAwait(false);
            if(existing == null)
            {
                existing = new Models.SalesChart
                {
                    Id = IdGenerator(day),
                    Relevancy = day.ToUnix(),
                    Label = day.ToString("s"),
                    Value = items.Sum(x => x.SubTotal)
                };
                await ctx.UoW().Add(existing.Id, existing).ConfigureAwait(false);
            }
            else
            {
                // todo: add additional fees when additional fees exist
                existing.Value += items.Sum(x => x.SubTotal);
                await ctx.UoW().Update(existing.Id, existing).ConfigureAwait(false);
            }
        }

19 Source : Sales.cs
with MIT License
from charlessolar

public async Task Handle(Events.Canceled e, IMessageHandlerContext ctx)
        {
            var order = await ctx.UoW().Get<Models.OrderingOrderIndex>(e.OrderId).ConfigureAwait(false);

            var existing = await ctx.UoW().Get<Models.SalesChart>(IdGenerator(order.Created.FromUnix().Date)).ConfigureAwait(false);
            existing.Value -= order.Total;
            await ctx.UoW().Update(existing.Id, existing).ConfigureAwait(false);
        }

19 Source : Sales.cs
with MIT License
from charlessolar

public async Task Handle(Enreplacedies.Item.Events.Added e, IMessageHandlerContext ctx)
        {
            var order = await ctx.UoW().Get<Models.OrderingOrderIndex>(e.OrderId).ConfigureAwait(false);
            var product = await ctx.UoW().Get<Catalog.Product.Models.CatalogProductIndex>(e.ProductId).ConfigureAwait(false);

            var existing = await ctx.UoW().Get<Models.SalesChart>(IdGenerator(order.Created.FromUnix().Date)).ConfigureAwait(false);
            existing.Value += product.Price * e.Quanreplacedy;
            await ctx.UoW().Update(existing.Id, existing).ConfigureAwait(false);
        }

19 Source : Sales.cs
with MIT License
from charlessolar

public async Task Handle(Enreplacedies.Item.Events.PriceOverridden e, IMessageHandlerContext ctx)
        {
            var order = await ctx.UoW().Get<Models.OrderingOrderIndex>(e.OrderId).ConfigureAwait(false);
            var orderItem = await ctx.UoW().Get<Enreplacedies.Item.Models.OrderingOrderItem>(Enreplacedies.Item.Handler.ItemIdGenerator(e.OrderId, e.ProductId)).ConfigureAwait(false);

            var existing = await ctx.UoW().Get<Models.SalesChart>(IdGenerator(order.Created.FromUnix().Date)).ConfigureAwait(false);
            // remove existing value
            existing.Value -= orderItem.Total;

            orderItem.Price = e.Price;

            // add updated total
            existing.Value += orderItem.Total;

            await ctx.UoW().Update(existing.Id, existing).ConfigureAwait(false);
        }

19 Source : Sales.cs
with MIT License
from charlessolar

public async Task Handle(Enreplacedies.Item.Events.Removed e, IMessageHandlerContext ctx)
        {
            var order = await ctx.UoW().Get<Models.OrderingOrderIndex>(e.OrderId).ConfigureAwait(false);
            var orderItem = await ctx.UoW().Get<Enreplacedies.Item.Models.OrderingOrderItem>(Enreplacedies.Item.Handler.ItemIdGenerator(e.OrderId, e.ProductId)).ConfigureAwait(false);

            var existing = await ctx.UoW().Get<Models.SalesChart>(IdGenerator(order.Created.FromUnix().Date)).ConfigureAwait(false);
            // remove existing value
            existing.Value -= orderItem.Total;

            await ctx.UoW().Update(existing.Id, existing).ConfigureAwait(false);
        }

19 Source : SalesWeekOverWeek.cs
with MIT License
from charlessolar

public async Task Handle(Events.Drafted e, IMessageHandlerContext ctx)
        {
            var day = e.Stamp.FromUnix().Date;
            
            // get all items in basket
            var itemIds = await ctx.Service<Basket.Basket.Enreplacedies.Item.Services.ItemsInBasket, string[]>(x => { x.BasketId = e.BasketId; })
                .ConfigureAwait(false);

            var items = await itemIds.SelectAsync(id =>
            {
                return ctx.UoW().Get<Basket.Basket.Enreplacedies.Item.Models.BaskereplacedemIndex>(id);
            }).ConfigureAwait(false);

            var existing = await ctx.UoW().TryGet<Models.SalesWeekOverWeek>(IdGenerator(day)).ConfigureAwait(false);
            if (existing == null)
            {
                existing = new Models.SalesWeekOverWeek
                {
                    Id = IdGenerator(day),
                    Relevancy = day.StartOfWeek().ToUnix(),
                    DayOfWeek = day.DayOfWeek.ToString(),
                    Value = items.Sum(x => x.SubTotal)
                };
                await ctx.UoW().Add(existing.Id, existing).ConfigureAwait(false);
            }
            else
            {
                // todo: add additional fees when additional fees exist
                existing.Value += items.Sum(x => x.SubTotal);
                await ctx.UoW().Update(existing.Id, existing).ConfigureAwait(false);
            }
        }

19 Source : SalesWeekOverWeek.cs
with MIT License
from charlessolar

public async Task Handle(Events.Canceled e, IMessageHandlerContext ctx)
        {
            var order = await ctx.UoW().Get<Models.OrderingOrderIndex>(e.OrderId).ConfigureAwait(false);

            var day = order.Created.FromUnix().Date;

            var existing = await ctx.UoW().Get<Models.SalesWeekOverWeek>(IdGenerator(day)).ConfigureAwait(false);
            existing.Value -= order.Total;
            await ctx.UoW().Update(existing.Id, existing).ConfigureAwait(false);
        }

19 Source : SalesWeekOverWeek.cs
with MIT License
from charlessolar

public async Task Handle(Enreplacedies.Item.Events.Added e, IMessageHandlerContext ctx)
        {
            var order = await ctx.UoW().Get<Models.OrderingOrderIndex>(e.OrderId).ConfigureAwait(false);
            var product = await ctx.UoW().Get<Catalog.Product.Models.CatalogProductIndex>(e.ProductId).ConfigureAwait(false);

            var day = order.Created.FromUnix().Date;

            var existing = await ctx.UoW().Get<Models.SalesWeekOverWeek>(IdGenerator(day)).ConfigureAwait(false);
            existing.Value += product.Price * e.Quanreplacedy;
            await ctx.UoW().Update(existing.Id, existing).ConfigureAwait(false);
        }

19 Source : SalesWeekOverWeek.cs
with MIT License
from charlessolar

public async Task Handle(Enreplacedies.Item.Events.PriceOverridden e, IMessageHandlerContext ctx)
        {
            var order = await ctx.UoW().Get<Models.OrderingOrderIndex>(e.OrderId).ConfigureAwait(false);
            var orderItem = await ctx.UoW().Get<Enreplacedies.Item.Models.OrderingOrderItem>(Enreplacedies.Item.Handler.ItemIdGenerator(e.OrderId, e.ProductId)).ConfigureAwait(false);

            var day = order.Created.FromUnix().Date;

            var existing = await ctx.UoW().Get<Models.SalesWeekOverWeek>(IdGenerator(day)).ConfigureAwait(false);
            // remove existing value
            existing.Value -= orderItem.Total;

            orderItem.Price = e.Price;

            // add updated total
            existing.Value += orderItem.Total;

            await ctx.UoW().Update(existing.Id, existing).ConfigureAwait(false);
        }

19 Source : SalesWeekOverWeek.cs
with MIT License
from charlessolar

public async Task Handle(Enreplacedies.Item.Events.Removed e, IMessageHandlerContext ctx)
        {
            var order = await ctx.UoW().Get<Models.OrderingOrderIndex>(e.OrderId).ConfigureAwait(false);
            var orderItem = await ctx.UoW().Get<Enreplacedies.Item.Models.OrderingOrderItem>(Enreplacedies.Item.Handler.ItemIdGenerator(e.OrderId, e.ProductId)).ConfigureAwait(false);

            var day = order.Created.FromUnix().Date;

            var existing = await ctx.UoW().Get<Models.SalesWeekOverWeek>(IdGenerator(day)).ConfigureAwait(false);
            // remove existing value
            existing.Value -= orderItem.Total;

            await ctx.UoW().Update(existing.Id, existing).ConfigureAwait(false);
        }

19 Source : DateScroller.cs
with MIT License
from cschladetsch

protected virtual DateTime LoopedDate(DateTime value, int steps, Func<DateTime, DateTime> step)
		{
			for (int i = 0; i < steps; i++)
			{
				value = LoopedClamp(step(value));
			}

			return value;
		}

19 Source : RateLimitCacheKey.cs
with Apache License 2.0
from DomainGroupOSS

public override string ToString()
        {
            return
                $"{RequestId}::{Method.ToUpperInvariant()} {Host.ToLowerInvariant()}{RouteTemplate.ToLowerInvariant()}::{_getSuffix(_dateTimeUtcNow)}";
        }

19 Source : SubscriptionSchedule.cs
with Apache License 2.0
from FasTnT

private static DateTime GetNextTentative(DateTime tentative, Func<DateTime, int> selector, Func<DateTime, DateTime> increment, ScheduleEntry entry)
        {
            while (!entry.HasValue(selector(tentative)))
            {
                tentative = increment(tentative);
            }

            return tentative;
        }

19 Source : LockableOutputLogResult.cs
with MIT License
from ibiza240

public ICollection<DateSnapshotInfo> BuildHistory()
        {
            var result = new List<DateSnapshotInfo>();

            Func<DateTime, DateSnapshotInfo> CreateOrGetDateSnapshotInfo = (date) =>
            {
                var dateOnly = date.Date;
                var info = result.FirstOrDefault(i => i.Date == dateOnly);
                if (info == null)
                {
                    info = new DateSnapshotInfo(dateOnly);
                    result.Add(info);
                }

                return info;
            };

            //foreach (var dataType in Data.Keys)
            //{
            //    foreach (var data in Data[dataType].GetData())
            //        CreateOrGetDateSnapshotInfo(data.DateTime).
            //}

            foreach (var collection in CollectionByDate.GetData())
                CreateOrGetDateSnapshotInfo(collection.DateTime).Collection = collection.Info;

            foreach (var inventory in InventoryByDate.GetData())
                CreateOrGetDateSnapshotInfo(inventory.DateTime).Inventory = inventory.Info;

            foreach (var progress in PlayerProgressByDate.GetData())
                CreateOrGetDateSnapshotInfo(progress.DateTime).PlayerProgress = progress.Info;

            foreach (var progress in PlayerProgressIntradayByDate.GetData())
                CreateOrGetDateSnapshotInfo(progress.DateTime).PlayerProgressIntraday = progress.Info;

            foreach (var matches in MatchesByDate.GetData())
                CreateOrGetDateSnapshotInfo(matches.DateTime).Matches = matches.Info;

            foreach (var quests in PlayerQuestsByDate.GetData())
                CreateOrGetDateSnapshotInfo(quests.DateTime).PlayerQuests = quests.Info;

            //foreach (var boosters in CrackedBoostersByDate.GetData())
            //    CreateOrGetDateSnapshotInfo(boosters.DateTime).CrackedBoosters = boosters.Info;

            foreach (var rankInfo in RankSyntheticByDate.GetData())
                CreateOrGetDateSnapshotInfo(rankInfo.DateTime).RankSynthetic = rankInfo.Info;

            foreach (var inventoryUpdate in InventoryUpdatesByDate.GetData())
                CreateOrGetDateSnapshotInfo(inventoryUpdate.DateTime).InventoryUpdates = inventoryUpdate.Info;

            foreach (var postMatchUpdate in PostMatchUpdatesByDate.GetData())
                CreateOrGetDateSnapshotInfo(postMatchUpdate.DateTime).PostMatchUpdates = postMatchUpdate.Info;

            //foreach (var draftPicks in DraftPickProgressByDate.GetData())
            //    CreateOrGetDateSnapshotInfo(draftPicks.DateTime).DraftPickProgress = draftPicks.Info;

            foreach (var draftPicks in DraftPickProgressIntradayByDate.GetData())
                CreateOrGetDateSnapshotInfo(draftPicks.DateTime).DraftPickProgressIntraday = draftPicks.Info;

            //foreach (var payEntry in PayEntryByDate.GetData())
            //    CreateOrGetDateSnapshotInfo(payEntry.DateTime).PayEntry = payEntry.Info;

            //foreach (var mythicRatingUpdated in MythicRatingUpdatedByDate.GetData())
            //    CreateOrGetDateSnapshotInfo(mythicRatingUpdated.DateTime).MythicRatingUpdated = mythicRatingUpdated.Info;

            foreach (var combinedRankInfo in CombinedRankInfoByDate.GetData())
                CreateOrGetDateSnapshotInfo(combinedRankInfo.DateTime).CombinedRankInfo = combinedRankInfo.Info;

            //foreach (var rankUpdated in RankUpdatedByDate.GetData())
            //    CreateOrGetDateSnapshotInfo(rankUpdated.DateTime).RankUpdated = rankUpdated.Info;

            foreach (var eventClaimPrice in EventClaimPriceByDate.GetData())
                CreateOrGetDateSnapshotInfo(eventClaimPrice.DateTime).EventClaimPrize = eventClaimPrice.Info;

            foreach (var mtgaDecksfound in MtgaDecksFoundByDate.GetData())
                CreateOrGetDateSnapshotInfo(mtgaDecksfound.DateTime).MtgaDecksFound = mtgaDecksfound.Info;

            //foreach (var vaultsOpened in VaultsOpenedByDate.GetData())
            //    CreateOrGetDateSnapshotInfo(vaultsOpened.DateTime).VaultsOpened = vaultsOpened.Info;

            //foreach (var collectionIntraday in CollectionIntradayByDate.GetData())
            //    CreateOrGetDateSnapshotInfo(collectionIntraday.DateTime).CollectionIntraday = collectionIntraday.Info;

            foreach (var inventoryIntraday in InventoryIntradayByDate.GetData())
                CreateOrGetDateSnapshotInfo(inventoryIntraday.DateTime).InventoryIntraday = inventoryIntraday.Info;

            //foreach (var decks in DecksByDate.GetData())
            //    CreateOrGetDateSnapshotInfo(decks.DateTime).Decks = decks.Info;

            //ICollection<ConfigModelRankInfo> previousRank = null;
            foreach (var s in result)
            {
                //s.Wins = s.Matches.Count(i => i.Outcome == GameOutcomeEnum.Victory);
                //s.Losses = s.Matches.Count(i => i.Outcome == GameOutcomeEnum.Defeat);
                s.OutcomesByMode = s.Matches
                    .GroupBy(i => i.EventName)
                    .ToDictionary(i => i.Key, i => new Outcomes
                    {
                        Wins = i.Count(x => x.Outcome == GameOutcomeEnum.Victory),
                        Losses = i.Count(x => x.Outcome == GameOutcomeEnum.Defeat),
                    });

                //s.ConstructedRank = (s.RankInfo.FirstOrDefault(i => i.Format == ConfigModelRankInfoFormatEnum.Constructed) ??
                //                    previousRank?.FirstOrDefault(i => i.Format == ConfigModelRankInfoFormatEnum.Constructed))?.ToString() ?? "N/A";
                //s.LimitedRank = (s.RankInfo.FirstOrDefault(i => i.Format == ConfigModelRankInfoFormatEnum.Limited) ??
                //                    previousRank?.FirstOrDefault(i => i.Format == ConfigModelRankInfoFormatEnum.Limited))?.ToString() ?? "N/A";

                //previousRank = s.RankInfo;
            }

            return result;
        }

19 Source : OutputLogResult.cs
with MIT License
from ibiza240

public ICollection<DateSnapshotInfo> BuildHistory()
        {
            var result = new List<DateSnapshotInfo>();

            Func<DateTime, DateSnapshotInfo> CreateOrGetDateSnapshotInfo = (date) =>
            {
                var dateOnly = date.Date;
                var info = result.FirstOrDefault(i => i.Date == dateOnly);
                if (info == null)
                {
                    info = new DateSnapshotInfo(dateOnly);
                    result.Add(info);
                }

                return info;
            };

            foreach (var mtgaDeck in MtgaDecksFoundByDate)
                CreateOrGetDateSnapshotInfo(mtgaDeck.DateTime).MtgaDecksFound = mtgaDeck.Info;

            foreach (var collection in CollectionByDate)
                CreateOrGetDateSnapshotInfo(collection.DateTime).Collection = collection.Info;

            foreach (var inventory in InventoryByDate)
                CreateOrGetDateSnapshotInfo(inventory.DateTime).Inventory = inventory.Info;

            foreach (var progress in PlayerProgressByDate)
                CreateOrGetDateSnapshotInfo(progress.DateTime).PlayerProgress = progress.Info;

            foreach (var progress in PlayerProgressIntradayByDate)
                CreateOrGetDateSnapshotInfo(progress.DateTime).PlayerProgressIntraday = progress.Info;

            foreach (var quest in PlayerQuestsByDate)
                CreateOrGetDateSnapshotInfo(quest.DateTime).PlayerQuests = quest.Info;

            foreach (var matches in MatchesByDate)
                CreateOrGetDateSnapshotInfo(matches.DateTime).Matches = matches.Info;

            foreach (var rankInfo in RankSyntheticByDate)
                CreateOrGetDateSnapshotInfo(rankInfo.DateTime).RankSynthetic = rankInfo.Info;

            foreach (var inventoryUpdate in InventoryUpdatesByDate)
                CreateOrGetDateSnapshotInfo(inventoryUpdate.DateTime).InventoryUpdates = inventoryUpdate.Info;

            foreach (var postMatchUpdate in PostMatchUpdatesByDate)
                CreateOrGetDateSnapshotInfo(postMatchUpdate.DateTime).PostMatchUpdates = postMatchUpdate.Info;

            //foreach (var draftPick in DraftPickProgressByDate)
            //    CreateOrGetDateSnapshotInfo(draftPick.DateTime).DraftPickProgress = draftPick.Info;

            foreach (var draftPick in DraftPickProgressIntradayByDate)
                CreateOrGetDateSnapshotInfo(draftPick.DateTime).DraftPickProgressIntraday = draftPick.Info;

            //foreach (var rankUpdated in RankUpdatedByDate)
            //    CreateOrGetDateSnapshotInfo(rankUpdated.DateTime).RankUpdated = rankUpdated.Info;

            foreach (var eventClaimPrice in EventClaimPriceByDate)
                CreateOrGetDateSnapshotInfo(eventClaimPrice.DateTime).EventClaimPrize = eventClaimPrice.Info;

            //foreach (var mythicRatingUpdated in MythicRatingUpdatedByDate)
            //    CreateOrGetDateSnapshotInfo(mythicRatingUpdated.DateTime).MythicRatingUpdated = mythicRatingUpdated.Info;

            //foreach (var payEntry in PayEntryByDate)
            //    CreateOrGetDateSnapshotInfo(payEntry.DateTime).PayEntry = payEntry.Info;

            foreach (var combinedRankInfo in CombinedRankInfoByDate)
                CreateOrGetDateSnapshotInfo(combinedRankInfo.DateTime).CombinedRankInfo = combinedRankInfo.Info;

            //foreach (var booster in CrackedBoostersByDate)
            //    CreateOrGetDateSnapshotInfo(booster.DateTime).CrackedBoosters = booster.Info;

            //foreach (var vault in VaultsOpenedByDate)
            //    CreateOrGetDateSnapshotInfo(vault.DateTime).VaultsOpened = vault.Info;

            //foreach (var vault in CollectionIntradayByDate)
            //    CreateOrGetDateSnapshotInfo(vault.DateTime).CollectionIntraday = vault.Info;

            foreach (var vault in InventoryIntradayByDate)
                CreateOrGetDateSnapshotInfo(vault.DateTime).InventoryIntraday = vault.Info;

            //foreach (var decks in DecksByDate)
            //    CreateOrGetDateSnapshotInfo(decks.DateTime).Decks = decks.Info;

            //ICollection<ConfigModelRankInfo> previousRank = null;
            foreach (var s in result)
            {
                //s.Wins = s.Matches.Count(i => i.Outcome == GameOutcomeEnum.Victory);
                //s.Losses = s.Matches.Count(i => i.Outcome == GameOutcomeEnum.Defeat);
                s.OutcomesByMode = s.Matches
                    .GroupBy(i => i.EventName)
                    .ToDictionary(i => i.Key, i => new Outcomes
                    {
                        Wins = i.Count(x => x.Outcome == GameOutcomeEnum.Victory),
                        Losses = i.Count(x => x.Outcome == GameOutcomeEnum.Defeat),
                    });

                //s.ConstructedRank = (s.RankInfo.FirstOrDefault(i => i.Format == ConfigModelRankInfoFormatEnum.Constructed) ??
                //                    previousRank?.FirstOrDefault(i => i.Format == ConfigModelRankInfoFormatEnum.Constructed))?.ToString() ?? "N/A";
                //s.LimitedRank = (s.RankInfo.FirstOrDefault(i => i.Format == ConfigModelRankInfoFormatEnum.Limited) ??
                //                    previousRank?.FirstOrDefault(i => i.Format == ConfigModelRankInfoFormatEnum.Limited))?.ToString() ?? "N/A";

                //previousRank = s.RankInfo;
            }

            return result;
        }

19 Source : ExpressionExtensionTests.cs
with MIT License
from IEvangelist

[
            Theory,
            MemberData(nameof(CompositionInput))
        ]
        public void ComposeCorrectlyAccountsForBothExpressions(DateTime arg, bool expected)
        {
            Expression<Func<DateTime, bool>> isOlderThanMe = date => date < new DateTime(1984, 7, 7);
            Expression<Func<DateTime, bool>> composition =
                isOlderThanMe.Compose(date => date != DateTime.MinValue, Expression.AndAlso);

            replacedert.Equal(expected, composition.Compile().Invoke(arg));
        }

19 Source : ExchangeHistoricalTradeHelper.cs
with MIT License
from jjxtra

public async Task ProcessHistoricalTrades()
            {
                if (Callback == null)
                {
                    throw new ArgumentException("Missing required parameter", nameof(Callback));
                }
                else if (TimestampFunction == null && UrlFunction == null)
                {
                    throw new ArgumentException("Missing required parameters", nameof(TimestampFunction) + "," + nameof(UrlFunction));
                }
                else if (ParseFunction == null)
                {
                    throw new ArgumentException("Missing required parameter", nameof(ParseFunction));
                }
                else if (string.IsNullOrWhiteSpace(Url))
                {
                    throw new ArgumentException("Missing required parameter", nameof(Url));
                }

                MarketSymbol = api.NormalizeMarketSymbol(MarketSymbol);
                string url;
                Url = Url.Replace("[marketSymbol]", MarketSymbol);
                List<ExchangeTrade> trades = new List<ExchangeTrade>();
                ExchangeTrade trade;
                EndDate = (EndDate ?? CryptoUtility.UtcNow);
                StartDate = (StartDate ?? EndDate.Value.Subtract(BlockTime));
                string startTimestamp;
                string endTimestamp;
                HashSet<string> previousTrades = new HashSet<string>();
                HashSet<string> tempTradeIds = new HashSet<string>();
                HashSet<string> tmpIds;
                SetDates(out DateTime startDateMoving, out DateTime endDateMoving);

                while (true)
                {
                    // format url and make request
                    if (TimestampFunction != null)
                    {
                        startTimestamp = TimestampFunction(startDateMoving);
                        endTimestamp = TimestampFunction(endDateMoving);
                        url = string.Format(Url, startTimestamp, endTimestamp);
                    }
                    else if (UrlFunction != null)
                    {
                        url = UrlFunction(this);
                    }
                    else
                    {
                        throw new InvalidOperationException("TimestampFunction or UrlFunction must be specified");
                    }
                    JToken obj = await api.MakeJsonRequestAsync<JToken>(url);

                    // don't add this temp trade as it may be outside of the date/time range
                    tempTradeIds.Clear();
                    foreach (JToken token in obj)
                    {
                        trade = ParseFunction(token);
                        if (!previousTrades.Contains(trade.Id) && trade.Timestamp >= StartDate.Value && trade.Timestamp <= EndDate.Value)
                        {
                            trades.Add(trade);
                        }
                        if (trade.Id != null)
                        {
                            tempTradeIds.Add(trade.Id);
                        }
                    }
                    previousTrades.Clear();
                    tmpIds = previousTrades;
                    previousTrades = tempTradeIds;
                    tempTradeIds = previousTrades;

                    // set dates to next block
                    if (trades.Count == 0)
                    {
                        if (DirectionIsBackwards)
                        {
							// no trades found, move the whole block back
							endDateMoving = startDateMoving;
							startDateMoving = endDateMoving.Subtract(BlockTime);
						}
                        else
                        {
                            // no trades found, move the whole block forward
                            startDateMoving = endDateMoving.Add(BlockTime);
                        }
                    }
                    else
                    {
                        // sort trades in descending order and callback
                        if (DirectionIsBackwards)
                        {
                            trades.Sort((t1, t2) => t2.Timestamp.CompareTo(t1.Timestamp));
                        }
                        else
                        {
                            trades.Sort((t1, t2) => t1.Timestamp.CompareTo(t2.Timestamp));
                        }
                        if (!Callback(trades))
                        {
                            break;
                        }

                        trade = trades[trades.Count - 1];
                        if (DirectionIsBackwards)
                        {
                            // set end date to the date of the earliest trade of the block, use for next request
                            if (MillisecondGranularity)
                            {
                                endDateMoving = trade.Timestamp.AddMilliseconds(-1.0);
                            }
                            else
                            {
                                endDateMoving = trade.Timestamp.AddSeconds(-1.0);
                            }
                            startDateMoving = endDateMoving.Subtract(BlockTime);
                        }
                        else
                        {
                            // set start date to the date of the latest trade of the block, use for next request
                            if (MillisecondGranularity)
                            {
                                startDateMoving = trade.Timestamp.AddMilliseconds(1.0);
                            }
                            else
                            {
                                startDateMoving = trade.Timestamp.AddSeconds(1.0);
                            }
                            endDateMoving = startDateMoving.Add(BlockTime);
                        }
                        trades.Clear();
                    }
                    // check for exit conditions
                    if (DirectionIsBackwards)
                    {
                        if (endDateMoving < StartDate.Value)
                        {
                            break;
                        }
                    }
                    else
                    {
                        if (startDateMoving > EndDate.Value)
                        {
                            break;
                        }
                    }
                    await Task.Delay(DelayMilliseconds);
                }
            }

19 Source : AddToTime.cs
with MIT License
from microsoft

private static (string, string) EvalAddToTime(object timestamp, long interval, string timeUnit, string format, CultureInfo locale)
        {
            string result = null;
            string error = null;
            object parsed = null;
            (parsed, error) = FunctionUtils.NormalizeToDateTime(timestamp);
            if (error == null)
            {
                var ts = (DateTime)parsed;
                Func<DateTime, DateTime> converter;
                (converter, error) = FunctionUtils.DateTimeConverter(interval, timeUnit, false);
                if (error == null)
                {
                    var addedTimeStamp = converter(ts);
                    (result, error) = FunctionUtils.ReturnFormatTimeStampStr(addedTimeStamp, format, locale);
                }
            }

            return (result, error);
        }

19 Source : GetPastTime.cs
with MIT License
from microsoft

private static (object value, string error) Evaluator(Expression expression, IMemory state, Options options)
        {
            object value = null;
            string error = null;
            IReadOnlyList<object> args;
            var locale = options.Locale != null ? new CultureInfo(options.Locale) : Thread.CurrentThread.CurrentCulture;
            var format = FunctionUtils.DefaultDateTimeFormat;
            (args, error) = FunctionUtils.EvaluateChildren(expression, state, options);
            if (error == null)
            {
                (format, locale, error) = FunctionUtils.DetermineFormatAndLocale(args, format, locale, 4);
            }

            if (error == null)
            {
                if (args[0].IsInteger() && args[1] is string string1)
                {
                    Func<DateTime, DateTime> timeConverter;
                    (timeConverter, error) = FunctionUtils.DateTimeConverter(Convert.ToInt64(args[0], CultureInfo.InvariantCulture), string1);
                    if (error == null)
                    {
                        value = timeConverter(DateTime.UtcNow).ToString(format, locale);
                    }
                }
                else
                {
                    error = $"{expression} should contain a time interval integer, a string unit of time, an optional output format string and an optional locale string.";
                }
            }

            return (value, error);
        }

19 Source : SubtractFromTime.cs
with MIT License
from microsoft

private static (object value, string error) Evaluator(Expression expression, IMemory state, Options options)
        {
            object value = null;
            string error = null;
            IReadOnlyList<object> args;
            var locale = options.Locale != null ? new CultureInfo(options.Locale) : Thread.CurrentThread.CurrentCulture;
            var format = FunctionUtils.DefaultDateTimeFormat;
            (args, error) = FunctionUtils.EvaluateChildren(expression, state, options);

            if (error == null)
            {
                (format, locale, error) = FunctionUtils.DetermineFormatAndLocale(args, format, locale, 5);
            }

            if (error == null)
            {
                if (args[1].IsInteger() && args[2] is string string2)
                {
                    Func<DateTime, DateTime> timeConverter;
                    (timeConverter, error) = FunctionUtils.DateTimeConverter(Convert.ToInt64(args[1], CultureInfo.InvariantCulture), string2);
                    if (error == null)
                    {
                        (value, error) = FunctionUtils.NormalizeToDateTime(args[0], dt => (timeConverter(dt).ToString(format, locale), null));
                    }
                }
                else
                {
                    error = $"{expression} should contain an ISO format timestamp, a time interval integer, a string unit of time, an optional output format string and an optional locale string.";
                }
            }

            return (value, error);
        }

19 Source : GetFutureTime.cs
with MIT License
from microsoft

private static (object value, string error) Evaluator(Expression expression, IMemory state, Options options)
        {
            object value = null;
            string error = null;
            IReadOnlyList<object> args;
            var locale = options.Locale != null ? new CultureInfo(options.Locale) : Thread.CurrentThread.CurrentCulture;
            var format = FunctionUtils.DefaultDateTimeFormat;
            (args, error) = FunctionUtils.EvaluateChildren(expression, state, options);

            if (error == null)
            {
                (format, locale, error) = FunctionUtils.DetermineFormatAndLocale(args, format, locale, 4);
            }

            if (error == null)
            {
                if (args[0].IsInteger() && args[1] is string string1)
                {
                    Func<DateTime, DateTime> timeConverter;
                    (timeConverter, error) = FunctionUtils.DateTimeConverter(Convert.ToInt64(args[0], CultureInfo.InvariantCulture), string1, false);
                    if (error == null)
                    {
                        value = timeConverter(DateTime.UtcNow).ToString(format, locale);
                    }
                }
                else
                {
                    error = $"{expression} should contain a time interval integer, a string unit of time, an optional output format string and an optional locale string.";
                }
            }

            return (value, error);
        }

19 Source : FormatDateTime.cs
with MIT License
from microsoft

private static (object, string) ParseTimestamp(string timeStamp, Func<DateTime, object> transform = null)
        {
            object result = null;
            string error = null;
            if (DateTime.TryParse(
                    s: timeStamp,
                    provider: CultureInfo.InvariantCulture,
                    styles: DateTimeStyles.RoundtripKind,
                    result: out var parsed))
            {
                result = transform != null ? transform(parsed) : parsed;
            }
            else
            {
                error = $"Could not parse {timeStamp}";
            }

            return (result, error);
        }

19 Source : TimePeriodMeasurementObservationGroupFactory.cs
with MIT License
from microsoft

public virtual (DateTime Start, DateTime End) GetBoundaryKey(IMeasurement measurement)
        {
            EnsureArg.IsNotNull(measurement);

            return _boundaryFunction(measurement.OccurrenceTimeUtc.ToUniversalTime());
        }

19 Source : ProjectionTests.cs
with MIT License
from microsoft

[TestMethod]
        [UnitTest]
        public void ComposeWithFuncComposesCorrectly()
        {
            var f = Projection.CreateUsingFuncAdaptor<int, DateTime>(i => DateTime.FromFileTime(i));
            var g = new Func<DateTime, string>(x => x.ToString());

            var argument = 23;
            var expected = g(f[argument]);

            var sut = f.Compose(g);
            var actual = sut[argument];

            replacedert.AreEqual(expected, actual);
        }

19 Source : BaseStoreService.cs
with MIT License
from msx752

private async void OnTimedEvent()
        {
            while (true)
            {
                try
                {
                    var ts = await CheckPeriod(DateTime.UtcNow);
                    Global.Log.Information("{lt}: {ServiceName} refresh period is {ServiceRefreshTime}", "Service", typeof(T).Name.Replace("EventArgs", ""), ts.ToString());
                    await Task.Delay(ts.Add(new TimeSpan(0, 1, 0)));
                    if (BaseStoreCallback != null)
                    {
                        await timedEventAction(this);
                    }
                }
                catch (Exception e)
                {
                    Global.Log.Error($"{{lt}}: {typeof(T).Name.Replace("EventArgs", "")}; {e}", "Service");
                }
            }
        }

19 Source : BaseIndexer.cs
with GNU Affero General Public License v3.0
from ONLYOFFICE

public IEnumerable<List<T>> IndexAll(
            Func<DateTime, (int, int, int)> getCount,
            Func<DateTime, List<int>> getIds,
            Func<long, long, DateTime, List<T>> getData)
        {
            var now = DateTime.UtcNow;
            var lastIndexed = WebstudioDbContext.WebstudioIndex
                .Where(r => r.IndexName == Wrapper.IndexName)
                .Select(r => r.LastModified)
                .FirstOrDefault();

            if (lastIndexed.Equals(DateTime.MinValue))
            {
                CreateIfNotExist(ServiceProvider.GetService<T>());
            }

            var (count, max, min) = getCount(lastIndexed);
            Log.Debug($"Index: {IndexName}, Count {count}, Max: {max}, Min: {min}");

            var ids = new List<int>() { min };
            ids.AddRange(getIds(lastIndexed));
            ids.Add(max);

            for (var i = 0; i < ids.Count - 1; i++)
            {
                yield return getData(ids[i], ids[i + 1], lastIndexed);
            }


            WebstudioDbContext.AddOrUpdate(r => r.WebstudioIndex, new DbWebstudioIndex()
            {
                IndexName = Wrapper.IndexName,
                LastModified = now
            });

            WebstudioDbContext.SaveChanges();

            Log.Debug($"index completed {Wrapper.IndexName}");
        }

19 Source : Guard.DateTime.cs
with MIT License
from safakgur

readonly ArgumentInfo<DateTime> KindSpecified(
            in this ArgumentInfo<DateTime> argument, Func<DateTime, string>? message = null)
        {
            if (argument.Value.Kind == DateTimeKind.Unspecified)
            {
                var m = message?.Invoke(argument.Value) ?? Messages.KindSpecified(argument);
                throw Fail(new ArgumentException(m, argument.Name));
            }

            return ref argument;
        }

19 Source : Guard.DateTime.cs
with MIT License
from safakgur

readonly ArgumentInfo<DateTime?> KindSpecified(
            in this ArgumentInfo<DateTime?> argument, Func<DateTime, string>? message = null)
        {
            if (argument.HasValue())
            {
                var value = argument.GetValueOrDefault();
                if (value.Kind == DateTimeKind.Unspecified)
                {
                    var m = message?.Invoke(value) ?? Messages.KindSpecified(argument);
                    throw Fail(new ArgumentException(m, argument.Name));
                }
            }

            return ref argument;
        }

See More Examples