I have data.txt file saved in SD card containing values of variables required for driving 3 stepper motors. I want to read data.txt file line by line, split the line by "," and save each values into respective variables. data.txt file has data something like this:
8.24, 5.67, 7.34
3,86, 3.56, 4.49
5.38, 6.29, 3.67
I want to save value of first integer in x, second in y and third in z and execute the code. Once the code is executed, I want to get next line and load respective values in their respective variables and continue the loop till there is no line left in data.txt file
This code for matrix, let change some type that you need
public Matrix loadIntMapData(InputStream input) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line;
ArrayList<double[]> list = new ArrayList<double[]>();
while ((line = reader.readLine()) != null) {
if (line.equals("")) {
//ignore
} else {
String[] vs = line.split(",");
double ints[] = new double[vs.length];
for (int i = 0; i < ints.length; i++) {
ints[i] = Double.parseDouble(vs[i]);
}
list.add(ints);
}
}
double[][] map = new double[list.size()][];
for (int i = 0; i < map.length; i++) {
map[i] = list.get(i);
}
return new Matrix(map);
}
public static final void writInteMapData(Matrix matrix, File file) throws IOException {
double[][] map = matrix.getArray();
StringBuffer output = new StringBuffer();
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) {
output.append(Double.toString(map[i][j]));
if (j != map[i].length - 1) {
output.append(",");
}
}
if (i != map.length - 1) {
output.append("\r\n");
}
}
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write(output.toString());
writer.close();
}
Related
enter image description hereWe are trying to convert lzw compressed raster(tiff) into text format(meaning extracting each pixel centroid and band1 value.. We see that some parts of the raster is missed while conversion.. however there is a pattern in miss data (data is coming in unequal striped pattern) Please see snapshot up .. Yellow dots shows the centroid converted while no overlap with yellow the data is missed while converting..
we have tried the tile size 128 and 256 but the output was different in both the cases
List<String> tiffExtensions = new ArrayList<>();
tiffExtensions.add(".tif");
tiffExtensions.add(".TIF");
tiffExtensions.add(".tiff");
tiffExtensions.add(".TIFF");
final scala.Option<CRS> crsNone = scala.Option.apply(null);
final scala.Option<Object> objectNone = scala.Option.apply(null);
final scala.Option<Object> numPartitionsObject = scala.Option.apply(new Integer(10));
final scala.Option<Object> tileSize = scala.Option.apply(Integer.parseInt("256"));
final scala.Option<Object> partitionBytes = scala.Option.apply(128l * 1024 * 1024);
HadoopGeoTiffRDD.Options options = new HadoopGeoTiffRDD.Options$().apply(
JavaConverters.asScalaIteratorConverter(tiffExtensions.iterator()).asScala().toSeq(), crsNone,
HadoopGeoTiffRDD.GEOTIFF_TIME_TAG_DEFAULT(), HadoopGeoTiffRDD.GEOTIFF_TIME_FORMAT_DEFAULT(), tileSize,
numPartitionsObject, partitionBytes, objectNone);
RDD<Tuple2<ProjectedExtent, Tile>> rasterImageRdd = HadoopGeoTiffRDD.spatial(new Path(rastedImageDir), options,
javaSparkContext.sc());
JavaRDD<Tuple2<ProjectedExtent, Tile>> rasterImageJavaRdd = rasterImageRdd.toJavaRDD();
JavaRDD<String> pixelRdd = rasterImageJavaRdd
.flatMap(new FlatMapFunction<Tuple2<ProjectedExtent, Tile>, String>() {
private static final long serialVersionUID = -6395159549445351446L;
public Iterator<String> call(Tuple2<ProjectedExtent, Tile> v1) throws Exception {
ArrayList<String> list = new ArrayList<String>();
Tile t = v1._2;
ProjectedExtent projectedExtent = v1._1;
ProjectedRaster<CellGrid> r = new ProjectedRaster<CellGrid>(
new Raster<CellGrid>(t, projectedExtent.extent()), projectedExtent.crs());
GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(), 4283);
WKTWriter wktWriter = new WKTWriter();
for (int i = 0; i < t.rows(); i++) {
for (int j = 0; j < t.cols(); j++) {
StringBuilder sb = new StringBuilder();
if (!Double.isNaN(t.getDouble(j, i))) {
Double elevation = t.getDouble(j, i);
Tuple2<Object, Object> longLatTupel = r.raster().rasterExtent().gridToMap(j, i);
if (longLatTupel._2() != null && longLatTupel._1() != null) {
Double latitude = Double.parseDouble(longLatTupel._2() + "");
Double longitude = Double.parseDouble(longLatTupel._1() + "");
Point point = geometryFactory.createPoint(new Coordinate(longitude, latitude));
sb.append(elevation).append(TAB_SEP);
sb.append(point);
list.add(sb.toString());
}
}
}
}
return list.iterator();
}
});
_
Hi i working on poi poc to generate xlsx file in webapplication i was able to render excel standalone well but when i integrate codebase in my project i was getting below error.
below is code base base to download xlsx file in webapplication
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet spreadsheet = workbook.createSheet("Sheet1");
XSSFRow row = spreadsheet.createRow(0);
XSSFCell cell;
while (response.nextResultSet()) {
resultSet = response.getResultSet();
Object[] columnMetaData = resultSet.getColumnNames();
int columnCount = columnMetaData.length;
//Columns Loop
ArrayList<String> columns = new ArrayList<String>();
for (int i = 1; i < columnCount; i++) {
String columnName = (String) columnMetaData[i];
columns.add(columnName);
cell = row.createCell(i-1);
cell.setCellValue(columnName);
}
int i=1;
while (resultSet.nextRow()) {
row = spreadsheet.createRow(i);
i++; // counter for each row of data
for (int j = 0; j < columnMetaData.length; j++)
{
String keyVal = String.valueOf(columnMetaData[j]);
String value = (String)resultSet.getValue(keyVal);
cell = row.createCell(j);
cell.setCellValue(value);
}
}
log.info("value if i--->" + i);
for (int k = 1; k < columnCount; k++) {
spreadsheet.autoSizeColumn(k-1);
}
}
ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
workbook.write(outByteStream);
context.getResponse().setHeader("content-disposition", "inline;filename=" + calendar.getTimeInMillis() + ".xlsx");
context.getResponse().setContentType("application/Excel");
context.getRequest().setAttribute("called_from", "excel");
//context.getResponse().setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//context.getResponse().setHeader("Content-Disposition", "attachment; filename=testxls.xlsx");
}
OutputStream os = null;
os = context.getResponse().getOutputStream();
byte [] outArray = is.toByteArray();
context.getResponse().setContentLength(outArray.length);
os.write(outArray);
log.info(os.toString());
os.flush();
I have created a web app which creates 1 text file. Inside this text file it is created 1000 rows with the same word "TRY AGAIN". After this each 50 rows I put a random code which means in 1000 rows, 20 rows are random.
This is my code:
static Random randNum = new Random();
public static string Random(int ran)
{
string _charachters = "ABCDEFGHIJKMLNOPQRSTUVWXYZ0123456789";
char[] chars = new char[ran];
int allowedCharCount = _charachters.Length;
for (int i = 0; i < ran; i++)
{
chars[i] = _charachters[(int)((_charachters.Length) * randNum.NextDouble())];
}
return new string(chars);
}
protected void Button1_Click(object sender, EventArgs e)
{
string pathCreate = #"C:\" + TextBox3.Text + ".txt";
if (!File.Exists(pathCreate))
{
using (StreamWriter sw = File.CreateText(pathCreate))
{
for (int i = 1; i <= int.Parse(TextBox1.Text); i++)
{
sw.WriteLine("TRY AGAIN.");
}
}
}
string pathRandom = #"C:\" + TextBox3.Text + ".txt";
string[] lines = File.ReadAllLines(pathRandom);
for (int i = 0; i < lines.Length; i += int.Parse(TextBox2.Text))
{
lines[i] = lines[i].Replace("TRY AGAIN.", Random(int.Parse("7")));
}
File.WriteAllLines(pathRandom, lines);
}
Now I want to create 2 ore more text files with one click of a button. And on each text file there will be random codes (not duplicates). Any idea?
Thank You.
I found the solution. It is late in my country and my brain barely works. :P
for(int j = 1; j <= 10; j++)
{
string pathKrijo = #"C:\inetpub\wwwroot\KODET\" + j.ToString() + ".txt";
using (StreamWriter sw = File.CreateText(pathKrijo))
{
for (int i = 1; i <= 100; i++)
{
sw.WriteLine("Provo Përsëri.");
}
}
string pathKodFitues = #"C:\inetpub\wwwroot\KODET\" + j.ToString() + ".txt";
string[] lines = File.ReadAllLines(pathKodFitues);
for (int i = 0; i < lines.Length; i += 10)
{
lines[i] = lines[i].Replace("Provo Përsëri.", Random(int.Parse("7")));
}
File.WriteAllLines(pathKodFitues, lines);
}
//Firstly I need to create a 2-D array of floating points(randomly generated) and store them in a text file no of rows and columns are user input
import java.io.;
import java.util.;
public class ClaransS {
public static void main(String args[]) throws IOException {
// *********************************************************************
// Variables declaration n-no.of rows k-forget it for now n_o_d-no. of
// columns
// *********************************************************************
int n, k, n_o_d;
// *********************************************************************
// Creating the text file to store data
// *********************************************************************
File f = new File("C:/x/y/clarans.text");
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
// *********************************************************************
// Taking user inputs
// *********************************************************************
Scanner userInputScanner = new Scanner(System.in);
System.out.println("Enter the no. of data you want to cluster");
n = userInputScanner.nextInt();
System.out.println(n);
System.out.println("Enter the no. of clusters you want to form");
k = userInputScanner.nextInt();
System.out.println(k);
System.out
.println("Enter the no. of dimensions each data will be in a space of");
n_o_d = userInputScanner.nextInt();
System.out.println(n_o_d);
userInputScanner.close();
// *********************************************************************
// Storing random data in the data-set
// *********************************************************************
double data_set[][] = new double[n][n_o_d];
int count = 1;
int i = 0;
int j = 1;
for (i = 0; i < n; i++) {
data_set[i][0] = count;
for (j = 1; j <= n_o_d; j++) {
//THIS LINE GIVES ERROR
data_set[i][j] = (double) Math.random();//YES THIS ONE XXX
}
count++;
}
for (i = 0; i < n; i++) {
for (j = 0; j <= n_o_d; j++) {
try (PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter(f, true)))) {
out.print(data_set[i][j] + "\t");
} catch (IOException e) {
}
}
try (PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter(f, true)))) {
out.println();
}
}
}
}
The error is in test condition of for
(j = 1; j <= n_o_d; j++).
Test condition will be j < n_o_d
I have a text file where I get my values,
I have a timer which works as an increaser to the x axis so the plot is real time.
here's my code.
void gui::x()
{
int xy = 0;
QVector<double> x(1000), y(1000);
FILE *file;
char line[1024];
file = fopen("x.txt", "r");
while (fgets(line,1024,file) != NULL)
{
fscanf(file,"%lf %lf", &y[xy], &x[xy]);
xy++;
}
fclose(file);
QwtPlotCurve *curve = new QwtPlotCurve;
curve->attach(plot_all[3]);
curve->setData(y,x);
curve->
QwtPlotCurve *curve2 = new QwtPlotCurve;
curve2->attach(plot[3]);
curve2->setData(y,x);
}
the proble is i get a weird second line below my plot.
can anyone help me?
I solved it by using an array instead of a vector.
void gui::ecg()
{
int xy = 0;
double x[1000], y[1000];
FILE *file;
char line[1024];
file = fopen("ecg.txt", "r");
while (fgets(line,1024,file) != NULL)
{
fscanf(file,"%lf %lf", &y[xy], &x[xy]);
xy++;
}
fclose(file);
QwtPlotCurve *curve = new QwtPlotCurve;
curve->attach(plot_all[0]);
curve->setData(x,y,1000);
curve->setPen(QPen(Qt::blue,1));
QwtPlotCurve *curve2 = new QwtPlotCurve;
curve2->setStyle(QwtPlotCurve::Lines);
curve2->attach(plot[0]);
curve2->setData(x,y,1000);
curve2->setPen(QPen(Qt::blue,1));
}