public static string FindPositionPart(IList<string> parts, int cursorPosition, out int foundPartsIndex, out int cursorInPartPosition) { cursorInPartPosition = 0; var partsComplete = parts.Aggregate(String.Empty, (aggr, s) => aggr + s); for (int i = 0; i < parts.Count(); i++) { var partsLower = parts.Take(i).Aggregate(String.Empty, (aggr, s) => aggr + s); var partsUpper = parts.Take(i + 1).Aggregate(String.Empty, (aggr, s) => aggr + s); var b = partsLower.Length; var t = partsUpper.Length; if ((cursorPosition >= b && cursorPosition < t) || partsUpper == partsComplete) { if (parts[i] == WorkDayParser.itemSeparator.ToString() || parts[i] == WorkDayParser.hourProjectInfoSeparator.ToString()) { // cursor left of separator foundPartsIndex = i - 1; var prevPart = parts.ElementAt(foundPartsIndex); // find out where in the found part the cursor is, need to use prevpart an its length cursorInPartPosition = prevPart.Length; return prevPart; } else { // find out where in the found part the cursor is cursorInPartPosition = cursorPosition - b; foundPartsIndex = i; return parts.ElementAt(i); } } } // not found foundPartsIndex = -1; return String.Empty; }
public Borda Unpack(IList<string> files, string key) { var borda = new Borda(); return files.Aggregate(borda, (b, file) => b + Unpack(file, key)); }
private static void MorphPart(RenderMeshPart part, IList<PartMorphInfo> morphInfos) { var count = morphInfos.Any() ? 1.0f / morphInfos.Count() : 1.0f; if (part.IsMirrored) { var verticesDictionary = new Dictionary<uint, Vector3>(); for (var i = 0; i < part.Points.Count; i++) { var point = part.Points[i]; var delta = morphInfos.Aggregate(Vector3.Zero, (current, mi) => current + mi.PointsMorph[i] * mi.Delta) * count; foreach (var index in point.Indices) { if (!verticesDictionary.ContainsKey(index)) verticesDictionary.Add(index, delta); } } for (var i = 0; i < part.Vertices.Length; i++) { var vertex = part.Vertices[i]; if (vertex.OriginalPosition.X >= 0.0f && vertex.OriginalPosition.X <= 1.0f) { var a = (uint)Math.Abs(vertex.OriginalPosition.Y); var b = (uint)Math.Abs(vertex.OriginalPosition.Z); var point0 = part.BaseVertices[a].Position + verticesDictionary[a]; var point1 = part.BaseVertices[b].Position + verticesDictionary[b]; vertex.Position = point0 + (point1 - point0) * vertex.OriginalPosition.X; } else { var p = (uint)Math.Abs(vertex.OriginalPosition.X) - 2; var delta = verticesDictionary[p]; vertex.Position = part.BaseVertices[p].Position + delta; if (vertex.Position.X > 0.0f == part.IsLeftToRight) vertex.Position.X = 0.0f; if (vertex.OriginalPosition.X < 0.0f) vertex.Position.X *= -1.0f; } part.Vertices[i] = vertex; } } else { for (var i = 0; i < part.Points.Count; i++) { var point = part.Points[i]; var delta = morphInfos.Aggregate(Vector3.Zero, (current, mi) => current + mi.PointsMorph[i] * mi.Delta) * count; foreach (var index in point.Indices) part.Vertices[index].Position = point.Position + delta; } } part.UpdateNormals(); }
public static async Task ShowErrorsAsync(IList<string> errors) { if (errors.Count > 0) { await ShowErrorAsync(errors.Aggregate((s, next) => s + '\n' + next)); } }
public static void ModifyFile(string pathToFile, IList<ProjectSolutionMapping> mappings) { string allText; Encoding originalEncoding; using (var fileStream = File.OpenText(pathToFile)) { originalEncoding = fileStream.CurrentEncoding; allText = fileStream.ReadToEnd(); } if (string.IsNullOrEmpty(allText)) { return; } if (!AnythingNeedsReplacing(allText, mappings)) { Console.WriteLine(@"nothing to modify in " + pathToFile); return; } Console.WriteLine(@"modifying " + pathToFile); allText = mappings.Aggregate( allText, (current, eachMapping) => current.Replace(eachMapping.OldText, eachMapping.NewText)); File.WriteAllText(pathToFile, allText, originalEncoding); }
private string AppendMethodParameters(string methodName, IList<string> parameters) { if (parameters.Count == 0) { return methodName + "()"; } return methodName + ('(' + parameters.Aggregate((a, b) => a + ", " + b) + ')'); }
private static IList<Int32> GenerateSlantingSegmentsRow(IList<Int32> sourceValue, Int32 delta) { return sourceValue.Aggregate(new List<Int32>(), (acc, value) => { acc.AddRange(new[] {value - delta, value + delta}); return acc; }); }
public bool OnActivate(IList<string> args) { // handle command line arguments of second instance Current.MainWindow.Title = args.Any() ? args.Aggregate((s1, s2) => string.Format("{0}, {1}", s1, s2)) : "Second instance launched"; return true; }
public CollisionGroup(IList<SimpleSphereCollider> colliders) { Colliders = colliders; _center = colliders.Aggregate(Vector3.zero, (total, each) => (total + each.transform.position)) / colliders.Count; _radius = colliders.Select( _=> (_.transform.position - _center).magnitude + _radius ).Max(); }
private static Language?TopScore(IList <AnalysisResult> source) { if (source.All(x => x.Score == 0)) { return(null); } return(source?.Aggregate((l, r) => l.Score > r.Score ? l : r).Language); }
private static void StartProcess(IList<string> parameters) { var process = new Process(); process.StartInfo.FileName = App.CurrentTranspilerPath; process.StartInfo.Arguments = parameters.Aggregate((x, y) => x + " " + y); process.Start(); }
public ValidateDeploymentUpgradeTypeAttribute() { this.validValues = new List<string> { UpgradeType.Auto, UpgradeType.Manual, UpgradeType.Simultaneous }; commaSeparatedUpgradeTypes = validValues.Aggregate((c, n) => c + ", " + n); }
/// <summary> /// /// </summary> /// <returns></returns> public Dictionary <string, string> BuildDictionary() { return(_dictionaries .Aggregate(new Dictionary <string, string>(), (result, dictionary) => { foreach (var kvp in dictionary) { result[kvp.Key] = kvp.Value; } return result; })); }
public int GetHashCode(IList <ArkName> obj) { const int seed = 1; const int modifier = 31; unchecked { return(obj.Aggregate(seed, (current, item) => (current * modifier) + item.GetHashCode())); } }
public int GetHashCode(IList <T> obj) { var hash = 19; unchecked { hash = obj.Aggregate(hash, (current, t) => current * 31 + (t != null ? t.GetHashCode() : 0)); } return(hash); }
public bool OnActivate(IList <string> args) { // handle command line arguments of second instance if (Current.MainWindow != null) { Current.MainWindow.Title = args.Any() ? args.Aggregate((s1, s2) => $"{s1}, {s2}") : "Second instance launched"; } return(true); }
public static List <string> FormatValidationFailures(IList <ValidationFailure> validationFailures) { return(validationFailures.Aggregate( new List <string>(), (errorList, validationFailure) => { errorList.Add(FluentValidationsFailureMessage(validationFailure.PropertyName, validationFailure.ErrorMessage)); return errorList; } )); }
public JObject GetGelfJson(LogEventInfo logEventInfo, string application, string environment, IList <RedactInfo> redactions) { //Retrieve the formatted message from LogEventInfo var logEventMessage = redactions.Aggregate(logEventInfo.FormattedMessage, (current, redaction) => redaction.LazyRegex.Value.Replace(current, redaction.Replacement)); if (logEventMessage == null) { return(null); } //Construct the instance of GelfMessage //See http://docs.graylog.org/en/2.1/pages/gelf.html?highlight=short%20message#gelf-format-specification "Specification (version 1.1)" var gelfMessage = new GelfMessage { Version = GelfVersion, Host = Dns.GetHostName().ToUpper(), ShortMessage = GetShortMessage(logEventMessage), FullMessage = logEventMessage, Timestamp = logEventInfo.TimeStamp, Level = GetSeverityLevel(logEventInfo.Level) }; //Convert to JSON var jsonObject = JObject.FromObject(gelfMessage); //Add any other interesting data to additional fields AddAdditionalField(jsonObject, new KeyValuePair <object, object>("application", application)); AddAdditionalField(jsonObject, new KeyValuePair <object, object>("environment", environment)); AddAdditionalField(jsonObject, new KeyValuePair <object, object>("line", logEventInfo.UserStackFrame?.GetFileLineNumber().ToString(CultureInfo.InvariantCulture))); AddAdditionalField(jsonObject, new KeyValuePair <object, object>("file", logEventInfo.UserStackFrame?.GetFileName())); AddAdditionalField(jsonObject, new KeyValuePair <object, object>("LoggerName", logEventInfo.LoggerName)); AddAdditionalField(jsonObject, new KeyValuePair <object, object>("LogLevelName", logEventInfo.Level?.ToString())); //If we are dealing with an exception, add exception properties as additional fields if (logEventInfo.Exception != null) { string exceptionDetail; string stackDetail; GetExceptionMessages(logEventInfo.Exception, out exceptionDetail, out stackDetail); AddAdditionalField(jsonObject, new KeyValuePair <object, object>("ExceptionSource", logEventInfo.Exception.Source)); AddAdditionalField(jsonObject, new KeyValuePair <object, object>("ExceptionMessage", exceptionDetail)); AddAdditionalField(jsonObject, new KeyValuePair <object, object>("StackTrace", stackDetail)); } foreach (var property in logEventInfo.Properties) { AddAdditionalField(jsonObject, property); } return(jsonObject); }
private Portal GetClosestPortalTo(IList <Portal> portals, Vector2 position) { if (portals.Any()) { return(portals.Aggregate((p1, p2) => (position - p1.Model.Position).sqrMagnitude < (position - p2.Model.Position).sqrMagnitude ? p1 : p2)); } else { return(null); } }
public static int GetSequenceHashCode <T>(this IList <T> sequence) { const int seed = 487; const int modifier = 31; unchecked { return(sequence.Aggregate(seed, (current, item) => (current * modifier) + item.GetHashCode())); } }
public static void ExecuteAggregateMethodWithResult() { IList <Student> students = StudentData.GetStudentData(); string names = students.Aggregate("Names: ", (str, s) => str += s.Name + ",", str => str.Substring(0, str.Length - 1)); "Aggregate Method".PrintHeader(); Console.WriteLine(names); }
/// <summary> /// Find the equivalent amount in the target currency by running the initial amount through the path of exchange rates. /// </summary> public int Convert(int amount) => edges .Aggregate <Edge, decimal>( amount, (aggregate, edge) => { // Each rate is multiplied with the next then rounded aggregate *= edge.Rate; return(aggregate.Round4()); }) .Round0();
/// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns> /// A hash code for the current <see cref="T:System.Object"/>. /// </returns> /// <filterpriority>2</filterpriority> public override int GetHashCode() { var result = 11; if (projects != null) { result = projects.Aggregate(result, (current, project) => current ^ project.GetHashCode()); } return(result); }
public static string GetTags(IList <string> tags) { if (tags.Count > 0) { return(tags.Aggregate((t1, t2) => t1.Trim() + Constants.TagSeparator + t2.Trim())); } else { return(string.Empty); } }
public static string Flatten(this IList <int> items) { var flattened = items.Aggregate(string.Empty, (current, item) => current + string.Format("{0},", item)); if (flattened.EndsWith(",")) { flattened = flattened.Substring(0, flattened.Length - 1); } return(flattened); }
/// <summary> /// Applies sorting to the specified query. /// </summary> /// <param name="query">The query.</param> /// <returns>Sorted results.</returns> public virtual IQueryable <T> Apply(IQueryable <T> query) { IOrderedQueryable <T> sortedQuery = null; if (_primarySortAction != null) { sortedQuery = _primarySortAction(query); } return(_sortActions.Aggregate(sortedQuery, (current, sortAction) => sortAction(current))); }
public static void ShowErrors(IList<string> errors) { if (errors.Count > 0) { ShowError(errors.Aggregate((s, next) => s + '\n' + next)); } else { ShowError("An unknown error has occurred."); } }
// Chinese Remainder Theorem (CRT) public static long CRT(IList <int> num, IList <int> rem) { long prod = num.Aggregate(1L, (a, b) => a * b); long sum = 0; for (int i = 0; i < num.Count; i++) { long p = prod / num[i]; sum += rem[i] * Utils.ModInverse(p, num[i]) * p; } return(sum % prod); }
public static IQueryable <TEntity> FilterBy <TEntity>(this IQueryable <TEntity> source, IList <Expression <Func <TEntity, bool> > > criterias) where TEntity : class { var queryable = source; if (criterias.Count > 0) { queryable = criterias.Aggregate(source, (current, filter) => current.Where(filter)); } return(queryable); }
public string GetPath() { return(_navigatorStorageFolders.First().FolderRelativeId.Split('\\')[0] == "0" ? CurrentStorageFolder.Path : _navigatorStorageFolders.Aggregate(string.Empty, (current, next) => { current += next.Name + "\\"; return current; } )); }
public T Aggregate <T>(T seed, Func <T, JsonDocument, T> aggregate) { slim.EnterReadLock(); try { return(innerList.Aggregate(seed, aggregate)); } finally { slim.ExitReadLock(); } }
public bool Remove(string paragraphName, bool distinctOnly) { if (_paragraphs.Count(p => p.Name.Equals(paragraphName)) > 1 && distinctOnly) { return(false); } IList <IMsBuildElementHelpParagraph> removeItems = _paragraphs.Where(x => x.Name.Equals(paragraphName)).ToList(); return(removeItems.Aggregate(true, (current, paragraph) => current && _paragraphs.Remove(paragraph))); }
public static SCNVector3?GetAverage(this IList <SCNVector3> vectors) { SCNVector3?result = null; if (vectors != null && vectors.Count > 0) { var sum = vectors.Aggregate(SCNVector3.Zero, (vector1, vector2) => vector1 + vector2); result = sum / vectors.Count; } return(result); }
public string DisplayNotes(IList <String> notes) { if (notes != null) { if (notes.Count == 0) { return("N/A"); } return(notes.Aggregate(string.Empty, (current, note) => current + note + "<br/>")); } return("N/A"); }
public void PrintAddLocalVariables(IList <string> currentBlockVariableList) { if (currentBlockVariableList.Count > 0) { string vars = currentBlockVariableList.Aggregate((one, two) => string.Format("{0}, {1}", one, two)); _stream.WriteLine("Добавлены переменные для блока{0}{1}", GrammarHelper.NewLineSymbol, vars); } else { _stream.WriteLine("В данном блоке не встречаются локальные переменные"); } }
private void btnOK_Click(object sender, EventArgs e) { if (!NamingGuidance.CheckNameFocus(tbName, "Query Name", true)) { return; } // Check length of queryname if (MaxQueryNameLength > 0 && tbName.Text.Trim().Length > MaxQueryNameLength) { MessageBox.Show("The Query Name is too long, it can be maximum " + MaxQueryNameLength.ToString() + " characters.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // Find the parameters that is nonunique if (outParameterNames.Count > 0) { IList <string> list = outParameterNames.Values.GroupBy(s => s).Where(g => g.Count() > 1).Select(g => g.Key).ToList(); if (list.Count > 0) { // Make a nice comma separated list! string listNames = list.Aggregate((current, next) => current + ", " + next); if (list.Count > 1) { MessageBox.Show("The parameters with the names " + listNames + " must be renamed.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { MessageBox.Show("The parameters with the name " + listNames + " must be renamed.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } return; } } ReportQuery parentReportQuery; string errorText; if (!ReportHelper.CheckReportParameterCombinations(ExistingSources, rtSQL.Text, out errorText, out parentReportQuery)) { MessageBox.Show(errorText, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } ParentReportQuery = parentReportQuery; CurrentQuery.Name = tbName.Text.Trim(); DialogResult = DialogResult.OK; }
private static Func <IHttpContext, Task> Aggregate(this IList <IHttpRequestHandler> handlers, int index) { if (index == handlers.Count) { return(null); } var currentHandler = handlers[index]; var nextHandler = handlers.Aggregate(index + 1); return(context => currentHandler.Handle(context, () => nextHandler(context))); }
private void UpdateCameraConfig() { int cullingMask = Slaves.Aggregate(0, (cull, cam) => cull | cam.cullingMask); // Remove layers that are captured by other cameras (see VRGUI) cullingMask |= VR.Interpreter.DefaultCullingMask; cullingMask &= ~(LayerMask.GetMask(VR.Context.UILayer, VR.Context.InvisibleLayer)); cullingMask &= ~(VR.Context.IgnoreMask); VRLog.Info("The camera sees {0} ({1})", string.Join(", ", UnityHelper.GetLayerNames(cullingMask)), string.Join(", ", Slaves.Select(s => s.name).ToArray())); GetComponent <Camera>().cullingMask = cullingMask; }
public UnionType(string name, IList <IType> types, UnionOptions options = null) : base(name) { _Types = types; _Dispatcher = options?.Dispatcher; _Eager = options?.Eager ?? true; Flags = types.Aggregate(TypeFlags.Union, (acc, type) => acc | type.Flags); ShouldAttachNode = types.Any(type => type.ShouldAttachNode); }
/// <summary> /// Refreshes the details. /// </summary> /// <param name="symbols">The symbols.</param> /// <param name="callback">The callback.</param> public void RefreshDetails(IList <string> symbols, Action <IDictionary <string, StockTickerDetails> > callback) { if (symbols.Count > 0) { var stockSymbols = symbols.Aggregate(string.Empty, (current, symbol) => current + (symbol + " ")); var uri = new Uri(string.Format(UrlStockDetails, symbols.Aggregate((x, y) => string.Format("{0}+{1}", x, y)))); DebugManager.LogTrace("StockDataService -> Requesting details for multiple stocks: " + stockSymbols); if (LastStockSymbols != stockSymbols) { LastStockSymbols = stockSymbols; DebugManager.LogTrace("StockDataService -> Requesting details link: " + uri.AbsoluteUri.Replace("http://", "")); } DebugManager.Time("StockDataService -> Requesting details"); var wc = new WebClient(); wc.OpenReadCompleted += OnRefreshDetailsCompleted; wc.OpenReadAsync(uri, callback); } }
public CurrentStatus(IList <Tuple <Repository, IReadOnlyList <Issue> > > state) { TotalOpenIssues = state.Aggregate(0, (current, item) => current + item.Item2.Count); var oldestToYoungest = state .SelectMany(x => x.Item2) .OrderBy(x => x.CreatedAt); OldestIssueAge = (DateTime.UtcNow - oldestToYoungest.First().CreatedAt).TotalDays; TopTenOldest = oldestToYoungest.Take(10).ToList(); }
public static QueryContainer MultiTermAndFilterFor <T, TValue>(Expression <Func <T, object> > field, IList <TValue> terms) where T : class { if (terms == null || !terms.Any()) { return(null); } var queryContainer = new QueryContainer(); return(terms.Aggregate(queryContainer, (current, term) => current && Query <T> .Term(field, term))); }
protected override int performOperation(IList<int> input) { if (input.Count == 0) { return 1; } if (input.Count == 1) { return input.First(); } return input.Aggregate((a, b) => a * b); }
public static float Run(IList<double> dp0, IList<IList<double>> dpc1) { IList<LocalPattern> lps1 = new List<LocalPattern>(); lps1 = dpc1.Aggregate(lps1, (current, ts) => current.Concat(GetLocalPatterns(ts, WINDOW_SIZE)).ToList()); IList<LocalPattern> lps0 = GetLocalPatterns(dp0, WINDOW_SIZE); BUCKET_SIZE = (int) (TOP_BUCKET_RATIO*dp0.Count); List<List<LocalPatternMatch>> lpmBuckets = GetLocalPatternMatchBuckets(lps0, lps1); var allLpms = new List<LocalPatternMatch>(); foreach (var bucket in lpmBuckets) { foreach (LocalPatternMatch lpm in bucket) { allLpms.Add(lpm); } } int numVertices = allLpms.Count + 2; var costMatrix = new int[numVertices, numVertices]; for (int i = 0; i < allLpms.Count; i++) { int distToStart = LocalPatternMatch.DistanceToPs(allLpms[i], allLpms.Count, WINDOW_SIZE); int distToEnd = LocalPatternMatch.DistanceToPe(allLpms[i], allLpms.Count, WINDOW_SIZE); costMatrix[0, i + 1] = distToStart; costMatrix[i + 1, numVertices - 1] = distToEnd; } for (int row = 0; row < numVertices - 2; row++) { for (int col = 0; col < numVertices - 2; col++) { if (row == col) costMatrix[row + 1, col + 1] = 0; else costMatrix[row + 1, col + 1] = LocalPatternMatch.Distance(allLpms[row], allLpms[col], allLpms.Count, WINDOW_SIZE); } } var dijkstra = new Dijkstra.Dijkstra(); dijkstra.Run(costMatrix, 0); return dijkstra.StartToEndDistance; }
public ValidateVMSizeAttribute(bool includeExtraSmall) { this.validValues = new List<string> { "Small", "Medium", "Large", "ExtraLarge", "A6", "A7" }; if (includeExtraSmall) { this.validValues.Insert(0, "ExtraSmall"); } commaSeparatedVMSizes = validValues.Aggregate((c, n) => c + ", " + n); }
public string UpdateAlertAttivita(IList<AlertAttivitaDTO> listaAlert) { try { var message = string.Empty; foreach (var alertAttivitaDTO in listaAlert) { var alert = manage(alertAttivitaDTO); if (alert == null) message += string.Format("L'alert {0} non è stato salvato.{1}", alertAttivitaDTO.ID, Environment.NewLine); } return message; } catch (Exception ex) { _log.ErrorFormat("Errore nel salvataggio degli Alert - {0} - alert:{1}", ex, Utility.GetMethodDescription(), listaAlert.Aggregate(string.Empty, (current, alertAttivitaDTO) => current + (alertAttivitaDTO.ID + ", "))); throw; } }
static void DownloadSubtitle(string movieFileName, bool lucky, IList<string> languages) { var systemLanguage = GetSystemLanguage(); using (var osdb = Osdb.Login(systemLanguage, "OS Test User Agent")) { var subtitles = osdb.SearchSubtitlesFromFile(languages.Aggregate( (a,b) => a + "," +b ),movieFileName); int subtitlesCount = subtitles.Count; if (subtitlesCount == 0) { Console.WriteLine("Sorry, no subtitles found for your movie"); return; } var selectedSubtitle = subtitles.First(); if (!lucky) { var canceled = !PromptForSubtitle(subtitles, ref selectedSubtitle); if (canceled) { return; } } string subtitleFile = osdb.DownloadSubtitleToPath(Path.GetDirectoryName(movieFileName), selectedSubtitle); Console.WriteLine("Subtitle downloaded to '{0}'", subtitleFile); } }
public string AperturaAutomaticaPratiche(IList<PraticaDTO> pratiche, IList<int> condomini, Urgenza urgenza, int idAzienda, LogTransazione logTransazione) { var result = string.Empty; try { foreach (var idCondominio in condomini) { foreach (var praticaDTO in pratiche) { Pratica pratica; AperturaPratica(0, DateTime.Now, praticaDTO.IdTipoPraticaRiferimento, idCondominio, null, praticaDTO.Oggetto, urgenza, null, idAzienda, logTransazione, out pratica); } } } catch (Exception ex) { _log.ErrorFormat("Errore nell'apertura automatica delle pratiche - {0} - condomini:{1} - pratiche:{2}", ex, Utility.GetMethodDescription(), condomini.Aggregate(string.Empty, (current, id) => current + $"{id},"), pratiche.Aggregate(string.Empty, (current, nome) => current + $"{nome.Oggetto},")); throw; } return result; }
public IList<AnswerGuess> GetAnswerGuesses(IList<AnsweredQuestion> answeredQuestions) { var answerGuesses = new List<AnswerGuess>(); double answeredQuestionsProbability = 0; foreach (var answerStatistic in answerStatistics) { var answeredQuestionsProbabilityRelativeToAnswer = answeredQuestions.Aggregate(1.0, (curr, q) => curr * GetAnsweringFrequency(answerStatistic.Value, q) / GetTotalAnsweringFrequency(answerStatistic.Value, q)); var answerProbability = answeredQuestionsProbabilityRelativeToAnswer * answerStatistic.Value.AnswerCount / answersGuessedCount; answerGuesses.Add(new AnswerGuess { AnswerId = answerStatistic.Key, Probability = answerProbability, AnswerStatistic = answerStatistic.Value }); answeredQuestionsProbability += answerProbability; } foreach (var answerGuess in answerGuesses) { answerGuess.Probability /= answeredQuestionsProbability; } return answerGuesses.OrderByDescending(g => g.Probability).Take(maxGuesses).ToList(); }
private static string CharListToString(IList<char> chars) => chars.Aggregate(new StringBuilder(), (builder, c) => builder.Append(c), builder => builder.ToString());
public string AddDocumentiAttivita(int idAttivita, IList<int> documenti) { try { var message = string.Empty; var attivita = _daoFactory.GetAttivitaDao().Find(idAttivita, false); if (attivita != null) { foreach (var idDocumento in documenti) { if (attivita.Documenti.Count(item => item.ID == idDocumento) == 0) { var documento = _daoFactory.GetDocumentoDao().Find(idDocumento, false); if (documento != null) { documento.AttivitaRiferimento = attivita; attivita.Documenti.Add(documento); } } } } return message; } catch (Exception ex) { _log.ErrorFormat("Errore il nell'associazione di documenti a attivita - {0} - attività:{1} - documenti:{2}", ex, Utility.GetMethodDescription(), idAttivita, documenti.Aggregate(string.Empty, (current, id) => current + (id + ", "))); throw; } }
public ModificationCombination(IList<Modification> modificationList) { Modifications = modificationList; Composition = modificationList.Aggregate(Data.Composition.Composition.Zero, (current, mod) => current + mod.Composition); }
/// <summary> /// http://vk.com/pages?oid=-1&p=messages.getDialogs#/pages?oid=-1&p=users.get /// </summary> public static async Task<string> GetUserListAsync(string token, IList<string> uids) { Debug.Assert(uids.Count <= 1000); Debug.Assert(uids.Count > 0); string allUids = uids.Aggregate("", (current, uid) => current + ("," + uid)).Remove(0, 1); string uri = BuildVkApiUri( "users.get", new[] { "uids", "fields" }, new[] { allUids, "uid,first_name,last_name,photo,online" }, token); return await DownloadStringTaskAsync(uri); }
private string PreformatMessage(string displayName, string expression, out IList<FormatItem> items) { var message = MessageFormatter.FormatString(ErrorMessageString, out items); // process custom format items: {fieldPath[:indicator]}, and substitute them entirely with guids, not to interfere with standard string.Format() invoked below message = string.Format(message, displayName, expression); // process standard format items: {index[,alignment][:formatString]}, https://msdn.microsoft.com/en-us/library/txafckwd(v=vs.110).aspx message = items.Aggregate(message, (cargo, current) => cargo.Replace(current.Uuid.ToString(), current.Substitute)); // give back, initially preprocessed, custom format items return message; }
public static void SaveInstalledPluginsFile(IList<String> pluginSystemNames, string filePath) { string result = pluginSystemNames.Aggregate("", (current, sn) => current + string.Format("{0}{1}", sn, Environment.NewLine)); File.WriteAllText(filePath, result); }
private static IEnumerable<int> CheckAndAddProducts(IList<string> productSubNumbers, string productMainDescr, IList<string> productSubDescriptions) { var productIds = new List<int>(); var productAttributes = new List<string>(); if (productSubNumbers.Count > 1) { var attributes = "Rozmiar"; var productNumberLength = productSubNumbers[0].Length - 2; string productNumber = productSubNumbers[0].Substring(0, productNumberLength); const string attributesRegex = "((rozm\\.)|(Rozmiar)|(rozmiar))\\s*\\w*"; foreach (var productSubDescription in productSubDescriptions) { var temp = new Regex(attributesRegex).Match(productSubDescription).Value; try { productAttributes.Add(temp.Split(' ')[1]); } catch(Exception) { try { productAttributes.Add(temp.Split('.')[1]); } catch(Exception) { var tempSubDescr = productSubDescription.Split(' '); productAttributes.Add(tempSubDescr[tempSubDescr.Length - 1]); } } } var productTemp = new Regex(attributesRegex).Match(productSubDescriptions[0]).Value; string productName = ""; try { productName = productSubDescriptions[0].Replace(productTemp, ""); } catch(Exception) { var tempProductNameAll = productSubDescriptions[0].Split(' '); var tempProductName = ""; for (var i = 0; i < tempProductNameAll.Length - 1; i++) { tempProductName += tempProductNameAll[i] + " "; } productName = tempProductName; } for (var i = 0; i < productSubNumbers.Count; i++) { attributes += String.Format(",({0}) {1}", productSubNumbers[i], productAttributes[i]); } var selectQuery = "select * from jos_vm_product where product_sku = " + productNumber; selectQuery = productSubNumbers.Aggregate(selectQuery, (current, productSubNumber) => current + (" or attribute like \"%" + productSubNumber + "%\"")); var selectCommand = new MySqlCommand(selectQuery, _mySqlConnect).ExecuteReader(); if (!selectCommand.Read()) { selectCommand.Close(); var insertQuery = String.Format("insert into jos_vm_product (vendor_id, product_parent_id, product_sku, product_s_desc, product_desc, product_thumb_image, product_full_image, product_publish, product_weight, product_weight_uom, product_length, product_width, product_height, product_lwh_uom, product_url, product_in_stock, product_available_date, product_availability, product_special, product_discount_id, ship_code_id, cdate, mdate, product_name, product_sales, attribute, custom_attribute, product_tax_id, product_unit, product_packaging, child_options, quantity_options, child_option_ids, product_order_levels) VALUES (1, 0, {0}, '', '{1}', '', '', 'Y', '0.0000', 'kg', '0.0000', '0.0000', '0.0000', 'cm', '', 0, 1279843200, '', 'N', 0, NULL, 1279922325, 1279922577, '{2}', 0, '{3}', '', 3, 'szt.', 0, 'N,N,N,N,N,Y,20%,10%,', 'none,0,0,1', '', '0,0')", productNumber, productMainDescr, productName, attributes); var insertCommand = new MySqlCommand(insertQuery, _mySqlConnect); insertCommand.ExecuteNonQuery(); productIds.Add((int)insertCommand.LastInsertedId); } else { productIds.Add(selectCommand.GetInt32("product_id")); selectCommand.Close(); } } else { for (var j = 0; j < productSubNumbers.Count; j++) { var selectQuery = "select * from jos_vm_product where product_sku = " + productSubNumbers[j]; selectQuery = productSubNumbers.Aggregate(selectQuery, (current, productSubNumber) => current + (" or attribute like \"%" + productSubNumber + "%\"")); var selectCommand = new MySqlCommand(selectQuery, _mySqlConnect).ExecuteReader(); if (!selectCommand.Read()) { selectCommand.Close(); var insertQuery = String.Format("insert into jos_vm_product (vendor_id, product_parent_id, product_sku, product_s_desc, product_desc, product_thumb_image, product_full_image, product_publish, product_weight, product_weight_uom, product_length, product_width, product_height, product_lwh_uom, product_url, product_in_stock, product_available_date, product_availability, product_special, product_discount_id, ship_code_id, cdate, mdate, product_name, product_sales, attribute, custom_attribute, product_tax_id, product_unit, product_packaging, child_options, quantity_options, child_option_ids, product_order_levels) VALUES (1, 0, {0}, '', '{1}', '', '', 'Y', '0.0000', 'kg', '0.0000', '0.0000', '0.0000', 'cm', '', 0, 1279843200, '', 'N', 0, NULL, 1279922325, 1279922577, '{2}', 0, '', '', 3, 'szt.', 0, 'N,N,N,N,N,Y,20%,10%,', 'none,0,0,1', '', '0,0')", productSubNumbers[j], productMainDescr, productSubDescriptions[j]); var insertCommand = new MySqlCommand(insertQuery, _mySqlConnect); insertCommand.ExecuteNonQuery(); productIds.Add((int)insertCommand.LastInsertedId); } else { productIds.Add(selectCommand.GetInt32("product_id")); selectCommand.Close(); continue; } } } return productIds; }
public IList<string> IsAllowDataRegistrazione(IList<int> idCondomini, Esercizio esercizio, DateTime dataRegistrazione) { try { var message = new List<string>(); if (dataRegistrazione != DateTime.MinValue) { if (esercizio != null) { if (dataRegistrazione < esercizio.DataApertura.GetValueOrDefault() || dataRegistrazione > esercizio.DataChiusura.GetValueOrDefault() || esercizio.Stato == StatoEsercizioEnum.Chiuso) { message.Add(string.Format("Data non valida per l'esercizio {0} - Data inizio esercizio: {1:d} - Data fine esercizio:{2:d}", esercizio.DisplayName, esercizio.DataApertura.GetValueOrDefault(), esercizio.DataChiusura.GetValueOrDefault())); _log.DebugFormat("Data di registrazione non corretta - {0} - esercizio:{1} - dataApertura:{2} - dataChiusura:{3} - dataRegistrazione:{4}", Utility.GetMethodDescription(), esercizio.ID, esercizio.DataApertura.GetValueOrDefault(), esercizio.DataChiusura.GetValueOrDefault(), dataRegistrazione); } } foreach (var id in idCondomini) { var condominio = _daoFactory.GetCondominioDao().Find(id, false); if (condominio != null) { var dataUltimaChiusura = _condominioService.GetDataUltimaChiusura(condominio).GetValueOrDefault(); if (dataRegistrazione <= dataUltimaChiusura) { message.Add(string.Format("Data non valida per il condominio {0} - Ultima chiusura: {1}", condominio.DisplayName, dataUltimaChiusura.ToShortDateString())); _log.DebugFormat("Data di registrazione non corretta - {0} - condominio:{1} - dataUltimaChiusura:{2} - dataRegistrazione:{3}", Utility.GetMethodDescription(), id, dataUltimaChiusura, dataRegistrazione); } var esercizioCompetenza = getEsercizioCompetenza(condominio, dataRegistrazione); if (esercizioCompetenza == null || esercizioCompetenza.Stato == StatoEsercizioEnum.Chiuso) { var messageEsercizio = esercizioCompetenza == null ? "l'esercizio di competenza non è ancora stato aperto" : string.Format("l'esercizio '{0}' è chiuso", esercizioCompetenza.DisplayName); message.Add(string.Format("{0} - Non è possibile registrare il movimento in data {1:d} perchè {2}.", condominio.DisplayName, dataRegistrazione, messageEsercizio)); } } } } return message; } catch (Exception ex) { _log.ErrorFormat("Errore inaspettato durante il controllo di validità della data di registrazione - {0} - idCondomini:{1} - dataRegistrazione:{2}", ex, Utility.GetMethodDescription(), idCondomini.Aggregate(string.Empty, (current, id) => current + (id + " - ")), dataRegistrazione); throw; } }
public string Generate(string className, IList<IList<string>> ps) { return ps.Aggregate("", (str, m) => str + GenAutoINPC(m)); }
public IList<RisultatoInvioMessaggio> InvioMessaggio(int idAzienda, PersonaMessaggioDTO personaMessaggioDTO, Condominio condominio, int? idUnitaImmobiliare, int? idFornitore, int? idResponsabile, int? idIncaricatoAttivita, MotivoMessaggio motivoMessaggio, string oggetto, string testo, IList<string> destinatari, string mittente, string emailRapportino, IList<DocumentInfo> allegati, ParametriInvioLettera parametriInvioLettera) { try { if (destinatari.Count > 0) { var message = string.Empty; var invioRiuscito = false; var allegatiLista = new List<DocumentInfo>(allegati.Count); Persona persona = null; if (personaMessaggioDTO != null) persona = _daoFactory.GetPersonaDao().Find(personaMessaggioDTO.ID, false); var results = new List<RisultatoInvioMessaggio>(); var result = new eMessageResultSendFAX(); try { int? idCondominio = null; if (condominio != null) idCondominio = condominio.ID; var destinatariSend = new List<string>(); foreach (var item in destinatari) { if (!item.Trim().StartsWith("+39")) destinatariSend.Add("+39" + Conversione.ToPhoneNumber(item)); else destinatariSend.Add(Conversione.ToPhoneNumber(item)); } // ===================================== // Creo le pagine del FAX // ===================================== var nomiFiles = new string[allegati.Count]; var contenutoAllegati = new byte[allegati.Count][]; // ------------------------------------- // Allegati // ------------------------------------- var index = 0; foreach (var documento in allegati) { nomiFiles[index] = documento.FileName + documento.FileExtension; contenutoAllegati[index] = documento.Body; allegatiLista.Add(documento); index++; } // ------------------------------------- // Oggetto // ------------------------------------- decimal? importo = null; var tipoIndirizzo = TipoIndirizzo.Recapito; if (personaMessaggioDTO != null) { importo = personaMessaggioDTO.Importo; tipoIndirizzo = personaMessaggioDTO.TipoIndirizzo; } var parametri = new ParametriStampaUnione(persona != null ? (int?)persona.ID : null, idUnitaImmobiliare, idResponsabile, idIncaricatoAttivita, idFornitore, idCondominio, null, tipoIndirizzo, importo, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null); oggetto = _messaggisticaService.ApplicaStampaUnione(oggetto, parametri, idAzienda); // ===================================== // Invio Messaggio // ===================================== // ------------------------------------- // Invio // ------------------------------------- var service = new Fax { Timeout = 999999999 }; var userService = new Users(); var credenziali = _configurationService.GetLoginInfo(idAzienda); if (credenziali != null && !string.IsNullOrEmpty(credenziali.Value.Utente) && !string.IsNullOrEmpty(credenziali.Value.Password)) { var success = false; try { var resultUsers = userService.Login(credenziali.Value.Utente, credenziali.Value.Password, null); success = resultUsers.success; } catch (Exception ex) { _log.WarnFormat("Errore durante il controllo delle credenziali - {0} - username:{1} - password:{2}", ex, Utility.GetMethodDescription(), credenziali.Value.Utente, credenziali.Value.Password); } if (success) { var identificazioneMittente = _configurationService.GetIdentificazioneMittente(idAzienda, TipoMessaggio.Fax, TipoIndirizzo.Recapito); // Controllo identificazione mittente if (string.IsNullOrEmpty(identificazioneMittente.Numero)) return new List<RisultatoInvioMessaggio> { new RisultatoInvioMessaggio("KO", null, false, "Il fax non può essere inviato perchè non è presente il numero di fax del mittente" + Environment.NewLine + "Inserire il numero nella anagrafica dello studio e riprovare.", new DocumentInfo()) }; if (!string.IsNullOrEmpty(identificazioneMittente.Email)) { if (!string.IsNullOrEmpty(emailRapportino)) emailRapportino += ","; emailRapportino += identificazioneMittente.Email; } // Mittente if (string.IsNullOrEmpty(mittente)) mittente = identificazioneMittente.Nome; if (ConfigurationManager.AppSettings["IsTest"] != null && bool.Parse(ConfigurationManager.AppSettings["IsTest"])) destinatariSend = new List<string> { "+390513371992" }; var parameters = new List<OptionalParameters> { new OptionalParameters { ParameterName = "NotificationEmail", ParameterValue = emailRapportino }, new OptionalParameters { ParameterName = "DeliveryTime", ParameterValue = DateTime.Now.ToString() }, new OptionalParameters { ParameterName = "HeaderFax", ParameterValue = identificazioneMittente.Numero }, new OptionalParameters { ParameterName = "HeaderName", ParameterValue = mittente } }; if (!parametriInvioLettera.Asincrono) result = service.Send(credenziali.Value.Utente, credenziali.Value.Password, destinatariSend.ToArray(), contenutoAllegati, nomiFiles, parameters.ToArray()); else { service.SendAsync(credenziali.Value.Utente, credenziali.Value.Password, destinatariSend.ToArray(), contenutoAllegati, nomiFiles, parameters.ToArray()); invioRiuscito = true; } message += result; _log.InfoFormat("Risultato invio fax:{0} - destinatario:{1}", result, destinatariSend.Aggregate(string.Empty, (current, dest) => current + (dest + ", "))); if (result.SpeditionResult.All(item => item.success)) invioRiuscito = true; } else { _log.WarnFormat("Credenziali non valide - {0} - username:{1} - password:{2}", Utility.GetMethodDescription(), credenziali.Value.Utente, credenziali.Value.Password); } } else { _log.FatalFormat("Errore inaspettato durante l'invio del fax. NON sono presenti le credenziali per l'invio del fax - {0} - oggetto:{1} - destinatario:{2}", Utility.GetMethodDescription(), oggetto, destinatari[0]); message = "KO - Non sono definite le credenziali per l'invio dei fax"; } } catch (Exception ex) { invioRiuscito = false; _log.FatalFormat("Errore inaspettato durante l'invio del fax - {0} - oggetto:{1} - destinatario:{2}", ex, Utility.GetMethodDescription(), oggetto, destinatari[0]); message = "KO - Errore inaspettato durante l'invio del fax"; } if (motivoMessaggio != MotivoMessaggio.ScadenzaContratto && invioRiuscito) { foreach (var singleResult in result.SpeditionResult) { try { string messaggioInvio; if (singleResult.success) { messaggioInvio = string.Format("Fax accodato per l'invio: {0}", singleResult.jobCode); _log.InfoFormat("Invio FAX RIUSCITO - {0} - messageCode: {1} - messaggio: {2} - jobcode: {3} - destinatario: {4}", Utility.GetMethodDescription(), singleResult.messageCode, singleResult.errorDescription, singleResult.jobCode, destinatari.Aggregate(string.Empty, (current, dest) => current + (dest + ";"))); } else { messaggioInvio = "Invio della lettera non riuscito:" + Environment.NewLine + singleResult.errorDescription; _log.WarnFormat("Invio FAX FALLITO - {0} - messageCode: {1} - messaggio: {2} - jobcode: {3} - destinatario: {4}", Utility.GetMethodDescription(), singleResult.messageCode, singleResult.errorDescription, singleResult.jobCode, destinatari.Aggregate(string.Empty, (current, dest) => current + (dest + ";"))); } var resultInvio = new RisultatoInvioMessaggio(singleResult.jobCode, singleResult.messageCode, singleResult.success, messaggioInvio, new DocumentInfo()); var storicoMessaggio = _messaggisticaService.StoricizzaMessaggio(persona, condominio, resultInvio, motivoMessaggio, oggetto, testo, destinatari, mittente, emailRapportino, allegatiLista, TipoMessaggio.Fax); if (storicoMessaggio != null) resultInvio.IdMessaggio = storicoMessaggio.ID; results.Add(resultInvio); } catch (Exception ex) { _log.ErrorFormat("Errore inaspettato durante la storicizzazione del messaggio - {0} - oggetto:{1} - destinatario:{2}", ex, Utility.GetMethodDescription(), oggetto, destinatari[0]); throw; } } } else { if (!invioRiuscito) results.Add(new RisultatoInvioMessaggio("KO", null, false, message, new DocumentInfo())); } return results; } } catch (Exception ex) { var idPersona = "<NULL>"; if (personaMessaggioDTO != null) idPersona = personaMessaggioDTO.ID.ToString(); var idCondominio = "<NULL>"; if (condominio != null) idCondominio = condominio.ID.ToString(); _log.FatalFormat("Errore inaspettato nell'invio del fax - {0} - azienda:{1} - persona:{2} - condominio:{3} - motivoMessaggio:{4} - oggetto:{5} - testo:{6} - destinatari:{7} - mittente:{8} - emailRapportino:{9}", ex, Utility.GetMethodDescription(), idAzienda, idPersona, idCondominio, motivoMessaggio, oggetto, testo, destinatari.Aggregate(string.Empty, (current, dest) => current + (dest + ", ")), mittente, emailRapportino); throw; } return new List<RisultatoInvioMessaggio> { new RisultatoInvioMessaggio(null, null, false, "Non è definito nessun destinatario", new DocumentInfo())}; }
public IList<VersamentoSoggettoDTO> GetVersamentiByEsercizioPersone(int? idEsercizio, IList<int> idPersone, bool sollecitaProprietarioConduzione) { try { var daoFactory = _windsorRepository.GetDaoFactory(_info.Azienda); var versamenti = daoFactory.GetVersamentoSoggettoDao().GetByEsercizioPersone(idEsercizio, idPersone); IList<VersamentoSoggettoDTO> listaDto = new List<VersamentoSoggettoDTO>(versamenti.Count); foreach (var item in versamenti) listaDto.Add(setDto(item, false)); // ================================================================================ // Se richiesto aggiungo per i proprietari le rate di conduzione // ================================================================================ if (sollecitaProprietarioConduzione) { var versamentiSoggetto = versamenti.GroupBy(item => item.Soggetto); foreach (var kvp in versamentiSoggetto) { var soggetto = kvp.Key; if (soggetto.Tipo == TipoSoggetto.Proprietario) { var conduttori = soggetto.UnitaImmobiliare.Conduttori; var idConduttori = new List<int>(conduttori.Count); idConduttori.AddRange(conduttori.Select(idConduttore => idConduttore.ID)); var versamentiConduzione = GetVersamentiByEsercizioSoggetti(idEsercizio, idConduttori, false); foreach (var versamentoSoggettoDTO in versamentiConduzione) { versamentoSoggettoDTO.IdSoggetto = soggetto.ID; versamentoSoggettoDTO.IdPersona = soggetto.Persona.ID; listaDto.Add(versamentoSoggettoDTO); } } } } return listaDto; } catch (Exception ex) { var soggetti = string.Empty; if (idPersone != null) soggetti = idPersone.Aggregate(soggetti, (current, id) => current + (id + ", ")); _log.ErrorFormat("Errore nel caricamento dei versamenti per esercizio e persone - {0} - esercizio:{1} - soggetti:{2}", ex, Library.Utility.GetMethodDescription(), idEsercizio, soggetti); throw; } }