protected override List<IIndividual> selection(List<IIndividual> individuals) { var size = _iconfig.selectionSize; var pressure = 0.9999999; var minimalFitness = individuals.Aggregate(Double.MaxValue, (acc, next) => ((acc > getIndividualFitness(next)) ? getIndividualFitness(next) : acc)); var totalFitness = individuals.Aggregate(0.0, (acc, next) => getIndividualFitness(next)-minimalFitness*pressure + acc); var step = totalFitness / size; var start = _rand.NextDouble()*step; var indOut = new List<IIndividual>(); var threshold = 0.0; foreach (var ind in individuals) // they don't have to be sorted { /* * | | | | | | | | | * ^ ^ ^ ^ <- uniformly spaced * first one randomly chosen from [0, totalFitness / size] * then skip by totalFitness / size * less elitist than Roulette which promotes the best individuals the most */ while (start < threshold + getIndividualFitness(ind) - minimalFitness * pressure) { indOut.Add(ind.duplicate()); start += step; } threshold += getIndividualFitness(ind) - minimalFitness * pressure; } return indOut; }
/// <summary> /// Gets the hero average damage to the opposing team. /// </summary> /// <param name="player">The player.</param> /// <param name="Enemies">The enemies.</param> /// <returns></returns> public static float GetHeroAvgDamage(AIHeroClient player, List<AIHeroClient> Enemies) { var totalEnemies = Enemies.Count(); if (totalEnemies == 0) { return -1; } var AADamage = Enemies.Aggregate(0, (current, s) => (int) (current + player.LSGetAutoAttackDamage(s) * 2)); var QDamage = Enemies.Aggregate(0, (current, s) => (int)(current + (player.GetSpell(SpellSlot.Q).IsReady() ? player.LSGetSpellDamage(s, SpellSlot.Q) : 0f))); var WDamage = Enemies.Aggregate(0, (current, s) => (int)(current + (player.GetSpell(SpellSlot.W).IsReady() ? player.LSGetSpellDamage(s, SpellSlot.W) : 0f))); var EDamage = Enemies.Aggregate(0, (current, s) => (int)(current + (player.GetSpell(SpellSlot.E).IsReady() ? player.LSGetSpellDamage(s, SpellSlot.E) : 0f))); var RDamage = Enemies.Aggregate(0, (current, s) => (int)(current + (player.GetSpell(SpellSlot.R).IsReady() ? player.LSGetSpellDamage(s, SpellSlot.R) : 0f))); var itemsDamage = 0f; foreach (var item in player.InventoryItems) { foreach (var hero in Enemies) { var itemID = item.Id; switch (itemID) { case ItemId.Bilgewater_Cutlass: itemsDamage += (float) player.GetItemDamage(hero, Damage.DamageItems.Bilgewater); break; case ItemId.Blade_of_the_Ruined_King: itemsDamage += (float) player.GetItemDamage(hero, Damage.DamageItems.Botrk); break; case ItemId.Hextech_Gunblade: itemsDamage += (float) player.GetItemDamage(hero, Damage.DamageItems.Hexgun); break; case ItemId.Frost_Queens_Claim: itemsDamage += (float) player.GetItemDamage(hero, Damage.DamageItems.FrostQueenClaim); break; case ItemId.Tiamat_Melee_Only: itemsDamage += player.IsMelee ? (float) player.GetItemDamage(hero, Damage.DamageItems.Tiamat) : 0f; break; case ItemId.Ravenous_Hydra_Melee_Only: itemsDamage += player.IsMelee ? (float) player.GetItemDamage(hero, Damage.DamageItems.Hydra) : 0f; break; case ItemId.Liandrys_Torment: itemsDamage += (float) player.GetItemDamage(hero, Damage.DamageItems.LiandrysTorment); break; } } } var totalDamage = AADamage + QDamage + WDamage + EDamage + RDamage + itemsDamage; return (float) totalDamage / totalEnemies; }
public static string Guess(List<char>secret, List<char> guess) { int index=0; string okLettOkPos= guess.Aggregate("",(x,y)=> x+=(secret[index++]==y?"p":"")); string okLettWrongPos= guess.Aggregate("",(x,y)=> x+=(Contains(secret,y)?"m":"")); string toReturn = okLettOkPos+okLettWrongPos; toReturn = toReturn.Substring(0,toReturn.Length-okLettOkPos.Length); return toReturn; }
/// <summary> /// Calculate Stock Price based on trades recorded in past 15 minutes /// </summary> /// <param name="stockSymbol"></param> /// <returns>Stock Price</returns> public double StockPrice(string stockSymbol) { List<Trade> validTrades = new List<Trade>(); validTrades.AddRange(Trades.Where(x => x.Stock.StockSymbol == stockSymbol && x.Timestamp > Trades.ElementAt(Trades.Count - 1).Timestamp.Subtract(new TimeSpan(0, 15, 0)))); if (validTrades.Count() <= 0) { Log.WarnFormat(Properties.Resources.SUPERSIMPLESTOCKS_ERR_003, stockSymbol); return 0; } return validTrades.Aggregate(0.0, (tot, x) => tot + (x.Price * x.Quantity)) / validTrades.Aggregate(0.0, (tot, x) => tot + x.Quantity); }
public GridRow(IEnumerable<IGridRenderable> renderables, Padding pad = null) { Renderables = renderables.ToList(); Pad = pad ?? new Padding(0, 0); Width = Renderables.Aggregate(0, (x, y) => y.Width); Height = Renderables.OrderBy(x => x.Height).First().Height; }
public static INode CloneNode(this INode node, List<int> path, INode newRoot, INode[] newRoots, ISelectOutput result) { path.Clear(); while (true) { var rootIndex = Array.IndexOf(result.Roots, node); if (rootIndex != -1) { newRoot = newRoots[rootIndex]; break; } var p = node.Parent; if (p == null) { break; } path.Add(p.IndexOfChild(node)); node = p; } if (newRoot == null) { throw new InvalidOperationException("Something strange: a root of selected nodes is not listed in root array."); } path.Reverse(); newRoot = path.Aggregate(newRoot, (current, cNum) => current.Children[cNum]); return newRoot; }
public string[] Find(int[] sortedSource) { var foundHoles = new string[0]; var counter = 0; for (var i = 0; i < sortedSource.Length; i++) { var result = new List<int>(); var tempStr = string.Empty; if (i >= sortedSource.Length - 1) continue; if (sortedSource[i + 1] - sortedSource[i] <= 1) continue; var holeSize = (sortedSource[i + 1] - sortedSource[i]) - 1; result.Add(sortedSource[i] + 1); if (holeSize > 1) { result.Add(sortedSource[i] + holeSize); } tempStr = result.Aggregate(tempStr, (current, t) => current + $"{t}-"); Array.Resize(ref foundHoles, foundHoles.Length + 1); foundHoles[counter] = tempStr.Substring(0, tempStr.Length - 1); counter++; } return foundHoles; }
public override void HandleCommand(IList<string> paramList, IrcUser user, bool isIngameCommand) { int i; // check if the params number 4, that the number/sides are integers, and that number and sides are both greater than 0 if (paramList.Count() == 3 && Int32.TryParse(paramList[1], out i) && Int32.TryParse(paramList[2], out i) && (Int32.Parse(paramList[1]) > 0) && (Int32.Parse(paramList[2]) > 0) && (Int32.Parse(paramList[1]) <= 4) && (Int32.Parse(paramList[2]) <= 100)) { var dice = Int32.Parse(paramList[1]); var sides = Int32.Parse(paramList[2]); var random = new Random(); var diceList = new List<int>(); for (var j = 0; j < dice; j++) { diceList.Add(random.Next(1, sides)); } var outputString = String.Format("Rolling a {0} sided die, {1} time{2}: {3}", sides, dice, (dice > 1) ? "s" : "", diceList.Aggregate("", (current, roll) => current + roll + " ").Trim()); Utils.SendChannel(outputString); } else { Utils.SendChannel("Usage: !dice <number 1-4 > <sides 1 - 100>"); } }
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { var rule = new ModelClientValidationRule() { ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()), ValidationType = "validname", }; var clientValidationRules = new List<string> { _onlyOneEntityValidator.GetClientValidationRules(metadata,context).First().ValidationType, _cannotBeNotApplicable.GetClientValidationRules(metadata,context).First().ValidationType, _cannotContainNumbers.GetClientValidationRules(metadata,context).First().ValidationType, }; var regexPatterns = new List<string> { _onlyOneEntityValidator.Pattern, _cannotBeNotApplicable.Pattern, _cannotContainNumbers.Pattern, }; var errorMessages = new List<string> { _onlyOneEntityValidator.FormatErrorMessage(metadata.GetDisplayName()), _cannotBeNotApplicable.FormatErrorMessage(metadata.GetDisplayName()), _cannotContainNumbers.FormatErrorMessage(metadata.GetDisplayName()) }; rule.ValidationParameters.Add("clientvalidationrules", clientValidationRules.Aggregate((i, j) => i + "," + j)); rule.ValidationParameters.Add("regexpatterns", regexPatterns.Aggregate((i, j) => i + "," + j)); rule.ValidationParameters.Add("errormessages", errorMessages.Aggregate((i, j) => i + "," + j)); yield return rule; }
public static List<int> GetAllPrimeFactors(this int number) { var factors = new List<int>(); var root = (int)Math.Sqrt(number); for (var j = 1; j <= root; j++) { if (number % j != 0) continue; if (j.IsPrime()) factors.Add(j); else if(j != number) factors.AddRange(j.GetAllPrimeFactors()); if ((number/j).IsPrime()) factors.Add(number/j); else if ((number / j) != number) factors.AddRange((number/j).GetAllPrimeFactors()); if (factors.Aggregate(1, (current, factor) => current*factor) == number) break; } return factors; }
public long Run () { var max = 20; var factors = new List <int> (); var products = new List <int> (); foreach (var n in Enumerable.Range (1, max)) { if (products.Contains (n)) continue; var newFactor = products .OrderByDescending (p => p) .Where (p => n % p == 0) .Select (p => n / p) .FirstOrDefault (); if (newFactor == 0) newFactor = n; products.AddRange (products.Select (p => newFactor * p).ToList ()); products.Add (newFactor); factors.Add (newFactor); } return factors.Aggregate ((a, b) => a * b); }
public Foo() { _numbers = new List<int>(); string s = _numbers[10].Format("{0}"); string s2 = _numbers.GetEnumerator().Current.Format("{0}"); string s3 = _numbers.Aggregate<int>(0, delegate(int accumulated, int item) { return accumulated + item; }).Format("{0}"); string s4 = _func(10).EncodeUriComponent(); Func<int, string> f2 = _func; f2(11).Trim(); Dictionary<string, int> d = new Dictionary<string, int>(); string s5 = jQuery.ExtendDictionary<string, int>(d, d)["abc"].Format("{0}"); int keys = d.Count; bool b = d.ContainsKey("abc"); d.Remove("abc"); foreach (KeyValuePair<string, int> de in d) { } jQuery.AjaxRequest<string>("http://example.com").Success(delegate(string html) { Script.Alert(html); }); string json = ""; Foo f = Json.ParseData<Foo>(json).Setup().Run().Cleanup(); string name = Document.GetElementById("nameTB").As<InputElement>().Value; }
public Sequence GetSequence(string sequence) { const string aminoAcidRegex = @"[" + AminoAcid.StandardAminoAcidCharacters + "]"; const string massRegex = @"\(\d+\.\d+\("; char[] parens = {'(', ')'}; if (!Regex.IsMatch(sequence, "(" + aminoAcidRegex + "|" + massRegex + ")+")) return null; var stdAaSet = StandardAminoAcidSet; var aaList = new List<AminoAcid>(); var matches = Regex.Matches(sequence, "(" + aminoAcidRegex + "|" + massRegex + ")"); AminoAcid aa = null; var mods = new List<Modification>(); foreach (Match match in matches) { var element = match.Value; if (element.Length == 0) continue; if (element.Length == 1 && char.IsLetter(element[0])) // amino acid { if (aa != null) { aa = mods.Aggregate(aa, (current, mod) => new ModifiedAminoAcid(current, mod)); aaList.Add(aa); mods.Clear(); } aa = stdAaSet.GetAminoAcid(element[0]); if (aa == null) throw new Exception("Unrecognized amino acid character: " + element[0]); // Console.WriteLine("{0} {1} {2}", aa.Residue, aa.Composition, aa.GetMass()); } else { element = element.Trim(parens); IList<Modification> modList; AminoAcid modAa; try { modList = Modifications[element].Item2; modAa = Modifications[element].Item1; } catch (KeyNotFoundException) { throw new Exception("Unrecognized modificaion mass: " + element); } // if (modList == null || modList.Count == 1) throw new Exception("Unrecognized modificaion mass: " + element); aa = modAa; mods.AddRange(modList); // Console.WriteLine("{0} {1} {2}", mod.Name, mod.Composition, mod.Composition.AveragineMass); } } if (aa != null) { aa = mods.Aggregate(aa, (current, mod) => new ModifiedAminoAcid(current, mod)); aaList.Add(aa); } return new Sequence(aaList); }
public bool Solve(out Dictionary<Tuple<int, int>, double> sol) { _basePlanValues = CalculateBasePlan(); _basePlan = _basePlanValues.Keys.ToList(); //Console.WriteLine("Base plan:\n{0}\n", _basePlan.Aggregate("", (acc, x) => String.Format("{0} ({1}, {2};)", acc, x.Item1, x.Item2))); for(int i =0; i < _iterationsCount; i++) { Console.WriteLine("Iteration #{0}\n", i); Console.WriteLine("Base plan:\n{0}\n", _basePlan.Aggregate("", (acc, x) => String.Format("{0} ({1}, {2};)", acc, x.Item1, x.Item2))); Step1CalculatePotencials(); Console.WriteLine("Potencials A:\n {0}\n", _aPotencials.Aggregate("", (a, x) => a + x + "; ")); Console.WriteLine("Potencials B:\n {0}\n", _bPotencials.Aggregate("", (a, x) => a + x + "; ")); Step2CalculateEstimations(); Console.WriteLine("Estimations:\n{0}\n", _estimations.ToString()); WriteCostMatrix(); if (Step3CheckForOptimum()) { sol = _basePlanValues; return true; } Step4GetPositiveEstimation(); double tet0; Tuple<int, int> tet0Point; Step5BuildCycle(out tet0, out tet0Point); Step6BuildNewBasePlanValues(tet0); Step7BuilNewBasePlan(tet0, tet0Point); } throw new Exception("iterations limit"); }
public static void ApplyImagesToEntities(List<EntityImageMap> mappings, IOrganizationService service) { foreach (var mapping in mappings) { if (mapping.ImageSize == 16) { mapping.Entity.IconSmallName = mapping.WebResourceName; } else { mapping.Entity.IconMediumName = mapping.WebResourceName; } var request = new UpdateEntityRequest { Entity = mapping.Entity }; service.Execute(request); } string parameter = mappings.Aggregate(string.Empty, (current, mapping) => current + ("<entity>" + mapping.Entity.LogicalName + "</entity>")); string parameterXml = string.Format("<importexportxml ><entities>{0}</entities></importexportxml>", parameter); var publishRequest = new PublishXmlRequest { ParameterXml = parameterXml }; service.Execute(publishRequest); }
public async Task<IEnumerable<Channel>> GetEventsForDateAsync(DateTime start, IEnumerable<string> channels = null) { var channelUri = string.Empty; var hackingList = new List<string>(channels); var needsHack = false; // HACK because the API does not return an JSON array when there is only one channel if (hackingList.Count == 1) { hackingList.Add("5"); // Get Info channel (small overhead in data) needsHack = true; } if (hackingList.Count > 1) channelUri = hackingList.Aggregate("&channels=", (current, channel) => current + (channel + ",")); var urlBuilder = new UriBuilder(EndpointUri) { Query = string.Format("start={0}&duration={1}{2}", start.ToString(App.DateFormat), MinutesInDay, channelUri) }; var jsonStream = await Client.GetStreamAsync(urlBuilder.Uri); var events = new List<Channel>(EventDataMapper.MapEvents(jsonStream)); if(needsHack) events.Remove(events.Last()); // TODO: Possible bug source :) return events; }
private void DisplayAvgLoanBase() { var calcUtil = new LoanCalcUtil( 10000 * decimal.Parse(txtTotalLoanBase.Text.Trim()), int.Parse(cbxYears.Text), 0.01M * decimal.Parse(txtYearInterestRate.Text.Trim()), PayLoanType.AvgLoanBase, rbtnQuarterly.Checked ? PayCycleType.PerQuarter : PayCycleType.PerMonth); Dictionary<int, decimal> interestsDic = new Dictionary<int, decimal>(); List<string> cyclePayList = new List<string>(); decimal cycleInterest = 0.0M; decimal cycleLoanBase = calcUtil.TotalLoanBase / calcUtil.Cycles; for (int cycle = 0; cycle < calcUtil.Cycles; cycle++) { cycleInterest = calcUtil.CalcInterestForAvgLoanBase(cycle); interestsDic.Add(cycle, cycleInterest); string cyclePay = string.Format("第 {0} {1}: 本金({2:F2}),利息({3:F2}),共({4:F2})元;{5}", cycle + 1, calcUtil.PayCycle == PayCycleType.PerMonth ? "月" : "季", cycleLoanBase, cycleInterest, cycleLoanBase + cycleInterest, Environment.NewLine); cyclePayList.Add(cyclePay); } var totalInterests = interestsDic.Aggregate(0.0M, (seed, kvp) => { return seed + kvp.Value; }); txtInterestsForLoanBase.Text = totalInterests.ToString("F2"); string showText = cyclePayList.Aggregate(string.Empty, (seed, cyclePay) => { return seed + cyclePay; }); rtxtCyclePays.Text = showText; }
public void Execute() { // // Emptyメソッドは、文字通り空のシーケンスを作成するメソッドである。 // Unionする際や、Aggregateする際の中間値として利用されることが多い。 // Output.WriteLine("COUNT = {0}", Enumerable.Empty<string>().Count()); // // 指定されたシーケンスから合計値が100を超えているシーケンスのみを抽出. // Aggregateのseed値として、空のシーケンスを渡すためにEnumerable.Emptyを // 使用している。 // var sequences = new List<IEnumerable<int>> { Enumerable.Range(1, 10), Enumerable.Range(30, 3), Enumerable.Range(50, 2), Enumerable.Range(200, 1) }; var query = sequences.Aggregate( Enumerable.Empty<int>(), (current, next) => next.Sum() > 100 ? current.Union(next) : current ); foreach (var item in query) { Output.WriteLine(item); } }
public static int GetProcessIdByWindowTitle(string appTitle) { var processes = Process.GetProcesses().ToList(); var ws = processes.Where(p => p.ToString().Contains("WORD")).ToList(); foreach (var process1 in ws) { List<string> sList = new List<string>(); foreach (ProcessModule module in process1.Modules) { sList.Add(module.FileName); } sList.Sort(); var txt = sList.Aggregate("", (a, b) => a + "\r\n" + b); } var process = processes.SingleOrDefault(p => p.MainWindowTitle.Equals(appTitle)); if (process != null) return process.Id; return -1; }
public string GetAllCultures() { var list=new List<string>{DictionaryAttribute.DefaultLanguage}; list.AddRange(CultureInfo.GetCultures(CultureTypes.AllCultures).Select(info => new CultureDescription(info).ToString())); string s = list.Aggregate("", (current, list1) => current + (list1 + ";")); return s.TrimEnd(';'); }
public static string ToString(List<string> result) { if (result.Count == 0) return ""; else return result.Aggregate((a, b) => a + b); }
/// <summary> /// Averages the specified vectors. /// </summary> /// <param Name="vectors">The vectors to average.</param> /// <returns>Average of the vectors</returns> public static Vector3 Average(List<Vector3> vectors) { Vector3 toReturn = vectors.Aggregate(Vector3.Zero, (current, vector) => current + vector); toReturn /= vectors.Count; return toReturn; }
public static List<long> GetAllPrimeFactors(this BigInteger number) { var factors = new List<long>(); var root = (long)Math.Sqrt(Convert.ToDouble(number.ToString())); for (long j = 1; j <= root; j++) { if (number % j != 0) continue; if (j.IsPrime()) factors.Add(j); else if (j != number) factors.AddRange(j.GetAllPrimeFactors()); if ((number / j).IsPrime()) factors.Add(Convert.ToInt64((number / j).ToString())); else if ((number / j) != number) factors.AddRange((number / j).GetAllPrimeFactors()); if (factors.Aggregate<long, long>(1, (current, factor) => current * factor) == number) break; } return factors; }
public void Validate() { IList<string> errorMessages = new List<string>(); foreach (var validator in Validators) { if (validator.Enable) { var isValidOptional = validator.Validate(); if(!isValidOptional) errorMessages.Add(validator.ErrorMessage); } else validator.IsValid = true; } if (IsOptional) { if (errorMessages.Count > 0) { _isValid = false; if (MessageBox.Show("Attenzione leggere i seguenti avvertimenti:" + Environment.NewLine + Environment.NewLine + errorMessages.Aggregate(string.Empty, (current, errorMessage) => current + (errorMessage + Environment.NewLine)) + Environment.NewLine + "Sei sicuro di voler continuare?", "Sfera", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.OK) _isValid = true; } else _isValid = true; } }
/// <summary> /// <param name="locations">A 2D map of locations on the surface of earth. </param> /// </summary> public void FillElevationData(ref LatLonAlt[,] locations) { CultureInfo ci = new CultureInfo("en-US"); List<string> loc = new List<string>(); for (int J = 0; J < locations.GetLength(0); J++) { for (int I = 0; I < locations.GetLength(1); I++) { loc.Add(String.Format(ci, "{0:0.0000},{1:0.0000}", locations[I, J].Latitude, locations[I, J].Longitude)); } } var url = String.Format("http://maps.googleapis.com/maps/api/elevation/xml?sensor=false&locations={0}", loc.Aggregate((i, j) => i + "|" + j)); Console.WriteLine("Fetching elevation data from maps.googleapis.com..."); XmlDocument elevationData = new XmlDocument(); elevationData.Load(url); XmlNodeList xmlNodeList = elevationData.SelectNodes("/ElevationResponse/result/elevation"); var di = 0; // A local counter int x = 0; // the I-index of the matrix int y = 0; // the J-index of the matrix. foreach (XmlNode xmlNode in xmlNodeList) { // Update locations directly as we're spinning through all XML nodes. locations[x, y].Altitude = double.Parse(xmlNode.InnerText, ci.NumberFormat); di++; x = di % locations.GetLength(0); if (x == 0) y++; } }
/// <summary> /// Calculate the GBCE All Share Index using the geometric mean of prices for all stocks /// </summary> /// <returns>GBCE All Share Index</returns> public double StocksGeometricMean() { List<Stock> validStocks = new List<Stock>(); validStocks.AddRange(Stocks.Where(x => StockPrice(x.StockSymbol) > 0)); return Math.Pow(validStocks.Aggregate(1.0, (tot, x) => tot * StockPrice(x.StockSymbol)), 1.0 / validStocks.Count()); }
public void JudgeOperate(Page page, int menuId, List<OperateEnum> operateTypes) { UserModel user = UserUtility.CurrentUser; try { AuthOperateBLL bll = new AuthOperateBLL(); ResultModel result = bll.JudgeOperate(user, menuId, operateTypes); if (result.ResultStatus != 0) { string oids = operateTypes.Aggregate(string.Empty, (current, operate) => current + (operate.ToString() + ",")); if (!string.IsNullOrEmpty(oids) && oids.IndexOf(',') > -1) oids = oids.Substring(0, oids.Length - 1); MenuBLL menuBLL = new MenuBLL(); result = menuBLL.Get(user, menuId); if (result.ResultStatus != 0) throw new Exception("获取菜单失败"); Menu menu = result.ReturnValue as Menu; if (menu != null) { string redirectUrl = string.Format("{0}/ErrorPage.aspx?t={1}&r={2}", DefaultValue.NfmtSiteName, string.Format("用户无{0}-{1}权限", menu.MenuName, oids), string.Format("{0}MainForm.aspx",NFMT.Common.DefaultValue.NfmtSiteName)); page.Response.Redirect(redirectUrl,false); } } } catch (Exception e) { log.ErrorFormat("用户{0},错误:{1}", user.EmpName, e.Message); page.Response.Redirect("/MainForm.aspx"); } }
public OpenFileResult OpenFile(string customFilter, bool multiselect) { List<string> baseFilters = new List<string>(); if (!string.IsNullOrEmpty(customFilter)) { baseFilters.Add(customFilter); } baseFilters.Add(Resources.Translations.FilterAllSupported); baseFilters.Add(Resources.Translations.FilterAllFiles); string delimiter = "|"; string filter = baseFilters.Aggregate((i, j) => i + delimiter + j); OpenFileDialog dialog = new OpenFileDialog(); dialog.Filter = filter; dialog.FilterIndex = 1; dialog.Multiselect = multiselect; List<OpenedFile> openedFiles = new List<OpenedFile>(); if (dialog.ShowDialog() == true) { string[] fileNames = dialog.FileNames; foreach (var filePath in fileNames) { string fileName = Path.GetFileName(filePath); Stream stream = File.OpenRead(filePath); openedFiles.Add(new OpenedFile(stream, fileName)); } } return new OpenFileResult(openedFiles); }
public ReplayStats(IReplay replayer) { _replayer = replayer; _vectors = replayer.Vectors.ToList(); TotalSegments = _vectors.Count(); StartTime = _vectors[0].Time; EndTime = _vectors[TotalSegments - 1].Time; TotalTime = EndTime - StartTime; Velocities = new List<double>(); Velocities.Add(0); for (var i = 1; i < TotalSegments; i++) { var distance = _vectors[i].Vector.magnitude; var time = (_vectors[i].Time - _vectors[i - 1].Time).TotalMilliseconds; if (time == 0) Velocities.Add(0); else Velocities.Add(distance / time); } var sortedVelocities = Velocities.OrderBy(x => x).ToList (); MaxVelocity = sortedVelocities.Last(); MinVelocity = sortedVelocities.First(); TotalDistance = _vectors.Aggregate(0f, (x, y) => y.Vector.magnitude); AverageVelocity = Velocities.Aggregate(0f, (x, y) => (float)(x + y)) / Velocities.Count; }
protected override object GetValue(int rowIndex) { if (string.IsNullOrEmpty(stringValue)) { if (OwningRow.Index < 0) { return string.Empty; } tableAdaptor = (MySqlTableAdaptor)OwningColumn.Tag; var poinedRows = new List<DataRow>(); if (((DataRowView)OwningRow.DataBoundItem).Row[ColumnIndex + 1] != DBNull.Value) { poinedRows = tableAdaptor.GetObjectByIDs(new List<decimal> { (decimal)((DataRowView)OwningRow.DataBoundItem).Row[ColumnIndex + 1] }); } // Advanced string result = poinedRows.Aggregate(string.Empty, (current, dr) => current + (", " + dr["NAME"])); if (result.Length > 2) { stringValue = result.Substring(2); } } return stringValue; }