Trying to verify an index number from another method - java

The first two methods are chunks out of my GUI programme. There are various text fields that allow me input data and then buttons on the GUI take this data and call different methods.
public String getTenant()
{
String theTenant = (tenantsNameText.getText());
return theTenant;
public int getPropertyNumber()
{
int propertyNumber = -1;
try{
propertyNumber = Integer.parseInt(propertyNumberText.getText());
if (properties.size() == 0){
propertyNumber = -1;
}
if (propertyNumber < 0 && propertyNumber >= properties.size()){
propertyNumber = -1;
}
}
catch(NumberFormatException exception){
}
return propertyNumber;
}
In this method I to take the data from the text field of "getTenant" and the data from the text field of "getPropertyNumber". What I'm not sure how to do is check if the property number is -1 or not, and this needs to be verified in the method "addTenant".
public void addTenant()
{
}

I possibly didn't ask the question right, but i figured it out with some help from a colleague.
public void addTenant()
{
int index = getPropertyNumber();
String newTenant = getTenant();
if(index != -1){
Property property = properties.get(index);
if(property instanceof PropertyToLet){
PropertyToLet propertyToLet = (PropertyToLet) property;
propertyToLet.addTenant(newTenant);
}
}
}

Related

Compare RDD Objects - Apache Spark

I'm fairly new into the apache spark technology and I'm having some problems while trying to analyze data I'm pulling from my files.
I have big list of genes information, and I'm pulling that information to a RDD, so far so good.
JavaRDD<Gene> inputfile = sc.textFile(logFile).map(
new Function<String, Gene>() {
#Override
public Gene call(String line) throws Exception {
String[] values = line.split("\t");
Gene gen = null;
//We are only interested in genes;
if( values.length > 2 && values[2].equalsIgnoreCase("gene") && !line.contains("#")){
String[] infoGene = values[8].split(";");
String geneId = StringUtils.substringBetween(infoGene[0], "\"");
String geneType = StringUtils.substringBetween(infoGene[2], "\"");
String geneName = StringUtils.substringBetween(infoGene[4], "\"");
gen = new Gene(geneName,values[3],values[4]);
return gen;
}
return gen;
}
}
).filter(new Function<Gene, Boolean>() {
#Override
public Boolean call(Gene gene) throws Exception {
if(gene == null)
return false;
else
return true;
}
});
The Gene class:
public class Gene implements Serializable{
String firstBp;
String lastBp;
String name;
public Gene(String name, String firstBp, String lastBp) {
this.name = name;
this.firstBp = firstBp;
this.lastBp = lastBp;
}
public String getFirstBp() {
return firstBp;
}
public String getLastBp() {
return lastBp;
}
public String getName() {
return name;
}
public String toString(){
return name + " " + firstBp + " " + lastBp;
}}
The problem starts here, I need to analyze if 2 Genes overlay, and for that I've made this simple utility function:
public static Boolean isOverlay(Gene gene1, Gene gene2){
int gene1First = Integer.parseInt(gene1.getFirstBp());
int gene1Last = Integer.parseInt(gene1.getLastBp());
int gene2First = Integer.parseInt(gene2.getFirstBp());
int gene2Last = Integer.parseInt(gene2.getLastBp());
if(gene2First >= gene1First && gene2First <= gene1Last) // FirstBp - Gene2 inside
return true;
else if (gene2Last >= gene1First && gene2Last <= gene1Last) // LastBP - Gene2 inside
return true;
else if (gene1First >= gene2First && gene1First <= gene2Last) // FirstBp - Gene1 inside
return true;
else if (gene1Last >= gene2First && gene1Last <= gene2Last) // LastBP - Gene1 inside
return true;
else
return false;
}
Now what I'm doing and I think is wrong is transforming the RDD Object into a list by doing:
List<Gene> genesList = inputfile.collect();
And iterate over that list to check if there are overlays and save to the file the results which is taking ages because I'm not using spark.
List<OverlayPair> overlayPairList= new ArrayList<OverlayPair>();
List<String> visitedGenes = new ArrayList<String>();
for (Gene gene1 : genesList){
for (Gene gene2 : genesList) {
if (gene1.getName().equalsIgnoreCase(gene2.getName()) || visitedGenes.contains(gene2.getName())) {
continue;
}
if (isOverlay(gene1, gene2))
overlayPairList.add(new OverlayPair(gene1.getName(), gene2.getName()));
}
visitedGenes.add(gene1.getName());
}
JavaRDD<OverlayPair> overlayFile = sc.parallelize(overlayPairList);
//Export the results to the file
String outputDirectory = "/Users/joaoalmeida/Desktop/Dissertacao/sol/data/mitocondrias/feup-pp/project/data/output/overlays";
overlayFile.coalesce(1).saveAsTextFile(outputDirectory);
The Overlay pair is basically an object with the 2 genes name.
Is there anyway to do this 2nd part while taking advantage of spark? Because the time complexity of those 2 for's its to big for the amount of data I currently have.
Yes, there is, you have to use RDD.cartesian function to get all the pairs and then you can basically apply the function you wrote.

Finding information stored in array by binary search

This is a small library with two books for the sake of the question, it allows the user to type in a random number, and if that number matches up with a book the title of the book is outputted. I've created a class called 'Book' which houses all the titles.
String book1, book2;
class Book {
Book (int _input, String book_1, String book_2) {
book1 = book_1 = "Read This Book";
book2 = book_2 = "How to Read a Book";
I apologize if my code is all one big mess that makes no sense...
}
}
ArrayList <Book> titles = new ArrayList <Book>(50);
public static Boolean binarySearch(String [] A, int left, int right, String V) { //binary search
int middle;
Boolean found = false;
while (found == false && left <= right) {
//If middle item == 0, returns true
middle = (left + right)/2;
int compare = A[middle].compareTo(V);
if (compare == 0) {
found = true;
} else {
if (compare >0) {
right = middle -1;
} else {
left = middle + 1;
}
}
}
if (left > right) {
return false;
} else {
return true;
}
}
Then the problem...I'm not sure how to use the binary search to actually output any information after pressing the "find" button, any ideas on what I should below to make this work?
private void findButtonActionPerformed(java.awt.event.ActionEvent evt) {
//Take inputted values which will match with book title
int input = Integer.parseInt(enterNumberField.getText());
//Store values in array
Book c = new Book (input, book1, book2);
titles.add(c);
String temp;
//calls out information in array
for (int j=0; j<=input; j++) {
for (int x=0; x<=input; x++) {
temp = titles.get(x) + "\n";
}
binarySearchField.setText("" + j); //should output book title
}
You want your binary search to return not just a true or false. You want it to return Book, the item it found, or null if it found no book matching this query. To be consistent you probably want to change the name from binarySearch, to getBook, or some other better suited name. In your case you don't want to know if an element is there, you want to get the element for use later (printing).
This is how collections are expected to behave when you query them. Just check out the get methods from any of the Java collections and you will see they do the same, returning the item if it's there, or null.
Here is some example code. This is just example code! So modify as you like, and also be careful about bugs, I used your search which I'm going to assume is correct to start with. Also know that there are better many good ways of storing a key to a value, Map for example, that I'm not going to use here.
public class Book{
public String title;
public int sameTitle(String bookTitle) {
return this.title.compareTo(bookTitle);
}
}
public static Book getBook(Book [] A, int left, int right, String bookTitle) { //binary search
int middle;
while (left <= right) {
//If middle item == 0, returns true
middle = (left + right)/2;
int compare = A[middle].sameTitle(bookTitle);
if (compare == 0) {
return A[middle];
} else {
if (compare >0) {
right = middle -1;
} else {
left = middle + 1;
}
}
}
return null;
}
// example use of getting and using the book
Book b = getBook(...);
if (b != null){
System.out.println("Success! you found the book " + b);
}
Try to change this line:
int compare = A[middle].compareTo(V);
if (compare == 0) {
found = true;
To:
int compare = A[middle].compareTo(V);
if (compare == 0) {
return A[middle];
And be sure to get the result in your findButtonActionPerformed method.
Also, it appears to be a mistake in your code... Should not A be a book array instead of a string array?

constructing a 2D array and assigning

package homework3;
public class DoubleMatrix
{
private double[][] doubMatrix;
public DoubleMatrix (int row, int col)
{
if(row > 0 & col > 0)
{
makeDoubMatrix(1,1);
}
else
{
row = 1;
col = 1;
}
}
public DoubleMatrix(double[][] tempArray)
{
int k = tempArray.length;
if(tempArray != null)
{
for(int i = 0; i < tempArray.length;i++)
{
if(k== tempArray[i].length)
{
}
}
}
else
{
makeDoubMatrix(1,1);
}
}
}
This is what i was supposed to start my assignment with:
Write a class called DoubleMatrix in which you declare a 2-dim. array of doubles (I'm calling it doubMatrix) as a private instance variable. Include the following constructors or instance methods (NO static METHODS HERE):
constructor with an int for the first dimension (be sure it's > 0, set to 1 if not), and an int for the second dimension (be sure it's > 0, set to 1 if not) and call the makeDoubMatrix private instance method (see below)
another constructor with a 2-dim. array of doubles as its parameter (assign if parameter isn't null AND if each row has the same length as the other rows), otherwise, call makeDoubMatrix with 1, 1)
can someone check that if I did the check in second constructor right? Also I left out the assigning statement in the second if because I don't know what to assign can anyone tell me what to assign since the problem only say assign but didn't say to assign to what value.
You would have to check for each row first, whether they are of same length or not. You can maintain a boolean flag variable, which you can set to false as soon as you see that the current row is not the same length as the next row.
You can try the below code, and test whether it works: -
public DoubleMatrix(double[][] tempArray)
{
if(tempArray != null)
{
boolean flag = true;
for(int i = 0; i < tempArray.length - 1;i++)
{
// Check each row with the next row
if(tempArray[i].length != tempArray[i + 1].length)
{
// as you find the row length not equal, set flag and break
flag = false;
break;
}
}
if (flag) {
doubleMatrix = tempArray;
} else {
makeDoubleMatrix(1,1);
}
} else {
makeDoubleMatrix(1, 1);
}
}
public DoubleMatrix(double[][] tempArray)
{
//Calling tempArray.length if tempArray is null will get you an error
if(tempArray != null)
{
for(int i = 0; i < tempArray.length;i++)
{
for(int j=0;j<tempArray[i].length;j++)
{
doubleMatrx[i][j] = tempArray[i][j];
}
}
}
else
{
makeDoubMatrix(1,1);
}
}
Also in Java a 2D array will always have the same number of columns in each row since it's declaration is something like int bob[][] = new int[a][b]

How to get blank cell value in apache POI XSSF

I have an issue with an Apache POI XSSF in that it is not reading blank cell value.
I hava a class that implements DefaultHandler. In that class all non-blank cells are able to read from startElement and endElement methods.
I want to read blank cells in middle of the data cells.
Can anyone provide an example of how to do so or directions as to how to debug this?
Ran into this very same problem today. I was using the XSSF event model. But XSSF wouldn't give a column element nor a value element for the blank columns. Most probably because the backing XML is that way.
The key is to check the attribute for the cell reference (you know the A1, A2, A3 that Excel uses). Attributes are passed to the startElement() callback method. We can then detect missing cell references. So if we got L1 for the previous column element and get N1 for the current column element, we know M1 is the blank/missing cell.
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
if (qName.equals("c")) {
String newColRef = atts.getValue("r");
coverColumnDistanceWithNulls(currentColRef, newColRef);
And coverColumnDistanceWithNulls() simply adds nulls for each missing cell reference between currentColRef and newColRef
private void coverColumnDistanceWithNulls(String fromColRefString, String toColRefString) {
int colRefDistance = getDistance(fromColRefString, toColRefString);
while (colRefDistance > 1) {
logger.debug("Covering distance with null");
rowValues.add(null);
--colRefDistance;
}
}
private int getDistance(String fromColRefString, String toColRefString) {
String fromColRef = getExcelCellRef(fromColRefString);
String toColRef = getExcelCellRef(toColRefString);
logger.debug("fromCol: {} toCol: {}", new Object[] {fromColRefString, toColRefString});
return excelCellReferenceOrder.get(toColRef) - excelCellReferenceOrder.get(fromColRef);
}
private String getExcelCellRef(String fromColRef) {
if (fromColRef != null) {
int i = 0;
for (;i < fromColRef.length(); i++) {
if (Character.isDigit(fromColRef.charAt(i))) {
break;
}
}
if (i == 0) {
return fromColRef;
}
else {
return fromColRef.substring(0, i);
}
}
return null;
}
Building off Sab Than's answer:
private void coverColumnDistance(String fromColRefString, String toColRefString) {
int colRefDistance = getDistance(fromColRefString, toColRefString);
while (colRefDistance > 0) {
c = getRow().addCell("");
colRefDistance--;
}
}
private int getDistance(String fromColRefString, String toColRefString) {
String fromColRef = getExcelCellRef(fromColRefString);
String toColRef = getExcelCellRef(toColRefString);
int distance = 0;
if (fromColRef == null || fromColRef.compareTo(toColRef) > 0)
return getDistance("A", toColRefString) + 1;
if (fromColRef != null && toColRef != null) {
while (fromColRef.length() < toColRef.length() || fromColRef.compareTo(toColRef) < 0) {
distance++;
fromColRef = increment(fromColRef);
}
}
return distance;
}
public String increment(String s) {
int length = s.length();
char c = s.charAt(length - 1);
if(c == 'Z') {
return length > 1 ? increment(s.substring(0, length - 1)) + 'A' : "AA";
}
return s.substring(0, length - 1) + ++c;
}
private String getExcelCellRef(String fromColRef) {
if (fromColRef != null) {
int i = 0;
for (; i < fromColRef.length(); i++) {
if (Character.isDigit(fromColRef.charAt(i))) {
break;
}
}
if (i == 0) {
return fromColRef;
}
else {
return fromColRef.substring(0, i);
}
}
return null;
}
If I remember correctly if you try and read a cell value that has not been assigned a value you get a NullPointerException or similar. You could surround the code that is examining the cell in a try-catch statement and then write your own code to deal with such scenario.
If my memory does not serve me correctly and tthe error thrown is not a NullPointerException then change the catch exception class to the relevant one.

In Java/Swing, is there a way to legally "attempt to mutate in notification"?

I was wondering if there is some sort of magic I can use to get around an IllegalStateException and allow a JTextField to "attempt to mutate in notification", or in other words to set its own text if its listener is triggered.
For your information, I am trying to program an auto-complete function which returns the most likely match in a range of 12 enums in response to a user's input in the JTextField.
Here is the code sample. You'll have to pardon my clumsy algorithm which creaks out enum results. I've highlighted the code which produces the exception with a comment:
jtfElement1.addCaretListener(new CaretListener() {
#Override
public void caretUpdate(CaretEvent e) {
String s = jtfElement1.getText();
int[] attributes = new int[13];
// iterate through each enum
for (BaseEnumAttributes b: BaseEnumAttributes.values()) {
// iterate through the length of the current text in jtfElement1
for (int i = 0; i < s.length(); i++) {
if (s.length() <= b.toString().length()) {
if (b.toString().charAt(i) == s.charAt(i)) {
// increase the number of "hits" noted for that enum
attributes[b.ordinal()] = attributes[b.ordinal()] + 1;
}
}
}
}
int priorC = 0;
int rightC = 0;
// iterate through the "array" of enums to find the highest score
for (int j = 0; j < attributes.length; j++) {
if (attributes[j] > priorC) {
priorC = attributes[j];
rightC = j;
}
}
if (!s.equals("")) {
// assign to b the Enum corresponding to the "array" with highest score
BaseEnumAttributes b = BaseEnumAttributes.values()[rightC];
iController.updateInputElement1String(b.toString());
// THIS TRIGGERS EXCEPTION
jtfElement1.setText(b.toString());
}
}
});
You are probably better off using a document filter or a custom document.
What are other listeners expected to see if the document doesn't stay the same during event dispatch?
Use SwingUtilities.invokeLater() placing all the modifications there
Maybe you can delay the setText() with a Thread to run after caretUpdate() has terminated.
i'm found on the same problem but i found an easy solution:
lock the caretUpdate() by a boolean if(false) while u'r setting the text to the jTextField than unlock it after . . something like this:
boolean caret = true;
private void listValueChanged(javax.swing.event.ListSelectionEvent evt) {
caret = false;
name.setText((String)list.getSelectedValue());
caret = true;
}
private void nameCaretUpdate(javax.swing.event.CaretEvent evt) {
if(caret){
model = new DefaultListModel();
this.fillList(name.getText());
list.setModel(model);
}
}
Create a custom Document and override insertString( )
filenameText = new JTextField(new FilenameDocument(), "", 0);
...
/**
* document which adds .xml extension if not specified
*
*/
private class FilenameDocument extends PlainDocument {
#Override
public void insertString(int offset, String insertedText, AttributeSet set)
throws BadLocationException {
if (offset == 0) {
insertedText = insertedText.trim( );
}
super.insertString(offset, insertedText, set);
if (filenameText != null) {
final int caretPos = filenameText.getCaretPosition();
String text = filenameText.getText().trim();
if (text.indexOf('.') == -1) {
filenameText.setText(text + ".xml");
filenameText.setCaretPosition(caretPos);
}
}
}
}
Note that calling setText will result in a recursive call to insertString( ), so make sure you have a stopping condition.
I'm surprised no one has answered this, but would'nt you have been better off implementing an editable JSpinner with a SpinnerListModel?

Categories