Menú

Mostrar Mensajes

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

Mostrar Mensajes Menú

Mensajes - Adalher

#121
Hola n0z,

pero ¿y si todavía no hay ningún root para mí modelo de Android? ¿Cómo puedo hacer yo un root para mi Android en Java?

Gracias y saludos
#122
Java / Re:Cifrado en JAVA
Mayo 29, 2019, 05:43:04 PM
Hola DeBobiPro,

1) Solo puedo ponerte en el corazón: ocúpate más intensamente con fundamentos y especialmente con convenciones de código.
2) Aquí no quiero ser vil pero: si está haciendo un pequeño ejercicio de programación en la escuela que utiliza el cifrado César como contenido, no significa eso que el código resultante sea de alguna utilidad para el público en general. Solo sirve para el propio entrenamiento personal de quien hace el ejercicio - nada más. Para TODO lo que se publica como resultado de un ejercicio habrá mejores soluciones. Estoy muy seguro de eso. Por ejemplo para el tema: cifrado.
Y, si uno piensa: "Eso no está pensado para algún uso productivo, sino como una ayuda para las personas que realizan este ejercicio o un ejercicio similar" entonces digo: No, ni siquiera eso. Primero, el resultado del trabajo de tales ejercicios suele ser tan deficiente en calidad que solo sirve como un ejemplo negativo, y en segundo lugar, deberían hacer otros, que hacen tal ejercicio, los ejercicios ellos mismos y no copiarlos. Pues el propósito de tales ejercicios no es el resultado/código final, sino la experiencia de llegar allí.

Saludos
#123
Hola KiddArabic,

me parece que eso lo que posteaste es solo para celulares que ya están rooteados o/y solamente para que un proceso tenga privilegios root.

Pero lo que yo necesito es rootear Android como lo hace KingoApp para que pueda utilizar cualquier App que necesite root.

Gracias y saludos
#124
Dudas y pedidos generales / AIDE - Rootear Android
Mayo 24, 2019, 06:34:37 AM
Hola a todos,

¿cómo puedo rootear Android con Java?
¿Necesito buscar exploits para eso? Si es así, ¿cómo los puedo buscar?

Gracias y saludos
#125
Java / BalancedBinarySearchTree
Mayo 23, 2019, 02:24:31 PM
Hola a todos,

publico un árbol binario que siempre está equilibrado, i. para cada nodo, la altura del subárbol derecho difiere en un máximo de 1 desde la altura del subárbol izquierdo y un BTreeMap que lo toca.
Pero ambas clases fueron creadas solo por diversión en la alegría. En el uso real, no desempeñan ningún papel, ya que se recurre a las clases del Framework (hasta ahora no vio ninguna razón para una dependencia adicional en los proyectos).
Aquí hay una contención importante: T debe implementar Comparable <T>. De lo contrario, el valor no se puede insertar!
Código: java

package de.kneitzel.lib.collections;

/**
* A binary search tree that is always balanced.
* @param <T> Type of the values to store inside the tree.
*/
public class BalancedBinarySearchTree<T extends Comparable<T>> {

    /**
     * Gets the size of the BalancedBinarySearchTree
     * @return Numbe of elements inside the BalancedBinarySearchTree
     */
    public int size() {
        return rootNode != null ? rootNode.count : 0;
    }

    /**
     * Root node of the BalancedBinarySearchTree.
     */
    private BalancedBinarySearchTreeNode<T> rootNode;

    /**
     * Add an element to the BalancedBinarySearchTree
     * @param item
     * @return The item.
     */
    public T put(T item) {
        if (rootNode == null) {
            rootNode = new BalancedBinarySearchTreeNode<>(item);
        } else {
            rootNode.put(item);
        }
        return item;
    }

    /**
     * Remove an item of the BalancedBinarySearchTree
     * @param item Item to remove.
     * @return The item removed or null if not found.
     */
    public T remove(T item)
    {
        if (rootNode == null)
            return null;

        // Get the element first
        T element = rootNode.remove(item);
        if (rootNode.item == null) {
            rootNode = null;
        }

        // return the element.
        return element;
    }

    /**
     * Checks the BalancedBinarySearchTree. This is just an internal method which is used to unit-test the implementation.
     * @return Should always return true.
     */
    public boolean check()
    {
        return rootNode == null ? true : rootNode.check();
    }

    /**
     * Searches if an item is inside the BalancedBinarySearchTree.
     * @param item Item to search for.
     * @return the Item if found else null.
     */
    public T find(T item)
    {
        return rootNode == null ? null : rootNode.find(item);
    }

    /**
     * Tree node of the BalancedBinarySearchTree
     * @param <T> Type of the values to store inside the node.
     */
    protected class BalancedBinarySearchTreeNode<T extends Comparable<T>> {

        /**
         * Item stored inside the BalancedBinarySearchTreeNode.
         */
        public T item;

        /**
         * Child Nodes.
         */
        public BalancedBinarySearchTreeNode<T> left, right; // left and right child

        /**
         * Number of items stored inside the node and all subnodes.
         */
        public int count;

        /**
         * Height of this subtree.
         */
        public int height;

        /**
         * Creates a new instance of type BalancedBinarySearchTreeNode.
         * @param item Item to store inside this node.
         */
        public BalancedBinarySearchTreeNode(T item) {
            left = null;
            right = null;
            this.item = item;
            count = 1;
            height = 1;
        }

        /**
         * Add the item to this subtree.
         * @param item item to put.
         */
        public void put(T item) {
            // Compare the item to put with the stored item.
            int comparison = item.compareTo(this.item);

            // Override the stored item if the comparison is 0
            if (comparison == 0) {
                this.item = item;
                // Only the stored element was overridden so there is no change to count and height and
                // no need to balance the tree.
                return;
            }

            if (comparison < 0) {
                // Store the item on the left side.
                if (left == null)
                    left = new BalancedBinarySearchTreeNode<>(item);
                else
                    left.put(item);
            } else {
                // Store the item on the right side.
                if (right == null)
                    right = new BalancedBinarySearchTreeNode<>(item);
                else
                    right.put(item);
            }

            // Increase count by one
            count++;

            // Balance the tree.
            balance();
        }

        /**
         * Check the balance of the tree and rebalance it if required.
         */
        private void balance()
        {
            if ((left == null) && (right == null))
            {
                height = 1;
                return;
            }

            int leftHeight = (left != null) ? left.height : 0;
            int rightHeight = (right != null) ? right.height : 0;

            if (leftHeight + 2 <= rightHeight)
                turnLeft();

            if (rightHeight + 2 <= leftHeight)
                turnRight();

            reCalculate();
        }

        /**
         * Switch the Elements to the left
        **/
        private void turnLeft()
        {
            // First switch the items of this element with the right item
            T temp = item;
            item = right.item;
            right.item = temp;

            // Now set the references correctly
            BalancedBinarySearchTreeNode<T> tempNode = right;
            right = tempNode.right;
            tempNode.right = tempNode.left;
            tempNode.left = left;
            left = tempNode;

            left.reCalculate();
            if (right != null) right.reCalculate();
        }

        /**
         * Switch the elements to the right
        **/
        private void turnRight()
        {
            // First switch the items of this element with the right item
            T temp = item;
            item = left.item;
            left.item = temp;

            // Now set the references correctly
            BalancedBinarySearchTreeNode<T> tempNode = left;
            left = tempNode.left;
            tempNode.left = tempNode.right;
            tempNode.right = right;
            right = tempNode;

            if (left != null)
                left.reCalculate();
            right.reCalculate();
        }

        /**
         * Calculate Height and Count of this node
        **/
        private void reCalculate()
        {
            // Set Count
            count = 1 + (left == null ? 0 : left.count) + (right == null ? 0 : right.count);

            // Set Height
            int leftHeight = (left != null) ? left.height : 0;
            int rightHeight = (right != null) ? right.height : 0;
            height = ((leftHeight > rightHeight) ? leftHeight : rightHeight) + 1;
        }

        /**
         * Remove the specified item.
         * @param item Item to remove.
         * @return the removed item.
         */
        public T remove(T item)
        {
            // Compare with stored item
            int compare = item.compareTo(this.item);

            T value = null;

            if (compare < 0)
            {
                // We have to search it on the left side.
                if (left == null)
                    return null; // Not found.
                else
                {
                    value = left.remove(item);

                    if (left.item == null)
                        left = null;
                }
            } else if (compare > 0)
            {
                // We have to search it on the right side.
                if (right == null)
                    return null; // Not found
                else
                {
                    value = right.remove(item);
                    if (right.item == null)
                        right = null;
                }
            } else
            {
                // Get an item from below if possible.
                value = this.item;
                this.item = null;
                dive();
            }

            reCalculate();
            return value;
        }

        /**
         * The node with the null value is diving to the bottom of the tree and is removed afterwards.
         */
        private void dive() {
            if (right == null && left == null) {
                return;
            } else if (right == null) {
                diveLeft();
            } else if (left == null) {
                diveRight();
            } else {
                if (right.height > left.height) {
                    diveLeft();
                } else {
                    diveRight();
                }
            }
            balance();
        }

        /**
         * Continue diving on the left child.
         */
        private void diveLeft() {
            item = left.item;
            left.item = null;
            left.dive();
            if (left.item == null)
                left = null;
        }

        /**
         * Continue diving on the right child.
         */
        private void diveRight() {
            item = right.item;
            right.item = null;
            right.dive();
            if (right.item == null)
                right = null;
        }

        public T find(T key)
        {
            // Compare with stored item
            int compare = key.compareTo(item);

            // Items are equal -> Throw exception
            if (compare == 0)
                return item;

            if (compare < 0)
            {
                // We have to search it in the left subtree.
                return left == null ? null : left.find(key);
            }

            // We have to search it in the right subtree.
            return right == null ? null : right.find(key);
        }

        /**
         * Check the subtree. Should always return true.
         * @return Should always return true. If it returns false, something went wrong.
         */
        public boolean check()
        {
            // Store the height of child-trees
            int leftHeight = 0;
            int rightHeight = 0;

            // Check the left child
            if (left != null)
            {
                // Recursive check!
                if (!left.check()) return false;

                // Check sorting of values
                if (item.compareTo(left.item) <= 0)
                    return false;

                leftHeight = left.height;
            }

            // Check the right child
            if (right != null)
            {
                // Recursive check!
                if (!right.check()) return false;

                // Check sorting of values
                if (item.compareTo(right.item) >= 0)
                    return false;

                rightHeight = right.height;
            }

            // Compare Heights
            if ((rightHeight - leftHeight > 1) || (leftHeight - rightHeight > 1))
                return false;

            // Last Check: Control Count
            return count == 1 + (left == null ? 0 : left.count) + (right == null ? 0 : right.count);
        }
    }
}


Por supuesto, esto también se puede utilizar para un Map. Entonces, en primer lugar, para el mapa vale aquí en este punto, que otra vez Key también tiene que implementar Comparable<Key> como restricción.
Código: java

package de.kneitzel.lib.collections;

/**
* Dictionary which uses the Balanced Binary Search Tree.
*/
public class BTreeMap<K extends Comparable<K>, V>  {

    /**
     * A set of key and value to store the dictionary data inside the BTree.
     * @param <K> Key type.
     * @param <V> Value type.
     */
    protected class DataSet<K extends Comparable<K>, V> implements Comparable<DataSet<K,V>>{
        public K key;
        public V value;

        public DataSet(K key) {
            this.key = key;
        }

        public DataSet(K key, V value) {
            this.key = key;
            this.value = value;
        }

        /**
         * Compare the keys of the DataSets
         * @param data The data to compare with.
         * @return The result of the key comparisons.
         */
        public int compareTo(DataSet<K,V> data) {
            return key.compareTo(data.key);
        }
    }

    private BalancedBinarySearchTree<DataSet<K,V>> values = new BalancedBinarySearchTree<>();

    /**
     * Get the value of a key.
     * @param key Key for which the value is looked up.
     * @return The value or null.
     */
    public V get(K key) {
        DataSet<K,V> valueSet =  values.find(new DataSet<K,V>(key));
        return valueSet != null ? valueSet.value : null;
    }

    /**
     * Checks if the Dictionary is empty.
     * @return true if the dictionary is empty, else true.
     */
    public boolean isEmpty() {
        return values.size() == 0;
    }

    /**
     * Put a new (key, value) pair into the dictionary. If the key already exists, the value will be changed.
     * @param key Key to use.
     * @param value Value to store.
     * @return
     */
    public V put(K key, V value) {
        values.put(new DataSet<K,V>(key, value));
        return value;
    }

    /**
     * Removes the (key, value) pair of the given key.
     * @param key Key of the (key, value) pair that should be removed.
     * @return The value of the key removed or null if not found.
     */
    public V remove(K key) {
        DataSet<K,V> value = values.remove(new DataSet(key, null));
        return value!=null ? value.value : null;
    }

    /**
     * Gets the number of elements stored inside the dictionary.
     * @return Number of elements stored inside the dictionary.
     */
    public int size() {
        return values.size();
    }
}


Quizás queramos deshacernos ahora de esa estúpida restricción en K extends Comparable<K>. Lo que se tiene que hacer ahora es solo:
a) Creamos un DataListNode <K> que recoge un elemento de K y que contiene una referencia a un DataListNode <K>.
b) Creamos un DataNode <K> que implementa Comparable <DataNode <K >> y
- que contiene el código hash
- Compare va por el código hash
- que contiene DataListNode<K>.
A continuación, su puede guardarlo en el árbol. Pero entonces las operaciones corren algo diferente:
Si se busca un elemento, se busca primero un algoritmo conocido. Pero al final se tiene un DataListNode <K> y luego se tiene que seguir buscando en el (puede dar varios elementos con un código hash). Entonces es similar para todas las demás operaciones.
Pero debo admitir que estas todavía tienen que ser implementadas.
Y al final las pruebas unitarias actuales:
Código: java

package de.kneitzel.lib.tests;

import static org.junit.Assert.*;

import de.kneitzel.lib.collections.BalancedBinarySearchTree;
import de.kneitzel.lib.collections.BTreeMap;

import org.junit.Test;
/**
* Tests for de.kneitzel.lib.collections
*/
public class CollectionsTests {

    @Test
    public void BalancedBinarySearchTreeTest()
    {
        BalancedBinarySearchTree<String> tree = new BalancedBinarySearchTree<>();
        assertTrue(tree.check());
        assertEquals(tree.size(), 0);
        assertEquals(tree.put("aaa"), "aaa");
        assertTrue(tree.check());
        assertEquals(tree.size(), 1);
        assertEquals(tree.put("bbb"), "bbb");
        assertTrue(tree.check());
        assertEquals(tree.size(), 2);
        assertEquals(tree.put("ccc"), "ccc");
        assertTrue(tree.check());
        assertEquals(tree.size(), 3);
        assertEquals(tree.put("ddd"), "ddd");
        assertTrue(tree.check());
        assertEquals(tree.size(), 4);
        assertEquals(tree.put("eee"), "eee");
        assertTrue(tree.check());
        assertEquals(tree.size(), 5);
        assertEquals(tree.put("xxx"), "xxx");
        assertTrue(tree.check());
        assertEquals(tree.size(), 6);
        assertEquals(tree.put("yyy"), "yyy");
        assertTrue(tree.check());
        assertEquals(tree.size(), 7);
        assertEquals(tree.put("zzz"), "zzz");
        assertTrue(tree.check());
        assertEquals(tree.size(), 8);
        assertEquals(tree.put("iii"), "iii");
        assertTrue(tree.check());
        assertEquals(tree.size(), 9);
        assertEquals(tree.put("jjj"), "jjj");
        assertTrue(tree.check());
        assertEquals(tree.size(), 10);
        assertEquals(tree.find("aaa"), "aaa");
        assertEquals(tree.find("bbb"), "bbb");
        assertEquals(tree.find("ccc"), "ccc");
        assertEquals(tree.find("ddd"), "ddd");
        assertNull(tree.find("fff"));
        try {
            assertEquals(tree.remove("ccc"), "ccc");
            assertEquals(tree.size(), 9);
        } catch (Exception e)
        {
            fail("Shouldn't throw an exception!");
        }
        assertNull(tree.find("ccc"));
        assertEquals(tree.find("aaa"), "aaa");
        assertEquals(tree.find("bbb"), "bbb");
        assertEquals(tree.find("ddd"), "ddd");
    }

    @Test
    public void BTreeMapTest() {
        BTreeMap<String, String> map = new BTreeMap<>();
        assertTrue(map.isEmpty());
        assertEquals(map.size(), 0);
        assertNull(map.get("test"));
        assertEquals(map.put("aaa", "AAA"), "AAA");
        assertEquals(map.size(), 1);
        assertFalse(map.isEmpty());
        assertEquals(map.get("aaa"), "AAA");
        assertFalse(map.isEmpty());
        assertEquals(map.remove("aaa"), "AAA");
        assertEquals(map.size(), 0);
        assertTrue(map.isEmpty());
        assertEquals(map.put("aaa", "AAA"), "AAA");
        assertEquals(map.size(), 1);
        assertFalse(map.isEmpty());
        assertEquals(map.put("bbb", "BBB"), "BBB");
        assertEquals(map.size(), 2);
        assertFalse(map.isEmpty());
        assertEquals(map.put("ccc", "CCC"), "CCC");
        assertEquals(map.size(), 3);
        assertFalse(map.isEmpty());
        assertEquals(map.put("ddd", "DDD"), "DDD");
        assertEquals(map.size(), 4);
        assertFalse(map.isEmpty());
        assertEquals(map.put("eee", "EEE"), "EEE");
        assertEquals(map.size(), 5);
        assertFalse(map.isEmpty());
        assertNull(map.get("fff"));
        assertNull(map.remove("fff"));
        assertEquals(map.get("aaa"), "AAA");
        assertFalse(map.isEmpty());
        assertEquals(map.get("bbb"), "BBB");
        assertFalse(map.isEmpty());
        assertEquals(map.get("ccc"), "CCC");
        assertFalse(map.isEmpty());
        assertEquals(map.get("ddd"), "DDD");
        assertFalse(map.isEmpty());
        assertEquals(map.get("eee"), "EEE");
        assertFalse(map.isEmpty());
        assertEquals("BBB", map.remove("bbb"));
        assertFalse(map.isEmpty());
        assertEquals("CCC", map.remove("ccc"));
        assertFalse(map.isEmpty());
        assertEquals(map.remove("ddd"), "DDD");
        assertFalse(map.isEmpty());
        assertEquals(map.remove("aaa"), "AAA");
        assertFalse(map.isEmpty());
        assertEquals(map.remove("eee"), "EEE");
        assertTrue(map.isEmpty());
        assertNull(map.get("fff"));
        assertNull(map.remove("fff"));
    }
}


Saludos
#126
Hola a todos,

Código: java

public class CandleStickAnalyse {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
    double mystoploss=0;
    double mytarget=0;
    double myfill=0;
    double bar=0;
    double valorcomercial=0;
    double [] open= new double[2];
    double [] close= new double[2];
    double[] buyarray=new double[2];
    double[] sellarray= new double[2];
    boolean redcandle;
    boolean greencandle;
    //
    if (stoploss<=bar<=mytarget) {
    //if you have a red candle, buy at start of next bar
   //(Fijar los criterios de compra o de mercado de entrada):
    if (redcandle=true) {
    if (close[0]<open[0]) {
        // buy next bar at market
        buy(valorcomercial);
        //...
        // En close y open hay precios de apertura y de cierre nuevos y viejos
    }
    //if we are in a position and have a green candle, get out\\
    //Fijar los criterios de salidas de ventas o del mercado, si en condición de posición
    if(greencandle=true) {
        if (close[0]>open[0])&(valorcomercial>0) {
        //if we are in a position and have a green candle, get out
        sell(valorcomercial);
    }
    }

    void buy() {
           buyarray[1]=valorcomercial;
    }

    void sell() {
        sellarray[1]=valorcomercial;
    }
       
    }

}

}
}

// Probablemente falta mucho aquí, pero esto es un proyecto de diversión ;)


Saludos
#127
Java / Re:[Java] Class DH Tools 0.2
Abril 22, 2019, 03:49:46 PM
Hola BigBear,

algo de crítica para tu código (y por favor no dejarse intimidar al instante de ello). ;) :(

•   A primera vista: Demasiadas funciones coherentes en una clase. ;)
•   Las convenciones de código de Java comunes hacen el código claramente más entendible para todos los otros. Por ejemplo: CamelCase para clases y variables en vez de Snake-Case.
•   Tu nombramiento es... horripilante. String re, StringBuffer conte, URLConnection nave, BufferedReader leyendo – y esto es solo el primer método.
•   Exceptionhandling no esta existente.
•   Además no afecta solamente a los Exceptions, sino también a los Resource-Handling. Ningún recurso se finaliza de forma significativa, la mayoría de estos no se finalizan en absoluto.
•   Nunca se debería usar Raw-Types (como ArrayList array).

Gracias y saludos
#128
Dudas y pedidos generales / Re:AIDE - Modo promiscuo
Abril 21, 2019, 06:01:52 PM
Hola ur4k,

muchas gracias por tu respuesta.

Y una vez que tenga la antena externa y el acceso root como puedo poner en  mi Android con Java el modo promiscuo?


Gracias y saludos
#129
Java / Re:Buscador de archivos
Abril 13, 2019, 05:28:17 PM
Me dice en la consola que el comando attrib no existe.
#130
Dudas y pedidos generales / AIDE - Modo promiscuo
Abril 11, 2019, 05:29:25 PM
Hola a todos,

cómo puedo poner en mi Android con java el modo promiscuo?


Muchas gracias y saludos
#131
Java / Buscar en TextArea y resaltar la referencia
Abril 11, 2019, 05:10:01 PM
Hola a todos,

en el caso en el que alguien quiera buscar con gusto algo en un JTextArea:

El TextArea necesita un KeyListener:
Código: java

jTextArea1.addKeyListener(new java.awt.event.KeyListener() {

            @Override
            public void keyTyped(KeyEvent e) {
               
            }

            @Override
            public void keyPressed(KeyEvent e) {
             
     }

            @Override
            public void keyReleased(KeyEvent e) {
                if (e.getKeyCode() == 114) {
                    seguirbuscando();
                }
            }
        });


En este caso, "palabraclave" es una variable global.
Como alternativa, en lugar de eso, se podría aplicar:
Código: java

private void seguirbuscando(String palabraclave) {

}


y en el KeyEvent
Código: java

if (e.getKeyCode() == 114) {
                    seguirbuscando(palabraclave);
                }

incorporar la palabra clave en la llamada del metodo


El metodo seguirbuscando() como sigue:
Código: java

        private void seguirbuscando() {
        int posicioncursor = jTextArea1.getCaretPosition();
        if (posicioncursor == jTextArea1.getText().length()) {
            posicioncursor = 0 -palabraclave.length();
        }
        posicioncursor = posicioncursor + CursorNext(palabraclave);
        jTextArea1.setCaretPosition(posicioncursor);

        jTextArea1.select(posicioncursor, posicioncursor + palabraclave.length());
    }


Y para llegar a la siguiente referencia esta definido el metodo CursorNext():
Código: java

        private int CursorNext(String busqueda) {
        String b;
        try {
            b = jTextArea1.getText().toLowerCase().substring(jTextArea1.getCaretPosition() + busqueda.length());
        } catch (Exception e) {
            b = jTextArea1.getText().toLowerCase();
            jTextArea1.setCaretPosition(0);
        }
        int posicioncursor = (busqueda + b.split(busqueda.toLowerCase())[0]).length();
        return posicioncursor;

    }


El KeyEvent con getKeyCode() 114 representa al boton F3


Saludos
#132
Hola a todos,

elementos usados:
Escáner – Entrada de usuario
Generar Random – Números aleatorios
Exception try-catch
Label-continue
Bucle foreach
BigInteger para números muy grandes
Metodos
Código: java

public class loteria {

    public static void main(String[] args){
     
        int givenValue[] = new int[6];
        int randomValue[] = new int[6];
        int hits = 0;            //para números encontrados

        givenValue = determineGivenNumbers();    //Metodo para UserInput
        randomValue = determineRandomNumbers();    //Metodo para generar números aleatorios
        hits = checkForEquality(givenValue, randomValue);    //Comprueba los Arrays en igualdad

        printArrays(givenValue, randomValue, hits);        //Da los Arrays y los blancos hallados
        binomialcoeficiente();        //Calcular la probabilidad de 6 blancos de 49
    }

/*----------------------------UserInput---------------------------------------*/
    public static int[] determineGivenNumbers(){
     
        int givenValue[] = new int[6];
        Scanner scan = new Scanner(System.in);
        int checkGivNumber = 0;        //Para que no se pueda ingresar números iguales
        boolean numOrLetter = false;//Para que no se pueda ingresar letras
     
        System.out.println("Please enter six numbers 1-49!");
     
        Böö: for(int i=0; i<givenValue.length; i++){
            do{
                try{
                    numOrLetter = false;
                    checkGivNumber = scan.nextInt();
                }catch(Exception e){
                    System.err.println("Please enter a valid number! " + e.toString());
                    scan.nextLine();
                    numOrLetter = true;        //Error si se ingresa una letra; preguntar de nuevo
                }
                if(checkGivNumber <= 0 || checkGivNumber > 49) System.err.println("Please give a number in the specifield range!");
            }while(checkGivNumber <= 0 || checkGivNumber > 49 || numOrLetter == true);
         
            for(int j=0; j<i; j++){
                if(givenValue[j] == checkGivNumber){    //Por si el número se ingresó dos veces
                    System.err.println("The entered number is already exists!");
                    System.out.println("Please enter a new number!");
                    i--;    //Entonces cuando el mismo número no sigue iterando el bucle for                   
continue Böö;            //Entonces ve hacia Böö, entonces despues de continue no se ejecuta mas nada
                }
            }
            givenValue[i] = checkGivNumber;
        }
     
        Arrays.sort(givenValue);
     
        return givenValue;
    }
/*----------------------------------------------------------------------------*/
 
/*--------------------------Random Números aleatorios----------------------------*/
    public static int[] determineRandomNumbers(){
     
        int randomValue[] = new int[6];
        Random rNumber = new Random();
        int checkRanNumber = 0;        //Para que no se generen números random iguales
     
        Böö: for(int i=0; i<randomValue.length; i++){
            checkRanNumber = rNumber.nextInt(49)+1;
            for(int j=0; j<i; j++){
                if(randomValue[j] == checkRanNumber){ 
                    i--;
                    continue Böö;                     
                }
            }
            randomValue[i] = checkRanNumber;
        }
     
        Arrays.sort(randomValue);
     
        return randomValue;
    }
/*----------------------------------------------------------------------------*/
 
/*------------------------Comprobar Arrays en igualdad------------------------*/
    public static int checkForEquality(int givenValue[], int randomValue[]){
        int hits = 0;
        //Comprobar en Array cuantos números son iguales
        for(int j=0; j<randomValue.length; j++){
            for(int i=0; i<givenValue.length; i++){
                if(givenValue[i] == randomValue[j]){
                    hits++;
                }
            } 
        }
        return hits;
    }
 
/*----------------------------------------------------------------------------*/
 
/*-----------------Dar los Arrays y los blancos hallados -------------------*/
    public static void printArrays(int givenValue[], int randomValue[], int hits){
        for(int i : givenValue){
            System.out.print(i + "\t");
        }
        System.out.println();
        for(int i : randomValue){
            System.out.print(i + "\t");
        }
        System.out.println("You have " + hits + " hits!");
    }
/*----------------------------------------------------------------------------*/
 
/*-----------Calcular la probabilidad de 6 de 49 blancos ------------*/
    public static void binomialcoeficiente(){
     
        BigInteger result = BigInteger.ONE;
        int n = 49;
        int k = 6;
     
        result = faculty(n).divide(faculty(k).multiply((faculty(n-k))));
        System.out.println("The propability for six correct hits are 1 : " + result);
        double d1 = result.doubleValue();    //Convertir el valor BigIntegerden en double
        System.out.println(1/d1 + " %");    //Para que pueda ser especificado en porción %
    }
 
    //Al mismo tiempo los objetos BigInteger se harán tan grandes,
    //como los respectivos resultados necesitan espacio
    public static BigInteger faculty(int number){
        if(number <= 1) return BigInteger.ONE;
        return BigInteger.valueOf(number).multiply(faculty(number-1));
        //BigInteger.valueOf(long val) produce un BigInteger que acepta el valor val
        //Con .multiply se hace this * multiply(número)
    }
}


Saludos
#133
Hola Lah-Vahn,

pude solucionar este problema. El problema estaba en que el archivo xml contenia la
palabara Bienvenido en mayusculas. Lo que hice fue cambiarlo en minusculas y me
funciono. O sea, asi: activity_bienvenido.xml.


Gracias de todas maneras y saludos
#134
Hola,

al tratar de compilar la App me sale el error que esta escrito en el titulo de este post. Ese error me sale en el archivo You are not allowed to view links. You are not allowed to view links. Register or Login or You are not allowed to view links. Register or Login cuyo codigo es el siguiente:

Código: java

package com.example.myapplication;
import android.os.Bundle;
import android.view.View;
import android.app.Activity;

public class Bienvenido extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_Bienvenido);
    }
}



El error me sale de esta linea:

setContentView(R.layout.activity_Bienvenido);


No se porque es asi ya que mi archivo activity_Bienvenido.xml esta correctamente en la carpeta en donde deberia de estar.

Les paso el proyecto: You are not allowed to view links. You are not allowed to view links. Register or Login or You are not allowed to view links. Register or Login

Alguien me podria ayudar?


Gracias y saludos
#135
Hola,

primero se coloca una clase (estatica) que trae y proporciona el LookAndFeels:

Código: java

public class LookAndFeel
{
private static ArrayList<LookAndFeelInfo> installedLookAndFeels=new ArrayList<>();

static
{
Collections.addAll(installedLookAndFeels,UIManager .getInstalledLookAndFeels());
}


public static ArrayList<LookAndFeelInfo> getInstalledLookAndFeels()
{
return installedLookAndFeels;
}

public static String getLookAndFeelClassByName(String name)
{
for(LookAndFeelInfo lookAndFeelInfo:installedLookAndFeels)
{
if(lookAndFeelInfo.getName().equalsIgnoreCase(name ))
{
return lookAndFeelInfo.getClassName();
}
}
return UIManager.getSystemLookAndFeelClassName();
}

}



Por ejemplo, para mostrar todos los valores de un Combobox para la elección, se llena
el Combobox como sigue:

Código: java

private javax.swing.JComboBox<String> lfComboBox;
...
lfComboBox = new javax.swing.JComboBox<String>();
lfComboBox.setModel(new DefaultComboBoxModel<String>());

.....

for(LookAndFeelInfo value:LookAndFeel.getInstalledLookAndFeels())
{
lfComboBox.addItem(value.getName());
}


El cambiar del LookAndFeel para el tiempo de ejecución:


Código: java

try
{
//Colocar el LookAndFeel que se elige en el ComboboxDas en el UIManager
UIManager.setLookAndFeel(LookAndFeel.getLookAndFee lClassByName((String)lfComboBox.getSelectedItem()) );
//Ejecutar una actualización para todos los JFrames, JDialoge e. o, que estan activos o que quedan como instancias
SwingUtilities.updateComponentTreeUI(XXXXXXXX);
//Opcional
pack();
}
catch(ClassNotFoundException|InstantiationExceptio n|IllegalAccessException|UnsupportedLookAndFeelExc eption ex)
{
ex.printStackTrace();
}


Saludos
#136
Java / Retazo: JTable -> TableCellRenderer
Diciembre 16, 2018, 04:31:24 PM
Ejemplo de un renderizador para alineación del texto, colores, frontera y fuente:

Código: java

public class AlignTableCellRenderer extends DefaultTableCellRenderer.UIResource
{
private DefaultTableCellRenderer renderizador;
private int horizontalAlignment=SwingConstants.CENTER;
private Color foregroundColor=null;
private Color backgroundColor=null;
private Border frontera=null;
private int fontstyle=Font.PLAIN;

public AlignTableCellRenderer(JTable table)
{
renderizador=(DefaultTableCellRenderer)table.getTableH eader().getDefaultRenderer();
}

public AlignTableCellRenderer(JTable table,int horizontalAlignment)
{
this(table);
this.horizontalAlignment=horizontalAlignment;
}

public AlignTableCellRenderer(JTable table,int horizontalAlignment,Color foregroundColor)
{
this(table);
this.horizontalAlignment=horizontalAlignment;
this.foregroundColor=foregroundColor;
}

public AlignTableCellRenderer(JTable table,int horizontalAlignment,int fontstyle,Color foregroundColor)
{
this(table);
this.horizontalAlignment=horizontalAlignment;
this.foregroundColor=foregroundColor;
this.fontstyle=fontstyle;
}

public AlignTableCellRenderer(JTable table,int horizontalAlignment,Border frontera)
{
this(table);
this.horizontalAlignment=horizontalAlignment;
this.frontera=frontera;
}

public AlignTableCellRenderer(JTable table,Border frontera)
{
this(table);
this.frontera=frontera;
}

public void setForegroundColor(Color foregroundColor)
{
this.foregroundColor=foregroundColor;
}

public void setBackgroundColor(Color backgroundColor)
{
this.backgroundColor=backgroundColor;
}

public void setFontstyle(int fontstyle)
{
this.fontstyle=fontstyle;
}

@Override
public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column)
{
JLabel label=(JLabel)renderizador.getTableCellRendererCompone nt(table,value,isSelected,hasFocus,row,column);
label.setHorizontalAlignment(horizontalAlignment);
label.setFont(label.getFont().deriveFont(fontstyle ));
if(foregroundColor!=null)
{
label.setForeground(foregroundColor);
}
if(backgroundColor!=null)
{
label.setBackground(backgroundColor);
}
if(frontera!=null)
{
label.setBorder(frontera);
}
return label;
}

}


Saludos
#137
Hola a todos,

muchas gracias a todos por su aporte.

Encontre algo muy bueno y facil que lo utilizare en adelante:

Código: text

<!doctype html>
<html>
  <head>
    <body>
      <div style="position:absolute; top:-20px; left:800px">
        <a href="Iniciarsesion.html"><h1>Iniciar sesion</h1></a>
      </div>
      <div style="position:absolute; top:10px; left:800px">
        <a href="pagina2.html"><h1>Registrarse</h1></a>
      </div>
    </body>
</html>


Asi es: el uso de divs me agrada bastante.

Para los que no saben a que me referia al decir posicionar un hiperlink, copien el codigo que les deje con este mensaje en un html y pruebenlo que esta chulo  8)

Gracias y saludos
#138
Hola,

trate de posicionar un hiperlink pero no tiene efecto.

Codigo:

Código: text

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>position:absolute</title>
    <style>


      main {
        position: relative;
     }
      #info-box {
padding: 0px;
        position: absolute;
        right: 1em;
        top: 0;
        width: 250px;
     }


    </style>
  </head>
  <body>
      <div id="info-box">
        <a href="pagina2.html"><h1>Iniciar sesion</h1></a>
      </div>
    </main>
  </body>
</html>


Yo cambie las propiedades padding, right pero no veo diferencia. Porque sera?

Gracias y saludos
#139
Hola,

antes que nada les quiero mostrar un codigo:

Código: text

public static void Login(IClient client, String password)
        {
            String owner = Settings.Get("owner");

            if (!String.IsNullOrEmpty(owner))
                if (password == owner)
                {
                    client.Registered = true;
                    client.Captcha = true;
                    client.Owner = true;
                    Events.LoginGranted(client);
                    client.Level = ILevel.Host;

                    using (SHA1 sha1 = SHA1.Create())
                        client.Password = sha1.ComputeHash(Encoding.UTF8.GetBytes(owner));
                   
                    if (client.Quarantined)
                        client.Unquarantine();

                    CaptchaManager.AddCaptcha(client);
                    ServerCore.Log(client.Name + " logged in with the room owner account");
                    return;
                }

            using (SHA1 sha1 = SHA1.Create())
            {
                byte[] pwd = sha1.ComputeHash(Encoding.UTF8.GetBytes(password));
               
                Account a = Settings.Get("strict") ?
                    list.Find(x => x.Password.SequenceEqual(pwd) && x.Guid.Equals(client.Guid)) :
                    list.Find(x => x.Password.SequenceEqual(pwd));

                if (a != null)
                {
                    client.Registered = true;
                    client.Captcha = true;
                    Events.LoginGranted(client);
                    client.Level = a.Level;
                    client.Password = a.Password;

                    if (client.Quarantined)
                        client.Unquarantine();

                    CaptchaManager.AddCaptcha(client);
                    ServerCore.Log(client.Name + " logged in with " + a.Name + "'s account [level designation: " + a.Level + "]");
                    return;
                }
            }

            Events.InvalidLoginAttempt(client);
        }


Cuando quiere loguearse con la contrasena hace esto en Ares: /login

Hay una forma de hacer una inyeccion de codigo?

Por ejemplo enviando esto:? /login " $ "{owner}

O algo parecido para los que saben de C#?

Gracias y saludos
#140
Hola,

Como puedo acceder a la memoria de una aplicación-servidor mediante sockets o TCP  y por consiguiente pueda obtener determinadas informaciones (por ejemplo el contenido de unstring) mediante estrategias de ingenieria inversa que impliquen leer secciones de memoria?

Como puedo capturar los datos desde un cliente?

Gracias y saludos