public String CommonNames(Int32 cutOff) { StringBuilder builder = new StringBuilder(); builder.AppendLine("Total number: " + NumberOfEntities.ToString()); List<KeyValuePair<String, Int32>> sorted = new List<KeyValuePair<String, Int32>>(); foreach ( var keyValuePair in _namesCount ) { String name = keyValuePair.Key; sorted.Add(keyValuePair); } sorted.Sort(delegate(KeyValuePair<String, Int32> x, KeyValuePair<String, Int32> y) { return y.Value.CompareTo(x.Value); }); Int32 count = 0; foreach ( var keyValuePair in sorted ) { builder.AppendLine(keyValuePair.Key + " (" + keyValuePair.Value.ToString() + ") "); count++; if ( count > cutOff ) { break; } } String result = builder.ToString(); return result; }
/// <summary> /// This formats the persisted string to something useful for the rte so that the macro renders properly since we /// persist all macro formats like {?UMBRACO_MACRO macroAlias=\"myMacro\" /} /// </summary> /// <param name="persistedContent"></param> /// <param name="htmlAttributes">The html attributes to be added to the div</param> /// <returns></returns> /// <remarks> /// This converts the persisted macro format to this: /// /// {div class='umb-macro-holder'} /// <!-- <?UMBRACO_MACRO macroAlias=\"myMacro\" /> --> /// {ins}Macro alias: {strong}My Macro{/strong}{/ins} /// {/div} /// /// </remarks> internal static string FormatRichTextPersistedDataForEditor(string persistedContent, IDictionary<string ,string> htmlAttributes) { return MacroPersistedFormat.Replace(persistedContent, match => { if (match.Groups.Count >= 3) { //<div class="umb-macro-holder myMacro mceNonEditable"> var alias = match.Groups[2].Value; var sb = new StringBuilder("<div class=\"umb-macro-holder "); sb.Append(alias); sb.Append(" mceNonEditable\""); foreach (var htmlAttribute in htmlAttributes) { sb.Append(" "); sb.Append(htmlAttribute.Key); sb.Append("=\""); sb.Append(htmlAttribute.Value); sb.Append("\""); } sb.AppendLine(">"); sb.Append("<!-- "); sb.Append(match.Groups[1].Value.Trim()); sb.Append(" />"); sb.AppendLine(" -->"); sb.Append("<ins>"); sb.Append("Macro alias: "); sb.Append("<strong>"); sb.Append(alias); sb.Append("</strong></ins></div>"); return sb.ToString(); } //replace with nothing if we couldn't find the syntax for whatever reason return ""; }); }
public static void Main() { #if DEBUG Console.SetIn(new System.IO.StreamReader(@"../../test.020.in.txt")); Debug.Listeners.Add(new ConsoleTraceListener()); #endif Stopwatch sw = new Stopwatch(); sw.Start(); StringBuilder sb = new StringBuilder(); int lines = int.Parse(Console.ReadLine()); for (int i = 0; i < lines; i++) { string line = Console.ReadLine(); bool isValid = Validate(line); if (isValid) { sb.AppendLine("VALID"); } else { sb.AppendLine("INVALID"); } } sw.Stop(); Console.Write(sb.ToString()); Debug.WriteLine(sw.Elapsed); string bla = "asdlj"; }
static StringBuilder BuildExceptionReport(Exception e, StringBuilder sb, int d) { if (e == null) return sb; sb.AppendFormat("Exception of type `{0}`: {1}", e.GetType().FullName, e.Message); var tle = e as TypeLoadException; if (tle != null) { sb.AppendLine(); Indent(sb, d); sb.AppendFormat("TypeName=`{0}`", tle.TypeName); } else // TODO: more exception types { } if (e.InnerException != null) { sb.AppendLine(); Indent(sb, d); sb.Append("Inner "); BuildExceptionReport(e.InnerException, sb, d + 1); } sb.AppendLine(); Indent(sb, d); sb.Append(e.StackTrace); return sb; }
private static bool Validate(ExpectedPixels expectation, Bitmap actualBitmap, double expectedToActualScale, StringBuilder report) { report?.AppendLine($"{expectation.Name}:"); bool isSuccess; switch (expectation.Tolerance.OffsetKind) { case LocationToleranceKind.PerRange: isSuccess = GetLocationOffsets(expectation) .Any(offset => GetPixelCoordinates(expectation) .All(pixel => ValidatePixel(actualBitmap, expectation, expectedToActualScale, pixel, offset, report))); break; case LocationToleranceKind.PerPixel: isSuccess = GetPixelCoordinates(expectation) .All(pixel => GetLocationOffsets(expectation) .Any(offset => ValidatePixel(actualBitmap, expectation, expectedToActualScale, pixel, offset, report))); break; default: throw new ArgumentOutOfRangeException(nameof(expectation.Tolerance.OffsetKind)); } if (isSuccess) // otherwise the report has already been full-filled { report?.AppendLine("\tOK"); } return(isSuccess); }
/// <summary> /// Returns true is the conjunctive part is properly loaded. If a string builder is passed in, and problems are /// detected, a description of the problems is added to the StringBuilder. /// </summary> private bool ConjunctiveRouteProperlyLoaded(Route route, StringBuilder report = null) { #if DEBUG var result = true; foreach (var(op0, op1) in route.Operations.Pairwise()) { if (!_graph.ArcExists(op0.Id, op1.Id, -1, out var l)) { result = false; report?.AppendLine($"Arc {op0.Id} -> {op1.Id} missing."); } else if (l != op0.Runtime) { result = false; report?.AppendLine( $"Arc {op0.Id} -> {op1.Id} should have length {op0.Runtime.Show()}, but has length {l.Show()}."); } } if (result) { report?.AppendLine($"Route properly loaded."); } return(result); #endif return(true); }
private void AppendOverallStats(StringBuilder builder, CoverageData coverage) { builder.AppendLine(@" <stats>"); builder.AppendLine(string.Format(@" <srcfiles value=""{0}"" />", this.TotalSourceFiles)); builder.AppendLine(string.Format(@" <srclines value=""{0}"" />", this.TotalSourceLines)); builder.AppendLine(@" </stats>"); }
protected void Page_Load(object sender, System.EventArgs e) { Response.ContentType = "text/plain"; HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Charset = "utf-8"; HttpContext.Current.Response.AddHeader("Content-Type", "application/octet-stream"); HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + ListType + "List.txt"); StringBuilder body = new StringBuilder(); if (ListType == "White") { foreach (WhiteListItem wli in WhiteListItem.List("")) { body.AppendLine(wli.From); } } if (ListType == "Black") { foreach (BlackListItem bli in BlackListItem.List("")) { body.AppendLine(bli.From); } } HttpContext.Current.Response.Write(body); HttpContext.Current.Response.End(); }
public override void GenerateClass(StringBuilder b, int pad) { b.Append(' ', pad); b.AppendLine("public class " + Name + " : GameMessage"); b.Append(' ', pad); b.AppendLine("{"); GenerateFieldsAndFunctions(b, pad+4); b.Append(' ', pad); b.AppendLine("}"); }
public override string ToText(Subtitle subtitle, string title) { StringBuilder sb = new StringBuilder(); sb.AppendLine("#\tAppearance\tCaption\t"); sb.AppendLine(); int count = 1; for (int i = 0; i < subtitle.Paragraphs.Count; i++) { Paragraph p = subtitle.Paragraphs[i]; string text = HtmlUtil.RemoveHtmlTags(p.Text); sb.AppendLine(string.Format("{0}\t{1}\t{2}\t", count.ToString().PadLeft(5, ' '), MakeTimeCode(p.StartTime), text)); sb.AppendLine("\t\t\t\t"); Paragraph next = subtitle.GetParagraphOrDefault(i + 1); if (next == null || Math.Abs(p.EndTime.TotalMilliseconds - next.StartTime.TotalMilliseconds) > 50) { count++; sb.AppendLine(string.Format("{0}\t{1}", count.ToString().PadLeft(5, ' '), MakeTimeCode(p.EndTime))); } count++; } RichTextBox rtBox = new RichTextBox(); rtBox.Text = sb.ToString(); string rtf = rtBox.Rtf; rtBox.Dispose(); return rtf; }
public override void Compute() { TLKeyValuePairsList precision = (TLKeyValuePairsList)Workspace.Load("PrecisionData"); TLKeyValuePairsList recall = (TLKeyValuePairsList)Workspace.Load("RecallData"); TLKeyValuePairsList avgprecision = (TLKeyValuePairsList)Workspace.Load("AvgPrecisionData"); StringBuilder sb = new StringBuilder(); sb.AppendFormat("{0}\n", _config.Title); sb.AppendLine("--------------------------------------------------"); sb.AppendFormat("Precision Data:\nMin:\t{0}\nMax:\t{1}\nAvg:\t{2}\n", GetMin(precision), GetMax(precision), GetAvg(precision) ); sb.AppendLine("--------------------------------------------------"); sb.AppendFormat("Recall Data:\nMin:\t{0}\nMax:\t{1}\nAvg:\t{2}\n", GetMin(recall), GetMax(recall), GetAvg(recall) ); sb.AppendLine("--------------------------------------------------"); sb.AppendFormat("Avg Precision Data:\nMin:\t{0}\nMax:\t{1}\nAvg:\t{2}\n", GetMin(avgprecision), GetMax(avgprecision), GetAvg(avgprecision) ); sb.AppendLine("--------------------------------------------------"); /* SimpleResultsWindow window = new SimpleResultsWindow(); window.PrintToScreen(sb.ToString()); window.ShowDialog(); */ Logger.Info(sb.ToString()); }
public static async Task ShowSavedAndUploadedFileMessage(this MainWindow window, string fileName, string url) { var sb = new StringBuilder(); if(fileName != null) sb.AppendLine($"Saved to\n\"{fileName}\""); sb.AppendLine($"Uploaded to\n{url}"); var result = await window.ShowMessageAsync("", sb.ToString(), AffirmativeAndNegativeAndSingleAuxiliary, new Settings {NegativeButtonText = "open in browser", FirstAuxiliaryButtonText = "copy url to clipboard"}); if(result == MessageDialogResult.Negative) { try { Process.Start(url); } catch(Exception ex) { Logger.WriteLine("Error starting browser: " + ex, "ScreenshotMessageDialog"); } } else if(result == MessageDialogResult.FirstAuxiliary) { try { Clipboard.SetText(url); } catch(Exception ex) { Logger.WriteLine("Error copying url to clipboard: " + ex, "ScreenshotMessageDialog"); } } }
public static void Postfix(Pawn p, StringBuilder explanation, ref float __result) { if (p?.apparel?.WornApparel.NullOrEmpty() ?? true) { return; } foreach (var apparel in p.apparel.WornApparel) { var modExtension = apparel.def.GetModExtension <ApparelExtension>(); if (modExtension != null && modExtension.carryingCapacity != -1f) { if (apparel.TryGetQuality(out var cat)) { __result += modExtension.carryingCapacity * GetMutiplierForQuality(cat); explanation?.AppendLine( $"{apparel.LabelCapNoCount}: +{modExtension.carryingCapacity} * {GetMutiplierForQuality(cat)} ({cat.GetLabel()})"); } else { __result += modExtension.carryingCapacity; explanation?.AppendLine($"{apparel.LabelCapNoCount}: +{modExtension.carryingCapacity}"); } } } }
public DataTable GetPdLine(string Connection, string Starg) { string methodName = MethodBase.GetCurrentMethod().Name; BaseLog.LoggingBegin(logger, methodName); try { string SQLText = ""; StringBuilder sb = new StringBuilder(); sb.AppendLine("select substring(Line,1,1) as PdLine "); sb.AppendLine("from Line where Stage=@Stage "); sb.AppendLine("group by substring(Line,1,1) "); sb.AppendLine("order by PdLine "); SQLText = sb.ToString(); return SQLHelper.ExecuteDataFill(Connection, System.Data.CommandType.Text, SQLText, new SqlParameter("@Stage", Starg)); } catch (Exception e) { BaseLog.LoggingError(logger, MethodBase.GetCurrentMethod(), e); throw; } finally { BaseLog.LoggingEnd(logger, methodName); } }
public static void Check_Instruction_20_CCF() { StringBuilder testProgram = new StringBuilder(); // TStatesByMachineCycle = "1 (4)" testProgram.AppendLine("CCF"); // TStatesByMachineCycle = "7 (4,3)" testProgram.AppendLine("LD A,0"); // TStatesByMachineCycle = "1 (4)" testProgram.AppendLine("CCF"); // TStatesByMachineCycle = "1 (4)" testProgram.AppendLine("CCF"); TestSystem testSystem = new TestSystem(); testSystem.LoadProgramInMemory(testProgram.ToString()); CPUStateLogger logger = new CPUStateLogger(testSystem.CPU); logger.StartLogging( CPUStateLogger.CPUStateElements.InternalState | CPUStateLogger.CPUStateElements.Registers, new Z80CPU.LifecycleEventType[] { Z80CPU.LifecycleEventType.MachineCycleEnd }); testSystem.ExecuteInstructionCount(4); logger.StopLogging(); if (!logger.CompareWithSavedLog("ALU/ArithmeticGeneralPurpose/Logs/Check_Instruction_20_CCF")) { throw new Exception("Log compare failed"); } }
private static void TransformAndExplain(StatRequest req, ref float val, StringBuilder explanation) { CompReloadable compReloadable = req.Thing?.TryGetComp <CompReloadable>(); if (compReloadable != null && compReloadable.RemainingCharges != compReloadable.MaxCharges) { if (compReloadable.AmmoDef != null) { int num = compReloadable.MaxAmmoNeeded(allowForcedReload: true); float num2 = (0f - compReloadable.AmmoDef.BaseMarketValue) * (float)num; val += num2; explanation?.AppendLine("StatsReport_ReloadMarketValue".Translate(NamedArgumentUtility.Named(compReloadable.AmmoDef, "AMMO"), num.Named("COUNT")) + ": " + num2.ToStringMoneyOffset()); } else if (compReloadable.Props.destroyOnEmpty) { float num3 = (float)compReloadable.RemainingCharges / (float)compReloadable.MaxCharges; explanation?.AppendLine("StatsReport_ReloadRemainingChargesMultipler".Translate(compReloadable.Props.ChargeNounArgument, compReloadable.LabelRemaining) + ": x" + num3.ToStringPercent()); val *= num3; } if (val < 0f) { val = 0f; } } }
internal static IEnumerable <VsInstallation> FilterInstallations(IEnumerable <VsInstallation> installations, VsTestSettings settings, StringBuilder output = null) { var majorVersions = new HashSet <int>(); foreach (var installation in settings.VsPreferLowestMinorVersion == false ? installations.OrderByDescending(x => x.Version) : installations.OrderBy(x => x.Version)) { if (!settings.VsAllowPreview && installation.Name.Contains("-pre")) { output?.AppendLine($"Skipping {installation.Path} because {nameof(Xunit.VsInstanceAttribute.AllowPreview)} is set to {false}."); continue; } if (!settings.VsSupportedVersionRanges.Any(range => installation.Version >= range.Minimum && installation.Version <= range.Maximum)) { output?.AppendLine($"Skipping {installation.Path} because the version {installation.Version} is not within any specified version range {string.Join(";", settings.VsSupportedVersionRanges)}."); continue; } if (!majorVersions.Add(installation.Version.Major)) { output?.AppendLine($"Skipping {installation.Path} because an instance for the same major version has been found already."); continue; } yield return(installation); } }
public override string ToString() { StringBuilder sb = new StringBuilder(); int tabLength = 3; int namePad = Components.Max(c => c.Name.Length) + 2; int detailsPad = Components.Where(c => c.Details != null).Max(c => c.Details.Length) + 2; sb.AppendLine($"PC name: {Name}"); sb.AppendLine("Components:"); foreach (var c in Components) { sb.Append("".PadRight(tabLength)); sb.Append("Name: " + c.Name.PadRight(namePad)); if (c.Details != null) { sb.Append("Details: " + c.Details.PadRight(detailsPad)); } sb.AppendLine("Price: " + $"{c.Price:C}"); } sb.Append($"Total price: {Price:C}"); return sb.ToString(); }
/// <summary> /// Formats the given parameters to call a function. /// </summary> /// <param name="parameters">An array of parameters.</param> /// <returns>The mnemonics to pass the parameters.</returns> public string FormatParameters(IntPtr[] parameters) { // Declare a var to store the mnemonics var ret = new StringBuilder(); var paramList = new List<IntPtr>(parameters); // Store the first parameter in the ECX register if (paramList.Count > 0) { ret.AppendLine("mov ecx, " + paramList[0]); paramList.RemoveAt(0); } // Store the second parameter in the EDX register if (paramList.Count > 0) { ret.AppendLine("mov edx, " + paramList[0]); paramList.RemoveAt(0); } // For each parameters (in reverse order) paramList.Reverse(); foreach (var parameter in paramList) { ret.AppendLine("push " + parameter); } // Return the mnemonics return ret.ToString(); }
private string buildDAOMethod() { StringBuilder sb = new StringBuilder(); sb.AppendLine("public void buildDAO()"); sb.AppendLine("{"); sb.AppendLine("// bussiness logic here"); sb.AppendLine("" + qm_.TableName_ + "_Table_DAO insertDao = new " + qm_.TableName_ + "_Table_DAO();"); foreach (var item in this.qm_.ColumnList_) { string lowerItem = item.ToLower(); string upperItem = item.ToUpper(); string fus = this.FirstUpperStr(lowerItem); string s = (item.Substring(item.Length - 4, 4)).ToUpper(); if (s == "DATE") { sb.AppendLine("insertDao." + upperItem + "_ = this." + fus + "_.ToString(\"yyyyMMdd\");"); } else { sb.AppendLine("insertDao." + upperItem + "_ = this." + fus + "_;"); } } sb.AppendLine("}"); sb.AppendLine(); return sb.ToString(); }
public List<BannerNewsSiteQuery> GetList(BannerNewsSiteQuery bs, out int totalCount) { StringBuilder sqlfield = new StringBuilder(); StringBuilder sqlwhere = new StringBuilder(); StringBuilder sqlorderby = new StringBuilder(); StringBuilder sql = new StringBuilder(); sqlfield.AppendLine(@"SELECT news_site_id,news_site_sort,news_site_status,news_site_mode,news_site_name,news_site_description,news_site_createdate,news_site_updatedate,news_site_ipfrom "); sqlfield.AppendLine(@" FROM banner_news_site where news_site_status = 1 "); sql.Append(sqlfield); //sql.Append(sqlwhere); sqlorderby.AppendFormat(@" ORDER BY news_site_sort DESC "); sql.Append(sqlorderby); sql.AppendFormat(@" limit {0},{1};", bs.Start, bs.Limit); //int totalCount; totalCount = 0; try { if (bs.IsPage) { DataTable dt = _access.getDataTable("select count(*) from banner_news_site where 1=1 " + sqlwhere); totalCount = int.Parse(dt.Rows[0][0].ToString()); } return _access.getDataTableForObj<BannerNewsSiteQuery>(sql.ToString()); } catch (Exception ex) { throw new Exception("BannerNewsSiteDao-->GetList" + ex.Message + sql.ToString(), ex); } }
public void Parse(Cursor cursor) { if (String.IsNullOrEmpty(cursor.Name)) return; String enumName = cursor.Name.Substring(2).Replace("_", ""); if (enumName == "ChildVisitResult") enumName = "CursorVisitResult"; if (enumName == "CallingConv") enumName = "CallingConvention"; String filename = Path.Combine(_di.FullName, enumName + ".h"); var contents = new StringBuilder(); contents.AppendLine(Template.Template.Header); if (enumName.EndsWith("Flags")) contents.AppendLine(" [System::Flags]"); contents.Append(" public enum class "); contents.Append(enumName); contents.AppendLine(" {"); // add values _sb = contents; cursor.VisitChildren(EnumVisitor); contents.AppendLine(" };"); contents.AppendLine(Template.Template.Footer); File.WriteAllText(filename, contents.ToString()); }
public ActionResult Add(string website, string title, string desc, string keywords, int parentId = 0, string layout = "", string tmpl = "blank", string locale = "") { var web = App.Get().Webs[string.IsNullOrEmpty(website) ? "home" : website]; if (web == null) throw new HttpException("The " + website + " not found"); try { var page = App.Get().Pages.InstantiateIn(tmpl, web.Model, title, desc, keywords, parentId, string.IsNullOrEmpty(locale) ? web.DefaultLocale : locale); if (!string.IsNullOrEmpty(layout)) { page.ViewData = ""; page.ViewName = "~/views/dynamicui/layouts/layout_" + layout + ".cshtml"; page.Save(); } web.ClearCache(); return Content(page.ToJsonString(), "application/json", System.Text.Encoding.UTF8); } catch (Exception e) { var sb = new StringBuilder(); sb.AppendLine(e.Message); var etp = e.InnerException; while (etp != null) { sb.AppendLine(etp.Message); etp = etp.InnerException; } throw new HttpException(sb.ToString()); //return new HttpStatusCodeResult(500, sb.ToString()); } }
private void btnGetStats_Click(object sender, EventArgs e) { // Get the words from the e-book. string[] words = theEBook.Split(new char[] { ' ', '\u000A', ',', '.', ';', ':', '-', '?', '/' }, StringSplitOptions.RemoveEmptyEntries); string[] tenMostCommon = null; string longestWord = string.Empty; Parallel.Invoke( () => { // Now, find the ten most common words. tenMostCommon = FindTenMostCommon(words); }, () => { // Get the longest word. longestWord = FindLongestWord(words); }); // Now that all tasks are complete, build a string to show all // stats in a message box. StringBuilder bookStats = new StringBuilder("Ten Most Common Words are:\n"); foreach (string s in tenMostCommon) { bookStats.AppendLine(s); } bookStats.AppendFormat("Longest word is: {0}", longestWord); bookStats.AppendLine(); MessageBox.Show(bookStats.ToString(), "Book info"); }
public override string ToText(Subtitle subtitle, string title) { const string timeCodeFormatNoHours = "{0:00}:{1:00}.{2:000}"; // h:mm:ss.cc const string timeCodeFormatHours = "{0}:{1:00}:{2:00}.{3:000}"; // h:mm:ss.cc const string paragraphWriteFormat = "{0} --> {1}{4}{2}{3}{4}"; var sb = new StringBuilder(); sb.AppendLine("WEBVTT FILE"); sb.AppendLine(); int count = 1; foreach (Paragraph p in subtitle.Paragraphs) { string start = string.Format(timeCodeFormatNoHours, p.StartTime.Minutes, p.StartTime.Seconds, p.StartTime.Milliseconds); string end = string.Format(timeCodeFormatNoHours, p.EndTime.Minutes, p.EndTime.Seconds, p.EndTime.Milliseconds); if (p.StartTime.Hours > 0 || p.EndTime.Hours > 0) { start = string.Format(timeCodeFormatHours, p.StartTime.Hours, p.StartTime.Minutes, p.StartTime.Seconds, p.StartTime.Milliseconds); end = string.Format(timeCodeFormatHours, p.EndTime.Hours, p.EndTime.Minutes, p.EndTime.Seconds, p.EndTime.Milliseconds); } string style = string.Empty; if (!string.IsNullOrEmpty(p.Extra) && subtitle.Header == "WEBVTT FILE") style = p.Extra; sb.AppendLine(count.ToString()); sb.AppendLine(string.Format(paragraphWriteFormat, start, end, FormatText(p), style, Environment.NewLine)); count++; } return sb.ToString().Trim(); }
public override string ToString() { StringBuilder result = new StringBuilder(); result.AppendLine("Teacher name:" + base.Name); result.AppendLine("Teacher disciplines:\n" + (string.Join("\n\n", Disciplines))); return result.ToString(); }
public string ToiCalFormat() { var sb = new StringBuilder(); sb.AppendLine("BEGIN:VCALENDAR"); sb.AppendLine("PRODID:TeamLab Calendar"); sb.AppendLine("VERSION:2.0"); sb.AppendLine("METHOD:PUBLISH"); sb.AppendLine("CALSCALE:GREGORIAN"); sb.AppendLine(String.Format("X-WR-CALNAME:{0}", Name)); sb.AppendLine(String.Format("X-WR-TIMEZONE:{0}", OlsenTimeZoneConverter.TimeZoneInfo2OlsonTZId(TimeZone))); //tz sb.AppendLine("BEGIN:VTIMEZONE"); sb.AppendLine(String.Format("TZID:{0}", OlsenTimeZoneConverter.TimeZoneInfo2OlsonTZId(TimeZone))); sb.AppendLine("END:VTIMEZONE"); //events foreach (var e in LoadEvents(SecurityContext.CurrentAccount.ID, DateTime.MinValue, DateTime.MaxValue)) { if (e is BaseEvent && e.GetType().GetCustomAttributes(typeof(AllDayLongUTCAttribute),true).Length==0) (e as BaseEvent).TimeZone = TimeZone; sb.AppendLine(e.ToiCalFormat()); } sb.Append("END:VCALENDAR"); return sb.ToString(); }
public override string ToText(Subtitle subtitle, string title) { var sb = new StringBuilder(); sb.AppendLine(title); sb.AppendLine(@"1ab 23/03/2012 03/05/2012 **:**:**.** 01:00:00.00 **:**:**.** **:**:**.** 01:01:01.12 01:02:30.00 01:02:54.01 **:**:**.** **:**:**.** 01:19:33.08 "); int count = 1; foreach (Paragraph p in subtitle.Paragraphs) { sb.AppendLine(string.Format("{0}: {1} {2}\r\n{3}", count.ToString(CultureInfo.InvariantCulture).PadLeft(9, ' '), MakeTimeCode(p.StartTime), MakeTimeCode(p.EndTime), p.Text)); count++; } var rtBox = new System.Windows.Forms.RichTextBox { Text = sb.ToString().Trim() }; return rtBox.Rtf; }
//public class RoadComposer : List<Vector3> //{ //} public static IEnumerable <Road> CreateRoad(this List <PathNode> points, StringBuilder builder) { if (points.IsNullOrEmpty()) { builder?.AppendLine($"\tskipped..."); yield break; // This chunk doesn't contain any road. Exiting. } //var dict = points.Select(p => new {Index = p.GetKey(), Point = p}).ToDictionary(x => x.Index, x => x.Point); //var builder = new StringBuilder(); var roads = GetRoads(points, builder).ToList(); foreach (var list in roads) { if (list.IsNullOrEmpty()) { continue; } //var first = road.First(); //var backIndex = ((Point)CityGenerator.SConv.GetRealPositionOnMap(first)).GetKey(); var road = CreateIndependantRoad(list); if (road == null) { continue; } builder?.AppendLine($"\t... finished road ({road.name}) with {list.Count} nodes."); yield return(road); } //Debug.Log(builder?.ToString()); }
public override string ToString() { String s = null; switch (ChangeType) { case FileChangeType.Create: s = "Create:"; break; case FileChangeType.Delete: s = "Delete:"; break; case FileChangeType.Rename: s = "Rename:"; break; case FileChangeType.Update: s = "Update"; break; } StringBuilder sb = new StringBuilder(); sb.AppendLine(s); sb.AppendLine("Source: " + base.From); sb.AppendLine("Destination: " + base.To); //sb.Append(s + " Source: " + base.From + " Destination: " + base.To); return sb.ToString(); }
public string BuildHookSnippet(Hook hook) { StringBuilder builder = new StringBuilder(); builder.Append($"function {hook.Parent}:{hook.Name}("); if (hook.Args != null && hook.Args.Count > 0) { for (int i = 0; i < hook.Args.Count; i++) builder.Append($"${{{i + 1}:{hook.Args[i].Type} {hook.Args[i].Name}{(hook.Args[i].Default != "" ? "=" + hook.Args[i].Default : "")}}},"); builder.Length--; } builder.AppendLine(")"); builder.Append(" "); if (hook.ReturnValues != null && hook.ReturnValues.Count > 0) { builder.Append("return "); for (int i = 0; i < hook.ReturnValues.Count; i++) builder.Append($"${{{i + 1 + hook.Args?.Count ?? 0}:{hook.ReturnValues[i].Type}}},"); builder.Length--; } else builder.Append($"${{{hook.Args?.Count + 1 ?? 1}:-- body}}"); builder.AppendLine(); builder.Append("end"); return builder.ToString(); }
private void btnBrowser_Click(object sender, EventArgs e) { string s = txtCharOrString.Text; StringBuilder sbResult = new StringBuilder(); int i16; byte[] array = System.Text.Encoding.Default.GetBytes(s); for (int i = 0; i < array.Length; i++) { if (array[i] >= 128 && array[i] <= 247) { sbResult.Append(System.Text.Encoding.Default.GetString(array, i, 2)); i16 = int.Parse(array[i].ToString("X2") + array[i + 1].ToString("X2"), System.Globalization.NumberStyles.HexNumber); sbResult.AppendLine(string.Format(" 高字节:{0},低字节:{1},机内码:{2}", array[i], array[i + 1], i16)); i++; } else { sbResult.Append(System.Text.Encoding.Default.GetString(array, i, 1)); sbResult.AppendLine(string.Format(" ASCII:{0}" , array[i])); } } txtResult.Text = sbResult.ToString(); }
public List<Entities.AutoMerge> Execute(out int total, int pageSize = -1, int pageNumber = -1) { List<Entities.AutoMerge> merges = new List<Entities.AutoMerge>(); StringBuilder query = new StringBuilder(); if(pageSize == -1 || pageNumber == -1) { query.AppendLine("SELECT * FROM [dbo].[AutoMerge]"); } else { query.AppendLine("SELECT * FROM [dbo].[AutoMerge] ORDER BY [Id] OFFSET (@pageSize * (@pageNumber - 1)) ROWS FETCH NEXT @pageSize ROWS ONLY"); } query.AppendLine("SELECT COUNT([Id]) FROM [dbo].[AutoMerge]"); using (IDbConnection connection = database.CreateConnection()) { using (var multi = connection.QueryMultiple(query.ToString(), new { pageNumber, pageSize })) { merges = multi.Read<Entities.AutoMerge>().ToList(); total = multi.Read<int>().First(); } } return merges; }
private string GetICSString(DateTime date, int duration, string name, string location, string shortDescription) { var sb = new StringBuilder(); sb.AppendLine("BEGIN:VCALENDAR"); sb.AppendLine("VERSION:1.0"); sb.AppendLine("BEGIN:VEVENT"); sb.AppendFormat("DTSTART:{0}", GetFormattedTime(date)); sb.AppendLine(); sb.AppendFormat("DTEND:{0}", GetFormattedTime(date.AddMinutes(duration))); sb.AppendLine(); sb.AppendFormat("SUMMARY:{0}", name); sb.AppendLine(); sb.AppendFormat("LOCATION:{0}", location); sb.AppendLine(); string description = shortDescription; if (description.IsEmpty()) { description = name; } sb.AppendFormat("DESCRIPTION:{0}", description.Replace(Environment.NewLine, " ")); sb.AppendLine(); sb.AppendLine("END:VEVENT"); sb.AppendLine("END:VCALENDAR"); return sb.ToString(); }
public override string Process(string input) { int totala1 = 0; int totala0 = 0; int totala26 = 0; int totala25 = 0; input = input.ToLower(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < input.Length; i++) { int pos = ROTATIONTABLE.IndexOf(input[i]); if (pos >= 0) { totala1 += (pos + 1); totala0 += pos; totala26 += 26 - pos; totala25 += 26 - pos - 1; } } sb.AppendLine(string.Format("a=0...z=25: {0}", totala0)); sb.AppendLine(string.Format("a=1...z=26: {0}", totala1)); sb.AppendLine(string.Format("a=25...z=0: {0}", totala25)); sb.AppendLine(string.Format("a=26...z=1: {0}", totala26)); sb.AppendLine(string.Format("{0}: {1}", Utils.LanguageSupport.Instance.GetTranslation(STR_WORDLENGTHSPACE), input.Replace("r", "").Replace("\n", "").Length)); sb.AppendLine(string.Format("{0}: {1}", Utils.LanguageSupport.Instance.GetTranslation(STR_WORDLENGTHNOSPACE), input.Replace(" ", "").Replace("\t", "").Replace("r", "").Replace("\n", "").Length)); return sb.ToString(); }
public DataTable GetModel(string DBConnection, IList<String> PdLine, DateTime From, DateTime To) { DataTable Result = null; string selectSQL = ""; string groupbySQL = ""; groupbySQL += "GROUP by b.Descr"; string orderbySQL = "ORDER BY b.Descr"; StringBuilder sb = new StringBuilder(); //sb.AppendLine("WITH [TEMP] AS ("); sb.AppendLine(" select distinct b.Descr as Family from PCBLog a inner join Part b on a.PCBModel=b.PartNo "); //sb.AppendLine("INNER JOIN PCB b ON a.PCBNo = b.PCBNo AND e.PartNo = b.PCBModelID "); sb.AppendLine("WHERE a.Cdt Between @StartTime AND @EndTime and b.BomNodeType='MB' "); if (PdLine.Count > 0) { sb.AppendFormat("AND a.Line in ('{0}') ", string.Join("','", PdLine.ToArray())); } sb.AppendFormat("{0} ", groupbySQL); sb.AppendFormat("{0} ", orderbySQL); Result = SQLHelper.ExecuteDataFill(DBConnection, System.Data.CommandType.Text, sb.ToString(), new SqlParameter("@StartTime", From), new SqlParameter("@EndTime", To)); return Result; }
public UnityEngine.Material CreateMaterial(PbrMaterial vpxMaterial, TableBehavior table, StringBuilder debug = null) { var unityMaterial = new UnityEngine.Material(GetShader()) { name = vpxMaterial.Id }; // apply some basic manipulations to the color. this just makes very // very white colors be clipped to 0.8204 aka 204/255 is 0.8 // this is to give room to lighting values. so there is more modulation // of brighter colors when being lit without blow outs too soon. var col = vpxMaterial.Color.ToUnityColor(); if (vpxMaterial.Color.IsGray() && col.grayscale > 0.8) { debug?.AppendLine("Color manipulation performed, brightness reduced."); col.r = col.g = col.b = 0.8f; } // alpha for color depending on blend mode ApplyBlendMode(unityMaterial, vpxMaterial.MapBlendMode); if (vpxMaterial.MapBlendMode == BlendMode.Translucent) { col.a = Mathf.Min(1, Mathf.Max(0, vpxMaterial.Opacity)); } unityMaterial.SetColor(BaseColor, col); // validate IsMetal. if true, set the metallic value. // found VPX authors setting metallic as well as translucent at the // same time, which does not render correctly in unity so we have // to check if this value is true and also if opacity <= 1. if (vpxMaterial.IsMetal && (!vpxMaterial.IsOpacityActive || vpxMaterial.Opacity >= 1)) { unityMaterial.SetFloat(Metallic, 1f); debug?.AppendLine("Metallic set to 1."); } // roughness / glossiness unityMaterial.SetFloat(Smoothness, vpxMaterial.Roughness); // map if (table != null && vpxMaterial.HasMap) { unityMaterial.SetTexture(BaseMap, table.GetTexture(vpxMaterial.Map.Name)); } // normal map if (table != null && vpxMaterial.HasNormalMap) { unityMaterial.EnableKeyword("_NORMALMAP"); unityMaterial.SetTexture(BumpMap, table.GetTexture(vpxMaterial.NormalMap.Name) ); } return(unityMaterial); }
public static void AppendLine(string message) { LogBuffer?.AppendLine(message); if (!IsQuiet) { Console.WriteLine(message); } }
static bool Validate(string license_str, BigInteger mod, BigInteger exp, StringBuilder log) { var blob = LicenseBlob.Deserialize(license_str); log?.AppendLine("---------------------------------------------"); log?.AppendLine("Parsed info: " + blob.Fields().ToString()); log?.AppendLine("Plaintext hash: " + BitConverter.ToString(new SHA512Managed().ComputeHash(blob.Data())).ToLower().Replace("-", "")); return(blob.VerifySignature(new[] { new RSADecryptPublic(mod, exp) }, log)); }
public static byte[] CreateSelfSignedCertificate(string commonNameValue, string issuerName, StringBuilder log = null) { CreateCertificateAuthorityCertificate(commonNameValue + " CA", out var ca, out var caSubjectName, log); CreateSelfSignedCertificateBasedOnPrivateKey(commonNameValue, caSubjectName, ca, false, false, 0, out var certBytes, log); var selfSignedCertificateBasedOnPrivateKey = new X509Certificate2(certBytes); log?.AppendLine($"Successfully loaded X509Certificate2 using certBytes with length: {certBytes.Length} "); selfSignedCertificateBasedOnPrivateKey.Verify(); log?.AppendLine($"Successfully verified chain for X509Certificate2: {Environment.NewLine}{selfSignedCertificateBasedOnPrivateKey}"); return(certBytes); }
private int CompareBodies(byte[] requestBody, byte[] responseBody, StringBuilder descriptionBuilder = null) { if (!_compareBodies) { return(0); } if (requestBody == null && responseBody == null) { return(0); } if (requestBody == null) { descriptionBuilder?.AppendLine("Request has body but response doesn't"); return(1); } if (responseBody == null) { descriptionBuilder?.AppendLine("Response has body but request doesn't"); return(1); } if (!requestBody.SequenceEqual(responseBody)) { if (descriptionBuilder != null) { var minLength = Math.Min(requestBody.Length, responseBody.Length); int i; for (i = 0; i < minLength - 1; i++) { if (requestBody[i] != responseBody[i]) { break; } } descriptionBuilder.AppendLine($"Request and response bodies do not match at index {i}:"); var before = Math.Max(0, i - 10); var afterRequest = Math.Min(i + 20, requestBody.Length); var afterResponse = Math.Min(i + 20, responseBody.Length); descriptionBuilder.AppendLine($" request: \"{Encoding.UTF8.GetString(requestBody, before, afterRequest - before)}\""); descriptionBuilder.AppendLine($" record: \"{Encoding.UTF8.GetString(responseBody, before, afterResponse - before)}\""); } return(1); } return(0); }
/// <summary> /// Parses the Path data string and converts it to CanvasGeometry. /// </summary> /// <param name="resourceCreator">ICanvasResourceCreator</param> /// <param name="pathData">Path data</param> /// <param name="logger">(Optional) For logging purpose. To log the set of /// CanvasPathBuilder commands, used for creating the CanvasGeometry, in /// string format.</param> /// <returns>CanvasGeometry</returns> public static CanvasGeometry CreateGeometry(ICanvasResourceCreator resourceCreator, string pathData, StringBuilder logger = null) { // Log command logger?.AppendLine("using (var pathBuilder = new CanvasPathBuilder(resourceCreator))"); logger?.AppendLine("{"); // Get the CanvasGeometry from the path data var geometry = CanvasGeometryParser.Parse(resourceCreator, pathData, logger); // Log command logger?.AppendLine("}"); return(geometry); }
private bool CompareList(string depth, IList from, IList to, StringBuilder builder) { var fromCount = from.Count; var toCount = to.Count; var changed = false; var shared = Math.Min(fromCount, toCount); var i = 0; foreach (var item in from) { if (i >= shared) { break; } var toItem = to[i]; //compare items if (CompareObject(depth + "[" + i + "]", item, toItem, builder)) { changed = true; } ++i; } if (from.Count > to.Count) { //removed last in from for (int j = shared; j < from.Count; j++) { builder?.Append(depth + "[" + j + "] removed: "); PrintObject(from[j], builder); builder?.AppendLine(); } changed = true; } else { //added last in to for (int j = shared; j < to.Count; j++) { builder?.Append(depth + "[" + j + "] added: "); PrintObject(to[j], builder); builder?.AppendLine(); } changed = true; } return(changed); }
internal void Execute() { try { InitParameter(); TryReloadDataAncCheck(); Pretreatment(); SpeculatePreferredPosition(); PredictLayout(); FreeTemp(); WriteOutResult(); } catch (Exception e) { Builder?.AppendLine($"{nameof(DateTime)} : {DateTime.Now}") .AppendLine(e.Message) .AppendLine(e.StackTrace); } finally { SpriteColorContainer?.Clear(); if (Builder != null) { File.WriteAllText($"{InfoDataFile.FullName}.log", Builder.ToString()); } } }
private async Task ReadStreamAsync( StreamReader source, TextWriter?writer, ICollection <string>?output1, ICollection <string>?output2, Action <string>?onOutput1, Action <string>?onOutput2, StringBuilder?outputBuilder1, StringBuilder?outputBuilder2) { try { string?line; while ((line = await source.ReadLineAsync()) != null) { writer?.WriteLine(line); lock (this.outputLockObject) { output1?.Add(line); output2?.Add(line); onOutput1?.Invoke(line); onOutput2?.Invoke(line); outputBuilder1?.AppendLine(line); outputBuilder2?.AppendLine(line); } } } catch { } }
/// <summary> /// /// </summary> /// <param name="builder"></param> /// <param name="condition"></param> /// <param name="text"></param> public static void AppendLineIf(this StringBuilder builder, bool condition, string text) { if (condition) { builder?.AppendLine(text); } }
/// <summary> /// Adds the Path Element to the Path. /// </summary> /// <param name="pathBuilder">CanvasPathBuilder object</param> /// <param name="currentPoint">The last active location in the Path before adding /// the Path Element</param> /// <param name="lastElement">The previous PathElement in the Path.</param> /// <param name="logger">For logging purpose. To log the set of CanvasPathBuilder /// commands, used for creating the CanvasGeometry, in string format.</param> /// <returns>The latest location in the Path after adding the Path Element</returns> public override Vector2 CreatePath(CanvasPathBuilder pathBuilder, Vector2 currentPoint, ref ICanvasPathElement lastElement, StringBuilder logger) { // Calculate coordinates var controlPoint = new Vector2(_x1, _y1); var point = new Vector2(_x, _y); if (IsRelative) { controlPoint += currentPoint; point += currentPoint; } // Save the absolute control point so that it can be used by the following // SmoothQuadraticBezierElement (if any) _absoluteControlPoint = controlPoint; // Execute command pathBuilder.AddQuadraticBezier(controlPoint, point); // Log command logger?.Append($"{Indent}pathBuilder.AddQuadraticBezier(new Vector2({controlPoint.X}, {controlPoint.Y})"); logger?.AppendLine($", new Vector2({point.X}, {point.Y}));"); // Set Last Element lastElement = this; // Return current point return(point); }
private void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine) { if (string.IsNullOrWhiteSpace(outLine.Data)) { return; } _log?.AppendLine(outLine.Data); var match = FrameFinderRegex.Match(outLine.Data); if (!match.Success) { return; } var arr = match.Value.Split('='); if (arr.Length != 2) { return; } if (long.TryParse(arr[1].Trim(), out var f)) { _processedFrames = f; } }
public static IProblem RemoveRedundantOperations(this IProblem problem, StringBuilder getReport = null) { Stopwatch sw = Stopwatch.StartNew(); int mergeCounter = 0; int OpCount() => problem.Jobs .SelectMany(j => j.Routes) .SelectMany(r => r.Operations) .Count(); var result = new ModifiedIProblem( problem.Jobs.Select( j => new ModifiedIJob(j.Routes.Select( r => new ModifiedIRoute( r.RoutingPenalty, r.Operations.RemoveRedundantOperations(ref mergeCounter).ToArray())) .ToArray())) .ToArray(), problem.Objective, problem.ProblemName); getReport? .AppendLine($"----------------- Report: Removing redundant operations. -----------------") .Append($"# operation redundant = {mergeCounter} ") .AppendLine( $"(total {OpCount(),6} operations, {Math.Round(100.0 * mergeCounter / OpCount()),4}%)") .AppendLine($"Simplification took {Math.Round(sw.ElapsedMilliseconds / 1000.0, 2)} sec.") .AppendLine("------------------ End Report ------------------"); return(result); }
public static void PostprocessLogFile(string srcName, string trgName, StringBuilder outputBuffer) { if (!WaitForFileAccess(srcName, FileAccess.Read)) { throw new InvalidOperationException("The source file can not be opened: " + srcName); } var sSrc = File.Open(srcName, FileMode.Open, FileAccess.Read, FileShare.Read); var sTrg = File.Open(trgName, FileMode.Create, FileAccess.Write, FileShare.None); using (var rSrc = new StreamReader(sSrc, Encoding.UTF8)) using (var wTrg = new StreamWriter(sTrg, Encoding.UTF8)) { var firstLine = rSrc.ReadLine(); // assuming the first line is the separator of the powershell transcript var line = firstLine; var separatorCount = 0; while (line != null) { if (string.Equals(line, firstLine)) { separatorCount++; } else if (separatorCount == 2) { wTrg.WriteLine(line); outputBuffer?.AppendLine(line); } line = rSrc.ReadLine(); } } }
/// <summary> /// Appends a copy of the specified string to this instance indenting every line by specified value. /// </summary> /// <param name="builder">The StringBuilder object.</param> /// <param name="text">The string to append.</param> /// <param name="indentLevel">Indentation level (multiples of 4).</param> public static void Append(this StringBuilder builder, string text, int indentLevel) { foreach (string line in text.GetLines(false)) { builder?.Append(' ', indentLevel * 4); builder?.AppendLine(line); } }
private void ReadData(byte[] payload) { try { _data?.AppendLine(Encoding.UTF8.GetString(payload)); } catch { } }
/// <summary> /// Parses the Path data string and converts it to CanvasGeometry. /// </summary> /// <param name="pathData">Path data</param> /// <param name="logger">(Optional) For logging purpose. To log the set of /// CanvasPathBuilder commands, used for creating the CanvasGeometry, in /// string format.</param> /// <returns>CanvasGeometry</returns> public static CanvasGeometry CreateGeometry(string pathData, StringBuilder logger = null) { using (new CultureShield("en-US")) { // Log command logger?.AppendLine("using (var pathBuilder = new CanvasPathBuilder(null))"); logger?.AppendLine("{"); // Get the CanvasGeometry from the path data var geometry = CanvasGeometryParser.Parse(null, pathData, logger); // Log command logger?.AppendLine("}"); return(geometry); } }
/// <summary> /// Called when the using() is completed. Close the tag if we're displaying text. /// </summary> public void Dispose() { if (Display) { SB?.AppendLine($"[/spoiler]"); } SB = null; }
public string RegenerateOrders() { var stolon = GetCurrentStolon(); var consumersBills = _context.ConsumerBills .Include(x => x.AdherentStolon) .Include(x => x.AdherentStolon.Adherent) .Include(x => x.AdherentStolon.Stolon) .Where(x => x.State == BillState.Pending && x.AdherentStolon.StolonId == stolon.Id) .OrderBy(x => x.AdherentStolon.Adherent.Id) .ToList(); var producersBills = _context.ProducerBills .Include(x => x.AdherentStolon) .Include(x => x.AdherentStolon.Adherent) .Include(x => x.AdherentStolon.Stolon) .Where(x => x.State != BillState.Paid && x.AdherentStolon.StolonId == stolon.Id) .OrderBy(x => x.AdherentStolon.Adherent.Id) .ToList(); var weekStolonBill = _context.StolonsBills .Include(x => x.Stolon) .Where(x => x.StolonId == stolon.Id) .ToList() .FirstOrDefault(x => x.BillNumber.EndsWith(DateTime.Now.Year + "_" + DateTime.Now.GetIso8601WeekOfYear())); DateTime start = DateTime.Now; StringBuilder report = new StringBuilder(); report.Append("Rapport de génération des commandes : "); report.AppendLine("- stolon : " + stolon.Label); report.AppendLine("- année : " + DateTime.Now.Year); report.AppendLine("- semaine : " + DateTime.Now.GetIso8601WeekOfYear()); report.AppendLine(); Dictionary <ConsumerBill, bool> consumers = new Dictionary <ConsumerBill, bool>(); consumersBills.ForEach(x => consumers.Add(x, BillGenerator.GenerateBillPDF(x))); Dictionary <ProducerBill, bool> producers = new Dictionary <ProducerBill, bool>(); producersBills.ForEach(x => producers.Add(x, BillGenerator.GenerateOrderPDF(x))); bool stolonBill = BillGenerator.GeneratePDF(weekStolonBill.HtmlBillContent, weekStolonBill.FilePath); report.AppendLine("RESUME : "); report.AppendLine("Commandes consomateurs générées : " + consumers.Count(x => x.Value == true) + "/" + consumers.Count); report.AppendLine("Commandes producteurs générées : " + producers.Count(x => x.Value == true) + "/" + producers.Count); report.AppendLine("Commandes stolons générées : " + stolonBill); report.AppendLine("DETAILS : "); report.AppendLine("-- Consomateurs ok : "); consumers.Where(x => x.Value).ToList().ForEach(consumer => report.AppendLine(consumer.Key.AdherentStolon.LocalId + " " + consumer.Key.AdherentStolon.Adherent.Name.ToUpper() + " " + consumer.Key.AdherentStolon.Adherent.Surname)); report.AppendLine("-- Consomateurs nok : "); consumers.Where(x => x.Value == false).ToList().ForEach(consumer => report.AppendLine(consumer.Key.AdherentStolon.LocalId + " " + consumer.Key.AdherentStolon.Adherent.Name.ToUpper() + " " + consumer.Key.AdherentStolon.Adherent.Surname)); report.AppendLine("-- Producteurs ok : "); producers.Where(x => x.Value).ToList().ForEach(producer => report.AppendLine(producer.Key.AdherentStolon.LocalId + " " + producer.Key.AdherentStolon.Adherent.Name.ToUpper() + " " + producer.Key.AdherentStolon.Adherent.Surname)); report.AppendLine("-- Producteurs nok : "); producers.Where(x => x.Value == false).ToList().ForEach(producer => report.AppendLine(producer.Key.AdherentStolon.LocalId + " " + producer.Key.AdherentStolon.Adherent.Name.ToUpper() + " " + producer.Key.AdherentStolon.Adherent.Surname)); report.AppendLine(); report?.AppendLine(" --Temps d'execution de la génération : " + (DateTime.Now - start)); return(report.ToString()); }
static bool Test_Generic(StringBuilder log) { log?.AppendLine("Generic license decryption self-test"); var exp = BigInteger.Parse("65537"); var mod = BigInteger.Parse("28178177427582259905122756905913963624440517746414712044433894631438407111916149031583287058323879921298234454158166031934230083094710974550125942791690254427377300877691173542319534371793100994953897137837772694304619234054383162641475011138179669415510521009673718000682851222831185756777382795378538121010194881849505437499638792289283538921706236004391184253166867653735050981736002298838523242717690667046044130539971131293603078008447972889271580670305162199959939004819206804246872436611558871928921860176200657026263241409488257640191893499783065332541392967986495144643652353104461436623253327708136399114561"); var license_str = "localhost:RG9tYWluOiBsb2NhbGhvc3QKT3duZXI6IEV2ZXJ5b25lCklzc3VlZDogMjAxNS0wMy0yOFQwOTozNjo1OVoKRmVhdHVyZXM6IFI0RWxpdGUgUjRDcmVhdGl2ZSBSNFBlcmZvcm1hbmNlCg==:h6D+kIXbF3qmvmW2gDpb+b4gdxBjnrkZLvSzXmEnqKAywNJNpTdFekpTOB4SwU14WbTeVyWwvFngHax7WuHBV+0WkQ5lDqKFaRW32vj8CJQeG8Wvnyj9PaNGaS/FpKhNjZbDEmh3qqirBp2NR0bpN4QbhP9NMy7+rOMo0nynAruwWvJKCnuf7mWWdb9a5uTZO9OUcSeS/tY8QaNeIhaCnhPe0Yx9qvOXe5nMnl10CR9ur+EtS54d1qzBGHqN/3oFhiB+xlqNELwz23qR4c8HxbTEyNarkG4CZx8CbbgJfHmPxAYGJTTBTPJ+cdah8MJR16Ta36cRZ2Buy8XYo/nf1g=="; return(Validate(license_str, mod, exp, log)); }
public static StringBuilder AppendLineFormat([CanBeNull] this StringBuilder builder, [NotNull] string format, [NotNull][ItemCanBeNull] params object[] arguments) { Contract.Requires(format != null); Contract.Requires(arguments != null); builder?.AppendFormat(format, arguments); builder?.AppendLine(); return(builder); }
/// <summary> /// Constructor. Initialize required values so we know what and whether /// to display the spoiler tags. /// </summary> /// <param name="sb">The string builder that the text will be added to.</param> /// <param name="label">The label for the spoiler. No spoiler will be displayed if it's null.</param> /// <param name="display">Whether we should display the text.</param> internal Spoiler(StringBuilder sb, string label, bool display) { SB = sb; Display = display && label != null; if (Display) { sb?.AppendLine($"[spoiler=\"{label}\"]"); } }
bool RetryLoad(XmlDocument dom, string filename, string backupFileName, StringBuilder debugInfo) { if (File.Exists(backupFileName)) { // 尝试从备份文件装载 try { dom.Load(backupFileName); _changed = true; debugInfo?.AppendLine($"尝试从临时文件 {backupFileName} 装载,成功"); return(true); } catch (Exception ex) { debugInfo?.AppendLine($"尝试从临时文件 {backupFileName} 装载,失败: {ex.Message}"); } } // 2021/9/8 var back_file = GetNewestBackupFilename(filename); if (string.IsNullOrEmpty(back_file) == false) { // 尝试从备份文件装载 try { dom.Load(back_file); _changed = true; debugInfo?.AppendLine($"尝试从备份文件 {back_file} 装载,成功"); return(true); } catch (Exception ex) { debugInfo?.AppendLine($"尝试从备份文件 {back_file} 装载,失败: {ex.Message}"); throw ex; } } return(false); }
public static void LogInformation(string message, ILogger log, TaskLogger taskLogger, IDictionary <string, string> variables, StringBuilder syncLogger, bool alwaysLog = false) { if (alwaysLog || IsDebugEnabled(variables)) { taskLogger?.Log(message).ConfigureAwait(false); syncLogger?.AppendLine(message); } log.LogInformation(message); }