|
11
|
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
|
en: 10 Septiembre 2023, 09:28 am
|
Un algoritmo para volcar un texto de forma vertical. Inspirado en este servicio: https://onlinetexttools.com/flip-text-verticallyLos resultados son idénticos o muy similares a estos: UtilString.vb' *********************************************************************** ' Author : ElektroStudios ' Modified : 11-July-2023 ' *********************************************************************** #Region " Public Members Summary " #Region " Functions " ' FlipTextVertically(String, VerticalFlipTextMode, Opt: Char) As String #End Region #End Region #Region " Option Statements " Option Strict On Option Explicit On Option Infer Off #End Region #Region " Imports " Imports System.Collections.Generic Imports System.ComponentModel Imports System.Linq Imports System.Text #End Region #Region " String Util " ' ReSharper disable once CheckNamespace Namespace DevCase.Core.DataProcessing.Common Partial Public NotInheritable Class UtilString #Region " Public Methods " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Transforms the source string into vertical text. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <seealso href="https://onlinetexttools.com/flip-text-vertically"/> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="input"> ''' The input string to flip it vertically. ''' <para></para> ''' If this value is null, no changes are made to the string. ''' </param> ''' ''' <param name="flipMode"> ''' The vertical flip mode indicating how the text should be flipped. ''' </param> ''' ''' <param name="separatorChar"> ''' Optional. The character used to separate columns. Default is "|". ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' The resulting vertically flipped text. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Shared Function FlipTextVertically(input As String, flipMode As VerticalFlipTextMode, Optional separatorChar As Char = "|"c) As String If String.IsNullOrEmpty(input) Then Return input End If If separatorChar.Equals(Nothing) Then Throw New ArgumentNullException(paramName:=NameOf(separatorChar)) End If Select Case flipMode Case VerticalFlipTextMode.CharByChar Dim lines As String() = input.Split({Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries) Dim maxLength As Integer = lines.Max(Function(line) line.Length) Dim verticalText As New StringBuilder() For i As Integer = 0 To maxLength - 1 For j As Integer = 0 To lines.Length - 1 If i < lines(j).Length Then verticalText.Append(lines(j)(i)) Else verticalText.Append(" "c) End If If j < lines.Length - 1 Then verticalText.Append($" {separatorChar} ") End If Next verticalText.AppendLine() Next Return verticalText.ToString() Case VerticalFlipTextMode.WordByWord Dim lines As String() = input.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries) Dim wordsPerLine As New List(Of List(Of String))() For Each line As String In lines Dim words As String() = line.Split({" "c}, StringSplitOptions.RemoveEmptyEntries) wordsPerLine.Add(words.ToList()) Next Dim maxLength As Integer = wordsPerLine.Max(Function(words) words.Count) Dim verticalText As New StringBuilder() For i As Integer = 0 To maxLength - 1 For j As Integer = 0 To wordsPerLine.Count - 1 Dim words As List(Of String) = wordsPerLine(j) If i < words.Count Then verticalText.Append(words(i).PadRight(words.Max(Function(word) word.Length))) Else verticalText.Append(" ".PadRight(words.Max(Function(word) word.Length))) End If If j < wordsPerLine.Count - 1 Then verticalText.Append($" {separatorChar} ") End If Next verticalText.AppendLine() Next Return verticalText.ToString() Case VerticalFlipTextMode.SentenceBySentence Dim GetMaxSentences As Func(Of String(), Integer) = Function(_lines As String()) As Integer Dim _maxSentences As Integer = 0 For Each line As String In _lines Dim sentences As String() = line.Split({"."c}, StringSplitOptions.RemoveEmptyEntries) _maxSentences = System.Math.Max(_maxSentences, sentences.Length) Next Return _maxSentences End Function Dim GetColumnWidths As Func(Of String(), Integer, Integer()) = Function(_lines As String(), _maxSentences As Integer) As Integer() Dim _columnWidths As Integer() = New Integer(_lines.Length - 1) {} For i As Integer = 0 To _lines.Length - 1 Dim line As String = _lines(i) Dim sentences As String() = line.Split({"."c}, StringSplitOptions.RemoveEmptyEntries) Dim maxWidth As Integer = 0 For j As Integer = 0 To System.Math.Min(_maxSentences, sentences.Length) - 1 maxWidth = System.Math.Max(maxWidth, sentences(j).Trim().Length) Next _columnWidths(i) = maxWidth Next Return _columnWidths End Function Dim lines As String() = input.Split({Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries) Dim maxSentences As Integer = GetMaxSentences(lines) Dim columnWidths As Integer() = GetColumnWidths(lines, maxSentences) Dim output As New StringBuilder() For i As Integer = 0 To maxSentences - 1 For j As Integer = 0 To lines.Length - 1 Dim line As String = lines(j) Dim sentences As String() = line.Split({"."c}, StringSplitOptions.RemoveEmptyEntries) Dim sentence As String = "" If i < sentences.Length Then sentence = sentences(i).Trim() & "." End If Dim column As String = sentence.PadRight(columnWidths(j) + 1) output.Append(column) If j < lines.Length - 1 Then output.Append($" {separatorChar} ") End If Next output.AppendLine() Next Return output.ToString() Case Else Throw New InvalidEnumArgumentException(argumentName:=NameOf(flipMode), invalidValue:=flipMode, enumClass:=GetType(VerticalFlipTextMode)) End Select End Function #End Region End Class End Namespace #End Region
VerticalFlipTextMode.vb' *********************************************************************** ' Author : ElektroStudios ' Modified : 11-July-2023 ' *********************************************************************** #Region " Option Statements " Option Strict Off Option Explicit On Option Infer Off #End Region #Region " Imports " #End Region #Region " VerticalFlipTextMode " ' ReSharper disable once CheckNamespace Namespace DevCase.Core.DataProcessing.Common ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Specifies how the text should be flipped when using <see cref="UtilString.FlipTextVertically"/> function. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Public Enum VerticalFlipTextMode As Integer ''' <summary> ''' Divides the text into characters. ''' That is, all the characters from every text row get rearranged in columns. ''' </summary> CharByChar ''' <summary> ''' Divides the text into words. ''' <para></para> ''' That is, all the words from every text row get rearranged in columns. ''' </summary> WordByWord ''' <summary> ''' Divides the text into sentences. ''' <para></para> ''' That is, if you have several sentences in one line, ''' then after rewriting them vertically, they will appear in a single column. ''' </summary> SentenceBySentence End Enum End Namespace #End Region
|
|
|
12
|
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
|
en: 10 Septiembre 2023, 09:20 am
|
Un algoritmo para justificar un string. Me he inspirado en este servicio online: https://onlinetexttools.com/justify-textEjemplo de uso: Dim input As String = "About 20% of oxygen is produced by the Amazon rainforest. The Earth's atmosphere is about 78 percent nitrogen, 21 percent oxygen, and about 1 percent other gases. For the existence of most organisms on the planet, oxygen is a necessary element, it provides the body with energy and removes carbon dioxide. Fortunately, plants constantly replenish the oxygen level of our planet thanks to photosynthesis. During this process, carbon dioxide and water are converted into energy, releasing oxygen as a byproduct. The Amazon rainforest covers 5.5 million square kilometers (2.1 million square miles), recycling much of the Earth's oxygen while absorbing large amounts of carbon dioxide." Dim lineLength As Integer = 50 Dim result As String = UtilString.JustifyText(input, lineLength, justifyLastLine:=True) Console.WriteLine(result)
Salida: About 20% of oxygen is produced by the Amazon rainforest. The Earth's atmosphere is about 78 percent nitrogen, 21 percent oxygen, and about 1 percent other gases.
For the existence of most organisms on the planet, oxygen is a necessary element, it provides the body with energy and removes carbon dioxide. Fortunately, plants constantly replenish the oxygen level of our planet thanks to photosynthesis. During this process, carbon dioxide and water are converted into energy, releasing oxygen as a byproduct.
The Amazon rainforest covers 5.5 million square kilometers (2.1 million square miles), recycling much of the Earth's oxygen while absorbing large amounts of carbon dioxide. ' *********************************************************************** ' Author : ElektroStudios ' Modified : 13-July-2023 ' *********************************************************************** #Region " Public Members Summary " #Region " Functions " ' JustifyText(String, Integer, Opt: Boolean) As String #End Region #End Region #Region " Option Statements " Option Strict On Option Explicit On Option Infer Off #End Region #Region " Imports " Imports System.Collections.ObjectModel Imports System.Text #End Region #Region " String Util " ' ReSharper disable once CheckNamespace Namespace DevCase.Core.DataProcessing.Common Partial Public NotInheritable Class UtilString #Region " Public Methods " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Justifies the input text by adjusting the line width and spacing between words. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code language="VB.NET"> ''' Dim input As String = ''' "About 20% of oxygen is produced by the Amazon rainforest. The Earth's atmosphere is about 78 percent nitrogen, 21 percent oxygen, and about 1 percent other gases. ''' ''' For the existence of most organisms on the planet, oxygen is a necessary element, it provides the body with energy and removes carbon dioxide. Fortunately, plants constantly replenish the oxygen level of our planet thanks to photosynthesis. During this process, carbon dioxide and water are converted into energy, releasing oxygen as a byproduct. ''' ''' The Amazon rainforest covers 5.5 million square kilometers (2.1 million square miles), recycling much of the Earth's oxygen while absorbing large amounts of carbon dioxide." ''' ''' Dim lineLength As Integer = 50 ''' ''' Dim result As String = JustifyText(input, lineLength, justifyLastLine:=True) ''' ''' Console.WriteLine(result) ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="input"> ''' The input text. ''' </param> ''' ''' <param name="length"> ''' The desired length for each text line. ''' </param> ''' ''' <param name="justifyLastLine"> ''' Optional. Indicates whether to justify the last line of the paragraphs. ''' <para></para> ''' Default value is: False. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' The resulting justified text. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Shared Function JustifyText(input As String, length As Integer, Optional justifyLastLine As Boolean = False) As String Dim paragraphs As String() = input.Split({Environment.NewLine}, StringSplitOptions.None) Dim paragraphsCount As Integer = paragraphs.Length For paragraphIdx As Integer = 0 To paragraphsCount - 1 Dim words As String() = paragraphs(paragraphIdx).Split(" "c) Dim currentLine As New StringBuilder() Dim currentLineLength As Integer = 0 For Each word As String In words Dim wordLength As Integer = word.Length If currentLineLength + wordLength <= length Then currentLine.Append(word & " ") currentLineLength += wordLength + 1 Else lines.Add(currentLine.ToString().Trim()) currentLine = New StringBuilder(word & " ") currentLineLength = wordLength + 1 End If If wordLength > length Then Dim remainingWord As String = word While remainingWord.Length > length lines.Add(remainingWord.Substring(0, length)) remainingWord = remainingWord.Substring(length) End While If remainingWord.Length > 0 Then lines.Add(remainingWord) End If End If Next lines.Add(currentLine.ToString().Trim()) For i As Integer = 0 To lines.Count - 1 Dim line As String = lines(i) If (i = lines.Count - 1) AndAlso Not justifyLastLine Then justifiedLines.Add(line) Continue For End If Dim lineLength As Integer = line.Length Dim wordsInLine As String() = line.Split(" "c) Dim wordsCount As Integer = wordsInLine.Length If wordsCount > 1 Then Dim remainingSpaces As Integer = length - line.Replace(" "c, "").Length Dim spacesPerGap As Integer = remainingSpaces \ (wordsCount - 1) Dim extraSpaces As Integer = remainingSpaces Mod (wordsCount - 1) Dim justifiedLine As New StringBuilder(wordsInLine(0)) For j As Integer = 1 To wordsCount - 1 justifiedLine.Append(" "c, spacesPerGap) If j <= extraSpaces Then justifiedLine.Append(" "c) End If justifiedLine.Append(wordsInLine(j)) Next line = justifiedLine.ToString() End If justifiedLines.Add(line) Next If Not justifyLastLine AndAlso justifiedLines.Count > 1 Then justifiedLines(justifiedLines.Count - 1) = justifiedLines(justifiedLines.Count - 1).TrimEnd() End If Next Return String.Join(Environment.NewLine, justifiedLines) End Function #End Region End Class End Namespace #End Region
|
|
|
13
|
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
|
en: 10 Septiembre 2023, 09:12 am
|
Un código para convertir el texto de un string a superscript y vice-versa. Ejemplos de uso: Dim input As String = "The ideal temperature for sleeping is 18.3 degrees Celsius (65 degrees Fahrenheit)" Dim result As String = ConvertToSuperscript(input)
Dim input As String = "ᵀʰᵉ ⁱᵈᵉᵃˡ ᵗᵉᵐᵖᵉʳᵃᵗᵘʳᵉ ᶠᵒʳ ˢˡᵉᵉᵖⁱⁿᵍ ⁱˢ ¹⁸⋅³ ᵈᵉᵍʳᵉᵉˢ ᑦᵉˡˢⁱᵘˢ ⁽⁶⁵ ᵈᵉᵍʳᵉᵉˢ ⸁ᵃʰʳᵉⁿʰᵉⁱᵗ⁾" Dim result As String = ConvertFromSuperscript(input)
' *********************************************************************** ' Author : ElektroStudios ' Modified : 11-July-2023 ' *********************************************************************** #Region " Public Members Summary " #Region " Functions " ' ConvertToSuperscript(String) As String ' ConvertFromSuperscript(String) As String #End Region #End Region #Region " Option Statements " Option Strict On Option Explicit On Option Infer Off #End Region #Region " Imports " Imports System.Collections.Generic Imports System.ComponentModel Imports System.Text #End Region #Region " String Util " ' ReSharper disable once CheckNamespace Namespace DevCase.Core.DataProcessing.Common Partial Public NotInheritable Class UtilString #Region " Private Fields " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Character map used by functions that converts ASCII characters to its Superscript forms. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Private Shared charMapAsciiToSuperscript As Dictionary(Of Char, Char ) ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Character map used by functions that converts Superscript characters to its ASCII forms. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Private Shared charMapSuperscriptToAscii As List(Of KeyValuePair(Of Char, Char)) #End Region #Region " Public Methods " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Converts the characters in the input string to their corresponding superscript forms. ''' <para></para> ''' Letters in a superscript text are half the normal letter size and are placed above the middle of a text line. ''' For example, the word "Sunshine" in superscript looks like this: "ᔆᵘⁿˢʰⁱⁿᵉ". ''' <para></para> ''' Superscripts are often used in mathematics to denote powers of a number, such as "x²" or "yᵐ". ''' They are also often used to write ordinal numbers, for example, 1ˢᵗ, 2ⁿᵈ, 3ʳᵈ, 4ᵗʰ, and so on. ''' <para></para> ''' Superscript (Wikipedia): <see href="https://en.wikipedia.org/wiki/Subscript_and_superscript"/> ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code language="VB.NET"> ''' Dim input As String = "The ideal temperature for sleeping is 18.3 degrees Celsius (65 degrees Fahrenheit)" ''' Dim result As String = ConvertToSuperscript(input) ''' Console.WriteLine(result) ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="input"> ''' The input string to convert to superscript. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' The input string converted to their corresponding superscript forms. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Shared Function ConvertToSuperscript(input As String) As String If String.IsNullOrWhiteSpace(input) Then Throw New ArgumentNullException(paramName:=NameOf(input)) End If If UtilString.charMapAsciiToSuperscript Is Nothing Then UtilString.charMapAsciiToSuperscript = New Dictionary(Of Char, Char )(EqualityComparer (Of Char ). Default) From { {"0"c, "⁰"c}, {"1"c, "¹"c}, {"2"c, "²"c}, {"3"c, "³"c}, {"4"c, "⁴"c}, {"5"c, "⁵"c}, {"6"c, "⁶"c}, {"7"c, "⁷"c}, {"8"c, "⁸"c}, {"9"c, "⁹"c}, {"+"c, "⁺"c}, {"-"c, "⁻"c}, {"="c, "⁼"c}, {"("c, "⁽"c}, {")"c, "⁾"c}, {"."c, "⋅"c}, {"·"c, "˙"c}, {"a"c, "ᵃ"c}, {"b"c, "ᵇ"c}, {"c"c, "ᶜ"c}, {"d"c, "ᵈ"c}, {"e"c, "ᵉ"c}, {"f"c, "ᶠ"c}, {"g"c, "ᵍ"c}, {"h"c, "ʰ"c}, {"i"c, "ⁱ"c}, {"j"c, "ʲ"c}, {"k"c, "ᵏ"c}, {"l"c, "ˡ"c}, {"m"c, "ᵐ"c}, {"n"c, "ⁿ"c}, {"o"c, "ᵒ"c}, {"p"c, "ᵖ"c}, {"q"c, "۹"c}, {"r"c, "ʳ"c}, {"s"c, "ˢ"c}, {"t"c, "ᵗ"c}, {"u"c, "ᵘ"c}, {"v"c, "ᵛ"c}, {"w"c, "ʷ"c}, {"x"c, "ˣ"c}, {"y"c, "ʸ"c}, {"z"c, "ᶻ"c}, {"A"c, "ᴬ"c}, {"B"c, "ᴮ"c}, {"C"c, "ᑦ"c}, {"D"c, "ᴰ"c}, {"E"c, "ᴱ"c}, {"F"c, "⸁"c}, {"G"c, "ᴳ"c}, {"H"c, "ᴴ"c}, {"I"c, "ᴵ"c}, {"J"c, "ᴶ"c}, {"K"c, "ᴷ"c}, {"L"c, "ᴸ"c}, {"M"c, "ᴹ"c}, {"N"c, "ᴺ"c}, {"O"c, "ᴼ"c}, {"P"c, "ᴾ"c}, {"Q"c, "ᑫ"c}, {"R"c, "ᴿ"c}, {"S"c, "ᔆ"c}, {"T"c, "ᵀ"c}, {"U"c, "ᵁ"c}, {"V"c, "ⱽ"c}, {"W"c, "ᵂ"c}, {"X"c, "ᕽ"c}, {"Y"c, "ʸ"c}, {"Z"c, "ᙆ"c} } End If Dim sb As New StringBuilder(input.Length) For Each c As Char In input Dim value As Char = Nothing If UtilString.charMapAsciiToSuperscript.TryGetValue(c, value) Then sb.Append(value) Else sb.Append(c) End If Next Return sb.ToString() End Function ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Converts the characters in the input string to their corresponding superscript forms. ''' <para></para> ''' Letters in a superscript text are half the normal letter size and are placed above the middle of a text line. ''' For example, the word "Sunshine" in superscript looks like this: "ᔆᵘⁿˢʰⁱⁿᵉ". ''' <para></para> ''' Superscripts are often used in mathematics to denote powers of a number, such as "x²" or "yᵐ". ''' They are also often used to write ordinal numbers, for example, 1ˢᵗ, 2ⁿᵈ, 3ʳᵈ, 4ᵗʰ, and so on. ''' <para></para> ''' Superscript (Wikipedia): <see href="https://en.wikipedia.org/wiki/Subscript_and_superscript"/> ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code language="VB.NET"> ''' Dim input As String = "ᵀʰᵉ ⁱᵈᵉᵃˡ ᵗᵉᵐᵖᵉʳᵃᵗᵘʳᵉ ᶠᵒʳ ˢˡᵉᵉᵖⁱⁿᵍ ⁱˢ ¹⁸⋅³ ᵈᵉᵍʳᵉᵉˢ ᑦᵉˡˢⁱᵘˢ ⁽⁶⁵ ᵈᵉᵍʳᵉᵉˢ ⸁ᵃʰʳᵉⁿʰᵉⁱᵗ⁾" ''' Dim result As String = ConvertFromSuperscript(input) ''' Console.WriteLine(result) ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="input"> ''' The input string to convert to superscript. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' The input string converted to their corresponding superscript forms. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Shared Function ConvertFromSuperscript(input As String) As String If String.IsNullOrWhiteSpace(input) Then Throw New ArgumentNullException(paramName:=NameOf(input)) End If If UtilString.charMapSuperscriptToAscii Is Nothing Then UtilString.charMapSuperscriptToAscii = New List(Of KeyValuePair(Of Char, Char)) From { {New KeyValuePair(Of Char, Char)("⁰"c, "0"c)}, {New KeyValuePair(Of Char, Char)("¹"c, "1"c)}, {New KeyValuePair(Of Char, Char)("²"c, "2"c)}, {New KeyValuePair(Of Char, Char)("³"c, "3"c)}, {New KeyValuePair(Of Char, Char)("⁴"c, "4"c)}, {New KeyValuePair(Of Char, Char)("⁵"c, "5"c)}, {New KeyValuePair(Of Char, Char)("⁶"c, "6"c)}, {New KeyValuePair(Of Char, Char)("⁷"c, "7"c)}, {New KeyValuePair(Of Char, Char)("⁸"c, "8"c)}, {New KeyValuePair(Of Char, Char)("⁹"c, "9"c)}, {New KeyValuePair(Of Char, Char)("⁺"c, "+"c)}, {New KeyValuePair(Of Char, Char)("⁻"c, "-"c)}, {New KeyValuePair(Of Char, Char)("⁼"c, "="c)}, {New KeyValuePair(Of Char, Char)("⁽"c, "("c)}, {New KeyValuePair(Of Char, Char)("⁾"c, ")"c)}, {New KeyValuePair(Of Char, Char)("⋅"c, "."c)}, {New KeyValuePair(Of Char, Char)("˙"c, "·"c)}, {New KeyValuePair(Of Char, Char)("ᵃ"c, "a"c)}, {New KeyValuePair(Of Char, Char)("ᵇ"c, "b"c)}, {New KeyValuePair(Of Char, Char)("ᶜ"c, "c"c)}, {New KeyValuePair(Of Char, Char)("ᵈ"c, "d"c)}, {New KeyValuePair(Of Char, Char)("ᵉ"c, "e"c)}, {New KeyValuePair(Of Char, Char)("ᶠ"c, "f"c)}, {New KeyValuePair(Of Char, Char)("ᵍ"c, "g"c)}, {New KeyValuePair(Of Char, Char)("ʰ"c, "h"c)}, {New KeyValuePair(Of Char, Char)("ⁱ"c, "i"c)}, {New KeyValuePair(Of Char, Char)("ʲ"c, "j"c)}, {New KeyValuePair(Of Char, Char)("ᵏ"c, "k"c)}, {New KeyValuePair(Of Char, Char)("ˡ"c, "l"c)}, {New KeyValuePair(Of Char, Char)("ᵐ"c, "m"c)}, {New KeyValuePair(Of Char, Char)("ⁿ"c, "n"c)}, {New KeyValuePair(Of Char, Char)("ᵒ"c, "o"c)}, {New KeyValuePair(Of Char, Char)("ᵖ"c, "p"c)}, {New KeyValuePair(Of Char, Char)("۹"c, "q"c)}, {New KeyValuePair(Of Char, Char)("ʳ"c, "r"c)}, {New KeyValuePair(Of Char, Char)("ˢ"c, "s"c)}, {New KeyValuePair(Of Char, Char)("ᵗ"c, "t"c)}, {New KeyValuePair(Of Char, Char)("ᵘ"c, "u"c)}, {New KeyValuePair(Of Char, Char)("ᵛ"c, "v"c)}, {New KeyValuePair(Of Char, Char)("ʷ"c, "w"c)}, {New KeyValuePair(Of Char, Char)("ˣ"c, "x"c)}, {New KeyValuePair(Of Char, Char)("ʸ"c, "y"c)}, {New KeyValuePair(Of Char, Char)("ᶻ"c, "z"c)}, {New KeyValuePair(Of Char, Char)("ᴬ"c, "A"c)}, {New KeyValuePair(Of Char, Char)("ᴮ"c, "B"c)}, {New KeyValuePair(Of Char, Char)("ᑦ"c, "C"c)}, {New KeyValuePair(Of Char, Char)("ᴰ"c, "D"c)}, {New KeyValuePair(Of Char, Char)("ᴱ"c, "E"c)}, {New KeyValuePair(Of Char, Char)("⸁"c, "F"c)}, {New KeyValuePair(Of Char, Char)("ᴳ"c, "G"c)}, {New KeyValuePair(Of Char, Char)("ᴴ"c, "H"c)}, {New KeyValuePair(Of Char, Char)("ᴵ"c, "I"c)}, {New KeyValuePair(Of Char, Char)("ᴶ"c, "J"c)}, {New KeyValuePair(Of Char, Char)("ᴷ"c, "K"c)}, {New KeyValuePair(Of Char, Char)("ᴸ"c, "L"c)}, {New KeyValuePair(Of Char, Char)("ᴹ"c, "M"c)}, {New KeyValuePair(Of Char, Char)("ᴺ"c, "N"c)}, {New KeyValuePair(Of Char, Char)("ᴼ"c, "O"c)}, {New KeyValuePair(Of Char, Char)("ᴾ"c, "P"c)}, {New KeyValuePair(Of Char, Char)("ᑫ"c, "Q"c)}, {New KeyValuePair(Of Char, Char)("ᴿ"c, "R"c)}, {New KeyValuePair(Of Char, Char)("ᔆ"c, "S"c)}, {New KeyValuePair(Of Char, Char)("ᵀ"c, "T"c)}, {New KeyValuePair(Of Char, Char)("ᵁ"c, "U"c)}, {New KeyValuePair(Of Char, Char)("ⱽ"c, "V"c)}, {New KeyValuePair(Of Char, Char)("ᵂ"c, "W"c)}, {New KeyValuePair(Of Char, Char)("ᕽ"c, "X"c)}, {New KeyValuePair(Of Char, Char)("ʸ"c, "Y"c)}, {New KeyValuePair(Of Char, Char)("ᙆ"c, "Z"c)} } End If Dim defaultPair As New KeyValuePair(Of Char, Char) Dim sb As New StringBuilder(input.Length) For Each c As Char In input Dim pair As KeyValuePair(Of Char, Char) = charMapSuperscriptToAscii.Find(Function(kv) kv.Key = c) If Not pair.Equals(defaultPair) Then sb.Append(pair.Value) Else sb.Append(c) End If Next Return sb.ToString() End Function #End Region End Class End Namespace #End Region
|
|
|
14
|
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
|
en: 10 Septiembre 2023, 09:05 am
|
CONTINUACIÓN DEL CÓDIGO DE ARRIBA ☝️☝️☝️ UnicodeAlphabeticCharacterSets.vb' *********************************************************************** ' Author : ElektroStudios ' Modified : 11-July-2023 ' *********************************************************************** #Region " Option Statements " Option Strict On Option Explicit On Option Infer Off #End Region #Region " UnicodeAlphabeticCharacterSets " ' ReSharper disable once CheckNamespace Namespace DevCase.Core.DataProcessing.Common ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Specifies a Unicode alphabetic character set. ''' <para></para> ''' This enum is used by <see cref="UtilString.ConvertToUnicodeLetters"/> function. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' The Unicode character sets are standardized sets of characters that cover ''' various scripts and symbols used in written languages worldwide. ''' <para></para> ''' Unicode provides a unique code point for each character, ensuring interoperability and ''' compatibility across different platforms and systems. ''' <para></para> ''' The alphabetic character sets defined in this enumeration represent ''' specific stylistic variations of alphabetic characters used in mathematics and typography. ''' <para></para> ''' These character sets are commonly used in scientific and mathematical contexts, ''' as well as in typography and font design. ''' <para></para> ''' They allow for precise representation of stylized alphabetic characters ''' in various mathematical equations, formulas, and text layouts. ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- Public Enum UnicodeAlphabeticCharacterSets ''' <summary> ''' Unicode symbols from the 'Mathematical Bold Italic' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D468 to U+1D49B), ''' representing the alphabet letters from 'a' to 'Z'. ''' <para></para> ''' e.g., 'A': '𝑨', 'a': '𝒂'. ''' </summary> MathematicalBoldItalic ''' <summary> ''' Unicode symbols from the 'Mathematical Bold Script' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D4D0 to U+1D503), ''' representing the alphabet letters from 'a' to 'Z'. ''' <para></para> ''' e.g., 'A': '𝓐', 'a': '𝓪'. ''' </summary> MathematicalBoldScript ''' <summary> ''' Unicode symbols from the 'Mathematical Italic' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D434 to U+1D467), ''' representing the alphabet letters from 'a' to 'Z'. ''' <para></para> ''' e.g., 'A': '𝐴', 'a': '𝑎'. ''' </summary> MathematicalItalic ''' <summary> ''' Unicode symbols from the 'Sans-Serif Bold Italic' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D63C to U+1D66F), ''' representing the alphabet letters from 'a' to 'Z'. ''' <para></para> ''' e.g., 'A': '𝘼', 'a': '𝙖'. ''' </summary> SansSerifBoldItalic ''' <summary> ''' Unicode symbols from the 'Sans-Serif Italic' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D608 to U+1D63B), ''' representing the alphabet letters from 'a' to 'Z'. ''' <para></para> ''' e.g., 'A': '𝘈', 'a': '𝘢'. ''' </summary> SansSerifItalic End Enum End Namespace #End Region
UnicodeAlphanumericCharacterSets.vb' *********************************************************************** ' Author : ElektroStudios ' Modified : 11-July-2023 ' *********************************************************************** #Region " Option Statements " Option Strict On Option Explicit On Option Infer Off #End Region #Region " UnicodeAlphanumericCharacterSets " ' ReSharper disable once CheckNamespace Namespace DevCase.Core.DataProcessing.Common ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Specifies a Unicode alphanumeric character set. ''' <para></para> ''' This enum is used by <see cref="UtilString.ConvertToUnicodeLetters"/> function. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' The Unicode character sets are standardized sets of characters that cover ''' various scripts and symbols used in written languages worldwide. ''' <para></para> ''' Unicode provides a unique code point for each character, ensuring interoperability and ''' compatibility across different platforms and systems. ''' <para></para> ''' The alphanumeric character sets defined in this enumeration represent ''' specific stylistic variations of alphabetic characters used in mathematics and typography. ''' <para></para> ''' These character sets are commonly used in scientific and mathematical contexts, ''' as well as in typography and font design. ''' <para></para> ''' They allow for precise representation of stylized alphabetic characters ''' in various mathematical equations, formulas, and text layouts. ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- Public Enum UnicodeAlphanumericCharacterSets ''' <summary> ''' Unicode symbols from the 'Mathematical Bold' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D400 to U+1D433), ''' representing the alphabet letters from 'a' to 'Z' and numbers from '0' to '9'. ''' <para></para> ''' e.g., 'A': '𝐀', 'a': '𝐚'. ''' </summary> MathematicalBold ''' <summary> ''' Unicode symbols from the 'Monospace' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D670 to U+1D6A3), ''' representing the alphabet letters from 'a' to 'Z' and numbers from '0' to '9'. ''' <para></para> ''' e.g., 'A': '𝙰', 'a': '𝚊'. ''' </summary> MonoSpace ''' <summary> ''' Unicode symbols from the 'Sans-Serif' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D5A0 to U+1D5D3), ''' representing the alphabet letters from 'a' to 'Z' and numbers from '0' to '9'. ''' <para></para> ''' e.g., 'A': '𝖠', 'a': '𝖺'. ''' </summary> SansSerif ''' <summary> ''' Unicode symbols from the 'Sans-Serif Bold' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D5D4 to U+1D607), ''' representing the alphabet letters from 'a' to 'Z' and numbers from '0' to '9'. ''' <para></para> ''' e.g., 'A': '𝗔', 'a': '𝗮'. ''' </summary> SansSerifBold End Enum End Namespace #End Region
UtilString.vb' *********************************************************************** ' Author : ElektroStudios ' Modified : 11-July-2023 ' *********************************************************************** #Region " Public Members Summary " #Region " Functions " ' ConvertToUnicodeLetters(String, UnicodeAlphabeticCharacterSets) As String ' ConvertToUnicodeLetters(String, UnicodeAlphanumericCharacterSets) As String #End Region #End Region #Region " Option Statements " Option Strict On Option Explicit On Option Infer Off #End Region #Region " Imports " Imports System.Collections.Generic Imports System.ComponentModel Imports System.Text #End Region #Region " String Util " ' ReSharper disable once CheckNamespace Namespace DevCase.Core.DataProcessing.Common Partial Public NotInheritable Class UtilString #Region " Public Methods " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Converts the alphabetic characters in the input string to their corresponding ''' Unicode representations based on the specified character set. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="input"> ''' The input string to convert. ''' </param> ''' ''' <param name="charSet"> ''' The Unicode character set to use for the character conversion. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' The input string with alphabetic characters replaced by their Unicode counterparts. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Shared Function ConvertToUnicodeLetters(input As String, charSet As UnicodeAlphabeticCharacterSets) As String If String.IsNullOrWhiteSpace(input) Then Return input End If Select Case charSet Case UnicodeAlphabeticCharacterSets.MathematicalBoldItalic charMap = UnicodeCharacterMaps.MathematicalBoldItalic Case UnicodeAlphabeticCharacterSets.MathematicalBoldScript charMap = UnicodeCharacterMaps.MathematicalBoldScript Case UnicodeAlphabeticCharacterSets.MathematicalItalic charMap = UnicodeCharacterMaps.MathematicalItalic Case UnicodeAlphabeticCharacterSets.SansSerifBoldItalic charMap = UnicodeCharacterMaps.SansSerifBoldItalic Case UnicodeAlphabeticCharacterSets.SansSerifItalic charMap = UnicodeCharacterMaps.SansSerifItalic Case Else Throw New InvalidEnumArgumentException(argumentName:=NameOf(charSet), invalidValue:=charSet, enumClass:=GetType(UnicodeAlphabeticCharacterSets)) End Select Dim sb As New StringBuilder(input.Length) For Each c As Char In input Dim value As String = Nothing If charMap.TryGetValue(c, value) Then sb.Append(value) Else sb.Append(c) End If Next Return sb.ToString() End Function ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Converts the alphanumeric characters in the input string to their corresponding ''' Unicode representations based on the specified character set. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="input"> ''' The input string to convert. ''' </param> ''' ''' <param name="charSet"> ''' The Unicode character set to use for the character conversion. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' The input string with alphanumeric characters replaced by their Unicode counterparts. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Shared Function ConvertToUnicodeLetters(input As String, charSet As UnicodeAlphanumericCharacterSets) As String If String.IsNullOrWhiteSpace(input) Then Return input End If Select Case charSet Case UnicodeAlphanumericCharacterSets.MathematicalBold charMap = UnicodeCharacterMaps.MathematicalBold Case UnicodeAlphanumericCharacterSets.MonoSpace charMap = UnicodeCharacterMaps.MonoSpace Case UnicodeAlphanumericCharacterSets.SansSerif charMap = UnicodeCharacterMaps.SansSerif Case UnicodeAlphanumericCharacterSets.SansSerifBold charMap = UnicodeCharacterMaps.SansSerifBold Case Else Throw New InvalidEnumArgumentException(argumentName:=NameOf(charSet), invalidValue:=charSet, enumClass:=GetType(UnicodeAlphanumericCharacterSets)) End Select Dim sb As New StringBuilder(input.Length) For Each c As Char In input Dim value As String = Nothing If charMap.TryGetValue(c, value) Then sb.Append(value) Else sb.Append(c) End If Next Return sb.ToString() End Function #End Region End Class End Namespace #End Region
|
|
|
15
|
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
|
en: 10 Septiembre 2023, 09:03 am
|
Un código para convertir el texto de un String a sets de caracteres Unicode. Nota: como resultará evidente, no es posible añadir soporte para los caracteres que carecen de un equivalente. UnicodeCharacterMaps.vb' *********************************************************************** ' Author : ElektroStudios ' Modified : 11-July-2023 ' *********************************************************************** #Region " Option Statements " Option Strict Off Option Explicit On Option Infer Off #End Region #Region " Public Members Summary " #Region " Properties " ' MathematicalBold As Dictionary(Of Char, String) ' MathematicalBoldItalic As Dictionary(Of Char, String) ' MathematicalBoldScript As Dictionary(Of Char, String) ' MathematicalItalic As Dictionary(Of Char, String) ' MonoSpace As Dictionary(Of Char, String) ' SansSerif As Dictionary(Of Char, String) ' SansSerifBold As Dictionary(Of Char, String) ' SansSerifBoldItalic As Dictionary(Of Char, String) ' SansSerifItalic As Dictionary(Of Char, String) #End Region #End Region #Region " Imports " Imports System.Collections.Generic #End Region #Region " UnicodeCharacterMaps " ' ReSharper disable once CheckNamespace Namespace DevCase.Core.DataProcessing.Common ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Provides access to predefined alphabetic and alphanumeric character maps for a range of Unicode character sets. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' The Unicode character sets are standardized sets of characters that cover ''' various scripts and symbols used in written languages worldwide. ''' <para></para> ''' Unicode provides a unique code point for each character, ensuring interoperability and ''' compatibility across different platforms and systems. ''' <para></para> ''' The character sets defined in this class represent specific stylistic variations ''' of alphabetic characters used in mathematics and typography. ''' <para></para> ''' These character sets are commonly used in scientific and mathematical contexts, ''' as well as in typography and font design. ''' <para></para> ''' They allow for precise representation of stylized alphabetic characters ''' in various mathematical equations, formulas, and text layouts. ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- Public Class UnicodeCharacterMaps #Region " Private Fields " ''' <summary> ''' (Backing Field) ''' <para></para> ''' A dictionary where the keys are the alphabet letters from 'a' to 'Z' and numbers from '0' to '9', ''' and the values are their corresponding symbols from the 'Mathematical Bold' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D400 to U+1D433). ''' <para></para> ''' e.g., dictionary key: 'A' gets value: '𝐀', and dictionary key: 'a' gets value: '𝐚'. ''' </summary> Private Shared _mathematicalBold As Dictionary(Of Char, String) ''' <summary> ''' (Backing Field) ''' <para></para> ''' A dictionary where the keys are the alphabet letters from 'a' to 'Z', ''' and the values are their corresponding symbols from the 'Mathematical Italic' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D434 to U+1D467). ''' <para></para> ''' e.g., dictionary key: 'A' gets value: '𝐴', and dictionary key: 'a' gets value: '𝑎'. ''' </summary> Private Shared _mathematicalItalic As Dictionary(Of Char, String) ''' <summary> ''' (Backing Field) ''' <para></para> ''' A dictionary where the keys are the alphabet letters from 'a' to 'Z', ''' and the values are their corresponding symbols from the 'Mathematical Bold Italic' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D468 to U+1D49B). ''' <para></para> ''' e.g., dictionary key: 'A' gets value: '𝑨', and dictionary key: 'a' gets value: '𝒂'. ''' </summary> Private Shared _mathematicalBoldItalic As Dictionary(Of Char, String) ''' <summary> ''' (Backing Field) ''' <para></para> ''' A dictionary where the keys are the alphabet letters from 'a' to 'Z', ''' and the values are their corresponding symbols from the 'Mathematical Bold Script' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D4D0 to U+1D503). ''' <para></para> ''' e.g., dictionary key: 'A' gets value: '𝓐', and dictionary key: 'a' gets value: '𝓪'. ''' </summary> Private Shared _mathematicalBoldScript As Dictionary(Of Char, String) ''' <summary> ''' (Backing Field) ''' <para></para> ''' A dictionary where the keys are the alphabet letters from 'a' to 'Z' and numbers from '0' to '9', ''' and the values are their corresponding symbols from the 'Sans-Serif' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D5A0 to U+1D5D3). ''' <para></para> ''' e.g., dictionary key: 'A' gets value: '𝖠', and dictionary key: 'a' gets value: '𝖺'. ''' </summary> Private Shared _sansSerif As Dictionary(Of Char, String) ''' <summary> ''' (Backing Field) ''' <para></para> ''' A dictionary where the keys are the alphabet letters from 'a' to 'Z' and numbers from '0' to '9', ''' and the values are their corresponding symbols from the 'Sans-Serif Bold' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D5D4 to U+1D607). ''' <para></para> ''' e.g., dictionary key: 'A' gets value: '𝗔', and dictionary key: 'a' gets value: '𝗮'. ''' </summary> Private Shared _sansSerifBold As Dictionary(Of Char, String) ''' <summary> ''' (Backing Field) ''' <para></para> ''' A dictionary where the keys are the alphabet letters from 'a' to 'Z', ''' and the values are their corresponding symbols from the 'Sans-Serif Italic' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D608 to U+1D63B). ''' <para></para> ''' e.g., dictionary key: 'A' gets value: '𝘈', and dictionary key: 'a' gets value: '𝘢'. ''' </summary> Private Shared _sansSerifItalic As Dictionary(Of Char, String) ''' <summary> ''' (Backing Field) ''' <para></para> ''' A dictionary where the keys are the alphabet letters from 'a' to 'Z', ''' and the values are their corresponding symbols from the 'Sans-Serif Bold Italic' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D63C to U+1D66F). ''' <para></para> ''' e.g., dictionary key: 'A' gets value: '𝘼', and dictionary key: 'a' gets value: '𝙖'. ''' </summary> Private Shared _sansSerifBoldItalic As Dictionary(Of Char, String) ''' <summary> ''' (Backing Field) ''' <para></para> ''' A dictionary where the keys are the alphabet letters from 'a' to 'Z' and numbers from '0' to '9', ''' and the values are their corresponding symbols from the 'Monospace' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D670 to U+1D6A3). ''' <para></para> ''' e.g., dictionary key: 'A' gets value: '𝙰', and dictionary key: 'a' gets value: '𝚊'. ''' </summary> Private Shared _monoSpace As Dictionary(Of Char, String) #End Region #Region " Properties " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Gets a dictionary where the keys are the alphabet letters from 'a' to 'Z' and numbers from '0' to '9', ''' and the values are their corresponding symbols from the 'Mathematical Bold' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D400 to U+1D433). ''' <para></para> ''' e.g., dictionary key: 'A' gets value: '𝐀', and dictionary key: 'a' gets value: '𝐚'. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Public Shared ReadOnly Property MathematicalBold As Dictionary(Of Char, String) Get If UnicodeCharacterMaps._mathematicalBold Is Nothing Then UnicodeCharacterMaps._mathematicalBold = New Dictionary(Of Char, String)(EqualityComparer (Of Char ). Default) From { {"A"c, "𝐀"}, {"B"c, "𝐁"}, {"C"c, "𝐂"}, {"D"c, "𝐃"}, {"E"c, "𝐄"}, {"F"c, "𝐅"}, {"G"c, "𝐆"}, {"H"c, "𝐇"}, {"I"c, "𝐈"}, {"J"c, "𝐉"}, {"K"c, "𝐊"}, {"L"c, "𝐋"}, {"M"c, "𝐌"}, {"N"c, "𝐍"}, {"O"c, "𝐎"}, {"P"c, "𝐏"}, {"Q"c, "𝐐"}, {"R"c, "𝐑"}, {"S"c, "𝐒"}, {"T"c, "𝐓"}, {"U"c, "𝐔"}, {"V"c, "𝐕"}, {"W"c, "𝐖"}, {"X"c, "𝐗"}, {"Y"c, "𝐘"}, {"Z"c, "𝐙"}, {"a"c, "𝐚"}, {"b"c, "𝐛"}, {"c"c, "𝐜"}, {"d"c, "𝐝"}, {"e"c, "𝐞"}, {"f"c, "𝐟"}, {"g"c, "𝐠"}, {"h"c, "𝐡"}, {"i"c, "𝐢"}, {"j"c, "𝐣"}, {"k"c, "𝐤"}, {"l"c, "𝐥"}, {"m"c, "𝐦"}, {"n"c, "𝐧"}, {"o"c, "𝐨"}, {"p"c, "𝐩"}, {"q"c, "𝐪"}, {"r"c, "𝐫"}, {"s"c, "𝐬"}, {"t"c, "𝐭"}, {"u"c, "𝐮"}, {"v"c, "𝐯"}, {"w"c, "𝐰"}, {"x"c, "𝐱"}, {"y"c, "𝐲"}, {"z"c, "𝐳"}, {"0"c, "𝟎"}, {"1"c, "𝟏"}, {"2"c, "𝟐"}, {"3"c, "𝟑"}, {"4"c, "𝟒"}, {"5"c, "𝟓"}, {"6"c, "𝟔"}, {"7"c, "𝟕"}, {"8"c, "𝟖"}, {"9"c, "𝟗"} } End If Return UnicodeCharacterMaps._mathematicalBold End Get End Property ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Gets a dictionary where the keys are the alphabet letters from 'a' to 'Z', ''' and the values are their corresponding symbols from the 'Mathematical Italic' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D434 to U+1D467). ''' <para></para> ''' e.g., dictionary key: 'A' gets value: '𝐴', and dictionary key: 'a' gets value: '𝑎'. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Public Shared ReadOnly Property MathematicalItalic As Dictionary(Of Char, String) Get If UnicodeCharacterMaps._mathematicalItalic Is Nothing Then UnicodeCharacterMaps._mathematicalItalic = New Dictionary(Of Char, String)(EqualityComparer (Of Char ). Default) From { {"A"c, "𝐴"}, {"B"c, "𝐵"}, {"C"c, "𝐶"}, {"D"c, "𝐷"}, {"E"c, "𝐸"}, {"F"c, "𝐹"}, {"G"c, "𝐺"}, {"H"c, "𝐻"}, {"I"c, "𝐼"}, {"J"c, "𝐽"}, {"K"c, "𝐾"}, {"L"c, "𝐿"}, {"M"c, "𝑀"}, {"N"c, "𝑁"}, {"O"c, "𝑂"}, {"P"c, "𝑃"}, {"Q"c, "𝑄"}, {"R"c, "𝑅"}, {"S"c, "𝑆"}, {"T"c, "𝑇"}, {"U"c, "𝑈"}, {"V"c, "𝑉"}, {"W"c, "𝑊"}, {"X"c, "𝑋"}, {"Y"c, "𝑌"}, {"Z"c, "𝑍"}, {"a"c, "𝑎"}, {"b"c, "𝑏"}, {"c"c, "𝑐"}, {"d"c, "𝑑"}, {"e"c, "𝑒"}, {"f"c, "𝑓"}, {"g"c, "𝑔"}, {"h"c, "𝘩"}, {"i"c, "𝑖"}, {"j"c, "𝑗"}, {"k"c, "𝑘"}, {"l"c, "𝑙"}, {"m"c, "𝑚"}, {"n"c, "𝑛"}, {"o"c, "𝑜"}, {"p"c, "𝑝"}, {"q"c, "𝑞"}, {"r"c, "𝑟"}, {"s"c, "𝑠"}, {"t"c, "𝑡"}, {"u"c, "𝑢"}, {"v"c, "𝑣"}, {"w"c, "𝑤"}, {"x"c, "𝑥"}, {"y"c, "𝑦"}, {"z"c, "𝑧"} } End If Return UnicodeCharacterMaps._mathematicalItalic End Get End Property ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Gets a dictionary where the keys are the alphabet letters from 'a' to 'Z', ''' and the values are their corresponding symbols from the 'Mathematical Bold Italic' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D468 to U+1D49B). ''' <para></para> ''' e.g., dictionary key: 'A' gets value: '𝑨', and dictionary key: 'a' gets value: '𝒂'. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Public Shared ReadOnly Property MathematicalBoldItalic As Dictionary(Of Char, String) Get If UnicodeCharacterMaps._mathematicalBoldItalic Is Nothing Then UnicodeCharacterMaps._mathematicalBoldItalic = New Dictionary(Of Char, String)(EqualityComparer (Of Char ). Default) From { {"A"c, "𝑨"}, {"B"c, "𝑩"}, {"C"c, "𝑪"}, {"D"c, "𝑫"}, {"E"c, "𝑬"}, {"F"c, "𝑭"}, {"G"c, "𝑮"}, {"H"c, "𝑯"}, {"I"c, "𝑰"}, {"J"c, "𝑱"}, {"K"c, "𝑲"}, {"L"c, "𝑳"}, {"M"c, "𝑴"}, {"N"c, "𝑵"}, {"O"c, "𝑶"}, {"P"c, "𝑷"}, {"Q"c, "𝑸"}, {"R"c, "𝑹"}, {"S"c, "𝑺"}, {"T"c, "𝑻"}, {"U"c, "𝑼"}, {"V"c, "𝑽"}, {"W"c, "𝑾"}, {"X"c, "𝑿"}, {"Y"c, "𝒀"}, {"Z"c, "𝒁"}, {"a"c, "𝒂"}, {"b"c, "𝒃"}, {"c"c, "𝒄"}, {"d"c, "𝒅"}, {"e"c, "𝒆"}, {"f"c, "𝒇"}, {"g"c, "𝒈"}, {"h"c, "𝒉"}, {"i"c, "𝒊"}, {"j"c, "𝒋"}, {"k"c, "𝒌"}, {"l"c, "𝒍"}, {"m"c, "𝒎"}, {"n"c, "𝒏"}, {"o"c, "𝒐"}, {"p"c, "𝒑"}, {"q"c, "𝒒"}, {"r"c, "𝒓"}, {"s"c, "𝒔"}, {"t"c, "𝒕"}, {"u"c, "𝒖"}, {"v"c, "𝒗"}, {"w"c, "𝒘"}, {"x"c, "𝒙"}, {"y"c, "𝒚"}, {"z"c, "𝒛"} } End If Return UnicodeCharacterMaps._mathematicalBoldItalic End Get End Property ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Gets a dictionary where the keys are the alphabet letters from 'a' to 'Z', ''' and the values are their corresponding symbols from the 'Mathematical Bold Script' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D4D0 to U+1D503). ''' <para></para> ''' e.g., dictionary key: 'A' gets value: '𝓐', and dictionary key: 'a' gets value: '𝓪'. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Public Shared ReadOnly Property MathematicalBoldScript As Dictionary(Of Char, String) Get If UnicodeCharacterMaps._mathematicalBoldScript Is Nothing Then UnicodeCharacterMaps._mathematicalBoldScript = New Dictionary(Of Char, String)(EqualityComparer (Of Char ). Default) From { {"A"c, "𝓐"}, {"B"c, "𝓑"}, {"C"c, "𝓒"}, {"D"c, "𝓓"}, {"E"c, "𝓔"}, {"F"c, "𝓕"}, {"G"c, "𝓖"}, {"H"c, "𝓗"}, {"I"c, "𝓘"}, {"J"c, "𝓙"}, {"K"c, "𝓚"}, {"L"c, "𝓛"}, {"M"c, "𝓜"}, {"N"c, "𝓝"}, {"O"c, "𝓞"}, {"P"c, "𝓟"}, {"Q"c, "𝓠"}, {"R"c, "𝓡"}, {"S"c, "𝓢"}, {"T"c, "𝓣"}, {"U"c, "𝓤"}, {"V"c, "𝓥"}, {"W"c, "𝓦"}, {"X"c, "𝓧"}, {"Y"c, "𝓨"}, {"Z"c, "𝓩"}, {"a"c, "𝓪"}, {"b"c, "𝓫"}, {"c"c, "𝓬"}, {"d"c, "𝓭"}, {"e"c, "𝓮"}, {"f"c, "𝓯"}, {"g"c, "𝓰"}, {"h"c, "𝓱"}, {"i"c, "𝓲"}, {"j"c, "𝓳"}, {"k"c, "𝓴"}, {"l"c, "𝓵"}, {"m"c, "𝓶"}, {"n"c, "𝓷"}, {"o"c, "𝓸"}, {"p"c, "𝓹"}, {"q"c, "𝓺"}, {"r"c, "𝓻"}, {"s"c, "𝓼"}, {"t"c, "𝓽"}, {"u"c, "𝓾"}, {"v"c, "𝓿"}, {"w"c, "𝔀"}, {"x"c, "𝔁"}, {"y"c, "𝔂"}, {"z"c, "𝔃"} } End If Return UnicodeCharacterMaps._mathematicalBoldScript End Get End Property ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Gets a dictionary where the keys are the alphabet letters from 'a' to 'Z' and numbers from '0' to '9', ''' and the values are their corresponding symbols from the 'Sans-Serif' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D5A0 to U+1D5D3). ''' <para></para> ''' e.g., dictionary key: 'A' gets value: '𝖠', and dictionary key: 'a' gets value: '𝖺'. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Public Shared ReadOnly Property SansSerif As Dictionary(Of Char, String) Get If UnicodeCharacterMaps._sansSerif Is Nothing Then UnicodeCharacterMaps._sansSerif = New Dictionary(Of Char, String)(EqualityComparer (Of Char ). Default) From { {"A"c, "𝖠"}, {"B"c, "𝖡"}, {"C"c, "𝖢"}, {"D"c, "𝖣"}, {"E"c, "𝖤"}, {"F"c, "𝖥"}, {"G"c, "𝖦"}, {"H"c, "𝖧"}, {"I"c, "𝖨"}, {"J"c, "𝖩"}, {"K"c, "𝖪"}, {"L"c, "𝖫"}, {"M"c, "𝖬"}, {"N"c, "𝖭"}, {"O"c, "𝖮"}, {"P"c, "𝖯"}, {"Q"c, "𝖰"}, {"R"c, "𝖱"}, {"S"c, "𝖲"}, {"T"c, "𝖳"}, {"U"c, "𝖴"}, {"V"c, "𝖵"}, {"W"c, "𝖶"}, {"X"c, "𝖷"}, {"Y"c, "𝖸"}, {"Z"c, "𝖹"}, {"a"c, "𝖺"}, {"b"c, "𝖻"}, {"c"c, "𝖼"}, {"d"c, "𝖽"}, {"e"c, "𝖾"}, {"f"c, "𝖿"}, {"g"c, "𝗀"}, {"h"c, "𝗁"}, {"i"c, "𝗂"}, {"j"c, "𝗃"}, {"k"c, "𝗄"}, {"l"c, "𝗅"}, {"m"c, "𝗆"}, {"n"c, "𝗇"}, {"o"c, "𝗈"}, {"p"c, "𝗉"}, {"q"c, "𝗊"}, {"r"c, "𝗋"}, {"s"c, "𝗌"}, {"t"c, "𝗍"}, {"u"c, "𝗎"}, {"v"c, "𝗏"}, {"w"c, "𝗐"}, {"x"c, "𝗑"}, {"y"c, "𝗒"}, {"z"c, "𝗓"}, {"0"c, "𝟢"}, {"1"c, "𝟣"}, {"2"c, "𝟤"}, {"3"c, "𝟥"}, {"4"c, "𝟦"}, {"5"c, "𝟧"}, {"6"c, "𝟨"}, {"7"c, "𝟩"}, {"8"c, "𝟪"}, {"9"c, "𝟫"} } End If Return UnicodeCharacterMaps._sansSerif End Get End Property ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Gets a dictionary where the keys are the alphabet letters from 'a' to 'Z' and numbers from '0' to '9', ''' and the values are their corresponding symbols from the 'Sans-Serif Bold' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D5D4 to U+1D607). ''' <para></para> ''' e.g., dictionary key: 'A' gets value: '𝗔', and dictionary key: 'a' gets value: '𝗮'. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Public Shared ReadOnly Property SansSerifBold As Dictionary(Of Char, String) Get If UnicodeCharacterMaps._sansSerifBold Is Nothing Then UnicodeCharacterMaps._sansSerifBold = New Dictionary(Of Char, String)(EqualityComparer (Of Char ). Default) From { {"A"c, "𝗔"}, {"B"c, "𝗕"}, {"C"c, "𝗖"}, {"D"c, "𝗗"}, {"E"c, "𝗘"}, {"F"c, "𝗙"}, {"G"c, "𝗚"}, {"H"c, "𝗛"}, {"I"c, "𝗜"}, {"J"c, "𝗝"}, {"K"c, "𝗞"}, {"L"c, "𝗟"}, {"M"c, "𝗠"}, {"N"c, "𝗡"}, {"O"c, "𝗢"}, {"P"c, "𝗣"}, {"Q"c, "𝗤"}, {"R"c, "𝗥"}, {"S"c, "𝗦"}, {"T"c, "𝗧"}, {"U"c, "𝗨"}, {"V"c, "𝗩"}, {"W"c, "𝗪"}, {"X"c, "𝗫"}, {"Y"c, "𝗬"}, {"Z"c, "𝗭"}, {"a"c, "𝗮"}, {"b"c, "𝗯"}, {"c"c, "𝗰"}, {"d"c, "𝗱"}, {"e"c, "𝗲"}, {"f"c, "𝗳"}, {"g"c, "𝗴"}, {"h"c, "𝗵"}, {"i"c, "𝗶"}, {"j"c, "𝗷"}, {"k"c, "𝗸"}, {"l"c, "𝗹"}, {"m"c, "𝗺"}, {"n"c, "𝗻"}, {"o"c, "𝗼"}, {"p"c, "𝗽"}, {"q"c, "𝗾"}, {"r"c, "𝗿"}, {"s"c, "𝘀"}, {"t"c, "𝘁"}, {"u"c, "𝘂"}, {"v"c, "𝘃"}, {"w"c, "𝘄"}, {"x"c, "𝘅"}, {"y"c, "𝘆"}, {"z"c, "𝘇"}, {"0"c, "𝟬"}, {"1"c, "𝟭"}, {"2"c, "𝟮"}, {"3"c, "𝟯"}, {"4"c, "𝟰"}, {"5"c, "𝟱"}, {"6"c, "𝟲"}, {"7"c, "𝟳"}, {"8"c, "𝟴"}, {"9"c, "𝟵"} } End If Return UnicodeCharacterMaps._sansSerifBold End Get End Property ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Gets a dictionary where the keys are the alphabet letters from 'a' to 'Z', ''' and the values are their corresponding symbols from the 'Sans-Serif Italic' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D608 to U+1D63B). ''' <para></para> ''' e.g., dictionary key: 'A' gets value: '𝘈', and dictionary key: 'a' gets value: '𝘢'. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Public Shared ReadOnly Property SansSerifItalic As Dictionary(Of Char, String) Get If UnicodeCharacterMaps._sansSerifItalic Is Nothing Then UnicodeCharacterMaps._sansSerifItalic = New Dictionary(Of Char, String)(EqualityComparer (Of Char ). Default) From { {"A"c, "𝘈"}, {"B"c, "𝘉"}, {"C"c, "𝘊"}, {"D"c, "𝘋"}, {"E"c, "𝘌"}, {"F"c, "𝘍"}, {"G"c, "𝘎"}, {"H"c, "𝘏"}, {"I"c, "𝘐"}, {"J"c, "𝘑"}, {"K"c, "𝘒"}, {"L"c, "𝘓"}, {"M"c, "𝘔"}, {"N"c, "𝘕"}, {"O"c, "𝘖"}, {"P"c, "𝘗"}, {"Q"c, "𝘘"}, {"R"c, "𝘙"}, {"S"c, "𝘚"}, {"T"c, "𝘛"}, {"U"c, "𝘜"}, {"V"c, "𝘝"}, {"W"c, "𝘞"}, {"X"c, "𝘟"}, {"Y"c, "𝘠"}, {"Z"c, "𝘡"}, {"a"c, "𝘢"}, {"b"c, "𝘣"}, {"c"c, "𝘤"}, {"d"c, "𝘥"}, {"e"c, "𝘦"}, {"f"c, "𝘧"}, {"g"c, "𝘨"}, {"h"c, "𝘩"}, {"i"c, "𝘪"}, {"j"c, "𝘫"}, {"k"c, "𝘬"}, {"l"c, "𝘭"}, {"m"c, "𝘮"}, {"n"c, "𝘯"}, {"o"c, "𝘰"}, {"p"c, "𝘱"}, {"q"c, "𝘲"}, {"r"c, "𝘳"}, {"s"c, "𝘴"}, {"t"c, "𝘵"}, {"u"c, "𝘶"}, {"v"c, "𝘷"}, {"w"c, "𝘸"}, {"x"c, "𝘹"}, {"y"c, "𝘺"}, {"z"c, "𝘻"} } End If Return UnicodeCharacterMaps._sansSerifItalic End Get End Property ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Gets a dictionary where the keys are the alphabet letters from 'a' to 'Z', ''' and the values are their corresponding symbols from the 'Sans-Serif Bold Italic' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D63C to U+1D66F). ''' <para></para> ''' e.g., dictionary key: 'A' gets value: '𝘼', and dictionary key: 'a' gets value: '𝙖'. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Public Shared ReadOnly Property SansSerifBoldItalic As Dictionary(Of Char, String) Get If UnicodeCharacterMaps._sansSerifBoldItalic Is Nothing Then UnicodeCharacterMaps._sansSerifBoldItalic = New Dictionary(Of Char, String)(EqualityComparer (Of Char ). Default) From { {"A"c, "𝘼"}, {"B"c, "𝘽"}, {"C"c, "𝘾"}, {"D"c, "𝘿"}, {"E"c, "𝙀"}, {"F"c, "𝙁"}, {"G"c, "𝙂"}, {"H"c, "𝙃"}, {"I"c, "𝙄"}, {"J"c, "𝙅"}, {"K"c, "𝙆"}, {"L"c, "𝙇"}, {"M"c, "𝙈"}, {"N"c, "𝙉"}, {"O"c, "𝙊"}, {"P"c, "𝙋"}, {"Q"c, "𝙌"}, {"R"c, "𝙍"}, {"S"c, "𝙎"}, {"T"c, "𝙏"}, {"U"c, "𝙐"}, {"V"c, "𝙑"}, {"W"c, "𝙒"}, {"X"c, "𝙓"}, {"Y"c, "𝙔"}, {"Z"c, "𝙕"}, {"a"c, "𝙖"}, {"b"c, "𝙗"}, {"c"c, "𝙘"}, {"d"c, "𝙙"}, {"e"c, "𝙚"}, {"f"c, "𝙛"}, {"g"c, "𝙜"}, {"h"c, "𝙝"}, {"i"c, "𝙞"}, {"j"c, "𝙟"}, {"k"c, "𝙠"}, {"l"c, "𝙡"}, {"m"c, "𝙢"}, {"n"c, "𝙣"}, {"o"c, "𝙤"}, {"p"c, "𝙥"}, {"q"c, "𝙦"}, {"r"c, "𝙧"}, {"s"c, "𝙨"}, {"t"c, "𝙩"}, {"u"c, "𝙪"}, {"v"c, "𝙫"}, {"w"c, "𝙬"}, {"x"c, "𝙭"}, {"y"c, "𝙮"}, {"z"c, "𝙯"} } End If Return UnicodeCharacterMaps._sansSerifBoldItalic End Get End Property ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Gets a dictionary where the keys are the alphabet letters from 'a' to 'Z' and numbers from '0' to '9', ''' and the values are their corresponding symbols from the 'Monospace' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D670 to U+1D6A3). ''' <para></para> ''' e.g., dictionary key: 'A' gets value: '𝙰', and dictionary key: 'a' gets value: '𝚊'. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Public Shared ReadOnly Property MonoSpace As Dictionary(Of Char, String) Get If UnicodeCharacterMaps._monoSpace Is Nothing Then UnicodeCharacterMaps._monoSpace = New Dictionary(Of Char, String)(EqualityComparer (Of Char ). Default) From { {"A"c, "𝙰"}, {"B"c, "𝙱"}, {"C"c, "𝙲"}, {"D"c, "𝙳"}, {"E"c, "𝙴"}, {"F"c, "𝙵"}, {"G"c, "𝙶"}, {"H"c, "𝙷"}, {"I"c, "𝙸"}, {"J"c, "𝙹"}, {"K"c, "𝙺"}, {"L"c, "𝙻"}, {"M"c, "𝙼"}, {"N"c, "𝙽"}, {"O"c, "𝙾"}, {"P"c, "𝙿"}, {"Q"c, "𝚀"}, {"R"c, "𝚁"}, {"S"c, "𝚂"}, {"T"c, "𝚃"}, {"U"c, "𝚄"}, {"V"c, "𝚅"}, {"W"c, "𝚆"}, {"X"c, "𝚇"}, {"Y"c, "𝚈"}, {"Z"c, "𝚉"}, {"a"c, "𝚊"}, {"b"c, "𝚋"}, {"c"c, "𝚌"}, {"d"c, "𝚍"}, {"e"c, "𝚎"}, {"f"c, "𝚏"}, {"g"c, "𝚐"}, {"h"c, "𝚑"}, {"i"c, "𝚒"}, {"j"c, "𝚓"}, {"k"c, "𝚔"}, {"l"c, "𝚕"}, {"m"c, "𝚖"}, {"n"c, "𝚗"}, {"o"c, "𝚘"}, {"p"c, "𝚙"}, {"q"c, "𝚚"}, {"r"c, "𝚛"}, {"s"c, "𝚜"}, {"t"c, "𝚝"}, {"u"c, "𝚞"}, {"v"c, "𝚟"}, {"w"c, "𝚠"}, {"x"c, "𝚡"}, {"y"c, "𝚢"}, {"z"c, "𝚣"}, {"0"c, "𝟶"}, {"1"c, "𝟷"}, {"2"c, "𝟸"}, {"3"c, "𝟹"}, {"4"c, "𝟺"}, {"5"c, "𝟻"}, {"6"c, "𝟼"}, {"7"c, "𝟽"}, {"8"c, "𝟾"}, {"9"c, "𝟿"} } End If Return UnicodeCharacterMaps._monoSpace End Get End Property #End Region #Region " Constructors " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Prevents a default instance of the <see cref="UnicodeCharacterMaps"/> class from being created. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- <DebuggerNonUserCode> Private Sub New() End Sub #End Region End Class End Namespace #End Region
EL CÓDIGO CONTINÚA EN EL SIGUIENTE POST 👇👇👇
|
|
|
16
|
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
|
en: 10 Septiembre 2023, 08:57 am
|
Un código para calcular la entropía de un String, basado en la fórmula de Shannon: https://en.wikipedia.org/wiki/Entropy_(information_theory)' *********************************************************************** ' Author : ElektroStudios ' Modified : 11-July-2023 ' *********************************************************************** #Region " Public Members Summary " #Region " Functions " ' CalculateStringEntropy(String) As Double #End Region #End Region #Region " Option Statements " Option Strict On Option Explicit On Option Infer Off #End Region #Region " Imports " #End Region #Region " String Util " ' ReSharper disable once CheckNamespace Namespace DevCase.Core.DataProcessing.Common Partial Public NotInheritable Class UtilString #Region " Public Methods " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Calculates the entropy of a string based on the Shannon's entropy formula. ''' <para></para> ''' The entropy is a measure of the amount of uncertainty or randomness in a set of characters. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <seealso href="https://en.wikipedia.org/wiki/Entropy_(information_theory)"/> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="str"> ''' The input string. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' A number representing the entropy value of the input string. ''' <para></para> ''' A higher entropy value indicates that the text contains more randomness or unpredictability, ''' while a lower entropy value indicates that the text is more structured or predictable. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' To calculate the entropy of the given text, the algorithm first counts the frequency of each character in the text. ''' It then uses these frequencies to calculate the probability of each character appearing in the text. ''' Once the probability of each character is known, the algorithm applies Shannon's entropy formula, ''' which looks like this: H = -Σp(x)log2p(x), where H is the entropy, p(x) is the probability that ''' character x will appear in the text, and log2 is the base 2 logarithm. ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Shared Function CalculateStringEntropy(str As String) As Double For Each c As Char In str If Not map.ContainsKey(c) Then map.Add(c, 1) Else map(c) += 1 End If Next c Dim result As Double = 0.0 Dim len As Integer = str.Length For Each item As KeyValuePair(Of Char, Integer) In map Dim frequency As Double = item.Value / len result -= frequency * (System.Math.Log(frequency) / System.Math.Log(2)) Next item Return result End Function #End Region End Class End Namespace #End Region
|
|
|
17
|
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
|
en: 10 Septiembre 2023, 08:50 am
|
Aquí un código para generar las páginas de impresión (para la impresora) del contenido de un control DataGridView. Ejemplo de uso: Dim headerBackColor As Color = Color.Gray Dim headerForeColor As Color = Color.White Dim rowBackColor As Color = Color.LightGray Dim rowForeColor As Color = Color.LightGray Dim rowBackColorAlternate As Color = Color.WhiteSmoke Dim rowForeColorAlternate As Color = Color.WhiteSmoke Dim printDocument As PrintDocument = Me.DataGridView1.GetPrintDocument("Title", textFont:=New Font("Arial", 16), headerBackColor:=headerBackColor, headerForeColor:=headerForeColor, rowBackColor:=rowBackColor, rowForeColor:=rowForeColor, rowBackColorAlternate:=rowBackColorAlternate, rowForeColorAlternate:=rowForeColorAlternate) Dim printPreviewDialog As PrintPreviewDialog = PrintPreviewDialog1 printPreviewDialog.ShowDialog()
' *********************************************************************** ' Author : ElektroStudios ' Modified : 13-July-2023 ' *********************************************************************** #Region " Public Members Summary " ' DataGridView.GetPrintDocument(Opt: String, Opt: Font, Opt: Color, Opt: Color, Opt: Color, Opt: Color, Opt: Color, Opt: Color) As PrintDocument #End Region #Region " Option Statements " Option Strict On Option Explicit On Option Infer Off #End Region #Region " Imports " Imports System.Drawing.Printing Imports System.Runtime.CompilerServices #End Region #Region " DataGridView Extensions " ' ReSharper disable once CheckNamespace Namespace DevCase.Extensions.DataGridViewExtensions ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Contains custom extension methods to use with <see cref="DataGridView"/> control. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- <HideModuleName> Public Module DataGridViewExtensions #Region " Public Extension Methods " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Generates a <see cref="PrintDocument"/> object for printing the contents of the source <see cref="DataGridView"/>. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code language="VB.NET"> ''' Dim headerBackColor As Color = Color.Gray ''' Dim headerForeColor As Color = Color.White ''' Dim rowBackColor As Color = Color.LightGray ''' Dim rowForeColor As Color = Color.LightGray ''' Dim rowBackColorAlternate As Color = Color.WhiteSmoke ''' Dim rowForeColorAlternate As Color = Color.WhiteSmoke ''' ''' Dim printDocument As PrintDocument = ''' Me.DataGridView1.GetPrintDocument("Title", textFont:=New Font("Arial", 16), ''' headerBackColor:=headerBackColor, headerForeColor:=headerForeColor, ''' rowBackColor:=rowBackColor, rowForeColor:=rowForeColor, ''' rowBackColorAlternate:=rowBackColorAlternate, rowForeColorAlternate:=rowForeColorAlternate) ''' ''' Dim printPreviewDialog As PrintPreviewDialog = PrintPreviewDialog1 ''' printPreviewDialog.ShowDialog() ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="dataGridView"> ''' The <see cref="DataGridView"/> to print. ''' </param> ''' ''' <param name="title"> ''' The title to be printed at the top of the document. ''' <para></para> ''' If not provided, the <see cref="DataGridView.Name"/> property value will be used as the title. ''' </param> ''' ''' <param name="textFont"> ''' Optional. The font to draw header and row texts. ''' <para></para> ''' If not provided, the <see cref="DataGridView.Font"/> property value will be used as the text font. ''' </param> ''' ''' <param name="headerBackColor"> ''' Optional. The background color of the header row. ''' <para></para> ''' If not provided, the default color is <see cref="Color.White"/>. ''' </param> ''' ''' <param name="headerForeColor"> ''' Optional. The text color of the header row. ''' <para></para> ''' If not provided, the default color is <see cref="Color.Black"/>. ''' </param> ''' ''' <param name="rowBackColor"> ''' Optional. The background color of the data rows. ''' <para></para> ''' If not provided, the default color is <see cref="Color.White"/>. ''' </param> ''' ''' <param name="rowForeColor"> ''' Optional. The text color of the data rows. ''' <para></para> ''' If not provided, the default color is <see cref="Color.Black"/>. ''' </param> ''' ''' <param name="rowBackColorAlternate"> ''' Optional. The background color of the alternate data rows. ''' <para></para> ''' If not provided, the default color is <see cref="Color.White"/>. ''' </param> ''' ''' <param name="rowForeColorAlternate"> ''' Optional. text color of the alternate data rows. ''' <para></para> ''' If not provided, the default color is <see cref="Color.Black"/>. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' A <see cref="PrintDocument"/> object for printing the contents of the source <see cref="DataGridView"/>. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <Extension> <DebuggerStepThrough> Public Function GetPrintDocument(dataGridView As DataGridView, Optional title As String = Nothing, Optional textFont As Font = Nothing, Optional headerBackColor As Color = Nothing, Optional headerForeColor As Color = Nothing, Optional rowBackColor As Color = Nothing, Optional rowForeColor As Color = Nothing, Optional rowBackColorAlternate As Color = Nothing, Optional rowForeColorAlternate As Color = Nothing) As PrintDocument If String.IsNullOrEmpty(title) Then title = dataGridView.Name End If If textFont Is Nothing Then textFont = dataGridView.Font End If If headerBackColor = Nothing Then headerBackColor = Color.White End If If headerForeColor = Nothing Then headerForeColor = Color.Black End If If rowBackColor = Nothing Then rowBackColor = Color.White End If If rowForeColor = Nothing Then rowForeColor = Color.Black End If If rowBackColorAlternate = Nothing Then rowBackColorAlternate = Color.White End If If rowForeColorAlternate = Nothing Then rowForeColorAlternate = Color.Black End If Dim currentPageIndex As Integer = 0 Dim printedRowsCount As Integer = 0 Dim printDocument As New PrintDocument() AddHandler printDocument.PrintPage, Sub(sender, e) Dim printAreaHeight As Integer = e.MarginBounds.Height Dim printAreaWidth As Integer = e.MarginBounds.Width Dim printAreaLeft As Integer = e.MarginBounds.Left Dim printAreaTop As Integer = e.MarginBounds.Top Dim headerHeight As Integer = dataGridView.ColumnHeadersHeight Dim rowHeight As Integer = dataGridView.Rows(0).Height Dim gridWidth As Integer = dataGridView.Columns.GetColumnsWidth(DataGridViewElementStates.Visible) Dim gridLeft As Integer = printAreaLeft + (printAreaWidth - gridWidth) \ 2 Dim titleSize As SizeF = e.Graphics.MeasureString(title, textFont) Dim titleLeft As Integer = gridLeft Dim titleTop As Integer = printAreaTop - CInt(titleSize.Height) - 20 e.Graphics.DrawString(title, textFont, Brushes.Black, titleLeft, titleTop, New StringFormat() With {.Alignment = StringAlignment.Near}) Dim rowsPerPage As Integer = CInt(Math.Floor((printAreaHeight - headerHeight) / rowHeight)) Dim rowIndex As Integer = printedRowsCount Dim headerWidth As Integer = 0 For Each column As DataGridViewColumn In dataGridView.Columns headerWidth += column.Width Next Dim headerBounds As New Rectangle(gridLeft, printAreaTop + headerHeight, headerWidth, rowHeight) Using headerBackBrush As New SolidBrush(headerBackColor) e.Graphics.FillRectangle(headerBackBrush, headerBounds) For Each column As DataGridViewColumn In dataGridView.Columns Dim cellBounds As New Rectangle(headerBounds.Left, headerBounds.Top, column.Width, headerBounds.Height) Using headerTextBrush As New SolidBrush(headerForeColor) e.Graphics.DrawString(column.HeaderText, textFont, headerTextBrush, cellBounds, New StringFormat() With {.Alignment = StringAlignment.Center}) End Using headerBounds.X += column.Width Next End Using While rowIndex < dataGridView.Rows.Count AndAlso rowIndex < printedRowsCount + rowsPerPage Dim row As DataGridViewRow = dataGridView.Rows(rowIndex) Dim cellIndex As Integer = 0 Dim currentRowBackColor As Color Dim currentRowForeColor As Color If rowIndex Mod 2 = 0 Then currentRowBackColor = rowBackColor currentRowForeColor = rowForeColor Else currentRowBackColor = rowBackColorAlternate currentRowForeColor = rowForeColorAlternate End If While cellIndex < dataGridView.Columns.Count Dim cellBounds As New Rectangle(printAreaLeft + (gridLeft - dataGridView.Columns(cellIndex).Width), (printAreaTop + headerHeight + (rowIndex - printedRowsCount) * rowHeight) + headerBounds.Height * 2, dataGridView.Columns(cellIndex).Width, rowHeight) Using rowBackBrush As New SolidBrush(currentRowBackColor) e.Graphics.FillRectangle(rowBackBrush, cellBounds) End Using e.Graphics.DrawRectangle(Pens.LightGray, cellBounds) Using rowTextBrush As New SolidBrush(currentRowForeColor) e.Graphics.DrawString(row.Cells(cellIndex).FormattedValue.ToString(), textFont, rowTextBrush, cellBounds, New StringFormat()) End Using printAreaLeft += dataGridView.Columns(cellIndex).Width cellIndex += 1 End While printAreaLeft = e.MarginBounds.Left rowIndex += 1 End While If rowIndex < dataGridView.Rows.Count Then printedRowsCount = rowIndex e.HasMorePages = True Else printedRowsCount = 0 currentPageIndex = 0 e.HasMorePages = False End If End Sub Return printDocument End Function #End Region End Module End Namespace #End Region
|
|
|
18
|
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
|
en: 10 Septiembre 2023, 08:44 am
|
Aquí les dejo una clase utiliratia para manipular el indexador de carpetas de Windows. Permite añadir y eliminar directorios, enumerar los directorios actuales, y buscar un directorio. Se necesita esta librería: https://www.nuget.org/packages/tlbimp-Microsoft.Search.InteropEjemplos de uso: Incluir un directorio: Dim directoryPath As String = "C:\Games\" SearchIndexerUtil.AddDirectoryRule(directoryPath, include:=True)
Eliminar el directorio: SearchIndexerUtil.RemoveDirectoryRule(directoryPath)
Comprobar si el directorio está incluído: Dim isIncluded As Boolean = SearchIndexerUtil.IsDirectoryIncluded(directoryPath) Debug. WriteLine($ "{NameOf(isIncluded)}: {isIncluded}")
Obtener los directorios incluídos: Dim rules As ReadOnlyCollection(Of CSearchScopeRule) = SearchIndexerUtil.GetDirectoryRules() For Each rule As CSearchScopeRuleClass In rules.Where(Function(x) x.IsDefault = 0) Debug. WriteLine($ "{NameOf(rule.PatternOrURL)}: {rule.PatternOrURL}") Debug. WriteLine($ "{NameOf(rule.IsIncluded)}: {rule.IsIncluded = 1}") Next
' *********************************************************************** ' Author : ElektroStudios ' Modified : 10-October-2022 ' *********************************************************************** #Region " Public Members Summary " #Region " Methods " ' AddDirectoryRule(String, Boolean) ' AddDirectoryRule(DirectoryInfo, Boolean) ' RemoveDirectoryRule(String) ' RemoveDirectoryRule(DirectoryInfo) ' GetDirectoryRules() As ReadOnlyCollection(Of CSearchScopeRule) ' FindDirectoryRule(String) As CSearchScopeRule ' FindDirectoryRule(DirectoryInfo) As CSearchScopeRule ' IsDirectoryIncluded(String) As Boolean ' IsDirectoryIncluded(DirectoryInfo) As Boolean #End Region #End Region #Region " Option Statements " Option Strict On Option Explicit On Option Infer Off #End Region #Region " Imports " Imports System.Collections.ObjectModel Imports System.IO Imports Microsoft.Search.Interop #End Region #Region " SearchIndexer Util " ' ReSharper disable once CheckNamespace Namespace DevCase.ThirdParty.MicrosoftSearchIndexer ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Contains Microsoft Search Indexer related utilities. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' Note: Some functionalities of this assembly may require to install one or all of the listed NuGet packages: ''' <para></para> ''' <see href="https://www.nuget.org/packages/tlbimp-Microsoft.Search.Interop">tlbimp-Microsoft.Search.Interop by mamift</see> ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- Public NotInheritable Class UtilSearchIndexer #Region " Private Fields " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Provides methods for controlling the Search service. ''' <para></para> ''' This interface manages settings and objects that affect the search engine across catalogs. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' Note: Some functionalities of this assembly may require to install one or all of the listed NuGet packages: ''' <para></para> ''' <see href="https://www.nuget.org/packages/tlbimp-Microsoft.Search.Interop">tlbimp-Microsoft.Search.Interop by mamift</see> ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- Private Shared searchManager As CSearchManager ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Provides methods to manage a search catalog for purposes such as re-indexing or setting timeouts. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' Note: Some functionalities of this assembly may require to install one or all of the listed NuGet packages: ''' <para></para> ''' <see href="https://www.nuget.org/packages/tlbimp-Microsoft.Search.Interop">tlbimp-Microsoft.Search.Interop by mamift</see> ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- Private Shared catalogManager As CSearchCatalogManager ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Provides methods that notify the search engine of containers to crawl and/or watch, ''' and items under those containers to include or exclude when crawling or watching. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' Note: Some functionalities of this assembly may require to install one or all of the listed NuGet packages: ''' <para></para> ''' <see href="https://www.nuget.org/packages/tlbimp-Microsoft.Search.Interop">tlbimp-Microsoft.Search.Interop by mamift</see> ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- Private Shared scopeManager As CSearchCrawlScopeManager #End Region #Region " Constructors " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Prevents a default instance of the <see cref="UtilSearchIndexer"/> class from being created. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' Note: Some functionalities of this assembly may require to install one or all of the listed NuGet packages: ''' <para></para> ''' <see href="https://www.nuget.org/packages/tlbimp-Microsoft.Search.Interop">tlbimp-Microsoft.Search.Interop by mamift</see> ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- <DebuggerNonUserCode> Private Sub New() End Sub #End Region #Region " Public Methods " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Adds the specified directory path to Windows Search Index. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' Documentation: <see href="https://learn.microsoft.com/en-us/windows/win32/api/searchapi/nf-searchapi-isearchcrawlscopemanager-adduserscoperule"/> ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code language="VB.NET"> ''' Dim directoryPath As String = "C:\Games\" ''' SearchIndexerUtil.AddDirectoryRule(directoryPath, include:=True) ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="directoryPathOrPattern"> ''' The directory path (or a directory path pattern with wildcards) to be indexed. ''' </param> ''' ''' <param name="include"> ''' <see langword="True"/> if this directory should be included in all searches; ''' otherwise, <see langword="False"/>. ''' </param> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Shared Sub AddDirectoryRule(directoryPathOrPattern As String, include As Boolean) UtilSearchIndexer.InitializeManagers() Dim uriPath As String = $"file:///{directoryPathOrPattern}" UtilSearchIndexer.scopeManager.AddUserScopeRule(uriPath, fInclude:=If(include, 1, 0), fOverrideChildren:=0, fFollowFlags:=Nothing) UtilSearchIndexer.scopeManager.SaveAll() End Sub ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Adds the specified directory path to Windows Search Index. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' Documentation: <see href="https://learn.microsoft.com/en-us/windows/win32/api/searchapi/nf-searchapi-isearchcrawlscopemanager-adduserscoperule"/> ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code language="VB.NET"> ''' Dim directory As New DirectoryInfo("C:\Games\") ''' SearchIndexerUtil.AddDirectoryRule(directory, include:=True) ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="directory"> ''' The directory path to be indexed. ''' </param> ''' ''' <param name="include"> ''' <see langword="True"/> if this directory should be included in all searches; ''' otherwise, <see langword="False"/>. ''' </param> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Shared Sub AddDirectoryRule(directory As DirectoryInfo, include As Boolean) UtilSearchIndexer.AddDirectoryRule(directory.FullName, include) End Sub ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Removes the specified directory path from Windows Search Index. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' Documentation: <see href="https://learn.microsoft.com/en-us/windows/win32/api/searchapi/nf-searchapi-isearchcrawlscopemanager-removescoperule"/> ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code language="VB.NET"> ''' Dim directoryPath As String = "C:\Games\" ''' SearchIndexerUtil.RemoveDirectoryRule(directoryPath) ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="directoryPath"> ''' The directory path (or a directory path pattern with wildcards) to be deindexed. ''' </param> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Shared Sub RemoveDirectoryRule(directoryPath As String) UtilSearchIndexer.InitializeManagers() Dim uriPath As String = $"file:///{directoryPath}" UtilSearchIndexer.scopeManager.RemoveScopeRule(uriPath) UtilSearchIndexer.scopeManager.SaveAll() End Sub ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Removes the specified directory path from Windows Search Index. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' Documentation: <see href="https://learn.microsoft.com/en-us/windows/win32/api/searchapi/nf-searchapi-isearchcrawlscopemanager-removescoperule"/> ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code language="VB.NET"> ''' Dim directory As New DirectoryInfo("C:\Games\") ''' SearchIndexerUtil.RemoveDirectoryRule(directory) ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="directory"> ''' The directory path to be deindexed. ''' </param> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Shared Sub RemoveDirectoryRule(directory As DirectoryInfo) UtilSearchIndexer.RemoveDirectoryRule(directory.FullName) End Sub ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Returns all the directory rules in Windows Search Index. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' Documentation: <see href="https://learn.microsoft.com/en-us/windows/win32/api/searchapi/nn-searchapi-ienumsearchscoperules"/> ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code language="VB.NET"> ''' Dim rules As ReadOnlyCollection(Of CSearchScopeRule) = SearchIndexerUtil.GetDirectoryRules() ''' ''' For Each rule As CSearchScopeRuleClass In rules.Where(Function(x) x.IsDefault = 0) ''' Debug.WriteLine($"{NameOf(rule.PatternOrURL)}: {rule.PatternOrURL}") ''' Debug.WriteLine($"{NameOf(rule.IsIncluded)}: {rule.IsIncluded = 1}") ''' Debug.WriteLine("") ''' Next ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' The resulting directory rules. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Shared Function GetDirectoryRules() As ReadOnlyCollection(Of CSearchScopeRule) UtilSearchIndexer.InitializeManagers() Dim scopeEnumerator As CEnumSearchScopeRules = UtilSearchIndexer.scopeManager.EnumerateScopeRules() Dim fetched As UInteger Do Dim scopeRule As CSearchScopeRule = Nothing scopeEnumerator.Next(1, scopeRule, fetched) If fetched <> 0 Then Else Exit Do End If Loop End Function ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Finds a directory rule that matches the specified directory path in Windows Search Index. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' Documentation: <see href="https://learn.microsoft.com/en-us/windows/win32/api/searchapi/nf-searchapi-isearchcrawlscopemanager-removescoperule"/> ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code language="VB.NET"> ''' Dim directoryPath As String = "C:\Games\" ''' Dim rule As CSearchScopeRule = FindDirectoryRule(directoryPath) ''' ''' If rule IsNot Nothing Then ''' Debug.WriteLine($"{NameOf(rule.PatternOrURL)}: {rule.PatternOrURL}") ''' Debug.WriteLine($"{NameOf(rule.IsIncluded)}: {rule.IsIncluded = 1}") ''' End If ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="directoryPathOrPattern"> ''' The directory path (or a directory path pattern with wildcards) to find. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' The resulting directory rule, ''' or <see langword="Nothing"/> if does not exist a directory rule that matches the specified directory path. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Shared Function FindDirectoryRule(directoryPathOrPattern As String) As CSearchScopeRule Dim uriPath As String = $"file:///{directoryPathOrPattern}" Return UtilSearchIndexer.GetDirectoryRules().Where(Function(scope) scope.PatternOrURL = uriPath).SingleOrDefault() End Function ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Finds a directory rule that matches the specified directory path in Windows Search Index. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' Documentation: <see href="https://learn.microsoft.com/en-us/windows/win32/api/searchapi/nf-searchapi-isearchcrawlscopemanager-removescoperule"/> ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code language="VB.NET"> ''' Dim directory As New DirectoryInfo("C:\Games\") ''' Dim rule As CSearchScopeRule = FindDirectoryRule(directory) ''' ''' If rule IsNot Nothing Then ''' Debug.WriteLine($"{NameOf(rule.PatternOrURL)}: {rule.PatternOrURL}") ''' Debug.WriteLine($"{NameOf(rule.IsIncluded)}: {rule.IsIncluded = 1}") ''' End If ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="directory"> ''' The directory path to find. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' The resulting directory rule, ''' or <see langword="Nothing"/> if does not exist a directory rule that matches the specified directory path. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Shared Function FindDirectoryRule(directory As DirectoryInfo) As CSearchScopeRule Return UtilSearchIndexer.FindDirectoryRule(directory.FullName) End Function ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Returns a value indicating whether the specified directory path is included in Windows Search Index. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' Documentation: <see href="https://learn.microsoft.com/en-us/windows/win32/api/searchapi/nf-searchapi-isearchcrawlscopemanager-includedincrawlscope"/> ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code language="VB.NET"> ''' Dim directoryPath As String = "C:\Games\" ''' Dim isIncluded As Boolean = IsDirectoryIncluded(directoryPath) ''' ''' Debug.WriteLine($"{NameOf(isIncluded)}: {isIncluded}") ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="directoryPathOrPattern"> ''' The directory path (or a directory path pattern with wildcards) to find. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' <see langword="True"/> if the specified directory path is included in Windows Search Index; ''' otherwise, <see langword="False"/>. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Shared Function IsDirectoryIncluded(directoryPathOrPattern As String) As Boolean UtilSearchIndexer.InitializeManagers() Dim uriPath As String = $"file:///{directoryPathOrPattern}" Dim included As Integer = UtilSearchIndexer.scopeManager.IncludedInCrawlScope(uriPath) Return included = 1 End Function ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Returns a value indicating whether the specified directory path is included in Windows Search Index. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' Documentation: <see href="https://learn.microsoft.com/en-us/windows/win32/api/searchapi/nf-searchapi-isearchcrawlscopemanager-includedincrawlscope"/> ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code language="VB.NET"> ''' Dim directory As New DirectoryInfo("C:\Games\") ''' Dim isIncluded As Boolean = IsDirectoryIncluded(directory) ''' ''' Debug.WriteLine($"{NameOf(isIncluded)}: {isIncluded}") ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="directory"> ''' The directory path to find. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' <see langword="True"/> if the specified directory path is included in Windows Search Index; ''' otherwise, <see langword="False"/>. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Shared Function IsDirectoryIncluded(directory As DirectoryInfo) As Boolean Return UtilSearchIndexer.IsDirectoryIncluded(directory.FullName) End Function #End Region #Region " Private Methods " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Initializes the value for <see cref="UtilSearchIndexer.searchManager"/>, ''' <see cref="UtilSearchIndexer.catalogManager"/> and ''' <see cref="UtilSearchIndexer.scopeManager"/> members. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' Note: Some functionalities of this assembly may require to install one or all of the listed NuGet packages: ''' <para></para> ''' <see href="https://www.nuget.org/packages/tlbimp-Microsoft.Search.Interop">tlbimp-Microsoft.Search.Interop by mamift</see> ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Private Shared Sub InitializeManagers() If UtilSearchIndexer.searchManager Is Nothing Then UtilSearchIndexer.searchManager = New CSearchManager() End If If UtilSearchIndexer.catalogManager Is Nothing Then UtilSearchIndexer.catalogManager = DirectCast(searchManager.GetCatalog("SystemIndex"), CSearchCatalogManager) End If If UtilSearchIndexer.scopeManager Is Nothing Then UtilSearchIndexer.scopeManager = DirectCast(catalogManager.GetCrawlScopeManager(), CSearchCrawlScopeManager) End If End Sub #End Region End Class End Namespace #End Region
|
|
|
19
|
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
|
en: 10 Septiembre 2023, 08:32 am
|
Aquí les dejo una función para eliminar los tags html de un código html y dejar solo el texto, lo que se conoce como "html stripper". Se necesita la librería HtmlAgilityPack: https://www.nuget.org/packages/HtmlAgilityPack' *********************************************************************** ' Author : ElektroStudios ' Modified : 17-July-2023 ' *********************************************************************** #Region " Public Members Summary " #Region " Functions " ' StripHtml(String, String()) As String #End Region #End Region #Region " Option Statements " Option Strict On Option Explicit On Option Infer Off #End Region #Region " Imports " Imports System.Collections.Generic Imports System.Collections.ObjectModel Imports System.ComponentModel Imports System.Linq Imports HtmlAgilityPack #End Region #Region " HtmlAgilityPack Util " ' ReSharper disable once CheckNamespace Namespace DevCase.ThirdParty.HtmlAgilityPack ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Contains HtmlAgilityPack related utilities. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' Note: Some functionalities of this assembly may require to install one or all of the listed NuGet packages: ''' <para></para> ''' <see href="https://www.nuget.org/packages/HtmlAgilityPack">HtmlAgilityPack</see> ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- <ImmutableObject(True)> Public NotInheritable Class UtilHtmlAgilityPack #Region " Constructors " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Prevents a default instance of the <see cref="UtilHtmlAgilityPack"/> class from being created. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' Note: Some functionalities of this assembly may require to install one or all of the listed NuGet packages: ''' <para></para> ''' <see href="https://www.nuget.org/packages/HtmlAgilityPack">HtmlAgilityPack</see> ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- <DebuggerNonUserCode> Private Sub New() End Sub #End Region #Region " Public Methods " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Removes HTML tags from an html string and returns the content in plain text format. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' Note: Some functionalities of this assembly may require to install one or all of the listed NuGet packages: ''' <para></para> ''' <seealso href="https://www.nuget.org/packages/HtmlAgilityPack">HtmlAgilityPack</seealso> ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- ''' <seealso href="https://stackoverflow.com/a/12836974/1248295">Original C# algorithm</seealso> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code language="VB.NET"> ''' Dim html As String = ''' <![CDATA[ ''' <P style="MARGIN: 0cm 0cm 10pt" class=MsoNormal><SPAN style="LINE-HEIGHT: 115%; ''' FONT-FAMILY: 'Verdana','sans-serif'; COLOR: #333333; FONT-SIZE: 9pt">In an ''' email sent just three days before the Deepwater Horizon exploded, the onshore ''' <SPAN style="mso-bidi-font-weight: bold"><b>BP</b></SPAN> manager in charge of ''' the drilling rig warned his supervisor that last-minute procedural changes were ''' creating "chaos". April emails were given to government investigators by <SPAN ''' style="mso-bidi-font-weight: bold"><b>BP</b></SPAN> and reviewed by The Wall ''' Street Journal and are the most direct evidence yet that workers on the rig ''' were unhappy with the numerous changes, and had voiced their concerns to <SPAN ''' style="mso-bidi-font-weight: bold"><b>BP</b></SPAN>’s operations managers in ''' Houston. This raises further questions about whether <SPAN ''' style="mso-bidi-font-weight: bold"><b>BP</b></SPAN> managers properly ''' considered the consequences of changes they ordered on the rig, an issue ''' investigators say contributed to the disaster.</SPAN></p><br/> ''' ]]>.Value ''' ''' Dim allowedTags As String() = {"span", "b"} ''' Dim str As String = StripHtml(html, allowedTags) ''' Console.WriteLine(str) ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="html"> ''' The string that contains HTML tags. ''' </param> ''' ''' <param name="allowedTags"> ''' An optional list of allowed HTML tags that will not be removed from the string. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' The resulting plain text content without HTML tags. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Shared Function StripHtml(html As String, ParamArray allowedTags As String()) As String If String.IsNullOrEmpty(html) Then Return String.Empty End If Dim document As New HtmlDocument() document.LoadHtml(html) Dim nodes As New Queue(Of HtmlNode)(document.DocumentNode.SelectNodes("./*|./text()")) Do While nodes.Count > 0 Dim node As HtmlNode = nodes.Dequeue() Dim parentNode As HtmlNode = node.ParentNode If Not allowedTags.Contains(node.Name) AndAlso node.Name <> "#text" Then Dim childNodes As HtmlNodeCollection = node.SelectNodes("./*|./text()") If childNodes IsNot Nothing Then For Each child As HtmlNode In childNodes nodes.Enqueue(child) parentNode.InsertBefore(child, node) Next child End If parentNode.RemoveChild(node) End If Loop Return System.Net.WebUtility.HtmlDecode(document.DocumentNode.InnerHtml) End Function #End Region End Class End Namespace #End Region
|
|
|
20
|
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
|
en: 10 Septiembre 2023, 08:25 am
|
He escrito este simulador / generador de errores tipográficos en un string. No está muy pulido, pero es un comienzo de idea. Las reglas son las siguientes: ● The error-rate percentage calculation is done for the input text length, instead of throwing the dice for each character.
● Letters can only be replaced with different letters of the same case (upper-case or lower-case).
● Numbers can only be replaced with other (different) numbers.
● Special characters like punctuation and white-spaces will remain untouched. Ejemplo de uso: Dim inputText As String = "I possess the virtues of rapid and error-free typing. Through my precise keystrokes and unwavering focus, I consistently deliver written content efficiently and accurately. My typing speed is unparalleled, allowing me to swiftly transcribe thoughts into written form with remarkable velocity. Each keystroke is executed with precision, enabling me to maintain a consistent flow of text while adhering to the highest standards of accuracy. In addition to speed, my dedication to perfection ensures that typographical errors are virtually non-existent in my output. Meticulously reviewing each line of text, I meticulously detect and rectify any potential errors, guaranteeing a polished and professional final product. Whether it's crafting detailed reports, composing compelling articles, or engaging in fast-paced communication, my quick and error-free typing abilities empower me to meet deadlines with ease and precision. I take pride in my proficiency, knowing that it contributes to a seamless and efficient workflow. In summary, my virtuosity in fast and error-free typing is a testament to my commitment to professionalism and excellence. With swift keystrokes and unwavering accuracy, I offer a valuable asset for any task that demands efficiency, precision, and an impeccable attention to detail." Dim errorrate As Integer = 2 ' 2 percent of the total input text length. Dim letters As Boolean = True Dim numbers As Boolean = True Dim result As String = UtilString.GenerateTypos(inputText, errorrate, letters, numbers) Console.WriteLine(result)
Salida: Whether it's crafting detailed reports, composing yompelling articles, or engaging in fast-paced communication, my quick and error-free gyping abilities empower me to meet deadlines with ease and precusion. I take pride in my proriciency, knowing that it contributes to a seamless and efficient workflow.
In summary, my virtuosity in fast and error-free typing is a kestament to my commitment to professionalism and excellence. With fwift keystrokes and unwavering accuracy, I offer a valuable asset for eny task that demands efficiencv, precision, and an imxeccable attention to detail.
UtilString.vb' *********************************************************************** ' Author : ElektroStudios ' Modified : 14-July-2023 ' *********************************************************************** #Region " Public Members Summary " #Region " Functions " ' GenerateTypos(String, Integer, Boolean, Boolean) As String #End Region #End Region #Region " Option Statements " Option Strict On Option Explicit On Option Infer Off #End Region #Region " Imports " Imports System.Collections.Generic Imports System.Text Imports DevCase.Runtime.Numerics #End Region #Region " String Util " ' ReSharper disable once CheckNamespace Namespace DevCase.Core.DataProcessing.Common Partial Public NotInheritable Class UtilString #Region " Public Methods " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Simulate random typographical errors in the input text, based on the specified error rate. ''' <para></para> ''' Rules: ''' <para></para> ''' ● The error-rate percentage calculation is done for the input text length, ''' instead of throwing the dice for each character. ''' <para></para> ''' ● Letters can only be replaced with different letters of the same case (upper-case or lower-case). ''' <para></para> ''' ● Numbers can only be replaced with different numbers. ''' <para></para> ''' ● Special characters like punctuation and white-spaces will remain untouched. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code language="VB.NET"> ''' Dim inputText As String = "I possess the virtues of rapid and error-free typing. Through my precise keystrokes and unwavering focus, I consistently deliver written content efficiently and accurately. ''' ''' My typing speed is unparalleled, allowing me to swiftly transcribe thoughts into written form with remarkable velocity. Each keystroke is executed with precision, enabling me to maintain a consistent flow of text while adhering to the highest standards of accuracy. ''' ''' In addition to speed, my dedication to perfection ensures that typographical errors are virtually non-existent in my output. Meticulously reviewing each line of text, I meticulously detect and rectify any potential errors, guaranteeing a polished and professional final product. ''' ''' Whether it's crafting detailed reports, composing compelling articles, or engaging in fast-paced communication, my quick and error-free typing abilities empower me to meet deadlines with ease and precision. I take pride in my proficiency, knowing that it contributes to a seamless and efficient workflow. ''' ''' In summary, my virtuosity in fast and error-free typing is a testament to my commitment to professionalism and excellence. With swift keystrokes and unwavering accuracy, I offer a valuable asset for any task that demands efficiency, precision, and an impeccable attention to detail." ''' ''' Dim errorrate As Integer = 2 ' 2 percent of the total input text length. ''' Dim letters As Boolean = True ''' Dim numbers As Boolean = True ''' ''' Dim result As String = GenerateTypos(inputText, errorrate, letters, numbers) ''' ''' Console.WriteLine(result) ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="input"> ''' The input text. ''' </param> ''' ''' <param name="errorRate"> ''' The error rate percentage. It must be in the range of 0 to 100. ''' <para></para> ''' Note: The error-rate percentage calculation is done for the input text length, ''' instead of throwing the dice for each character. ''' <para></para> ''' If this value is 0, no changes are made to the input text. ''' <para></para> ''' If error rate is too small for the length of the input text, it may not add any typos. ''' <para></para> ''' Suggested values can go between 1 to 5 percent. ''' Higher values will produce more typos, so more unrealistic simulations. ''' </param> ''' ''' <param name="letters"> ''' Optional. If true, allows to simulate random typographical errors in letters. Default value is True. ''' <para></para> ''' Note: Letters can only be replaced with different letters of the same case (upper-case or lower-case). ''' </param> ''' ''' <param name="numbers"> ''' Optional. If true, allows to simulate random typographical errors in numbers. Default value is True. ''' <para></para> ''' Note: Numbers can only be replaced with different numbers. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' The resulting text with random typographical errors added. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- Public Shared Function GenerateTypos(input As String, errorRate As Integer, letters As Boolean, numbers As Boolean) As String If errorRate < 0 Or errorRate > 100 Then Throw New ArgumentException($"'{NameOf(errorRate)}' must be in the range of 0 to 100.") ElseIf errorRate = 0 Then Return input End If ' Get a proper input string length by replacing white-spaces ' to try produce a more realistic (smaller) error rate count. Dim charsToRemove As Char() = ",.´`+¡'!·$%&/()=?¿^;:¨*[]{}-_""".ToCharArray() Dim inputLength As Integer = InternalReplaceChars(input, charsToRemove, Nothing, StringComparison.OrdinalIgnoreCase, -1).Length ' Calculate the amount of typographical errors to generate in the source string. Dim typosCount As Integer = CInt(System.Math.Round(inputLength * errorRate / 100)) If typosCount = 0 Then typosCount = 1 End If Dim sb As New StringBuilder() Dim selectedIndices As New HashSet(Of Integer)() Dim validIndices As New List(Of Integer)() For i As Integer = 0 To input.Length - 1 Dim c As Char = input(i) If (letters AndAlso Char.IsLetter(c)) OrElse (numbers AndAlso Char.IsDigit(c)) Then validIndices.Add(i) End If Next If validIndices.Count = 0 Then Return input End If If validIndices.Count <= typosCount Then For i As Integer = 0 To input.Length - 1 Dim c As Char = input(i) Dim modifiedChar As Char = c If validIndices.Contains(i) AndAlso RandomNumberGenerator.Instance.Next(100) < errorRate Then If letters AndAlso Char.IsLetter(c) Then modifiedChar = RandomReplaceLetterOrDigit(c) ElseIf numbers AndAlso Char.IsDigit(c) Then modifiedChar = RandomReplaceLetterOrDigit(c) End If End If sb.Append(modifiedChar) Next Return sb.ToString() End If While selectedIndices.Count < typosCount Dim index As Integer = validIndices(RandomNumberGenerator.Instance.Next(validIndices.Count)) selectedIndices.Add(index) End While For i As Integer = 0 To input.Length - 1 Dim c As Char = input(i) Dim modifiedChar As Char = c If selectedIndices.Contains(i) Then If letters AndAlso Char.IsLetter(c) Then modifiedChar = RandomReplaceLetterOrDigit(c) ElseIf numbers AndAlso Char.IsDigit(c) Then modifiedChar = RandomReplaceLetterOrDigit(c) End If End If sb.Append(modifiedChar) Next Return sb.ToString() End Function #End Region #Region " Private Methods " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Replaces text using the specified string comparison type. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' Original source: ''' <see href="http://www.codeproject.com/Articles/10890/Fastest-C-Case-Insenstive-String-Replace?msg=1835929#xx1835929xx"/> ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code language="VB.NET"> ''' Dim str As String = "Hello World!".Replace("Hd".ToCharArray(), "_", StringComparison.OrdinalIgnoreCase) ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="str"> ''' The source <see cref="String"/>. ''' </param> ''' ''' <param name="findWhat"> ''' The characters to find. ''' </param> ''' ''' <param name="replaceWith"> ''' The string to replace with. ''' </param> ''' ''' <param name="comparisonType"> ''' The string comparison type. ''' </param> ''' ''' <param name="stringBuilderCapacity"> ''' The initial buffer size of the <see cref="Stringbuilder"/>. ''' This parameter is reserved for testing purposes. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' The replaced string. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Private Shared Function InternalReplaceChars(str As String, findWhat As IEnumerable(Of Char), replaceWith As String, comparisonType As StringComparison, stringBuilderCapacity As Integer) As String Dim sb As New Global.System.Text.StringBuilder(capacity:=If(stringBuilderCapacity <= 0, System.Math.Min(4096, str.Length), stringBuilderCapacity)) Dim charFound As Boolean For Each c As Char In str For Each find As Char In findWhat If CStr(c).Equals(find, comparisonType) Then charFound = True Exit For End If Next If Not charFound Then sb.Append(c) Else sb.Append(replaceWith) charFound = False End If Next Return sb.ToString() End Function #End Region End Class End Namespace #End Region
UtilString.vb' *********************************************************************** ' Author : ElektroStudios ' Modified : 14-July-2023 ' *********************************************************************** #Region " Public Members Summary " #Region " Functions " ' RandomReplaceLetterOrDigit(Char) As Char #End Region #End Region #Region " Option Statements " Option Strict On Option Explicit On Option Infer Off #End Region #Region " Imports " Imports DevCase.Runtime.Numerics #End Region #Region " String Util " ' ReSharper disable once CheckNamespace Namespace DevCase.Core.DataProcessing.Common Partial Public NotInheritable Class UtilString #Region " Public Methods " ''' -------------------------------------------------------------------------------------------------- ''' <summary> ''' Replaces a letter or digit character with a random character of the same type based on these specific rules: ''' <para></para> ''' ● If the character is a digit ( <c>Char.IsDigit(character)</c> ), ''' the function returns a different digit from the range "0" to "9". ''' <para></para> ''' ● If the character is a letter ( <c>Char.IsLetter(character)</c> ): ''' <para></para> ''' - If it is a vowel, and it is upper-case, the function returns a different upper-case vowel. ''' <para></para> ''' - If it is a vowel, and it is lower-case, the function returns a different lower-case vowel. ''' <para></para> ''' - If it is a consonant, and it is upper-case, the function returns a different upper-case consonant. ''' <para></para> ''' - If it is a consonant, and it is lower-case, the function returns a different lower-case consonant. ''' <para></para> ''' ● If the character is neither a letter nor a digit, the function returns the same character. ''' </summary> ''' -------------------------------------------------------------------------------------------------- ''' <param name="character"> ''' The character to be replaced. ''' </param> ''' -------------------------------------------------------------------------------------------------- ''' <returns> ''' If the character is a letter or digit, returns a random character of the same type; ''' otherwise, returns the same character. ''' </returns> ''' -------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Shared Function RandomReplaceLetterOrDigit(character As Char) As Char Dim availableChars As Char() If Char.IsDigit(character) Then availableChars = "0123456789".ToCharArray() ElseIf Char.IsLetter(character) Then availableChars = If(Char.IsUpper(character), If("AEIOU".Contains(character), "AEIOU".ToCharArray(), "BCDFGHJKLMNPQRSTVWXYZ".ToCharArray()), If("aeiou".Contains(character), "aeiou".ToCharArray(), "bcdfghjklmnpqrstvwxyz".ToCharArray())) Else Return character ' Throw New ArgumentException("The character is neither a letter nor a digit.", paramName:=NameOf(character)) End If Dim randomChar As Char Do randomChar = availableChars(RandomNumberGenerator.Instance.Next(availableChars.Length)) Loop While randomChar = character Return randomChar End Function #End Region End Class End Namespace #End Region
RandomNumberGenerator.vbhttps://foro.elhacker.net/net_c_vbnet_asp/libreria_de_snippets_para_vbnet_compartan_aqui_sus_snippets-t378770.0.html;msg2272581#msg2272581
|
|
|
|
|
|
|