JavaFX TableView how to get file size to PropertyValueFactory? - file

I have some TableView with two columns - name and size;
This Table works with File objects;
PropertyValueFactory for columns can take properties of object, trying search somenameProrperty, getSomename, isSomename;
I'm need to get length() method from File.
columnName.setCellValueFactory(new PropertyValueFactory<>("name"));
columnSize.setCellValueFactory(new PropertyValueFactory<>("length"));
This code view file names (getName() method), but length colums is empty.
Know anyone what i can do with factory to get length() from File?

You should implement the cell value factory directly, instead of using the convenience (and somewhat legacy) class PropertyValueFactory.
Assuming your columnSize is a TableColumn<File, Number>, you can do
columnSize.setCellValueFactory(cellData ->
new SimpleLongProperty(cellData.getValue().length()));
If you want to format the data in the column more elegantly, you can additionally set a cell factory:
columnSize.setCellFactory(col -> new TableCell<File, Number>() {
#Override
protected void updateItem(Number length, boolean empty) {
super.updateItem(length, empty);
if (empty) {
setText(null);
} else {
setText(formatFileLength(length.longValue()));
}
}
});
// ...
private String formatFileLength(long length) {
final String[] unitNames = {"bytes", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"};
int i ;
for (i = 0 ; length > 1024 && i < unitNames.length - 1 ; i++) {
length = length / 1024 ;
}
return String.format("%,d %s", length, unitNames[i]);
}

Found solution
columnSize.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<File, String>, ObservableValue<String>>() {
#Override
public ObservableValue<String> call(TableColumn.CellDataFeatures<File, String> param) {
long size = param.getValue().length();
size = size/1024;
return new ReadOnlyObjectWrapper(String.valueOf(size));
}
});

Related

Shifting array data structure C#

I was curious to know if there is an efficient way to store data into a container that has a maximum amount of values and when that value is reached it start removing the oldest values in order to add new ones. And all this in an ordered fashion (meaning that new data should come after the last new data).
I know I could achieve this using a queue
q.Enqueue(1);
q.Enqueue(2);
q.Enqueue(3); // 1 2 3
q.Dequeue(); // 2 3
q.Enqueue(4); // 2 3 4
but in order to iterate through the data afterwards requires to transform the queue in an array, which I'm not sure how efficient it is.
Maybe it's better to have an array with a fixed size and have an index that shifts to the start when the array is full and using some modulo magic iterate always backwards to query the data from most recent to less recent. This would be less readable but working and more efficient I guess.
So my question would be, is there a better more readable and efficient way?
And also, what is the efficiency of using ToArray() when using other data structures (e.g. List, Queue, Stack..). When should this be avoided?
At the end I decided to implement my idea. Not sure if this is the best way, but it works well for my needs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DataHolder<T> : IEnumerable
{
private T[] _data;
private int _maxSize;
private int _currIdx;
private int _currSize;
public DataHolder(int size)
{
_maxSize = size;
_data = new T[_maxSize];
_currIdx = -1;
_currSize = 0;
}
public void Add(T data)
{
if (_currSize < _maxSize) _currSize++;
_currIdx = NioUtils.PositiveMod((_currIdx + 1), _maxSize);
_data[_currIdx] = data;
}
///<summary>
/// Gets the element at index. The 0 element is the last one added.
///</summary>
public T GetElementAt(int index)
{
if (index >= _currSize)
{
throw new System.ArgumentException("Index out of bounds exception.", "index");
}
int shiftIndex = NioUtils.PositiveMod((_currIdx - index), _maxSize);
return _data[shiftIndex];
}
/// Implement interface IEnumerable in order to iterate throught this object.
public IEnumerator GetEnumerator()
{
int count = 0;
int index = _currIdx;
while (count < _currSize)
{
count++;
yield return _data[index];
index = NioUtils.PositiveMod((index - 1), _maxSize);
}
}
}
Where PositiveMod is:
public static int PositiveMod(int value, int n)
{
int v = value % n;
return v >= 0 ? v : n + v;
}

What does the error unexpected token 'public' mean?

I am a beginner in Apex and I need your help. What I am trying to do is creating a class that returns an array of formatted strings. The class has as a parameter the number of strings and it returns the array of strings formatted as:
Test 0, Test 1, ...Test n
The error I get is:
unexpected token 'public (line 1).
There might be more than one error in my code, if yes please feel free to let me know.
Thank you in advance!
public class StringArrayTest {
public static void generateStringArray(Integer n){
//List<String> stringArray = new List<String>();
for(Integer i=0; i<n; i++){
List<String>stringArray = new List<String>{'Test '+i};
}
return stringArray[];
}
}
There are a few things wrong with the code you have posted. When I tried this out I didn't get the error you mentioned, but here are the things to fix and get your code working:
The method should declare a return value of List<String>
Uncomment the line to initialize your list before the loop.
Return just the variable itself, no need to have the brackets. It's already a list.
Here is working code:
public class StringArrayTest {
public static List<String> generateStringArray(Integer n){
List<String> stringArray = new List<String>();
for(Integer i = 0; i < n; i++){
stringArray.add('Test ' + i);
}
return stringArray;
}
}

How can i store the results returned by a method into an array for further use? (Java)

I am trying to store the results returned from a method into an array, however I don´t know which would be the best way to do it.
public class Wealth {
METHOD
double taxes() {
return (0.08*riquezaEnCarros) + (0.15*riquezaEnCasas);
ARRAY?
double [] = taxes();
NEW EDIT
double riquezaTotalHijo() {
return riquezaEnEfectivo + riquezaEnCarros + riquezaEnCasas -
impuestosHijo() + riquezaTotalPadre();
}
public ArrayList<Double> list = new ArrayList<>();
list.add(riquezaTotalHijo());
}
If you are using array then we can assume that you want to call method multiple times
Let if you want to call it 5 times
List<double> list = new ArrayList<double>();
for(int i=0; i<5;i++)
{
//Add values to array list
list.add(taxes());
}
//ArrayList list have values now
//Now you can loop on array list to use values
for (double val : list) {
System.out.println(val);
}

Extend the Array class in AS3

I've been learning OOP recently and have decided to take that paradigm shift into it (its not easy...at ALL) and in trying some of the concepts of it I'm having a bit of a problem inheriting from the Array class in ActionScript 3.0 (not that i have tried in AS 2.0)...sigh. Anyway I am trying to call the parent constructor to instantiate the ...rest arguments from within the child class like so
public class CustomArray extends Array{
public function CustomArray(...rest):void {
super(rest);
}
}
And I keep getting this Error from the output...
ReferenceError: Error #1056: Cannot create property 0 on classes.CustomArray.
...to my utter dismay :(.
I'm obviously doing something wrong but for the love of me can't seem to find out what it is. Really in need of help. Thanks.
Unfortunately in AS3 you can't call super constructor and pass parameters to it in Function::apply style, so in your Array implementation array with length=1 and one element (the passed rest parameter with the type of Array) will always be created.
If you want to implement the default AS3 Array constructor behavior:
Array Constructor
public function Array(... values)
Parameters
... values — A comma-separated list of one or more arbitrary values.
Note: If only a single numeric parameter is passed to the Array constructor,
it is assumed to specify the array's length property.
You have to add some code to the constructor of your CustomArray:
public dynamic class CustomArray extends Array
{
public function CustomArray(...rest)
{
super();
var i:int, len:int;
if(rest.length == 1)
{
len = rest[0];
for (i = 0; i < len; i++)
this[i] = "";
}
else
{
len = rest.length;
for (i = 0; i < len; i++)
this[i] = rest[i];
}
}
}
Also don't forget to make this class dynamic.
Declare this class as dynamic. Also constructor is a method which doesn't specify return type, remove :void from its declaration.
Sorry to revive this "old" thread. I felt compelled to improve the constructor proposed by fsbmain.
When one calls new Array("foo"), an Array object is created containing the String "foo" - ["foo"]. So I think the custom constructor must take that possibility into account ( only one parameter that is not a number).
Here's the code I propose:
package {
public dynamic class MyArray extends Array {
public function MyArray(...rest) {
// super();
// I think super() is not mandatory here since
// we are basically replacing the constructor...
var i: int, len: int;
if (rest.length == 1) {
if(rest[0] is Number){
len = rest[0];
for (i = 0; i < len; i++) {
this[i] = null; // empty values must be null, not ""
}
}else{
this[0]=rest[0];
}
} else {
len = rest.length;
for (i = 0; i < len; i++) {
this[i] = rest[i];
}
}
}
}
}

Is there any possibility to store all database fields value into one array variable if all fields have same datatype in java?

in this program i have used different array variable for each of
the fields in a
database.In database all fields having the same datatype and now i want to store all
the fields values into one array variable.is it possible???
import java.sql.*;
class ja1
{
public static void main(String ar[])
{
try
{
int x,i,j,k,l;
int a[]=new int[30];
int b[]=new int[30];
int c[]=new int[30];
int d[]=new int[30];
int count[]=new int[10];
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c1=DriverManager.getConnection("Jdbc:Odbc:ds");
Statement s=c1.createStatement();
ResultSet r=s.executeQuery("select * from pro");
i=0;
j=0;
k=0;
l=0;
x=0;
while(r.next())
{
a[i]=r.getInt(2);
i++;
b[j]=r.getInt(3);
j++;
c[k]=r.getInt(4);
k++;
d[l]=r.getInt(5);
l++;
}
for(i=0;i<6;i++)
System.out.println(""+a[i]);
for(j=0;j<6;j++)
System.out.println(""+b[j]);
System.out.print("\n\n");
for(k=0;k<6;k++)
System.out.println(""+c[k]);
System.out.print("\n\n");
for(l=0;l<6;l++)
System.out.println(""+d[l]);
}
catch(Exception e)
{
System.out.print(e);
}
}
}
Yes, it is possible in several ways :
1) If you want to use only one array then please create an array with size of 120 (4X30) and use 4 counter to arrange your data in range. That means, your first variable would be from index 0 to 29, the 2nd would be from 30 to 69 and so on. This is not good if you don't know the exact size of your array as you are binding them with perfect size of 30.
2) You can create a POJO and have 4 arrays into it, you can use a List instead of array, but it depends on your implementation. So, create a class, put 4 arrays into it, give good variable names and access thru getter/setter methods. This will be a clear code
3) You can use a Map<Integer,Integer[]> or Map<Integer,List<Integer>> and have a single variable/reference which is holding your key value pair.
It all depends on you, if you dont know, why are you using arrays,then please move the Collection
I would define a POJO for the record and then use a generic list to add and iterate the record/s
Try this:
class RecordData
{
public int First;
public int Second;
public int Third;
public int Fourth;
}
class ja1
{
public static void main(String ar[])
{
try
{
List<RecordData> list = new ArrayList<RecordData>;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c1=DriverManager.getConnection("Jdbc:Odbc:ds");
Statement s=c1.createStatement();
ResultSet r=s.executeQuery("select * from pro");
while(r.next())
{
RecordData data = new RecordData();
data.First = r.getInt(2);
data.Second = r.getInt(3);
data.Third = r.getInt(4);
data.Fourth = r.getInt(5);
list.add(data);
}
for(RecordData data : list) {
System.out.println(data.First);
System.out.println(data.Second);
System.out.println(data.Third);
System.out.println(data.Fourth);
}
}
catch(Exception e)
{
System.out.print(e);
}
}
}

Resources