viernes, 30 de diciembre de 2022

Crear Usuario ORACLE DATABASE

Crear Usuario ORACLE DATABASE
================================

Ejecutar cmd SQL Plus

Introduzca usuario: CONN /AS SYSDBA
Introduzca contraseña:

$> ALTER SESSION SET "_ORACLE_SCRIPT"=TRUE;
$> CREATE USER usuario IDENTIFIED BY secret;
$> GRANT DBA TO usuario;

-------------------------------------------------------------------------------
--LISTAR TODOS LOS USUARIOS/ESQUEMAS  DENTRO DE LA BASE DE DATOS EN LA CUAL ESTOY CONECTADO
SELECT * FROM DBA_USERS

--CAMBIAR LA FECHA DE EXPIRACIÓN DE LA CONTRASEÑA
ALTER PROFILE DEFAULT LIMIT PASSWORD_LIFE_TIME UNLIMITED

--CAMBIAR LA CONTRASEÑA DE UN USUARIO/ESQUEMA
ALTER USER SYSTEM IDENTIFIED BY 1234


Crear  Tabla en ORACLE DATABASE
==================================

CREATE TABLE post(
    id NUMBER(10) PRIMARY KEY NOT NULL,
    title VARCHAR2(50) NOT NULL UNIQUE,
    description VARCHAR2(150) NOT NULL,
    content VARCHAR2(255) NOT NULL,
    status CHAR(1) DEFAULT '1' NOT NULL
);
CREATE SEQUENCE seq_post START WITH 1;

INSERT INTO post(id,title,description,content) VALUES(seq_post.nextval,'My New first Post','First Post description','This is my new first post');

INSERT INTO post(id,title,description,content) VALUES(seq_post.nextval,'My Second Post','Second Post description','This is my new second post');

UPDATE post 
set description='FOURTH POST DESCRIPTION' 
WHERE id=2;


viernes, 23 de diciembre de 2022

Programacion Funcional JAVA

 Programación Funcional JAVA

1.  List<Integer> numeros = List.of(11, 21, 38, 43, 54, 66, 7, 8, 19, 10);

     a) Obtener la cantidad de números pares.
     b) Obtener todos los números pares.
     c) Ordenar la lista de números en orden ascendente.
     d) Ordenar la lista de números en orden descendente.
     e) Ordenar solo los números pares en orden descendente.

Solución:

a)
     long result = numeros.stream()                                 
                                      .filter(n -> n % 2 == 0)
                                      .count();
     System.out.println(result);

b)
     List<Integer> listNumeros =  numeros.stream()                                 
                                                         .filter(n -> n%2 == 0)
                                                         .collect(Collectors.toList());
     listNumeros.forEach(System.out::println);   
                   
c)
     List<Integer> listOrderAsc =  numeros.stream() 
                                                         .sorted()                                   
                                                         .collect(Collectors.toList());
     listOrderAsc.forEach(System.out::println);

d)
     List<Integer> listOrderDesc =  numeros.stream() 
                                                         .sorted(Collections.reverseOrder())                                   
                                                         .collect(Collectors.toList());
     listOrderDesc.forEach(System.out::println);    

e)
     List<Integer> listOrderParDesc =  numeros.stream() 
                                                         .filter(n -> n % 2 == 0)
                                                         .sorted(Collections.reverseOrder())                                   
                                                         .collect(Collectors.toList());
     listOrderParDesc.forEach(System.out::println);  

2. Se tiene la siguiente lista de objetos. Crear la clase User con sus atributos name, edad y sus metodos get y set.

  List<User> users = new ArrayList<>();
    users.add(new User("Rafael", 25));
    users.add(new User("Daniel", 20));
    users.add(new User("Tania", 15));
    users.add(new User("Luisa", 24));
    users.add(new User("Miguel", 16));
    users.add(new User("Raul", 17));

a) Obtener la cantidad de usuarios con una edad mayor o igual a 18 y que su nombre empiecen con la letra "R".
b) Obtener solo el nombre de todas las personas mayores a 18
c) Ordenar la lista de objetos por el nombre en orden ascedente y mostrar solo el nombre.
d) Ordenar la lista de objetos por el nombre en orden descendente.
e) ghg
f) ghg
g) hg
h) gh

Solución:

a)
long cantidad = users.stream()
            .filter(user -> user.getAge() >= 18 && user.getName().toUpperCase().startsWith("R"))
            .count();
    System.out.println(cantidad);

b)
List<String> listMayor = users.stream()
            .filter(user -> user.getAge() >= 18)
            .map(User::getName)       // (u->u.getName())   //u es un objeto de la Clase User
            .collect(Collectors.toList());
    listMayor.forEach(System.out::println);

c)
List<String> byNameAsc = users.stream()
            .sorted((User a, User b) -> a.getName().compareTo(b.getName()))
            .map(User::getName) // (u->u.getName())   //u es un objeto de la Clase User
            .collect(Collectors.toList());

   byNameAsc.forEach(System.out::println);

d)
List<User> listUserOrderDesc = users.stream()
            .sorted((User a, User b) -> b.getName().compareTo(a.getName()))
            .collect(Collectors.toList());

    listUserOrderDesc.forEach(System.out::println);


martes, 6 de diciembre de 2022

Procedimientos Almacenados SQL SERVER

-- Procedimiento Listar
CREATE PROCEDURE sp_getAllCategories
AS
BEGIN
    SELECT id,descripcion,estado
    FROM CATEGORIAS
    ORDER BY id DESC
END
GO

EXEC sp_getAllCategories;

Uso del Case
CREATE PROCEDURE sp_getAllClients
AS
BEGIN
SELECT id,
name,
lastName,
dni,
CASE gender
WHEN 1 THEN 'Masculino'
WHEN 0 THEN 'Femenino'
END AS gender,
phone,
address,
email,
CASE status
WHEN 1 THEN 'Activo'
WHEN 0 THEN 'Inactivo'
END AS status
FROM CLIENT
ORDER BY id DESC
END


-- Procedimiento Buscar
CREATE PROCEDURE sp_searchCategory
@text varchar(50)
AS
BEGIN

    SELECT id,descripcion,estado
    FROM CATEGORIAS
    WHERE nombre LIKE '%' + @text + 
'%' OR descripcion LIKE '%' + @text + '%'
    ORDER BY nombre ASC
END
GO

-- Procedimiento Buscar por nombre
CREATE PROCEDURE sp_findCategoryByName
@nombre varchar(30)
AS
BEGIN

    SELECT id,descripcion,estado
    FROM CATEGORIAS
    WHERE estado=1 and UPPER(TRIM(descripcion)) LIKE '%' + UPPER(TRIM(@nombre)) +'%'
END
GO

exec uspFiltrarCategoriaPorNombre 'A'

-- Procedimiento Insertar
CREATE PROCEDURE sp_insertCategory
@nombre varchar(50),
@descripcion varchar(150)
AS
BEGIN
INSERT INTO CATEGORIAS(nombre,descripcion)
        VALUES(@nombre,@descripcion)
END
GO

EXEC sp_insertCategory @nombre='Este es otro nombre',
                                             @descripcion='Este es otra descripcion'

-- Procedimiento Actualizar
CREATE PROCEDURE sp_updateCategory
@id INT,
@descripcion varchar(30)
AS
BEGIN
UPDATE CATEGORIAS 
SET descripcion=@descripcion
WHERE id=@id
END
GO

EXEC sp_updateCategory @id=2,
                                               @descripcion='descripcion actualizada';

-- Procedimiento Eliminar
CREATE PROCEDURE sp_deleteCategory
@id int
AS 
BEGIN
     DELETE CATEGORIAS
     WHERE id=@id
END
GO

-- Procedimiento Desactivar
CREATE PROCEDURE sp_disableCategory
@id int
AS 
BEGIN
     UPDATE CATEGORIA SET status=0
     WHERE id=@id
END
GO

-- Procedimiento Activar
CREATE PROCEDURE sp_enableCategory
@id int
AS 
BEGIN
     UPDATE CATEGORIA SET status=1
     WHERE id=@id
END
GO

lunes, 17 de octubre de 2022

ARRAY CON PHP


Ejercicios

1. Del siguiente arreglo:
$numbers = [1, 5, 23, 4, 12, 45, 78, 6, 8.2, 26];

Filtrar los números que son mayores a 20.

Solución:
$results = array_filter($numbers, function ($number) {
  return $number > 20;
});

foreach ($results as $result) {
  echo $result;
}

2. Del siguiente arreglo:

$students = [
  [
    'name' => 'Carlos',
    'score' => 12
  ],
  [
    'name' => 'Daniel',
    'score' => 10
  ],
  [
    'name' => 'Sofia',
    'score' => 18,
  ],
  [
    'name' => 'Maria',
    'score' => 11,
  ],
  [
    'name' => 'Alex',
    'score' => 9,
  ]
];

Obtener la lista de estudiantes aprobados y desaprobados.

Solución:

$approved = array_filter($students, function ($student) {
  return $student['score'] >= 11;
});

foreach ($approved as $student) {
  echo $student['name'] . ' ' . $student['score'] . '<br>';
}

$disapproved = array_filter($students, function ($student) {
  return $student['score'] <= 10;
});

foreach ($disapproved as $student) {
  echo $student['name'] . ' ' . $student['score'] . '<br>';
}



lunes, 10 de octubre de 2022

CONFIGURAR LAS VARIABLES DE ENTORNO DE PHP

CONFIGURAR LAS VARIABLES DE ENTORNO PHP

CONFIGURAR LA VARIABLE PHP_HOME

Buscamos Editar las variables de entorno del sistema -> Variables de entorno -> Nueva (Variables del sistema)

Crear Nueva Variable del sistema
Escribiremos en las cajas de texto lo siguiente:
Nombre de variable : PHP7
Valor de variable : 
C:\laragon\bin\php\php-7.4.32-Win32-vc15-x64

Crear Nueva Variable del sistema
Escribiremos en las cajas de texto lo siguiente:
Nombre de variable : PHP8
Valor de variable : 
C:\laragon\bin\php\
php-8.1.10-Win32-vs16-x64



Ahora apuntaremos a una sola versión de PHP
Escribiremos en las cajas de texto lo siguiente:
Nombre de variable : PHP_HOME
Valor de variable : %PHP7%

CONFIGURAR LA VARIABLE PATH
Seleccionamos Path (Variables del sistema) -> Editar -> Nuevo
Escribiremos lo siguiente: 
%PHP_HOME%
Con esto le indicamos que utilizara la versión a la que este apuntando el PHP_HOME.







domingo, 9 de octubre de 2022

RESTAURAR VISUAL STUDIO CODE A VALORES DE FÁBRICA


RESTAURAR VISUAL STUDIO CODE A VALORES DE FÁBRICA

- Desinstalamos totalmente Visual Studio Code

- Abrir la ventana de ejecutar (Tecla [Win] + [R]) Y escribimos:
   %userprofile%\AppData\Roaming
  Buscamos la carpeta Code y la eliminamos.

- Para eliminar las extensiones ir a la ubicacion %userprofile%
  Buscamos la capeta .vscode y la eliminamos.

- Finalmente volvemos a reinstalar VS Code

--------------------------------------------------------------------------------------------------------------
Ruta del Fichero global de atajos de teclado keybindings.json y settings.json

%userprofile%\AppData\Roaming\Code\User

jueves, 6 de octubre de 2022

Ejercicios de Polimorfismo JAVA


Ejercicios de Polimorfismo JAVA
------------------------------------------------

1. Hacer un programa para calcular el área de polígonos (Triángulos y Rectángulos) el programa debe ser capaz de almacenar en un arreglo N triángulos y rectángulos, y al final mostrar el área y los datos de cada uno.

Para ello se tendrá lo siguiente:

Solución:

public abstract class Polygon {
private int numberOfSides;
public abstract double area();

public Polygon(int numberOfSides) {
this.numberOfSides = numberOfSides;
}

public int getNumberOfSides() {
return numberOfSides;
}

public void setNumberOfSides(int numberOfSides) {
this.numberOfSides = numberOfSides;
}

@Override
public String toString() {
return "Polygon{" +
"numberOfSides=" + numberOfSides +
"area=" + area() +
'}';
}
}

public class Rectangle extends Polygon {
  private double side1;
  private double side2;

  public Rectangle(int numberOfSides, double side1, double side2) {
    super(numberOfSides);
    this.side1 = side1;
    this.side2 = side2;
  }

  public double getSide1() {
    return side1;
  }

  public void setSide1(double side1) {
    this.side1 = side1;
  }

  public double getSide2() {
    return side2;
  }

  public void setSide2(double side2) {
    this.side2 = side2;
  }

  @Override
  public double area() {
    return side1 * side2;
  }
}

public class Triangle extends Polygon {
  private double side1;
  private double side2;
  private double side3;

  public Triangle(int numberOfSides, double side1, double side2, double side3) {
    super(numberOfSides);
    this.side1 = side1;
    this.side2 = side2;
    this.side3 = side3;
  }

  public double getSide1() {
    return side1;
  }

  public void setSide1(double side1) {
    this.side1 = side1;
  }

  public double getSide2() {
    return side2;
  }

  public void setSide2(double side2) {
    this.side2 = side2;
  }

  public double getSide3() {
    return side3;
  }

  public void setSide3(double side3) {
    this.side3 = side3;
  }

  @Override
  public double area() {
    double p = side1 + side2 + side3;
    return Math.sqrt(p * (p - side1) * (p - side2) * (p - side3));
  }
}

public class Main {
  static Scanner sc = new Scanner(System.in);
  static List<Polygon> polygons = new ArrayList<>();

  public static void main(String[] args) {
    fillPolygon();
    showData();
  }

  public static void fillPolygon() {
    int opcion = 0;
    do {
      System.out.println("Digite que poligono desea:");
      System.out.println("1. Triangulo");
      System.out.println("2. Rectangulo");
      System.out.println("3. Salir");
      System.out.print("Opcion: ");
      opcion = sc.nextInt();

      switch (opcion) {
        case 1:
          fillTriangle();
          break;
        case 2:
          fillRectangle();
          break;
        case 3:
          break;
      }
    } while (opcion != 3);
  }

  public static void fillTriangle() {
    double side1, side2, side3;
    System.out.println("\nDigite el lado1 del triangulo: ");
    side1 = sc.nextDouble();
    System.out.println("Digite el lado2 del triangulo: ");
    side2 = sc.nextDouble();
    System.out.print("Digite el lado3 del triangulo: ");
    side3 = sc.nextDouble();

    Polygon t = new Triangle(3, side1, side2, side3);
    polygons.add(t);
  }

  public static void fillRectangle() {
    double side1, side2;
    System.out.print("\nDigite el lado1 del Rectangle: ");
    side1 = sc.nextDouble();
    System.out.print("Digite el lado2 del Rectangle: ");
    side2 = sc.nextDouble();

    Polygon r = new Rectangle(2, side1, side2);
    polygons.add(r);
  }

  public static void showData() {
    for (Polygon p : polygons) {
      System.out.println(p);
    }
  }
}

2. Diseñe una clase abstracta de nombre Empleado que tenga atributos protegidos para el nombre, apellidos, dni, métodos get-set, métodos abstractos para ingresos(), bonificaciones(), descuentos().

Un método no abstracto que retorne el sueldoNeto() y otro método no abstracto que retorne la información correspondiente al nombre, apellidos, dni, ingresos, bonificaciones, descuentos, sueldo neto de cualquier empleado.
Aplique polimorfismo y diseñe una clase hija de nombre EmpleadoVendedor que tenga atributos para monto vendido y porcentaje de comisión, constructor, métodos get-set, desarrollo de métodos abstractos.
Luego, diseñe una clase hija de nombre EmpleadoPermanente que tenga atributos para sueldo basico y afiliación (afp ó snp), constructor, métodos get-set, desarrollo de métodos abstractos.
Diseñe una clase administradora de nombre ColeccionEmpleados que permita la administración de objetos de tipo EmpleadoVendedor y/o EmpleadoPermanente a la vez, utilizando un objeto de la clase ArrayList.



Solución:

public abstract class Employee {
  private String name;
  private String lastName;
  private String dni;

  public Employee(String name, String lastName, String dni) {
    this.name = name;
    this.lastName = lastName;
    this.dni = dni;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getLastName() {
    return lastName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }

  public String getDni() {
    return dni;
  }

  public void setDni(String dni) {
    this.dni = dni;
  }

  public abstract double income();

  public abstract double bonuses();

  public abstract double discounts();


  @Override
  public String toString() {
    return "Empleado{" +
            "name='" + name + '\'' +
            ", lastName='" + lastName + '\'' +
            ", dni='" + dni + '\'' +
            ", income='" + income() + '\'' +
            ", bonuses='" + bonuses() + '\'' +
            ", discounts='" + discounts() + '\'' +
            '}';
  }
}

public class SellerEmployee extends Employee {
  private double amountSold;
  private double commissionPercentage;

  public SellerEmployee(String name, String lastName, String dni, double amountSold, double commissionPercentage) {
    super(name, lastName, dni);
    this.amountSold = amountSold;
    this.commissionPercentage = commissionPercentage;
  }

  public double getAmountSold() {
    return amountSold;
  }

  public void setAmountSold(double amountSold) {
    this.amountSold = amountSold;
  }

  public double getCommissionPercentage() {
    return commissionPercentage;
  }

  public void setCommissionPercentage(double commissionPercentage) {
    this.commissionPercentage = commissionPercentage;
  }

  @Override
  public double income() {
    return amountSold * commissionPercentage;
  }

  @Override
  public double bonuses() {
    return amountSold * 0.15;
  }

  @Override
  public double discounts() {
    return income() * 0.22;
  }
}


public class PermanentEmployee extends Employee {
  private double basicSalary;
  private int membership;

  public PermanentEmployee(String name, String lastName, String dni, double basicSalary, int membership) {
    super(name, lastName, dni);
    this.basicSalary = basicSalary;
    this.membership = membership;
  }

  public double getBasicSalary() {
    return basicSalary;
  }

  public void setBasicSalary(double basicSalary) {
    this.basicSalary = basicSalary;
  }

  public int getMembership() {
    return membership;
  }

  public void setMembership(int membership) {
    this.membership = membership;
  }

  @Override
  public double income() {
    return basicSalary;
  }

  @Override
  public double bonuses() {
    if (membership == 1)
      return basicSalary * 0.13;
    else
      return basicSalary * 0.20;
  }

  @Override
  public double discounts() {
    return bonuses() * 0.10;
  }
}

public class EmployeesCollection {

  List<Employee> employees;

  public EmployeesCollection() {
    employees = new ArrayList<>();
  }

  public int size() {
    return employees.size();
  }

  public void add(Employee e) {
    employees.add(e);
  }

  public void delete(Employee e) {
    employees.remove(e);
  }

  public Employee get(int i) {
    return employees.get(i);
  }
}

public static void main(String[] args) {
    Employee a = new SellerEmployee("Juan", "Perez", "78767574", 300, 5);
    Employee b = new SellerEmployee("Luis", "Garcia", "75747372", 500, 10);

    Employee c = new PermanentEmployee("Raul", "Romero", "54213356", 600, 150);
    EmployeesCollection ec = new EmployeesCollection();
    ec.add(a);
    ec.add(b);
    ec.add(c);
    listar(ec);
  }


public static void listar(EmployeesCollection x) {
    for (int i = 0; i < x.size(); i++) {
      Employee e = x.get(i);
      System.out.println(e);
      if (e instanceof SellerEmployee) {
        System.out.println(((SellerEmployee) e).getAmountSold());
        System.out.println(((SellerEmployee) e).getCommissionPercentage());
      } else {
        System.out.println(((PermanentEmployee) e).getBasicSalary());
        System.out.println(((PermanentEmployee) e).getMembership());
      }
    }
  }







domingo, 2 de octubre de 2022

Ejercicios POO en JAVA

Ejercicios POO en JAVA

1. 
Crear una clase Aeropuerto con los siguientes atributos: nombre(String), direccion(Direccion), Año Inauguración(int), Capacidad(int) y los métodos públicos get/set y el método toString. Considere un constructor explicito con parámetros.
Crear la clase Direccion con los siguientes atributos: Pais(String)
, Calle(String), Numero(int), Ciudad(String) y sus metodos get/set y el metodo toString();
Desarrolle Un método que devuelva el número de años que ha estado abierto el aeropuerto.

Solucion:

public class Aeropuerto {
  private String name;
  private Direccion direccion;
  private int inaugurationYear;
  private int capacity;

  public Aeropuerto(String name, Direccion direccion, int inaugurationYear, int capacity) {
    this.name = name;
    this.direccion = direccion;
    this.inaugurationYear = inaugurationYear;
    this.capacity = capacity;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public Direccion getDireccion() {
    return direccion;
  }

  public void setDireccion(Direccion direccion) {
    this.direccion = direccion;
  }

  public int getInaugurationYear() {
    return inaugurationYear;
  }

  public void setInaugurationYear(int inaugurationYear) {
    this.inaugurationYear = inaugurationYear;
  }

  public int getCapacity() {
    return capacity;
  }

  public void setCapacity(int capacity) {
    this.capacity = capacity;
  }

  @Override
  public String toString() {
    return "Aeropuerto{" +
            "name='" + name + '\'' +
            ", direccion=" + direccion +
            ", inaugurationYear=" + inaugurationYear +
            ", capacity=" + capacity +
            '}';
  }

  public int numberOfYearsOpen() {
    return LocalDate.now().getYear() - inaugurationYear;
  }
}


public class Direccion {
  private String pais;
  private String calle;
  private int numero;
  private String ciudad;

  public Direccion(String pais, String calle, int numero, String ciudad) {
    this.pais = pais;
    this.calle = calle;
    this.numero = numero;
    this.ciudad = ciudad;
  }

  @Override
  public String toString() {
    return "Direccion{" +
            "pais='" + pais + '\'' +
            ", calle='" + calle + '\'' +
            ", numero=" + numero +
            ", ciudad='" + ciudad + '\'' +
            '}';
  }
}

public class Main {
  public static void main(String[] args) {
    Direccion d = new Direccion("peru", "calle nueva", 2, "lima");
    Aeropuerto a = new Aeropuerto("Jorge Chavez", d, 1970, 3000);
    System.out.println(a.numberOfYearsOpen());
    System.out.println(a);
  }
}

2. Del ejercicio anterior Agregue la clase Avión con los siguientes atributos: modelo, numero de asientos, velocidad maxima con sus respectivos metodos get/set y toString.
En la clase Aeropuerto incluya como atributo un arreglo de objetos de tipo Avion y actualice sus metodos.
Registre 2 Aeropuertos con sus aviones y Muestre en pantalla los aviones que tienen cada aeropuerto.



Solucion:
public class Aeropuerto{
    private Aviones[] avion;
}

 public static void main(String[] args) {
    Direccion d = new Direccion("peru", "calle nueva", 2, "lima");

    Avion[] x = new Avion[]{
            new Avion("ABC", 300, 1000),
            new Avion("XYZ", 200, 2000)
    };

    Avion[] y = new Avion[]{
            new Avion("SPD", 400, 5000),
            new Avion("WAR", 100, 3000)
    };

    Aeropuerto a1 = new Aeropuerto("Jorge Chavez", d, 1970, 800, x);
    Aeropuerto a2 = new Aeropuerto("Alejandro Velasco", d, 1950, 400, y);
    System.out.println(a1);
    System.out.println(a2);
  }

3. HERENCIA

public class Person {
  private String name;
  private String lastname;
  private int age;

  public Person() {
  }

  public Person(String name, String lastname, int age) {
    this.name = name;
    this.lastname = lastname;
    this.age = age;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getLastname() {
    return lastname;
  }

  public void setLastname(String lastname) {
    this.lastname = lastname;
  }

  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age = age;
  }

  public String showData() {
    return name + "\n" + lastname + "\n" + age;
  }
}


public class Student extends Person {
  private int code;
  private double finalNote;

  public Student(String name, String lastname, int age, int code, double finalNote) {
    super(name, lastname, age);
    this.code = code;
    this.finalNote = finalNote;
  }

  public int getCode() {
    return code;
  }

  public void setCode(int code) {
    this.code = code;
  }

  public double getFinalNote() {
    return finalNote;
  }

  public void setFinalNote(double finalNote) {
    this.finalNote = finalNote;
  }

  @Override
  public String showData() {
    return getName() + "\n" + getLastname() + "\n" + getAge() + "\n" + code + "\n" + finalNote;
  }
}


Student s = new Student("Luis", "Perez", 20, 666, 18);
    System.out.println(s.showData());








viernes, 30 de septiembre de 2022

JPA


JPA (JAVA PERSISTENCE API)

Persistencia: La persistencia es el mecanismo que se usa para mantener la información almacenada.

JPA Es un ORM, tiene como objetivo lograr la persistencia de datos entre una aplicación desarrollada en Java y una base de datos 

JPA busca traducir el modelado de las clases de Java a un modelado relacional en la base de datos permitiendo al programador elegir que clases u objetos quiere persistir

jueves, 29 de septiembre de 2022

Ejercicios Java con CHAR Y STRING


Ejercicios Java con CHAR Y STRING

1. Realizar un programa que pida al usuario una frase y una letra a buscar en esa frase.
La funcion debe devolver la cantidad de veces que encontró la letra.

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    System.out.print("Ingresa una frase: ");
    String frase = sc.nextLine();
    System.out.print("Ingresa una letra a buscar: ");
    char letra = sc.next().charAt(0);

    int c = 0;
    for (int i = 0; i < frase.length(); i++) {
      if (frase.charAt(i) == letra) {
        c++;
      }
    }
    System.out.println("cantidad de veces de la letra " + letra + ": " + c);
  }

2. Realizar un programa que pida al usuario ingresar una cadena hasta que el usuario escriba una cadena vacia o un espacio en blanco. Muestre la concatenacion de todas las cadenas.

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    StringBuilder sb = new StringBuilder();
    String cadena = "";

    System.out.print("Ingrese una cadena: ");
    cadena = sc.nextLine();

    while (!cadena.equals("") && !cadena.equals(" ")) {
      sb.append(cadena);//concat+=cadena;
      System.out.print("Ingrese una cadena: ");
      cadena = sc.nextLine();
    }
    String result = sb.toString();
    System.out.println(result);
  }

3. Se tiene la siguiente cadena de texto: "Hola mundo desde JAVA"
Realizar un programa que Elimine los espacios en blanco de la cadena de texto y luego muestre el resultado final en pantalla.

public static void main(String[] args) {
    String cadena = "Hola mundo desde JAVA";
    StringBuilder sb = new StringBuilder(cadena);

    for (int i = 0; i < sb.length(); i++) {
      if (sb.charAt(i) == '\u0020' || sb.charAt(i) == '\n') {
        sb.deleteCharAt(i);
        i--;
      }
    }
    System.out.println(sb.toString());
  }

Otra Altenativa usando Expresiones Regulares
String cadena = "Hola mundo desde JAVA";
    cadena = cadena.replaceAll("\\s+", "");
    System.out.println(cadena);

4. Realizar un programa que pida al usuario ingresar un año por teclado e indicar si es bisiesto o no.

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.print("Ingrese el año a evaluar: ");
    int year = sc.nextInt();
    if ((year % 4 == 0) && (year % 100 != 0 || year % 400 == 0)) {
      System.out.println(year + " ES UN AÑO BISIESTO");
    } else {
      System.out.println(year + " NO ES UN AÑO BISIESTO");
    }
  }

5. Generar 10 números entre 1 y 10
//int numAleatorio =  (int) (Math.random() * (max - min + 1)) + min;

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int aleatorio = 0;
    int min = 1;
    int max = 10;
    for (int i = 0; i < 10; i++) {
      aleatorio = (int) (Math.random() * max + min);
      System.out.println(aleatorio);
    }
  }

6. Realizar un programa que pida ingresar una frase e indicar si es o no es palíndromo.

public static void main(String[] args) {
  Scanner sc = new Scanner(System.in);
  System.out.print("Ingrese una frase: ");
  String cadena = sc.nextLine();
  cadena = cadena.replaceAll("\\s+", "");
  StringBuilder sb = new StringBuilder();

  for (int i = cadena.length() - 1; i >= 0; i--) {
    sb.append(cadena.charAt(i));
  }

  if (cadena.equals(sb.toString())) {
    System.out.println("ES PALINDROMO");
  } else {
    System.out.println("NO ES PALINDROMO");
  }
}

miércoles, 28 de septiembre de 2022

Scanner en Java



Scanner en Java
===============

Esta clase la que nos permitirá ingresar datos por teclado.

Scanner es la mejor clase para recibir información a través del teclado y nos permite capturar datos primitivos tipo int, double, string y varios más, que han sido introducidos por el usuario.

next() → Lee un String hasta encontrar un delimitador, generalmente un espacio.
nextBoolean() → Lee valores booleanos.
nextByte() → Lee valores byte que ingresan por teclado.
nextDouble() → Lee valores decimales (double) introducidos por el usuario.
nextFloat() → Recibe los valores float, que ingresan.
nextShort() → Lee un dato de tipo short.
nextInt() → Para leer datos del tipo entero.
nextLong() → Para leer un dato del tipo long.
nextLine() → Lee un String hasta encontrar un salto de línea.
close() → Cierra la clase Scanner luego de utilizada


El buffer de entrada de datos de la clase Scanner
-----------------------------------------------------------------
Un buffer, recibe los datos del usuario. El buffer recibirá por un lado el dato enviado y por otro la pulsación del ENTER en un código Ascii.

Ejemplo:

public class Ejemplo {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.print("Ingresa tu edad: ");
    int edad = sc.nextInt();
    System.out.print("Ingresa tu nombre: ");
    String nombre = sc.nextLine();
    System.out.println("El nombre es " + nombre + " la edad es " + edad);
  }
}
Resultado:  Ingresa tu edad: 20
                    Ingresa tu nombre: 
                    El nombre es  la edad es 20

El buffer de la clase scanner almacena el dato ingresado y el salto de línea(string).
El nextInt extrae del buffer y toma el dato entero y lo asigna en la variable edad (int), en el buffer queda guardado el intro. el buffer tiene que estar vacío para poder recibir nuevos datos.
El nextLine extrae del buffer toma todo los caracteres hasta antes de llegar al intro y elimina el intro del buffer, por lo tanto solo se asigna una cadena vacía a la variable nombre(String).

Solución:
Se debe limpiar el buffer de entrada si se van a leer datos de tipo carácter a > continuación de la lectura de datos numéricos.
La forma más sencilla de limpiar el buffer de entrada en Java es ejecutar la instrucción:
sc.nextLine();

lunes, 26 de septiembre de 2022

CONFIGURACION VISUAL STUDIO CODE



{
"editor.fontSize": 17,
"editor.fontFamily": "Hasklig, Mononoki Nerd Font, Consolas, 'Courier New', monospace",
"editor.letterSpacing": 0.3,
"editor.parameterHints.enabled": false,
// "editor.lineHeight": 0,
"editor.insertSpaces": true,
"editor.tabSize": 2,
"editor.detectIndentation": false,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.folding": true,
"editor.formatOnSave": true,
"editor.formatOnPaste": true,
"editor.formatOnType": true,
"editor.suggestSelection": "recentlyUsedByPrefix",
"editor.suggest.preview": true,
"editor.wordWrap": "on",
"editor.smoothScrolling": true,
"editor.bracketPairColorization.enabled": true,
"editor.guides.bracketPairs": true,
"editor.linkedEditing": true,
"editor.cursorBlinking": "smooth",
"editor.renderWhitespace": "selection",
"extensions.ignoreRecommendations": true,
"editor.fontLigatures": true,
"workbench.list.smoothScrolling": true,
"files.trimFinalNewlines": true,
"files.insertFinalNewline": false,
"files.trimTrailingWhitespace": true,
"workbench.startupEditor": "none",
"workbench.settings.editor": "json",
"workbench.editor.wrapTabs": true,
"window.titleBarStyle": "custom",
"workbench.iconTheme": "material-icon-theme",
"workbench.sideBar.location": "right",
"workbench.activityBar.visible": false,
"window.restoreWindows": "none",
"git.ignoreMissingGitWarning": true,
"terminal.integrated.profiles.windows": {
"PowerShell": { "path": "C:\\Program Files\\PowerShell\\7\\pwsh.exe" }
},
"terminal.integrated.fontFamily": "Hack Nerd Font Mono",
"terminal.integrated.defaultProfile.windows": "PowerShell",
"terminal.integrated.fontSize": 17,
// "files.autoSave": "onFocusChange",
"explorer.autoReveal": false,
"explorer.sortOrder": "type",
"explorer.openEditors.visible": 0,
"editor.occurrencesHighlight": false,
//"editor.glyphMargin": false,
//"editor.renderWhitespace": "all",
"workbench.editor.enablePreview": false,
"comment-divider.mainHeaderFiller": "=",
"prettier.tabWidth": 2,
"prettier.useTabs": false,
"prettier.htmlWhitespaceSensitivity": "ignore",
// "prettier.printWidth": 120,
"prettier.bracketSpacing": true,
// "prettier.semi": true,
//"editor.rulers": [120],
"php.suggest.basic": false,
"php.executablePath": "C:\\laragon\\bin\\php\\php-8.1.7-Win32-vs16-x64\\php.exe",
"intelephense.format.braces": "k&r",
"workbench.tree.indent": 17,
"html.autoClosingTags": true,
"css.validate": true,
"scss.validate": true,
"less.validate": true,
"javascript.validate.enable": false,
"eslint.enable": true,
"eslint.validate": ["javascript"],
"eslint.alwaysShowStatus": true,
"material-icon-theme.folders.color": "#DDB686",
"workbench.colorTheme": "Palenight Italic",
"editor.inlineSuggest.enabled": true,
"blade.format.enable": true,

"workbench.colorCustomizations": {
"titleBar.activeBackground": "#2D2D2D",
"editor.background": "#1D1D1D",
"activityBar.background": "#0F0F1A",
"activityBar.border": "#3F3F46",
"sideBar.background": "#252526",
"sideBar.border": "#434343",
"sideBar.foreground": "#DFDFDF",
"sideBarSectionHeader.background": "#37373D",
"activityBar.foreground": "#a9ebff",
"activityBar.inactiveForeground": "#6B7A83",
// "activityBar.activeBackground": "#ccda14",
"activityBarBadge.background": "#00e6cb",
"activityBarBadge.foreground": "#000000",
"list.activeSelectionBackground": "#7144BB",
"list.inactiveSelectionBackground": "#5f3b9e",
"editorIndentGuide.activeBackground": "#8BD0FE",
"editorIndentGuide.background": "#1E292F",
"list.inactiveSelectionForeground": "#fff",
"tab.activeBorder": "#52DCFF",
"tab.inactiveBackground": "#252526",
"tab.activeBackground": "#1F4061",
"tab.inactiveForeground": "#888888",
"editorGroupHeader.tabsBackground": "#252526",
"editorCursor.foreground": "#FFCC00",
// "editor.wordHighlightBackground": "#39f00b",
"editor.wordHighlightBackground": "#1e1e1e00",
"panel.border": "#007ACC",
"statusBar.background": "#4A1757",
"editor.lineHighlightBackground": "#1D1D1D",
"editor.lineHighlightBorder": "#696969",
"editorLineNumber.activeForeground": "#FFF",
"editorLineNumber.foreground": "#7D7D7D",
"editor.selectionBackground": "#264F78",
"editorBracketMatch.background": "#464646",
"editorBracketMatch.border": "#1E1E1E",
"scrollbarSlider.hoverBackground": "#4F4F4F",
"scrollbarSlider.background": "#4F4F4F",
"scrollbarSlider.activeBackground": "#343C40",
"editor.findMatchHighlightBackground": "#8f1527",
//"editor.findMatchHighlightBackground": "#4D78CC",
"editor.findMatchBackground": "#4D78CC",
"list.hoverBackground": "#343C40",
"list.focusBackground": "#1B67A5",
"pickerGroup.foreground": "#00F4D6",
"editorWidget.resizeBorder": "#6ffd62",
// "editorWidget.background": "#262930",
//"editor.findMatchHighlightBorder": "#00ff22",
"input.border": "#0086DF",
"input.background": "#272727",
"selection.background": "#0082D9",
"editorHoverWidget.border": "#7E57C2",
"editorSuggestWidget.selectedBackground": "#2E64C8",
"editorSuggestWidget.foreground": "#e7e5e5",
"editorSuggestWidget.focusHighlightForeground": "#00FFFF",
// "terminal.background": "#ff0000",
"panel.background": "#1E1E1E"
},
"[html]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},

"[php]": {
"editor.defaultFormatter": "bmewburn.vscode-intelephense-client",
"editor.formatOnSave": true,
"editor.formatOnPaste": true
},

"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"editor.formatOnPaste": true,
"editor.tabSize": 2,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true,
"source.fixAll.stylelint": true
}

},

"[json]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"editor.formatOnPaste": true,
"editor.tabSize": 2
},

"emmet.includeLanguages": {
"javascript": "html",
"php": "html"
},

"editor.tokenColorCustomizations": {
"[Palenight Italic]": {
"comments": "#8B9398",
// "functions": "#9BBCFF",
// "strings": "#FF0000",
"textMateRules": [
{
"scope": ["punctuation.section.embedded"],
"settings": {
"foreground": "#EE8CF0"
}
},
{
"scope": ["keyword.control"],
"settings": {
"fontStyle": "italic"
}
},
{
"scope": ["punctuation.definition.variable.php"],
"settings": {
"foreground": "#07E8C1"
}
},
{
"scope": ["variable.other.php"],
"settings": {
"foreground": "#07E8C1"
}
},
{
"scope": ["variable.other.env"],
"settings": {
"foreground": "#E48596"
}
}
]
}
},

"editor.codeActionsOnSave": {
"source.fixAll.eslint": true,
"source.fixAll.stylelint": true
},

"files.associations": {
"*.json": "jsonc"
},

"[blade]": {
"editor.defaultFormatter": "shufo.vscode-blade-formatter"
},

"security.workspace.trust.untrustedFiles": "open",
"files.autoSave": "afterDelay",
"window.menuBarVisibility": "compact"
}

Instalar Powershell 7

Instalar Powershell Version 7 -------------------------------------- $> winget search powershell $> winget install Microsoft.Powershe...