i am quite new to Javafx, and would like your help in solving the below:
I have two tableviews, and i would like to compare the column values between the two and highlight the cell of one of the tables, if the values are different.
(Assumption - both tables have same number of columns, restricting rows to the minimum content among tables)
ex:
table 1 has
column1 column2 column3
1 America Newyork
table 2 has
column1 column2 column3
1 America Washington
The second table last column should be highlighted with a textfill
I have this pseudo code, doesnt seem to work though
int colsize1= tableview1.getColumns().size();
int colsize2= tableview2.getColumns().size();
if(colsize1 != colsize2) {
alert("number of columns do not match, cannot be validated");
return;
}
ObservableList<ObservableList<String>> da1 = FXCollections.observableArrayList();
ObservableList<ObservableList<String>> da2 = FXCollections.observableArrayList();
da1.addAll(tableview1.getItems());
da2.addAll(tableview2.getItems());
int size = Math.min(da1.size(), da2.size());
for(int i = 0; i < size; i++) {
for (int j = 0; j < colsize1; j++) {
if(!(tableview1.getItems().get(i).get(j).equals(tableview2.getItems().get(i).get(j)))) {
String value = tableview1.getItems().get(i).get(j);
String value2 = tableview2.getItems().get(i).get(j);
int currentrow = i;
TableColumn<TableView<ObservableList<String>>, String> columns = (TableColumn) tableview2.getColumns().get(j);
columns.setCellFactory(column -> {
return new TableCell<TableView<ObservableList<String>>, String>() {
#Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
System.out.println("item is " + item + " empty is " + empty);
if(empty){
if(value != value2){
this.setStyle("-fx-background-color : yellow");
}
}
if (!empty) {
if((value != item) && currentrow == getTableRow().getIndex()) {
// int rowindex = getTableRow().getIndex();
System.out.println(" item is " + item);
this.setText(item);
this.setTextFill(Color.RED);
this.setStyle("-fx-background-color : yellow");
}else {
this.setText(item);
}
}
}
};
});
}
}
}
}
I found a solution to the given problem.
#FXML
public void onvalidatebutton() {
int colsize1 = tableview1.getColumns().size();
int colsize2 = tableview2.getColumns().size();
if (colsize1 != colsize2) {
alert("number of columns do not match, cannot be validated");
return;
}
int size = tableview1.getItems().size();
for (int i = 0; i < size; i++) {
for (int j = 0; j < colsize1; j++) {
TableColumn columns2 = tableview2.getColumns().get(j);
// String value = tableview1.getItems().get(currentrow).get(j);
settingcell(columns2);
}
}
}
private void settingcell(TableColumn<ObservableList<String>,String> column) {
column.setCellFactory(col -> {
return new TableCell<ObservableList<String>, String>() {
#Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (!empty) {
int ind = getTableView().getVisibleLeafIndex(column);
// System.out.println(" ind is " + ind);
String value = tableview1.getItems().get(this.getIndex()).get(ind);
// System.out.println(" value is " + value + " & item is "+ item);
if (!(StringUtils.equals(value,item))) {
this.setText(item);
this.setTextFill(Color.RED);
this.setStyle("-fx-background-color : yellow");
} else {
this.setText(item);
}
}
else{
this.setText("");
}
}
};
});
}
Related
I wrote a program for a binary addition in java. But the result is sometimes not right.
For example if i add 1110+111. The result should be 10101.
But my program throws out 10001.
Maybe one of you find the mistake.
import java.util.Scanner;
public class BinaryAdder {
public static String add(String binary1, String binary2) {
int a = binary1.length()-1;
int b = binary2.length()-1;
int sum = 0;
int carry = 0;
StringBuffer sb = new StringBuffer();
while (a >= 0 || b >= 0) {
int help1 = 0;
int help2 = 0;
if( a >=0){
help1 = binary1.charAt(a) == '0' ? 0 : 1;
a--;
} if( b >=0){
help2 = binary2.charAt(b) == '0' ? 0 : 1;
b--;
}
sum = help1 +help2 +carry;
if(sum >=2){
sb.append("0");
carry = 1;
} else {
sb.append(String.valueOf(sum));
carry = 0;
}
}
if(carry == 1){
sb.append("1");
}
sb.reverse();
String s = sb.toString();
s = s.replaceFirst("^0*", "");
return s;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("First: ");
String input1 = scan.next("(0|1)*");
System.out.print("Second: ");
String input2 = scan.next("(0|1)*");
scan.close();
System.out.println("Result: " + add(input1, input2));
}
}
this function is much simpler :
public static String binaryAdd(String binary1,String binary2){
return Long.toBinaryString(Long.parseLong(binary1,2)+Long.parseLong(binary2,2));
}
you can change Long.parseLong into Integer.parseInt if you don't expect very large numbers, you can also replace parse(Long/Int) with parseUnsigned(Long/Int) since you don't expect your strings to have a minus sign do you ?
You are not considering the case when
help1 + help2 = 3
So your method String add(String binary1, String binary2) should be like this:
public static String add(String binary1, String binary2) {
int a = binary1.length()-1;
int b = binary2.length()-1;
int sum = 0;
int carry = 0;
StringBuffer sb = new StringBuffer();
while (a >= 0 || b >= 0) {
int help1 = 0;
int help2 = 0;
if( a >=0){
help1 = binary1.charAt(a) == '0' ? 0 : 1;
a--;
} if( b >=0){
help2 = binary2.charAt(b) == '0' ? 0 : 1;
b--;
}
sum = help1 +help2 +carry;
if (sum == 3){
sb.append("1");
carry = 1;
}
else if(sum ==2){
sb.append("0");
carry = 1;
} else {
sb.append(String.valueOf(sum));
carry = 0;
}
}
if(carry == 1){
sb.append("1");
}
sb.reverse();
String s = sb.toString();
s = s.replaceFirst("^0*", "");
return s;
}
I hope this could help you!
sum = help1 +help2 +carry;
if(sum >=2){
sb.append("0");
carry = 1;
} else {
sb.append(String.valueOf(sum));
carry = 0;
}
If sum is 2 then append "0" and carry = 1
What about when the sum is 3, append "1" and carry = 1
Will never be 4 or greater
Know I'm a bit late but I've just done a similar task so to anyone in my position, here's how I tackled it...
import java.util.Scanner;
public class Binary_Aids {
public static void main(String args[]) {
System.out.println("Enter the value you want to be converted");
Scanner inp = new Scanner(System.in);
int num = inp.nextInt();
String result = "";
while(num > 0) {
result = result + Math.floorMod(num, 2);
num = Math.round(num/2);
}
String flippedresult = "";
for(int i = 0; i < result.length(); i++) {
flippedresult = result.charAt(i) + flippedresult;
}
System.out.println(flippedresult);
}
}
This took an input and converted to binary. Once here, I used this program to add the numbers then convert back...
import java.util.Scanner;
public class Binary_Aids {
public static void main(String args[]) {
Scanner inp = new Scanner(System.in);
String decimalToBinaryString = new String();
System.out.println("First decimal number to be added");
int num1 = inp.nextInt();
String binary1 = decimalToBinaryString(num1);
System.out.println("Input decimal number 2");
int num2 = inp.nextInt();
String binary2 = decimalToBinaryString(num2);
int patternlength = Math.max[binary1.length[], binary2.length[]];
while(binary1.length() < patternlength) {
binary1 = "0" + binary2;
}
System.out.println(binary1);
System.out.println(binary2);
int carry = 0;
int frequency_of_one;
String result = "";
for(int i = patternlength -i; i >= 0; i--) {
frequency_of_one = carry;
if(binary1.charAt(i) == '1') {
frequency_of_one++;
}
if(binary2.charAt(i) == '1') {
frequency_of_one++;
}
switch(frequency_of_one) {
case 0 ;
carry = 0;
result = "1" + result;
break;
case 1 ;
carry = 0;
result = "1" + result;
break;
case 2;
carry = 1;
result = "0" + result;
breake;
case 3;
carry = 1;
result = "1" + result;
breake;
}
}
if(carry == 1) {
result = "1" + result;
}
System.out.println(result);
}
public static String decimalToBinaryString(int decimal1) {
String result = "";
while(decimal1 > 0) {
result = result + Math.floorMod(decimal1, 2);
decimal = Math.round(decimal1/2);
}
String flipresult = "";
for(int i = 0; i < result.length[]; i++) {
flipresult = result.charAt(i) + flippedresult;
}
return flippedresult;
}
}
hallo i have this sniped code like this:
public static void Put_CSVtoSQL_Adhesion()
{
bool IsFirst = true;
DataTable dt = new DataTable();
string line = null;
int i = 0;
try
{
string fileName = Path.Combine(HttpContext.Current.Server.MapPath(UploadDirectory), TheFileName);
using (StreamReader sr = File.OpenText(fileName))
{
while ((line = sr.ReadLine()) != null)
{
string[] data = line.Split(';');
if (data.Length > 0)
{
if (i == 0)
{
foreach (var item in data)
{
dt.Columns.Add(new DataColumn());
}
i++;
}
DataRow row = dt.NewRow();
row.ItemArray = data;
// Pour enlever la tete
if (!IsFirst) dt.Rows.Add(row);
IsFirst = false;
}
}
}
using (var connectionWrapper = new Connexion())
{
var connectedConnection = connectionWrapper.GetConnected();
using (SqlBulkCopy copy = new SqlBulkCopy(connectionWrapper.conn))
{
int CountColl = dt.Columns.Count;
copy.ColumnMappings.Add(0, 1);
copy.ColumnMappings.Add(1, 2);
copy.ColumnMappings.Add(2, 3);
copy.ColumnMappings.Add(3, 4);
copy.ColumnMappings.Add(4, 5);
copy.DestinationTableName = "cotisation";
copy.WriteToServer(dt);
}
}
}
catch (Exception excThrown)
{
throw new Exception(excThrown.Message);
}
}
this code work well, but now i have more than 60 column, should i type manualy from 1 to 60 column or there are another methode ?
copy.ColumnMappings.Add(0, 1);
copy.ColumnMappings.Add(1, 2);
copy.ColumnMappings.Add(2, 3);
copy.ColumnMappings.Add(3, 4);
copy.ColumnMappings.Add(4, 5);
...until 60 column ?
the column is all the same i just shifted 1 column, because the first one is autoincremented column as an ID
Write a loop?
for (int i = 0; i < dt.Columns.Count - 1; i++)
{
copy.ColumnMappings.Add(i, i + 1);
}
I am trying to do multiple columns sorting in my application .
Like i have firstname , last name columns
Right now , when i click on firstname header , it sorts as per firstname , when i click on lastname column it sorts as per lastname column..
what i need is when i click on firstname header it should sort on the basis of firstname and then if i click on lastname(with shift or any other option) header it should sort on the basis of both firstname and lastname , firstname as primary column and last name as sub sorting column
here is what i have now
private void sortTableUsers(List<UserDTO> userList){
ListDataProvider<UserDTO> dataProvider = new ListDataProvider<UserDTO>();
dataProvider.addDataDisplay(usersTable);
List<UserDTO> list = dataProvider.getList();
for (UserDTO UserDTO : userList) {
list.add(UserDTO);
}
final ListHandler<UserDTO> columnSortHandler = new ListHandler<UserDTO>(list);
columnSortHandler.setComparator(firstNameColumn,new Comparator<UserDTO>() {
public int compare(UserDTO o1,UserDTO o2) {
if (o1 == o2) {
return 0;
}
// Compare the firstname columns.
if (o1 != null) {
return (o2 != null) ? o1.getUser().getFirstName().compareTo(o2.getUser().getFirstName()) : 1;
}
return -1;
}
});
columnSortHandler.setComparator(lastNameColumn,new Comparator<UserDTO>() {
public int compare(UserDTO o1,UserDTO o2) {
if (o1 == o2) {
return 0;
}
// Compare the lastname columns.
if (o1 != null) {
return (o2 != null) ? o1.getUser().getLastName().compareTo(o2.getUser().getLastName()) : 1;
}
return -1;
}
});
usersTable.getColumnSortList().push(firstNameColumn);
usersTable.getColumnSortList().push(middleNameColumn);
}
Well, you need a different comparator for each column, the second comparator is the one that you need to change.
First it must sort for FirstName,and if the firstnames are equal, then go on and compare the last names too.
I'm not using your DTO, and i don't check for nulls, but it's the same thing, you get the idea
ArrayList<Map> list = new ArrayList<Map>();
ListHandler<Map> _sortHandler = new ListHandler<Map>(list);
Column columnDefinitionFirstName = null; // create your column first name
columnDefinitionFirstName.setSortable(true);
//
_sortHandler.setComparator(columnDefinitionFirstName, new Comparator<Map>()
{
public int compare(Map o1, Map o2)
{
int res = 0;
String object1 = (String) o1.get("FIRST_NAME");
String object2 = (String) o2.get("FIRST_NAME");
res = object1.compareTo(object2);
return res;
}
});
Column columnDefinitionLastName = null; // create your column last name
columnDefinitionLastName.setSortable(true);
_sortHandler.setComparator(columnDefinitionLastName, new Comparator<Map>()
{
public int compare(Map o1, Map o2)
{
int res = 0;
String object1 = (String) o1.get("FIRST_NAME");
String object2 = (String) o2.get("FIRST_NAME");
res = object1.compareTo(object2);
if(res == 0)
{
String object11 = (String) o1.get("LAST_NAME");
String object22 = (String) o2.get("LAST_NAME");
res = object11.compareTo(object22);
}
return res;
}
});
I am working on my C# ADO.NET app. I have connected my SQL Server database with C# app, and I can perform simple CRUD operations. I want to make that my app open my reminder form when someone in my database have birthday, so I made my query and all persons who have birthday on today's day are in my query, and with using property from my reminder form I change label's text with name and surname of person who have birthday. Now I just dont know how to change next label's text when more than one person have birthday in my query... I dont know how to get next element in my foreach loop...
Here is my code:
Form2 forma = new Form2();
TBirthDayEntities today_born = new TBirthDayEntities();
public Form1()
{
InitializeComponent();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 1000;
timer1.Enabled = true;
timer1.Start();
}
private Boolean provjera_rodj()
{
Boolean flag = false;
int cnt = 0;
IQueryable<TBD> query;
using (var data = new TBirthDayEntities())
{
query = (from x in data.TBD
where x.BirthDay.Day == System.DateTime.Now.Day && x.BirthDay.Month == System.DateTime.Now.Month
select x);
foreach (var x in query)
{
today_born.TBD.Add(x);
cnt += 1;
flag = true;
}
}
switch (cnt)
{
case 1:
{
foreach (var x in today_born.TBD)
{
forma.p_label2 = x.FName + " " + x.LName;
}
break;
}
case 2:
{
foreach (var x in today_born.TBD)
{
forma.p_label2 = x.FName + x.LName;
forma.p_label3 = x.FName + x.LName; //wrong
}
break;
}
}
return flag;
}
private void timer1_Tick(object sender, EventArgs e)
{
Boolean flag = provjera_rodj();
if (flag == true)
{
forma.Show();
timer1.Stop();
}
}
switch (cnt)
{
case 1:
case 2:
{
var lstLabel = new List<Label>()
{
forma.p_label2
, forma.p_label3
};
for(int i = 0; i < today_born.TBD.Count; i++)
{
var x in today_born.TBD[i];
lstLabel[x].Text = x.FName + x.LName;
}
break;
}
}
EDIT:
switch (cnt)
{
case 1:
case 2:
{
var lstLabel = new List<Action<string>>()
{
new Action<string>(s =>forma.p_label2 = s)
, new Action<string>(s =>forma.p_label3 = s)
};
for(int i = 0; i < today_born.TBD.Count; i++)
{
var x = today_born.TBD[i];
lstLabel[x](x.FName + x.LName);
}
break;
}
}
I need a sus implementation in c# for finding candidate individuals in a population this is what i have so far but im not sure if it is correct.
public void sus(IEnumerable<TimeTable>population)
{
var ag = population.Sum(i => normalize((double) i.Fitness, true));
var mark = rnMutate.NextDouble();
var index = 0;
foreach (var candidate in population)
{
var cu = population.Sum(i => normalize((double)i.Fitness, false)) / ag * 5;
while (cu > mark + index)
{
Survivors.Add(candidate);
index++;
}
}
}
public double normalize(double fitness, bool natural)
{
if (natural)
return fitness;
return fitness == (double)FitnessLBound ? double.PositiveInfinity : 1 / fitness;
}
private IEnumerable<TimeTable> StochasticSample(IEnumerable<TimeTable> population, int size)
{
var t = population.Sum(it => it.Fitness);
var temp = new List<TimeTable>();
var ptr = rnMutate.NextDouble();
var sum = 0M;
for (int i = 0; i < size; i++)
{
for (sum += ExpValue(i, t); sum > (decimal) ptr; ptr++)
{
temp.Add(population.ElementAt(i));
--size;
}
}
return temp;
}
private decimal ExpValue(decimal fitness, decimal sum)
{
return decimal.Divide(fitness, sum);
}