Hola grep,
muchas gracias por tu ayuda. Esta vez no la merecía.
Gracias y saludos
muchas gracias por tu ayuda. Esta vez no la merecía.
Gracias y saludos

Esta sección te permite ver todos los mensajes escritos por este usuario. Ten en cuenta que sólo puedes ver los mensajes escritos en zonas a las que tienes acceso en este momento.
Mostrar Mensajes MenúCitarTienes razón. Lo que pasa es que mi Network no cumple con los requisitos para instalar Android Studio. Es por eso que lo hago con AIDE.
Por eso, creo que usar una app como AIDE para desarrollar aplicaciones es impractico, yo preferiría hacerlo desde una computadora.
package com.mycompany.myapp2;
import android.app.*;
import android.os.*;
import android.net.VpnService;
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
run();
}
public void run() {
VpnService.prepare(MainActivity.this);
VpnService.Builder builder = new VpnService.Builder();
// Create a local TUN interface using predetermined addresses. In your app,
// you typically use values returned from the VPN gateway during handshaking.
ParcelFileDescriptor localTunnel = builder
.addAddress("192.168.2.2", 24)
.addRoute("0.0.0.0", 0)
.addDnsServer("192.168.1.1")
.establish();
}
}

Citar
Quiero y tengo en mente, pero necesito tener tiempo libre, hacer un analizador uploadfile:
Consiste en crear un javaweb proyecto con un bonito index.jsp que será el uploader a través de getter setter quiero que analize el archivo y si va metido dentro de él código .php, o lo que es lo mismo un shell.php, deniege el upload y redireccione a un html bonito.
private long startTime = 0L;
private List<Long> stopTimes = new ArrayList<>();
public void arranque() {
if (startTime == 0L) {
startTime = System.nanoTime();
}
}
public void fin() {
stopTimes.add(System.nanoTime());
}
public long getFullInterval() {
return stopTimes.get(stopTimes.size()-1) - startTime;
}
public void arranque() {
if (stopTimes.size() == 0) {
stopTimes.add(System.nanoTime());
}
}
public long getFullInterval() {
return getInterval(0, stopTimes.size()-1);
}
public long getInterval(int from, int to) {
return stopTimes.get(to) - stopTimes.get(from);
}
import java.math.BigInteger;
import java.security.SecureRandom;
/**
* Utilizes a Diffie-Hellman Key-Exchange<br>
* <br>
* <pre>
* Partner A Partner B
* g, p, a (randomly) b (randomly)
* A = g^a mod p
* g, p, A ==>
* B = g^b mod p
* <== B
* K = B^a mod p K = A^b mod p
* </pre>
* <br>
* Example Usage:<br>
* Partner A:<br>
* <code>
* DiffieHellman dh = new DiffieHellman(DiffieHellman.PARTNER_A);<br>
* dh.init(512);<br>
* sendToOtherSide(dh.getG());<br>
* sendToOtherSide(dh.getP());<br>
* sendToOtherSide(dh.getA());<br>
* byte[] key = dh.getKey(receiveFromOtherSide());<br>
* </code><br>
* <br>
* Partner B:<br>
* <code>
* DiffieHellman dh = new DiffieHellman(DiffieHellman.PARTNER_B);<br>
* dh.init(512);<br>
* BigInteger g = receiveFromOtherSide();<br>
* BigInteger p = receiveFromOtherSide();<br>
* BigInteger A = receiveFromOtherSide();<br>
* byte[] key = dh.getKey(g, p, A);<br>
* sendToOtherSide(dh.getB());<br>
* </code>
* @author Tobias Marstaller
*/
public class DiffieHellman
{
public static final int PARTNER_A = 0xF124A;
public static final int PARTNER_B = 0xC134B;
protected BigInteger g;
protected BigInteger p;
protected BigInteger a;
protected BigInteger b;
protected BigInteger A;
protected BigInteger B;
protected byte[] K;
protected int side;
protected boolean initDone = false;
protected SecureRandom rand;
/**
* Constructs a new Key-Exchange for the given side
*/
public DiffieHellman(int side)
{
if (side != PARTNER_A && side != PARTNER_B)
{
throw new IllegalArgumentException("side must be equal to PARTNER_A or PARTNER_B");
}
this.side = side;
}
/**
* Constructs a new Key-Exchange for the given side with the default bit
* length 1024 and <code>random</code> as a source of randomness.
* @param random A SPRNG for the parameter-generation
*/
public DiffieHellman(int side, SecureRandom random)
{
this(side);
this.rand = random;
}
/**
* Constructs a new Key-Exchange for side B (therefore <code>assert(side == PARTNER_B)</code>)
* with <code>b</code> as the private parameter.<br>
* If this constructor is used, the call to {@link #init()} is not required anymore.
* @param b The private parameter <code>b</code>
*/
public DiffieHellman(int side, BigInteger b)
{
if (side != PARTNER_B)
{
throw new IllegalArgumentException("Side must be PARTNER_B");
}
this.side = side;
this.b = b;
initDone = true;
}
/**
* Constructs a new Key-Exchange for side A (therefore <code>assert(side == PARTNER_A)</code>)
* with <code>g</code>, <code>p</code> and <code>a</code> as the private parameters.<br>
* If this constructor is used, the call to {@link #init()} is not required anymore.
* @param g The private parameter <code>g</code>
* @param p The private parameter <code>p</code>
* @param a The private parameter <code>a</code>
*/
public DiffieHellman(int side, BigInteger g, BigInteger p, BigInteger a)
{
if (side != PARTNER_A)
{
throw new IllegalArgumentException("Side must be PARTNER_A");
}
this.side = side;
this.g = g;
this.p = p;
this.a = a;
this.A = this.g.modPow(a, p);
initDone = true;
}
/**
* Initializes the instance with the default bit-length 1024
*/
public void init()
{
init(1024);
}
/**
* Initializes the instance with the given bitLength
*/
public void init(int bitLength)
{
if (rand == null)
{
rand = new SecureRandom();
}
if (this.side == PARTNER_A)
{
this.g = BigInteger.probablePrime(bitLength, rand);
this.p = BigInteger.probablePrime(bitLength, rand);
this.a = BigInteger.probablePrime(bitLength, rand);
this.A = this.g.modPow(a, p);
}
else if (this.side == PARTNER_B)
{
this.b = BigInteger.probablePrime(bitLength, rand);
}
initDone = true;
}
/**
* @return Returns the key, if already calculated
* @throws RuntimeException If the key hast not been calculated yet.
*/
public byte[] getKey()
{
if (this.K == null)
{
throw new RuntimeException("The key has not been calculated yet.");
}
return K;
}
/**
* Calculates the key for side B (therefore <code>assert(side == PARTNER_B)</code>).
* @param g Parameter <code>g</code>
* @param p Parameter <code>p</code>
* @param A Parameter <code>A</code>
* @return Returns the calculated key
* @throws UnsupportedOperaionException If this instance has been inizialied as PARTNER_A
* @throws RuntimeException If the parameters are not initialized
*/
public byte[] getKey(BigInteger g, BigInteger p, BigInteger A)
{
if (this.side != PARTNER_B)
{
throw new UnsupportedOperationException("This method only works for PARTNER_B instances.");
}
if (!this.initDone)
{
throw new RuntimeException("The object has to be initialized.");
}
this.B = g.modPow(b, p);
this.K = A.modPow(b, p).toByteArray();
return K;
}
/**
* Calculates the key for side A (therefore <code>assert(side == PARTNER_A)</code>).
* @param g Parameter <code>g</code>
* @param p Parameter <code>p</code>
* @param A Parameter <code>A</code>
* @return Returns the calculated key
* @throws UnsupportedOperaionException If this instance has been inizialied as PARTNER_B
*/
public byte[] getKey(BigInteger B)
{
if (this.side != PARTNER_A)
{
throw new UnsupportedOperationException("This method only works for PARTNER_A instances.");
}
if (!this.initDone)
{
throw new RuntimeException("The object has to be initialized.");
}
this.K = B.modPow(a, p).toByteArray();
return K;
}
public BigInteger getG()
{
return g;
}
public BigInteger getP()
{
return p;
}
public BigInteger getA()
{
return A;
}
public BigInteger getB()
{
return B;
}
}
// Partner A
DiffieHellman dh = new DiffieHellman(DiffieHellman.PARTNER_A);
dh.init(512);
sendToOtherSide(dh.getG());
sendToOtherSide(dh.getP());
sendToOtherSide(dh.getA());
byte[] key = dh.getKey(receiveFromOtherSide());
// Partner B
DiffieHellman dh = new DiffieHellman(DiffieHellman.PARTNER_B);
dh.init(512);
BigInteger g = receiveFromOtherSide();
BigInteger p = receiveFromOtherSide();
BigInteger A = receiveFromOtherSide();
byte[] key = dh.getKey(g, p, A);
sendToOtherSide(dh.getB());
private int[][] createSudoku()
{
int[][] field = new int[9][9];
for(int i = 0; i < field.length; i++)
{
int[] rand;
do {
rand = createRandomRange();
System.arraycopy(rand, 0, field[i], 0, rand.length);
}
while(!proofIntField(field));
}
return field;
}
private boolean proofIntField(int[][] field)
{
for(int i = 0; i < field.length; i++)
{
if(!proofNoDuplicate(field[i])) {
return false;
}
}
for(int i = 0; i < 9; i++)
{
int[] temp = new int[9];
for(int j = 0; j < 9; j++)
{
temp[j] = field[j][i];
}
if(!proofNoDuplicate(temp)) {
return false;
}
}
for(int i = 0; i < 9; i += 3)
{
for(int j = 0; j < 9; j += 3)
{
int[] temp = new int[9];
int h = 0;
for(int k = 0; k < 3; k++)
{
for(int g = 0; g < 3; g++)
{
temp[h] = field[i+k][j+g];
h++;
}
}
if(!proofNoDuplicate(temp)) {
return false;
}
}
}
return true;
}
private boolean proofNoDuplicate(int[] field)
{
int[] temp = new int[9];
for(int i = 0; i < field.length; i++)
{
if(field[i] != 0) {
for(int j:temp)
{
if(j == field[i]) {
return false;
}
}
temp[i] = field[i];
}
}
return true;
}
private int[] createRandomRange()
{
int[] field = new int[9];
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i = 1; i <= 9; i++)
{
list.add(i);
}
Collections.shuffle(list);
for(int i = 0; i < 9; i++)
{
field[i] = list.get(i).intValue();
}
return field;
}
package CronoMetro;
import java.util.HashMap;
/**
* <p>Con ello la clase ayuda a calcular y a emitir fácilmente tiempos de
* ejecuciones de aplicaciones.</p>
* <p>Después de la instanciación el método arranque() debe ser llamado para definir un
* tiempo de inicio. </p>
* <p>Después de la terminación del programa se finaliza el cronometraje con fin(), después de esto
* los valores del intervalo están disponibles:</p>
* <p>El intervalo total convertido en</p>
* <ul>
* <li>Nanosegundos</li>
* <li>Milisegundos</li>
* <li>Segundos</li>
* <li>Minutos</li>
* <li>Horas</li>
* <li>Días</li>
* <li>El intervalo convertido legiblemente</li>
* </ul>
* @author Dominik Sust
* @creation 07.07.2014 09:20:36
* @version 1.0
*/
public class CronoMetro
{
//Arranque y tiempo de finalización en nanosegundos
private long startTime = 0L;
private long endTime = 0L;
//Intervalos
private long intervalInNanoseconds;
private double intervalInMilliseconds;
private double intervalInSeconds;
private double intervalInMinutes;
private double intervalInHours;
private double intervalInDays;
//Intervalo total
private HashMap<String, Integer> totalInterval = new HashMap<String, Integer>();
/**
* Arranca el cronometraje
* Esa función puede ser llamada sólo una vez para que no pueda ocurrir un intervalo
* de tiempo negativo. Solo se registrará la primera llamada,
* las llamadas posteriores serán ignoradas.
*/
public void arranque()
{
if ( startTime == 0L )
{
startTime = System.nanoTime();
}
}
/**
* Finaliza el cronometraje.
* Esta función puede ser llamada varias veces para calcular varios
* (con medida a la primera llamada
* arranque()). Después de la llamada de este método los valores de los resultados están
* disponibles.
*/
public void fin()
{
endTime = System.nanoTime();
calculaTiempos();
}
/**
* Función interna que calcula todos los intervalos
*/
private void calculaTiempos()
{
//Intervalos totales
intervalInNanoseconds = endTime - startTime;
intervalInMilliseconds = (double) intervalInNanoseconds / (double) 1000000;
intervalInSeconds = intervalInMilliseconds / (double) 1000;
intervalInMinutes = (double) intervalInSeconds / (double) 60;
intervalInHours = intervalInMinutes / (double) 60;
intervalInDays = intervalInHours / (double) 24;
//Intervalos totales en días, horas, minutos, segundos
double oneSecondInMS = 1000.0;
double oneMinuteInMS = 60000.0;
double oneHourInMS = 3600000.0;
double oneDayInMS = 86400000.0;
//Calcular días
double tempInterval = intervalInMilliseconds;
int temp = (int) (tempInterval / oneDayInMS);
totalInterval.put( "Days", temp );
//Quitar los días calculados del intervalo total
tempInterval -= temp * oneDayInMS;
//Calcular horas
temp = (int) (tempInterval / oneHourInMS);
totalInterval.put( "Hours", temp );
//Quitar las horas calculados del intervalo total
tempInterval -= temp * oneHourInMS;
//Calcular minutos
temp = (int) (tempInterval / oneMinuteInMS);
totalInterval.put( "Minutes", temp );
// Quitar los minutos calculados del intervalo total
tempInterval -= temp * oneMinuteInMS;
//Calcular segundos
temp = (int) (tempInterval / oneSecondInMS);
totalInterval.put( "Seconds", temp );
//Quitar los segundos calculados del intervalo total
tempInterval -= temp * oneSecondInMS;
//¿¿Milisegundos??
totalInterval.put( "Milliseconds", (int) tempInterval );
}
/**
* Retorna el intervalo total en nanosegundos.
* Esta función suministra solamente un valor válido después de que los métodos
* arranque() y fin() son llamados
* @return El intervalo total en nanosegundos
*/
public long getIntervalInNanoseconds()
{
return intervalInNanoseconds;
}
/**
* Retorna el intervalo total en milisegundos.
* Esta función suministra solamente un valor válido después de que los métodos
* arranque() y fin() son llamados
* @return El intervalo total en milisegundos
*/
public double getIntervalInMilliseconds()
{
return intervalInMilliseconds;
}
/**
* Retorna el intervalo total en segundos.
* Esta función suministra solamente un valor válido después de que los métodos
* arranque() y fin() son llamados
* @return El intervalo total en segundos
*/
public double getIntervalInSeconds()
{
return intervalInSeconds;
}
/**
* Retorna el intervalo total en minutos.
* Esta función suministra solamente un valor válido después de que los métodos
* arranque() y fin() son llamados
* @return El intervalo total en minutos
*/
public double getIntervalInMinutes()
{
return intervalInMinutes;
}
/**
* Retorna el intervalo total en horas.
* Esta función suministra solamente un valor válido después de que los métodos
* arranque() y fin() son llamados
* @return El intervalo total en horas
*/
public double getIntervalInHours()
{
return intervalInHours;
}
/**
* Retorna el intervalo total en días.
* Esta función suministra solamente un valor válido después de que los métodos
* arranque() y fin() son llamados
* @return El intervalo total en días
*/
public double getIntervalInDays()
{
return intervalInDays;
}
/**
* <p>Retorna una Hashmap con los valores del intervalo.</p>
* <p>Llaves son</p>
* <ul>
* <li>Days</li>
* <li>Hours</li>
* <li>Minutes</li>
* <li>Seconds</li>
* <li>Milliseconds</li>
* </ul>
* <p>Con eso se puede elaborar una salida individual del intervalo.</p>
* @return HashMap<String, Integer>
*/
public HashMap<String, Integer> getTotalInterval()
{
return totalInterval;
}
/**
* <p>Retorna el intervalo en forma de strings totales.</p>
* <p>Ejemplo:<br>
* 2 días, 4 horas, 40 minutos, 38 segundos, 456 milisegundos</p>
* <p>Si no se necesita todos los valores se puede elaborar por medio del
* metodo getTotalInterval() una propia salida.</p>
*
* @return El intervalo en forma de string
*/
public String totalIntervalToString()
{
int d = totalInterval.get( "Days" );
int h = totalInterval.get( "Hours" );
int min = totalInterval.get( "Minutes" );
int s = totalInterval.get( "Seconds" );
int ms = totalInterval.get( "Milliseconds" );
String result = d+" dia, "+h+" hora, "+min+" minuto, "+s+" segundo, "+ms+" milisegundo";
//Días
if ( d != 1 )
{
result = result.replace( "dia", "dias");
}
//Horas
if ( h != 1 )
{
result = result.replace( "hora", "horas");
}
//Minutos
if ( min != 1 )
{
result = result.replace( "minuto", "minutos");
}
//Segundos
if ( s != 1 )
{
result = result.replace( "segundo", "segundos");
}
//Milisegundos
if ( ms != 1 )
{
result = result.replace( "milisegundo", "milisegundos");
}
return result;
}
/**
* <p>Emite todos los valores del objeto en el siguiente orden:</p>
* <ul>
* <li>startTime</li>
* <li>endTime</li>
* <li>intervalInNanoseconds</li>
* <li>intervalInMilliseconds</li>
* <li>intervalInSeconds</li>
* <li>intervalInMinutes</li>
* <li>intervalInHours</li>
* <li>intervalInDays</li>
* <li>La salida del metodo totalIntervalToString()</li>
* </ul>
* @return String
*/
@Override
public String toString()
{
return "IntervalUtil{"
+ "startTime=" + startTime
+ ",\n endTime=" + endTime
+ ",\n intervallInNanoseconds=" + intervalInNanoseconds
+ ",\n intervallInMilliseconds=" + intervalInMilliseconds
+ ",\n intervallInSeconds=" + intervalInSeconds
+ ",\n intervallInMinutes=" + intervalInMinutes
+ ",\n intervallInHours=" + intervalInHours
+ ",\n intervallInDays=" + intervalInDays
+ ",\n " + totalIntervalToString() + "'}'";
}
}
import java.util.Random; //importar
import java.util.Scanner; //importar
public class GenCont {
public static void main(String[] args) {
Scanner s = new Scanner (System.in); //Crear un nuevo objeto de la clase Scanner
int largo, seleccion; //inicializar las variables para la selección y el largo de la contraseña
System.out.println("Hola y bienvenido");
System.out.println("Por favor ingrese el largo de la contraseña y a continuación presione Enter:");
largo = s.nextInt(); //Selección del largo
System.out.println("Por favor haga una selección: \n1. Solamente números \n2. Solamente letras \n3. Alfanúmerico");
seleccion = s.nextInt(); //Selección de la clase de contraseña
System.out.println(creacont(seleccion, largo)); // Llamada del método para la generación de la contraseña
}
private static char[] creacont( int seleccion, int largo) {
char[] cont;
cont = new char[largo];
int contador = 0;
switch (seleccion) {
case 1:
while (contador<largo) {
cont[contador] = intercambionumero(numeroaleatorio(10, 26));
contador++;
}
break;
case 2:
while (contador<largo) {
cont[contador] = intercambionumero(numeroaleatorio(26, 0));
contador++;
}
break;
case 3:
while (contador<largo) {
cont[contador] = intercambionumero(numeroaleatorio(36, 0));
contador++;
}
break;
}
return cont;
}
private static int numeroaleatorio(int limitea, int limiteb) {
Random cont = new Random();
return cont.nextInt(limitea)+limiteb; //Creación de un número aleatorio
}
private static char intercambionumero(int numero){ //Genera letras y números a partir de los números transmitidos
String s = "abcdefghijklmnopqrstuvwxyz0123456789"; //Definir las/los posibles letras/números
char[] c = s.toCharArray(); //Convertir el String en Char para que pueda abordar a las letras individualmente
return c[numero]; //Distribuye la letra respectiva
}
}
CitarCódigo: java
int n = 1; // n = numero de premios
for (int i = 0; i <= n; i++) {
//comprueba si combinación esta en premios registrados
if (Arrays.equals(frutas, coleccion[i].getCombGanad()) == true){
credDisp = credDisp + coleccion[i].getPremio();
}
}
for (Premio premio : coleccion) {
if (Arrays.equals(frutas, premio.getCombGanad()) == true){
credDisp = credDisp + premio.getPremio();
}
}
import static java.util.stream.LongStream.iterate;
import java.util.BitSet;
import java.util.stream.LongStream;
public class PrimeFactors {
public static void main(String[] args) {
primeFactors(2 * 2 * 2 * 2 * 2 * 109).forEach(System.out::println);
}
public static LongStream primeFactors(int n) {
BitSet notPrime = new BitSet(n);
return iterate(2, i -> i <= n, i -> notPrime.nextClearBit((int) (i + 1)))
.peek(i -> iterate(i * i, j -> j <= n, j -> j + i)
.forEach(j -> notPrime.set((int) j, true)))
.flatMap(i -> iterate(n, j -> (j % i) == 0, j -> j / i)
.map(__ -> i));
}
}
CitarEdición: Aunque aquí 8 ya bastaría, 8! Ya es algo grande.
Si opinas tener un algoritmo: Pues ¿suministra el números correctos? (¡Aquí se prueba con números pequeños que también se pueden verificar a mano y así! ¡Por tanto prueba una vez tu algoritmo p. e. con el número 8!)
import java.util.ArrayList;
import java.util.List;
public class PrimeFactor {
public static List<Long> getPrimeFactors(final long number) {
List<Long> result = new ArrayList<>();
long counter = 2;
long reminder = number;
while (counter < Math.sqrt(reminder)) {
while (reminder % counter == 0) {
result.add(counter);
reminder=reminder/counter;
}
counter = (counter==2) ? 3 : counter+1;
}
if (reminder > 1) {
result.add(reminder);
}
return result;
}
public static void main(String[] args) {
System.out.println("8 fraccionado: " + getPrimeFactors(8));
System.out.println("600851475143 fraccionado: " + getPrimeFactors(600851475143L));
}
}
.
import static java.util.stream.IntStream.range;
import static org.jooq.lambda.Seq.seq; // <- https://github.com/jOOQ/jOOL
import java.util.ArrayList;
import java.util.function.Supplier;
import java.util.stream.Stream;
public class VerschlüsselungJAVA2 {
private final static int ALFA[] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '_', '.', ',', ';', ':'
};
private static Supplier<? extends IllegalArgumentException> characterNotInAlphabet(int cp) {
return () -> new IllegalArgumentException("Character not in alphabet: " + Character.toString(cp));
}
private static int alphaAt(int index) {
return ALFA[index % ALFA.length];
}
public static String encrypt(String key, String phrase) {
// zip the phrase characters with the exclusive prefix
// sum mapping the space to 0 and every other character to 1,
// lookup the alphabet character and offset by the key digit
// at the index provided by the prefix sum
return seq(phrase.chars())
.map(Character::toUpperCase)
.zip(keyIndicesOf(phrase))
.map(t -> t.v1 == ' ' ? ' ' : alphaAt(offset(t.v1, key, t.v2)))
.map(Character::toString)
.toString();
}
private static int findAlphabetIndexOf(int cp) {
// 'C' -> 2
return range(0, ALFA.length)
.filter(i -> ALFA[i] == cp)
.findFirst()
.orElseThrow(characterNotInAlphabet(cp));
}
private static int offset(int phraseChar, String key, int keyIndex) {
// Find the index of the phrase character and offset by the digit at the key index
return findAlphabetIndexOf(phraseChar)
+ key.charAt(keyIndex % key.length()) - '0';
}
private static Stream<Integer> keyIndicesOf(String phrase) {
// Exclusive prefix sum of the stream producing
// 0 for spaces and 1 for every other character
// "abc de f" -> [0, 1, 2, 2, 3, 4, 4, 5]
return phrase.chars()
.map(c -> isIgnored(c) ? 0 : 1)
.collect(ArrayList<Integer>::new,
(l, v) -> l.add(v + (l.isEmpty() ? 0 : l.get(l.size() - 1))),
(l1, l2) -> {}).stream()
.map(i -> i - 1);
}
private static boolean isIgnored(int c) {
return c == ' ';
}
public static void main(String[] args) {
String phrase = "cifrado ejemplo";
String key = "9876"; // Cualquier número
System.out.println(encrypt(key, phrase));
}
}