writing data into .dat file in 3 columns using java - java

I want to write data generated in loops in my java code into a .dat file and in three columns so that I could use this .dat file to draw plots in matlab or gnuplot. could you help me please.
public static initialpop evolalgorithm(initialpop Population, File results) throws IOException {
initialpop newPopulation = new initialpop(mu+landa,false);
double AverageFit = Population.chooseBests(mu);
double LeastParentsFitness= Population.getroute(mu-1).fitness();
int Alived=mu;
for(int i=0;i<Alived;i++)
{
newPopulation.saveroute(i, Population.getroute(i));
}
for (int i = Alived; i < newPopulation.populationSize(); i++) {
route child = inheritance(Population);
newPopulation.saveroute(i, child);
}
for (int i = Alived; i < newPopulation.populationSize(); i++) {
mutate(newPopulation.getroute(i));
}
double bestIndividualFitness=newPopulation.getFittest().fitness();
return newPopulation;}
I want to have a column of values of AverageFit, a column of values of LeastParentsFitness and onother column for bestIndividualFitness in my data file. these values should be added to a file, each time this function evolalgorithm is called.

Related

NegativeArraySizeException, DataProvider, Excel

I'd like to implement the data from Excel file to different tests depending on the scenario correct data/invalid one, however when I want to get the cell value I get the "NegativeArraySizeException".
The first row has just a title so I don't want to read it, that's why I have the parameters [rows-1].
Could you please indicate what is my mistake?
Thank you
public class SignInTest extends Driver {
#BeforeMethod
public void setUp() {
Driver.initConfiguration();
}
public Object[][] getData(String excelPath, String sheetName) {
int rows = excel.getRowCount(sheetName);
int cols = excel.getColumnCount(sheetName);
Object[][] data = new Object[rows - 1][1];
excel = new ExcelReader(excelPath);
for (int rowNum = 1; rowNum < rows; rowNum++) {
for (int colNum = 0; colNum < cols; colNum++) {
data[rowNum - 1][colNum] = excel.getCellData(sheetName, colNum, rowNum);
}
}
return data;
}
#DataProvider(name = "credentials")
public Object[][] getCredentials() {
Object[][] data = getData(excelPath, sheetName);
return data;
}
#Test(dataProviderClass = DataProviders.class, dataProvider = "credentials")
public void loginWithCorrectCredentials(String email, String password) {
HomePageActions hp = new HomePageActions();
SignInActions sign = new SignInActions();
DataProviders dp = new DataProviders();
dp.getData(excelPath, "correctData");
System.out.println("email " + email);
System.out.println("password " + password);
}
This function "excel.getRowCount(sheetName)"
On this line:
int rows = excel.getRowCount(sheetName);
Is returning 0 (or possibly null), thus when you do rows-1, you get a number less than zero. I should hope that much is obvious. So the question becomes WHY?
Things to look for in troubleshooting:
Is the getColumnCount also returning zero? If so, this points to a possible
error in the worksheet reference.
Is the sheetName actually correctly being passed into the function?
Can you insert an explicit value into a specific place on the worksheet? Meaning is that reference working? Throw in a test line and see what happens.
What happens if you hard set the array to say:
Object[][] data = new Object[100][1];
My gut is telling me you have an issue with the reference to the worksheet, but without knowing more about your worksheet referencing, it's impossible to know for sure.
I hope some of this points you in the right direction and gets you going. Good luck!

Apache POI Java - Write to excel and dynamically update cells

My java spring boot app needs to create a new excel file based on the contents of my DB. My current solution places all the data from my DB and inserts it in my excel sheet, but I want to improve it by not stating what the cell values are. For example, although it works, my solution has 34 fields so I am stating the userRow.createCell line 34 times for each field which is repetitive. Ideally I want to say create the cell(n) and take all the values from each row in the DB. How can this be done? Another for loop within this for loop? Every example I looked at online seems to specifically state what the cell value is.
List<CaseData> cases = (List<CaseData>) model.get("cases");
Sheet sheet = workbook.createSheet("PIE Cases");
int rowCount = 1;
for (CaseData pieCase : cases) {
Row userRow = sheet.createRow(rowCount++);
userRow.createCell(0).setCellValue(pieCase.getCaseId());
userRow.createCell(1).setCellValue(pieCase.getAcknowledgementReceivedDate());
}
Use the Reflection API
Example:
try {
Class caseDataObj = CaseData.class;
Method [] methods = caseDataObj.getDeclaredMethods();
Sheet sheet = workbook.createSheet("PIE Cases");
int rowCount = 1;
for(CaseData cd : cases) {
int cellIndex = 0;
Row userRow = sheet.createRow(rowCount++);
for (Method method : methods) {
String methodName = method.getName();
if(methodName.startsWith("get")) {
// Assuming all getters return String
userRow.createCell(cellIndex++).setCellValue((String) method.invoke(cd));
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
There are probably many ways to do this, You can try something like this, this is how I usually go about it for things like what you are doing.
public enum DATA {
CASE_ID(0),
ACK_RECIEVED(1),
ETC(2);
//ETC(3) and so on
public int index;
DATA(int index) {
this.index = index;
}
public Object parse(CaseData data) throws Exception {
switch (this) {
case CASE_ID:
return data.getCaseId();
case ACK_RECIEVED:
return data.getAcknowledgementReceivedDate();
case ETC:
return "etc...";
default: return null;
}
}
}
Then, the implementation is:
List<CaseData> cases = (List<CaseData>) model.get("cases");
Sheet sheet = workbook.createSheet("PIE Cases");
int rowCount = 1;
for (CaseData pieCase : cases) {
Row userRow = sheet.createRow(rowCount++);
for (DATA DAT : DATA.values()) {
userRow.createCell(DAT.index).setCellValue(DAT.parse(pieCase));
}
}

Add content that prevents page breaks inside

Using docx4j I'm adding multiple dynamically filled subTemplates to my main template.
I don't want to have page breaks inside those subTemplates (unless even a whole page is too small for one).
Therefore: If a subTemplate would break inside, I want to move the whole subTemplate to the next page.
How do I do this?
My code so far:
//...
WordprocessingMLPackage mainTemplate = getWp();//ignore this method
List<WordprocessingMLPackage> projectTemplates = new ArrayList<>();
List<Project> projects = getProjects();//ignore this method
for (Project project : projects) {
WordprocessingMLPackage template = getWpProject();//ignore this method
//fill template with content from project
//...
projectList.add(template);
}
//Here's the part that will have to be changed I think:
//Since the projectTemplate only consists of tables I just added all its tables to the main template
for (WordprocessingMLPackage temp : projectTemplates){
List<Object> tables = doc.getAllElementFromObject(temp.getMainDocumentPart(), Tbl.class);
for (Object table : tables) {
mainTemplate.getMainDocumentPart().addObject(table);
}
}
If you can think of a way to change the .docx template with Word to achieve my goal feel free to suggest it.
And if you have suggestions for code improvement in general just write a comment.
I made this "workaround" that works nicely for me:
I count all rows together and also check if the text inside the rows breaks (with an approximate threshold).
Then I add the rows of each project up and as soon as there are too many rows I insert a break before the current project and start over.
final int maxRowCountPerPage = 44;
final int maxLettersPerLineInDescr = 55;
int totalRowCount = 0;
WordprocessingMLPackage mainTemplate = getWp();
//Iterate over projects
for (Project project : getProjects()) {
WordprocessingMLPackage template = this.getWpProject();
String projectDescription = project.getDescr();
//Fill template...
//Count the lines
int rowsInProjectDescr = (int) Math.floor((double) projectDescription.length() / maxLettersPerLineInDescr);
int projectRowCount = 0;
List<Object> tables = doc.getAllElementFromObject(template.getMainDocumentPart(), Tbl.class);
for (Object table : tables) {
List<Object> rows = doc.getAllElementFromObject(table, Tr.class);
int tableRowCount = rows.size();
projectRowCount += tableRowCount;
}
//System.out.println("projectRowCount before desc:" + projectRowCount);
projectRowCount += rowsInProjectDescr;
//System.out.println("projectRowCount after desc:" + projectRowCount);
totalRowCount += projectRowCount;
//System.out.println("totalRowCount: " + totalRowCount);
//Break page if too many lines for page
if (totalRowCount > maxRowCountPerPage) {
addPageBreak(wp);
totalRowCount = projectRowCount;
}
//Add project template to main template
for (Object table : tables) {
mainTemplate.getMainDocumentPart().addObject(table);
}
}
If you notice a way to make the code nicer, let me know in a comment!

How to create nested object and array in parquet file?

How do I create a parquet file with nested fields? I have the following:
public static void main(String[] args) throws IOException {
int fileNum = 10; //num of files constructed
int fileRecordNum = 50; //record num of each file
int rowKey = 0;
for (int i = 0; i < fileNum; ++i) {
Map<String, String> metas = new HashMap<>();
metas.put(HConstants.START_KEY, genRowKey("%10d", rowKey + 1));
metas.put(HConstants.END_KEY, genRowKey("%10d", rowKey + fileRecordNum));
ParquetWriter<Group> writer = initWriter("pfile/scanner_test_file" + i, metas);
for (int j = 0; j < fileRecordNum; ++j) {
rowKey++;
Group group = sfg.newGroup().append("rowkey", genRowKey("%10d", rowKey))
.append("cf:name", "wangxiaoyi" + rowKey)
.append("cf:age", String.format("%10d", rowKey))
.append("cf:job", "student")
.append("timestamp", System.currentTimeMillis());
writer.write(group);
}
writer.close();
}
}
I want to create two fields:
Hobbies which contains a list of hobbies ("Swimming", "Kickboxing")
A teacher object that contains subfields like:
{
'teachername': 'Rachel',
'teacherage':50
}
Can someone provide an example how to do this in Java?
Parquet is columned (mini-storages) key-value storage... I.e. this kind of storage cannot keep nested data, but this storage accepts converting logical types of data to binary format (byte array with header that contains data to understand what kind of convertation should be applied to this data).
I'm not sure about how should you implement your converter, but basically you should work with Binary class as data container and create some converter... sample converter you can find for String data type.

Cell values not getting set for newly added rows : using apache poi

I have a table in a ppt slide. Data to the table will be read from an ArrayList (Each object in the ArrayList will contain one row data) of String[].
If the number of rows in the table is less than the size of the ArrayList, new rows will be added to match the size of the ArrayList.
Problem here is data is getting set for already existing rows but not for the newly added rows. Please find the code snippet below.
Any help/suggestion is much appreciated. Thanks in advance.
XSLFTable table = (XSLFTable) shape;
int noOfDataRows=table.getNumberOfRows()-1;
if(noOfDataRows<ap.size()) {
for(int rws=0;rws<(ap.size()- noOfDataRows);rws++) {
System.out.println(" Adding row");
table.addRow();
}
}
List<XSLFTableRow> rows = table.getRows();
for (int i = 0; i < ap.size(); i++) {
String[] awaitprop={'1','2','3','4','5','6','7','8'};
XSLFTableRow row=rows.get(i+1);
List<XSLFTableCell> cells=row.getCells();
for(int j=0;j<cells.size();j++) {
XSLFTableCell cell=cells.get(j);
cell.clearText();
XSLFTextParagraph paragraph=cell.addNewTextParagraph();
paragraph.setTextAlign(TextAlign.CENTER);
XSLFTextRun textRun=paragraph.addNewTextRun();
textRun.setFontFamily("Calibri");
textRun.setFontSize(11);
textRun.setText(awaitprop[j]);
}
}
With reference to following tutorial, at first you should create cell(s) in the new row, I guess. Then you can put a content there.
XSLFTableRow headerRow = table.addRow();
for(int i = 0; i < 3; i++) {
XSLFTableCell th = headerRow.addCell();
XSLFTextParagraph p = th.addNewTextParagraph();
XSLFTextRun r = p.addNewTextRun();
r.setText("Text");
}
I hope it helps!

Categories

Resources