System.Text.StringBuilder.Append(char)

Here are the examples of the csharp api System.Text.StringBuilder.Append(char) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

8245 Examples 7

19 View Source File : Helpers.cs
License : MIT License
Project Creator : Aminator

public static string ToPascalCase(string name)
        {
            if (name.Contains(" ") || name.Contains("_") || name == name.ToUpper())
            {
                var words = name.ToLower().Split(' ', '_');

                StringBuilder sb = new StringBuilder();

                foreach (string word in words)
                {
                    sb.Append(char.ToUpper(word[0]));
                    sb.Append(word.Substring(1));
                }

                return sb.ToString();
            }
            else
            {
                return char.ToUpper(name[0]) + name.Substring(1);
            }
        }

19 View Source File : CheckForUpdates.cs
License : Apache License 2.0
Project Creator : AmpScm

public override void OnExecute(CommandEventArgs e)
        {
            if (e.Argument != null)
            {
                ShowUpdate(e);
                return;
            }

            int interval = 24 * 6; // 6 days
            IAnkhConfigurationService config = e.GetService<IAnkhConfigurationService>();

            if (config.Instance.DisableUpdateCheck)
                return;

            using (RegistryKey rk = config.OpenUserInstanceKey("UpdateCheck"))
            {
                object value = rk.GetValue("Interval");

                if (value is int)
                {
                    interval = (int)value;

                    if (interval <= 0)
                        return;
                }
            }

            Version version = GetCurrentVersion(e.Context);
            Version osVersion = Environment.OSVersion.Version;

            StringBuilder sb = new StringBuilder();
            sb.Append("http://svc.ankhsvn.net/svc/");
            if (IsDevVersion())
                sb.Append("dev/");
            sb.Append("update-info/");
            sb.Append(version.ToString(2));
            sb.Append(".xml");
            sb.Append("?av=");
            sb.Append(version);
            sb.Append("&vs=");
            sb.Append(VSVersion.FullVersion);
            sb.Append("&os=");
            sb.Append(osVersion);

            if (IsDevVersion())
                sb.Append("&dev=1");

            sb.AppendFormat(CultureInfo.InvariantCulture, "&iv={0}", interval);
            int x = 0;
            // Create some hashcode that is probably constant and unique for all users
            // using the same IP address, but not translatable to a single user
            try
            {
                foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
                {
                    string type = ni.NetworkInterfaceType.ToString();

                    if (type.Contains("Ethernet") || type.Contains("Wireless"))
                        x ^= ni.GetPhysicalAddress().GetHashCode();
                }
            }
            catch { }

            sb.AppendFormat(CultureInfo.InvariantCulture, "&xx={0}&pc={1}", x, Environment.ProcessorCount);

            try
            {
                using (RegistryKey rk = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\NET Framework Setup\\NDP"))
                {
                    if (rk != null)
                    {
                        sb.Append("&dn=");
                        Regex re = new Regex("^[vV]([0-9]+\\.[0-9]+)(\\.[0-9]+)*", RegexOptions.Singleline);
                        bool first = true;
                        HybridCollection<string> vers = new HybridCollection<string>();

                        foreach (string s in rk.GetSubKeyNames())
                        {
                            Match m = re.Match(s);

                            if (m.Success)
                            {
                                string v = m.Groups[1].Value;

                                if (vers.Contains(v))
                                    continue;

                                vers.Add(v);

                                if (first)
                                    first = false;
                                else
                                    sb.Append(',');

                                sb.Append(v);
                            }
                        }
                    }
                }
            }
            catch
            { }

            WebRequest wr;
            try
            {
                wr = WebRequest.Create(new Uri(sb.ToString()));
            }
            catch (System.Configuration.ConfigurationException)
            {
                // The global .Net or Visual Studio configuration probably contains an invalid (proxy) configuration
                return; // Not our problem
            }

            HttpWebRequest hwr = wr as HttpWebRequest;

            if (hwr != null)
            {
                hwr.AllowAutoRedirect = true;
                hwr.AllowWriteStreamBuffering = true;
                hwr.UserAgent = string.Format("AnkhSVN/{0} VisualStudio/{1} Windows/{2}", version, VSVersion.FullVersion, osVersion);
            }

            try
            {
                wr.BeginGetResponse(OnResponse, wr);
            }
            catch (NotSupportedException)
            { /* Raised when an invalid proxy server setting is set */ }
        }

19 View Source File : ItemIgnore.cs
License : Apache License 2.0
Project Creator : AmpScm

private static void AddIgnores(IAnkhServiceProvider context, string path, List<string> ignores)
        {
            try
            {
                context.GetService<IProgressRunner>().RunModal(CommandStrings.IgnoreCaption,
                    delegate(object sender, ProgressWorkerArgs e)
                    {
                        SvnGetPropertyArgs pa = new SvnGetPropertyArgs();
                        pa.ThrowOnError = false;
                        SvnTargetPropertyCollection tpc;
                        if (e.Client.GetProperty(path, SvnPropertyNames.SvnIgnore, pa, out tpc))
                        {
                            SvnPropertyValue pv;
                            if (tpc.Count > 0 && null != (pv = tpc[0]) && pv.StringValue != null)
                            {
                                int n = 0;
                                foreach (string oldItem in pv.StringValue.Split('\n'))
                                {
                                    string item = oldItem.TrimEnd('\r');

                                    if (item.Trim().Length == 0)
                                        continue;

                                    // Don't add duplicates
                                    while (n < ignores.Count && ignores.IndexOf(item, n) >= 0)
                                        ignores.RemoveAt(ignores.IndexOf(item, n));

                                    if (ignores.Contains(item))
                                        continue;

                                    ignores.Insert(n++, item);
                                }
                            }

                            StringBuilder sb = new StringBuilder();
                            bool next = false;
                            foreach (string item in ignores)
                            {
                                if (next)
                                    sb.Append('\n'); // Subversion wants only newlines
                                else
                                    next = true;

                                sb.Append(item);
                            }

                            e.Client.SetProperty(path, SvnPropertyNames.SvnIgnore, sb.ToString());
                        }
                    });

                // Make sure a changed directory is visible in the PC Window
                context.GetService<IFileStatusMonitor>().ScheduleMonitor(path); 
            }
            finally
            {
                // Ignore doesn't bubble
                context.GetService<ISvnStatusCache>().MarkDirtyRecursive(path);
            }
        }

19 View Source File : BinaryDiffLines.cs
License : Apache License 2.0
Project Creator : AmpScm

private string GetLineString(Stream S, int iLength)
        {
            //The magic number 3 appears in this method because each
            //byte takes two hex characters plus a space after it.

            StringBuilder sbHex = new StringBuilder(iLength * 3);
            StringBuilder sbChars = new StringBuilder(iLength);

            for (int i = 0; i < iLength; i++)
            {
                int iByte = S.ReadByte();
                if (iByte == -1)
                {
                    sbHex.Append("   ");
                }
                else
                {
                    byte by = (byte)iByte;
                    sbHex.AppendFormat("{0:X2} ", by);
                    char ch = (char)by;
                    sbChars.Append(char.IsControl(ch) ? '.' : ch);
                }
            }

            while (sbHex.Length < 3 * m_iBytesPerLine)
            {
                sbHex.Append("   ");
            }

            return string.Concat("    ", sbHex.ToString(), "   ", sbChars.ToString());
        }

19 View Source File : SvnItem.cs
License : Apache License 2.0
Project Creator : AmpScm

public static string MakeRelative(string root, string filename)
        {
            if (string.IsNullOrEmpty(root) || string.IsNullOrEmpty(filename))
                return filename;

            string[] rootComponents = root.Split(Path.DirectorySeparatorChar);
            string[] filecomponents = filename.Split(Path.DirectorySeparatorChar);

            int num = 1;
            while (num < rootComponents.Length && num < filecomponents.Length && !(rootComponents[num] != filecomponents[num]))
            {
                num++;
            }
            StringBuilder sb = new StringBuilder();
            for (int i = num; i < rootComponents.Length - 1; i++)
            {
                sb.Append("..");
                sb.Append(Path.DirectorySeparatorChar);
            }
            for (int j = num; j < filecomponents.Length; j++)
            {
                sb.Append(filecomponents[j]);
                if (j < filecomponents.Length - 1)
                {
                    sb.Append(Path.DirectorySeparatorChar);
                }
            }
            return sb.ToString();
        }

19 View Source File : SolutionExplorerDataItem.cs
License : Apache License 2.0
Project Creator : AmpScm

public static IList<string> DecodeProjecreplacedemData(IDataObject data, string format)
            {
                /*
                 This function reads the memory stream in the data object and parses the data.
                 The structure of the data is as follows:
                DROPFILES structure (20 bytes)
                String\0
                String\0
                ..
                String\0\0
       
                One String for each drag-dropped Soln Explorer node. 
                The fWide member in the DROPFILES structure tells us if the string is encoded in Unicode or ASCII.
                And each string contains the following:
                {project guid} +"|"+ project file name +"|"+ drag-dropped file name

                The exact format is doreplacedented as part of the doreplacedentation of IVsSolution.GereplacedemOfProjref()
                which is the API to parse these strings.
                */

                using (MemoryStream stream = data.GetData(format) as MemoryStream)
                {
                    if (stream == null || stream.Length <= 22 || !stream.CanRead)
                        return new string[0];

                    Encoding encoding = (System.BitConverter.IsLittleEndian ? Encoding.Unicode : Encoding.BigEndianUnicode);
                    BinaryReader reader = new BinaryReader(stream, encoding);

                    // Read the initial DROPFILES struct (20 bytes)
                    Int32 files = reader.ReadInt32();
                    Int32 x = reader.ReadInt32();
                    Int32 y = reader.ReadInt32();
                    Int32 unused = reader.ReadInt32(); // This is not used anywhere, but is read out of the way.
                    Int32 unicode = reader.ReadInt32();

                    // If the string is not unicode, use ASCII encoding
                    if (unicode == 0)
                    {
                        reader = new BinaryReader(stream, Encoding.ASCII);
                    }

                    char lastChar = '\0';
                    List<string> items = new List<string>();
                    StringBuilder sb = new StringBuilder();

                    while (stream.Position < stream.Length)
                    {
                        char c = reader.ReadChar();
                        if (c == '\0' && lastChar == '\0')
                        {
                            break;
                        }

                        if (c == '\0')
                        {
                            items.Add(sb.ToString());
                            sb.Length = 0;
                        }
                        else
                        {
                            sb.Append(c);
                        }

                        lastChar = c;
                    }

                    return items.AsReadOnly();
                }
            }

19 View Source File : SccSvnOrigin.cs
License : Apache License 2.0
Project Creator : AmpScm

public void Write(IPropertyMap map)
        {
            if (!string.IsNullOrEmpty(Enlist))
                map.SetValue(EnlistName, Enlist);

            if (!string.IsNullOrEmpty(SvnUri))
                map.SetValue(UriName, SvnUri);

            if (!string.IsNullOrEmpty(SvnSuffix))
                map.SetValue(ProjectSuffix, SvnSuffix);

            if (!string.IsNullOrEmpty(Group))
                map.SetValue(GroupName, Group);

            if (!string.IsNullOrEmpty(Relation))
                map.SetValue(RelationName, Relation);

            StringBuilder sb = null;

            foreach (KeyValuePair<string, string> kv in _custom)
            {
                if (map.WrittenKey(kv.Key))
                    continue;

                if (InList(kv.Key, HandledProperties))
                    continue;

                map.SetValue(kv.Key, kv.Value);
            }

            foreach(string k in map.WrittenKeys)
            {
                if (!InList(k, InitialProperties))
                    continue;

                if (sb == null)
                    sb = new StringBuilder();
                else
                    sb.Append(',');

                sb.Append(k);
            }

            if (sb != null)
                map.SetValue(KeysName, sb.ToString());
        }

19 View Source File : LogRevisionItem.cs
License : Apache License 2.0
Project Creator : AmpScm

private string GetIssueText()
        {
            StringBuilder sb = null;
            ICollection<string> issueList = new List<string>();
            foreach (TextMarker issue in Issues)
            {
                if (!issueList.Contains(issue.Value))
                {
                    if (sb == null)
                        sb = new StringBuilder();
                    else
                        sb.Append(',');

                    sb.Append(issue.Value);
                    issueList.Add(issue.Value);
                }
            }
            return sb != null ? sb.ToString() : "";
        }

19 View Source File : InterpreterParser.cs
License : MIT License
Project Creator : Analogy-LogViewer

public static List<Token> Lex(string text)
        {
            var result = new List<Token>();
            for (var i = 0; i < text.Length; i++)
            {
                char c = text[i];
                switch (c)
                {
                    case '+':
                        result.Add(new Token("+", SearchType.And));
                        break;
                    case '&':
                        result.Add(new Token("&", SearchType.And));
                        break;
                    case '|':
                        result.Add(new Token("|", SearchType.Or));
                        break;
                    case '(':
                        result.Add(new Token("(", SearchType.Lparentheses));
                        break;
                    case ')':
                        result.Add(new Token(")", SearchType.Rparentheses));
                        break;
                    default:
                        var sb = new StringBuilder(c.ToString());
                        for (int j = i + 1; j < text.Length; j++)
                        {
                            if (text[j] == '+' || text[j] == '&' || text[j] == '(' || text[j] == ')' || text[j] == '|')
                            {
                                result.Add(new Token(sb.ToString(), SearchType.Expression));
                                break;
                            }
                            else
                            {
                                sb.Append(text[j]);
                                ++i;
                            }
                        }
                        break;
                }
            }

            return result;
        }

19 View Source File : FilterCriteriaObject.cs
License : MIT License
Project Creator : Analogy-LogViewer

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static string EscapeLikeValue(string value)
        {
            StringBuilder sb = new StringBuilder(value.Length);
            foreach (var c in value)
            {
                switch (c)
                {


                    case ']':
                    case '[':
                    case '%':
                    case '*':
                        sb.Append("[").Append(c).Append("]");
                        break;
                    case '\'':
                        sb.Append("''");
                        break;
                    case '@':
                        break;
                    default:
                        sb.Append(c);
                        break;
                }
            }

            return sb.ToString();
        }

19 View Source File : InterpreterParser.cs
License : MIT License
Project Creator : Analogy-LogViewer

private static string EscapeLikeValue(string value)
        {
            StringBuilder sb = new StringBuilder(value.Length);
            foreach (var c in value)
            {
                switch (c)
                {


                    case ']':
                    case '[':
                    case '%':
                    case '*':
                        sb.Append("[").Append(c).Append("]");
                        break;
                    case '\'':
                        sb.Append("''");
                        break;
                    case '@':
                        break;
                    default:
                        sb.Append(c);
                        break;
                }
            }

            return sb.ToString();
        }

19 View Source File : TerminalDevice.cs
License : MIT License
Project Creator : ancientproject

public override void write(long address, long data)
    {
        switch (address)
        {
            case 0x5:
                var c1 = (char)data;
                if(c1 == 0xA)
                    Write(Environment.NewLine);
                else 
                    Write(c1);
                break;
            case 0x6:
                var c2 = (char)data;
                if (c2 == 0xA)
                    relMemory.Append(Environment.NewLine);
                else 
                    relMemory.Append(c2);
                break;
            case 0x7:
                Out.Write(relMemory);
                break;
            case 0x8:
                relMemory.Clear();
                break;
            case 0x9:
                var u1 = ((short)data & 0xF0) >> 4;
                var u2 = (short)data & 0xF;

                switch (u1)
                {
                    case 0x1:
                        ForegroundColor = (ConsoleColor)u2;
                        break;
                    case 0x2:
                        BackgroundColor = (ConsoleColor)u2;
                        break;
                    case 0x3:
                        ForegroundColor = ConsoleColor.White;
                        break;
                    case 0x4:
                        BackgroundColor = ConsoleColor.Black;
                        break;
                }
                break;
        }
    }

19 View Source File : Formatter.cs
License : MIT License
Project Creator : andersnm

private static string FormatDate(ExcelDateTime date, List<string> tokens, CultureInfo culture)
        {
            var containsAmPm = ContainsAmPm(tokens);

            var result = new StringBuilder();
            for (var i = 0; i < tokens.Count; i++)
            {
                var token = tokens[i];

                if (token.StartsWith("y", StringComparison.OrdinalIgnoreCase))
                {
                    // year
                    var digits = token.Length;
                    if (digits < 2)
                        digits = 2;
                    if (digits == 3)
                        digits = 4;

                    var year = date.Year;
                    if (digits == 2)
                        year = year % 100;

                    result.Append(year.ToString("D" + digits));
                }
                else if (token.StartsWith("m", StringComparison.OrdinalIgnoreCase))
                {
                    // If  "m" or "mm" code is used immediately after the "h" or "hh" code (for hours) or immediately before 
                    // the "ss" code (for seconds), the application shall display minutes instead of the month. 
                    if (LookBackDatePart(tokens, i - 1, "h") || LookAheadDatePart(tokens, i + 1, "s"))
                    {
                        var digits = token.Length;
                        result.Append(date.Minute.ToString("D" + digits));
                    }
                    else
                    {
                        var digits = token.Length;
                        if (digits == 3)
                        {
                            result.Append(culture.DateTimeFormat.AbbreviatedMonthNames[date.Month - 1]);
                        }
                        else if (digits == 4)
                        {
                            result.Append(culture.DateTimeFormat.MonthNames[date.Month - 1]);
                        }
                        else if (digits == 5)
                        {
                            result.Append(culture.DateTimeFormat.MonthNames[date.Month - 1][0]);
                        }
                        else
                        {
                            result.Append(date.Month.ToString("D" + digits));
                        }
                    }
                }
                else if (token.StartsWith("d", StringComparison.OrdinalIgnoreCase))
                {
                    var digits = token.Length;
                    if (digits == 3)
                    {
                        // Sun-Sat
                        result.Append(culture.DateTimeFormat.AbbreviatedDayNames[(int)date.DayOfWeek]);
                    }
                    else if (digits == 4)
                    {
                        // Sunday-Saturday
                        result.Append(culture.DateTimeFormat.DayNames[(int)date.DayOfWeek]);
                    }
                    else
                    {
                        result.Append(date.Day.ToString("D" + digits));
                    }
                }
                else if (token.StartsWith("h", StringComparison.OrdinalIgnoreCase))
                {
                    var digits = token.Length;
                    if (containsAmPm)
                        result.Append(((date.Hour + 11) % 12 + 1).ToString("D" + digits));
                    else
                        result.Append(date.Hour.ToString("D" + digits));
                }
                else if (token.StartsWith("s", StringComparison.OrdinalIgnoreCase))
                {
                    var digits = token.Length;
                    result.Append(date.Second.ToString("D" + digits));
                }
                else if (token.StartsWith("g", StringComparison.OrdinalIgnoreCase))
                {
                    var era = culture.DateTimeFormat.Calendar.GetEra(date.AdjustedDateTime);
                    var digits = token.Length;
                    if (digits < 3)
                    {
                        result.Append(culture.DateTimeFormat.GetAbbreviatedEraName(era));
                    }
                    else
                    {
                        result.Append(culture.DateTimeFormat.GetEraName(era));
                    }
                }
                else if (string.Compare(token, "am/pm", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    var ampm = date.ToString("tt", CultureInfo.InvariantCulture);
                    result.Append(ampm.ToUpperInvariant());
                }
                else if (string.Compare(token, "a/p", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    var ampm = date.ToString("%t", CultureInfo.InvariantCulture);
                    if (char.IsUpper(token[0]))
                    {
                        result.Append(ampm.ToUpperInvariant());
                    }
                    else
                    {
                        result.Append(ampm.ToLowerInvariant());
                    }
                }
                else if (token.StartsWith(".0"))
                {
                    var value = date.Millisecond;
                    var digits = token.Length - 1;
                    result.Append("." + value.ToString("D" + digits));
                }
                else if (token == "/")
                {
#if NETSTANDARD1_0
                    result.Append(DateTime.MaxValue.ToString("/d", culture)[0]);
#else
                    result.Append(culture.DateTimeFormat.DateSeparator);
#endif
                }
                else if (token == ",")
                {
                    while (i < tokens.Count - 1 && tokens[i + 1] == ",")
                    {
                        i++;
                    }

                    result.Append(",");
                }
                else
                {
                    FormatLiteral(token, result);
                }
            }

            return result.ToString();
        }

19 View Source File : ProjectSettingsWindow.cs
License : MIT License
Project Creator : anderm

private void EnableVirtualReality()
        {
            try
            {
                // Grab the text from the project settings replacedet file
                string settingsPath = "ProjectSettings/ProjectSettings.replacedet";
                string settings = File.ReadAllText(settingsPath);

                // We're looking for the list of VR devices for the current build target, then
                // ensuring that the HoloLens is in that list
                bool foundBuildTargetVRSettings = false;
                bool foundBuildTargetMetro = false;
                bool foundBuildTargetEnabled = false;
                bool foundDevices = false;
                bool foundHoloLens = false;

                StringBuilder builder = new StringBuilder(); // Used to build the final output
                string[] lines = settings.Split(new char[] { '\n' });
                for (int i = 0; i < lines.Length; ++i)
                {
                    string line = lines[i];

                    // Look for the build target VR settings
                    if (!foundBuildTargetVRSettings)
                    {
                        if (line.Contains("m_BuildTargetVRSettings:"))
                        {
                            // If no targets are enabled at all, just create the known entries and skip the rest of the tests
                            if (line.Contains("[]"))
                            {
                                // Remove the empty array symbols
                                line = line.Replace(" []", "\n");

                                // Generate the new lines
                                line += "  - m_BuildTarget: Metro\n";
                                line += "    m_Enabled: 1\n";
                                line += "    m_Devices:\n";
                                line += "    - HoloLens";

                                // Mark all fields as found so we don't search anymore
                                foundBuildTargetVRSettings = true;
                                foundBuildTargetMetro = true;
                                foundBuildTargetEnabled = true;
                                foundDevices = true;
                                foundHoloLens = true;
                            }
                            else
                            {
                                // The target VR settngs were found but the others
                                // still need to be searched for.
                                foundBuildTargetVRSettings = true;
                            }
                        }
                    }

                    // Look for the build target for Metro
                    else if (!foundBuildTargetMetro)
                    {
                        if (line.Contains("m_BuildTarget: Metro"))
                        {
                            foundBuildTargetMetro = true;
                        }
                    }

                    else if (!foundBuildTargetEnabled)
                    {
                        if (line.Contains("m_Enabled"))
                        {
                            line = "    m_Enabled: 1";
                            foundBuildTargetEnabled = true;
                        }
                    }

                    // Look for the enabled Devices list
                    else if (!foundDevices)
                    {
                        if (line.Contains("m_Devices:"))
                        {
                            // Clear the empty array symbols if any
                            line = line.Replace(" []", "");
                            foundDevices = true;
                        }
                    }

                    // Once we've found the list look for HoloLens or the next non element
                    else if (!foundHoloLens)
                    {
                        // If this isn't an element in the device list
                        if (!line.Contains("-"))
                        {
                            // add the hololens element, and mark it found
                            builder.Append("    - HoloLens\n");
                            foundHoloLens = true;
                        }

                        // Otherwise test if this is the hololens device
                        else if (line.Contains("HoloLens"))
                        {
                            foundHoloLens = true;
                        }
                    }

                    builder.Append(line);

                    // Write out a \n for all but the last line
                    // NOTE: Specifically preserving unix line endings by avoiding StringBuilder.AppendLine
                    if (i != lines.Length - 1)
                    {
                        builder.Append('\n');
                    }
                }

                // Capture the final string
                settings = builder.ToString();

                File.WriteAllText(settingsPath, settings);
            }
            catch (Exception e)
            {
                Debug.LogException(e);
            }
        }

19 View Source File : Formatter.cs
License : MIT License
Project Creator : andersnm

public static void FormatThousands(string valueString, bool thousandSeparator, bool significantZero, List<string> tokens, CultureInfo culture, StringBuilder result)
        {
            var significant = false;
            var formatDigits = GetDigitCount(tokens);
            valueString = valueString.PadLeft(formatDigits, '0');

            // Print literals occurring before any placeholders
            var tokenIndex = 0;
            for (; tokenIndex < tokens.Count; tokenIndex++)
            {
                var token = tokens[tokenIndex];
                if (Token.IsPlaceholder(token))
                    break;
                else
                    FormatLiteral(token, result);
            }

            // Print value digits until there are as many digits remaining as there are placeholders
            var digitIndex = 0;
            for (; digitIndex < (valueString.Length - formatDigits); digitIndex++)
            {
                significant = true;
                result.Append(valueString[digitIndex]);

                if (thousandSeparator)
                    FormatThousandSeparator(valueString, digitIndex, culture, result);
            }

            // Print remaining value digits and format literals
            for (; tokenIndex < tokens.Count; ++tokenIndex)
            {
                var token = tokens[tokenIndex];
                if (Token.IsPlaceholder(token))
                {
                    var c = valueString[digitIndex];
                    if (c != '0' || (significantZero && digitIndex == valueString.Length - 1)) significant = true;

                    FormatPlaceholder(token, c, significant, result);

                    if (thousandSeparator && (significant || token.Equals("0")))
                        FormatThousandSeparator(valueString, digitIndex, culture, result);

                    digitIndex++;
                }
                else
                {
                    FormatLiteral(token, result);
                }
            }
        }

19 View Source File : Formatter.cs
License : MIT License
Project Creator : andersnm

static void FormatPlaceholder(string token, char c, bool significant, StringBuilder result)
        {
            if (token == "0")
            {
                if (significant)
                    result.Append(c);
                else
                    result.Append("0");
            }
            else if (token == "#")
            {
                if (significant)
                    result.Append(c);
            }
            else if (token == "?")
            {
                if (significant)
                    result.Append(c);
                else
                    result.Append(" ");
            }
        }

19 View Source File : SqlNameMangling.cs
License : GNU General Public License v3.0
Project Creator : anderson-joyle

public static string GetValidSqlName(string nameOfField, int arrayIndex)
        {
            // Support for Table Extension
            nameOfField = nameOfField.Contains(ExtensionNameSeparator) ? nameOfField.Replace(ExtensionNameSeparator, '$') : nameOfField;
            nameOfField = nameOfField.ToUpperInvariant();

            if (nameOfField[0] == '.')
            {
                nameOfField = "$" + nameOfField.Substring(1);
            }
            else if (nameOfField[0] == ':')
            {
                nameOfField = X + nameOfField.Substring(1);
            }
            else if (nameOfField[0] == '_')
            {
                nameOfField = X + nameOfField.Substring(1);
            }

            StringBuilder filtered = new StringBuilder(nameOfField.Length);
            for (int i = 0; i < nameOfField.Length; i++)
            {
                char current = nameOfField[i];
                if (current > 127)
                {
                    filtered.Append(X);
                }
                else
                {
                    filtered.Append(current);
                }
            }
            nameOfField = filtered.ToString();

            if (arrayIndex > 1)
            {
                // generate array fields like Dim, Dim2_, Dim3_ ...
                nameOfField += arrayIndex + "_";
            }
            // handle reserved keywords like "key", "percent" etc.
            else if (ReservedKeywordsSet.Contains(nameOfField))
            {
                nameOfField += "_";
            }

            return nameOfField;
        }

19 View Source File : SimpleJson.cs
License : GNU General Public License v3.0
Project Creator : AndrasMumm

public static JSONNode Parse(string aJSON)
        {
            Stack<JSONNode> stack = new Stack<JSONNode>();
            JSONNode ctx = null;
            int i = 0;
            StringBuilder Token = new StringBuilder();
            string TokenName = "";
            bool QuoteMode = false;
            bool TokenIsQuoted = false;
            while (i < aJSON.Length)
            {
                switch (aJSON[i])
                {
                    case '{':
                        if (QuoteMode)
                        {
                            Token.Append(aJSON[i]);
                            break;
                        }
                        stack.Push(new JSONObject());
                        if (ctx != null)
                        {
                            ctx.Add(TokenName, stack.Peek());
                        }
                        TokenName = "";
                        Token.Length = 0;
                        ctx = stack.Peek();
                        break;

                    case '[':
                        if (QuoteMode)
                        {
                            Token.Append(aJSON[i]);
                            break;
                        }

                        stack.Push(new JSONArray());
                        if (ctx != null)
                        {
                            ctx.Add(TokenName, stack.Peek());
                        }
                        TokenName = "";
                        Token.Length = 0;
                        ctx = stack.Peek();
                        break;

                    case '}':
                    case ']':
                        if (QuoteMode)
                        {

                            Token.Append(aJSON[i]);
                            break;
                        }
                        if (stack.Count == 0)
                            throw new Exception("JSON Parse: Too many closing brackets");

                        stack.Pop();
                        if (Token.Length > 0 || TokenIsQuoted)
                        {
                            ParseElement(ctx, Token.ToString(), TokenName, TokenIsQuoted);
                            TokenIsQuoted = false;
                        }
                        TokenName = "";
                        Token.Length = 0;
                        if (stack.Count > 0)
                            ctx = stack.Peek();
                        break;

                    case ':':
                        if (QuoteMode)
                        {
                            Token.Append(aJSON[i]);
                            break;
                        }
                        TokenName = Token.ToString();
                        Token.Length = 0;
                        TokenIsQuoted = false;
                        break;

                    case '"':
                        QuoteMode ^= true;
                        TokenIsQuoted |= QuoteMode;
                        break;

                    case ',':
                        if (QuoteMode)
                        {
                            Token.Append(aJSON[i]);
                            break;
                        }
                        if (Token.Length > 0 || TokenIsQuoted)
                        {
                            ParseElement(ctx, Token.ToString(), TokenName, TokenIsQuoted);
                            TokenIsQuoted = false;
                        }
                        TokenName = "";
                        Token.Length = 0;
                        TokenIsQuoted = false;
                        break;

                    case '\r':
                    case '\n':
                        break;

                    case ' ':
                    case '\t':
                        if (QuoteMode)
                            Token.Append(aJSON[i]);
                        break;

                    case '\\':
                        ++i;
                        if (QuoteMode)
                        {
                            char C = aJSON[i];
                            switch (C)
                            {
                                case 't':
                                    Token.Append('\t');
                                    break;
                                case 'r':
                                    Token.Append('\r');
                                    break;
                                case 'n':
                                    Token.Append('\n');
                                    break;
                                case 'b':
                                    Token.Append('\b');
                                    break;
                                case 'f':
                                    Token.Append('\f');
                                    break;
                                case 'u':
                                    {
                                        string s = aJSON.Substring(i + 1, 4);
                                        Token.Append((char)int.Parse(
                                            s,
                                            System.Globalization.NumberStyles.AllowHexSpecifier));
                                        i += 4;
                                        break;
                                    }
                                default:
                                    Token.Append(C);
                                    break;
                            }
                        }
                        break;

                    default:
                        Token.Append(aJSON[i]);
                        break;
                }
                ++i;
            }
            if (QuoteMode)
            {
                throw new Exception("JSON Parse: Quotation marks seems to be messed up.");
            }
            return ctx;
        }

19 View Source File : JsonHelper.cs
License : GNU General Public License v3.0
Project Creator : AndrasMumm

public static string Escape(string str)
    {
        if (str == null || str.Length == 0)
        {
            return "";
        }

        char c;
        int len = str.Length;
        StringBuilder sb = new StringBuilder(len + 4);
        for (int i = 0; i < len; i += 1)
        {
            c = str[i];
            switch (c)
            {
                case '\\':
                case '"':
                    sb.Append('\\');
                    sb.Append(c);
                    break;
                case '\b':
                    sb.Append("\\b");
                    break;
                case '\t':
                    sb.Append("\\t");
                    break;
                case '\n':
                    sb.Append("\\n");
                    break;
                case '\f':
                    sb.Append("\\f");
                    break;
                case '\r':
                    sb.Append("\\r");
                    break;
                case '\u0085': // Next Line
                    sb.Append("\\u0085");
                    break;
                case '\u2028': // Line Separator
                    sb.Append("\\u2028");
                    break;
                case '\u2029': // Paragraph Separator
                    sb.Append("\\u2029");
                    break;
                default:
                    sb.Append(c);
                    break;
            }
        }
        return sb.ToString();
    }

19 View Source File : NativeMethods.cs
License : GNU General Public License v3.0
Project Creator : AndreiFedarets

public static StringDictionary ReadEnvironmentVariables(IntPtr environment)
        {
            StringDictionary environmentVariables = new StringDictionary();
            StringBuilder testData = new StringBuilder(string.Empty);
            unsafe
            {
                short* start = (short*)environment.ToPointer();
                bool done = false;
                short* current = start;
                while (!done)
                {
                    if ((testData.Length > 0) && (*current == 0) && (current != start))
                    {
                        String data = testData.ToString();
                        int index = data.IndexOf('=');
                        if (index == -1)
                        {
                            environmentVariables.Add(data, string.Empty);
                        }
                        else if (index == (data.Length - 1))
                        {
                            environmentVariables.Add(data.Substring(0, index), string.Empty);
                        }
                        else
                        {
                            environmentVariables.Add(data.Substring(0, index), data.Substring(index + 1));
                        }
                        testData.Length = 0;
                    }
                    if ((*current == 0) && (current != start) && (*(current - 1) == 0))
                    {
                        done = true;
                    }
                    if (*current != 0)
                    {
                        testData.Append((char)*current);
                    }
                    current++;
                }
            }
            return environmentVariables;
        }

19 View Source File : UWolframAlpha.Data.UIElements.cs
License : MIT License
Project Creator : andrew-raphael-lukasik

public static TextField ToCsvField ( string text )
		{
			if( text!=null && text.Length!=0 )
			{
				var csv = new System.Text.StringBuilder();
				string[] rawRows = text.Split('\n');
				int numRawRows = rawRows.Length;
				for( int r=0 ; r<numRawRows ; r++ )
				{
					string raw_row = rawRows[r];
					var row = new System.Text.StringBuilder();
					{
						string[] rawCells = raw_row.Split('|');
						int numRawCells = rawCells.Length;
						for( int c=0 ; c<numRawCells ; c++ )
						{
							string cell = rawCells[c].TrimStart(' ').TrimEnd(' ');
							if( c!=0 ) row.Append(',');
							row.Append( cell );
						}
					}
					csv.AppendLine( row.ToString() );
				}

				var CSV = new TextField();
				CSV.value = csv.ToString();
				CSV.isReadOnly = true;
				return CSV;
			}
			else return null;
		}

19 View Source File : HistogramBin.cs
License : MIT License
Project Creator : AndreyAkinshin

[PublicAPI] public string ToString(CultureInfo cultureInfo)
        {
            var unit = TimeUnit.GetBestTimeUnit(Values);
            var builder = new StringBuilder();
            builder.Append('[');
            builder.Append(TimeInterval.FromNanoseconds(Lower).ToString(unit, formatProvider: cultureInfo));
            builder.Append(';');
            builder.Append(TimeInterval.FromNanoseconds(Upper).ToString(unit, formatProvider: cultureInfo));
            builder.Append(' ');
            builder.Append('{');
            for (var i = 0; i < Values.Length; i++)
            {
                if (i != 0)
                    builder.Append("; ");
                builder.Append(TimeInterval.FromNanoseconds(Values[i]).ToString(unit, formatProvider: cultureInfo));
            }
            builder.Append('}');
            
            return builder.ToString();
        }

19 View Source File : ManualModalityDataFormatter.cs
License : MIT License
Project Creator : AndreyAkinshin

public string Format(ModalityData data, string numberFormat = null, IFormatProvider numberFormatProvider = null)
        {
            replacedertion.NotNull(nameof(data), data);

            var outlierDetectorFactory = OutlierDetectorFactory ?? SimpleOutlierDetectorFactory.DoubleMad;
            numberFormat ??= "N2";
            numberFormatProvider ??= DefaultCultureInfo.Instance;

            bool compactMode = CompactMiddleModes && data.Modality > 2;
            var modes = compactMode
                ? new[] {data.Modes.First(), data.Modes.Last()}
                : data.Modes;
            var builder = new StringBuilder();
            var bunch = new Bunch();
            bool isFirst = true;

            void AddBunch(char open, string multiSeparator, char close)
            {
                if (bunch.Any())
                {
                    if (isFirst)
                        isFirst = false;
                    else
                        builder.Append(GroupSeparator);
                    bunch.Present(builder, open, multiSeparator, close, PresentCount, numberFormat, numberFormatProvider);
                }
            }

            void AddMode() => AddBunch('[', "; ", ']');
            void AddOutliers() => AddBunch('{', "..", '}');

            void AddMiddleNodesIfNeeded(int index)
            {
                if (index == 0 && compactMode)
                {
                    int extraModes = data.Modality - 2;
                    if (isFirst)
                        isFirst = false;
                    else
                        builder.Append(GroupSeparator);
                    builder.Append('<');
                    builder.Append(extraModes);
                    builder.Append(' ');
                    builder.Append(extraModes > 1 ? "modes" : "mode");
                    builder.Append('>');
                }
            }


            if (PresentOutliers)
            {
                for (int i = 0; i < modes.Count; i++)
                {
                    var mode = modes[i];
                    var outlierDetector = outlierDetectorFactory.Create(mode.Values);
                    int index = 0;

                    // *Lower outliers*
                    while (index < mode.Values.Count && outlierDetector.IsLowerOutlier(mode.Values[index]))
                        bunch.Add(mode.Values[index++]);
                    if (!(compactMode && i != 0))
                        AddOutliers();
                    bunch.Clear();

                    // *Central values*
                    while (index < mode.Values.Count && !outlierDetector.IsOutlier(mode.Values[index]))
                        bunch.Add(mode.Values[index++]);
                    if (PresentModeLocations)
                        bunch.Mode = mode.Location;
                    AddMode();
                    bunch.Clear();

                    // *Upper outliers*
                    while (index < mode.Values.Count && outlierDetector.IsUpperOutlier(mode.Values[index]))
                        bunch.Add(mode.Values[index++]);
                    // Propagate bunch to the lower outliers of the next mode

                    AddMiddleNodesIfNeeded(i);
                }

                AddOutliers(); // Upper outliers of the last mode
            }
            else
            {
                for (int i = 0; i < modes.Count; i++)
                {
                    var mode = modes[i];
                    bunch.Min = mode.Min();
                    bunch.Max = mode.Max();
                    if (PresentModeLocations)
                        bunch.Mode = mode.Location;
                    bunch.Count = mode.Values.Count;
                    AddBunch('[', "; ", ']');
                    AddMiddleNodesIfNeeded(i);
                }
            }

            return builder.ToString();
        }

19 View Source File : ManualModalityDataFormatter.cs
License : MIT License
Project Creator : AndreyAkinshin

public void Present([NotNull] StringBuilder builder, char open, string multiSeparator, char close, bool presentCount,
                [NotNull] string format, [NotNull] IFormatProvider formatProvider)
            {
                switch (Count)
                {
                    case 0:
                        break;
                    case 1:
                        builder.Append(open);
                        builder.Append(Min.ToString(format, formatProvider));
                        builder.Append(close);
                        break;
                    case 2:
                        builder.Append(open);
                        builder.Append(Min.ToString(format, formatProvider));
                        builder.Append(", ");
                        builder.Append(Max.ToString(format, formatProvider));
                        builder.Append(close);
                        break;
                    default:
                    {
                        builder.Append(open);
                        if (Mode != null)
                        {
                            builder.Append(Min.ToString(format, formatProvider));
                            builder.Append(" | ");
                            builder.Append(Mode?.ToString(format, formatProvider));
                            builder.Append(" | ");
                            builder.Append(Max.ToString(format, formatProvider));
                        }
                        else
                        {
                            builder.Append(Min.ToString(format, formatProvider));
                            builder.Append(multiSeparator);
                            builder.Append(Max.ToString(format, formatProvider));
                        }

                        builder.Append(close);
                        break;
                    }
                }

                if (Count > 2 && presentCount)
                {
                    builder.Append("_");
                    builder.Append(Count);
                }
            }

19 View Source File : ConfidenceInterval.cs
License : MIT License
Project Creator : AndreyAkinshin

public string ToString(string format, IFormatProvider formatProvider = null, bool showLevel = true)
        {
            formatProvider ??= DefaultCultureInfo.Instance;

            var builder = new StringBuilder();
            builder.Append('[');
            builder.Append(Lower.ToString(format, formatProvider));
            builder.Append("; ");
            builder.Append(Upper.ToString(format, formatProvider));
            builder.Append("]");
            if (showLevel)
            {
                builder.Append(" (CI ");
                builder.Append(ConfidenceLevel.ToString());
                builder.Append(")");
            }

            return builder.ToString();
        }

19 View Source File : MovingP2QuantileEstimatorTests.cs
License : MIT License
Project Creator : AndreyAkinshin

[Theory]
        [InlineData(1000, 51, 0.5, 0.2, 0.7)]
        public void MovingP2QuantileEstimatorMedianTest1(int n, int windowSize, double probability, double relativeThreshold,
            double minSuccessRate)
        {
            var random = new Random();
            double[] data = new double[n];
            for (int i = 0; i < n; i++)
            {
                data[i] = 10 + Math.Sin(i / 20.0) * 5 + random.NextDouble(-3, 3);
                if (random.Next(10) == 0 && i > windowSize / 2)
                    data[i] += random.Next(20, 50);
                data[i] = Math.Round(data[i], 3);
            }

            var mp2Estimator = new MovingP2QuantileEstimator(probability, windowSize);
            var phEstimator = new ParreplacedioningHeapsMovingQuantileEstimator(windowSize, probability);

            var outputBuilder = new StringBuilder();
            outputBuilder.AppendLine("i,data,estimation,true");
            int successCounter = 0;
            for (int i = 0; i < n; i++)
            {
                mp2Estimator.Add(data[i]);
                phEstimator.Add(data[i]);

                double mp2Estimation = mp2Estimator.GetQuantile();
                double trueValue = phEstimator.GetQuantile();

                if (Math.Abs(mp2Estimation - trueValue) / trueValue < relativeThreshold)
                    successCounter++;

                outputBuilder.Append(i);
                outputBuilder.Append(',');
                outputBuilder.Append(data[i].ToString(TestCultureInfo.Instance));
                outputBuilder.Append(',');
                outputBuilder.Append(mp2Estimation.ToString(TestCultureInfo.Instance));
                outputBuilder.Append(',');
                outputBuilder.Append(trueValue.ToString(TestCultureInfo.Instance));
                outputBuilder.AppendLine();
            }
            double actualSuccessRate = successCounter * 1.0 / n;

            output.WriteLine("ExpectedSuccessRate = " + minSuccessRate.ToString(TestCultureInfo.Instance));
            output.WriteLine("ActualSuccessRate   = " + actualSuccessRate.ToString(TestCultureInfo.Instance));
            output.WriteLine();
            output.WriteLine(outputBuilder.ToString());

            replacedert.True(successCounter * 1.0 / n > minSuccessRate);
        }

19 View Source File : SimpleJSON.cs
License : MIT License
Project Creator : andruzzzhka

public static JSONNode Parse(string aJSON)
        {
            Stack<JSONNode> stack = new Stack<JSONNode>();
            JSONNode ctx = null;
            int i = 0;
            StringBuilder Token = new StringBuilder();
            string TokenName = "";
            bool QuoteMode = false;
            bool TokenIsQuoted = false;
            while (i < aJSON.Length)
            {
                switch (aJSON[i])
                {
                    case '{':
                        if (QuoteMode)
                        {
                            Token.Append(aJSON[i]);
                            break;
                        }
                        stack.Push(new JSONObject());
                        if (ctx != null)
                        {
                            ctx.Add(TokenName, stack.Peek());
                        }
                        TokenName = "";
                        Token.Length = 0;
                        ctx = stack.Peek();
                        break;

                    case '[':
                        if (QuoteMode)
                        {
                            Token.Append(aJSON[i]);
                            break;
                        }

                        stack.Push(new JSONArray());
                        if (ctx != null)
                        {
                            ctx.Add(TokenName, stack.Peek());
                        }
                        TokenName = "";
                        Token.Length = 0;
                        ctx = stack.Peek();
                        break;

                    case '}':
                    case ']':
                        if (QuoteMode)
                        {

                            Token.Append(aJSON[i]);
                            break;
                        }
                        if (stack.Count == 0)
                            throw new Exception("JSON Parse: Too many closing brackets");

                        stack.Pop();
                        if (Token.Length > 0 || TokenIsQuoted)
                            ctx.Add(TokenName, ParseElement(Token.ToString(), TokenIsQuoted));
                        TokenIsQuoted = false;
                        TokenName = "";
                        Token.Length = 0;
                        if (stack.Count > 0)
                            ctx = stack.Peek();
                        break;

                    case ':':
                        if (QuoteMode)
                        {
                            Token.Append(aJSON[i]);
                            break;
                        }
                        TokenName = Token.ToString();
                        Token.Length = 0;
                        TokenIsQuoted = false;
                        break;

                    case '"':
                        QuoteMode ^= true;
                        TokenIsQuoted |= QuoteMode;
                        break;

                    case ',':
                        if (QuoteMode)
                        {
                            Token.Append(aJSON[i]);
                            break;
                        }
                        if (Token.Length > 0 || TokenIsQuoted)
                            ctx.Add(TokenName, ParseElement(Token.ToString(), TokenIsQuoted));
                        TokenIsQuoted = false;
                        TokenName = "";
                        Token.Length = 0;
                        TokenIsQuoted = false;
                        break;

                    case '\r':
                    case '\n':
                        break;

                    case ' ':
                    case '\t':
                        if (QuoteMode)
                            Token.Append(aJSON[i]);
                        break;

                    case '\\':
                        ++i;
                        if (QuoteMode)
                        {
                            char C = aJSON[i];
                            switch (C)
                            {
                                case 't':
                                    Token.Append('\t');
                                    break;
                                case 'r':
                                    Token.Append('\r');
                                    break;
                                case 'n':
                                    Token.Append('\n');
                                    break;
                                case 'b':
                                    Token.Append('\b');
                                    break;
                                case 'f':
                                    Token.Append('\f');
                                    break;
                                case 'u':
                                    {
                                        string s = aJSON.Substring(i + 1, 4);
                                        Token.Append((char)int.Parse(
                                            s,
                                            System.Globalization.NumberStyles.AllowHexSpecifier));
                                        i += 4;
                                        break;
                                    }
                                default:
                                    Token.Append(C);
                                    break;
                            }
                        }
                        break;
                    case '/':
                        if (allowLineComments && !QuoteMode && i + 1 < aJSON.Length && aJSON[i + 1] == '/')
                        {
                            while (++i < aJSON.Length && aJSON[i] != '\n' && aJSON[i] != '\r') ;
                            break;
                        }
                        Token.Append(aJSON[i]);
                        break;
                    case '\uFEFF': // remove / ignore BOM (Byte Order Mark)
                        break;

                    default:
                        Token.Append(aJSON[i]);
                        break;
                }
                ++i;
            }
            if (QuoteMode)
            {
                throw new Exception("JSON Parse: Quotation marks seems to be messed up.");
            }
            if (ctx == null)
                return ParseElement(Token.ToString(), TokenIsQuoted);
            return ctx;
        }

19 View Source File : HttpUtility.cs
License : MIT License
Project Creator : andruzzzhka

private static string htmlDecode (string s)
    {
      var buff = new StringBuilder ();

      // 0: None
      // 1: Right after '&'
      // 2: Between '&' and ';' but no NCR
      // 3: '#' found after '&' and getting numbers
      // 4: 'x' found after '#' and getting numbers
      var state = 0;

      var reference = new StringBuilder ();
      var num = 0;

      foreach (var c in s) {
        if (state == 0) {
          if (c == '&') {
            reference.Append ('&');
            state = 1;

            continue;
          }

          buff.Append (c);
          continue;
        }

        if (c == '&') {
          buff.Append (reference.ToString ());

          reference.Length = 0;
          reference.Append ('&');
          state = 1;

          continue;
        }

        reference.Append (c);

        if (state == 1) {
          if (c == ';') {
            buff.Append (reference.ToString ());

            reference.Length = 0;
            state = 0;

            continue;
          }

          num = 0;
          state = c == '#' ? 3 : 2;

          continue;
        }

        if (state == 2) {
          if (c == ';') {
            var enreplacedy = reference.ToString ();
            var name = enreplacedy.Substring (1, enreplacedy.Length - 2);

            var enreplacedies = getEnreplacedies ();
            if (enreplacedies.ContainsKey (name))
              buff.Append (enreplacedies[name]);
            else
              buff.Append (enreplacedy);

            reference.Length = 0;
            state = 0;

            continue;
          }

          continue;
        }

        if (state == 3) {
          if (c == ';') {
            if (reference.Length > 3 && num < 65536)
              buff.Append ((char) num);
            else
              buff.Append (reference.ToString ());

            reference.Length = 0;
            state = 0;

            continue;
          }

          if (c == 'x') {
            state = reference.Length == 3 ? 4 : 2;
            continue;
          }

          if (!isNumeric (c)) {
            state = 2;
            continue;
          }

          num = num * 10 + (c - '0');
          continue;
        }

        if (state == 4) {
          if (c == ';') {
            if (reference.Length > 4 && num < 65536)
              buff.Append ((char) num);
            else
              buff.Append (reference.ToString ());

            reference.Length = 0;
            state = 0;

            continue;
          }

          var n = getNumber (c);
          if (n == -1) {
            state = 2;
            continue;
          }

          num = (num << 4) + n;
        }
      }

      if (reference.Length > 0)
        buff.Append (reference.ToString ());

      return buff.ToString ();
    }

19 View Source File : ChunkStream.cs
License : MIT License
Project Creator : andruzzzhka

private InputChunkState setChunkSize (byte[] buffer, ref int offset, int length)
    {
      byte b = 0;
      while (offset < length) {
        b = buffer[offset++];
        if (_sawCr) {
          if (b != 10)
            throwProtocolViolation ("LF is expected.");

          break;
        }

        if (b == 13) {
          _sawCr = true;
          continue;
        }

        if (b == 10)
          throwProtocolViolation ("LF is unexpected.");

        if (b == 32) // SP
          _goreplaced = true;

        if (!_goreplaced)
          _saved.Append ((char) b);

        if (_saved.Length > 20)
          throwProtocolViolation ("The chunk size is too long.");
      }

      if (!_sawCr || b != 10)
        return InputChunkState.None;

      _chunkRead = 0;
      try {
        _chunkSize = Int32.Parse (
          removeChunkExtension (_saved.ToString ()), NumberStyles.HexNumber);
      }
      catch {
        throwProtocolViolation ("The chunk size cannot be parsed.");
      }

      if (_chunkSize == 0) {
        _trailerState = 2;
        return InputChunkState.Trailer;
      }

      return InputChunkState.Data;
    }

19 View Source File : ChunkStream.cs
License : MIT License
Project Creator : andruzzzhka

private InputChunkState setTrailer (byte[] buffer, ref int offset, int length)
    {
      // Check if no trailer.
      if (_trailerState == 2 && buffer[offset] == 13 && _saved.Length == 0) {
        offset++;
        if (offset < length && buffer[offset] == 10) {
          offset++;
          return InputChunkState.End;
        }

        offset--;
      }

      while (offset < length && _trailerState < 4) {
        var b = buffer[offset++];
        _saved.Append ((char) b);
        if (_saved.Length > 4196)
          throwProtocolViolation ("The trailer is too long.");

        if (_trailerState == 1 || _trailerState == 3) {
          if (b != 10)
            throwProtocolViolation ("LF is expected.");

          _trailerState++;
          continue;
        }

        if (b == 13) {
          _trailerState++;
          continue;
        }

        if (b == 10)
          throwProtocolViolation ("LF is unexpected.");

        _trailerState = 0;
      }

      if (_trailerState < 4)
        return InputChunkState.Trailer;

      _saved.Length -= 2;
      var reader = new StringReader (_saved.ToString ());

      string line;
      while ((line = reader.ReadLine ()) != null && line.Length > 0)
        _headers.Add (line);

      return InputChunkState.End;
    }

19 View Source File : HttpConnection.cs
License : MIT License
Project Creator : andruzzzhka

private string readLineFrom (byte[] buffer, int offset, int length, out int read)
    {
      read = 0;

      for (var i = offset; i < length && _lineState != LineState.Lf; i++) {
        read++;

        var b = buffer[i];
        if (b == 13)
          _lineState = LineState.Cr;
        else if (b == 10)
          _lineState = LineState.Lf;
        else
          _currentLine.Append ((char) b);
      }

      if (_lineState != LineState.Lf)
        return null;

      var line = _currentLine.ToString ();

      _currentLine.Length = 0;
      _lineState = LineState.None;

      return line;
    }

19 View Source File : StringEncryption.cs
License : MIT License
Project Creator : AnErrupTion

private string Encrypt(string str, int key)
        {
            //str = Convert.ToBase64String(Encoding.UTF32.GetBytes(str));
            /*I'm using UTF32, but you can
            also use UTF8 or Unicode for example for shorter encryption.*/
            //char[] chars = "*$,;:!ù^*&é\"'(-è_çà)".ToCharArray();

            //for (int i = 0; i < 5; i++)
            /*<-- this is how many times you will add every character from the
                array at a random position. 5 is just enough for what we want to do.*/
            //foreach (char c in chars) str = str.Insert(Next(str.Length), c.ToString());
            //return str;

            StringBuilder builder = new StringBuilder();
            foreach (char c in str.ToCharArray())
                builder.Append((char)(c + key));

            return builder.ToString();
        }

19 View Source File : StringDecoder.cs
License : MIT License
Project Creator : AnErrupTion

public static string Decrypt(string str, int min, int key, int hash, int length, int max)
        {
            if (max > 78787878) ;
            if (length > 485941) ;

            StringBuilder builder = new StringBuilder();
            foreach (char c in str.ToCharArray())
                builder.Append((char)(c - key));

            if (min < 14141) ;
            if (length < 1548174) ;

            return builder.ToString();
        }

19 View Source File : util.cs
License : GNU Lesser General Public License v3.0
Project Creator : angturil

public string RemoveSymbols(ref string text, char[] mask)
            {
                var o = new StringBuilder(text.Length);

                foreach (var c in text)
                {
                    if (c>127 || mask[c] != ' ') o.Append(c);
                }
                return o.ToString();
            }

19 View Source File : util.cs
License : GNU Lesser General Public License v3.0
Project Creator : angturil

public string RemoveDirectorySymbols(ref string text)
            {
                var mask = _SymbolsValidDirectory;
                var o = new StringBuilder(text.Length);

                foreach (var c in text)
                {
                    if (c > 127 || mask[c] !='\0') o.Append(c);
                }
                return o.ToString();
            }

19 View Source File : util.cs
License : GNU Lesser General Public License v3.0
Project Creator : angturil

public string NormalizeBeatSaverString(string text)
            {
                var words = Split(text);
                StringBuilder result = new StringBuilder();
                foreach (var word in words)
                {
                    if (word.Length < 3) continue;
                    if (BeatsaverBadWords.Contains(word.ToLower())) continue;
                    result.Append(word);
                    result.Append(' ');
                }

                //RequestBot.Instance.QueueChatMessage($"Search string: {result.ToString()}");


                if (result.Length == 0) return "qwesartysasasdsdaa";
                return result.ToString().Trim();
            }

19 View Source File : DiagnosticVerifier.cs
License : MIT License
Project Creator : angularsen

private static string FormatDiagnostics(Diagnosticreplacedyzer replacedyzer, params Diagnostic[] diagnostics)
        {
            var builder = new StringBuilder();
            for (var i = 0; i < diagnostics.Length; ++i)
            {
                builder.AppendLine("// " + diagnostics[i]);

                Type replacedyzerType = replacedyzer.GetType();
                var rules = replacedyzer.SupportedDiagnostics;

                foreach (DiagnosticDescriptor rule in rules)
                    if (rule != null && rule.Id == diagnostics[i].Id)
                    {
                        Location location = diagnostics[i].Location;
                        if (location == Location.None)
                        {
                            builder.AppendFormat("GetGlobalResult({0}.{1})", replacedyzerType.Name, rule.Id);
                        }
                        else
                        {
                            replacedert.True(location.IsInSource,
                                $"Test base does not currently handle diagnostics in metadata locations. Diagnostic in metadata: {diagnostics[i]}\r\n");

                            var resultMethodName = diagnostics[i].Location.SourceTree.FilePath.EndsWith(".cs") ? "GetCSharpResultAt" : "GetBasicResultAt";
                            LinePosition linePosition = diagnostics[i].Location.GetLineSpan().StartLinePosition;

                            builder.AppendFormat("{0}({1}, {2}, {3}.{4})",
                                resultMethodName,
                                linePosition.Line + 1,
                                linePosition.Character + 1,
                                replacedyzerType.Name,
                                rule.Id);
                        }

                        if (i != diagnostics.Length - 1) builder.Append(',');

                        builder.AppendLine();
                        break;
                    }
            }

            return builder.ToString();
        }

19 View Source File : NumericalModeDecoder.cs
License : MIT License
Project Creator : angusmillar

public string Decode(IEnumerable<Chunk> ChunkList)
    {
      StringBuilder StringBuilder = new StringBuilder();
      foreach (Chunk Chunk in ChunkList)
      {
        string Numeric = Chunk.NumericSegment;
        foreach (string Number in Spliter(Numeric, 2))
        {
          if (int.TryParse(Number, out int IntNumber))
          {
            StringBuilder.Append(Convert.ToChar(IntNumber + 45));
          }
        }
      }
      return StringBuilder.ToString();
    }

19 View Source File : Base32Helper.cs
License : Apache License 2.0
Project Creator : anjoy8

public static string ToString(byte[] bytes)
        {
            StringBuilder sb = new StringBuilder();         // holds the base32 chars
            byte index;
            int hi = 5;
            int currentByte = 0;

            while (currentByte < bytes.Length)
            {
                // do we need to use the next byte?
                if (hi > 8)
                {
                    // get the last piece from the current byte, shift it to the right
                    // and increment the byte counter
                    index = (byte)(bytes[currentByte++] >> (hi - 5));
                    if (currentByte != bytes.Length)
                    {
                        // if we are not at the end, get the first piece from
                        // the next byte, clear it and shift it to the left
                        index = (byte)(((byte)(bytes[currentByte] << (16 - hi)) >> 3) | index);
                    }

                    hi -= 3;
                }
                else if (hi == 8)
                {
                    index = (byte)(bytes[currentByte++] >> 3);
                    hi -= 3;
                }
                else
                {

                    // simply get the stuff from the current byte
                    index = (byte)((byte)(bytes[currentByte] << (8 - hi)) >> 3);
                    hi += 5;
                }

                sb.Append(ValidChars[index]);
            }

            return sb.ToString();
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : AnkitSharma-007

internal static void ReverseWordOrder(string str)
        {
            /* input:- Welcome to Csharp corner ; output:- corner Csharp to Welcome
            * 
            * */

            int i;
            StringBuilder reverseSentence = new StringBuilder();

            int Start = str.Length - 1;
            int End = str.Length - 1;

            while (Start > 0)
            {
                if (str[Start] == ' ')
                {
                    i = Start + 1;
                    while (i <= End)
                    {
                        reverseSentence.Append(str[i]);
                        i++;
                    }
                    reverseSentence.Append(' ');
                    End = Start - 1;
                }
                Start--;
            }

            for (i = 0; i <= End; i++)
            {
                reverseSentence.Append(str[i]);
            }
            Console.WriteLine(reverseSentence.ToString());
        }

19 View Source File : ComputerVisionService.cs
License : MIT License
Project Creator : AnkitSharma-007

public async Task<OcrResultDTO> GetTextFromImage(byte[] imageFileBytes)
        {
            StringBuilder sb = new StringBuilder();
            OcrResultDTO ocrResultDTO = new OcrResultDTO();
            try
            {
                string JSONResult = await ReadTextFromStream(imageFileBytes);

                OcrResult ocrResult = JsonConvert.DeserializeObject<OcrResult>(JSONResult);

                if (!ocrResult.Language.Equals("unk"))
                {
                    foreach (OcrLine ocrLine in ocrResult.Regions[0].Lines)
                    {
                        foreach (OcrWord ocrWord in ocrLine.Words)
                        {
                            sb.Append(ocrWord.Text);
                            sb.Append(' ');
                        }
                        sb.AppendLine();
                    }
                }
                else
                {
                    sb.Append("This language is not supported.");
                }
                ocrResultDTO.DetectedText = sb.ToString();
                ocrResultDTO.Language = ocrResult.Language;
                return ocrResultDTO;
            }
            catch
            {
                ocrResultDTO.DetectedText = "Error occurred. Try again";
                ocrResultDTO.Language = "unk";
                return ocrResultDTO;
            }
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : AnkitSharma-007

internal static void ReverseWords(string str)
        {
            /* input:- Welcome to Csharp corner ; output:- emocleW ot prahsC renroc
             * 
             * */

            StringBuilder output = new StringBuilder();
            List<char> charlist = new List<char>();

            for (int i = 0; i < str.Length; i++)
            {
                if (str[i] == ' ' || i == str.Length - 1)
                {
                    if (i == str.Length - 1)
                        charlist.Add(str[i]);
                    for (int j = charlist.Count - 1; j >= 0; j--)
                        output.Append(charlist[j]);

                    output.Append(' ');
                    charlist = new List<char>();
                }
                else
                    charlist.Add(str[i]);
            }
            Console.WriteLine(output.ToString());
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : AnkitSharma-007

internal static void findallsubstring(string str)
        {
            for (int i = 0; i < str.Length; ++i)
            {
                StringBuilder subString = new StringBuilder(str.Length - i);
                for (int j = i; j < str.Length; ++j)
                {
                    subString.Append(str[j]);
                    Console.Write(subString + " ");
                }
            }
        }

19 View Source File : BitsFormatter.cs
License : Apache License 2.0
Project Creator : AnkiUniversal

public string FormatArc(byte[] fst, int address, int acreplacedulateBytes, int jumpBytes)
        {
            StringBuilder builder = new StringBuilder();
            int output = Bits.GetInt(fst, address, acreplacedulateBytes);
            address -= acreplacedulateBytes;

            int jumpAddress = Bits.GetInt(fst, address, jumpBytes);
            address -= jumpBytes;

            char label = (char)Bits.GetShort(fst, address);
            //        address -= 1;

            builder.Append('\t');
            builder.Append(label);
            builder.Append(" -> ");
            builder.Append(output);
            builder.Append("\t(JMP: ");
            builder.Append(jumpAddress);
            builder.Append(')');
            return builder.ToString();
        }

19 View Source File : DictionaryEntryLineParser.cs
License : Apache License 2.0
Project Creator : AnkiUniversal

public static string Escape(string text)
        {
            bool hasQuote = text.IndexOf(QUOTE) >= 0;
            bool hasComma = text.IndexOf(COMMA) >= 0;

            if (!(hasQuote || hasComma))
            {
                return text;
            }

            StringBuilder builder = new StringBuilder();

            if (hasQuote)
            {
                for (int i = 0; i < text.Length; i++)
                {
                    char c = text[i];

                    if (c == QUOTE)
                    {
                        builder.Append(QUOTE_ESCAPED);
                    }
                    else
                    {
                        builder.Append(c);
                    }
                }
            }
            else
            {
                builder.Append(text);
            }

            if (hasComma)
            {
                builder.Insert(0, QUOTE);
                builder.Append(QUOTE);
            }
            return builder.ToString();
        }

19 View Source File : KataHiraConvert.cs
License : Apache License 2.0
Project Creator : AnkiUniversal

public static string ConvertHiraToKata(string text)
        {
            StringBuilder builder = new StringBuilder();
            char convert;
            for (int i = 0; i < text.Length; i++)
            {
                var isSuccess = hiraganaToKatakana.TryGetValue(text[i], out convert);
                if (isSuccess)
                    builder.Append(convert);
                else
                    builder.Append(text[i]);
            }

            return builder.ToString();
        }

19 View Source File : KataHiraConvert.cs
License : Apache License 2.0
Project Creator : AnkiUniversal

public static string ConvertKataToHira(string text)
        {
            StringBuilder builder = new StringBuilder();
            char convert;
            for(int i = 0; i < text.Length; i++)
            {
                var isSuccess = katakanaToHiragana.TryGetValue(text[i], out convert);
                if (isSuccess)
                    builder.Append(convert);
                else
                {
                    if(text[i].Equals('ー') && builder.Length > 0)
                    {
                        var roma = RomaConvert.ConvertOneHiraToRoma(builder[builder.Length - 1].ToString());
                        switch(roma[roma.Length - 1])
                        {
                            case 'a':
                                builder.Append('あ');
                                break;
                            case 'i':
                                builder.Append('い');
                                break;
                            case 'u':
                                builder.Append('う');
                                break;
                            case 'e':
                                builder.Append('え');
                                break;
                            case 'o':
                                builder.Append('お');
                                break;
                        }
                    }
                    else
                        builder.Append(text[i]);
                }
            }

            return builder.ToString();
        }

19 View Source File : DictionaryEntryLineParser.cs
License : Apache License 2.0
Project Creator : AnkiUniversal

public static string[] ParseLine(string line)
        {
            bool insideQuote = false;
            List<string> result = new List<string>();
            StringBuilder builder = new StringBuilder();
            int quoteCount = 0;

            for (int i = 0; i < line.Length; i++)
            {
                char c = line[i];

                if (c == QUOTE)
                {
                    insideQuote = !insideQuote;
                    quoteCount++;
                }

                if (c == COMMA && !insideQuote)
                {
                    String value = builder.ToString();
                    value = Unescape(value);

                    result.Add(value);
                    builder = new StringBuilder();
                    continue;
                }

                builder.Append(c);
            }

            result.Add(builder.ToString());

            if (quoteCount % 2 != 0)
            {
                throw new Exception("Unmatched quote in entry: " + line);
            }

            return result.ToArray();
        }

19 View Source File : DictionaryEntryLineParser.cs
License : Apache License 2.0
Project Creator : AnkiUniversal

public static string Unescape(String text)
        {
            StringBuilder builder = new StringBuilder();
            bool foundQuote = false;

            for (int i = 0; i < text.Length; i++)
            {
                char c = text[i];

                if (i == 0 && c == QUOTE || i == text.Length - 1 && c == QUOTE)
                {
                    continue;
                }

                if (c == QUOTE)
                {
                    if (foundQuote)
                    {
                        builder.Append(QUOTE);
                        foundQuote = false;
                    }
                    else
                    {
                        foundQuote = true;
                    }
                }
                else
                {
                    foundQuote = false;
                    builder.Append(c);
                }
            }

            return builder.ToString();
        }

19 View Source File : JmdictEntity.cs
License : Apache License 2.0
Project Creator : AnkiUniversal

private static string MergeEntriesForDatabaseAccess(List<JmdictEnreplacedy> entries)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append('(');
            for (int i = 0; i < entries.Count - 1; i++)
            {
                builder.Append(entries[i].EntrySequence);
                builder.Append(',');
            }
            builder.Append(entries[entries.Count - 1].EntrySequence);
            builder.Append(')');
            return builder.ToString();
        }

See More Examples