elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Entrar al Canal Oficial Telegram de elhacker.net


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
0 Usuarios y 2 Visitantes están viendo este tema.
Páginas: 1 ... 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 [29] 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 ... 58 Ir Abajo Respuesta Imprimir
Autor Tema: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)  (Leído 480,184 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #280 en: 10 Agosto 2013, 22:55 pm »

Una Class para manipular el archivo Hosts:

Código
  1. #Region " Hosts Helper "
  2.  
  3. Public Class Hosts_Helper
  4.  
  5.  
  6.    ' [ Hosts Helper ]
  7.    '
  8.    ' // By Elektro H@cker
  9.    '
  10.    ' Examples:
  11.    '
  12.    ' MsgBox(Hosts_Helper.HOSTS_Exists)
  13.    ' Hosts_Helper.Add("www.youtube.com", "231.7.66.33")
  14.    ' Hosts_Helper.Block("www.youtube.com")
  15.    ' MsgBox(Hosts_Helper.IsAdded("www.youtube.com"))
  16.    ' MsgBox(Hosts_Helper.IsBlocked("www.youtube.com"))
  17.    ' Hosts_Helper.Remove("www.youtube.com")
  18.    ' Hosts_Helper.Clean_Hosts_File()
  19.  
  20.  
  21.    Shared ReadOnly HOSTS As String = _
  22.    IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "Drivers\etc\hosts")
  23.  
  24.  
  25.    ''' <summary>
  26.    ''' Adds a new Block mapping into the Hosts file.
  27.    ''' </summary>
  28.    Public Shared Sub Block(ByVal URL As String)
  29.  
  30.        Dim Entry As String = String.Format("::1 {0}", URL)
  31.  
  32.        If HOSTS_Exists() AndAlso IsBlocked(URL) Then
  33.  
  34.            Throw New Exception(String.Format("""{0}"" is already blocked.", URL))
  35.            Exit Sub
  36.  
  37.        ElseIf HOSTS_Exists() AndAlso IsAdded(URL) Then
  38.  
  39.            Remove(URL)
  40.  
  41.        End If
  42.  
  43.        Try
  44.            IO.File.AppendAllText(HOSTS, (Environment.NewLine & Entry), System.Text.Encoding.Default)
  45.        Catch ex As Exception
  46.            Throw New Exception(ex.Message)
  47.        End Try
  48.  
  49.    End Sub
  50.  
  51.  
  52.    ''' <summary>
  53.    ''' Adds a new mapping into Hosts file.
  54.    ''' </summary>
  55.    Public Shared Sub Add(ByVal URL As String, ByVal IP_Address As String)
  56.  
  57.        Dim Entry As String = String.Format("{0} {1}", IP_Address, URL)
  58.  
  59.        If HOSTS_Exists() AndAlso (IsAdded(URL) OrElse IsBlocked(URL)) Then
  60.            Throw New Exception(String.Format("""{0}"" is already mapped.", URL))
  61.            Exit Sub
  62.  
  63.        ElseIf Not Validate_IP(IP_Address) Then
  64.            Throw New Exception(String.Format("""{0}"" is not a valid IP adress.", IP_Address))
  65.            Exit Sub
  66.        End If
  67.  
  68.        Try
  69.            IO.File.AppendAllText(HOSTS, (Environment.NewLine & Entry), System.Text.Encoding.Default)
  70.        Catch ex As Exception
  71.            Throw New Exception(ex.Message)
  72.        End Try
  73.  
  74.    End Sub
  75.  
  76.  
  77.    ''' <summary>
  78.    ''' Removes a blocked or an added URL from the Hosts file.
  79.    ''' </summary>
  80.    Public Shared Sub Remove(ByVal URL As String)
  81.  
  82.        If Not HOSTS_Exists() Then
  83.            Throw New Exception("HOSTS File does not exists.")
  84.            Exit Sub
  85.        ElseIf HOSTS_Exists() And Not (IsAdded(URL) OrElse IsBlocked(URL)) Then
  86.            Throw New Exception(String.Format("""{0}"" is not added yet.", URL))
  87.            Exit Sub
  88.        End If
  89.  
  90.        Try
  91.  
  92.            Dim Content As String = _
  93.                System.Text.RegularExpressions.Regex.Replace(IO.File.ReadAllText(HOSTS).ToLower, _
  94.                String.Format("(\d{{1,3}}\.\d{{1,3}}\.\d{{1,3}}\.\d{{1,3}}|::1)(\s+|\t+){0}", URL.ToLower), String.Empty)
  95.  
  96.            IO.File.WriteAllText(HOSTS, Content, System.Text.Encoding.Default)
  97.  
  98.        Catch ex As Exception
  99.            Throw New Exception(ex.Message)
  100.        End Try
  101.  
  102.    End Sub
  103.  
  104.  
  105.    ''' <summary>
  106.    ''' Checks if an URL is already added into the Hosts file.
  107.    ''' </summary>
  108.    Public Shared Function IsAdded(ByVal URL As String) As Boolean
  109.  
  110.        Return If(Not HOSTS_Exists(), False, _
  111.                  System.Text.RegularExpressions.Regex.IsMatch( _
  112.                  System.Text.RegularExpressions.Regex.Replace(IO.File.ReadAllText(HOSTS).ToLower, "\s+|\t+", ";"), _
  113.                  String.Format(";[^\#]?\d{{1,3}}\.\d{{1,3}}\.\d{{1,3}}\.\d{{1,3}};{0}", URL.ToLower)))
  114.  
  115.    End Function
  116.  
  117.  
  118.    ''' <summary>
  119.    ''' Checks if an URL is already blocked into the Hosts file.
  120.    ''' </summary>
  121.    Public Shared Function IsBlocked(ByVal URL As String) As Boolean
  122.  
  123.        Return If(Not HOSTS_Exists(), False, _
  124.                  System.Text.RegularExpressions.Regex.IsMatch( _
  125.                  System.Text.RegularExpressions.Regex.Replace(IO.File.ReadAllText(HOSTS).ToLower, "\s+|\t+", String.Empty), _
  126.                  String.Format("[^\#](127.0.0.1|::1){0}", URL.ToLower)))
  127.  
  128.    End Function
  129.  
  130.  
  131.    ''' <summary>
  132.    ''' Checks if the Hosts file exists.
  133.    ''' </summary>
  134.    Public Shared Function HOSTS_Exists() As Boolean
  135.        Return IO.File.Exists(HOSTS)
  136.    End Function
  137.  
  138.  
  139.    ''' <summary>
  140.    ''' Cleans all the mappings inside the Hosts file.
  141.    ''' </summary>
  142.    Public Shared Sub Clean_Hosts_File()
  143.        Try
  144.            IO.File.WriteAllText(HOSTS, String.Empty)
  145.        Catch ex As Exception
  146.            MsgBox(ex.Message)
  147.        End Try
  148.    End Sub
  149.  
  150.  
  151.    ' Validates an IP adress.
  152.    Private Shared Function Validate_IP(ByVal IP_Address As String) As Boolean
  153.        Dim IP As System.Net.IPAddress = Nothing
  154.        Return System.Net.IPAddress.TryParse(IP_Address, IP)
  155.    End Function
  156.  
  157. End Class
  158.  
  159. #End Region


« Última modificación: 10 Agosto 2013, 23:16 pm por EleKtro H@cker » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #281 en: 14 Agosto 2013, 10:59 am »

Obtener la diferencia (personalizada) entre dos fechas:

#Region " Date Difference "
    
       ' Date Difference
       '
       ' // By Elektro H@cker
       '
       ' Examples :
       '
       ' MsgBox(DateDifference(DateTime.Parse("01/03/2013"), DateTime.Parse("10/04/2013"))) ' Result: 1 Months, 1 Weeks, 2 Days, 0 Hours, 0 Minutes and 0 Seconds
       ' MsgBox(DateDifference(DateTime.Parse("01/01/2013 14:00:00"), DateTime.Parse("02/01/2013 15:00:30"))) ' Result: 0 Months, 0 Weeks, 1 Days, 1 Hours, 0 Minutes and 30 Seconds
    
       Private Function DateDifference(ByVal Date1 As DateTime, ByVal Date2 As DateTime) As String
    
           Dim MonthDiff As String, WeekDiff As String, _
               DayDiff As String, HourDiff As String, _
               MinuteDiff As String, SecondDiff As String
    
           MonthDiff = Convert.ToString(DateDiff("M", Date1, Date2))
           WeekDiff = Convert.ToString(DateDiff("d", Date1.AddMonths(DateDiff("M", Date1, Date2)), Date2) \ 7)
           DayDiff = Convert.ToString(DateDiff("d", Date1.AddMonths(DateDiff("M", Date1, Date2)), Date2) - (WeekDiff * 7))
           HourDiff = Convert.ToString(DateDiff("h", Date1.AddHours(DateDiff("h", Date1, Date2)), Date2) - (Date1.Hour - Date2.Hour))
           MinuteDiff = Convert.ToString(DateDiff("n", Date1.AddMinutes(DateDiff("n", Date1, Date2)), Date2) - (Date1.Minute - Date2.Minute))
           SecondDiff = Convert.ToString(DateDiff("s", Date1.AddSeconds(DateDiff("s", Date1, Date2)), Date2) - (Date1.Second - Date2.Second))
    
           Return String.Format("{0} Months, {1} Weeks, {2} Days, {3} Hours, {4} Minutes and {5} Seconds", _
                                MonthDiff, WeekDiff, DayDiff, HourDiff, MinuteDiff, SecondDiff)
    
       End Function
    
    #End Region


Corregido:
Código
  1. #Region " Date Difference "
  2.  
  3.    ' Date Difference
  4.    '
  5.    ' Examples :
  6.    '
  7.    ' MsgBox(DateDifference(DateTime.Parse("01/03/2013"), DateTime.Parse("10/04/2013"))) ' Result: 1 Months, 1 Weeks, 2 Days, 0 Hours, 0 Minutes and 0 Seconds
  8.    ' MsgBox(DateDifference(DateTime.Parse("01/01/2013 14:00:00"), DateTime.Parse("02/01/2013 15:00:30"))) ' Result: 0 Months, 0 Weeks, 1 Days, 1 Hours, 0 Minutes and 30 Seconds
  9.  
  10.    Private Function DateDifference(ByVal Date1 As DateTime, ByVal Date2 As DateTime) As String
  11.  
  12.        Dim Time As TimeSpan
  13.        Dim MonthDiff As Integer, WeekDiff As Integer
  14.  
  15.        Do Until Date1 > Date2
  16.            Date1 = Date1.AddMonths(1)
  17.            MonthDiff += 1
  18.        Loop
  19.  
  20.        MonthDiff -= 1
  21.        Date1 = Date1.AddMonths(-1)
  22.        Time = (Date2 - Date1)
  23.        WeekDiff = (Time.Days \ 7)
  24.        Time = (Time - TimeSpan.FromDays(WeekDiff * 7))
  25.  
  26.        Return String.Format("{0} Months, {1} Weeks, {2} Days, {3} Hours, {4} Minutes and {5} Seconds", _
  27.                             MonthDiff, WeekDiff, Time.Days, Time.Hours, Time.Minutes, Time.Seconds)
  28.  
  29.    End Function
  30.  
  31. #End Region


« Última modificación: 16 Agosto 2013, 02:14 am por EleKtro H@cker » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #282 en: 16 Agosto 2013, 04:19 am »

Unos tips que he codeado sobre el manejo de una lista de Tuplas, de una lista de FIleInfo, y sobre la utilización de algunas extensiones de LINQ:

PD: Es muy bueno aprender todos estos métodos para dejar en el olvido a los FOR.


List(Of Tuple)
Código
  1.        ' Create the list:
  2.        Dim TupleList As New List(Of Tuple(Of String, Boolean, Integer)) ' From {Tuple.Create("Hello world", True, 1)}
  3.  
  4.        ' Add an Item:
  5.        TupleList.Add(Tuple.Create("Elektro", False, 0))
  6.        TupleList.Add(Tuple.Create("H@cker", True, 1))
  7.  
  8.        ' Order the TupleList by a Tuple item:
  9.        TupleList = TupleList.OrderBy(Function(Tuple) Tuple.Item3).ToList
  10.  
  11.        ' Sort the TupleList by a Tuple item:
  12.        TupleList.Sort( _
  13.        Function(Comparer_A As Tuple(Of String, Boolean, Integer), _
  14.                 Comparer_B As Tuple(Of String, Boolean, Integer)) _
  15.                 Comparer_A.Item3.CompareTo(Comparer_B.Item3))
  16.  
  17.        ' Filter the list by items equals as "True" in their Tuple second item:
  18.        TupleList = TupleList.Where(Function(Tuple) Tuple.Item2 = True).ToList
  19.  
  20.        ' Display a Tuple item from a list item:
  21.        MsgBox(TupleList.Item(0).Item2)
  22.  
  23.        ' Looping the list:
  24.        For Each Item As Tuple(Of String, Boolean, Integer) In TupleList
  25.            MsgBox(Item.Item1)
  26.        Next


List(Of FileInfo)
Código
  1.        ' Create the list:
  2.        Dim Files As List(Of IO.FileInfo) = IO.Directory.GetFiles("C:\", "*") _
  3.        .Select(Function(ToFileInfo) New IO.FileInfo(ToFileInfo)).ToList
  4.  
  5.        ' Add an Item:
  6.        Files.Add(New IO.FileInfo("C:\Windows\Notepad.exe"))
  7.  
  8.        ' Order the list by a file property:
  9.        Files = Files.OrderBy(Function(File) File.Extension).ToList
  10.  
  11.        ' Sort the list by a file property:
  12.        Files.Sort( _
  13.        Function(Comparer_A As IO.FileInfo, Comparer_B As IO.FileInfo) _
  14.                 Comparer_A.Extension.CompareTo(Comparer_B.Extension))
  15.  
  16.        ' Filter the list by files containing "note" word in their filename:
  17.        Files = Files.Where(Function(File) File.Name.ToLower.Contains("note")).ToList
  18.  
  19.        ' Display a file property from a list item:
  20.        MsgBox(Files.Item(0).FullName)
  21.  
  22.        ' Looping the list:
  23.        For Each File As IO.FileInfo In Files
  24.            MsgBox(File.FullName)
  25.        Next
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #283 en: 17 Agosto 2013, 05:48 am »

Convierte una fecha a formato de fecha Unix

Código
  1. #Region " DateTime To Unix "
  2.  
  3.    ' [ DateTime To Unix Function ]
  4.    '
  5.    ' Examples :
  6.    '
  7.    ' MsgBox(DateTime_To_Unix(DateTime.Parse("01/01/2013 12:00:00"))) ' Result: 1357041600
  8.  
  9.    Public Function DateTime_To_Unix(ByVal DateTime As DateTime) As Long
  10.        Return DateDiff(DateInterval.Second, #1/1/1970#, DateTime)
  11.    End Function
  12.  
  13. #End Region

Convierte formato de fecha Unix a Fecha normal.

Código
  1. #Region " Unix To DateTime "
  2.  
  3.    ' [ Unix To DateTime Function ]
  4.    '
  5.    ' Examples :
  6.    '
  7.    ' MsgBox(Unix_To_DateTime(1357041600)) ' Result: 01/01/2013 12:00:00
  8.  
  9.    Public Function Unix_To_DateTime(ByVal UnixTime As Long) As DateTime
  10.        Return DateAdd(DateInterval.Second, UnixTime, #1/1/1970#)
  11.    End Function
  12.  
  13. #End Region
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #284 en: 17 Agosto 2013, 19:17 pm »

Una función para convertir entre tasas de transferencia de telecomunicaciones y tasas de transferencia de datos, es decir, entre Bp/s y B/s.

PD: En este snippet @IkillNukes me ha ayudado con los cálculos matemáticos de las enumeraciones, que me daban ciertos problemas.

Código
  1. #Region " Telecommunication Bitrate To DataStorage Bitrate "
  2.  
  3.    ' [ Base64 To String Function ]
  4.    '
  5.    ' // By Elektro H@cker & IKillNukes
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' MsgBox(Telecommunication_Bitrate_To_DataStorage_Bitrate(365, _
  10.    '        Telecommunications_Bitrates.Kilobips, _
  11.    '        DataStorage_Bitrates.Kilobytes)) ' Result: 45
  12.    '
  13.    ' MsgBox(Telecommunication_Bitrate_To_DataStorage_Bitrate(365, _
  14.    '        Telecommunications_Bitrates.Kilobips, _
  15.    '        DataStorage_Bitrates.Kilobytes)) ' Result: 45,625
  16.  
  17.    Private Enum Telecommunications_Bitrates As Long
  18.        Bips = 1 ' bit/s
  19.        Kilobips = 1000 ' bit/s
  20.        Megabips = 1000000 ' bit/s
  21.        Gigabips = 1000000000 ' bit/s
  22.        Terabips = 1000000000000 ' bit/s
  23.    End Enum
  24.  
  25.    Private Enum DataStorage_Bitrates As Long
  26.        Bytes = 8 ' bits
  27.        Kilobytes = 8000 ' bits
  28.        Megabytes = 8000000 ' bits
  29.        Gigabytes = 8000000000 ' bits
  30.        Terabytes = 8000000000000  ' bits
  31.    End Enum
  32.  
  33.    Private Function Telecommunication_Bitrate_To_DataStorage_Bitrate( _
  34.                       ByVal BitRate As Single, _
  35.                       ByVal Telecommunications_Bitrates As Telecommunications_Bitrates, _
  36.                       ByVal DataStorage_Bitrates As DataStorage_Bitrates, _
  37.                       Optional ByVal Rounded As Boolean = True
  38.                     ) As Single
  39.  
  40.        Return IIf(Rounded, _
  41.                   (BitRate * Telecommunications_Bitrates) \ DataStorage_Bitrates, _
  42.                   (BitRate * Telecommunications_Bitrates) / DataStorage_Bitrates)
  43.  
  44.    End Function
  45.  
  46. #End Region
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #285 en: 17 Agosto 2013, 20:03 pm »

Una función para abreviar cantidades de dinero al estilo americano.

PD: He preguntado a gente americana como son las abreviaturas para cifras más grandes de un Trillón pero al parecer no existen abreviaturas Standards, así que me las he inventado un poco basándome en el nombre de las cantidades. http://ell.stackexchange.com/questions/9123/money-abbreviations

EDITO: Corregido la ubicación del caracter del dolar, parece ser que se pone a la izquierda de la cantidad, no a la derecha.
Código
  1.    #Region " Money Abbreviation "
  2.  
  3.       ' [ Money Abbreviation Function ]
  4.       '
  5.       ' // By Elektro H@cker
  6.       '
  7.       ' Examples :
  8.       '
  9.       ' MsgBox(Money_Abbreviation(1000))           ' Result: 1 K
  10.       ' MsgBox(Money_Abbreviation(1000000))        ' Result: 1 M
  11.       ' MsgBox(Money_Abbreviation(1500000, False)) ' Result: 1,5 M
  12.  
  13.       Private Function Money_Abbreviation(ByVal Quantity As Object, _
  14.                                           Optional ByVal Rounded As Boolean = True) As String
  15.  
  16.           Dim Abbreviation As String = String.Empty
  17.  
  18.           Select Case Quantity.GetType()
  19.  
  20.               Case GetType(Int16), GetType(Int32), GetType(Int64)
  21.                   Quantity = FormatNumber(Quantity, TriState.False)
  22.  
  23.               Case Else
  24.                   Quantity = FormatNumber(Quantity, , TriState.False)
  25.  
  26.           End Select
  27.  
  28.           Select Case Quantity.ToString.Count(Function(character As Char) character = Convert.ToChar("."))
  29.  
  30.               Case 0 : Return String.Format("${0}", Quantity)
  31.               Case 1 : Abbreviation = "k"
  32.               Case 2 : Abbreviation = "M"
  33.               Case 3 : Abbreviation = "B"
  34.               Case 4 : Abbreviation = "Tr."
  35.               Case 5 : Abbreviation = "Quad."
  36.               Case 6 : Abbreviation = "Quint."
  37.               Case 7 : Abbreviation = "Sext."
  38.               Case 8 : Abbreviation = "Sept."
  39.               Case Else
  40.                   Return String.Format("${0}", Quantity)
  41.  
  42.           End Select
  43.  
  44.           Return IIf(Rounded, _
  45.                  String.Format("{0} {1}", StrReverse(StrReverse(Quantity).Substring(StrReverse(Quantity).LastIndexOf(".") + 1)), Abbreviation), _
  46.                  String.Format("{0} {1}", StrReverse(StrReverse(Quantity).Substring(StrReverse(Quantity).LastIndexOf(".") - 1)), Abbreviation))
  47.  
  48.       End Function
  49.  
  50.    #End Region





Contar la cantidad de coincidencias de un caracter dentro de un string.

Código
  1. #Region " Count Character "
  2.  
  3.    ' [ Count Character Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Count_Character("Elektro", "e"))       ' Result: 1
  9.    ' MsgBox(Count_Character("Elektro", "e", True)) ' Result: 2
  10.  
  11.    Public Function Count_Character(ByVal str As String, ByVal character As Char, _
  12.                                    Optional ByVal IgnoreCase As Boolean = False) As Integer
  13.  
  14.        Return IIf(IgnoreCase, _
  15.                   str.ToLower.Count(Function(c As Char) c = Convert.ToChar(character.ToString.ToLower)), _
  16.                   str.Count(Function(c As Char) c = character))
  17.  
  18.    End Function
  19.  
  20. #End Region
« Última modificación: 17 Agosto 2013, 21:55 pm por EleKtro H@cker » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #286 en: 8 Septiembre 2013, 01:43 am »

Este código devuelve la cantidad de coincidencias de un String en los valores de un Array:

Código
  1. #Region " Count Array Matches "
  2.  
  3.    ' [ Count Array Matches ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Count_Array_Matches({"a", "b", "c", "d", "d", "d"}, "d")) ' Result: 3
  9.  
  10.    Private Function Count_Array_Matches(ByVal Collection As String(), _
  11.                                         ByVal Match As String, ByVal _
  12.                                         IgnoreCase As Boolean) As Integer
  13.  
  14.        Return IIf(IgnoreCase, _
  15.                  Collection.Where(Function(str) str.ToLower = Match.ToLower).Count, _
  16.                  Collection.Where(Function(str) str = Match).Count)
  17.  
  18.    End Function
  19.  
  20. #End Region





Este código elimina los valores únicos de un array:

Código
  1. #Region " Delete Array Unique Names "
  2.  
  3.    ' [ Delete Array Unique Names ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Dim MyArray as String() = Delete_Unique_Values_In_Array({"a", "b", "c", "d", "d", "d"}) ' Result: {"d", "d", "d"}
  9.  
  10.    Private Function Delete_Unique_Values_In_Array(ByVal Collection As String()) As String()
  11.        Return Collection.GroupBy(Function(x) x) _
  12.        .Where(Function(x) x.Count() > 1) _
  13.        .SelectMany(Function(x) x) _
  14.        .ToArray()
  15.    End Function
  16.  
  17. #End Region

PD: No está muy optimizado pero para Arrays pequeños no se aprecia nada el performance.
« Última modificación: 8 Septiembre 2013, 01:46 am por EleKtro H@cker » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #287 en: 9 Septiembre 2013, 15:09 pm »

Contar las líneas en blanco o valores vacios de un array usando LINQ:


Código
  1. MsgBox(RichTextBox1.Lines.Where(Function(Line) String.IsNullOrEmpty(Line)).Count)
  2.  
  3. MsgBox({"a", "", "", "b"}.Where(Function(value) String.IsNullOrEmpty(value)).Count)


EDITO:

Unas funciones genéricas muy cortas:

Código
  1. #Region " Count Blank Lines "
  2.  
  3.    ' [ Count Blank Lines ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' MsgBox(Count_Blank_Lines(RichTextBox1.Lines))
  10.    ' MsgBox(Count_Blank_Lines({"A", "", "", "B"})) ' Result: 2
  11.  
  12.    Private Function Count_Blank_Lines(ByVal str As String()) As Integer
  13.        Return str.Where(Function(X) String.IsNullOrEmpty(X)).Count
  14.    End Function
  15.  
  16. #End Region

Código
  1. #Region " Count Non Blank Lines "
  2.  
  3.    ' [ Count non blank lines ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' MsgBox(Count_Non_Blank_Lines(RichTextBox1.Lines))
  10.    ' MsgBox(Count_Non_Blank_Lines({"A", "", "", "B"})) ' Result: 2
  11.  
  12.    Private Function Count_Non_Blank_Lines(ByVal str As String()) As Integer
  13.        Return str.Where(Function(X) Not String.IsNullOrEmpty(X)).Count
  14.    End Function
  15.  
  16. #End Region

Código
  1. #Region " Get non blank lines "
  2.  
  3.    ' [ Get non blank lines ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' MsgBox(String.Join(Environment.NewLine, Get_Non_Blank_Lines(RichTextBox1.Lines)))
  10.    ' MsgBox(String.Join(Environment.NewLine, Get_Non_Blank_Lines({"A", "", "", "B"}))) ' Result: {"A", "B"}
  11.  
  12.    Private Function Get_Non_Blank_Lines(ByVal str As String()) As String()
  13.        Return str.Where(Function(X) Not String.IsNullOrEmpty(X)).ToArray
  14.    End Function
  15.  
  16. #End Region
« Última modificación: 9 Septiembre 2013, 15:27 pm por EleKtro H@cker » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #288 en: 9 Septiembre 2013, 20:05 pm »

Contar todas las agrupaciones en un string:

PD: Para quien no sepa, una agrupación empieza con el caracter "(" y acaba con el ")"

Código
  1.                Dim stack As New Stack(Of Char)
  2.                'Dim input As String = ")((()))("
  3.                Dim input As String = "(Hello) ) ( (World)?"
  4.  
  5.                Dim opened As Integer = 0
  6.                Dim closed As Integer = 0
  7.  
  8.                For Each ch As Char In input
  9.  
  10.                    If ch = "(" Then
  11.                        stack.Push("#")
  12.  
  13.                    ElseIf ch = ")" Then
  14.  
  15.                        If stack.Count = 0 Then
  16.                            opened += 1
  17.                        Else
  18.                            closed += 1
  19.                            stack.Pop()
  20.  
  21.                        End If
  22.  
  23.                    End If
  24.                Next ch
  25.  
  26.                opened = opened + stack.Count
  27.  
  28.                Console.WriteLine("Opened:{0} Closed:{1}", opened, closed)
  29.                MsgBox(String.Format("Opened:{0} Closed:{1}", opened, closed))


EDITO:

Lo he modificado un poco para usarlo a mis necesidades:

Código
  1.  Private ReadOnly Property TotalAgrupations As Dictionary(Of String, Integer)
  2.        Get
  3.            Return Count_Agrupations_In_String(TextBox_RegEx.Text)
  4.        End Get
  5.    End Property
  6.  
  7.    ' MsgBox(TotalAgrupations("Opened"))
  8.    ' MsgBox(TotalAgrupations("Closed"))
  9.  
  10.    Private Function Count_Agrupations_In_String(ByVal str As String) As Dictionary(Of String, Integer)
  11.  
  12.        Dim stack As New Stack(Of Char)
  13.  
  14.        Dim opened As Integer = 0
  15.        Dim closed As Integer = 0
  16.  
  17.        For Each ch As Char In str
  18.  
  19.            If ch = "(" Then
  20.                stack.Push("#")
  21.  
  22.            ElseIf ch = ")" Then
  23.  
  24.                If stack.Count = 0 Then
  25.                    opened += 1
  26.                Else
  27.                    closed += 1
  28.                    stack.Pop()
  29.  
  30.                End If
  31.  
  32.            End If
  33.  
  34.        Next ch
  35.  
  36.        Return New Dictionary(Of String, Integer) From { _
  37.            {"Opened", opened + stack.Count}, _
  38.            {"Closed", closed} _
  39.        }
  40.  
  41.    End Function





Los siguientes códigos he testeado su velocidad de ejecución usando métodos distintos con LINQ, RegEx y For, ha ganado For y con mucha diferencia de ms así que aquí tienen:


Reemplaza (o elimina) todos los caracteres que indiquemos en un string

Código
  1. #Region " Replace All Characters "
  2.  
  3.    ' [ Replace All Characters Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' MsgBox(Replace_All_Characters("Hello World!", {"e"c, "o"c}, "+")) ' Result: H+ll+ W+rld!
  10.  
  11.    Public Function Replace_All_Characters(ByVal str As String, _
  12.                                           ByVal chars As Char(), _
  13.                                           replaceWith As Char) As String
  14.  
  15.        For Each c As Char In chars
  16.            str = str.Replace(c, replaceWith)
  17.        Next
  18.  
  19.        Return str
  20.  
  21.    End Function
  22.  
  23. #End Region





Reemplazar todos los caracteres en un string, menos los caracteres que indiquemos.

Código
  1. #Region " Replace All Characters Except "
  2.  
  3.    ' [ Replace All Characters Except Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' MsgBox(Replace_All_Characters("Hello World!", "eo", ".")) ' Result: ".e..o..o...."
  10.  
  11.    Public Function Replace_All_Characters_Except(ByVal str As String, _
  12.                                                  ByVal chars As String, _
  13.                                                  replaceWith As Char) As String
  14.  
  15.        Dim temp_str As String = String.Empty
  16.  
  17.        For Each c As Char In str
  18.            If Not chars.Contains(c) Then
  19.                temp_str &= c
  20.            Else
  21.                temp_str &= replaceWith
  22.            End If
  23.        Next c
  24.  
  25.        Return temp_str
  26.  
  27.    End Function
  28.  
  29. #End Region





Eliminar todos los caracteres en un string, menos los caracteres que indiquemos.

El snippet de arriba se puede usar para esta misma función, pero traducido a milisegundos este código es más rápido.

Código
  1. #Region " Remove All Characters Except "
  2.  
  3.    ' [ Remove All Characters Except Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' MsgBox(Remove_All_Characters_Except("Hello World!", "eo".ToCharArray)) ' Result: "eoo"
  10.  
  11.    Public Function Remove_All_Characters_Except(ByVal str As String, _
  12.                                              ByVal chars As Char()) As String
  13.  
  14.        Dim temp_str As String = String.Empty
  15.  
  16.        For Each c As Char In str
  17.            For Each cc As Char In chars
  18.                If c = cc Then temp_str &= cc
  19.            Next cc
  20.        Next c
  21.  
  22.        Return temp_str
  23.  
  24.    End Function
  25.  
  26. #End Region

« Última modificación: 9 Septiembre 2013, 20:26 pm por EleKtro H@cker » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #289 en: 11 Septiembre 2013, 00:57 am »

Hice un código improvisado en Batch para crear un listado con colores RGB aleatorios (todo lo aleatorio que cabe usando Batch) para luego copiarlo diréctamente en la IDE.

Esto lo hice por la misma razón que suelo hacer con todo este tipo de snippets, para ahorrarme el trabajo manual repetitivo xD, aunque habría quedado más bonito en otro lenguaje.

No necesito generar esta lista en tiempo de ejecución así que perdonarme por no postear una versiónd el code traducida a VB.

Código
  1. @Echo OFF
  2.  
  3. REM By Elektro H@cker
  4.  
  5. TITLE Random Color.FromArgb() Generator for .NET
  6.  
  7. :::::::::::::::::::::
  8. Set /A Max_Colors=255
  9. :::::::::::::::::::::
  10.  
  11. set /A random1 & set /A random2 & set /A random3
  12. set /a index=0
  13.  
  14. Echo+>"Color.FromArgb.txt"
  15.  
  16. :loop1
  17. Call set /a "random1=%%RANDOM:~0,3%%"
  18. if not %random1% GTR 255 (Goto :loop2)
  19. Call set /a "random1=%%RANDOM:~1,2%%" 2>NUL || Call set /a "random1=%%RANDOM:~0,1%%"
  20.  
  21. :loop2
  22. Call set /a "random2=%%RANDOM:~0,3%%"
  23. if not %random2% GTR 255 (Goto :loop3)
  24. Call set /a "random2=%%RANDOM:~1,2%%" 2>NUL || Call set /a "random2=%%RANDOM:~0,1%%"
  25.  
  26. :loop3
  27. Call set /a "random3=%%RANDOM:~0,3%%"
  28. if not %random3% GTR 255 (Goto :Append)
  29. Call set /a "random3=%%RANDOM:~1,2%%" 2>NUL || Call set /a "random3=%%RANDOM:~0,1%%"
  30.  
  31. :Append
  32. Echo Color.FromArgb(%RANDOM1%, %RANDOM2%, %RANDOM3%)
  33. Echo {%index%, Color.FromArgb(%RANDOM1%, %RANDOM2%, %RANDOM3%)}, _>>"Color.FromArgb.txt"
  34.  
  35. Set /A Index+=1
  36. if %index% GTR %Max_Colors% (Pause&Exit)
  37. Goto:loop1

El output es algo así:

CMD:
Código:
Color.FromArgb(248, 51, 134)
Color.FromArgb(119, 23, 233)
Color.FromArgb(120, 81, 71)
Color.FromArgb(54, 209, 179)
Color.FromArgb(115, 219, 46)
Color.FromArgb(146, 229, 130)
Color.FromArgb(254, 87, 184)
Color.FromArgb(117, 50, 23)
Color.FromArgb(47, 203, 46)
Color.FromArgb(75, 226, 13)
Color.FromArgb(192, 40, 49)
Color.FromArgb(49, 214, 63)
Color.FromArgb(149, 105, 65)
Color.FromArgb(130, 133, 166)
Color.FromArgb(45, 185, 214)
Color.FromArgb(41, 196, 20)
Color.FromArgb(230, 23, 193)
Color.FromArgb(146, 21, 5)
Color.FromArgb(40, 92, 52)
Color.FromArgb(151, 93, 22)
Color.FromArgb(124, 236, 78)
Color.FromArgb(55, 226, 50)
Color.FromArgb(30, 139, 76)
Color.FromArgb(67, 50, 69)

Archivo de texto:
Código:
{0, Color.FromArgb(44, 222, 32)}, _
{1, Color.FromArgb(23, 17, 75)}, _
{2, Color.FromArgb(6, 97, 1)}, _
{3, Color.FromArgb(39, 138, 57)}, _
{4, Color.FromArgb(67, 158, 13)}, _
{5, Color.FromArgb(76, 31, 26)}, _
{6, Color.FromArgb(142, 104, 118)}, _
{7, Color.FromArgb(29, 217, 91)}, _
{8, Color.FromArgb(229, 176, 216)}, _
{9, Color.FromArgb(133, 73, 45)}, _
{10, Color.FromArgb(151, 47, 21)}, _
{11, Color.FromArgb(32, 31, 205)}, _
{12, Color.FromArgb(126, 173, 80)}, _
{13, Color.FromArgb(240, 179, 146)}, _
{14, Color.FromArgb(11, 197, 205)}, _
{15, Color.FromArgb(37, 206, 129)}, _
{16, Color.FromArgb(253, 214, 137)}, _
{17, Color.FromArgb(89, 119, 31)}, _
{18, Color.FromArgb(2, 103, 255)}, _
{19, Color.FromArgb(91, 166, 196)}, _
{20, Color.FromArgb(79, 90, 82)}, _
{21, Color.FromArgb(154, 249, 78)}, _
{22, Color.FromArgb(93, 125, 5)}, _
{23, Color.FromArgb(192, 119, 17)}, _
{24, Color.FromArgb(60, 250, 236)}, _
{25, Color.FromArgb(196, 97, 99)}, _
« Última modificación: 11 Septiembre 2013, 01:00 am por EleKtro H@cker » En línea

Páginas: 1 ... 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 [29] 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 ... 58 Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines