internal static object GetJsonForAoutPayment(IEnumerable<Payment> payment, int page) { if (payment == null) { return string.Empty; } var result = new { total = payment.Count(), page, records = payment.Count(), rows = payment.OrderByDescending(c => c.PaymentDate).Select(x => new { id = x.Id, cell = new[] { x.PaymentDate.ToString("dd.MM.yyyy"), x.FromAccount.CardNumber.ToString(), x.ToAccount.Description, x.TotalAmount.ToString(), x.Currency.Abbreveature } }) }; return result; }
public ElementSetPoints( ISpatialDefinition spatial, IEnumerable<IIdentifiable> ids, IEnumerable<double> x, IEnumerable<double> y, IEnumerable<double> z = null, IEnumerable<double> m = null) : base(spatial, ids, ElementType.Point, z != null, m != null) { if (x.Count() != ElementCount) throw new Exception(string.Format("x.Count() {0} != {1}", x.Count(), ElementCount)); if (y.Count() != ElementCount) throw new Exception(string.Format("y.Count() {0} != {1}", y.Count(), ElementCount)); if (HasZ && (z == null || z.Count() != ElementCount)) throw new Exception(string.Format("z.Length = {0} != {1}", z == null ? "null" : z.Count().ToString(), ElementCount)); if (HasM && (m == null || m.Count() != ElementCount)) throw new Exception(string.Format("m.Length = {0} != {1}", m == null ? "null" : m.Count().ToString(), ElementCount)); X = x.ToArray(); Y = y.ToArray(); if (HasZ) Z = z.ToArray(); if (HasM) M = m.ToArray(); }
private static object _syncRoot = new object(); // Used for source file changes so they don't try to write to the same file at the same time. /// <summary> /// Parses a compiler config file and runs the configured compilers. /// </summary> /// <param name="configFile">The absolute or relative file path to compilerconfig.json</param> /// <param name="configs">Optional configuration items in the config file</param> /// <param name="force">Forces compilation of all config items.</param> /// <returns>A list of compiler results.</returns> public IEnumerable<CompilerResult> Process(string configFile, IEnumerable<Config> configs = null, bool force = false) { if (_processing.Contains(configFile)) return Enumerable.Empty<CompilerResult>(); _processing.Add(configFile); List<CompilerResult> list = new List<CompilerResult>(); try { FileInfo info = new FileInfo(configFile); configs = configs ?? ConfigHandler.GetConfigs(configFile); if (configs.Any()) OnConfigProcessed(configs.First(), 0, configs.Count()); foreach (Config config in configs) { if (force || config.CompilationRequired()) { var result = ProcessConfig(info.Directory.FullName, config); list.Add(result); OnConfigProcessed(config, list.Count, configs.Count()); } } } finally { if (_processing.Contains(configFile)) _processing.Remove(configFile); } return list; }
internal static object GetJsonForCards(IEnumerable<Card> cards, int page) { if (cards == null) { return string.Empty; } var result = new { total = cards.Count(), page, records = cards.Count(), rows = cards.Select(x => new { id = x.Id, cell = new[] { x.CardNumber, x.CardType.Name, x.ExpirationDate.ToString("dd.MM.yyyy"), x.Currency.Abbreveature, Math.Round(x.Balance, 3).ToString() } }) }; return result; }
/// <summary> /// Add AccountDictionaryRecordConditions to database /// </summary> /// <param name="instances">AccountDictionaryRecordCondition instance array</param> /// <param name="accountDictionaryRecord">AccountDictionaryRecord instance for instances</param> /// <param name="saveAfterInsert">Save database after insertion</param> /// <param name="waitUntilSaving">Wait until saving</param> public void AccountDictionaryRecordConditionAdd(IEnumerable<AccountDictionaryRecordCondition> instances, AccountDictionaryRecord accountDictionaryRecord, bool saveAfterInsert = true, bool waitUntilSaving = true) { try { if (instances == null) throw new ArgumentNullException("instances"); if (accountDictionaryRecord == null) throw new ArgumentNullException("accountDictionary"); instances = instances.Where(i => i != null).ToArray(); try { foreach (var i in instances) if (i.DictionaryRecord != accountDictionaryRecord) i.DictionaryRecord = accountDictionaryRecord; this.Context.AccountDictionaryRecordConditions.AddRange(instances); if (saveAfterInsert) this.SaveChanges(waitUntilSaving); } catch (Exception ex) { var e = new Exception(ex.Message, ex); for (int i = 0; i < instances.Count();i++) e.Data.Add(string.Format("instance_{0}", i), instances.ElementAt(i).ToString()); throw e; } } catch (Exception ex) { Helpers.Log.Add(ex, string.Format("Repository.AccountDictionaryRecordConditionAdd(instances=[{0}],saveAfterInsert={1},waitUntilSaving={2})", instances == null ? "NULL" : instances.Count().ToString(), saveAfterInsert, waitUntilSaving)); throw; } }
/// <summary> /// Add AccountSettingsImportDirectorys to database /// </summary> /// <param name="instances">AccountSettingsImportDirectory instance array</param> /// <param name="saveAfterInsert">Save database after insertion</param> /// <param name="waitUntilSaving">Wait until saving</param> public void AccountSettingsImportDirectoryAdd(IEnumerable<AccountSettingsImportDirectory> instances, AccountSettings settings, bool saveAfterInsert = true, bool waitUntilSaving = true) { try { if (instances == null) throw new ArgumentNullException("instances"); if (settings == null) throw new ArgumentNullException("settings"); instances = instances.Where(i => i != null).ToArray(); try { this.Context.AccountSettingsImportDirectories.AddRange(instances); if (saveAfterInsert) this.SaveChanges(waitUntilSaving); } catch (Exception ex) { var e = new Exception(ex.Message, ex); for (int i = 0; i < instances.Count();i++) e.Data.Add(string.Format("instance_{0}", i), instances.ElementAt(i).ToString()); throw e; } } catch (Exception ex) { Helpers.Log.Add(ex, string.Format("Repository.AccountSettingsImportDirectoryAdd(instances=[{0}],saveAfterInsert={1},waitUntilSaving={2})", instances == null ? "NULL" : instances.Count().ToString(), saveAfterInsert, waitUntilSaving)); throw; } }
public NodeManager(IEnumerable<WorkerNode> nodes) { IObservable<bool> allNodesRunningStatus=null; foreach (var node in nodes) { var nodeStatusAsBools = Observable.FromEventPattern<HealthStatusEventArgs>( h => node.NodeHealth += h, h => node.NodeHealth -= h) .Select(i => i.EventArgs.Status); var nodeStatusObs = Observable.Return(false) .Concat(nodeStatusAsBools) .DistinctUntilChanged(); if (allNodesRunningStatus == null) { allNodesRunningStatus = nodeStatusObs; continue; } allNodesRunningStatus = allNodesRunningStatus.Merge(nodeStatusObs); } NodesRunning = allNodesRunningStatus .ObserveOn(NewThreadScheduler.Default) // Observing on a single thread so that the count update is syncronized .Scan(nodes.Count(),(currentCount, newStatus) => newStatus ? currentCount + 1 : currentCount - 1) .DistinctUntilChanged() .Publish() .RefCount(); NodeCount = nodes.Count(); }
public IPagedList<User> GetServiceProvidersPage(int page, int itemsPerPage, IEnumerable<int> locations, IEnumerable<Guid> tags, string searchString) { IQueryable<User> users = _serviceHubEntities.Users .Include("Tags") .Include("Ratings") .Include("Locations") .Where(o => o.IsPublic); if (locations.Count() > 0) locations = _serviceHubEntities.GetLocationsHierarchy(string.Join(",", locations)).Select(o => o.Id); if (locations.Count() > 0 && tags.Count() > 0) users = users.Where(o => o.Locations.Any(i => locations.Contains(i.Id)) || o.Tags.Any(i => tags.Contains(i.Id))); else if (locations.Count() > 0) users = users.Where(o => o.Locations.Any(i => locations.Contains(i.Id))); else if (tags.Count() > 0) users = users.Where(o => o.Tags.Any(i => tags.Contains(i.Id))); if (!string.IsNullOrWhiteSpace(searchString)) { string searchStringUpperCase = searchString.ToUpper(); users = users.Where(o => o.Name.ToUpper().Contains(searchStringUpperCase)); } return users .OrderByDescending(o => o.Ratings.Average(i => i.Score)) .ToPagedList(page, itemsPerPage); }
public async void Play(IEnumerable<string> songPaths) { if(songPaths.Count() >= 1) { //Play 1st song Play(songPaths.First()); //After a small delay add other songs in playList to AIMP3s playlist if(songPaths.Count() > 1) { //Delay shouldn't halt thread await Task.Run(() => { //Alway wait 1s before adding new songs Task.Delay(1000).Wait(); //Make sure program is fired up properly before adding more songs for(int tries = 0; tries < 20; tries++) { Process[] found = Process.GetProcessesByName("AIMP3"); if(found.Length >= 1 && DateTime.Now - found[0].StartTime > TimeSpan.FromSeconds(5)) { Insert(songPaths.Skip(1)); break; } else { Task.Delay(2500).Wait(); } } }); } } }
/// <summary> /// BuildTeachersTable /// </summary> /// <param name="ws"></param> /// <param name="Teachers"></param> private static void BuildTeachersTable(ExcelWorksheet ws, IEnumerable<OfficeVisitsByTeacher> Teachers) { ws.Column(1).Width = 17.86; ws.Column(2).Width = 12.43; //Set Header titles ws.Cells[4, 1].Value = "Teachers"; ws.Cells[4, 1].Style.Font.Bold = true; ws.Cells[5, 1].Value = "Teacher Name"; ws.Cells[5, 1].Style.Border.BorderAround(ExcelBorderStyle.Thin); // ws.Cells[5, 1].AutoFilter = true; ws.Cells[5, 2].Value = "Office Visits"; ws.Cells[5, 2].Style.Border.BorderAround(ExcelBorderStyle.Thin); // ws.Cells[5, 2].AutoFilter = true; //Get Data for Teachers for (int i = 0; i < Teachers.Count(); i++) { ws.Cells[i + 6, 1].Value = Teachers.ElementAt(i).sent_by_contact_name; ws.Cells[i + 6, 1].Style.Border.BorderAround(ExcelBorderStyle.Thin); ws.Cells[i + 6, 2].Value = Teachers.ElementAt(i).total_visits; ws.Cells[i + 6, 2].Style.Border.BorderAround(ExcelBorderStyle.Thin); } //Set Header style using (ExcelRange rng = ws.Cells[4, 1, 5 + Teachers.Count(), 2]) { rng.Style.Border.BorderAround(ExcelBorderStyle.Medium); } }
public IEnumerable<StudyTask> Distribute(IEnumerable<User> users, IEnumerable<StudyTask> tasks) { var userList = users.ToList(); var sublists = new List<List<StudyTask>>(); var rangeSize = tasks.Count()/userList.Count(); var additionalItems = tasks.Count()%userList.Count(); var index = 0; while (index < tasks.Count()) { var currentRangeSize = rangeSize + (additionalItems > 0 ? 1 : 0); sublists.Add(tasks.ToList().GetRange(index, currentRangeSize)); index += currentRangeSize; additionalItems--; } var ui = 0; foreach (var sublist in sublists) { foreach (var task in sublist) { task.DataFields.ForEach(d => d.UserData.Clear()); task.Users.Add(userList[ui]); foreach (var dataField in task.DataFields) { dataField.UserData.Add(new UserData {UserId = userList[ui].ID}); } yield return task; } ui++; } }
public static DT.Run ToDto(DA.Run source, bool includeBinaryValues, IEnumerable<DT.ValueName> valueNames) { if (source == null) return null; var dto = new DT.Run { Id = source.Id, Algorithm = Convert.ToDto(source.Algorithm), Problem = Convert.ToDto(source.Problem), CreatedDate = source.CreatedDate, ClientId = source.ClientId, UserId = source.UserId }; dto.ParameterValues = source.Values.Where(x => x.ValueName.Category == DA.ValueNameCategory.Parameter && valueNames.Count(y => y.Name == x.ValueName.Name) > 0).Select(x => Convert.ToDto(x, includeBinaryValues)).ToArray(); dto.ResultValues = source.Values.Where(x => x.ValueName.Category == DA.ValueNameCategory.Result && valueNames.Count(y => y.Name == x.ValueName.Name) > 0).Select(x => Convert.ToDto(x, includeBinaryValues)).ToArray(); return dto; }
public static string DocumentFilenameWithIncrement(string originalFilename, IEnumerable<ClientDocument> documents) { var originalFilenameWithoutExtention = originalFilename.Substring(0, originalFilename.LastIndexOf(".")); var extension = originalFilename.Substring(originalFilename.LastIndexOf(".")); var filenameFormat = originalFilenameWithoutExtention + "{0}" + extension; var formattedFilename = ""; var filename = originalFilename; var duplicateFilename = false; var newFilenameCreated = false; int i = 1; if (documents.Count(d => d.Filename == filename) > 0) duplicateFilename = true; while (duplicateFilename && !newFilenameCreated) { formattedFilename = string.Format(filenameFormat, " (" + (i++) + ")"); if (documents.Count(d => d.Filename == formattedFilename) == 0) { filename = formattedFilename; newFilenameCreated = true; } } return filename; }
public static Position GetCentralPosition(IEnumerable<Position> geoCoordinates) { if (geoCoordinates.Count() == 1) { return geoCoordinates.Single (); } double x = 0; double y = 0; double z = 0; foreach (var geoCoordinate in geoCoordinates) { var latitude = geoCoordinate.Latitude * Math.PI / 180; var longitude = geoCoordinate.Longitude * Math.PI / 180; x += Math.Cos (latitude) * Math.Cos (longitude); y += Math.Cos (latitude) * Math.Sin (longitude); z += Math.Sin (latitude); } var total = geoCoordinates.Count(); x = x / total; y = y / total; z = z / total; var centralLongitude = Math.Atan2 (y, x); var centralSquareRoot = Math.Sqrt (x * x + y * y); var centralLatitude = Math.Atan2 (z, centralSquareRoot); return new Position ( centralLatitude * 180 / Math.PI, centralLongitude * 180 / Math.PI ); }
public static StatementSyntax BuildStatement(IEnumerable<IStatement> statements, IStatementBlock parent, WhitespaceKindLookup whitespaceLookup) { StatementSyntax statementBlock; var statementSyntaxList = statements .SelectMany(x => RDom.CSharp.GetSyntaxGroup(x)) .ToList(); var hasBlock = parent.HasBlock; if (hasBlock || statements.Count() > 1) { statementBlock = SyntaxFactory.Block(SyntaxFactory.List(statementSyntaxList)); statementBlock = BuildSyntaxHelpers.AttachWhitespace(statementBlock, parent.Whitespace2Set, whitespaceLookup); // Block tokens are held in parent } else if (statements.Count() == 1) { statementBlock = (StatementSyntax)statementSyntaxList.First(); //statementBlock = BuildSyntaxHelpers.AttachWhitespace(statementBlock, parent.Whitespace2Set, whitespaceLookup); } else { statementBlock = SyntaxFactory.EmptyStatement(); statementBlock = BuildSyntaxHelpers.AttachWhitespace(statementBlock, parent.Whitespace2Set, whitespaceLookup); } return statementBlock; }
static public bool GetPublishedFileDetails(IEnumerable<ulong> publishedFileIds, Action<bool, string> callback) { uint handle = HTTP.CreateHTTPRequest(HTTPMethod.POST, string.Format(m_requestFormat, "ISteamRemoteStorage", "GetPublishedFileDetails", 1)); if (!HTTP.SetHTTPRequestGetOrPostParameter(handle, "itemcount", publishedFileIds.Count().ToString())) { MySandboxGame.Log.WriteLine(string.Format("HTTP: failed to set parameter '{0}' = '{1}'", "itemcount", publishedFileIds.Count().ToString())); return false; } int i = 0; foreach(var id in publishedFileIds) { if (!HTTP.SetHTTPRequestGetOrPostParameter(handle, string.Format("publishedfileids[{0}]", i), id.ToString())) { MySandboxGame.Log.WriteLine(string.Format("HTTP: failed to set parameter '{0}' = '{1}'", string.Format("publishedfileids[{0}]", i), id.ToString())); return false; } ++i; } if (!HTTP.SendHTTPRequest(handle, onRequestCompleted)) { MySandboxGame.Log.WriteLine("HTTP: failed to send request"); return false; } m_callbacks[handle] = callback; return true; }
public void AddOrder(Order order, IEnumerable<BE.Ordered_Dish> orderedDish) { List<Ordered_Dish> orderedDishList = orderedDish as List<BE.Ordered_Dish>; dal_func.AddOrder(order); int i = 0; if (orderedDish == null || orderedDish.Count() == 0) { return; } try { for (; i < orderedDish.Count(); i++) { AddOrdered_Dish(orderedDishList[i]); } } catch (Exception ex) { dal_func.DeletOrder(order); for (int j =0; j < i; j++) { dal_func.RemoveOrderde_dish(orderedDishList[j]); } throw ex; } }
/// <summary> /// Adds the WaterPackets and returns them as the most advanced type. /// </summary> /// <param name="Waters"></param> /// <returns></returns> public static IWaterPacket Mix(IEnumerable<IWaterPacket> Waters) { if (Waters.Count() == 0) return null; else if (Waters.Count()==1) return Waters.First(); else { IWaterPacket[] warr = Waters.ToArray(); IWaterPacket Water1 = warr[0]; for (int i = 1; i < warr.Count(); i++) { if (warr[i].GetType().IsSubclassOf(Water1.GetType())) { warr[i].Add(Water1); Water1 = warr[i]; } else Water1.Add(warr[i]); } return Water1; } }
public static IAsyncResult ScrobbleAsync(IEnumerable<TrackScrobble> tracks, Action<IEnumerable<TrackScrobble>> callback) { if (tracks.Count() > 50) throw new ArgumentException("Last.fm supports a maximum of 50 tracks"); if (tracks.Count() == 0) return null; var parameters = new Dictionary<string, string>(); parameters.Add("method", "track.scrobble"); var i = 0; foreach (var trackScrobble in tracks) { var tp = trackScrobble.track.GetParametersDictionary(i); foreach (var p in tp) { parameters.Add(p.Key, p.Value); } parameters.Add("timestamp[" + i + "]", trackScrobble.timestamp.ToString()); i++; } return LfmServiceProxy.GetResponseAsync(parameters, (doc) => { if (callback != null) callback(tracks); var info = doc.Element("lfm").Element("scrobbles"); var acc = info.Attribute("accepted").Value; var rej = info.Attribute("ignored").Value; Logger.LogMessage(string.Format("Batch scrobble info: accepted {0} tracks, ignored {1} tracks", acc, rej)); }); }
public Graphlet1(string name, IEnumerable<int> includedChannels, Multigraph mg) { InitializeComponent(); this.mg = mg; this.DataContext = mg; this.gp = mg.gp; this.name.Content = name; this.Height = MainWindow.graphletSize; this.Width = this.Height * mg.aspect; StringBuilder tooltip = new StringBuilder(includedChannels.Count() > 1 ? name : ""); bool colon = true; foreach (int chan in includedChannels) { if (includedChannels.Count() > 1) tooltip.Append((colon ? ": " : ", ")); tooltip.Append(Multigraph.trimChannelName(mg.fis.ChannelNames(chan)) + "(" + (chan + 1).ToString("0") + ")"); colon = false; this.channels.Add(chan); } this.graphletName.Text = tooltip.ToString(); if (mg.typeAxis == AxisType.Pos) offset = MainWindow._baseSize; else if (mg.typeAxis == AxisType.PosNeg) { offset = MainWindow._baseSize / 2D; Canvas.SetBottom(xAxis, offset); } else { offset = 0D; Canvas.SetBottom(xAxis, MainWindow._baseSize); } }
public static void RenameFiles(IEnumerable<FileInfo> aFilesCollection, string aPrexif, string aSuffix) { if (aFilesCollection != null && (aFilesCollection.Count() > 0)) { var lNumber = 1; var lNumberCount = Math.Truncate(Math.Log10(aFilesCollection.Count())) + 1; var lInvalidChars = Path.GetInvalidFileNameChars(); foreach (var lFile in aFilesCollection) { if (!lFile.Exists) throw new FileNotFoundException("Soubor (" + lFile.FullName + ") neexistuje"); var lNewFileName = string.Format("{0}{1}{2}{3}{4}", aPrexif, "".AppendChars('0', ZeroCountPrefix(lNumber, (int)lNumberCount)), lNumber, aSuffix, Path.GetExtension(lFile.Name).ToLower() ); if (lNewFileName.IndexOfAny(lInvalidChars) > 0) throw new NotSupportedException("Byly použity nepodporované znaky pro název souboru. Soubor: \"" + lNewFileName + "\""); File.Move(lFile.FullName, lFile.DirectoryName + @"\" + lNewFileName); lNumber++; } } }
private void CreateInlineDiffs(IEnumerable<ILine> originals, IEnumerable<ILine> modifieds) { if (originals.Count() != modifieds.Count()) { originalLines.AddRange( originals.Select(x => new ModificationLine(new[] { new Span(x.Value, SpanKind.Deletion) })) ); modifiedLines.AddRange( modifieds.Select(x => new ModificationLine(new[] { new Span(x.Value, SpanKind.Addition) })) ); return; } var maxLines = Math.Max(originals.Count(), modifieds.Count()); for (var i = 0; i < maxLines; i++) { var originalLine = originals.ElementAtOrDefault(i); var modifiedLine = modifieds.ElementAtOrDefault(i); if (originalLine == null && modifiedLine == null) continue; if (originalLine != null && modifiedLine == null) originalLines.Add(new ModificationLine(new[] { new Span(originalLine.Value, SpanKind.Deletion) })); else if (originalLine == null) modifiedLines.Add(new ModificationLine(new[] { new Span(modifiedLine.Value, SpanKind.Addition) })); else { var originalToModifiedChanges = DiffInline(originalLine, modifiedLine); originalLines.Add(new ModificationLine(new[] { new Span(originalLine.Value, SpanKind.Equal) })); modifiedLines.Add(new ModificationLine(originalToModifiedChanges)); } } }
/// <summary> /// Permet de filtrer sur les parametres d'une fonction pour les fonctions surchargées /// </summary> /// <param name="methods"></param> /// <param name="parameters"></param> /// <returns></returns> private static MethodInfo FilterMethodByParams(IEnumerable<MethodInfo> methods, IEnumerable<object> parameters) { if (parameters != null) { var paramsNull = parameters.Where(p => p.Equals(null)); if (!paramsNull.Any()) { IEnumerable<Type> types = parameters.Select(param => param.GetType()); var methodsFiltered = methods.Where(m => m.GetParameters().Count() == parameters.Count()); if (methodsFiltered.Any()) { foreach (var methodInfo in methodsFiltered) { if (types.SequenceEqual(methodInfo.GetParameters().Select(p => p.ParameterType).ToList())) { return methodInfo; } } } } else { var methodsFiltered = methods.Where(m => m.GetParameters().Count() == parameters.Count()); if (methodsFiltered.Any()) { return methodsFiltered.First(); } } } return null; }
private WeatherResult GetAverageWeatherResult(IEnumerable<WeatherResult> results, TemperatureUnits tempUnit, WindUnits windUnit) { WeatherResult aver = new WeatherResult(); aver.TemperatureUnit = tempUnit; aver.WindUnit = windUnit; aver.Temperature = 0; aver.Wind = 0; foreach (var weatherTemp in results) { aver.Temperature += weatherTemp.TemperatureUnit != tempUnit ? weatherTemp.Temperature.To(tempUnit) : weatherTemp.Temperature; aver.Wind += weatherTemp.WindUnit != windUnit ? weatherTemp.Wind.To(windUnit) : weatherTemp.Wind; } aver.Temperature = (float)Math.Round( aver.Temperature / (float)results.Count(), 2); aver.Wind = (float)Math.Round(aver.Wind / (float)results.Count(),2); return aver; }
private static string createColumnParameterAssignments( IEnumerable<KeyValuePair<Column, StoredProcedureParameter>> columnsToParameters, string firstDelimiter, string delimiter, int indent) { StringBuilder stringBuilder = new StringBuilder(); string indentString = string.Empty; for (int i = 0; i < indent; i++) { indentString = string.Format("{0}{1}", indentString, "\t"); } int columnNameSize = 0; if (columnsToParameters.Count() > 1) { foreach (KeyValuePair<Column, StoredProcedureParameter> kv in columnsToParameters) { if (kv.Key.Name.Length > columnNameSize) { columnNameSize = kv.Key.Name.Length; } } } columnNameSize += 3; IEnumerator<KeyValuePair<Column, StoredProcedureParameter>> enumerator = columnsToParameters.GetEnumerator(); if (enumerator.MoveNext()) { KeyValuePair<Column, StoredProcedureParameter> current = enumerator.Current; string currentName = string.Format("[{0}]", current.Key.Name); stringBuilder = stringBuilder.AppendFormat("{0}{1}{2}= {3}{4}", firstDelimiter, currentName.PadRight(columnNameSize), columnsToParameters.Count() > 1 ? "\t" : " ", current.Value.Name, Environment.NewLine); } while (enumerator.MoveNext()) { KeyValuePair<Column, StoredProcedureParameter> current = enumerator.Current; string currentName = string.Format("[{0}]", current.Key.Name); stringBuilder = stringBuilder.AppendFormat("{0}{1}{2}{3}= {4}{5}", indentString, delimiter, currentName.PadRight(columnNameSize), columnsToParameters.Count() > 1 ? "\t" : " ", current.Value.Name, Environment.NewLine); } string str = stringBuilder.ToString(); if (str.LastIndexOf(Environment.NewLine) > 0) { str = str.Remove(str.LastIndexOf(Environment.NewLine)); } return str; }
public static string Write(IEnumerable<LibraryItem> items) { if (items.Count() > 0) { StringBuilder result = new StringBuilder(); result.Append("[playlist]\r\n"); result.Append("NumberOfEntries=" + items.Count() + "\r\n"); int entryIndex = 1; foreach (AudioStream entry in items) { result.Append("File" + entryIndex + "=" + entry.Path + "\r\n"); result.Append("Title" + entryIndex + "=" + entry.Label + "\r\n"); entryIndex += 1; } result.Append("Version=2\r\n"); return result.ToString(); } else { return null; } }
private async Task SelectLabels(IEnumerable<LabelModel> x) { //If nothing has changed, dont do anything... if (_originalLables != null && _originalLables.Count() == x.Count() && _originalLables.Intersect(x).Count() == x.Count()) { ChangePresentation(new MvxClosePresentationHint(this)); return; } if (SaveOnSelect) { try { IsSaving = true; var labels = x != null ? x.Select(y => y.Name).ToArray() : null; var updateReq = this.GetApplication().Client.Users[Username].Repositories[Repository].Issues[Id].UpdateLabels(labels); var newIssue = await this.GetApplication().Client.ExecuteAsync(updateReq); Messenger.Publish(new IssueEditMessage(this) { Issue = newIssue.Data }); } catch { DisplayAlert("Unable to save labels! Please try again."); } finally { IsSaving = false; } } else { Messenger.Publish(new SelectIssueLabelsMessage(this) { Labels = SelectedLabels.Items.ToArray() }); } ChangePresentation(new MvxClosePresentationHint(this)); }
public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context) { ValidateArguments(arguments, 2); var row = ArgToInt(arguments, 0); var col = ArgToInt(arguments, 1); ThrowExcelErrorValueExceptionIf(() => row < 0 && col < 0, eErrorType.Value); var referenceType = ExcelReferenceType.AbsoluteRowAndColumn; var worksheetSpec = string.Empty; if (arguments.Count() > 2) { var arg3 = ArgToInt(arguments, 2); ThrowExcelErrorValueExceptionIf(() => arg3 < 1 || arg3 > 4, eErrorType.Value); referenceType = (ExcelReferenceType)ArgToInt(arguments, 2); } if (arguments.Count() > 3) { var fourthArg = arguments.ElementAt(3).Value; if(fourthArg.GetType().Equals(typeof(bool)) && !(bool)fourthArg) { throw new InvalidOperationException("Excelformulaparser does not support the R1C1 format!"); } if (fourthArg.GetType().Equals(typeof(string))) { worksheetSpec = fourthArg.ToString() + "!"; } } var translator = new IndexToAddressTranslator(context.ExcelDataProvider, referenceType); return CreateResult(worksheetSpec + translator.ToAddress(col, row), DataType.ExcelAddress); }
public async Task<Result<UploadResults>> LoginAndSubmitArenaRuns(IEnumerable<Deck> runs, Action<double> setProgress = null) { Result<CookieContainer, UploadResults> result = await LogInToHearthArena(); CookieContainer cookieContainer = result.ResultData; if (result.Outcome == UploadResults.Success && cookieContainer != null) { Log.WriteLine(string.Format("Uploading {0} run(s)", runs.Count()), LogType.Info); int i = 1; int max = runs.Count(); foreach (Deck run in runs) { Result<UploadResults> uploadResult = await SubmitArenaRun(run, cookieContainer); if (uploadResult.Outcome != UploadResults.Success) { return uploadResult; } if (setProgress != null) setProgress((double)i++ / max); } Log.WriteLine("Upload successful", LogType.Info); return new Result<UploadResults>(UploadResults.Success, string.Empty); } return new Result<UploadResults>(result.Outcome, result.ErrorMessage); }
ProgressMonitorStatusMessage CreateProgressMessage (IEnumerable<ReinstallPackageAction> actions) { if (actions.Count () == 1) { return ProgressMonitorStatusMessageFactory.CreateRetargetingSinglePackageMessage (actions.First ().PackageId); } return ProgressMonitorStatusMessageFactory.CreateRetargetingPackagesInProjectMessage (actions.Count ()); }
private static void ItemsSourceExChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ItemsControl?control = d as ItemsControl; IEnumerable? arg = (IEnumerable?)e.NewValue; // ReSharper disable once PossibleMultipleEnumeration if (arg?.Count() > 0) { Application.Current.Dispatcher.InvokeAsync(() => (control ?? throw new Exception("sd3 443 ")).SetValue(ItemsSourceProperty, arg.GetPropertyRefValues <object>((string)control.GetValue(VariableProperty)).Cast <IEnumerable <object> >().SelectMany(_s => _s)), System.Windows.Threading.DispatcherPriority.Background, default);
private string GenerateSQLtext(IEnumerable <Screen> Screens, Module ModuleObject) { string fill; string[] s1 = new string[100]; string[] s2 = new string[100]; int i = 0; Queries queries = new Queries(); fill = queries.DB(ModuleObject.EnglishNameInSingle); foreach (var Screen in Screens) { ScreenType screenType = context.ScreenTypes.FirstOrDefault(s => s.ID == Screen.screenTypeID); if (screenType.Name.ToLower() == "create") { IEnumerable <ScreenComponent> ScreenComponents = context.ScreenComponent.Where(s => s.ScreenID == Screen.ID); //if(ScreenComponents.Count() != 0) //{ s1 = new string[ScreenComponents.Count()]; s2 = new string[ScreenComponents.Count()]; i = 0; foreach (var ScreenComponent in ScreenComponents) { FieldType inputType = context.FieldTypes.FirstOrDefault(s => s.ID == ScreenComponent.FieldTypeID); string name = inputType.Name; if (name == "button") { continue; } s1[i] = ScreenComponent.FieldNameEnglish; switch (name.ToLower()) { case "dropdown": name = "int"; break; case "number": name = "nvarchar(255)"; break; case "text": name = "nvarchar(255)"; break; case "email": name = "nvarchar(255)"; break; case "radibutton": name = "nvarchar(255)"; break; case "textarea": name = "nvarchar(255)"; break; case "file": name = "nvarchar(255)"; break; case "checkbox": name = "boolean"; break; case "date": name = "datetime"; break; default: name = ""; break; } s2[i] = name; i++; } fill += queries.CreateTable(Screen.ScreenName, s1, s2); //} } } return(fill); }
public static double CalculateConfidenceInterval95(IEnumerable <double> values) { double confidenceInterval95 = 1.96 * CalculateStandardDeviation(values) / Math.Sqrt((values.Count() - 1)); return(confidenceInterval95); }
public void GetValidationWarnings_MultipleCoverageLayers_ReturnsMessage() { // Setup var random = new Random(21); const double belowPhreaticLevelDeviation = 0.5; const int belowPhreaticLevelShift = 10; const double belowPhreaticLevelMeanBase = 15.0; var topCoverageLayer = new PipingSoilLayer(testSurfaceLineTopLevel) { IsAquifer = false, BelowPhreaticLevel = new LogNormalDistribution { Mean = (RoundedDouble)(belowPhreaticLevelMeanBase + belowPhreaticLevelShift + random.NextDouble()), StandardDeviation = (RoundedDouble)belowPhreaticLevelDeviation, Shift = (RoundedDouble)belowPhreaticLevelShift } }; var middleCoverageLayer = new PipingSoilLayer(8.5) { IsAquifer = false, BelowPhreaticLevel = new LogNormalDistribution { Mean = (RoundedDouble)(belowPhreaticLevelMeanBase + belowPhreaticLevelShift + random.NextDouble()), StandardDeviation = (RoundedDouble)belowPhreaticLevelDeviation, Shift = (RoundedDouble)belowPhreaticLevelShift } }; var bottomAquiferLayer = new PipingSoilLayer(5.0) { IsAquifer = true, Permeability = new VariationCoefficientLogNormalDistribution { Mean = (RoundedDouble)1, CoefficientOfVariation = (RoundedDouble)0.5 }, DiameterD70 = new VariationCoefficientLogNormalDistribution { Mean = (RoundedDouble)1e-4, CoefficientOfVariation = (RoundedDouble)0 } }; var profile = new PipingSoilProfile(string.Empty, 0.0, new[] { topCoverageLayer, middleCoverageLayer, bottomAquiferLayer }, SoilProfileType.SoilProfile1D); calculation.InputParameters.StochasticSoilProfile = new PipingStochasticSoilProfile(0.0, profile); // Call IEnumerable <string> messages = PipingCalculationValidationHelper.GetValidationWarnings(calculation.InputParameters); // Assert Assert.AreEqual(1, messages.Count()); const string expectedMessage = "Meerdere aaneengesloten deklagen gevonden. De grondeigenschappen worden bepaald door het nemen van een gewogen gemiddelde, mits de standaardafwijkingen en verschuivingen voor alle lagen gelijk zijn."; Assert.AreEqual(expectedMessage, messages.ElementAt(0)); }
public static List <ChangeRecord> FromDTO(this Member member, IEnumerable <PaymentDTO> list, string userName) { var changes = new List <ChangeRecord>(); if (list != null && list.Count() > 0) { var existingPayments = member.Payments.Where(x => list.Select(l => l.Id).Contains(x.Id)); var deletedPayments = member.Payments.Where(x => !list.Select(l => l.Id).Contains(x.Id)); var newPayments = list.Where(x => !member.Payments.Select(p => p.Id).Contains(x.Id)); foreach (var item in deletedPayments) { member.Payments.Remove(item); changes.Add(new ChangeRecord { Time = DateTimeOffset.Now, By = userName, Description = $"payment received on {item.ReceivedDate.Format()}, amount {item.AmountReceived.Format()} deleted" }); } foreach (var item in newPayments) { var np = new Payment { Member = member, //DueDate = item.DueDate, //AmountDue = item.AmountDue, SubscriptionYear = item.SubscriptionYear, ReceivedDate = item.ReceivedDate, AmountReceived = item.AmountReceived, Type = item.Type, IsPaid = item.IsPaid, }; foreach (var n in item.Notes) { var pn = new PaymentNote { Note = new Note { CreatedOn = n.CreatedOn.StripTimeAndZone() } }; n.NoteLines.ToList().ForEach(x => pn.Note.NoteLines.Add(new NoteLine { Index = x.Index, Line = x.Line })); np.PaymentNotes.Add(pn); } member.Payments.Add(np); changes.Add(new ChangeRecord { Time = DateTimeOffset.Now, By = userName, RecordForNewMember = true, Description = $"new payment added: Amount Received £{item.AmountReceived.Format()} for {item.SubscriptionYear}, received on {item.ReceivedDate.Format()}" }); } foreach (var item in existingPayments) { var dto = list.Single(x => x.Id == item.Id); changes.AddRange(item.FromDTO(dto, userName)); } } return(changes); }
/// <summary> /// 如果加载失败就生成 /// </summary> /// <param name="fullPath"></param> public void ProcessConfig(string fullPath) { List <InstrumentInfo> oldList = new List <InstrumentInfo>(InstrumentInfoList); LoadInstrumentInfoList(); // 得到要订阅的表,是否覆盖原表? List <InstrumentInfo> newList = Filter(InstrumentInfoList); InstrumentInfoList = newList; IEnumerable <InstrumentInfo> _have = newList.Intersect(oldList); // 对于已经订阅的,有可能合约最小变动价位变化,所以可能需要重新更新 foreach (var h in _have) { AddInstrument(h); } IEnumerable <InstrumentInfo> _old = oldList.Except(newList); Unsubscribe(_old); IEnumerable <InstrumentInfo> _new = newList.Except(oldList); int f = Subscribe(_new); Log.Info("取消订阅:{0},尝试订阅:{1},已经订阅:{2},订阅失败:{3}", _old.Count(), _new.Count(), _have.Count(), f); SaveAsInstrumentInfoList(); }
public void AddShipsToBoard(IEnumerable <Ship> ships, int maxWidth, int maxHeight) { for (int index = 1; index <= ships.Count(); index++) { bool result = false; while (result == false) { Random random = new Random(); int row = random.Next(0, 10); int column = random.Next(this.board.axis.Length); var location = new List <Square>(); var StartPoint = new Square() { Row = random.Next(1, 10), Column = this.board.axis[column], ShipIdentifier = index }; Ships[index - 1].Id = index; location.Add(StartPoint); bool isVertical = random.NextDouble() >= 0.5; for (int i = 1; i <= Ships[index - 1].Width - 1; i++) { if (isVertical) { location.Add(new Square() { Row = (StartPoint.Row + i), Column = StartPoint.Column, ShipIdentifier = i }); } else { location.Add(new Square() { Row = StartPoint.Row, Column = this.board.axis[(this.board.axis.IndexOf(StartPoint.Column) + i) > maxWidth ? 1 : (this.board.axis.IndexOf(StartPoint.Column) + i)], ShipIdentifier = i }); } } Boardhelper service = new Boardhelper(location, this.board.coordinates); if (service.IsValidLocation(Ships[index - 1].Width)) { service.AddToBoard(Ships[index - 1].Id); } else { continue; } result = true; } } }
public override SqlScalarExpression Visit(SqlFunctionCallScalarExpression sqlFunctionCallScalarExpression) { SqlScalarExpression rewrittenExpression; // If the function call is an aggregate just evaluate the aggregate first and return that if ( !sqlFunctionCallScalarExpression.IsUdf && Enum.TryParse(value: sqlFunctionCallScalarExpression.Name.Value, ignoreCase: true, result: out Aggregate aggregate)) { IReadOnlyList <SqlScalarExpression> arguments = sqlFunctionCallScalarExpression.Arguments; if (arguments.Count != 1) { throw new ArgumentException("Aggregates only accept one argument."); } IEnumerable <CosmosElement> results = this.dataSource .Select((element) => arguments[0].Accept( ScalarExpressionEvaluator.Singleton, element)); // If aggregates are pushed to the index, then we only get back defined results results = results.Where((result) => result != Undefined); CosmosElement aggregationResult; switch (aggregate) { case Aggregate.Min: case Aggregate.Max: if (results.Count() == 0) { aggregationResult = Undefined; } else if (results.Any(result => !Utils.IsPrimitive(result))) { aggregationResult = Undefined; } else { aggregationResult = results.First(); foreach (CosmosElement result in results) { // First compare the types int comparison = result.CompareTo(aggregationResult); if (aggregate == Aggregate.Min) { if (comparison < 0) { aggregationResult = result; } } else if (aggregate == Aggregate.Max) { if (comparison > 0) { aggregationResult = result; } } else { throw new InvalidOperationException("Should not get here"); } } } break; case Aggregate.Avg: case Aggregate.Sum: CosmosNumber sum = CosmosNumber64.Create(0); double count = 0; foreach (CosmosElement result in results) { if ((result is CosmosNumber resultAsNumber) && (sum != Undefined)) { sum = CosmosNumber64.Create(Number64.ToDouble(sum.Value) + Number64.ToDouble(resultAsNumber.Value)); count++; } else { sum = Undefined; } }
private MediaData CreateNewFile(InRiverImportResource inriverResource) { ResourceMetaField resourceFileId = inriverResource.MetaFields.FirstOrDefault(m => m.Id == "ResourceFileId"); if (string.IsNullOrEmpty(resourceFileId?.Values.FirstOrDefault()?.Data)) { _logger.Debug($"ResourceFileId is null, won't do stuff."); return(null); } _logger.Debug($"Attempting to create and import file from path: {inriverResource.Path}"); var fileInfo = new FileInfo(inriverResource.Path); IEnumerable <Type> mediaTypes = _contentMediaResolver.ListAllMatching(fileInfo.Extension).ToList(); _logger.Debug($"Found {mediaTypes.Count()} matching media types for extension {fileInfo.Extension}."); var contentTypeType = mediaTypes.FirstOrDefault(x => x.GetInterfaces().Contains(typeof(IInRiverResource))) ?? _contentMediaResolver.GetFirstMatching(fileInfo.Extension); if (contentTypeType == null) { _logger.Warning($"Can't find suitable content type when trying to import {inriverResource.Path}"); } else { _logger.Debug($"Chosen content type-type is {contentTypeType.Name}."); } var contentType = _contentTypeRepository.Load(contentTypeType); var newFile = _contentRepository.GetDefault <MediaData>(GetFolder(fileInfo, contentType), contentType.ID); newFile.Name = fileInfo.Name; newFile.ContentGuid = EpiserverEntryIdentifier.EntityIdToGuid(inriverResource.ResourceId); newFile.RouteSegment = GetUrlSlug(inriverResource); if (newFile is IInRiverResource resource) { resource.ResourceFileId = int.Parse(resourceFileId.Values.First().Data); resource.EntityId = inriverResource.ResourceId; try { resource.HandleMetaData(inriverResource.MetaFields); } catch (Exception exception) { _logger.Error($"Error when running HandleMetaData for resource {inriverResource.ResourceId} with contentType {contentType.Name}: {exception.Message}"); } } var blob = _blobFactory.CreateBlob(newFile.BinaryDataContainer, fileInfo.Extension); using (var stream = blob.OpenWrite()) { var fileStream = File.OpenRead(fileInfo.FullName); fileStream.CopyTo(stream); } newFile.BinaryData = blob; _logger.Debug($"New mediadata is ready to be saved: {newFile.Name}, from path {inriverResource.Path}"); var contentReference = _contentRepository.Save(newFile, SaveAction.Publish, AccessLevel.NoAccess); var mediaData = _contentRepository.Get <MediaData>(contentReference); _logger.Debug($"Saved file {fileInfo.Name} with Content ID {contentReference?.ID}."); return(mediaData); }
protected virtual long CalculateRequiredForCompressionStreamMemorySize(IEnumerable <InputStream> inputStreams, FileInfo inputFileInfo) { return(inputFileInfo.Length / inputStreams.Count()); }
protected virtual long CalculateRequiredInputFileMemorySize(IEnumerable <InputStream> inputStreams) { return(inputStreams.Count() * _compressionSettings.Reader.Settings.ChunkSize); }
public InputQueue Create(string inputFilePath, string outputFilePath, IEnumerable <InputStream> inputStreams, OutputQueue outputQueue) { if (inputStreams == null) { throw new ArgumentNullException("Input streams must be non-empty"); } if (outputQueue == null) { throw new ArgumentNullException("Output queue must be non-empty"); } if (string.IsNullOrEmpty(inputFilePath)) { throw new ArgumentException("Input file path must be non-empty"); } if (string.IsNullOrEmpty(outputFilePath)) { throw new ArgumentException("Output file path must be non-empty"); } InputQueue inputQueue = new InputQueue(); if (inputStreams.Count() == 1) { Stream rawOutputStream = File.Create(outputFilePath); OutputStream outputStream = new OutputStream(0, rawOutputStream); InputWorkItem workItem = new InputWorkItem( inputStreams.First(), outputStream, outputQueue, _compressionSettings ); inputQueue.Add(workItem); } else { FileInfo inputFileInfo = new FileInfo(inputFilePath); if (!inputFileInfo.Exists) { throw new ArgumentException("Input file does not exist"); } long availableMemoryStreamsCount = CalculateAvailableMemoryStreamsCount(inputStreams, inputFileInfo); int index = 0; foreach (InputStream inputStream in inputStreams) { Stream rawOutputStream = index < availableMemoryStreamsCount ? (Stream)(new MemoryStream()) : (Stream)(new TempFileStream()); OutputStream outputStream = new OutputStream(index++, rawOutputStream); InputWorkItem workItem = new InputWorkItem( inputStream, outputStream, outputQueue, _compressionSettings ); inputQueue.Add(workItem); } } return(inputQueue); }
[InlineData(new int[] { 2, 3, 5, 9 }, new int[] { 8, 10 }, new int[] { 2, 3, 5, 9, 8, 10 })] // Neither side is empty public void PossiblyEmptyInputs(IEnumerable <int> first, IEnumerable <int> second, IEnumerable <int> expected) { VerifyEqualsWorker(expected, first.Concat(second)); VerifyEqualsWorker(expected.Skip(first.Count()).Concat(expected.Take(first.Count())), second.Concat(first)); // Swap the inputs around }
public MoveDirection Move(MoveState state) { // Наша змея Snake mainSnake = state.Snakes.Single(x => x.Id == state.You); // Противники IEnumerable <Snake> enemies = state.Snakes.Where(x => x.Id != state.You); // информация о карте MapInformation.map = new int[state.Width, state.Height]; MapInformation.height = state.Height; MapInformation.width = state.Width; // Заполняем карту служебной имнформацией for (int i = 0; i < state.Width; ++i) { for (int j = 0; j < state.Height; ++j) { MapInformation.map[i, j] = -1; } } // заполняем карту препятствиями foreach (var enemy in enemies) { foreach (var cell in enemy.Coords) { MapInformation.map[cell.X, cell.Y] = MapInformation.barrier; } if (enemy.Coords.Length >= mainSnake.Coords.Length) { int x = 0; int y = 0; // Змеи находятся напротив друг друга вертикально if (Math.Abs(enemy.HeadPosition.X - mainSnake.HeadPosition.X) == 2 && (enemy.HeadPosition.Y - mainSnake.HeadPosition.Y) == 0) { if (enemy.HeadPosition.X > mainSnake.HeadPosition.X) { x = enemy.HeadPosition.X - 1; } else { x = enemy.HeadPosition.X + 1; } y = enemy.HeadPosition.Y; MapInformation.map[x, y] = MapInformation.barrier; } // Змеи находятся напротив друг друга горизонтально if ((enemy.HeadPosition.X - mainSnake.HeadPosition.X) == 0 && Math.Abs(enemy.HeadPosition.Y - mainSnake.HeadPosition.Y) == 2) { if (enemy.HeadPosition.Y > mainSnake.HeadPosition.Y) { y = enemy.HeadPosition.Y - 1; } else { y = enemy.HeadPosition.Y + 1; } x = enemy.HeadPosition.X; MapInformation.map[x, y] = MapInformation.barrier; } // Змеи находятся в друг от друга по диагонали, но в одном шаге if (Math.Abs(enemy.HeadPosition.X - mainSnake.HeadPosition.X) == 1 && Math.Abs(enemy.HeadPosition.Y - mainSnake.HeadPosition.Y) == 1) { MapInformation.map[mainSnake.HeadPosition.X, enemy.HeadPosition.Y] = MapInformation.barrier; MapInformation.map[enemy.HeadPosition.X, mainSnake.HeadPosition.Y] = MapInformation.barrier; } } } foreach (var cell in mainSnake.Coords) { MapInformation.map[cell.X, cell.Y] = MapInformation.barrier; } // Будем считать голову свободной ячейкой для удобства расчетов MapInformation.map[mainSnake.HeadPosition.X, mainSnake.HeadPosition.Y] = -1; // Находим путь до каждого фрукта List <List <Point> > paths = new List <List <Point> >(); foreach (var fruit in state.Food) { var path = FindPath(mainSnake.HeadPosition, fruit, MapInformation.map, state.Width, state.Height); // Если нашли путь, добавляем его в список if (path.Count > 0) { paths.Add(path); } } List <List <Point> > checkedPaths = new List <List <Point> >(); foreach (var path in paths) { Point fruit = path.Last(); bool dangerousPath = false; if (enemies.Count() > 0) { foreach (var enemy in enemies) { // Если вражеская змея в шаге от фрукта if ((Math.Abs(enemy.HeadPosition.X - fruit.X) == 1 && (enemy.HeadPosition.Y - fruit.Y) == 0) || ((enemy.HeadPosition.X - fruit.X) == 0 && Math.Abs(enemy.HeadPosition.Y - fruit.Y) == 1)) { // Если нам идти более чем 1 шаг или вражеская змея большем либо равна нашей, то исключаем этот фрукт из выборки if (enemy.Coords.Length >= mainSnake.Coords.Length) { dangerousPath = true; } } } if (!dangerousPath) { checkedPaths.Add(path); } } else { checkedPaths.Add(path); } } List <Point> pathToNearestFruit = checkedPaths.OrderBy(x => x.Count).FirstOrDefault(); // Если нашли путь до фрукта if (pathToNearestFruit != null) { // Берем первую ячейку пути, в которую нам и надо шагнуть var nextCell = pathToNearestFruit[0]; int translationX = mainSnake.HeadPosition.X - nextCell.X; int translationY = mainSnake.HeadPosition.Y - nextCell.Y; if (translationX == 0) { if (translationY > 0) { return(new MoveDirection { Move = "up", Taunt = "Moving up" }); } else { return(new MoveDirection { Move = "down", Taunt = "Moving down" }); } } if (translationX > 0) { return(new MoveDirection { Move = "left", Taunt = "Moving left" }); } else { return(new MoveDirection { Move = "right", Taunt = "Moving right" }); } } // Если не смогли найти путь до фрукта, то тянем время с помощью движения в сторону самой удаленной доступной ячейки с помощью пути найденного поиском в глубину else { DFSBehavior dfs = new DFSBehavior(); return(dfs.Move(mainSnake.HeadPosition)); } }
public static double CalculateStandardDeviation(IEnumerable <double> values) { double average = values.Average(); double sumOfSquaresOfDifferences = values.Select(val => (val - average) * (val - average)).Sum(); double standardDeviation = Math.Sqrt(sumOfSquaresOfDifferences / (values.Count() - 1)); return(standardDeviation); }
.ToDictionary(pair => pair.letter, pair => dictionary.ElementAt(dictionary.Count() - pair.index - 1));
public static IEnumerable<T> SkipLast<T> (this IEnumerable<T> source, int count) { return source.Take (source.Count () - count); }
public ActionResult Datatable(PaypalApiRequest request) { #region 自定义动作 if (!string.IsNullOrEmpty(request.customActionType)) { string[] id_Array = Request.Params.GetValues("id[]"); List <int> ids = new List <int>(); foreach (string i in id_Array) { ids.Add(int.Parse(i)); } switch (request.customActionType) { case "group_action": switch (request.customActionName) { case "delete": this.ImsService.DeletePaypalApi(ids); break; } break; case "delete": this.ImsService.DeletePaypalApi(ids); break; } } #endregion var allPaypalApi = this.ImsService.GetPaypalApiList(null); IEnumerable <PaypalApi> filterPaypalApi = allPaypalApi; #region 搜索 //if (!string.IsNullOrEmpty(request.search)) //{ // var isNameSearchable = Convert.ToBoolean(Request["columns[1][searchable]"]); //} //else if (request.action == "filter") //{ // var NameFilter = Convert.ToString(Request["name"]).Trim().ToLower(); // var SkuFilter = Convert.ToString(Request["sku"]).Trim().ToLower(); // var PackingWeightFilter = Convert.ToString(Request["packingweight"]).Trim().ToLower(); // var isNameSearchable = Convert.ToBoolean(Request["columns[1][searchable]"].ToString()); // if (isNameSearchable) // { // filterProduct = filterProduct.Where(c => c.Name.ToLower().Contains(NameFilter)); // } // var isSkuSearchable = Convert.ToBoolean(Request["columns[2][searchable]"].ToString()); // if (isSkuSearchable) // { // filterProduct = filterProduct.Where(c => c.Sku.ToLower().Contains(SkuFilter)); // } // var isPackingWeightSearchable = Convert.ToBoolean(Request["columns[3][searchable]"].ToString()); // if (isPackingWeightSearchable && !string.IsNullOrEmpty(PackingWeightFilter)) // { // filterProduct = filterProduct.Where(c => c.PackWeight == PackingWeightFilter.ToInt()); // } //} //else if (request.action == "filter_cancel") //{ // filterProduct = allProduct; //} //else //{ // filterProduct = allProduct; //} #endregion #region 排序 var isPPAccountSortable = Convert.ToBoolean(Request["columns[1][orderable]"]); var isApiUserNameSortable = Convert.ToBoolean(Request["columns[2][orderable]"]); var isIsActiveSortable = Convert.ToBoolean(Request["columns[3][orderable]"]); var sortColumnIndex = Convert.ToInt32(Request["order[0][column]"]); Func <PaypalApi, string> orderingFunction = (c => sortColumnIndex == 1 && isPPAccountSortable ?c.PPAccount : sortColumnIndex == 2 && isApiUserNameSortable ? c.ApiUserName : sortColumnIndex == 3 && isIsActiveSortable?c.IsActive.ToString(): ""); var sortDirection = Request["order[0][dir]"]; // asc or desc if (sortDirection == "asc") { filterPaypalApi = filterPaypalApi.OrderBy(orderingFunction); } if (sortDirection == "desc") { filterPaypalApi = filterPaypalApi.OrderByDescending(orderingFunction); } #endregion var displayedPaypalApi = filterPaypalApi.Skip(request.start).Take(request.length); var result = from c in displayedPaypalApi select new[] { Convert.ToString(c.ID) , c.PPAccount //c.OrderTime.ToCnDataString() , c.ApiUserName //c.TransactionID , c.IsActive.ToString() , Convert.ToString(c.ID) }; return(Json(new { draw = request.draw, //param.sEcho, recordsTotal = allPaypalApi.Count(), //alltransactions.Count(), recordsFiltered = filterPaypalApi.Count(), data = result }, JsonRequestBehavior.AllowGet)); }
public void AssembliesTest() { Assert.AreEqual(1, assembliesWithoutPreprocessing.Count(), "Wrong number of assemblies"); }
public int Part1() { return entries.Count(entry => entry.Validate()); }
protected bool IsSingleSegmentWithTypeSpecification(IEnumerable <string> segments) { return(segments.Count() == 2 && SegmentsIncludeTypeSpecification(segments)); }
public override nint RowsInSection(UITableView tableview, nint section) { return(datasource.Count()); }
public bool NameMatchesAny(IEnumerable <string> tags) { return(0 == tags.Count() || default != tags.FirstOrDefault(name => name.Equals(Name, StringComparison.CurrentCultureIgnoreCase))); }
public static bool IsNotNullOrEmpty <TSource>(this IEnumerable <TSource> source) where TSource : class { return(source == null ? false : source.Count <TSource>() > 0); }
public override CompletionSet GetCompletions(IGlyphService glyphService) { var start1 = _stopwatch.ElapsedMilliseconds; IEnumerable <CompletionResult> members = null; IEnumerable <CompletionResult> replMembers = null; var interactiveWindow = _snapshot.TextBuffer.GetInteractiveWindow(); var pyReplEval = interactiveWindow?.Evaluator as IPythonInteractiveIntellisense; var analysis = GetAnalysisEntry(); string text; SnapshotSpan statementRange; if (!GetPrecedingExpression(out text, out statementRange)) { return(null); } else if (string.IsNullOrEmpty(text)) { if (analysis != null) { var analyzer = analysis.Analyzer; lock (analyzer) { var location = VsProjectAnalyzer.TranslateIndex( statementRange.Start.Position, statementRange.Snapshot, analysis ); var parameters = Enumerable.Empty <CompletionResult>(); var sigs = analyzer.WaitForRequest(analyzer.GetSignaturesAsync(analysis, View, _snapshot, Span), "GetCompletions.GetSignatures"); if (sigs != null && sigs.Signatures.Any()) { parameters = sigs.Signatures .SelectMany(s => s.Parameters) .Select(p => p.Name) .Distinct() .Select(n => new CompletionResult(n, PythonMemberType.Field)); } members = analyzer.WaitForRequest(analyzer.GetAllAvailableMembersAsync(analysis, location, _options.MemberOptions), "GetCompletions.GetAllAvailableMembers") .MaybeEnumerate() .Union(parameters, CompletionComparer.MemberEquality); } if (pyReplEval == null) { var expansions = analyzer.WaitForRequest(EditorServices.Python?.GetExpansionCompletionsAsync(), "GetCompletions.GetExpansionCompletions"); if (expansions != null) { // Expansions should come first, so that they replace our keyword // completions with the more detailed snippets. if (members != null) { members = expansions.Union(members, CompletionComparer.MemberEquality); } else { members = expansions; } } } } if (pyReplEval != null) { replMembers = pyReplEval.GetMemberNames(string.Empty); } } else { var analyzer = analysis?.Analyzer; Task <IEnumerable <CompletionResult> > analyzerTask = null; if (analyzer != null && (pyReplEval == null || !pyReplEval.LiveCompletionsOnly)) { lock (analyzer) { var location = VsProjectAnalyzer.TranslateIndex( statementRange.Start.Position, statementRange.Snapshot, analysis ); // Start the task and wait for it below - this allows a bit more time // when there is a REPL attached, so we are more likely to get results. analyzerTask = analyzer.GetMembersAsync(analysis, text, location, _options.MemberOptions); } } if (pyReplEval != null && pyReplEval.Analyzer.ShouldEvaluateForCompletion(text)) { replMembers = pyReplEval.GetMemberNames(text); } if (analyzerTask != null) { members = analyzer.WaitForRequest(analyzerTask, "GetCompletions.GetMembers"); } } if (replMembers != null) { if (members != null) { members = members.Union(replMembers, CompletionComparer.MemberEquality); } else { members = replMembers; } } var end = _stopwatch.ElapsedMilliseconds; if (/*Logging &&*/ (end - start1) > TooMuchTime) { if (members != null) { var memberArray = members.ToArray(); members = memberArray; Trace.WriteLine(String.Format("{0} lookup time {1} for {2} members", this, end - start1, members.Count())); } else { Trace.WriteLine(String.Format("{0} lookup time {1} for zero members", this, end - start1)); } } if (members == null) { // The expression is invalid so we shouldn't provide // a completion set at all. return(null); } var start = _stopwatch.ElapsedMilliseconds; var result = new FuzzyCompletionSet( "Python", "Python", Span, members.Select(m => PythonCompletion(glyphService, m)), _options, CompletionComparer.UnderscoresLast, matchInsertionText: true ); end = _stopwatch.ElapsedMilliseconds; if (/*Logging &&*/ (end - start1) > TooMuchTime) { Trace.WriteLine(String.Format("{0} completion set time {1} total time {2}", this, end - start, end - start1)); } return(result); }
public string GetGroupDescription(IEnumerable <DiagnosticResult> results) { int count = results.Count(); return($"{count} torn {RegistrationsPlural(count)}."); }
private string RandomTzName() { return(_tzNames.ElementAt(_random.Next(0, _tzNames.Count()))); }
/// <summary> /// Checks each of the actual Diagnostics found and compares them with the corresponding DiagnosticResult in the array of expected results. /// Diagnostics are considered equal only if the DiagnosticResultLocation, Id, Severity, and Message of the DiagnosticResult match the actual diagnostic. /// </summary> /// <param name="actualResults">The Diagnostics found by the compiler after running the analyzer on the source code</param> /// <param name="analyzer">The analyzer that was being run on the sources</param> /// <param name="expectedResults">Diagnostic Results that should have appeared in the code</param> private static void VerifyDiagnosticResults(IEnumerable <Diagnostic> actualResults, DiagnosticAnalyzer analyzer, params DiagnosticResult[] expectedResults) { int expectedCount = expectedResults.Count(); int actualCount = actualResults.Count(); if (expectedCount != actualCount) { string diagnosticsOutput = actualResults.Any() ? FormatDiagnostics(analyzer, actualResults.ToArray()) : " NONE."; Assert.IsTrue(false, string.Format("Mismatch between number of diagnostics returned, expected \"{0}\" actual \"{1}\"\r\n\r\nDiagnostics:\r\n{2}\r\n", expectedCount, actualCount, diagnosticsOutput)); } for (int i = 0; i < expectedResults.Length; i++) { var actual = actualResults.ElementAt(i); var expected = expectedResults[i]; if (expected.Line == -1 && expected.Column == -1) { if (actual.Location != Location.None) { Assert.IsTrue(false, string.Format("Expected:\nA project diagnostic with No location\nActual:\n{0}", FormatDiagnostics(analyzer, actual))); } } else { VerifyDiagnosticLocation(analyzer, actual, actual.Location, expected.Locations.First()); var additionalLocations = actual.AdditionalLocations.ToArray(); if (additionalLocations.Length != expected.Locations.Length - 1) { Assert.IsTrue(false, string.Format("Expected {0} additional locations but got {1} for Diagnostic:\r\n {2}\r\n", expected.Locations.Length - 1, additionalLocations.Length, FormatDiagnostics(analyzer, actual))); } for (int j = 0; j < additionalLocations.Length; ++j) { VerifyDiagnosticLocation(analyzer, actual, additionalLocations[j], expected.Locations[j + 1]); } } if (actual.Id != expected.Id) { Assert.IsTrue(false, string.Format("Expected diagnostic id to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n", expected.Id, actual.Id, FormatDiagnostics(analyzer, actual))); } if (actual.Severity != expected.Severity) { Assert.IsTrue(false, string.Format("Expected diagnostic severity to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n", expected.Severity, actual.Severity, FormatDiagnostics(analyzer, actual))); } if (actual.GetMessage() != expected.Message) { Assert.IsTrue(false, string.Format("Expected diagnostic message to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n", expected.Message, actual.GetMessage(), FormatDiagnostics(analyzer, actual))); } } }
/// <summary> /// Computes statistics for a given collection of <see cref="AnnoObject"/>. /// </summary> /// <param name="objects"></param> /// <param name="includeRoads"></param> /// <returns>Properties about the collection - minX, maxX</returns> public StatisticsCalculationResult CalculateStatistics(IEnumerable <AnnoObject> objects, bool includeRoads = false) { if (objects == null) { return(null); } var result = new StatisticsCalculationResult(); if (objects.Count() == 0) { return(result); } /* old logic is easier to understand, but slower * // calculate bouding box * var boxX = placedObjects.Max(_ => _.Position.X + _.Size.Width) - placedObjects.Min(_ => _.Position.X); * var boxY = placedObjects.Max(_ => _.Position.Y + _.Size.Height) - placedObjects.Min(_ => _.Position.Y); * // calculate area of all buildings * var minTiles = placedObjects.Where(_ => !_.Road).Sum(_ => _.Size.Width * _.Size.Height); */ var maxX = double.MinValue; var maxY = double.MinValue; var minX = double.MaxValue; var minY = double.MaxValue; var sum = 0d; foreach (var curObject in objects) { var curPosX = curObject.Position.X; var curPosY = curObject.Position.Y; var curSize = curObject.Size; var curMaxX = curPosX + curSize.Width; var curMaxY = curPosY + curSize.Height; if (curMaxX > maxX) { maxX = curMaxX; } if (curPosX < minX) { minX = curPosX; } if (curMaxY > maxY) { maxY = curMaxY; } if (curPosY < minY) { minY = curPosY; } if (includeRoads || !curObject.Road) { sum += (curSize.Width * curSize.Height); } } // calculate bouding box var boxX = maxX - minX; var boxY = maxY - minY; // calculate area of all buildings var minTiles = sum; result.MinX = minX; result.MinY = minY; result.MaxX = maxX; result.MaxY = maxY; result.UsedAreaWidth = boxX; result.UsedAreaHeight = boxY; result.UsedTiles = boxX * boxY; result.MinTiles = minTiles; result.Efficiency = Math.Round(minTiles / boxX / boxY * 100); return(result); }
/// <summary> /// 更新积分统计 /// </summary> /// <param name="userId">用户Id</param> /// <param name="pointCategory2PointsDictionary"><remarks>key=PointCategory,value=Points</remarks>积分分类-积分字典</param> /// <returns>修订后应获取到的积分值</returns> public Dictionary <string, int> UpdateStatistic(long userId, Dictionary <PointCategory, int> pointCategory2PointsDictionary) { Dictionary <string, int> dictionary = new Dictionary <string, int>(); RWLock.EnterWriteLock(); PetaPocoDatabase dao = CreateDAO(); try { dao.OpenSharedConnection(); //1、检查当日积分统计是否存在,不存在创建 //2、检查是否超过当日限额,如果未超过更新当日积分累计 var sql = Sql.Builder; sql.Select("*") .From("tn_PointStatistics") .Where("UserId = @0", userId) .Where("StatisticalYear = @0", DateTime.UtcNow.Year) .Where("StatisticalMonth = @0", DateTime.UtcNow.Month) .Where("StatisticalDay = @0", DateTime.UtcNow.Day); IEnumerable <PointStatistic> pointStatistices = dao.Fetch <PointStatistic>(sql); //初始化 foreach (var pair in pointCategory2PointsDictionary) { dictionary[pair.Key.CategoryKey] = pair.Value; } //当日积分统计不存在 if (pointStatistices == null || pointStatistices.Count() == 0) { //创建当日积分统计 foreach (var pair in pointCategory2PointsDictionary) { if (pair.Key.QuotaPerDay <= 0) { continue; } var pointStatistic = PointStatistic.New(); pointStatistic.UserId = userId; pointStatistic.PointCategoryKey = pair.Key.CategoryKey; pointStatistic.Points = pair.Value; dao.Insert(pointStatistic); } } else { //检查是积分限额,调整用户最终获取到的积分 foreach (var pair in pointCategory2PointsDictionary) { if (pair.Key.QuotaPerDay <= 0) { continue; } var category = pair.Key; var pointStatistic = pointStatistices.FirstOrDefault(n => n.PointCategoryKey == category.CategoryKey); if (pointStatistic == null) { continue; } if (pair.Value > 0 && pointStatistic.Points + pair.Value > category.QuotaPerDay)//超过限额 { dictionary[pair.Key.CategoryKey] = 0; } else { pointStatistic.Points += pair.Value; dao.Update(pointStatistic); } } } } finally { dao.CloseSharedConnection(); RWLock.ExitWriteLock(); } //更新用户分区缓存 RealTimeCacheHelper.IncreaseAreaVersion("UserId", userId); return(dictionary); }