dimanche 28 juin 2015

Populate a JCombo Box with each element of Array in Java

Please forgive me, I'm new to Java.

Basically I'm trying to display every element of an Array (i.e. peopleInfo[0], peopleInfo[1], and peopleInfo[2] ) into a JComboBox. I have added elements to the Array from a text file. However when I try to display the elements of the array in the JComboBox only the first element is displayed which is not what I want.

I have attempted to correct this by using a for loop however when I did this it didn't seem to correct my problem however I don't know whether I coded it correctly.

My code currently is:

private JComboBox mainComboBox;
private JComboBox subComboBox;
private Hashtable subItems = new Hashtable();

public SplitFile() throws FileNotFoundException, IOException
{

    BufferedReader bReader = new BufferedReader(new FileReader("organisms.txt"));

    bReader.readLine(); // this will read the first line


    String line = null;
    while ((line = bReader.readLine()) != null){

        //removes the first space 
        String test = line.replaceFirst("\\s+", "");

        //used regex lookaround to split wherever there are 3 capital letters present, or where any of the tree are present
        String[] peopleInfo = test.split("(\\p{Upper}(?=\\p{Upper})\\p{Upper}\\p{Upper})|(?=Chromalveolata)|(?=Metazoa)|(?=Mycetozoa)|(?=Viridiplantae)|(?=Viruses)|\\;");

        //creates arrays for id, organism and tree
        String id = ">" + peopleInfo[0];
        String organism = peopleInfo[1];
        String tree = peopleInfo[2].replaceAll(";", "").replaceAll("\\d+.*", "");
       System.out.println(tree);
       ArrayList<String> testArray = new ArrayList<String>();
    String[] items = { tree , "Color", "Shape", "Fruit" };


    mainComboBox = new JComboBox( items );
    mainComboBox.addActionListener( this );

    getContentPane().add( mainComboBox, BorderLayout.WEST );

    //  Create sub combo box with multiple models

    //this code displays values dependent on what element is selected from the mainComboBox

    subComboBox = new JComboBox();
    subComboBox.setPrototypeDisplayValue("XXXXXXXXXX"); // JDK1.4
    getContentPane().add( subComboBox, BorderLayout.EAST );

    String[] subItems1 = { "Select Color", "Red", "Blue", "Green" };
    subItems.put(items[1], subItems1);

    String[] subItems2 = { "Select Shape", "Circle", "Square", "Triangle" };
    subItems.put(items[2], subItems2);

}}

@Override
public void actionPerformed(ActionEvent e)
{
    String item = (String)mainComboBox.getSelectedItem();
    Object o = subItems.get( item );

    if (o == null)
    {
        subComboBox.setModel( new DefaultComboBoxModel() );
    }
    else
    {
        subComboBox.setModel( new DefaultComboBoxModel( (String[])o ) );
    }
}

Any help would be much appreciated!

Thanks :)

How do I find all word combinations that add up to a certain length?

I need a little help with coming up with an algorithm to traverse through a sorted word array and finding all the possible combinations that add up to a certain length. Any help is greatly appreciated! Thanks :)

Fast array manipulation based on element inclusion in binary matrix

For a large set of randomly distributed points in a 2D lattice, I want to efficiently extract a subarray, which contains only the elements that, approximated as indices, are assigned to non-zero values in a separate 2D binary matrix. Currently, my script is the following:

lat_len = 100 # lattice length
input = np.random.random(size=(1000,2)) * lat_len
binary_matrix = np.random.choice(2, lat_len * lat_len).reshape(lat_len, -1)

def landed(input):
    output = []
    input_as_indices = np.floor(input)
    for i in range(len(input)):
        if binary_matrix[input_as_indices[i,0], input_as_indices[i,1]] == 1:
            output.append(input[i])
    output = np.asarray(output)
    return output   

However, I suspect there must be a better way of doing this. The above script can take quite long to run for 10000 iterations.

Add value in specific index array

i have array data like this.

[0] => Array (
    [id] => 1
    [id_requestor] => 1
    [jam_input] => 2015-06-20 06:00:00
    [jam_pakai] => 2015-06-28 08:00:00
    [total_poin] => 30
    )
[1] => Array (
    [id] => 2
    [id_requestor] => 2
    [jam_input] => 2015-06-20 07:00:00
    [jam_pakai] => 2015-06-28 08:00:00
    [total_poin] => 10
    )
[2] => Array (
    [id] => 3
    [id_requestor] => 3
    [jam_input] => 2015-06-20 06:30:00
    [jam_pakai] => 2015-06-28 08:00:00
    [total_poin] => 5
    )

In above data, there is total_poin. This total_poin that i use later. I want to sort total_poin array descending. But i wont to use php built in array function. Cause i have to use method from research paper like this.

for i=0 to i<main queue.size
   if jobi+1 length > jobi length then
    add jobi+1 in front of job i in the queue
end if
   if main queue.size = 0 then
    add job i last in the main queue
end if

And here is my implementation :

function LJFAlgorithm($time_str) {
        $batchData = getBatch($time_str);

        $ljf = [];
        for ($i=0; $i < count($batchData)-1; $i++) { 
            echo $batchData[$i+1]['total_poin'] ." >= ". $batchData[$i]['total_poin'] . " = " . ($batchData[$i+1]['total_poin'] >= $batchData[$i]['total_poin']);

            if ($batchData[$i+1]['total_poin'] >= $batchData[$i]['total_poin']) {
                echo ", Add " . $batchData[$i+1]['total_poin'] . " in front of " . $batchData[$i]['total_poin'];
            } else {
                echo ", Add " . $batchData[$i]['total_poin'] . " in front of " . $batchData[$i+1]['total_poin'];
            }

            echo '<br/>';
        }

        print_r($ljf);
    }

But it not work perfectly, i get one data missing. Here is my output code :

10 >= 30 = , Add 30 in front of 10
5 >= 10 = , Add 10 in front of 5

5 value not added in array. How to fix that?

Thank you very much.

How to sum two dimensional arrays in Java?

I've created a short code to practice two-dimensional arrays but I've stumbled upon a problem that I can't solve in my code. Hope you guys can help me.

Desired Output:

Enter number:1
Enter number:2
Enter number:3

NUMBERS THAT YOU ENTERED:
1
2
3

TOTAL: 6

Enter number:1
Enter number:2
Enter number:3

NUMBERS THAT YOU ENTERED:
1
2
3

TOTAL: 6

But instead I'm seeing this:

Enter number:1
Enter number:2
Enter number:3

NUMBERS THAT YOU ENTERED:
1
2
3

TOTAL: 6

Enter number:1
Enter number:2
Enter number:3

NUMBERS THAT YOU ENTERED:
1
2
3

TOTAL: 12

______________________________________________________

It's adding up every number that I input instead of just adding three numbers in each iteration. Please check the code below:

PART I

package Test;

 public class Test1 {
   private int[][] number;
   private int number1;
   public Test1(int[][]n){
      number = new int[2][3];
    for(int dx = 0;dx < number.length;dx++){
        for(int ix = 0;ix < number[dx].length;ix++){
            number[dx][ix]=n[dx][ix];
        }

    }
}

public Test1(int n){
    number1 = n;
}

public int getTotal(){
    int total = 0;

    for(int dx = 0;dx < number.length;dx++){
        for(int ix = 0;ix < number[dx].length;ix++){
            total += number[dx][ix];
        }

    }

    return total;
}

public int getNumbers(){

    return number1;
}

}

PART II

  package Test;
  import java.util.Scanner;
  public class TestMain {
  public static void main(String[]args){
    final int DIVS = 2;
    final int NUM_INSIDE = 3;
    Test1[][] t1 = new Test1[DIVS][NUM_INSIDE];
    int[][]numbers = new int[DIVS][NUM_INSIDE];
    getValues(numbers,DIVS,NUM_INSIDE,t1);

}

public static void getValues(int[][]numbers,int DIVS,int NUM_INSIDE,Test1[][] t1){
    Scanner hold = new Scanner(System.in);
    int num;
    for(int div = 0;div < DIVS;div++){
        for(int ins = 0;ins < NUM_INSIDE;ins++){
            System.out.print("Enter number:");
            numbers[div][ins]=hold.nextInt();
            num = numbers[div][ins];
            t1[div][ins] = new Test1(num);

        }
        Test1 t = new Test1(numbers);
        display(t,t1,div);

    }
}

public static void display(Test1 t,Test1[][] t1,int div){
    System.out.print("****************************\n");
    System.out.print("NUMBERS THAT YOU ENTERED:\n");

    for(int y = 0; y < t1[div].length;y++){
        System.out.print(t1[div][y].getNumbers() + "\n");
    }

    System.out.print("****************************\n");
    System.out.print("TOTAL: " + t.getTotal() + "\n");
    System.out.print("****************************\n");
}
}

Remove subarray from array when one of it's value match another arrays value (PHP)

I have two arrays:

$to_import = Array(
  [0] => Array(['native_id'] => 35339920, ['type'] => product)
  [1] => Array(['native_id'] => 22045872, ['type'] => product)
  [2] => Array(['native_id'] => 25913185, ['type'] => profile)
  [3] => Array(['native_id'] => 14354407, ['type'] => profile)
)

$existing = Array(
  [0] => Array(['native_id'] => 22045872)
  [1] => Array(['native_id'] => 25913185)
  [2] => Array(['native_id'] => 30836971)
)

I need to remove the record from the first array when the id is found in the second array, and when type matches 'profile'. So in this example, three remain:

$to_import = Array(
  [0] => Array(['native_id'] => 35339920, ['type'] => product)
  [1] => Array(['native_id'] => 22045872, ['type'] => product)
  [3] => Array(['native_id'] => 14354407, ['type'] => profile)
)

I have found similar questions, but I can't work out how to apply them to my requirements. This answer looks like it is close to what I want, but I can't get it to work, my knowledge is failing me.

Splitting NSString doesn't work in Swift

I have a long string i need split into an array by splitting when "|||" is found

I can split a String using two ways i found at SO

First one is this

 func split(splitter: String) -> Array<String> {
    let regEx = NSRegularExpression(pattern: splitter, options: NSRegularExpressionOptions(), error: nil)!
    let stop = "<SomeStringThatYouDoNotExpectToOccurInSelf>"
    let modifiedString = regEx.stringByReplacingMatchesInString (self, options: NSMatchingOptions(),
        range: NSMakeRange(0, count(self)),
        withTemplate:stop)
    return modifiedString.componentsSeparatedByString(stop)
}

Second one is this

var splt = str.componentsSeparatedByString("[\\x7C][\\x7C][\\x7C]")

I tried using the delimiter as both "[\x7C][\x7C][\x7C]" and "|||" and i tried using both String and NSString

Nothing seems to work though, i just get an array with the original string in it