samedi 28 février 2015

Get CPU load per core using Java



I'm using this code to get CPU load from /proc/stat using Java code:



private static long PREV_IDLE; //CPU Idle time
private static long PREV_TOTAL; //CPU Total time
private static final int CONSERVATIVE = 0;
private static final int AVERAGE = 1;
private static final int OPTIMISTIC = 2;

public static float getCPUProcOrig() throws Exception
{
BufferedReader cpuReader = null;
try
{
cpuReader = new BufferedReader(new InputStreamReader(new FileInputStream("/proc/stat")));
String cpuLine = cpuReader.readLine();
if (cpuLine == null)
{
throw new Exception("/proc/stat didn't work well");
}
else
{
String[] CPU = cpuLine.split("\\s+");

long IDLE = Long.parseLong(CPU[4]);//Get the idle CPU time.
long TOTAL = Long.parseLong(CPU[1]) + Long.parseLong(CPU[2]) + Long.parseLong(CPU[3]) + Long.parseLong(CPU[4]);
// System.out.println("IDLE : " + IDLE);

long DIFF_IDLE = IDLE - PREV_IDLE;
long DIFF_TOTAL = TOTAL - PREV_TOTAL;
long DIFF_USAGE = DIFF_TOTAL == 0 ? 0 : (1000 * (DIFF_TOTAL - DIFF_IDLE) / DIFF_TOTAL + 5) / 10;
// System.out.println("CPU: " + DIFF_USAGE + "%");

PREV_TOTAL = TOTAL;
PREV_IDLE = IDLE;
return (float) DIFF_USAGE;
}
}
catch (Exception e)
{
throw e; // It's not desirable to handle the exception here
}
finally
{
if (cpuReader != null)
try
{
cpuReader.close();
}
catch (IOException e)
{
// Do nothing
}
}
}


Unfortunately this code works well but for average CPU load. I would like to list all cores load separately. I tried to extend the code:



private static long PREV_IDLE; //CPU Idle time
private static long PREV_TOTAL; //CPU Total time
private static final int CONSERVATIVE = 0;
private static final int AVERAGE = 1;
private static final int OPTIMISTIC = 2;

public HashMap<String, HashMap<String, Float>> getCPUProc() throws Exception
{
BufferedReader cpuReader = null;
HashMap<String, HashMap<String, Float>> usageData = new HashMap<>();

try
{
String line;
cpuReader = new BufferedReader(new InputStreamReader(new FileInputStream("/proc/stat")));
while ((line = cpuReader.readLine()) != null)
{
String[] CPU = line.split("\\s+");
if (CPU[0].startsWith("cpu"))
{
String cpuName = String.valueOf(CPU[0]);//Get the cpu number.
long IDLE = Long.parseLong(CPU[4]);//Get the idle CPU time.
long TOTAL = Long.parseLong(CPU[1]) + Long.parseLong(CPU[2]) + Long.parseLong(CPU[3]) + Long.parseLong(CPU[4]);
// System.out.println("IDLE : " + IDLE);

long DIFF_IDLE = IDLE - PREV_IDLE;
long DIFF_TOTAL = TOTAL - PREV_TOTAL;
long DIFF_USAGE = DIFF_TOTAL == 0 ? 0 : (1000 * (DIFF_TOTAL - DIFF_IDLE) / DIFF_TOTAL + 5) / 10;
// System.out.println("CPU: " + DIFF_USAGE + "%");

PREV_TOTAL = TOTAL;
PREV_IDLE = IDLE;

HashMap<String, Float> usageData2 = new HashMap<>();
usageData2.put("cpu", (float) DIFF_USAGE);

usageData.put(cpuName, usageData2);
}

// return (float) DIFF_USAGE;
}
}
catch (IOException | NumberFormatException e)
{
throw e; // It's not desirable to handle the exception here
}
finally
{
if (cpuReader != null)
try
{
cpuReader.close();
}
catch (IOException e)
{
// Do nothing
}
}
return usageData;
}


As you can see from the first code there are several static variables which are used to calculate the CPU load. When I try to read all lines from /proc/stat these static variables are not used properly and data between the cores is messed up and the result is not accurate.


Can you help me to read the load properly? I'm out of ideas. How I can fix the code?




How to have the same order in a JSON Array as a JSON response?



I am receiving a JSON response such as



{
"status": "success",
"0": {
"fname": "john",
"lname":"doe"
},
"1": {
"fname":"jane",
"lname":"doe"
}
}


When I get this JSONObject and try to put it into a JSON Array such that element 0 is status:succes, element 1 is fname: "john", lname: "doe" .. etc. The result is mixed up. The array is not in the same order as the JSON Response. How can I parse the JSON Response and each element as a JSON Object in the same order?




Why is String considered Abstract data type?



Was checking lectures from this link :-


http://ift.tt/1N409e8


It states Strings as ADT, I am confused why?




BufferStrategy in windowed mode causes constant intense white screen flicker



I put this code together based on a lot of examples I found around here on stackoverflow. When I run the program the entire screen flickers intensely. I'm sure there is something simple I'm overlooking, but so far have been unable to track down a solution. I've been debugging this for a couple hours mostly with the help of online forum reading, so I figured it was time to ask the audience.


public class Screen extends JComponent {



@Override
public Dimension getPreferredSize(){
Dimension tempDimension = Toolkit.getDefaultToolkit().getScreenSize();
return tempDimension;
}

@Override
protected void paintComponent(Graphics g) {

super.paintComponent(g);
Graphics2D g2D = (Graphics2D)bufferStrategy.getDrawGraphics();
g2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER)); //sprites overlap instead of overwrite
if(game==null){
drawSplash(g2D);
}else{
drawBoard(g2D);
}
g2D.dispose();
bufferStrategy.show();
}
}


If any additional code is required, I can provide it. Thank you for your help, stackoverflow!




Anyone know how to insert a date ('2/28/2015') and hour from java to a MySql database?



Please, I need insert to dates, hours and integers in Mysql database from Java




Overlapping issue in Swing



I'm encountering this issue in Java Swing:


Image of the problem


Both Magenta and Green components are JButtons. I'm using absolute layout for this. When hovering to Green, it overlaps Magenta even if no layout manager is applied nor JLayeredPane used.


Any reason for this behavior? How can I make sure the Magenta stays on top when hovering to Green?




Switching Between Months in Gregorian Calendar



So I am able to print the Gregorian Calendar for the current month, but when I am trying to flip to the next or previous month, it just seems to reprint the current month again. Please note that by "printing" the calendar, I mean that I am actually formatting it to look like I full calendar (all the days like a Google calendar, etc). Also, this program is in very early stages. Ultimately, I want it to support adding events to days, printing the events, etc.


Anyway, here is some code that I have that might be relevant:


MyCalendar class:



import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;


public class MyCalendar {

GregorianCalendar calendar;
String[] months;
String[] dayOfWeek;
int todayDay;
int maxDays;
static PrintMenu print = new PrintMenu();
private HashMap<MyCalendar, Event> myCalHash = new HashMap<MyCalendar, Event>();

MyCalendar(){
calendar = new GregorianCalendar(); //capture today
months = new String[]{"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
dayOfWeek = new String[]{"Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"};
todayDay = calendar.get(Calendar.DAY_OF_MONTH);
maxDays = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
calendar.set(Calendar.DAY_OF_MONTH, 1);

}

public Calendar getCalendar(){
return calendar;
}

public void setCalendar(GregorianCalendar cal){
calendar = cal;
}

public Date getFirstDayOfMonth(){
return calendar.getTime();
//return calendar.get((Calendar.DAY_OF_WEEK) - 1);
}

public int getDay(){
return calendar.get(Calendar.DAY_OF_MONTH);
}

public int getMaximumDays(){
return maxDays;
}

public int getTodayDay(){
return todayDay;
}

public int getMonth(){
return calendar.get(Calendar.MONTH);
}

public int getYear(){
return calendar.get(Calendar.YEAR);
}

public void setNext(){
calendar.add(Calendar.MONTH, 1);
}
public void setPrevious(){
calendar.add(Calendar.MONTH, -1);
}
public static void main(String[] args) {
// TODO Auto-generated method stub

print.printCalendar(false);
print.printMenu();

System.out.println("I think we're done here!");
}

}


PrintMenu Class:



public class PrintMenu {

MenuHandler menu = new MenuHandler();
MyCalendar myCalendar = new MyCalendar();


void printCalendar(boolean withEvents){

int count = 0; //for formatting
int day = myCalendar.getTodayDay();

System.out.println(myCalendar.months[myCalendar.getMonth()] + " " + myCalendar.getYear());
System.out.print(myCalendar.dayOfWeek[6] + " ");
for(int i = 0; i < myCalendar.dayOfWeek.length - 1; i++){
System.out.print(myCalendar.dayOfWeek[i] + " ");
}

// int daysInMonth = myCalendar.getMaximumDays(); // 28
for(int i = 1; i <= myCalendar.dayOfWeek.length; i++){
count++;
if(!myCalendar.dayOfWeek[i].equals(myCalendar.getFirstDayOfMonth().toString().substring(0, 2))){
System.out.print(" ");
}else{
count = 0;
break;
}
}
System.out.println();
for(int i = 1; i <= myCalendar.getMaximumDays(); i++){
if(!withEvents){
if(i == day){
System.out.print("[" + i + "]");
}
if(i < 10){
System.out.print(" " + i + " ");

}else{
if(i != day){
System.out.print(i + " ");
}
}
}
else{
if(i < 10){
System.out.print(" " + i + " ");

}else{
System.out.print(i + " ");
}
}


count++;
if(count >= 7){
System.out.println();
count = 0; //reset back
}
}
}

void printMenu(){

System.out.println("-------------------------------------------------------------------");

System.out.println("Select one of the following options: ");
System.out.println("[L]oad [V]iew by [C]reate, [G]o to [E]vent list [D]elete [Q]uit");
menu.handleChoice();
printMenu();
}

}


ViewCalendar class (this is where I'm trying to navigate the calendar and failing)



import java.util.Calendar;
import java.util.Scanner;


public class ViewCalendar {
Scanner sc = new Scanner(System.in);
MyCalendar myCalendar = new MyCalendar();

public void whatView(){

System.out.print("[D]ay view or [M]view? ");
char userChoice = sc.next().charAt(0);
if(Character.toUpperCase(userChoice) == 'D'){ dayView(); }
else if(Character.toUpperCase(userChoice) == 'M'){ monthView(); }
else{
System.out.println("Invalid choice.");
whatView();
}

}
public void dayView(){
//print day calendar
System.out.print("[P]revious or [N]ext or [M]ain menu ? ");
char userChoice = sc.next().charAt(0);
if(Character.toUpperCase(userChoice) == 'P'){

}
else if(Character.toUpperCase(userChoice) == 'N'){

}
else if(Character.toUpperCase(userChoice) == 'M'){
return;
}
else{
System.out.println("Invalid choice.");
dayView();
}
}
public void monthView(){
//print month calendar
myCalendar.print.printCalendar(true);
System.out.print("[P]revious or [N]ext or [M]ain menu ? ");
char userChoice = sc.next().charAt(0);
if(Character.toUpperCase(userChoice) == 'P'){
myCalendar.setPrevious();
myCalendar.print.printCalendar(true);
}
else if(Character.toUpperCase(userChoice) == 'N'){
myCalendar.setNext();
myCalendar.print.printCalendar(true);
}
else if(Character.toUpperCase(userChoice) == 'M'){
return;
}
else{
System.out.println("Invalid choice.");
dayView();
}
}


}


Anyway, I hope that's not too much information. I followed the calendar.add() syntax, but it doesn't seem to have any effect. I appreciate any insight you guys may have!


Here is the MenuHandler class:



import java.util.Scanner;


public class MenuHandler {

Scanner sc = new Scanner(System.in);
ViewCalendar view = new ViewCalendar();


public void handleChoice(){

char userChoice = sc.next().charAt(0);
switch(Character.toUpperCase(userChoice)){
case 'L':

case 'V': view.whatView();
// menu.printMenu();

case 'C':

case 'G':

case 'E':

case 'D':

case 'Q': return;
}


}

}



Java - Creating a method which returns an iterator



I'm currently creating a class called ArraySet that implements the Set interface. I'm supposed to create an iterator method that returns the values in natural order, where the time complexities are iterator(): O(1); hasNext(): O(1); next(): O(1); required space: O(1). The method is supposed to return an Iterator that does this. I'm confused by the way this method works and what is exactly wanted from me. Because it's a method I shouldn't be able to create hasNext(), or next() methods inside of it, and what Iterator am I trying to return? I tried just returning an Iterator but it's abstract and cannot be instantiated. I can understand making a new iterator class, but am having trouble understanding how this works in method form. Basically, what the method looks like at the moment is this, but like I've said I don't know what to even put inside of it. Also, if it helps there are two fields in the ArraySet class, int size (the number of elements in the Array), and T[] elements (the array where the elements are stored, strictly in natural order though I'm not even sure how to enforce natural order)



public Iterator<T> iterator() {
return null;
}



How to search for an element in an array? and How to add variables with declared methods into an array list?



I have 2 major troubles (that I'm aware of) with this program. Firstly, I don't know how to get FinalGrade and LetterGrade into the array. Secondly, I don't know how to use last name and first name to search for a student in the array. Let me know if you find other problems with my program. Thanks


This is the 1st class



package student;

public class Person {

protected String FirstName, LastName;

//Constructor
public Person(String FirstName, String LastName) {
this.FirstName = FirstName;
this.LastName = LastName;
}

//Getters
public String getFirstName() {
return FirstName;
}

public String getLastName() {
return LastName;
}
//Setters
public void setFirstName(String FirstName) {
this.FirstName = FirstName;
}

public void setLastName(String LastName) {
this.LastName = LastName;
}


}


This is the 2nd class:



package student;

import java.util.ArrayList;
import java.util.Scanner;



public class Student extends Person{
private int HomeworkAve, QuizAve, ProjectAve, TestAve;
private double FinalGrade;
private String LetterGrade;

//Constructor for the averages
public Student(int HomeworkAve, int QuizAve, int ProjectAve, int TestAve, String FirstName, String LastName)
{
super(FirstName, LastName);
this.HomeworkAve = HomeworkAve;
this.QuizAve = QuizAve;
this.ProjectAve = ProjectAve;
this.TestAve = TestAve;

}

//Method to calculate final grade and letter grade
//Final grade calculation
public double CalcGrade (int HomeworkAve, int QuizAve, int ProjectAve, int TestAve)
{
FinalGrade = (double)(0.15*HomeworkAve + 0.05*QuizAve + 0.4 * ProjectAve + 0.4*TestAve);
return FinalGrade;
}

//Letter grade calculation
public String CalcGrade ( double FinalGrade)
{
if ( FinalGrade >= 90.00)
LetterGrade="A";
else if(FinalGrade >= 80.00)
LetterGrade="B";
else if(FinalGrade>=70.00)
LetterGrade="C";
else if(FinalGrade>=60.00)
LetterGrade="D";
else LetterGrade="F";

return LetterGrade;
}

public String getFullName (String FirstName,String LastName)
{
String str1 = FirstName;
String str2 = LastName;
String FullName = str1+","+str2;
return FullName;
}

public Student(int HomeworkAve, int QuizAve, int ProjectAve, int TestAve, double FinalGrade, String LetterGrade, String FirstName, String LastName) {
super(FirstName, LastName);
this.HomeworkAve = HomeworkAve;
this.QuizAve = QuizAve;
this.ProjectAve = ProjectAve;
this.TestAve = TestAve;
this.FinalGrade = FinalGrade;
this.LetterGrade = LetterGrade;

}


//Setters for this student class
public void setHomeworkAve(int HomeworkAve) {
this.HomeworkAve = HomeworkAve;
}

public void setQuizAve(int QuizAve) {
this.QuizAve = QuizAve;
}

public void setProjectAve(int ProjectAve) {
this.ProjectAve = ProjectAve;
}

public void setTestAve(int TestAve) {
this.TestAve = TestAve;
}

public void setFinalGrade(int FinalGrade) {
this.FinalGrade = FinalGrade;
}

public void setLetterGrade(String LetterGrade) {
this.LetterGrade = LetterGrade;
}


//Getters for this student class
public int getHomeworkAve() {
return HomeworkAve;
}

public int getQuizAve() {
return QuizAve;
}

public int getProjectAve() {
return ProjectAve;
}

public int getTestAve() {
return TestAve;
}

public double getFinalGrade() {
return FinalGrade;
}

public String getLetterGrade() {
return LetterGrade;
}

public void DisplayGrade (){
System.out.println(FirstName+" "+LastName+"/nFinal Grade: "+FinalGrade+"/nLetter Grade: "+ LetterGrade);
}




public static void main(String[] args){
Scanner oScan = new Scanner(System.in);
Scanner iScan = new Scanner(System.in);

boolean bContinue = true;
int iChoice;

ArrayList<Student> students = new ArrayList<>();


while (bContinue == true)
{
//The menu
System.out.println("1. New Class List");
System.out.println("2. Search for a Student");
System.out.println("3. Exit");
System.out.println("Choose an item");

iChoice = iScan.nextInt();


//The 1st case: when the user wants to enter the new list
if (iChoice == 1){

System.out.println("Enter the number of students");

int numberOfStudents = iScan.nextInt();

for(int iCount = 0;iCount < numberOfStudents;){

System.out.println("Enter the name for Student " + ++iCount);
System.out.println("Enter First Name");
String FirstName = oScan.nextLine();
System.out.println();

System.out.println("Enter Last Name");
String LastName = oScan.nextLine();
System.out.println();

System.out.println("Enter Homework Average");
int HomeworkAve = iScan.nextInt();
System.out.println();

System.out.println("Enter Quiz Average");
int QuizAve = iScan.nextInt();
System.out.println();

System.out.println("Enter Project Average");
int ProjectAve = iScan.nextInt();
System.out.println();

System.out.println("Enter Test Average");
int TestAve = iScan.nextInt();
System.out.println();


How to get FinalGrade and LetterGrade??



Student hobbit = new Student(HomeworkAve,QuizAve, ProjectAve,TestAve,FirstName, LastName);
students.add(hobbit);
}
}


//The 2nd case: when the user wants to search for a student
else if (iChoice == 2)
{
System.out.println("Enter First Name");
String FirstName = oScan.nextLine();
System.out.println();

System.out.println("Enter Last Name");
String LastName = oScan.nextLine();
System.out.println();


below is my way to find the student in the array but it doesn't work, I type exactly the first name and last name but it said "Not found"



int iFound1, iFound;
iFound1 = students.indexOf(FirstName);
iFound2 = students.indexOf(LastName);
if (iFound1 >= 0 & iFound2 >= 0)
System.out.println("The student is " + students.get(iFound1)+ students.get(iFound2) );
else
System.out.println("\n\nNot found!");

}


//The 3r case: when the user wants to exit
else if (iChoice == 3)
{
bContinue = false;
}
}
}

}



Using an if statement with a while loop?



I'm trying to do this question:


Design a program that reads in a list of numbers terminated by -9999 and prints out the sum entered.


I am amending the program so that only values between 1 and 100 are summed, and as you can see I've tried to implement an if statement. But, nothing has changed and this part has stumped me. I've been stuck on it for ages, code follows:



import java.util.Scanner;

public class Summing {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int Number, Sum = 0;

System.out.println("Enter a list of whole numbers, finished by -9999");
Number = sc.nextInt();

if (Number > 0 || Number < 100);
while (Number != -9999) {
Sum = Sum + Number;
Number = sc.nextInt();
}

System.out.println("Sum is " + Sum);
}
}



Printing out strings to align to match it's placement in another String



I need to print out strings that align to match it's placement in another String when data is grouped together. For instance:


I have an ArrayList of Strings containing:



[0] "data1 data2 data3"
[1] "data1 data2 data3"
[2] "data3"
[3] "data4"
[4] "data4 data5"


I want the output to be



[0] "data1 data2 data3"
[1] "data1 data2 data3"
[2] " data3"
[3] "data4"
[4] "data4 data5"



Drawing on a Jframe from two different classes



I am trying to create a program that record mouse clicks, draw lines between those points and after some calculations display some circles through a button call. My problem is that I can display the lines or the circles, but not both.


I know there is something overlapping something else, but I am very new to Java and I don't know how to fix it. Here is the code:



package fempack;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

import java.lang.Math;



public class MainFem extends JPanel {



final DrawPoints Npoints = new DrawPoints();
final DrawLines Nline = new DrawLines();


private static final long serialVersionUID = 1L;
private MouseHandler mouseHandler = new MouseHandler();
private Point p1 = new Point(100, 100);
public int Xpoint[][] = new int[500][30];
public int Ypoint[][] = new int[500][30];
private double Xmpoint[][] = new double[500][1000]; // [i γραμμή][συντεταγμένη Χ]
private double Ympoint[][] = new double[500][1000];

private double Vec[][][] = new double[500][2][500]; // [i γραμμή][0,1][0α 1β]


private double dist[] = new double[10000];
private boolean drawing;
private int c1;
private int c2;

public MainFem() {

this.addMouseListener(mouseHandler);
this.addMouseMotionListener(mouseHandler);

}


// -------------- Draw by clicking -----------------------

private class MouseHandler extends MouseAdapter {

@Override
public void mousePressed(MouseEvent e) {
if(SwingUtilities.isRightMouseButton(e)){
drawing=false;
c2++;

}
if(SwingUtilities.isLeftMouseButton(e)){

p1 = e.getPoint();
Xpoint[c1][c2] = p1.x;
Ypoint[c1][c2] = p1.y;




if (c1 > 3) {

for (int j = 0; j<c2+1; j++){
for (int i = 0; i<c1; i++){


if ((Math.abs(Xpoint[i][j]-Xpoint[c1][c2]) < 10) && (Math.abs(Ypoint[i][j]-Ypoint[c1][c2]) < 10)) {


Xpoint[c1][c2] = Xpoint[i][j];
Ypoint[c1][c2] = Ypoint[i][j];
System.out.println(Xpoint[i][j]);

}
}
}
}

if (drawing == true){
Nline.addLine(Xpoint[c1][c2], Ypoint[c1][c2], Xpoint[c1-1][c2], Ypoint[c1-1][c2]);
}



c1++;
drawing = true;

}
}


}


// ---------------- Create Mesh Points --------------------------

public void createmesh() {
int mdi = 0;


for (int j = 0; j<=c2; j++){
for (int i = 0; i<c1-1; i++){

// Υπολογισμός a και b συνιστωσών της εξίσωσης της γραμμής


Vec[i][0][mdi] = (Ypoint[i+1][j] - Ypoint[i][j])/(Xpoint[i+1][j] - Xpoint[i][j]);
Vec[i][1][mdi] = Ypoint[i][j] - Xpoint[i][j]*Vec[i][1][mdi];


// Υπολογισμός μέτρου διανύσματος

dist[mdi] = Math.sqrt(Math.pow(Xpoint[i][j] - Xpoint[i+1][j], 2) + Math.pow(Ypoint[i][j] - Ypoint[i+1][j], 2) );



// Υπολογισμός ενδιάμεσον σημείων

int nkom = 3;
double xa = Xpoint[i][j];
double ya = Ypoint[i][j];

for (int ii = 0; ii <nkom; ii++) {
double a = Vec[i][0][mdi];
double b = Vec[i][1][mdi];

Xmpoint[i][ii] = (-((2*a)*(b - ya) - 2*xa) + Math.sqrt(Math.abs(Math.pow(((2*a)*(b - ya) - 2*xa), 2) - 4*(1 + a*a)*(xa*xa + Math.pow((b - ya),2) - Math.pow(dist[mdi]/nkom,2)))))/(2 + 2*a*a);


Ympoint[i][ii] = a*Xmpoint[i][ii] + b;


double xm11 = Xmpoint[i][ii];
double ym11 = Ympoint[i][ii];
int xm1 = (int) xm11;
int ym1 = (int) ym11;

Npoints.addPoint(xm1, ym1);


System.out.println("i:" + ym11 + "...ii:" + ym1 );

xa = Xmpoint[i][ii];
ya = Ympoint[i][ii];
}





mdi++;


}
}
}



//------------------------- Display ---------------------------





private void display() {
JFrame f = new JFrame("LinePanel");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.setPreferredSize(new Dimension(500, 600));

f.setLocationRelativeTo(null);




f.add(Npoints);
f.add(Nline);





JPanel buttonsPanel = new JPanel();



//-----------------Complete---------------

JButton dcomp = new JButton("Complete");
buttonsPanel.add(dcomp);


dcomp.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {

createmesh();

}
});


//------------------Clean-------------------

JButton clearButton = new JButton("Clear");
buttonsPanel.setBorder(BorderFactory.createLineBorder(Color.black));
buttonsPanel.setPreferredSize(new Dimension(500, 100));
f.add(buttonsPanel, BorderLayout.SOUTH);
buttonsPanel.add(clearButton);


clearButton.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
Nline.clearLines();
}
});
f.pack();
f.setVisible(true);
f.add(this);

}




//---------------------------------------------------------

public static void main(String[] args) {



EventQueue.invokeLater(new Runnable() {

@Override
public void run() {

new MainFem().display();


}
});
}
}


Class to draw lines:



package fempack;


import java.awt.Graphics;
import java.util.LinkedList;

import javax.swing.JPanel;


public class DrawLines extends JPanel {


/**
*
*/
private static final long serialVersionUID = 1L;

public DrawLines() {

}

private static class Line{
final int x1;
final int y1;
final int x2;
final int y2;


public Line(int x1, int y1, int x2, int y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;

}



}

private final LinkedList<Line> lines = new LinkedList<Line>();



public void addLine(int x1, int x2, int x3, int x4) {
lines.add(new Line(x1,x2,x3,x4));

repaint();
}



public void clearLines() {
lines.clear();
repaint();

}


@Override
protected void paintComponent(Graphics g) {

super.paintComponent(g);

for (Line line : lines) {
// System.out.println(line);

g.drawLine(line.x1, line.y1, line.x2, line.y2);
}



}

}


And class to draw Circles:



package fempack;

import java.awt.Graphics;

import javax.swing.JPanel;

import java.util.LinkedList;


public class DrawPoints extends JPanel {


private static final long serialVersionUID = 1L;

public DrawPoints() {

}




private static class Point {
final int x;
final int y;


public Point(int x, int y) {
this.x = x;
this.y = y;
}
}

private final LinkedList<Point> points = new LinkedList<Point>();


public void addPoint(int x, int y) {
points.add(new Point(x,y));
// System.out.println(x);
repaint();
}




@Override
protected void paintComponent(Graphics g) {

super.paintComponent(g);

for (Point point : points) {
// System.out.println(point);

g.drawOval(point.x, point.y, 5, 5);

}
}

}



Object in Business layer same as DTO with logic?



Let's say I have a Spring MVC project, in which I'm using DTO to get data from a database and to pass data to the UI. Let's suppose that I have a UserDTO and in my business layer I have to do something with that, but I need to put logic in the User and the DTO pattern says that no logic is allowed (or just simple logic).


Should I transform this UserDTO to a User object in order to have the logic and then make a UserDTO to give it to the UI? Or just use the UserDTO and process it in the business layer?


May a BO help?


Thanks




Printing a checker board with nested loops. [Java]



I'm having issues with getting my code to print. I need to print a checker board with a grid the size of a user input.


Ex. Checker Board with a grid of 5


Here's my code:



import java.util.Scanner;
public class nestedpractice1
{
public static void main(String[] args)
{
Scanner kbinput = new Scanner(System.in);
//Create Size variable
System.out.println("Input a size: ");
int n = 0; n = kbinput.nextInt();

for(int r = 0; r < n; r++)
{
for(int c = 0; c < r; c++)
{
if((r%2) == 0)
{
System.out.print("*");
}
else if((r%1) == 0)
{
System.out.print(" *");
}
}
System.out.println("");
kbinput.close();
}
}
}



how to test a functionality when an event occurs in Eclipse Android



I have an already working Android App developed in Eclipse. I am testing the app using test case methods using JUnit. I am new to the Unit Testing in JAVA Android.


My question is, in my app, when I press a button, an alert box appears and I want to test it and show that the test passes (that is, the alert box appears each time the user presses the button). I notice that all the tests are run immediately after the app is installed on my phone.


Since, it is a click event in my app of a button, how do I make the test method run when I click on the button. Any help is highly appreciated. Just a generic suggestion could help a lot. In the code, I want to test if an alert box appears when a button is clicked. The test method is



// Method to check if a message box appears when the button is clicked
public void testifbutton_works() {

}


So, I want to write code in this method that checks if an alert box opens when the user clicks on the button. I notice that all the test methods run when at the start of the app. Any idea how to make this work only when the button is clicked?




How to use Asynchronous and onPostExecute to send value to PHP and get Response



How to send value to php page using Asynchronous with HttpRequest and get a response, then do something with it using OnPostExcute for example.


Java :



private class MyAsyncTask extends AsyncTask<String, Integer, Double>{

@Override
protected Double doInBackground(String... params) {
// TODO Auto-generated method stub
postData(params[0]);
return null;
}

protected void onPostExecute(Double result){
pb.setVisibility(View.GONE);
// Do something with the response here
// ....
}

public void postData(String valueIWantToSend) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("__url_to_file.php");

// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("myHttpData", valueIWantToSend));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

HttpResponse response = httpclient.execute(httppost);
}

}


PHP :



<?php
// return the value back to the app
echo $_POST["myHttpData"];

?>



Jersey: Set up response content-type based on file extension or InputStream?



I am using Jersey to serve a bunch of media-type files from resource folder inside a Jar file. I have the file URL returned by getClassLoader().getResource() and the InputStream returned by getClassLoader().getResourceAsStream(), is there a way for Jersey to detect the content-type for this file?




Android: getting data from database causes app to stop responding, Stuck on progress dialog



Hey guys im creating an app where it populates a list view with data from mysql, the data that will fill the list view consists of courseid, courseName and lecturerName. However when i click the button to view the list it creates the progress dialog as it should however it gets stuck and then the application stop responding.


Below is the code to which i believe is causing the error because the logcat mentions something about doInBackground which is in this class:


the log cat file is: http://ift.tt/1E5vjiM


i really appreciate your time and help, i further want to say i am sorry about my debugging skills im still getting used to android.



public class AllCoursesActivity extends ListActivity {

//progress dialog
private ProgressDialog pDialog;

//create json parser object to understand the php files that were created
JSONParser jsonParser = new JSONParser();

ArrayList<HashMap<String, String>> courseList;

//url to get all the product list
private static String url_all_courses = "http://ift.tt/1AVISNV";


//JSON node Names
private static final String TAG_SUCCESS = "success";
private static final String TAG_COURSES = "courses";
private static final String TAG_COURSEID = "courseid";
private static final String TAG_COURSENAME = "courseName";

//products JSON array
JSONArray courses =null;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.allcourses);

//hashmap for listview
courseList = new ArrayList<HashMap<String, String>>();

//loading courses in background thread
new LoadAllCourses().execute();

//GET list view
ListView lv = getListView();


}

class LoadAllCourses extends AsyncTask<String, String, String>{

//before starting the background thread show some progress dialog

protected void onPreExecute(){
super.onPreExecute();
pDialog = new ProgressDialog(AllCoursesActivity.this);
pDialog.setMessage("Loading Courses. Please Wait");
pDialog.setCancelable(false);
pDialog.setIndeterminate(false);
pDialog.show();
}

//getting all products from the URL
@Override
protected String doInBackground(String... args) {
//building parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
//Getting JSON String from URL
JSONObject json = jsonParser.makeHttpRequest(url_all_courses, "GET", params);
//check log cat for json response
Log.d("All Products: ", json.toString());

try {
//checking for success TAG
int success = json.getInt(TAG_SUCCESS);

if (success == 1){
//it means courses were found
//Getting Array of products
courses = json.getJSONArray(TAG_COURSES);

//looping through all products
for (int i = 0; i < courses.length(); i++){
JSONObject c = courses.getJSONObject(i);

//storing each JSON Item in the variable
String courseid = c.getString(TAG_COURSEID);
String coursename = c.getString(TAG_COURSENAME);

//creating new HASHMAP
HashMap<String, String> map = new HashMap<String, String>();

//adding each child node to hashmap key => value
map.put(TAG_COURSEID, courseid);
map.put(TAG_COURSENAME, coursename);

//adding Hash list to array list
courseList.add(map);
}
}else {
//no courses found
//go back to dashboard
Intent i = new Intent(getApplicationContext(),MainScreenActivity.class);

//closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
}catch(JSONException e){
e.printStackTrace();
}

return null;
}


//after completing background task Dismiss the progress dialog
protected void onPostExecute(String file_url){
//dismiss the dialog after getting all the courses
pDialog.dismiss();
//updating ui from background thread
runOnUiThread(new Runnable() {
@Override
public void run() {
//updating parsed JSon data into list view
ListAdapter adapter = new SimpleAdapter(AllCoursesActivity.this, courseList,
R.layout.listcourse, new String[]{TAG_COURSEID, TAG_COURSENAME},
new int[]{R.id.courseid, R.id.coursename});
//updating listview
setListAdapter(adapter);
}
});
}
}


}




How to write a method using Sets [on hold]



I was given an assignment to write a sets method that takes the difference of two sets and makes a third set with the difference. If somebody can please provide me with feedback on how I can start it I would greatly appreciate it.


Thank you!



Write a static method named difference that takes two Sets of Integers as parameters C and D and returns a new Set of Integers that contains C - D. The original Sets C and D should be the same after the method is finished.





Java.lang.Class.cast doesn't return a casted object



I am trying to cast an object to its superclass using Java.lang.Class.cast but I get the same object. What can be the reason?


This is the code I'm running:



public static void parse(Object obj)
{
// parse all super classes
Class<?> clazz = obj.getClass().getSuperclass();
if (!clazz.equals(prevClass))
{
prevClass = clazz;
Object castedObj = clazz.cast(obj);
parse(castedObj);
}
fillObject(obj);
}


but when passing to parse an object of dynamic type B, where B extends A, castedObj is equal to obj. But I want castedObj to be a new object of dynamic type A because the parse method relies on that fact (iterates on the fields of the dynamic type class).




Using an existing array in another class



Let's change the way I am asking the question. For constructing an object in a class, we can also use some other variables. Consider this example:



public class Foo {
int X1;
int X2;
public Foo(int a) {
int[] array=new int[4];
// ...
}
}


If we create 2 objects of this class, we will have 2 variables per object and totally the memory will be occupied for 4 integer variables. My concern is the memory dedicated to the integer array defined inside the constructor. How the memory will be assigned when creating several objects?


Thanks,




Get java.lang.NoClassDefFoundError after adding library



I have downloaded java code and try to launch it on examples that are provided there. In particular I run java edu.toronto.cs.propagation.ic.ICEstimate -m 50 -d 1e-8 -s data/memeS.sn -i data/memeS.out -o data/memeS.probs from the main directory. However, I get the following message:



Exception in thread "main" java.lang.NoClassDefFoundError: com/martiansoftware/jsap/StringParser
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2531)
at java.lang.Class.getMethod0(Class.java:2774)
at java.lang.Class.getMethod(Class.java:1663)
at sun.launcher.LauncherHelper.getMainMethod(LauncherHelper.java:494)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:486)
Caused by: java.lang.ClassNotFoundException: com.martiansoftware.jsap.StringParser
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)


I have specified CLASSPATH and PATH as following:



export PATH="/home/sergey/miniconda/bin:$PATH" export CLASSPATH="/home/sergey/workspace/Spine/javalib/:$CLASSPATH" export CLASSPATH="/home/sergey/workspace/Spine/spine.0.1.jar:$CLASSPATH"



and I have jsap library in my javalib folder.


What can be the problem? How can I run the code?




Checking if class is child of class



I am loading classes via ClassLoader:



Class<?> clazz = urlClassLoader.loadClass(name.substring(0, name.length() - 6).replaceAll("/", "."));
System.out.println(clazz);
System.out.println(clazz.isInstance(SkillCast.class));
System.out.println(SkillCast.class.isInstance(clazz));
System.out.println(SkillCast.class.isAssignableFrom(clazz));
System.out.println(clazz.isAssignableFrom(SkillCast.class));


This is my structure:



public class SkillFireball extends SkillCast implements ISkillThrown
public abstract class SkillCast extends Skill


And prints are:



class skills.SkillFireball
false
false
false
false


What I am sure of is that clazz is SkillFireball and I can print field/method names.


How can I check if clazz is child of SkillCast?




Derby in JavaFX - Datas to Tableview



I want to write all data from a derby table to a TableView in JavaFX2. The connection with the local derby database is working, but I have no idea how could I upload the data from the table to the TableView (called 'List' in my case) Does anybody have an idea? I would really appreciate the help.




Dozer + Spring: MappingException: Dozer Bean Mapper is already initialized



I am trying to implement Dozer as help for bridge pattern on my current webapp running Spring and Hibernate but I think I am doing something wrong, since trying to use a DozerBeanMapper instance more than once, will give me a MappingException.


Spring config:



@Configuration
public class AppConfig {
...
@Bean
public DozerBeanMapper dozerBeanMapper() {
return new DozerBeanMapper();
}
}


Usage:



@Service
public class FooService {
@Autowired private DozerBeanMapper mapper;

public void doSomething() {
mapper.map(foo, ImmutableFoo.class);
...
}


First time I call this service will work fine, but any further attempt to use it will result in an exception. Can someone please point what I am doing wrong?


Thanks.




List Fragment with ActionBarActivity



If I need to use a toolbar in my activity but I don know how to use at the same time an ActionBarActivity and a ListFragment. What I must to do to mix these two things (ActionBarActivity and ListFragment?




How to control .gif behavior in JavaFX?



I wanted to have quick animation of button when it is hovered. I created still picture for button and a gif, which animates only once(looping option:once). And I presumed that after button is hovered gif will play once and stop. But in reality animation is looping and if I hover button again gif will start not from the beginning, but from the same place where it stopped. Is there a way to make gif behave normally: start from the beginning when button is hovered and stop once animation ends?


CSS code for button:



.clock_button{
-fx-background-image: url("images/pink.png");}

.clock_button:hover{
-fx-background-image: url("images/pink_a.gif");}



Calling "guess" variable for two objects in Java



I'm creating a game for homework, and I'm very stuck in the beginning stages. The game takes inputs from two players. The player class controls the guesses by each player. I've been able to correctly set up the player class so that it only accepts the allowed range of inputs.


However, I'm having difficulty calling the guess variable for two player objects. I've tried to determine how to call the value of each guess variable for each object, but it keeps giving me errors. Am I calling the variable correctly? Or is my logic of having two different guesses values for each player object correct? Or is there another way that I need to write the code to have a guess variable for each player?


player class code:



import java.util.Scanner;

public class player {

//handles the input from the player
public player() {

while (true) {

// Prompt the user to guess the number
System.out.println("Enter your guess: ");
Scanner input = new Scanner(System.in);
int guess = input.nextInt();
System.out.println(guess);

if (guess < 0) {
System.out.println("You entered a negative number.
+ "The number you enter must be between 0 and 4. " +
"Please try again. ");
}
else if (guess >= 5){
System.out.println("You entered is greater than 4. "
+ "The number you enter must be between 0 and 4. " +
"Please try again. ");
}
else{
break;
}

} // End of while loop

}//end of player method

}//End of player class


Main code:



public class HW2 {

public static void main(String[] args) {

System.out.println("It's Player A's turn to guess!");
player playerA = new player();
System.out.println(playerA.guess);


System.out.println("It's Player B's turn to guess!");
player playerB = new player();
System.out.println(playerB.guess);

}//end of main


} // end of HW2 class


Thank you in advance for any help!




How to create a for statement to handle my Exception



I had previously created a program that contained a customerList that added courses to each customer via their courseList. Now I have to modify the program (having a new list of customers) to throw an exception called CustomerNotEnrolledException if one the customers are not enrolled in any course.


I throw the exception from a createInvoice method in my Customer class, and handle it in the test class. My question is:


How will I write a for loop to check for these courses within each customer.


The two arrays that I have declared earlier are:



ArrayList<Course> courseList = new ArrayList<Course>();
ArrayList<Customer> customerList = new ArrayList<Customer>();



The Best Search Algorithm for a Linked List



I have to write a program as efficiently as possible that will insert given nodes into a sorted LinkedList. I'm thinking of how binary search is faster than linear in average and worst case, but when I Googled it, the runtime was O(nlogn)? Should I do linear on a singly-LinkedList or binary search on a doubly-LinkedList and why is that one (the one to chose) faster?


Also how is the binary search algorithm > O(logn) for a doubly-LinkedList? (No one recommend SkipList, I think they're against the rules since we have another implementation strictly for that data structure)




How to rotate a non-square image in Java?



I recently saw this question on how to rotate an image in Java. I copy/pasted it directly from that answer. On implementation, it seems to only rotate images that are squares(that is have the same size, width and height). When I try to use it for a non-square image, it seems to cut off that part that would make it be a rectangle, if that makes sense. Like this



How can I fix/work around this?




JS EventSource receiving mysterious error from my 3.0 async servlet



My EventSource connects, the output gets printed, but when I call asyncContext.complete() my JS EventSource receives an error. The errors for EventSource never bear a message.


For those who voted to close: It would be nice if you provided a reason next time. I even posted link to the Git project. What else is one supposed to do? o.O


Tested with Tomcat 7.0.30, 7.0.59, 8.0.20


The response returns with http status OK/200 and following headers:



  • Connection: close

  • Content-Type: text/event-stream;charset=UTF-8

  • Date: Sat, 28 Feb 2015 21:32:35 GMT

  • Server: Apache-Coyote/1.1

  • Transfer-Encoding: identity


In case anyone would be willing to try here's the minimized Maven project: BitBucket.org


I tried things like turning my antivirus SW off.


Can you see anything suspicious here, please?


JS:



function setupEventSource() {
var es = new EventSource('/sse');
es.onerror = function(event) {
console.log('[EventSource] Error while connecting to ' + es.url);
// es.close();
};
}
setupEventSource();


Java:



@WebServlet(urlPatterns = { "/sse" }, asyncSupported = true)
public class EventSource2 extends HttpServlet {
private static ScheduledExecutorService executor = Executors
.newScheduledThreadPool(10);

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/event-stream");
response.setCharacterEncoding("UTF-8");

final AsyncContext asyncContext = request.startAsync();

Runnable runnableDummy = new Runnable() {
@Override
public void run() {
try {
PrintWriter writer = asyncContext.getResponse().getWriter();
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
writer.println("data: Hello " + i + "\n");
writer.flush();
}
} catch (IOException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (InterruptedException e) {
throw new RuntimeException(e.getMessage(), e);
}

asyncContext.complete();
}
};

executor.execute(runnableDummy);
}

@Override
public void destroy() {
executor.shutdown();
}
}


server.xml



<Connector port="80" protocol="HTTP/1.1"
URIEncoding="UTF-8" connectionTimeout="20000" asyncTimeout="20000" />



Missing artifact com.oracle:ojdbc14:jar:10.2.0.1.0



I am trying to add dependency for ojdbc14 in pom.xml. Steps I followed for adding ojdbc14.jar in local repository of maven:



  1. Create a new project

  2. move to that particular folder where is pom.xml file was located in command prompt.

  3. execute the command mvn clean.


  4. execute the command:


    mvn install:install-file -Dfile=ojdbc14.jar -DgroupId=com.oracle -DartifactId=oracle -Dversion=10.2.0.1.0 -Dpackaging=jar -DgeneratePom=true




after this I got a build success message


![enter image description here][1]


I have updated the global and local repository in Eclipse > Maven Repositories


![enter image description here][2]


![enter image description here][3]



C:\> mvn install:install-file -Dfile="C:\Users\Dhia\Desktop\Nouveau dossier\ojdb
c14.jar" -DgroupId=com.oracle -DartifactId=ojdbc14 -Dversion=10.2.0.1.0 -Dpackag
ing=jar
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-install-plugin:2.4:install-file (default-cli) @ standalone-pom
---
[INFO] Installing C:\Users\Dhia\Desktop\Nouveau dossier\ojdbc14.jar to C:\Users\
Dhia\.m2\repository\com\oracle\ojdbc14\10.2.0.1.0\ojdbc14-10.2.0.1.0.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.460s
[INFO] Finished at: Sat Feb 28 22:44:13 CET 2015
[INFO] Final Memory: 4M/15M
[INFO] ------------------------------------------------------------------------
C:\>


my local repoitory is C:\Users\Dhia\Desktop\eclipse jee and when opening .com in eclipse oracle repository doesn't appear


when adding com.oracle ojdbc14 10.2.0.1.0


I got error in my pom.xml file, and I am not able to see the ojdbc14.jar file in my local repository. Is there any thing wrong in the steps I followed. Please help me out.


Thanks




Find the number of nodes at level of x and above



I want to find number the of nodes that are in the same level as the node with @title="d" or are in the higher level


XML:



<item title="a">
<item title="b">
<item title="c"></item>
<item title="d">
<item title="e"></item>
<item title="f"></item>
</item>
</item>
<item title="x">
<item title="y"></item>
<item title="z"></item>
</item>
</item>



L0 . . . . . . a . . . .
/ \
L1 . . . . . b . . x . .
/ \ / \
L2 . . . .c . d .y . z .
/ \
L3 . . . . .e . f . . . .

Some examples:



System.out.println(leftDomainSize("d")); // 7
System.out.println(leftDomainSize("x")); // 3
System.out.println(leftDomainSize("e")); // 9


Code:



public int leftDomainSize(String s){
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(path);
//????
}



Android: Is onPause() guaranteed to be called after finish()?



Couldn't find a solid answer to this anywhere. I have a method where finish() is being called, and onPause() is called afterward.


Is onPause() guaranteed to be called after a call to finish() ?




Need to save multiple entities within a grid. Could I somehow use ArrayLists inside twodimensional Arrays?



So I'm working on particle physics simulation using Java Processing where I now needs to keep track on what entities (objects with x and y coordinate) exists at certain parts of the screen. I'd also need to be able to know the cells' position to eachother as to do such as checking for collision between objects in a cell and bordering cells.


What's the best way to implement such a system? Is it somehow possible to put an ArrayList inside an array of arrays (2D-array)? Cause I didn't seem to manage to put lists inside arrays when I tried. Any better way to do it?




Java Graphics2D scale doubling



I'm having trouble scaling objects with Graphics2D in Java. In my paintComponent I create two graphics2D objects for easier management. I then try to scale them. The problem is that the output is scaled x4 (the scale commands affect each other). Otherwise everything renders as it should.


How is this best solved.


The code in question:



@Override
public void paintComponent(Graphics g) {
playerGraphics = (Graphics2D) g;
backgroundGraphics = (Graphics2D) g;

playerGraphics.scale(2.0, 2.0);
backgroundGraphics.scale(2.0, 2.0);

backgroundGraphics.drawImage(background.getBackground(), 0, 0, null);

for(int i = 0; i < noPlayers; i++) {
playerGraphics.drawImage(players.get(i).getCurrentSprite(), players.get(i).getXPos(), players.get(i).getYPos(), null);
}
}



android caller id app source for newbie



I am looking for source of caller id android app I can learn from. Soemthing like this (or more simple) http://ift.tt/1vKdqmS - but I can't build the app because of some problems with maven. Or something like this http://ift.tt/1Dm9CFI - but there is no code anymore.


I tried google for this but I can't find sources I can learn from. I prefer something I can open in eclipse and start learning code or makeing trial and error changes in it and the compile. Thank you.




Downloaded Java 7 Eclipse doesn't start



Ok, so I've been using eclipse Luna for a bit now with the Java 6 and all. Today, I decided it was time to update to Java 7. I did so by going to the Oracle site, downloading the Java 7 run time environment, and it said it would install. I let it install, but it told me that it detected previous versions of java (java 6) that it wanted to uninstall. I don't know a lot about the process and assumed it was fine and this probably isn't the problem anyway. But it installed, and when I tried to run things in eclipse, it gave me an error. So I restarted Eclipse. Suddenly, it wouldn't start giving me the error code 13. Then, I re installed Eclipse Luna. Now I get the same error and am worried I totally screwed up my Java. Can you help? I can also post the error report it gives me.



Java was started but returned exit code=13
C:/ProgramData/Oracle/Java/javapath/Javaw.exe
-Dosgi.requiredJavaVersion=1.6
-Xms40m
-Xmx512m
-jar
C:/Users/Jared/Downloads/eclipse-java-luna-SR2-win32x86_64/eclipse//plugins/org.eclipse.equinox.launcher_1.3.0.v20140415-2008.jar
-os win32
-ws win32
-arch x86_64
-showsplash
C:/Users/Jared/Downloads/eclipse-java-luna-SR2-win32-x86_64/eclipse//plugins/org.eclipse.platform_4.4.2.v20150204-1700/splash.bmp
-launcher
C:/Users/Jared/Downloads/eclipse-java-luna-SR2-win32-x86_64/eclipse/eclipse.exe
-name Eclipse
--launcher.library
C:/Users/Jared/Downloads/eclipse-java-luna-SR2-win32-x86_64/eclipse//plugins/org.eclipse.equinox.launcher.win32.x86_64_1.1.200.v20150204-1316/eclipse_1608.dll
-startup
C:/Users/Jared/Downloads/eclipse-java-luna-SR2-win32-x86_64/eclipse//plugins/org.eclipse.equinox.launcher_1.3.0.v20140415-2008.jar
--launcher.appendVmargs
-exitdata 2b0_5c
-product org.eclipse.epp.package.java.product
-vm C:/ProgramData/Oracle/Java/javapath/javaw.exe
-vmargs
-Dogsi.requiredJavaVersion=1.6
Xms40m
-Xmx512m
-jar
C:/Users/Jared/Downloads/eclipse-java-luna-SR2-win32-x86_64/eclipse//plugins/org.eclipse.equinox.launcher_1.3.0.v20140415-2008.jar


If I check my java version via command prompt, it looks like this:



C:\Users\Jared>java -version
java version "1.8.0_31"
Java(TM) SE Runtime Environment (build 1.8.0_31-b13)
Java HotSpot(TM) Client VM (build 25.31-b07, mixed mode)


I have minimal knowledge on this process however, if my educated guess is right, Luna is based on 1.6-1.7 and since I apparently have 1.8.0_31, I need a more updated version.


If you know how to help, please explain thoroughly, so I can understand as much as possible Thanks in advance


-Jared.




Multiplying two dimensional Array lists



I'm learning ArrayLists. All I'm trying to do is to multiply two different ArrayLists. Given below is the code. The code generates one ArrayList from user input and the second ArrayList is given in the code.



import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;

public class prog3 {

public static void main(String[] args) {

ArrayList<ArrayList<Integer>> array = new ArrayList<ArrayList<Integer>>();
Scanner sc = new Scanner(System.in);
System.out.println("enter the number of rows ");
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
array.add(new ArrayList<Integer>());
for (int j = 0; j < 2; j++) {
array.get(i).add(sc.nextInt());
}
}
Iterator it = array.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}

ArrayList<ArrayList<Integer>> arr = new
ArrayList<ArrayList<Integer>>();
arr.add(new ArrayList<Integer>());
arr.add(new ArrayList<Integer>());

arr.get(0).add(5);
arr.get(0).add(4);
arr.get(1).add(7);
arr.get(1).add(8);
Iterator it2 = arr.iterator();
while (it2.hasNext()) {
System.out.println(it2.next());
}

for (int r = 0; r < array.size(); r++) {
for (int h = 0; h < arr.size(); h++) {

System.out.println(r * h);
}
}
}
}



How to replace cocos2d-x scene from Java?



I want to replace the scene in a cocos2d project from Java. I created the following JNI methods:



void cocos_android_app_init (JNIEnv* env, jobject thiz) {
LOGD("cocos_android_app_init");
AppDelegate *pAppDelegate = new AppDelegate();
}

extern "C" {
JNIEXPORT void JNICALL Java_com_example_myapp_MainActivity_changeScene(
JNIEnv* env, jobject thiz){
cocos2d::Scene* scene = MyScene::createScene();
Director::getInstance()->replaceScene(
TransitionFade::create( 1, scene ));
//NOT WORKING BECAUSE Director::getInstance() is NULL
}
}


However, when the method changeScene is called from java, my App crashes because Director::getInstance() seems to be a NULL-pointer. How can the scene be changed correctly from Java?




Why won't the textField print date?



Why wont this tidField.setText(date); work? Everything else works, the date is taken from getDatum() which is a diffrent class that works perfectly fine when called here textArea.append(r.getLista()); but for tidField.setText(date); it wont change the field



final JComboBox<String> comboBox = new JComboBox<String>();
comboBox.addItem("Företag");
comboBox.addItem("Normal");
comboBox.addItem("Student");
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
Kund kek = new Kund();
int kb = 0;
String date = kek.getDatum();
String SaldoString = "";
JComboBox<?> comboBox = (JComboBox<?>) event.getSource();
Object selected = comboBox.getSelectedItem();
if(selected.toString().equals("Normal")) {
Register r = new Register();
Kund k = new Normal();
k.setBelopp(100);
k.setDatum(date);
r.regKund(k);
int tempbelopp = k.getBelopp();
String b = Integer.toString(tempbelopp);
tidField.setText(date);
beloppField.setText(b);
kb = kb + 100;
SaldoString = Integer.toString(kb);
saldoText.setText(SaldoString);
textArea.append(r.getLista());
}
else if(selected.toString().equals("Student")) {
Register r = new Register();
Kund k = new Normal();
k=new Student();
k.setBelopp(50);
k.setDatum(date);
beloppField.setText(date);
tidField.setText(date);
if( kb >=50)
r.regKund(k);
kb = kb - 50;

textArea.append("Det finns inga cash, student reggades ej!" + "\n");

}
else if(selected.toString().equals("Företag")) {
Register r = new Register();
Kund k = new Normal();
k.setBelopp(0);
k.setDatum("20:17");
k.setLopnummer(r.getLopnummer());
r.regKund(k);
// Den skriver ut samma skit ändra det
textArea.append(r.getLista());
textArea.append("Kassan har nu "+kb+" kr" + "\n");
}

}
});
comboBox.setToolTipText("Välj vilken typ av Kund du är");
comboBox.setRenderer(new MyComboBoxRenderer("Välj..."));
//comboBox.setSelectedIndex(-1);
comboBox.setBounds(171, 46, 97, 22);
frame.getContentPane().add(comboBox);


}
}



How to create and interact with a custom grid like sudoku of size m*n in android



I started working on an android project which looks something like the image attached below.enter image description here


I created a relative layout which should now contain two layouts. A linear which has a timer and a custom layout which should have a n*n grid layout.(say 8*10) horizontal layout.


I need to interact with grids like clicking on the grid should add an image to the grid etc. Is there a better way of implementing this rather than gridview?


Thanks




How To Sort Strings of JComboBoxes in JTables?



I have following problem:


I've inserted into the 5th column of my JTable for each row an JComboBox-Object. Everything is fine until I want to rowsort the column with setAutoCreateRowSorter(true). In this case im getting following exception:



ClassCastException: java.lang.String cannot be cast to javax.swing.JComboBox


Here are my classes that im using for my JTable:


The TableModel:



private class MyTableModel implements TableModel {

@Override
public void addTableModelListener(TableModelListener l) {
}

@Override
public Class<?> getColumnClass(int columnIndex) {

switch (columnIndex) {
case 0:
return String.class;
case 1:
return String.class;
case 2:
return String.class;
case 3:
return Number.class;
case 4:
return Boolean.class;
case 5:
return String.class;
default:
return null;
}

}

@Override
public int getColumnCount() {
return columnNames.length;
}

@Override
public String getColumnName(int columnIndex) {
return columnNames[columnIndex];
}

@Override
public int getRowCount() {
return data[0].length - 1;
}

@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return data[rowIndex][columnIndex];

}

@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
switch (columnIndex) {
case 5:
return true;
default:
return false;
}

}

@Override
public void removeTableModelListener(TableModelListener l) {
}

@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
data[rowIndex][columnIndex] = aValue;

}

}


The TableRenderer:



public class StringTableCellRenderer extends JLabel implements
TableCellRenderer {

private static final long serialVersionUID = 1L;

public StringTableCellRenderer() {
setOpaque(true);
setLayout(new BorderLayout());
}

@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
Font font = getFont().deriveFont(Font.BOLD, 15);

if ((row % 2) == 0) {
setBackground(new Color(240, 255, 255));
} else {
setBackground(new Color(191, 239, 255));
}

if (isSelected) {
setBackground(new Color(0, 191, 255));
}

setHorizontalAlignment(JLabel.CENTER);
setForeground(Color.BLACK);
setFont(font);

if (value instanceof JComboBox) {
setText((String) ((JComboBox<?>) value).getSelectedItem());
} else {
setText(value.toString());
}

return this;
}

}


And the TableEditor:



public class MyTableCellEditor extends AbstractCellEditor implements
TableCellEditor, ActionListener {

private static final long serialVersionUID = 1L;
private String fieldValue = null;


@Override
public void actionPerformed(ActionEvent event) {
if (event.getSource() instanceof JComboBox<?>) {
JComboBox<?> jComboBox = (JComboBox<?>) event.getSource();
fieldValue = (String) jComboBox.getSelectedItem();
}
}

@Override
public Object getCellEditorValue() {
System.out.println("Editor: getCellEditorValue()");
return fieldValue;
}

@Override
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
JComboBox<String> comboBox = new JComboBox<String>();
comboBox.addItem("Me");
comboBox.addItem("You");
comboBox.addItem("They");
comboBox.addItem("Us");
comboBox.addItem("We");
comboBox.addActionListener(this);
System.out.println("Editor: getTableCellEditorComponent");
if (value instanceof JComboBox<?>) {
fieldValue = (String) ((JComboBox<?>) value).getSelectedItem();
}

comboBox.setSelectedItem(fieldValue);

return comboBox;
}

}


My idea for that problem was defining an own RowSorter-object and adding it to my JTable-Object (jTable) like this:



private class JComboBoxBoxComparator implements
Comparator<JComboBox<String>> {

@Override
public int compare(JComboBox<String> o1, JComboBox<String> o2) {
return ((String) o1.getSelectedItem()).compareTo((String) o2
.getSelectedItem());
}

}


TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(
jTable.getModel());
sorter.setComparator(5, new JComboBoxBoxComparator());
jTable.setRowSorter(sorter);


Unfortunately this does not have any effect....




Java Array.Out.Of.Bound exception



I have a huge problem I can not understant why this part of code throws this exception because I can not see where I get out of my array bound? I want to derive a polinom with int coeff and positive powers. i save my powers in an array iPower and my coeff in iCoefficient. in my polinom class iMaxPower gives my the highest fower of my polinom.



public int DerivePolinom(Polinom p1, Polinom p2)//operation class
{
int i,count=0;
i=p1.iMaxPower;

while(i>0)
{
if(p1.iPower[i]==1)// here is my exception!
{
p2.iPower[i]=1;//I know it does not derive my polinom
p2.iCoefficient[i]=p1.iCoefficient[i];
count++;// use this to know the nr of the result polinom terms

}
i++;
}

return count;
}



int iDegreeMax=0;//main class
System.out.print("Enter the polinom: number of terms-power-coefficient \n");
Polinom p1 = new Polinom();//create my polinom object
iDegree=sc.nextInt();//read the numbers of terms
p1.readPolinom(iDegree);//read my polinom
p1.printPolinom(p1,iDegree);

Operation o = new Operation();//create operation object
Polinom p2 = new Polinom();//we create another polinom object to pun the result in
iDegreeMax=o.DerivePolinom(p1,p2);
System.out.print("\nThe derivation of the polinom is: ");
p2.printPolinom(p2,iDegreeMax);



Find path through maze using recursion



I have these two methods, one is called findPath, which should recursively find the path through the maze. And another one called solve, which I think should just call findPath. The problem I am facing now is that I keep getting an array out of bounds exception. I think it's at the part where I create variable up in findPath.But I wrote a method to check if the move is valid. Here is the code:





private static boolean isLegal(int row, int col){
if(row < 0 || row >= numRows){
return false;
}
if(col < 0 || col >= numCols){
return false;
}

return false;
}

public MazeLocationList solve() {
findPath(0,1,8,9);
return path;
}

private boolean findPath(int fromRow, int fromCol, int toRow, int toCol) {
boolean solved = false;
visited = new boolean [numRows][numCols];
char right = maze[fromRow][fromCol+1];
char left = maze[fromRow][fromCol-1];
char up = maze[fromRow-1][fromCol];
char down = maze[fromRow+1][fromCol];


if (right == ' ' && isLegal(fromRow,fromCol+1) && visited[fromRow][fromCol+1]==false) {
point = new MazeLocation(fromRow,fromCol+1);
path.insertTail(point);
solved= findPath(fromRow, fromCol+1, toRow, toCol);
}
if (left == ' ' && isLegal(fromRow,fromCol-1) && visited[fromRow][fromCol-1]==false) {
point = new MazeLocation(fromRow,fromCol-1);
path.insertTail(point);
solved= findPath(fromRow, fromCol-1, toRow, toCol);
}
if (up == ' ' && isLegal(fromRow+1,fromCol) && visited[fromRow+1][fromCol]==false) {
point = new MazeLocation(fromRow+1,fromCol);
path.insertTail(point);
solved= findPath(fromRow+1, fromCol, toRow, toCol);
}
if(down == ' ' && isLegal(fromRow-1,fromCol) && visited[fromRow-1][fromCol]==false) {
point = new MazeLocation(fromRow-1,fromCol);
path.insertTail(point);
solved= findPath(fromRow-1, fromCol,toRow,toCol);
}

return solved;
}



Thanks in advance




When to use JViewport.getExtentSize() vs. JViewport.getSize()?



Looking at the source, it seems that JViewport.getExtentSize() always returns the same value as JViewport.getSize() (The same holds for setExtentSize() and setSize()). Why do both exist? Is it just an alias to make it clearer in code that you are getting the size (visible extent) of the viewport.view? Is there something else happening in the UI delegates and/or something related to plaf that I'm missing? Or, does getExtentSize() exist purely for symmetry with setExtentSize(), and the latter exists to provide different notification than setSize() (I note ChangeListeners are notified when setExtentSize() is called)?




Good cross-platform format for config files?



I need to be able to get strings in Java from a configuration file that is platform independent. It needs to be human readable. Which file formats are suitable? Thanks!




Creating pdf with latex in a Java program



Is there a library that would ease creating pdfs out of latex code in Java?


The aim is to add pdf report creation in a Java app. As Latex can produce sophisticated pdfs, the idea would be to fill the values in latex code using java and generate the pdf with latex compiler.


Any good way to do this?




vendredi 27 février 2015

All permutations of ArrayList



I am trying to write a program that returns all permutations of an ArrayList. So far it's only working when using 0, 1, or 2 elements. However I know there is something wrong with my final "else" statement, I just cannot figure out what. This is pretty confusing to me and I'm not quite sure how to go about it...



import java.util.ArrayList;

public class Permutation
{
public static ArrayList<ArrayList<Integer>> permutation(final ArrayList<Integer> list)
{
ArrayList<Integer> yourList = list;
return insertTypePermutation(yourList);

}

public static ArrayList<ArrayList<Integer>> insertTypePermutation(ArrayList<Integer> yourList)
{
ArrayList<Integer> arrayList = new ArrayList<Integer>();

for(int i = 0; i < yourList.size(); i++)
{
arrayList.add(yourList.get(i));
}

ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();

if(yourList.size() < 2)
{
result.add(yourList);
return result;
}
else if(yourList.size() == 2)
{
result.add(yourList);
result.add(reverse(yourList));
return result;
} //problem starts: -----------------------------------------------
else
{
int firstEntry = yourList.get(0);
yourList.remove(0);
result = insertTypePermutation(yourList);
int currResultSize = result.size();
int currResultElementSize = result.get(0).size();

for(int i = 0; i < currResultSize; i++)
{
for(int j = 0; j <= currResultElementSize; j++)
{
ArrayList<Integer> tempResult = result.get(0);
tempResult.add(j, firstEntry);
result.add(tempResult);

if(j == currResultElementSize)
{
result.remove(0);
}
}
}

return result;
} //problem ends ^ -------------------------------------------
}

public static ArrayList<Integer> reverse(final ArrayList<Integer> someList)
{
ArrayList<Integer> tempList = new ArrayList<Integer>();

for(int i = 0; i < someList.size(); i++)
{
tempList.add(someList.get(i));
}

int temp = tempList.get(0);
tempList.remove(0);
tempList.add(temp);
return tempList;
}


}




This is my program so far, it wants to print an upside down right triangle until "6 5 4" is printed. I can't seemto get it to 6 5 4 much less stop it



This is my program so far, it wants to print an upside down right triangle until "6 5 4" is printed. I can't seem to get it to 6 5 4 much less stop it


import java.util.Scanner;


public class Lab16C {



private int num;

public static void main(String[ ] args)
{
Lab16C lab = new Lab16C( );
lab.input(); // Read rom the keyboard
lab.output(); // Display output
}

public void input() {
Scanner reader = new Scanner(System.in);
System.out.print("Enter a number: ");
num = reader.nextInt();
}

public void output(){
for(int y = 0 ; y < num ; y++)
{
for(int x = num ; x >= 4; x--)
System.out.print(x + " ");
num = num -1;
System.out.println ();
}
}


}




Java , add new string object if the length of the chain exceeds a number of character



I'm trying to add a new String in arraylist if the lenght of this one is too big.


like that;



private void createLore(String s) {
ArrayList<String> a = new ArrayList<String>();
if(s.lenght > maximumLenght) {
a.add(s /TODO new object with same string
//it's like a new line .. possible to detect a space ?
//This avoids the cut of a text


Thank's !




How do I force the HTTP Request Connector to use a certain Content-Type?



In Mule 3.6, I have the following HTTP Request Connector:



<http:request config-ref="IPAM_Request_Config" path="${ipam.path}" method="POST" doc:name="Send SMS to IPAM">
<http:request-builder>
<http:query-param paramName="mobile" value="sms.mobile"/>
<http:query-param paramName="textmsg" value="sms.text"/>
<http:query-param paramName="receiver" value="sms.receiver"/>
<http:query-param paramName="mobileoperator" value="sms.operator"/>
<http:query-param paramName="circle" value="sms.circle"/>
<http:query-param paramName="time" value="sms.time"/>
</http:request-builder>
</http:request>


How do I force this to take the Content-Type as application/x-www-form-urlencoded. It is taking text/plain;charset=windows-1252 even though the payload is a org.mule.module.http.internal.ParameterMap.




Dynamically update a member based on other member in class



This is my class



public class Cars{

public double Len;
public List<Double> vehicle;


setters and getters



public List<Double> getVehicle() {
return vehicle;
}
public void setVehicle(List<Double> vehicle) {
this.vehicle= vehicle;
this.Len = this.vehicle.size();

}

public double getLen() {
return Len;
}

public void setLen(double Len) {
this.Len = Len;
}


}


Is it possible to update the member Len with length of position List of vehicles .