/// <summary> /// /// </summary> /// <param name="numberOfItemsToCreate">The number of test posts to create</param> /// <param name="commentLimit">The upper limit of the number of random comments to create per post</param> public static void Run(int numberOfItemsToCreate, int commentLimit) { Console.WriteLine(String.Format("InitializeDatabase")); List<Post> posts = new List<Post>(); var repo = new MongoData(); repo.Clean(); for (int i = 0; i < numberOfItemsToCreate; i++) { var post = CreateTestPost("Discussion " + i, "email" + i + "@here.com", commentLimit); posts.Add(post); } Console.WriteLine(String.Format("\tTotal posts[{0}] and comments[{1}]",posts.Count(),posts.Sum(post => post.Comments.Count()))); DateTime start = DateTime.Now; repo.SaveBatch(posts); //repo.Save(posts); DateTime end = DateTime.Now; Console.WriteLine(String.Format("\tTime to insert {0} items:{1} seconds. {2} per insert" , (posts.Count() + posts.Sum(post => post.Comments.Count())) , (end - start).TotalSeconds , (end - start).TotalSeconds/ (posts.Count() + posts.Sum(post => post.Comments.Count())))); Console.WriteLine(String.Format("\tCreated MongoDB {0} with {1} rows", MongoData.MongoDbName, numberOfItemsToCreate)); repo.SaveManuscript(CreateTestWord()); repo.SaveManuscript(CreateTestExcel()); }
static void Main() { string input = Console.ReadLine(); List<decimal> inputNums = new List<decimal>(); List<decimal> oddNums = new List<decimal>(); List<decimal> evenNums = new List<decimal>(); string[] numbers = input.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); foreach (var num in numbers) { inputNums.Add(decimal.Parse(num)); } int index = 1; for (int i = 0; i < inputNums.Count; i++) { if (index % 2 == 1) { oddNums.Add(inputNums[i]); } else { evenNums.Add(inputNums[i]); } index++; } if (inputNums.Count == 0) { Console.WriteLine("OddSum=No, OddMin=No, OddMax=No, EvenSum=No, EvenMin=No, EvenMax=No"); } else if (inputNums.Count == 1) { double oddNumsSum = (double)oddNums.Sum(); double oddNumsMin = (double)oddNums.Min(); double oddNumsMax = (double)oddNums.Max(); Console.WriteLine("OddSum={0:G0}, OddMin={1:G0}, OddMax={2:G0}, EvenSum=No, EvenMin=No, EvenMax=No", oddNumsSum, oddNumsMin, oddNumsMax); } else { double oddNumsSum = (double)oddNums.Sum(); double oddNumsMin = (double)oddNums.Min(); double oddNumsMax = (double)oddNums.Max(); double evenNumsSum = (double)evenNums.Sum(); double evenNumsMin = (double)evenNums.Min(); double evenNumsMax = (double)evenNums.Max(); Console.WriteLine("OddSum={0:G0}, OddMin={1:G0}, OddMax={2:G0}, EvenSum={3:G0}, EvenMin={4:G0}, EvenMax={5:G0}", // {...:G0} Remove trailing zeros oddNumsSum, oddNumsMin, oddNumsMax, evenNumsSum, evenNumsMin, evenNumsMax); } }
public NaiveBayes(List<Case> cases) { this.classProbabilities = new List<ClassGrouping>(); this.attrProbabilities = new List<AttrGroupings>(); for (int i = 0; i < cases.First().attributes.Count; i++) attrProbabilities.Add(new AttrGroupings(cases, i)); var originalGroupings = cases.GroupBy(c => c.classification).ToList(); if (originalGroupings.Count <= 25) { for (int i = 0; i < originalGroupings.Count; i++) { double probability = (double)originalGroupings[i].Sum(c => c.weight) / (double)cases.Sum(c => c.weight); // trenger egentlig ikke dele her, da sum av vekter er 1. this.classProbabilities.Add(new ClassGrouping(originalGroupings[i].ToList(), this.attrProbabilities, probability)); } } else { List<Case> temp = cases.OrderBy(c => c.classification).ToList(); int takeCount = temp.Count / numOfGroupings; for (int i = 0; i < numOfGroupings; i++) { List<Case> temp2; if (i != numOfGroupings - 1) temp2 = temp.Skip(takeCount * i).Take(takeCount).ToList(); else temp2 = temp.Skip(takeCount * i).ToList(); double probability = (double)temp2.Sum(c => c.weight) / (double)cases.Sum(c => c.weight); // trenger egentlig ikke dele her, da sum av vekter er 1. this.classProbabilities.Add(new ClassGrouping(temp2, this.attrProbabilities, probability)); } } }
public override void NormalizeRouletteWheel(List<AbstractPhenotype> adults) { double average = adults.Average(x => x.Fitness); double standardDeviation = Math.Sqrt(adults.Sum(x => Math.Pow((x.Fitness - average), 2))/adults.Count); double rouletteProportion = 0; if (standardDeviation <= 0.0) { double normalizedValue = 1.0/adults.Count; foreach (AbstractPhenotype adult in adults) { rouletteProportion += normalizedValue; adult.RouletteProportion = rouletteProportion; } } else { double sigmaSum = adults.Sum(x => (1 + ((x.Fitness - average)/(2*standardDeviation)))); foreach (AbstractPhenotype adult in adults) { double normalizedValue = (1 + ((adult.Fitness - average)/(2*standardDeviation)))/sigmaSum; rouletteProportion += normalizedValue; adult.RouletteProportion = rouletteProportion; } } }
void AgentsEventHandler_OnPhoneCall(object sender, PhoneCallEventArguments e) { if (!lbCalls.Items.Contains(e.PhoneCallEvent)) lbCalls.Items.Add(e.PhoneCallEvent); lbCalls.DisplayMember = "PhoneCallID"; long totalTime = 0, totalWait = 0; List<PhoneCallEvent> meList = new List<PhoneCallEvent>(); foreach (object o in lbCalls.Items) meList.Add(o as PhoneCallEvent); //get the total number of calls int totalCalls = CallCenter.CallsCompleted; //(from tc in meList select tc).Count(); //get the total time for and the total wait time totalTime = meList.Sum(n => n.PhoneCallLength); totalWait = meList.Sum(n => n.WaitTimeLength); //find out if there are any unassigned phone calls lblPendingCallsValue.Text = (from tc in meList where tc.AgentID == 0 select tc).Count().ToString(); //now assign the variables if (totalCalls > 0) { lblAvgCallTimeValue.Text = FormatMSToTime(totalTime / totalCalls); lblAvgWaitValue.Text = String.Format("{0} ms", (totalWait / totalCalls)); } else lblAvgCallTimeValue.Text = "N/A"; UpdateData(cbData.SelectedItem.ToString()); }
public TopicModel(ILmsService ilmsService, long selectDisciplineId) { IEnumerable<Topic> temp_allowedTopics = ilmsService.FindService<IDisciplineService>().GetTopicsByDisciplineId((int)selectDisciplineId); this.disciplineName = ilmsService.FindService<IDisciplineService>().GetDiscipline((int)selectDisciplineId).Name; if (temp_allowedTopics != null & temp_allowedTopics.Count() != 0) { double tempDisciplineQuality = 0; var temp = new List<KeyValuePair<Topic, double>>(); foreach (var topic in temp_allowedTopics) { List<double> quality = new List<double>(); quality.Add(0); tempDisciplineQuality += quality.Sum() / quality.Count; temp.Add(new KeyValuePair<Topic, double>(topic, quality.Sum() / quality.Count)); } this.disciplineQuality = tempDisciplineQuality / temp.Count; this.allowedTopics = temp; } else { this.disciplineQuality = 0; this.allowedTopics = null; } }
public void MakeForecast(double[] x, double[] y, out double[] resX, out double[] resY, int count) { double xmin = x.Min(); double n = y.Length; List<double> x_ = new List<double>(); for (int i = 0; i < x.Count()-1; i++) x_.Add(x[i] - xmin + 1); double sum_log_yt = y.Sum(yt => Math.Log(yt)); double sum_t_2 = x_.Sum(t => t*t); double sum_t = x_.Sum(t => t); double sum_log_yt_t = x_.Sum(t => Math.Log(y[(int) t - 1])*t); double B = (sum_log_yt*sum_t - n*sum_log_yt_t)/(sum_t*sum_t - n*sum_t_2); double A = (sum_log_yt*sum_t_2 - sum_log_yt_t*sum_t)/(n*sum_t_2 - sum_t*sum_t); //double B = (sum_t*sum_log_yt - n*sum_log_yt_t)/(sum_t*sum_t - n*sum_t_2); //double A = 1/n*(sum_log_yt - sum_t*B); double a = Math.Exp(A); double b = Math.Exp(B); List<double> listX = new List<double>(); List<double> listY = new List<double>(); for (int i = 0; i < x.Length + count-1; i++) { listX.Add(i + xmin); listY.Add(a*Math.Pow(b, i)); } resX = listX.ToArray(); resY = listY.ToArray(); }
private SeriesStatistics MapSeriesStatistics(List<SeasonStatistics> seasonStatistics) { var seriesStatistics = new SeriesStatistics { SeasonStatistics = seasonStatistics, SeriesId = seasonStatistics.First().SeriesId, EpisodeFileCount = seasonStatistics.Sum(s => s.EpisodeFileCount), EpisodeCount = seasonStatistics.Sum(s => s.EpisodeCount), TotalEpisodeCount = seasonStatistics.Sum(s => s.TotalEpisodeCount), SizeOnDisk = seasonStatistics.Sum(s => s.SizeOnDisk) }; var nextAiring = seasonStatistics.Where(s => s.NextAiring != null) .OrderBy(s => s.NextAiring) .FirstOrDefault(); var previousAiring = seasonStatistics.Where(s => s.PreviousAiring != null) .OrderBy(s => s.PreviousAiring) .LastOrDefault(); seriesStatistics.NextAiringString = nextAiring != null ? nextAiring.NextAiringString : null; seriesStatistics.PreviousAiringString = previousAiring != null ? previousAiring.PreviousAiringString : null; return seriesStatistics; }
public PersonSalaryReport( List<PersonReportItem> persons ) { Persons = persons; TotalSalary = persons.Sum( p => p.Salary ); TotalTaxes = persons.Sum( p => p.Tax ); TotalTakeHomeSalary = TotalSalary - TotalTaxes; }
public RankingData(FormMain form, DateTime dtFraArg, DateTime dtTilArg, DateTime dtPickArg) { try { this.main = form; dtFra = dtFraArg; dtTil = dtTilArg; dtPick = dtPickArg; velgerPeriode = FormMain.datoPeriodeVelger; this.varekoderDataAlle = main.appConfig.varekoder.Where(item => item.kategori == "Nettbrett" || item.kategori == "Data").ToList(); this.varekoderData = main.appConfig.varekoder.Where(item => item.kategori == "Data").ToList(); this.varekoderNettbrett = main.appConfig.varekoder.Where(item => item.kategori == "Nettbrett").ToList(); this.varekoderDataColumns = varekoderData.Where(p => p.synlig == true).DistinctBy(p => p.alias).ToList(); this.varekoderNettbrettColumns = varekoderNettbrett.Where(p => p.synlig == true).DistinctBy(p => p.alias).ToList(); // Sjekk om listen har provisjon int prov = varekoderDataAlle.Sum(x => Convert.ToInt32(x.provSelger)); prov += varekoderDataAlle.Sum(x => Convert.ToInt32(x.provTekniker)); if (prov != 0) provisjon = true; } catch (Exception ex) { Log.Unhandled(ex); } }
private static BigInteger Solve(List<int> parties, int k) { var sums = new BigInteger[parties.Sum() + 1]; sums[0] = 1; var maxSum = 0; for (int i = 0; i < parties.Count; i++) { var number = parties[i]; for (int j = maxSum; j >= 0; j--) { if (sums[j] > 0) { sums[j + number] += sums[j]; maxSum = Math.Max(j + number, maxSum); } } } BigInteger combinations = 0; for (int i = k; i <= parties.Sum(); i++) { combinations += sums[i]; } return combinations; }
static void Main(string[] args) { int num = int.Parse(Console.ReadLine()); int[] n = Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); int[] seq = n.Distinct().ToArray(); double combinations = Math.Pow(2, seq.Length); List<int> intList = new List<int>(); int count = 0; for (int i = 1; i < combinations; i++) { int sum = 0; CheckCombination(i, seq, ref intList); sum = intList.Sum(); if ( sum == num ) { Console.WriteLine("{0} = {1}", string.Join(" + ", intList.Select(x => x.ToString()).ToArray()), intList.Sum() ); count++; } intList = new List<int>(); } if (count == 0) { Console.WriteLine("No matching subsets."); } }
public static void Calculate(IEnumerable<byte> bytes, byte bitWidth) { var maxValues = Math.Pow(2, bitWidth); var blockValuesBuffer = new List<byte>(); var blockSizes = new List<int>(); var currentBlockSize = 0; foreach (var b in bytes) { var isRepeatedByte = blockValuesBuffer.Contains(b); if (!isRepeatedByte && blockValuesBuffer.Count == maxValues || currentBlockSize == MaxBlockSize) { blockSizes.Add(currentBlockSize); blockValuesBuffer.Clear(); currentBlockSize = 0; } if (!isRepeatedByte) { blockValuesBuffer.Add(b); } currentBlockSize++; } float totalBits = blockSizes.Sum() * 8; float compressedBits = blockSizes.Sum() * bitWidth + blockSizes.Count * (256 /* bitmask */ + 16 /* block size */); Console.WriteLine("Total blocks: {0:N0}", blockSizes.Count); Console.WriteLine("Average block size: {0:N0}", blockSizes.Average()); Console.WriteLine("Max block size: {0}", blockSizes.Max()); Console.WriteLine("Estimated file size: {0:N2}%", 100 * compressedBits / totalBits); }
private static void GetSumOfLimitedCoins(int[] arr, int sum, List<int> combTemp, int index = 0) { if (combTemp.Sum() == sum) { combinations.Add(string.Join(",", combTemp)); return; } if (combTemp.Sum() > sum) { return; } for (int i = index; i < arr.Length; i++) { if (!usedCoins[i]) { usedCoins[i] = true; combTemp.Add(arr[i]); GetSumOfLimitedCoins(arr, sum, combTemp, i); combTemp.Remove(arr[i]); usedCoins[i] = false; } } }
static void Main() { int searchedSum = int.Parse(Console.ReadLine()); int[] numbers = Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); int[] sequence = numbers.Distinct().ToArray(); double combinations = Math.Pow(2, sequence.Length); List<int> listOfInts = new List<int>(); int count = 0; for (int i = 1; i < combinations; i++) { int sum = 0; FindCombinations(i, sequence, ref listOfInts); sum = listOfInts.Sum(); if (sum == searchedSum) { Console.WriteLine("{0} = {1}", string.Join(" + ", listOfInts.Select(x => x.ToString()).ToArray()), listOfInts.Sum() ); count++; } listOfInts = new List<int>(); } if (count == 0) { Console.WriteLine("No matching subsets."); } }
DtoResultadosProcesoElectoral ContarVotosProcesoElectoralUnipersonal(Pe01_ProcesoElectoral procesoElectoral) { if (procesoElectoral != null) { var listasProceso = procesoElectoral.Listas; if (listasProceso?.Count() > 0) { var votosProceso = _votoRepository.Get <Mv01_Voto>(x => x.Estado.Equals(Auditoria.EstadoActivo) && x.ProcesoElectoralId == procesoElectoral.Id); var resultadoListas = new List <DtoVotoDetalleLista>(); listasProceso.ToList()?.ForEach(x => { resultadoListas.Add(ObtenerInformacionListaUniPersonal(x, votosProceso)); }); return(new DtoResultadosProcesoElectoral() { NumeroEmpadronados = procesoElectoral?.PadronesVotacion?.Count() ?? 0, NumeroVotosValidos = resultadoListas?.Sum(x => x.CantidadVotos) ?? 0, NumeroVotosBlancos = resultadoListas?.Sum(x => x.CantidadBlancos) ?? 0, NumeroVotosNulos = resultadoListas?.Sum(x => x.CantidadNulos) ?? 0, PorcentajeVotantes = (procesoElectoral?.PadronesVotacion?.Count() ?? 0) == 0 ? 0 : ((votosProceso?.Count() ?? 0) / (procesoElectoral.PadronesVotacion.Count()) * 100), DetallesListas = resultadoListas }); } throw new Exception("Proceso sin listas "); } throw new Exception("Proceso electoral votación no existe"); }
public virtual decimal Calculate(List<LineItem> lineItems) { var totalCost = lineItems.Sum(x => x.Amount - x.TaxAmount); var totalTax = lineItems.Sum(x => x.TaxAmount); return Round(totalCost + totalCost * DefaultMargin + totalTax); }
private async Task WriteBuildDetails(Build build, List <TestRun> testRuns, CodeCoverageSummary coverage, ISink sink) { CodeCoverageStatistics linesCovered = coverage?.CoverageData?.FirstOrDefault()?.CoverageStats?.FirstOrDefault(s => s.Label == LinesCoverageStatsLabel); int totalTests = testRuns?.Sum(r => r.TotalTests) ?? 0; int passedTests = testRuns?.Sum(r => r.PassedTests) ?? 0; int ignoredTests = testRuns?.Sum(r => r.IncompleteTests + r.NotApplicableTests + r.UnanalyzedTests) ?? 0; await sink.Write( new string[] { build.Id.ToString(), build.BuildNumber, build.Definition?.Name, build.RequestedBy?.DisplayName, build.RequestedFor?.DisplayName, build.Repository?.Name, build.QueueTime?.ToString("s"), build.StartTime?.ToString("s"), build.FinishTime?.ToString("s"), build.SourceBranch, build.SourceVersion, build.Result.ToString(), totalTests.ToString(), passedTests.ToString(), ignoredTests.ToString(), linesCovered?.Covered.ToString(), linesCovered?.Total.ToString() }); }
static void Main(string[] args) { Prime.SieveOfAtkin(1000000); int biggestPrime = 0; List<int> sumList = new List<int>(); int sumCount = 0; foreach (int p in Prime.Primes) { sumList = new List<int>(); for (int i = Prime.Primes.IndexOf(p); i < Prime.Primes.Count; i++) { sumList.Add(Prime.Primes[i]); if (sumList.Sum() > Prime.Primes.Last()) break; int sum = sumList.Sum(); if (Prime.Primes.Contains(sum)) { if (sumList.Count > sumCount) { biggestPrime = sum; sumCount = sumList.Count; } } } } Console.WriteLine(biggestPrime); Console.Read(); }
static void Main() { int sumNumber = int.Parse(Console.ReadLine()); int[] input = Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); int[] sequence = input.Distinct().ToArray(); double combinations = Math.Pow(2, sequence.Length); List<int> sumsList = new List<int>(); bool match = false; for (int i = 1; i < combinations; i++) { int sum = 0; CheckCombination(i, sequence, ref sumsList); sum = sumsList.Sum(); if (sum == sumNumber) { Console.WriteLine("{0} = {1}", string.Join(" + ", sumsList.Select(x => x.ToString()).ToArray()), sumsList.Sum()); match = true; } sumsList = new List<int>(); } if (match == false) { Console.WriteLine("No matching subsets."); } }
public override decimal Calculate(List<LineItem> lineItems) { var totalCost = lineItems.Sum(x => x.Amount - x.TaxAmount); var totalTax = lineItems.Sum(x => x.TaxAmount); return Round(totalCost + totalCost * (DefaultMargin + ExtraMargin) + totalTax); }
static void Main() { int n = int.Parse(Console.ReadLine()); List<int> oddNums = new List<int>(); List<int> evenNums = new List<int>(); int count = 0; for (int i = 0; i < n * 2; i++) { int number = int.Parse(Console.ReadLine()); count++; if (count % 2 == 0) { evenNums.Add(number); } else { oddNums.Add(number); } } if (oddNums.Sum() == evenNums.Sum()) { Console.WriteLine("Yes, sum={0}", oddNums.Sum()); } else { Console.WriteLine("No, diff={0}", Math.Abs(oddNums.Sum() - evenNums.Sum())); } }
public void BuildReport(StringBuilder sb) { sb.AppendLine(" <br/> <h3>Торговля</h3>"); sb.AppendLine(" <br/> <table class=\"lightTable\">"); sb.AppendLine(AccountTrades.RenderCaption()); // получить количество открытых / закрытых по счетам сделок за указанное количество дней var records = new List<AccountTrades>(); foreach (var account in RobotFarm.Instance.Accounts.OrderBy(a => a.AccountId)) { var record = MakeAccountTradesRecord(account); records.Add(record); sb.AppendLine(record.ToString()); } var sumRecord = new AccountTrades { AccountTitle = "- Суммарно -", ClosedTrades = records.Sum(r => r.ClosedTrades), OpenedTrades = records.Sum(r => r.OpenedTrades), ClosedVolumeDepo = records.Sum(r => r.ClosedVolumeDepo), Exposure = records.Sum(r => r.Exposure), OpenProfit = records.Sum(r => r.OpenProfit), }; sumRecord.LastOpen = records.Count == 0 ? DateTime.MinValue : records.Max(r => r.LastOpen ?? DateTime.MinValue); if (sumRecord.LastOpen == DateTime.MinValue) sumRecord.LastOpen = null; sb.AppendLine(sumRecord.ToString()); sb.AppendLine(" </table>"); }
static void Main(string[] args) { List<int> list = new List<int>(); list = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(x => int.Parse(x)) .ToList(); Console.WriteLine("Sum: {0}, Average: {1}", list.Sum(), (double)list.Sum()/list.Count); }
protected override string GetHeaderSection(List<UserDayStats> userStats, DateTime date, int startHour, int endHour) { var totalStarredMessages = userStats.Sum(x => x.StarredMessages); var totalStarsGiven = userStats.Sum(x => x.StarsGained); var dateValue = date.ToString("yyyy-MM-dd"); return $"A total of {totalStarredMessages} messages were starred and {totalStarsGiven} stars were given on {dateValue} between hours {startHour} and {endHour}."; }
/// <summary> /// Take each sentences, dillute the score according to this sentence's proportion of the total /// length, and then round down to the nearest whole number. That's our score. 0 is most negative, /// 4 is most positive. /// </summary> private Sentiments CalculatedWeightedSentiment(List<ScoredSentence> sentences) { var totalLength = sentences.Sum(s => s.Sentence.length()); decimal averageScore = sentences.Sum(s => s.WeightedScore(totalLength)); int finalScore = (int) Math.Floor(averageScore); return (Sentiments) finalScore; }
static void Main(string[] args) { string input = Console.ReadLine(); List<string> text = new List<string>(); while (input != "</table>") { text.Add(input); input = Console.ReadLine(); } List<decimal> result = new List<decimal>(); result.Add(Decimal.MinValue); Regex regex = new Regex(@"<td>(-?[0-9.?]+)</td>"); for (int i = 2; i < text.Count; i++) { List<decimal> tempList = new List<decimal>(); string tempstr = text[i]; MatchCollection matches = regex.Matches(tempstr); foreach (Match match in matches) { tempList.Add(decimal.Parse(match.Groups[1].Value)); } if (tempList.Sum() > result.Sum()) { result.Clear(); result.AddRange(tempList); } } if (result.Count == 0) { Console.WriteLine("no data"); } else if (result.Count() == 1 ) { Console.WriteLine("{0:f0} = {0}", result.First()); } else { StringBuilder resultBuilder = new StringBuilder(); if (result.Sum() == 0) { resultBuilder.AppendFormat("{0:f0} = ", result.Sum()); } else { resultBuilder.AppendFormat("{0} = ", result.Sum()); } foreach (var num in result) { resultBuilder.Append(num + " + "); } Console.WriteLine(resultBuilder.ToString().Trim(new char[] { '+', ' ' })); } }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { // Get application and document objects UIApplication uiApp = commandData.Application; try { // Implement Selection Filter to select curves IList<Element> pickedRef = null; Selection sel = uiApp.ActiveUIDocument.Selection; DetailLineFilter selFilter = new DetailLineFilter(); pickedRef = sel.PickElementsByRectangle(selFilter, "Select lines"); // Measure their total length List<double> lengthList = new List<double>(); foreach (Element e in pickedRef) { DetailLine line = e as DetailLine; if (line != null) { lengthList.Add(line.GeometryCurve.Length); } } string lengthFeet = Math.Round(lengthList.Sum(), 2).ToString() + " ft"; string lengthMeters = Math.Round(lengthList.Sum() * 0.3048, 2).ToString() + " m"; string lengthMilimeters = Math.Round(lengthList.Sum() * 304.8, 2).ToString() + " mm"; string lengthInch = Math.Round(lengthList.Sum() * 12, 2).ToString() + " inch"; StringBuilder sb = new StringBuilder(); sb.AppendLine("Total Length is:"); sb.AppendLine(lengthFeet); sb.AppendLine(lengthInch); sb.AppendLine(lengthMeters); sb.AppendLine(lengthMilimeters); // Return a message window that displays total length to user TaskDialog.Show("Line Length", sb.ToString()); // Assuming that everything went right return Result.Succeeded return Result.Succeeded; } // This is where we "catch" potential errors and define how to deal with them catch (Autodesk.Revit.Exceptions.OperationCanceledException) { // If user decided to cancel the operation return Result.Canceled return Result.Cancelled; } catch (Exception ex) { // If something went wrong return Result.Failed message = ex.Message; return Result.Failed; } }
public void LoadIssues(List<Issue> issues, DateTime worklogStartdate, DateTime worklogEnddate) { Issues = issues; EstimateInSeconds = Issues.Sum(issue => (issue.TimeTracking != null ? issue.TimeTracking.OriginalEstimateSeconds : 0)); TimeSpentInSeconds = Issues.Sum(issue => (issue.TimeTracking != null ? issue.TimeTracking.TimeSpentSeconds : 0)); RemainingEstimateInSeconds = Issues.Sum(issue => (issue.TimeTracking != null ? issue.TimeTracking.RemainingEstimateSeconds : 0)); }
protected override string GetHeaderSection(List<UserDayStats> userStats, DateTime startDate, DateTime endDate) { var totalStarredMessages = userStats.Sum(x => x.StarredMessages); var totalStarsGiven = userStats.Sum(x => x.StarsGained); var start = startDate.ToString("yyyy-MM-dd"); var end = endDate.ToString("yyyy-MM-dd"); return $"A total of {totalStarredMessages} messages were starred and {totalStarsGiven} stars were given between {start} and {end}."; }
public IDictionary<BetSheet, IList<BetOrder>> BuildOrder(User user, LotterySpecies specie, IEnumerable<AutoBetItem> betList, IDictionary<string, object> parameters) { this._betResult = new BetResult(); BetResult returnResult = new Models.BetResult(); var todayLotteryCompany = TodayLotteryCompany.Instance.GetTodayCompany(); //获取今日开奖公司 var memberComm = CommManager.GetMemberCommissionInSession(user, specie); //获取会员的佣金 IDictionary<BetSheet, IList<BetOrder>> betSheetDic = new Dictionary<BetSheet, IList<BetOrder>>(); IDictionary<BetSheet, IList<BetOrder>> resultDic = new Dictionary<BetSheet, IList<BetOrder>>(); foreach (var betOrder in betList) { int[] nums; switch (betOrder.BetType) { case AutoBetType.TwelveZodiac: nums = LotterySystem.Current.TwelveZodiac; break; case AutoBetType.EvenEven: nums = LotterySystem.Current.EvenEven; break; case AutoBetType.EvenOdd: nums = LotterySystem.Current.EvenOdd; break; case AutoBetType.OddEven: nums = LotterySystem.Current.OddEven; break; case AutoBetType.OddOdd: nums = LotterySystem.Current.OddOdd; break; case AutoBetType.Small: nums = LotterySystem.Current.Small; break; case AutoBetType.Big: nums = LotterySystem.Current.Big; break; default: throw new InvalidDataException("不可到达,数据异常!"); } var sheet = BuildAutoElectionCodeOrder(user, specie, betOrder.CompanyList, betOrder.WagerList, nums); betSheetDic.AddRange(sheet); returnResult.Append(this.BetResult); List<BetOrder> orderList = new List<BetOrder>(); foreach (var item in betSheetDic) orderList.AddRange(item.Value); StringBuilder companySb = new StringBuilder(); foreach (var companyId in betOrder.CompanyList) { var company = todayLotteryCompany.Find(it => it.CompanyId == companyId); if (company == null) throw new InvalidDataException("CompanyId:" + companyId); companySb.AppendFormat("{0} ", company.Abbreviation); } BetSheet orderSheet = new BetSheet { Num = betOrder.BetType.ToString(), Turnover = orderList.Sum(it => it.Turnover), NetAmount = orderList.Sum(it => it.NetAmount), Commission = orderList.Sum(it => it.Commission), UserId = user.UserId, Status = BetStatus.Valid, IPAddress = IPHelper.IPAddress, BetCompany = companySb.ToString(), BetAmount = JoinSheetBetAmount(sheet.Keys) }; resultDic.Add(orderSheet, orderList); betSheetDic.Clear(); } this._betResult = returnResult; return resultDic; }
public ActionResult ObtenerVentasDiarias(PagingInfo paginacion, string ANIO = null, string MES = null) { //string mes, anio; if (ANIO == null && MES == null) { //DateTime fecha = DateTime.Now; MES = DateTime.Now.ToString("MM"); ANIO = DateTime.Now.ToString("yyyy"); } var result = _serVen.ObtenerVentasDiariasPaginado(paginacion, ANIO, MES).GroupBy(y => new { y.FECHA }).Select(z => new { FECHA = z.Key.FECHA, TOTAL = z.Sum(x => x.TOTAL) }); List<VentasDiariasModel> listas = new List<VentasDiariasModel>(); foreach (var item in result) { VentasDiariasModel venDia = new VentasDiariasModel { FECHA = item.FECHA, VENTA_TOTAL = item.TOTAL }; var ventadiaria = _serVen.ObtenerVentasDiariasPorCriterio(x => x.FECHA == item.FECHA); foreach (var diario in ventadiaria) { if (diario.TURNO == "DIA") { venDia.VENTA_DIA = diario.TOTAL; } else if (diario.TURNO == "TARDE") { venDia.VENTA_TARDE = diario.TOTAL; } else { venDia.VENTA_NOCHE = diario.TOTAL; } } listas.Add(venDia); } listas = listas.OrderBy(x => x.FECHA).ToList(); listas.Add(new VentasDiariasModel() { VENTA_DIA = listas.Sum(x=>x.VENTA_DIA), VENTA_NOCHE = listas.Sum(x=>x.VENTA_NOCHE), VENTA_TARDE = listas.Sum(x=>x.VENTA_TARDE), VENTA_TOTAL = listas.Sum(x=>x.VENTA_TOTAL) }); JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); string callback1 = paginacion.callback + "(" + javaScriptSerializer.Serialize(new { Rows = listas, Total = paginacion.total }) + ");"; return JavaScript(callback1); }
internal static ValuationFeeDetails Map(List <BldgapplicationValues> bldgvalues) { List <ValuationFeeDetailsItem> items = new List <ValuationFeeDetailsItem>(); for (int i = 0; i < bldgvalues?.Count; i++) { items.Add(new ValuationFeeDetailsItem(bldgvalues[i]?.SequenceNumber, bldgvalues[i]?.ComponentDescription, bldgvalues[i]?.OccupantType, bldgvalues[i]?.NumberOfOccupants, bldgvalues[i]?.TableNumberSectLineSeq, bldgvalues[i]?.SquareFeet, bldgvalues[i]?.SectionDescription, bldgvalues[i]?.ConstructionTypeDescription, bldgvalues[i]?.Cost, bldgvalues[i]?.ExtendedValue)); } return(new ValuationFeeDetails(bldgvalues?.Sum(t => t?.ExtendedValue), bldgvalues?.Sum(t => t?.SquareFeet), items)); }
private static ArgumentListSyntax GenerateArgumentListSyntaxWithCommas(List <ExpressionSyntax> argumentSyntax) { var argumentListSyntaxWithCommas = new List <SyntaxNodeOrToken>(); var allArgumentsLengthRequiresBreak = argumentSyntax?.Sum(x => x.FullSpan.Length) > 50 && argumentSyntax?.Count > 2; for (var i = 0; i < argumentSyntax?.Count; i++) { argumentListSyntaxWithCommas.Add(SyntaxFactory.Argument(argumentSyntax[i])); if (i == argumentSyntax.Count - 1) { continue; } if (allArgumentsLengthRequiresBreak) { argumentListSyntaxWithCommas.Add(CreateCommaTokenWithEnter()); } else { argumentListSyntaxWithCommas.Add(SyntaxFactory.Token(SyntaxKind.CommaToken)); } } return(SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList <ArgumentSyntax>(argumentListSyntaxWithCommas))); }
private static Procedure_InclusaoReservaFiltersType GerarReservaFiltersType(string chave, string senha, Reserva reserva, List <IMes> mes, Programa programa, Estrutura estrutura, Fonte fonte, Regional regional) { var bim1 = new string[] { "01", "02", "03" }; var bim2 = new string[] { "04", "05", "06" }; var bim3 = new string[] { "07", "08", "09" }; var bim4 = new string[] { "10", "11", "12" }; var inQuotaReserva1 = mes?.Where(x => bim1.Contains(x.Descricao)).Sum(y => y.ValorMes).ToString(); var inQuotaReserva2 = mes?.Where(x => bim2.Contains(x.Descricao)).Sum(y => y.ValorMes).ToString(); var inQuotaReserva3 = mes?.Where(x => bim3.Contains(x.Descricao)).Sum(y => y.ValorMes).ToString(); var inQuotaReserva4 = mes?.Where(x => bim4.Contains(x.Descricao)).Sum(y => y.ValorMes).ToString(); var inTotalReserva = mes?.Sum(x => x.ValorMes).ToString(); Procedure_InclusaoReservaFiltersType reservaFiltersType = new Procedure_InclusaoReservaFiltersType { inOperador = chave, inChave = senha, inAnoRefRes = reserva?.AnoExercicio.ToString().Substring(2, 2), inAnoExercicio = DateTime.Now.Month <= 2 ? reserva?.AnoExercicio.ToString().Substring(2, 2) : null, inCFPRes_1 = programa?.Cfp?.Substring(0, 2), inCFPRes_2 = programa?.Cfp?.Substring(2, 3), inCFPRes_3 = programa?.Cfp?.Substring(5, 4), inCFPRes_4 = programa?.Cfp?.Substring(9, 4), inCFPRes_5 = reserva?.OrigemRecurso?.Substring(1, 2) + "00" ?? string.Empty, inCEDRes_1 = estrutura?.Natureza?.Substring(0, 1), inCEDRes_2 = estrutura?.Natureza?.Substring(1, 1), inCEDRes_3 = estrutura?.Natureza?.Substring(2, 1), inCEDRes_4 = estrutura?.Natureza?.Substring(3, 1), inCEDRes_5 = estrutura?.Natureza?.Substring(4, 2), inOrgao = regional?.Descricao?.Substring(2, 2), inCodAplicacaoRes = reserva?.Obra?.ToString(), inOrigemRecursoRes = reserva?.OrigemRecurso?.Substring(1, 2), inDestinoRecursoRes = reserva?.DestinoRecurso, inNumProcessoRes = reserva?.Processo, inAutoProcFolhasRes = reserva?.AutorizadoSupraFolha, inCodEspecDespesaRes = reserva?.EspecificacaoDespesa, inEspecifDespesaRes = reserva?.DescEspecificacaoDespesa.Replace(";", "").Replace(";", ""), inAutoPorAssRes = reserva?.AutorizadoAssinatura, inAutoPorGrupoRes = reserva?.AutorizadoGrupo, inAutoPorOrgaoRes = reserva?.AutorizadoOrgao, inExamPorAssRes = reserva?.ExaminadoAssinatura, inExamPorGrupoRes = reserva?.ExaminadoGrupo, inExamPorOrgaoRes = reserva?.ExaminadoOrgao, inRespEmissaoAssRes = reserva?.ResponsavelAssinatura, inRespEmissGrupoRes = reserva?.ResponsavelGrupo, inRespEmissOrgaoRes = reserva?.ResponsavelOrgao, inIdentContratoANORes = reserva?.Contrato?.Substring(0, 2), inIdentContratoORGAORes = reserva?.Contrato?.Substring(2, 2), inIdentContratoNUMRes = reserva?.Contrato?.Substring(4, 5), inIdentContratoDCRes = reserva?.Contrato?.Substring(9, 1), inQuotaReserva_1 = inQuotaReserva1?.Length < 3 ? "0" + inQuotaReserva1 : inQuotaReserva1, inQuotaReserva_2 = inQuotaReserva2?.Length < 3 ? "0" + inQuotaReserva2 : inQuotaReserva2, inQuotaReserva_3 = inQuotaReserva3?.Length < 3 ? "0" + inQuotaReserva3 : inQuotaReserva3, inQuotaReserva_4 = inQuotaReserva4?.Length < 3 ? "0" + inQuotaReserva4 : inQuotaReserva4, inTotalReserva = inTotalReserva?.Length < 3 ? "0" + inTotalReserva : inTotalReserva, inImprimirRes = "A" }; return(reservaFiltersType); }
internal static DataTable PrepareDailyActivityScoreTable(DateTime startDate, DateTime endDate , List <EventTelemetrySummary> eventDataSummaries, List <ViewTelemetrySummary> viewDataSummaries, List <ExceptionInfo> errorData) { DataTable data = new DataTable(); data.Columns.Add("Date"); data.Columns.Add("Events", typeof(int)); data.Columns.Add("Views", typeof(int)); data.Columns.Add("Errors", typeof(int)); DateTime dateRecord = startDate; while (dateRecord.Date <= endDate.Date) //include empty days { DataRow row = data.NewRow(); row["Date"] = ToDashboardDateString(dateRecord); row["Events"] = eventDataSummaries?.Sum(s => s.TelemetryDetails?.Count(d => d.Timestamp.Date == dateRecord.Date)); row["Views"] = viewDataSummaries?.Sum(x => x.TelemetryDetails?.Count(d => d.Timestamp.Date == dateRecord.Date)); row["Errors"] = errorData?.Count(x => x.Timestamp.Date == dateRecord.Date); data.Rows.Add(row); dateRecord = dateRecord.AddDays(1); } return(data); }
public static ReadOnlySpan <byte> PackMessage(int messageType, ReadOnlySpan <byte> protobufMessage, List <ArgumentDescriptor> arguments) { var argumentLength = arguments?.Sum(argument => argument.Argument.Length + ProtobufHubProtocolConstants.ARGUMENT_HEADER_LENGTH); var totalLength = ProtobufHubProtocolConstants.TYPE_PLACEHOLDER_SIZE // messageType + ProtobufHubProtocolConstants.TOTAL_LENGTH_PLACEHOLDER_SIZE // totalLength + ProtobufHubProtocolConstants.PROTOBUF_MESSAGE_LENGTH_PLACEHOLDER_SIZE // ProtobufMessageLength + protobufMessage.Length + (argumentLength ?? 0); var byteArray = ArrayPool <byte> .Shared.Rent(totalLength); try { byteArray[0] = (byte)messageType; // Span share memory adress with byteArray var span = byteArray.AsSpan(ProtobufHubProtocolConstants.TYPE_PLACEHOLDER_SIZE); //var messageTotalLength = totalLength - ProtobufHubProtocolConstants.TYPE_AND_TOTAL_LENGTH_HEADER; //MemoryMarshal.Write(span, ref messageTotalLength); BinaryPrimitivesExtensions.WriteInt32(span, totalLength - ProtobufHubProtocolConstants.TYPE_AND_TOTAL_LENGTH_HEADER); span = byteArray.AsSpan(ProtobufHubProtocolConstants.TYPE_AND_TOTAL_LENGTH_HEADER); //var protobufMessageLength = protobufMessage.Length; //MemoryMarshal.Write(span, ref protobufMessageLength); BinaryPrimitivesExtensions.WriteInt32(span, protobufMessage.Length); span = byteArray.AsSpan(ProtobufHubProtocolConstants.MESSAGE_HEADER_LENGTH); protobufMessage.CopyTo(span); var currentLength = protobufMessage.Length + ProtobufHubProtocolConstants.MESSAGE_HEADER_LENGTH; for (var i = 0; i < arguments?.Count; i++) { span = byteArray.AsSpan(currentLength); //var argType = arguments[i].Type; //MemoryMarshal.Write(span, ref argType); BinaryPrimitivesExtensions.WriteInt32(span, arguments[i].Type); span = byteArray.AsSpan(currentLength + ProtobufHubProtocolConstants.ARG_TYPE_PLACEHOLDER_SIZE); //var argLength = arguments[i].Argument.Length; //MemoryMarshal.Write(span, ref argLength); BinaryPrimitivesExtensions.WriteInt32(span, arguments[i].Argument.Length); span = byteArray.AsSpan(currentLength + ProtobufHubProtocolConstants.ARGUMENT_HEADER_LENGTH); arguments[i].Argument.CopyTo(span); currentLength = currentLength + ProtobufHubProtocolConstants.ARGUMENT_HEADER_LENGTH + arguments[i].Argument.Length; } return(byteArray.AsSpan(0, totalLength)); } finally { ArrayPool <byte> .Shared.Return(byteArray); } }
public override void Draw(UISpriteBatch batch) { batch.GraphicsDevice.DepthStencilState = DepthStencilState.Default; batch.GraphicsDevice.BlendState = BlendState.NonPremultiplied; Camera.ProjectionOrigin = new Vector2(batch.GraphicsDevice.Viewport.Width, batch.GraphicsDevice.Viewport.Height) / 2; Scene.Draw(batch.GraphicsDevice); batch.DrawString(GameFacade.MainFont.GetNearest(8).Font, (Comp3D?.Sum(x => x.Mesh?.Geoms?.FirstOrDefault()?.Sum(y => y.Value.PrimCount) ?? 0) ?? 0) + " tris", new Vector2(10, 10), Color.Red); }
public override int GetHashCode() { return((int)(map.GetHashCode() + gameMode.GetHashCode() + fragLimit + timeLimit + timeElapsed + scoreBoard?.Sum(u => u.GetHashCode()) ?? 0)); }
public List <ValorPorComodo> ObterMelhorOpcaoValoresPorComodo(List <ValorPorComodo> v1, List <ValorPorComodo> v2) { var retorno = v1; if (retorno?.Sum(x => x.Recortes?.Count ?? 0) < v2?.Sum(x => x.Recortes?.Count ?? 0)) { retorno = v2; } return(retorno); }
/// <summary> /// Computes AnalysisXResultCell aggregated results /// </summary> /// <param name="lstAnalysis"> /// List of <see cref="AnalysisProcessingResultColumnValue"/> /// </param> /// <param name="aggregationType"> /// <see cref="AnalysisAggregationType"/> object /// </param> /// <param name="column"> /// <see cref="AnalysisColumn"/> object. /// </param> /// <returns> /// List of <see cref="AnalysisXResultCell"/> /// </returns> private static List <AnalysisXResultCell> GetAnalysisXResultCells( List <AnalysisProcessingResultColumnValue> lstAnalysis, AnalysisAggregationType aggregationType, AnalysisColumn column) { var xResultCells = new List <AnalysisXResultCell>(); var xCategoryValues = column.XCategoryValues; foreach (var xCategoryValue in xCategoryValues) { var result = 0.0; if (aggregationType.Sum) { result = lstAnalysis?.Sum(x => x.ResultForXCategoryValueKey(xCategoryValue.Key)) ?? result; } else if (aggregationType.Min) { if (lstAnalysis?.Any() == true) { result = lstAnalysis.Min(x => x.ResultForXCategoryValueKey(xCategoryValue.Key)); } } else if (aggregationType.Max) { result = lstAnalysis?.Max(x => x.ResultForXCategoryValueKey(xCategoryValue.Key)) ?? result; } else { var count = 0; var currentCount = 0; if (lstAnalysis?.Any() == true) { foreach (var colVal in lstAnalysis) { currentCount = colVal.CountForXCategoryValueKey(xCategoryValue.Key); if (currentCount > 0) { result += colVal.ResultForXCategoryValueKey(xCategoryValue.Key) * currentCount; count += currentCount; } } } result = count > 0 ? result / count : 0; } xResultCells.Add(new AnalysisXResultCell(result, column.ResultColumn.DisplayStringFromNumber(result))); } return(xResultCells); }
public OrderSummary GetOrderSummary(IEnumerable <MarketItem> items, List <Mineral> minerals, MineralList mineralList) { var itemList = items.ToList(); var perfectPurchasePrice = itemList.Sum(o => Math.Round(o.Pricing.CalculateBestTotal((int)Math.Ceiling(o.Qty)), 2)); var buyAllPurchasePrice = itemList.Sum(o => o.TotalPrice); var totalOreVolume = (decimal)itemList.Sum(o => o.Volume * o.Qty); var sourceStagingShippingCost = itemList.Sum(o => o.AverageShippingCost * (decimal)o.Qty); var mineralBuyAllPurchasePrice = minerals?.Sum(m => m.TotalPrice); var totalMineralVolume = minerals?.Sum(m => m.Volume * m.DesiredQty); var mineralValueRatio = (buyAllPurchasePrice + sourceStagingShippingCost) / mineralBuyAllPurchasePrice; if (minerals != null) { foreach (var mineral in minerals) { if (mineral.Qty == 0) { continue; } mineral.ComparisonTotal = Math.Round(mineral.TotalPrice * mineralValueRatio.Value, 2); mineral.ComparisonPrice = Math.Round(mineral.ComparisonTotal / (decimal)mineral.DesiredQty, 2); } } return(new OrderSummary { MarketItems = itemList, Minerals = minerals, MineralValueRatio = mineralValueRatio, TotalMineralVolume = totalMineralVolume, PurchaseCostBest = perfectPurchasePrice, PurchaseCost = buyAllPurchasePrice, TotalVolume = totalOreVolume, SourceStagingShippingCost = sourceStagingShippingCost, }); }
public IActionResult PriceControl() { long basketCount = 0; string session = HttpContext.Session.GetString("AddProducts"); List <CartProductViewModel> cart = new List <CartProductViewModel>(); if (session != null) { cart = JsonConvert.DeserializeObject <List <CartProductViewModel> >(session); } basketCount = cart?.Sum(item => item.Price * item.Quantity) ?? 0; return(Json(basketCount)); }
private void calculateSummary() { _totalOunces = _items?.Where(x => x.Type == "Beer").Sum(x => x.USOunces); _totalCost = _items?.Sum(x => x.Cost); _averageBoxRating = _totalOunces == 0 ? 0 : _items?.Where(x => x.Type == "Beer").Sum(x => x.USOunces * x.UntappdRating) / _totalOunces; _minimumBeerRating = _items?.Where(x => x.UntappdRating > 0).Min(x => x.UntappdRating); _totalUnique = _items?.Where(x => x.Type == "Beer").Select(x => x.UntappdId).Distinct().Count(); _qualifyingOunces = _items?.Where(x => x.Type == "Beer" && x.UntappdRating >= (_minBeerRating ?? -1)).Sum(x => x.USOunces); _qualifyingCost = _items?.Where(x => x.Type == "Beer").Sum(x => x.Cost); _qualifyingBoxRating = calculateQualifyingBoxRating(); _qualifyingBeerRating = calculateQualifyingBeerRating(); }
public override void Draw(UISpriteBatch batch) { batch.GraphicsDevice.DepthStencilState = DepthStencilState.Default; batch.GraphicsDevice.BlendState = BlendState.NonPremultiplied; Camera.ProjectionOrigin = new Vector2(batch.GraphicsDevice.Viewport.Width, batch.GraphicsDevice.Viewport.Height) / 2; Scene.Draw(batch.GraphicsDevice); var text = (Comp3D?.Sum(x => x.Mesh?.Geoms?.FirstOrDefault()?.Sum(y => y.Value.PrimCount) ?? 0) ?? 0) + " tris"; batch.End(); GameFacade.EdithVectorFont.Draw(batch.GraphicsDevice, text, new Vector2(10), Color.Black, Vector2.One * 0.6f, null); batch.Begin(); }
private void conditionalOperator_Click(object sender, EventArgs e) { List <Employee> employees1 = new List <Employee>(); employees1.Add(new Employee { Id = 1, FirstName = "Emp 1" }); employees1.Add(new Employee { Id = 2, LastName = "Emp 2" }); int?length1 = employees1?.Count; // if not null, get Count int length2 = employees1?.Count ?? 0; // if not null, get Count. If null, get 0 int empId = employees1?[0].Id ?? 0; // if not null, get Id property value of first index int idSum = employees1?.Sum(i => i.Id) ?? 0; // if not null, get sum of Id property. If null, get 0 }
public void Correction(double value) { var sum = Parents?.Sum(am => am.ActivationValue) ?? 0; if (sum == 0) { ActivationValue -= value; return; } foreach (var parent in Parents) { var res = CorrectionCalc(sum, parent.ActivationValue, value); parent.Correction(res); } }
public async Task <IActionResult> Post(List <IFormFile> files) { var size = files?.Sum(f => f.Length); if (files == null || files?.Count == 0) { return(BadRequest("No file selected to Upload!")); } if (size >= 10000000) { return(BadRequest("File size larger than allowed (> 10MB)!")); } var rabbitMQHost = Environment.GetEnvironmentVariable("RabbitMQHost"); var rabbitMQPort = int.Parse(Environment.GetEnvironmentVariable("RabbitMQPort")); var queueName = Environment.GetEnvironmentVariable("QueueName"); foreach (var file in files) { if (file.FileName.Substring(file.FileName.Length - 3, 3) != "csv") { ViewBag.Message = "SELECIONE APENAS ARQUIVOS CSV PARA ENVIO!"; return(View("Upload")); } if (file.Length > 0) { var filePath = $"/repository/{file.FileName}"; try { var stream = new FileStream(filePath, FileMode.Create); await file.CopyToAsync(stream); stream.Dispose(); } catch { throw; } this.RabbitMQProducer.SendMessage(rabbitMQHost, rabbitMQPort, queueName, filePath); } } return(Ok(new { count = files.Count, totalSize = size, files })); }
/// <summary> /// Расчет з/п для конкретного сотрудника. /// Расчитывает з.п подчиненных если определено должностью и сохраняет в БД /// </summary> /// <param name="month">месяц</param> /// <param name="year">год</param> /// <param name="id">id сотрудника</param> /// <returns>Возращает сумму з.п</returns> public async Task <float> CalculateAsyncById(int month, int year, int id) { float koeffemployees = 0, salaryOfEmploees = 0, payforEmployees = 0; List <sreport> sreport = new List <sreport>(); Employee employee = _employee.GetSingle(n => n.Id == id, n => n.Position, p => p.Position); var startPeriodDay = new DateTime(year, month, 1); var YearSpan = startPeriodDay.Year - employee.DateofRecruitment.Year; int stage = startPeriodDay.AddYears(YearSpan) <= employee.DateofRecruitment ? YearSpan : YearSpan - 1; if (startPeriodDay < employee.DateofRecruitment) { return(0); // Не работал на данный период } int LongevitProcent = (int)employee.Position.LongevityKoeff * stage; LongevitProcent = LongevitProcent >= employee.Position.MaxLongevityKoeff ?(int)employee.Position.MaxLongevityKoeff : LongevitProcent; if (employee.Position.IsChildrenSalary) { sreport = await GetAllemployeesAsync(employee, month, year); if (!employee.Position.IsAllChildrenSalary) { sreport = sreport.Where(n => n.Employee.ManagerId == id).ToList(); // Убираем данные не нужные для расчета } koeffemployees = (float)employee.Position.Koeff; } if (sreport.Count > 0) { salaryOfEmploees = (float)sreport?.Sum(n => n.SumOfSalary); payforEmployees = koeffemployees * salaryOfEmploees / 100; } float Summ = employee.Position.SalaryRate * (1 + LongevitProcent / 100) + payforEmployees; await AddAsync(new SalaryReport { EmployeeId = id, month = month, year = year, DateCreate = DateTime.Now, SumOfSalary = Summ, salaryOfEmploees = salaryOfEmploees }); await CommitAsync(); return(Summ); }
private bool _handleFinePaidEvent(FinePaidEvent @event) { bool update = false; foreach (FactionRecord record in criminalrecord.ToList()) { // If paid at 'Legal Facilities', fines are grouped by superpower bool match = @event.brokerpercentage == null ? record.faction == @event.faction : record.Allegiance.invariantName == @event.faction; if (@event.allfines || match) { // Get all fines incurred, excluding the discrepancy report // Note that all fines are assigned to the ship, not the commander List <FactionReport> reports = record.factionReports .Where(r => !r.bounty && r.crimeDef != Crime.None && r.crimeDef != Crime.Fine && r.shipId == @event.shipid) .ToList(); long total = reports?.Sum(r => r.amount) ?? 0; // Check for discrepancy in logged fines incurred if (total < @event.amount) { // Adjust the discrepancy report & remove when zeroed out FactionReport report = record.factionReports .FirstOrDefault(r => r.crimeDef == Crime.Fine); if (report != null) { report.amount -= Math.Min(@event.amount - total, report.amount); if (report.amount == 0) { reports.Add(report); } } } // Remove associated fines record.factionReports = record.factionReports.Except(reports).ToList(); // Adjust the total fines incurred amount record.fines -= Math.Min(@event.amount, record.fines); RemoveRecord(record); update = true; } } return(update); }
private static Procedure_AnulacaoReservaFiltersType GerarAnulacaoFiltersType(string chave, string senha, ReservaCancelamento cancelamento, List <IMes> mes) { var bim1 = new string[] { "01", "02", "03" }; var bim2 = new string[] { "04", "05", "06" }; var bim3 = new string[] { "07", "08", "09" }; var bim4 = new string[] { "10", "11", "12" }; Procedure_AnulacaoReservaFiltersType reforcoFiltersType = new Procedure_AnulacaoReservaFiltersType { inChave = senha, // inImpressora = inOperador = chave, inNumReserva = cancelamento?.Reserva.ToString(), inQuotaAnulacao_1 = mes?.Where(x => bim1.Contains(x.Descricao)).Sum(y => y.ValorMes).ToString(), inQuotaAnulacao_2 = mes?.Where(x => bim2.Contains(x.Descricao)).Sum(y => y.ValorMes).ToString(), inQuotaAnulacao_3 = mes?.Where(x => bim3.Contains(x.Descricao)).Sum(y => y.ValorMes).ToString(), inQuotaAnulacao_4 = mes?.Where(x => bim4.Contains(x.Descricao)).Sum(y => y.ValorMes).ToString(), inTotalAnulacao = mes?.Sum(x => x.ValorMes).ToString(), inAutoPorAssAnu = cancelamento?.AutorizadoAssinatura, inAutoPorGrupoAnu = cancelamento?.AutorizadoGrupo, inAutoPorOrgaoAnu = cancelamento?.AutorizadoOrgao, inAutoProcFolhasAnu = cancelamento?.AutorizadoSupraFolha, inDestinoRecursoAnu = cancelamento?.DestinoRecurso, inExamPorAssAnu = cancelamento?.ExaminadoAssinatura, inExamPorGrupoAnu = cancelamento?.ExaminadoGrupo, inExamPorOrgaoAnu = cancelamento?.ExaminadoOrgao, inNumProcessoAnu = cancelamento?.Processo, InOrigemRecursoAnu = cancelamento?.OrigemRecurso?.Substring(1, 2), inCodEspecDespesaAnu = cancelamento?.EspecificacaoDespesa, inEspecifiDespesaRef = cancelamento?.DescEspecificacaoDespesa.Replace(";", "").Replace(";", ""), inRespEmissGrupoAnu = cancelamento?.ResponsavelGrupo, inRespEmissaoAssAnu = cancelamento?.ResponsavelAssinatura, inRespEmissOrgaoAnu = cancelamento?.ResponsavelOrgao, inImprimirAnu = "A" }; return(reforcoFiltersType); }
/// <summary> /// This method is an implementation of the WooliesX trolleyTotal end point /// </summary> /// <param name="trolleyRequest"></param> /// <returns></returns> public async Task <decimal> CalculateTrolleyTotal(TrolleyRequest trolleyRequest) { var applicableSpecials = new List <Special>(); var trolleyProducts = trolleyRequest.Products; var trolleySpecials = trolleyRequest.Specials; var trolleyQuantities = trolleyRequest.Quantities; var products = (from p in trolleyProducts join q in trolleyQuantities on p.Name equals q.Name select new TrolleyProduct { Name = p.Name, Price = p.Price, Quantity = q.Quantity }).ToList(); if (trolleySpecials != null && trolleySpecials.Any()) { foreach (var special in trolleySpecials) { var totalPrice = (from tp in products join sp in special.Quantities on tp.Name equals sp.Name group new { tp, sp } by tp.Name into productQtyGroup select productQtyGroup.Sum(x => x.tp.Price * x.sp.Quantity)).Sum(); special.TotalBenefit = totalPrice - special.Total; } var result = GetApplicableSpecials(products?.ToDictionary(x => x.Name), trolleySpecials); if (result != null && result.Any()) { applicableSpecials.AddRange(result); } } return((applicableSpecials?.Sum(x => x.Total) ?? 0) + products.Sum(p => p.Quantity * p.Price)); }
public ReadOnlySpan <byte> PackMessage(int messageType, ReadOnlySpan <byte> protobufMessage, List <ArgumentDescriptor> arguments) { var argumentLength = arguments?.Sum(argument => argument.Argument.Length + ProtobufHubProtocolConstants.ARGUMENT_HEADER_LENGTH); var totalLength = 1 // messageType + 4 // totalLength + 4 // ProtobufMessageLength + protobufMessage.Length + (argumentLength ?? 0); var byteArray = ArrayPool <byte> .Shared.Rent(totalLength); try { byteArray[0] = (byte)messageType; BitConverter.GetBytes(totalLength - ProtobufHubProtocolConstants.TYPE_AND_TOTAL_LENGTH_HEADER).CopyTo(byteArray, 1); BitConverter.GetBytes(protobufMessage.Length).CopyTo(byteArray, 5); protobufMessage.ToArray().CopyTo(byteArray, ProtobufHubProtocolConstants.MESSAGE_HEADER_LENGTH); var currentLength = protobufMessage.Length + ProtobufHubProtocolConstants.MESSAGE_HEADER_LENGTH; for (var i = 0; i < arguments?.Count; i++) { BitConverter.GetBytes(arguments[i].Type).CopyTo(byteArray, currentLength); BitConverter.GetBytes(arguments[i].Argument.Length).CopyTo(byteArray, currentLength + ProtobufHubProtocolConstants.ARGUMENT_HEADER_LENGTH / 2); arguments[i].Argument.CopyTo(byteArray, currentLength + ProtobufHubProtocolConstants.ARGUMENT_HEADER_LENGTH); currentLength = currentLength + ProtobufHubProtocolConstants.ARGUMENT_HEADER_LENGTH + arguments[i].Argument.Length; } return(byteArray.AsSpan().Slice(0, totalLength)); } finally { ArrayPool <byte> .Shared.Return(byteArray); } }
public async Task <decimal> CalculateTrolleyTotal(Trolley trolley) { _eligibleSpecials = new List <Special>(); var products = (from p in trolley.Products join q in trolley.Quantities on p.Name equals q.Name select new Product { Name = p.Name, Price = p.Price, Quantity = q.Quantity }).ToList(); if (trolley.Specials?.Count() > 0) { foreach (var special in trolley.Specials) { special.FullTotal = CalculateFullTotal(special.Quantities, products); } ApplyBundeledSpecials(products, trolley); } var regularPriceProductTotal = products.Sum(p => p.Quantity * p.Price); var bundeledPriceProductTotal = _eligibleSpecials?.Sum(x => x.Total) ?? 0; return(regularPriceProductTotal + bundeledPriceProductTotal); }
public static IEnumerable <int> DeployFunnlling() { var totalRageCount = rageSpell.Sum(u => u.Count); Log.Info($"[{AllInOnePushDeploy.AttackName}] deploy funnelling troops on sides"); var QW = AllInOnePushDeploy.QWSettings == 1 && queen?.Count > 0 && healer?.Count >= AllInOnePushDeploy.HealerOnQWSettings ? true : false; if (QW) { Log.Info($"{AllInOnePushDeploy.AttackName} start queen walk"); foreach (var t in Deploy.AtPoint(queen, AllInOnePushDeploy.FirstFunnellingPoint)) { yield return(t); } yield return(400); foreach (var t in Deploy.AtPoint(healer, AllInOnePushDeploy.QWHealer, AllInOnePushDeploy.HealerOnQWSettings)) { yield return(t); } Deploy.WatchHeroes(new List <DeployElement> { queen }); if (AllInOnePushDeploy.RageOnQWSettings == 1) { var rageCount = rageSpell?.Sum(u => u.Count); if (rageCount > 0) { var unit = rageSpell.FirstOrDefault(); foreach (var t in Deploy.AtPoint(unit, AllInOnePushDeploy.QWRagePoint)) { yield return(t); } } } yield return(10000); if (bowler?.Count > 0) { bowlerFunnelCount = bowler.Count / 4; foreach (var t in Deploy.AtPoint(bowler, AllInOnePushDeploy.SecondFunnellingPoint, bowlerFunnelCount)) { yield return(t); } } if (witch?.Count > 4) { witchFunnelCount = witch.Count / 4; foreach (var t in Deploy.AtPoint(witch, AllInOnePushDeploy.SecondFunnellingPoint, witchFunnelCount)) { yield return(t); } } if (healer?.Count > 0) { foreach (var t in Deploy.AtPoint(healer, AllInOnePushDeploy.SecondFunnellingPoint, healer.Count)) { yield return(t); } } yield return(1000); if (AllInOnePushDeploy.RageFunnelling == 1 && totalRageCount >= 3) { foreach (var t in DeploySpell(rageSpell, AllInOnePushDeploy.SecondFunnellingRagePoint)) { yield return(t); } } if (wizard?.Count > 0) { foreach (var t in Deploy.AtPoint(wizard, AllInOnePushDeploy.SecondFunnellingPoint)) { yield return(t); } } yield return(5000); } else { if (bowler?.Count > 0 || witch?.Count > 0) { Log.Info($"{AllInOnePushDeploy.AttackName} start funnlling "); if (bowler?.Count > 0) { bowlerFunnelCount = bowler.Count / 4; foreach (var t in Deploy.AtPoint(bowler, AllInOnePushDeploy.FirstFunnellingPoint, bowlerFunnelCount)) { yield return(t); } } if (witch?.Count > 0) { witchFunnelCount = witch.Count > 4 ? witch.Count / 4 : witch.Count / 2; foreach (var t in Deploy.AtPoint(witch, AllInOnePushDeploy.FirstFunnellingPoint, witchFunnelCount)) { yield return(t); } } if (healer?.Count >= 2) { healerFunnlCount = healer.Count / 2; foreach (var t in Deploy.AtPoint(healer, AllInOnePushDeploy.FirstFunnellingPoint, healerFunnlCount)) { yield return(t); } } if (bowler?.Count > 0) { foreach (var t in Deploy.AtPoint(bowler, AllInOnePushDeploy.SecondFunnellingPoint, bowlerFunnelCount)) { yield return(t); } } if (witchFunnelCount > 0 && witch?.Count > 0) { foreach (var t in Deploy.AtPoint(witch, AllInOnePushDeploy.SecondFunnellingPoint, witchFunnelCount)) { yield return(t); } } if (healer?.Count > 0 && healerFunnlCount > 0) { foreach (var t in Deploy.AtPoint(healer, AllInOnePushDeploy.SecondFunnellingPoint, healerFunnlCount)) { yield return(t); } } if (AllInOnePushDeploy.RageFunnelling == 1 && totalRageCount >= 3) { foreach (var t in DeploySpell(rageSpell, AllInOnePushDeploy.QWRagePoint)) { yield return(t); } foreach (var t in DeploySpell(rageSpell, AllInOnePushDeploy.SecondFunnellingRagePoint)) { yield return(t); } } if (wizard?.Count > 0) { foreach (var t in Deploy.AtPoint(wizard, AllInOnePushDeploy.FirstFunnellingPoint)) { yield return(t); } foreach (var t in Deploy.AtPoint(wizard, AllInOnePushDeploy.SecondFunnellingPoint)) { yield return(t); } } yield return(new Random().Next(10000, 13000)); } else { if (wizard?.Count > 0) { var waves = wizard.Count > 12 ? 2 : 1; foreach (var t in DeployWizard(waves)) { yield return(t); } } } } }
public ParticipantResult CalculateParticipantsResults(LeaderboardParticipant participant, List <SummaryActivity> activites) { var result = activites?.Sum(x => (x.Distance ?? 0d) / 1000) ?? 0; return(new ParticipantResult(participant, result, string.Format("{0:0.##} km", result))); }
private string GetWorkNeeded() => _slimeHutches?.Sum(slimeHutch => slimeHutch.waterSpots.Count).ToString(CultureInfo.InvariantCulture);
public async Task <IEnumerable <DashboardDto> > GetDashboardData(int userId) { List <Inventory> items = new List <Inventory>(); List <ProductCategory> cats = new List <ProductCategory>(); var responseList = new List <DashboardDto>(); items = await _context.Inventories.Where(i => i.AppUserId == userId).ToListAsync(); cats = await _context.ProductCategories.ToListAsync(); //All gender and age range possibilities var response = new DashboardDto() { AppUserId = userId, Gender = "All", AgeRange = "All", AveragePrice = items?.Average(i => i?.ItemPrice), TotalCount = items?.Sum(i => i?.ItemCount), Categories = GetCategorySummary(items, cats) }; responseList.Add(response); //Boys 2-4 var itemsFiltered = items?.Where(i => i?.Gender == "Boys" && i?.AgeRange == "2 - 4"); response = new DashboardDto() { AppUserId = userId, Gender = "Boys", AgeRange = "2 - 4", AveragePrice = itemsFiltered?.Average(i => i?.ItemPrice), TotalCount = itemsFiltered?.Sum(i => i?.ItemCount), Categories = GetCategorySummary(itemsFiltered.ToList(), cats) }; responseList.Add(response); //Boys 5-9 itemsFiltered = items?.Where(i => i?.Gender == "Boys" && i?.AgeRange == "5 - 9"); response = new DashboardDto() { AppUserId = userId, Gender = "Boys", AgeRange = "5 - 9", AveragePrice = itemsFiltered?.Average(i => i?.ItemPrice), TotalCount = itemsFiltered?.Sum(i => i?.ItemCount), Categories = GetCategorySummary(itemsFiltered.ToList(), cats) }; responseList.Add(response); //Boys 10-14 itemsFiltered = items?.Where(i => i?.Gender == "Boys" && i?.AgeRange == "10 - 14"); response = new DashboardDto() { AppUserId = userId, Gender = "Boys", AgeRange = "10 - 14", AveragePrice = itemsFiltered?.Average(i => i?.ItemPrice), TotalCount = itemsFiltered?.Sum(i => i?.ItemCount), Categories = GetCategorySummary(itemsFiltered.ToList(), cats) }; responseList.Add(response); //Girls 2-4 itemsFiltered = items?.Where(i => i?.Gender == "Girls" && i?.AgeRange == "2 - 4"); response = new DashboardDto() { AppUserId = userId, Gender = "Girls", AgeRange = "2 - 4", AveragePrice = itemsFiltered?.Average(i => i?.ItemPrice), TotalCount = itemsFiltered?.Sum(i => i?.ItemCount), Categories = GetCategorySummary(itemsFiltered.ToList(), cats) }; responseList.Add(response); //Girls 5-9 itemsFiltered = items?.Where(i => i?.Gender == "Girls" && i?.AgeRange == "5 - 9"); response = new DashboardDto() { AppUserId = userId, Gender = "Girls", AgeRange = "5 - 9", AveragePrice = itemsFiltered?.Average(i => i?.ItemPrice), TotalCount = itemsFiltered?.Sum(i => i?.ItemCount), Categories = GetCategorySummary(itemsFiltered.ToList(), cats) }; responseList.Add(response); //Girls 10-14 itemsFiltered = items?.Where(i => i?.Gender == "Girls" && i?.AgeRange == "10 - 14"); response = new DashboardDto() { AppUserId = userId, Gender = "Girls", AgeRange = "10 - 14", AveragePrice = itemsFiltered?.Average(i => i?.ItemPrice), TotalCount = itemsFiltered?.Sum(i => i?.ItemCount), Categories = GetCategorySummary(itemsFiltered.ToList(), cats) }; responseList.Add(response); //Either 2-4 itemsFiltered = items?.Where(i => i?.Gender == "Either" && i?.AgeRange == "2 - 4"); response = new DashboardDto() { AppUserId = userId, Gender = "Either", AgeRange = "2 - 4", AveragePrice = itemsFiltered?.Average(i => i?.ItemPrice), TotalCount = itemsFiltered?.Sum(i => i?.ItemCount), Categories = GetCategorySummary(itemsFiltered.ToList(), cats) }; responseList.Add(response); //Either 5-9 itemsFiltered = items?.Where(i => i?.Gender == "Either" && i?.AgeRange == "5 - 9"); response = new DashboardDto() { AppUserId = userId, Gender = "Either", AgeRange = "5 - 9", AveragePrice = itemsFiltered?.Average(i => i?.ItemPrice), TotalCount = itemsFiltered?.Sum(i => i?.ItemCount), Categories = GetCategorySummary(itemsFiltered.ToList(), cats) }; responseList.Add(response); //Either 10-14 itemsFiltered = items?.Where(i => i?.Gender == "Either" && i?.AgeRange == "10 - 14"); response = new DashboardDto() { AppUserId = userId, Gender = "Either", AgeRange = "10 - 14", AveragePrice = itemsFiltered?.Average(i => i?.ItemPrice), TotalCount = itemsFiltered?.Sum(i => i?.ItemCount), Categories = GetCategorySummary(itemsFiltered.ToList(), cats) }; responseList.Add(response); return(responseList); }
public ValidationResult Validate(Element element, Dictionary <string, dynamic> viewModel, FormSchema baseForm) { if (element.Type != EElementType.MultipleFileUpload) { return new ValidationResult { IsValid = true } } ; var key = $"{element.Properties.QuestionId}{FileUploadConstants.SUFFIX}"; if (!viewModel.ContainsKey(key)) { return new ValidationResult { IsValid = true } } ; List <DocumentModel> documentModel = viewModel[key]; if (documentModel == null) { return new ValidationResult { IsValid = true } } ; var maxCombinedFileSize = element.Properties.MaxCombinedFileSize > 0 ? element.Properties.MaxCombinedFileSize * SystemConstants.OneMBInBinaryBytes : SystemConstants.DefaultMaxCombinedFileSize; var sessionGuid = _sessionHelper.GetSessionGuid(); var cachedAnswers = _distributedCache.GetString(sessionGuid); var convertedAnswers = cachedAnswers == null ? new FormAnswers { Pages = new List <PageAnswers>() } : JsonConvert.DeserializeObject <FormAnswers>(cachedAnswers); var path = viewModel.FirstOrDefault(_ => _.Key.Equals("Path")).Value; var pageAnswersString = convertedAnswers.Pages.FirstOrDefault(_ => _.PageSlug.Equals(path))?.Answers.FirstOrDefault(_ => _.QuestionId == key); var response = new List <FileUploadModel>(); if (pageAnswersString != null) { response = JsonConvert.DeserializeObject <List <FileUploadModel> >(pageAnswersString.Response.ToString()); } if (documentModel.Sum(_ => _.FileSize) + response?.Sum(_ => _.FileSize) < maxCombinedFileSize) { return new ValidationResult { IsValid = true } } ; return(new ValidationResult { IsValid = false, Message = $"The total size of all your added files must not be more than {maxCombinedFileSize.ToReadableMaxFileSize()}MB" }); } } }
public ParticipantResult CalculateParticipantsResults(LeaderboardParticipant participant, List <SummaryActivity> activities) { var result = activities?.Sum(x => x.TotalElevationGain ?? 0d) ?? 0; return(new ParticipantResult(participant, result, string.Format("{0:0.#} m", result))); }