File data not being read processing - processing

I am absolutely stuck, my file data is not being read in processing using loadStrings();. I have tried everything. Here is my code:
Main Class
Student[] studentList;
String[] fileData;
void loadFileData(){
fileData = loadStrings("StudentData.txt");
}
void setup(){
loadFileData();
studentList = new Student[fileData.length/3];
for(int i = 0; i < fileData.length/3; i++){
studentList[i].studentName = fileData[i];
studentList[i].studentAddress = fileData[i+1];
studentList[i].studentNumber = parseInt(fileData[i+3]);
}
printArray(fileData);
}
Student Class
class Student{
String studentName;
String studentAddress;
int studentNumber;
Student(String name, String address, int number){
studentName = name;
studentAddress = address;
studentNumber = number;
}
}
My file directory is exactly as follows:
>Processing
>data
>StudentData.txt
>student
>studentSearch
All of the data is formatted in lines, name, address, number, repeat
Thank you!

I copied your code and ran it here in Processing.
I get a NullPointerException on this line:
studentList[i].studentName = fileData[i];
But it's not being caused by the fileData array. You can see this if you print the array immediately after it's loaded. The data is there:
fileData = loadStrings("StudentData.txt");
printArray(fileData);
You get an error because you're trying to access a Student object that doesn't exist. You create an array to hold the objects, but you don't actually put any objects in it before trying to access them in your loop. So studentList[i] is null.
You can pass the data directly to your Student constructor when you create the object:
studentList[i] = new Student(fileData[i], fileData[i+1], parseInt(fileData[i+3]));

Related

Getting path of ArrayList<image> that is already set and convert to string

My program creates a "Deck" of cards in a List, I want to be able to get the image, find the path to parse it to get the information that is in the image name.
For this, I am using an ArrayList to store the cards.
List<Image> mainDeck = new ArrayList<Image>();
To load the image, I am using this code
public List load(List<Image> newDeck) {
count = 0;
for (int i = 0; i < 4; i++) {
for (int k = 0; k < 10; k++) {
newDeck.add(new Image("images/" + prefix.get(i) + "" + (k + 1) + ".png"));
count++;
}// end number card for loop
for (int l = 0; l < 3; l++) {
newDeck.add(new Image("images/" + prefix.get(l) + "" + prefixFace.get(l) + ".png"));
count++;
}// end face card for loop
}// end deck for loop
it then gets called and populated with images that work perfectly, I would like to create a matching array filled with Strings that hold the path for the matching Image array.
The names of images are "c1.png", "c2.png", etc, and I just need the number in the pathname
Once I get the array I should be able to parse the data to get the numbers.
Any help would be much appreciated.
when using get url, I am getting an error, here is that code
for (Image card : mainDeck){
String path = card.getUrl();
String name = path.substring(path.lastIndexOf("/")+1, path.lastIndexOf("."));
nameData.put(card, name);
it is not recognizing card.getUrl();
you don't have to create another arrayList for the paths cause the path data is already saved with the images.
if you want to retrieve the path of an image after creating it then you might use the method getUrl() in the Image class, calling getUrl() from an Image object will return the path that you used to create the image when you called the constructor, note that it will only work if you called the Image constructor using a String as the path for the image, it will not work if you used an inputStream to initialize your image, and also that it was defined in java 9, after getting the path you might split it to get the useful data you want, something like
Image image = new Image("file:/C:/Users/zinou/Desktop/edit.png");
String path = image.getUrl();
String name = path.substring(path.lastIndexOf("/") + 1, path.lastIndexOf("."));
System.out.println(name);
and if i were to associate every card with its path, i would use a hashMap as in
List<Image> mainDeck = new ArrayList<Image>();
//population of the list
HashMap<Image, String> nameData = new HashMap<Image, String>();
for (Image card : mainDeck) {
String path = card.getUrl();
String name = path.substring(path.lastIndexOf("/") + 1, path.lastIndexOf("."));
nameData.put(card, name);
}
If you have java 8
you can create a class that extends the Image class and give it an additional attribute (the URL), and add a getter for the URL so you can access it, but then your cards will be instances of the new class you created, so you can get the URL for them, the new class may look like this
public class MyImage extends javafx.scene.image.Image{
String url;
public MyImage(String arg0) {
super(arg0);
url = arg0;
}
public String geturl() {
return url;
}
}

get workflow malfunction exception with java api

Does anyone know how to get a workflow malfunction error message using the java pe api? I am running the QueueSample java code provided by IBM and it is not clear to me how to do this. Any help would be appreciated!
I found the malfunction error message for my workflow in the VWParticipantHistory.getLogFields() array. I modified the example code from the Developing Applications with IBM FileNet P8 APIs redbook:
// Create session object and log onto Process Engine
...
// Get the specific work item
...
// Get VWProcess object from work object
VWProcess process = stepElement.fetchProcess();
// Get workflow definitions from the VWProcess
VWWorkflowDefinition workflowDefinition =
process.fetchWorkflowDefinition(false);
// Get maps for each workflow definition
VWMapDefinition[] workflowMaps = workflowDefinition.getMaps();
// Iterate through each map in the workflow Definition
for (int i = 0; i < workflowMaps.length; i++) {
// Get map ID and map name for each map definition
int mapID = workflowMaps[i].getMapId();
String mapName = workflowMaps[i].getName();
// Get workflow history information for each map
VWWorkflowHistory workflowHistory = process.fetchWorkflowHistory(mapID);
String workflowOriginator = workflowHistory.getOriginator();
// Iterate through each item in the Workflow History
while (workflowHistory.hasNext()) {
// Get step history objects for each workflow history
VWStepHistory stepHistory = workflowHistory.next();
String stepName = stepHistory.getStepName();
System.out.println("step history name = " + stepName);
// Iterate through each item in the Step History
while (stepHistory.hasNext()) {
// Get step occurrence history
// objects for each step history object
VWStepOccurrenceHistory stepOccurenceHistory = stepHistory.next();
Date stepOcurrenceDateReceived = stepOccurenceHistory.getDateReceived();
Date stepOcurrenceDateCompleted = stepOccurenceHistory.getCompletionDate();
while (stepOccurenceHistory.hasNext()) {
// Get step work object information
// for each step occurrence
VWStepWorkObjectHistory stepWorkObjectHistory = stepOccurenceHistory.next();
stepWorkObjectHistory.resetFetch();
// Get participant information for each work object
while (stepWorkObjectHistory.hasNext()) {
VWParticipantHistory participantHistory = stepWorkObjectHistory.next();
String opName = participantHistory.getOperationName();
System.out.println("operation name = " + opName);
Date participantDateReceived = participantHistory.getDateReceived();
String participantComments = participantHistory.getComments();
String participantUser = participantHistory.getUserName();
String participantName = participantHistory.getParticipantName();
VWDataField[] logFields = participantHistory.getLogFields();
System.out.println("** start get log fields **");
for (int index=0; index<logFields.length; index++){
VWDataField dataField = logFields[index];
String name = dataField.getName();
String val = dataField.getStringValue();
System.out.println("name = " + name + " , value = " + val);
}
System.out.println("** end get log fields **");
} // while stepWorkObjectHistory
} // while stepOccurenceHistory
} // while stepHistory
} // while workflowHistory
} // for workflow maps

Using Bulk Insert dramatically slows down processing?

I'm fairly new to Oracle but I have used the Bulk insert on a couple other applications. Most seem to go faster using it but I've had a couple where it slows down the application. This is my second one where it slowed it down significantly so I'm wondering if I have something setup incorrectly or maybe I need to set it up differently. In this case I have a console application that processed ~1,900 records. Inserting them individually it will take ~2.5 hours and when I switched over to the Bulk insert it jumped to 5 hours.
The article I based this off of is http://www.oracle.com/technetwork/issue-archive/2009/09-sep/o59odpnet-085168.html
Here is what I'm doing, I'm retrieving some records from the DB, do calculations, and then write the results out to a text file. After the calculations are done I have to write those results back to a different table in the DB so we can look back at what those calculations later on if needed.
When I make the calculation I add the results to a List. Once I'm done writing out the file I look at that List and if there are any records I do the bulk insert.
With the bulk insert I have a setting in the App.config to set the number of records I want to insert. In this case I'm using 250 records. I assumed it would be better to limit my in memory arrays to say 250 records versus the 1,900. I loop through that list to the count in the App.config and create an array for each column. Those arrays are then passed as parameters to Oracle.
App.config
<add key="UpdateBatchCount" value="250" />
Class
class EligibleHours
{
public string EmployeeID { get; set; }
public decimal Hours { get; set; }
public string HoursSource { get; set; }
}
Data Manager
public static void SaveEligibleHours(List<EligibleHours> listHours)
{
//set the number of records to update batch on from config file Subtract one because of 0 based index
int batchCount = int.Parse(ConfigurationManager.AppSettings["UpdateBatchCount"]);
//create the arrays to add values to
string[] arrEmployeeId = new string[batchCount];
decimal[] arrHours = new decimal[batchCount];
string[] arrHoursSource = new string[batchCount];
int i = 0;
foreach (var item in listHours)
{
//Create an array of employee numbers that will be used for a batch update.
//update after every X amount of records, update. Add 1 to i to compensated for 0 based indexing.
if (i + 1 <= batchCount)
{
arrEmployeeId[i] = item.EmployeeID;
arrHours[i] = item.Hours;
arrHoursSource[i] = item.HoursSource;
i++;
}
else
{
UpdateDbWithEligibleHours(arrEmployeeId, arrHours, arrHoursSource);
//reset counter and array
i = 0;
arrEmployeeId = new string[batchCount];
arrHours = new decimal[batchCount];
arrHoursSource = new string[batchCount];
}
}
//process last array
if (arrEmployeeId.Length > 0)
{
UpdateDbWithEligibleHours(arrEmployeeId, arrHours, arrHoursSource);
}
}
private static void UpdateDbWithEligibleHours(string[] arrEmployeeId, decimal[] arrHours, string[] arrHoursSource)
{
StringBuilder sbQuery = new StringBuilder();
sbQuery.Append("insert into ELIGIBLE_HOURS ");
sbQuery.Append("(EMP_ID, HOURS_SOURCE, TOT_ELIG_HRS, REPORT_DATE) ");
sbQuery.Append("values ");
sbQuery.Append("(:1, :2, :3, SYSDATE) ");
string connectionString = ConfigurationManager.ConnectionStrings["Server_Connection"].ToString();
using (OracleConnection dbConn = new OracleConnection(connectionString))
{
dbConn.Open();
//create Oracle parameters and pass arrays of data
OracleParameter p_employee_id = new OracleParameter();
p_employee_id.OracleDbType = OracleDbType.Char;
p_employee_id.Value = arrEmployeeId;
OracleParameter p_hoursSource = new OracleParameter();
p_hoursSource.OracleDbType = OracleDbType.Char;
p_hoursSource.Value = arrHoursSource;
OracleParameter p_hours = new OracleParameter();
p_hours.OracleDbType = OracleDbType.Decimal;
p_hours.Value = arrHours;
OracleCommand objCmd = dbConn.CreateCommand();
objCmd.CommandText = sbQuery.ToString();
objCmd.ArrayBindCount = arrEmployeeId.Length;
objCmd.Parameters.Add(p_employee_id);
objCmd.Parameters.Add(p_hoursSource);
objCmd.Parameters.Add(p_hours);
objCmd.ExecuteNonQuery();
}
}

ToString does not work

Why toString doesn´t work in my code? The output should be all elements that are in the idChild[].
Error:
child[Ljava.lang.String;#15db9742
public String[] onePointCrossover(int father, int mother) {
String linha1 = individualID.get(father);
idFather = linha1.split(" ");
String linha2 = individualDep.get(father);
depenFather= linha2.split(" ");
String linha3 = individualHour.get(father);
hourFather = linha3.split(" ");
String linhaA = individualID.get(mother);
idMother = linha1.split(" ");
String linhaB = individualDep.get(mother);
depenMother= linha2.split(" ");
String linhaC = individualHour.get(mother);
hourMother = linha3.split(" ");
String [] idChild = new String [idFather.length];
int crossPoint = (int) (Math.random()*idFather.length);
for(int i=0; i<idFather.length; i++)
{
if (i<crossPoint)
idChild[i] = idFather[i];
else
idChild [i] = idMother[i];
}
System.out.println("child" + idChild.toString());
return idChild;
}
If you want to loop through all childs in your array, then you need to loop through it, other wise you are attempting to read an array of objects as a string!
Try:
foreach (string s in idChild)
{
System.out.println(s);
}
This is the way toString() works (documentation here): the default implementation of the Object class (and of all arrays) shows the class name, the # symbol and the hexadecimal representation of the hash code of the object:
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
The documentation says:
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object.
So it's really up to the programmer to choose what "textually represents" means.
If you want to print the String representation of all the items in an array you have to iterate over it.

How can I post a list then access it in my controller?

I created a list property in my model like so
public virtual List<String> listOfDays { get; set; }
then I converted and stored it in the list like this:
for (int i = 0; i < 30 i++)
{
var enrollment = new Enrollment();
enrollment.StudentID = id;
enrollment.listOfDays = searchString.ToList();
db.Enrollments.Add(enrollment);
db.SaveChanges();
}
I put a breakpoint here... enrollment.listOfDays = searchString.ToList(); ... and all is well. I see that the conversion was performed and I can see the values in listOfDays.
So I thought I would find a column in my database called listOfDays since I'm doing code first but the property is not there.
Then I thought I'd try accessing it anyway like this...
var classdays = from e in db.Enrollments where e.StudentID == id select e.listOfDays;
var days = classdays.ToList();
//here I get an error message about this not being supported in Linq.
Questions:
Why do you think the property was not in the database?
How can I post this array to my model then access it in a controller?
Thanks for any help.
Thanks to Decker: http://forums.asp.net/members/Decker%20Dong%20-%20MSFT.aspx
Here’s how it works:
Using form collection here…
In [HttpPost]…
private void Update (FormCollection formCollection, int id)
for (int sc = 0; sc < theSelectedCourses.Count(); sc++)
{
var enrollment = new Enrollment();
enrollment.CourseID = Convert.ToInt32(theSelectedCourses[sc]);
enrollment.StudentID = id;
enrollment.listOfDays = formCollection["searchString"] ;//bind this as a string instead of a list or array.
Then in [HttpGet]…
private void PopulateAssignedenrolledData(Student student, int id)
{
var dayList = from e in db.Enrollments where e.StudentID == id select e;
var days = dayList.ToList();
if (days.Count > 0)
{
string dl = days.FirstOrDefault().listOfDays;
string[] listofdays = dl.Split(',');
ViewBag.classDay = listofdays.ToList();
}
Thanks to Decker: http://forums.asp.net/members/Decker%20Dong%20-%20MSFT.aspx
Here’s how it works:
Using form collection here…
In [HttpPost]…
private void Update (FormCollection formCollection, int id)
for (int sc = 0; sc < theSelectedCourses.Count(); sc++)
{
var enrollment = new Enrollment();
enrollment.CourseID = Convert.ToInt32(theSelectedCourses[sc]);
enrollment.StudentID = id;
enrollment.listOfDays = formCollection["searchString"] ;//bind this as a string instead of a list or array.
Then in [HttpGet]…
private void PopulateAssignedenrolledData(Student student, int id)
{
var dayList = from e in db.Enrollments where e.StudentID == id select e;
var days = dayList.ToList();
if (days.Count > 0)
{
string dl = days.FirstOrDefault().listOfDays;
string[] listofdays = dl.Split(',');
ViewBag.classDay = listofdays.ToList();
}

Resources