Menú

Mostrar Mensajes

Esta sección te permite ver todos los mensajes escritos por este usuario. Ten en cuenta que sólo puedes ver los mensajes escritos en zonas a las que tienes acceso en este momento.

Mostrar Mensajes Menú

Mensajes - carlitos.dll

#1
Código (java) [Seleccionar]


/*-
* Copyright (c) 2008 Carlos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
*    notice, this list of conditions and the following disclaimer in the
*    documentation and/or other materials provided with the distribution.
* 3. Neither the name of copyright holders nor the names of its
*    contributors may be used to endorse or promote products derived
*    from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL COPYRIGHT HOLDERS OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/

import java.util.*;

/**
* ReglasDeNegocio.java
*
* Esta clase implementa una serie de métodos estáticos,
* para implementar reglas de negocio
* tales como sanitizar palabras, validar rut.
*
* @author Carlos
* @version 14-9-2008
*/
final class ReglasDeNegocio
{
  /**
   * Método sanitizador de Strings.
   * @param Recibe:
   * Un String con el String a sanitizar
   * Un int con el tipo de sanitización
   * Un String con el nombreDelAtributo que llama al método, en caso de que se lanzen excepciones
   * 1 corresponde a limpieza para Strings de nombres.
   * 2 corresponde a limpieza para Strings de direcciones.
   * Ejemplo: si tengo una variable String nombre:
   * Ejemplo: nombre = ReglasDeNegocio.filtro("Juan123456 Pérez###", 1, "nombre"),
   * nombre tendrá el contenido: "Juan Pérez",
   * si nombre es nulo se lanza una excepción diciendo: "nombre no puede ser nulo", nombre es el identificador de la variable.
   * Ejemplo: filtro("Santa Rosa%%%%%////123", 2, "direccion") devuelve "Santa Rosa 123"
   * autor: Carlos
   */
  public static String filtro(
                               String argumento,
                               int opcion,
                               String nombreVariable) throws Exception
  {
      try
      {
          nombreVariable = nombreVariable.trim();
          if (nombreVariable.length() < 1)
          {
              throw new Exception(
              "el nombreVariable debe contener el nombre de la variable.");
          }
      }
      catch (NullPointerException npe)
      {
          throw new Exception("Error en los parámetros.");
      }

      String patron;
      switch (opcion)
      {
          case 1 : {
                       patron = new String("[^A-Za-záéíóúñÁÉÍÓÚÑüÜ -]");
                       break;
                   }
          case 2 : {
                       patron = new String("[^0-9A-Za-záéíóúñÁÉÍÓÚÑüÜ#° -]");
                       break;
                   }
          default: {
                       throw new Exception(String.valueOf(opcion));
                   }
      }
      try
      {
          argumento = argumento.trim();
          if (argumento.length() < 1)
          {
              throw new Exception(nombreVariable + " está vacío.");
          }
      }
      catch (NullPointerException npe)
      {
          throw new Exception(nombreVariable + " no puede ser nulo");
      }

      Scanner palabra = new Scanner(argumento).useDelimiter(patron);
      String reconstruccion = new String();
      while(palabra.hasNext())
      {
          reconstruccion = reconstruccion + palabra.next();
      }
      palabra.close();

      argumento = new String();
      StringTokenizer tokens = new StringTokenizer(reconstruccion);
      while(tokens.hasMoreTokens())
      {
          argumento = argumento + " " + tokens.nextToken();
      }
      argumento = argumento.trim();
      return argumento;
  }

  /**
   * Método sanitizador y validador de rut.
   * @param Recibe una cadena correspondiente al rut.
   * @return Devuelve un rut sanitizado,
   * en caso de que el digito verificador sea correcto, sino lanza una excepción.
   * Ejemplo "123456789-2" lo devuelve correcto.
   * "123456789-26999" lo devuelve como "123456789-2".
   * "123456789-3" lanza excepción pues el digito verificador es 2.
   * "00000123456789-2" lo devuelve como "123456789-2".
   * autor: Carlos
   * version: 1.1
   */
   public static String validadorRut(String rut) throws Exception
   {
      if (rut == null)
      {
          throw new Exception("rut no puede ser nulo");
      }
     
      rut = rut.replace('—','-').replace('–','-');

      String datosRut = new String();
      Scanner token = new Scanner(rut).useDelimiter("[[\\D]&&[^Kk-]]");
      while (token.hasNext())
      {
          datosRut = datosRut + token.next();
      }
      StringTokenizer tokens = new StringTokenizer(datosRut, "-");
      if (tokens.countTokens() != 2)
      {
          throw new Exception("error de formato en el rut");
      }
     
      String datos = tokens.nextToken();
     
      boolean comienzaConCero = datos.startsWith("0");
      if (comienzaConCero)
      {
          int indice;  
          for (indice = 0; indice < datos.length() && comienzaConCero; indice++)
          {
              comienzaConCero = datos.substring(indice, indice + 1).equals("0");
          }
          datos = datos.substring(indice - 1);
      }
     
      String digitoVerificador = new String();
      try
      {
          int formato = Integer.parseInt(datos);
          int contador = 2;
          int calculo = 0;
          for (int i = datos.length() - 1; i >= 0; i--)
          {
              contador = contador > 7 ? 2 : contador;
              calculo += Integer.parseInt(datos.substring(i, i + 1)) * contador++;
          }
          calculo = 11 - (calculo % 11);
          String digito = new String(calculo == 10 ? "K" : calculo == 11 ? "0" : String.valueOf(calculo));
          String digitoRecibido = tokens.nextToken().substring(0, 1);
          if (digito.equalsIgnoreCase(digitoRecibido))
          {
              return rut = datos + "-" + digito;
          }
          else
          {
              throw new Exception("El digito verificador del rut no es correcto.");
          }
      }
      catch (NumberFormatException nfe)
      {
          throw new Exception("Error de formato en el rut.");
      }
   }

}

#2

@echo off
::Escrito por Carlos

:menu
echo Opciones:
echo 0. Abrir google
echo 1. Abrir yahoo
echo 2. Salir
set op=
set/p op=Ingrese su opcion:
call :^%op:~0,1%op &cls
goto:menu

:^0op
start http://www.google.com
goto:eof

:^1op
start http://www.yahoo.com
goto:eof

:^2op
exit
#3
Cita de: Eazy en  7 Octubre 2008, 01:41 AM
Por uqe va todo a SMP?

debe ser el nombre de un archivo, aunque si existe en en el lugar en donde se ejecuta el batch una carpeta  con dicho nombre, el batch arrojaria un acceso denegado.

Ejemplo, si ejecuto el batch desde el escritorio y tengo una carpeta llamada smp.


aquí hay otra forma de bajarse un archivo por ftp.: http://foro.elhacker.net/scripting/enviar_archivo_x_ftp-t226662.0.html

#4
Scripting / Re: bat que produce sonidos
4 Octubre 2008, 03:49 AM
en consola colocas:
echo [y presionas alt 7 o control + g]>sonido.txt
luego:
notepad sonido.txt
luego verás un cuadrado, y ese cuadrado lo copias, y pegas, en un archivo bat
puedes colocar
echo [y el cuadrado que antes copaiste] o simplemente deja el cuadrado, ese es el carácter del código ascii 7 que corresponde a un beep, y se ve como un cudarado porque es un carácter no imprimible.
#5

@echo off
pushd "C:\MiCarpeta\"

for /r %%a in (*) do (
if /i "%%~xa"==".txt" (call:blank "%%a") else (
if /i "%%~xa"==".air" (call:blank "%%a") else (
if /i "%%~xa"==".cns" (call:blank "%%a") else (
if /i "%%~xa"==".cmd" (call:blank "%%a") else (
if /i "%%~xa"==".def" (call:blank "%%a") ))))
)
popd
goto:eof

:blank
echo.>>%1
goto:eof


#6
Scripting / Re: Ayuda para automatizar.
2 Octubre 2008, 03:16 AM
con autoit también se puede hacer.
#7
Scripting / Re: Problema con set /A 09 y 08
30 Septiembre 2008, 07:38 AM
Que buena idea sirdarckat, no se me había ocurrido, y tiene mucha lógica.
Implementé tu idea al código.


@echo off
call:date
echo %day%
echo %month%
echo %year%
pause
goto :eof

::::::::::::::::::::Funcion::::::::::::::::::::
:date
if [%1]==[] (for /f "tokens=1-3 delims=-" %%a in ("%date%") do (call :date %%a %%b %%c))
if not [%1]==[] (
set /a day=1%1-100
set /a month=1%2-100
set /a year=%3
)
goto:eof
::::::::::::::::::::Funcion::::::::::::::::::::


#8
Scripting / Re: Problema con set /A 09 y 08
26 Septiembre 2008, 19:34 PM
no puedes ingresar a un set /a 08 o 09, porque anteponiendo 0 dices que es octal, y el conjunto de números octales va de 0 a 7.
La otra vez hice una función, que te retornaba la fecha, en tres variables, recursivamente. (La rescate del caché de google :D)


@echo off
rem Funcion recursiva que devuelve la fecha en formato decimal.
rem author CarlitoS.dll
rem %day% = dia
rem %month% = mes
rem %year% = agno

:date
if [%1]==[] (for /f "tokens=1-3 delims=-" %%a in ("%date%") do (call :date %%a %%b %%c))
if not [%1]==[] (
set day=%1
set month=%2
set year=%3
goto :eof
)
set day=%day:*0=%
set month=%month:*0=%
echo %day%
echo %month%
echo %year%
goto :eof
#9



@echo off
(
echo ^<?xml version="1.0" encoding="ISO-8859-1"?^>
echo ^<note^>
echo ^<to^>Tove^</to^>
echo ^<from^>Jani^</from^>
echo ^<heading^>Reminder^</heading^>
echo ^<body^>Don't forget me this weekend!^</body^>
echo ^</note^>
)>archivo.txt



recuerda el carácter ^
#10
Java / Re: ayuda con clase Scanner
13 Septiembre 2008, 20:40 PM
Resulta que al final eran tres tipos de guiones.
Lo dejo sin las etiquetas geshi para que se vea la diferencia.

Este es el guión normal: -
Este es uno ligeramente más grande: –
Este es uno más extenso: —

Aquí dejo la solución que se me ocurrió, le puede servir a alguien.

        try
        {
            argumento = argumento .trim();
            argumento = argumento .replace('—','-');
            argumento = argumento .replace('–','-');
        }
        catch (NullPointerException npe)
        {
            throw new ValoresAceptadosException("argumento no puede ser nulo.");
        }
       
        Scanner entrada = new Scanner(argumento ).useDelimiter("\\s*-\\s*");