How to convert EPSG:4326 to EPSG:32632 Osmdroid - gps

I get my position in EPSG: 4326 by my Android GPS, now i would convert it coordinates to EPSG: 32632.
Someone have an idea?

Use geotools.
http://www.geotools.org/
Here is an transformation example.
http://docs.geotools.org/stable/userguide/library/api/jts.html
First, you have to remove 3 jar files from the download directory as follows:
For example geotools version 18.0,
gt-epsg-hsql-18.0.jar gt-epsg-oracle-18.0.jar
gt-epsg-postgresql-18.0.jar
There are almost two cases existing.
1. using decode method of a CRS class:
CRSFactory crsFactory = ReferencingFactoryFinder.getCRSFactory(null);
CoordinateReferenceSystem targetCRS = null;
CoordinateReferenceSystem sourceCRS = null;
Geometry transCoordGeometry = null;
try {
targetCRS = CRS.decode("EPSG:32632");
sourceCRS = CRS.decode("EPSG:4326");
} catch (FactoryException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
MathTransform transform = null;
try {
transform = CRS.findMathTransform(sourceCRS, targetCRS);
transCoordGeometry = JTS.transform(orgGeometry, transform);
} catch (FactoryException | MismatchedDimensionException | TransformException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Using a wkt string.
the string variable of the targetWKT from
http://spatialreference.org/ref/epsg/wgs-84-utm-zone-32n/prettywkt/
PROJCS["WGS 84 / UTM zone 32N",
GEOGCS["WGS 84",
DATUM["WGS_1984",
SPHEROID["WGS 84",6378137,298.257223563,
AUTHORITY["EPSG","7030"]],
AUTHORITY["EPSG","6326"]],
PRIMEM["Greenwich",0,
AUTHORITY["EPSG","8901"]],
UNIT["degree",0.01745329251994328,
AUTHORITY["EPSG","9122"]],
AUTHORITY["EPSG","4326"]],
UNIT["metre",1,
AUTHORITY["EPSG","9001"]],
PROJECTION["Transverse_Mercator"],
PARAMETER["latitude_of_origin",0],
PARAMETER["central_meridian",9],
PARAMETER["scale_factor",0.9996],
PARAMETER["false_easting",500000],
PARAMETER["false_northing",0],
AUTHORITY["EPSG","32632"],
AXIS["Easting",EAST],
AXIS["Northing",NORTH]]
Then, the code is:
CRSFactory crsFactory = ReferencingFactoryFinder.getCRSFactory(null);
CoordinateReferenceSystem targetCRS = null;
CoordinateReferenceSystem sourceCRS = null;
Geometry transCoordGeometry = null;
try {
targetCRS = crsFactory.createFromWKT(targetWKT);
sourceCRS = CRS.decode("EPSG:4326");
} catch (FactoryException e1) {
e1.printStackTrace();
}
MathTransform transform = null;
try {
transform = CRS.findMathTransform(sourceCRS, targetCRS);
transCoordGeometry = JTS.transform(orgGeometry, transform);
} catch (FactoryException | MismatchedDimensionException | TransformException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Related

File provider error to receive pdf from another program

`# Dears, this class works well to receive PDF files from another application on below Android 6, but it gives an error for Android uper 6
` #RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public int ExtractImage(Intent intent) {
try {
String filepath = null;
if (intent != null) {
String action = intent.getAction();
String type = intent.getType();
if (Intent.ACTION_VIEW.equals(action) && type.endsWith("pdf")) {
Uri file_uri = intent.getData();
if (file_uri != null) {
filepath = file_uri.getPath();
}
} else if (Intent.ACTION_SEND.equals(action) && type.endsWith("pdf")) {
Uri uri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (uri != null) {
filepath = uri.getPath();
}
}
}
File file = new File(filepath);
PdfRenderer renderer = null;
Bitmap bm;
try {
renderer = new PdfRenderer(ParcelFileDescriptor.open(file,
ParcelFileDescriptor.MODE_READ_ONLY));
} catch (Exception e) {
}
assert renderer != null;
final int pageCount = renderer.getPageCount();
totalPage = pageCount;
for (int i = 0; i < pageCount; i++) {
PdfRenderer.Page page = renderer.openPage(i);
// Create a bitmap and canvas to draw the page into
int width = 570;
int zarib = 570 / (page.getWidth() + 1);
int height = (page.getHeight() * 2) + 1;
heightArray.add(i, height);
// Create a bitmap and canvas to draw the page into
bm = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// Create canvas to draw into the bitmap
Canvas c = new Canvas(bm);
// Fill the bitmap with a white background
Paint whiteBgnd = new Paint();
whiteBgnd.setColor(Color.WHITE);
whiteBgnd.setStyle(Paint.Style.FILL);
c.drawRect(0, 0, width, height, whiteBgnd);
// paint the page into the canvas
page.render(bm, null, null, PdfRenderer.Page.RENDER_MODE_FOR_PRINT);
// Save the bitmap
OutputStream outStream = null;
try {
outStream = new
FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/printDo2ta" + i + ".png");
} catch (Exception e) {
e.printStackTrace();
}
bm.compress(Bitmap.CompressFormat.PNG, 80, outStream);
try {
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
page.close();
}
} catch (Exception e) {
runOnUiThread(() -> Toast.makeText(getBaseContext(),
"خطا در پردازش فایل: " + e.getMessage(),
Toast.LENGTH_SHORT).show());
}
return totalPage;
}
I inserted this code in AndroidManifest.xml
`<provider
android:name="androidx.core.content.FileProvider"
android:authorities="ir.myproject.test.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths" />
</provider>`
`
And I made the class provider_paths.xml
`<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="external_files" path="."/>
</paths>`
I don't know what else I need to change to make it work on Android 8
please help me`

Why are results in the browser using Google AutoML so different from an exported tflite file in my android app?

I'm training a model using Google AutoML. I then exported a TFLite model to run on an android app.
With the same image used in the app and in the browser (Google AutoML gives you a chance to test your model in the browser), I get a very accurate answer in the browser but in my app, I get a not-so accurate answer.
Any thoughts on why this could be happening?
Relevant code:
public void predict(String imagePath, final Promise promise) {
imgData.order(ByteOrder.nativeOrder());
labelProbArray = new byte[1][RESULTS_TO_SHOW];
try {
labelList = loadLabelList();
} catch (Exception ex) {
ex.printStackTrace();
}
Log.w("FIND_ ", imagePath);
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
convertBitmapToByteBuffer(bitmap);
try {
tflite = new Interpreter(loadModelFile());
} catch (Exception ex) {
Log.w("FIND_exception in loading tflite", "1");
}
tflite.run(imgData, labelProbArray);
promise.resolve(getResult());
}
private WritableNativeArray getResult() {
WritableNativeArray result = new WritableNativeArray();
//ArrayList<JSONObject> result = new ArrayList<JSONObject>();
try {
for (int i = 0; i < RESULTS_TO_SHOW; i++) {
WritableNativeMap map = new WritableNativeMap();
map.putString("label", Integer.toString(i));
float output = (float)(labelProbArray[0][i] & 0xFF) / 255f;
map.putString("prob", String.valueOf(output));
result.pushMap(map);
Log.w("FIND_label ", Integer.toString(i));
Log.w("FIND_prob ", String.valueOf(labelProbArray[0][i]));
}
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
private List<String> loadLabelList() throws IOException {
Activity activity = getCurrentActivity();
List<String> labelList = new ArrayList<String>();
BufferedReader reader =
new BufferedReader(new InputStreamReader(activity.getAssets().open(LABEL_PATH)));
String line;
while ((line = reader.readLine()) != null) {
labelList.add(line);
}
reader.close();
return labelList;
}
private void convertBitmapToByteBuffer(Bitmap bitmap) {
if (imgData == null) {
return;
}
imgData.rewind();
Log.w("FIND_bitmap width ", String.valueOf(bitmap.getWidth()));
Log.w("FIND_bitmap height ", String.valueOf(bitmap.getHeight()));
bitmap.getPixels(intValues, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
// Convert the image to floating point.
int pixel = 0;
//long startTime = SystemClock.uptimeMillis();
for (int i = 0; i < DIM_IMG_SIZE_X; ++i) {
for (int j = 0; j < DIM_IMG_SIZE_Y; ++j) {
final int val = intValues[pixel++];
imgData.put((byte) ( ((val >> 16) & 0xFF)));
imgData.put((byte) ( ((val >> 8) & 0xFF)));
imgData.put((byte) ( (val & 0xFF)));
Log.w("FIND_i", String.valueOf(i));
Log.w("FIND_j", String.valueOf(j));
}
}
}
private MappedByteBuffer loadModelFile() throws IOException {
Activity activity = getCurrentActivity();
AssetFileDescriptor fileDescriptor = activity.getAssets().openFd(MODEL_PATH);
FileInputStream inputStream = new FileInputStream(fileDescriptor.getFileDescriptor());
FileChannel fileChannel = inputStream.getChannel();
long startOffset = fileDescriptor.getStartOffset();
long declaredLength = fileDescriptor.getDeclaredLength();
return fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength);
}
One of the things I don't know if is correct is how I adjust my output data into a probability. In the getResult() method, I write this:
float output = (float)(labelProbArray[0][i] & 0xFF) / 255f;
I divide by 255 in order to get a number between 0 and 1, but I don't know if this is correct.
The .tflite model is a quantized uint8 model if that helps.

SCALA: executing complete .sql file

I have a .sql script files and need to execute complete .sql file at once, I have found many related answers, where programmer reads file and execute query one by one.
I require to run .sql file all at-once, like picking up the file and executing in within SCALA.
Currently I am doing it with following code, copied it from copied it from:https://gist.github.com/joe776/831762, my Lead ask me to do it in simple way, instead of executing script line by line, it should get executed as .SQL file
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ScriptRunner {
private static final String DEFAULT_DELIMITER = ";";
private static final String DELIMITER_LINE_REGEX = "(?i)DELIMITER.+";
private static final String DELIMITER_LINE_SPLIT_REGEX = "(?i)DELIMITER";
private final Connection connection;
private final boolean stopOnError;
private final boolean autoCommit;
private PrintWriter logWriter = new PrintWriter(System.out);
private PrintWriter errorLogWriter = new PrintWriter(System.err);
private String delimiter = DEFAULT_DELIMITER;
private boolean fullLineDelimiter = false;
/**
* Default constructor.
*
* #param connection
* #param autoCommit
* #param stopOnError
*/
public ScriptRunner(Connection connection, boolean autoCommit, boolean stopOnError) {
this.connection = connection;
this.autoCommit = autoCommit;
this.stopOnError = stopOnError;
}
/**
* #param delimiter
* #param fullLineDelimiter
*/
public void setDelimiter(String delimiter, boolean fullLineDelimiter) {
this.delimiter = delimiter;
this.fullLineDelimiter = fullLineDelimiter;
}
/**
* Setter for logWriter property.
*
* #param logWriter
* - the new value of the logWriter property
*/
public void setLogWriter(PrintWriter logWriter) {
this.logWriter = logWriter;
}
/**
* Setter for errorLogWriter property.
*
* #param errorLogWriter
* - the new value of the errorLogWriter property
*/
public void setErrorLogWriter(PrintWriter errorLogWriter) {
this.errorLogWriter = errorLogWriter;
}
/**
* Runs an SQL script (read in using the Reader parameter).
*
* #param reader
* - the source of the script
* #throws SQLException
* if any SQL errors occur
* #throws IOException
* if there is an error reading from the Reader
*/
public void runScript(Reader reader) throws IOException, SQLException {
try {
boolean originalAutoCommit = connection.getAutoCommit();
try {
if (originalAutoCommit != autoCommit) {
connection.setAutoCommit(autoCommit);
}
runScript(connection, reader);
} finally {
connection.setAutoCommit(originalAutoCommit);
}
} catch (IOException e) {
throw e;
} catch (SQLException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("Error running script. Cause: " + e, e);
}
}
/**
* Runs an SQL script (read in using the Reader parameter) using the connection passed in.
*
* #param conn
* - the connection to use for the script
* #param reader
* - the source of the script
* #throws SQLException
* if any SQL errors occur
* #throws IOException
* if there is an error reading from the Reader
*/
private void runScript(Connection conn, Reader reader) throws IOException, SQLException {
StringBuffer command = null;
try {
LineNumberReader lineReader = new LineNumberReader(reader);
String line = null;
while ((line = lineReader.readLine()) != null) {
if (command == null) {
command = new StringBuffer();
}
String trimmedLine = line.trim();
if (trimmedLine.startsWith("--")) {
println(trimmedLine);
} else if (trimmedLine.length() < 1 || trimmedLine.startsWith("//")) {
// Do nothing
} else if (trimmedLine.length() < 1 || trimmedLine.startsWith("--")) {
// Do nothing
} else if (!fullLineDelimiter && trimmedLine.endsWith(getDelimiter())
|| fullLineDelimiter && trimmedLine.equals(getDelimiter())) {
Pattern pattern = Pattern.compile(DELIMITER_LINE_REGEX);
Matcher matcher = pattern.matcher(trimmedLine);
if (matcher.matches()) {
setDelimiter(trimmedLine.split(DELIMITER_LINE_SPLIT_REGEX)[1].trim(),
fullLineDelimiter);
line = lineReader.readLine();
if (line == null) {
break;
}
trimmedLine = line.trim();
}
command.append(line.substring(0, line.lastIndexOf(getDelimiter())));
command.append(" ");
Statement statement = conn.createStatement();
println(command);
boolean hasResults = false;
if (stopOnError) {
hasResults = statement.execute(command.toString());
} else {
try {
statement.execute(command.toString());
} catch (SQLException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
}
}
if (autoCommit && !conn.getAutoCommit()) {
conn.commit();
}
ResultSet rs = statement.getResultSet();
if (hasResults && rs != null) {
ResultSetMetaData md = rs.getMetaData();
int cols = md.getColumnCount();
for (int i = 0; i < cols; i++) {
String name = md.getColumnLabel(i);
print(name + "\t");
}
println("");
while (rs.next()) {
for (int i = 1; i <= cols; i++) {
String value = rs.getString(i);
print(value + "\t");
}
println("");
}
}
command = null;
try {
if (rs != null) {
rs.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (statement != null) {
statement.close();
}
} catch (Exception e) {
e.printStackTrace();
// Ignore to workaround a bug in Jakarta DBCP
}
} else {
Pattern pattern = Pattern.compile(DELIMITER_LINE_REGEX);
Matcher matcher = pattern.matcher(trimmedLine);
if (matcher.matches()) {
setDelimiter(trimmedLine.split(DELIMITER_LINE_SPLIT_REGEX)[1].trim(),
fullLineDelimiter);
line = lineReader.readLine();
if (line == null) {
break;
}
trimmedLine = line.trim();
}
command.append(line);
command.append(" ");
}
}
if (!autoCommit) {
conn.commit();
}
} catch (SQLException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
throw e;
} catch (IOException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
throw e;
} finally {
conn.rollback();
flush();
}
}
private String getDelimiter() {
return delimiter;
}
private void print(Object o) {
if (logWriter != null) {
logWriter.print(o);
}
}
private void println(Object o) {
if (logWriter != null) {
logWriter.println(o);
}
}
private void printlnError(Object o) {
if (errorLogWriter != null) {
errorLogWriter.println(o);
}
}
private void flush() {
if (logWriter != null) {
logWriter.flush();
}
if (errorLogWriter != null) {
errorLogWriter.flush();
}
}
}
Why did you tag "scala"?
To execute a whole sql file at once:
sql < myFile.sql
Edit: as Cyrille Corpet pointed out, you can perform this command directly via scala
import sys.process._
"sql < myfile.sql" !

Converting Pdf files to tiff files

I used www.jcgonzalez.com/img/0/75/libraries.zip this libraries and here is my code
public static void pdfconverter(String FILEPATH){
Document document = new Document();
try {
document.setFile(FILEPATH);
} catch (PDFException ex) {
System.out.println("Error parsing PDF document " + ex);
} catch (PDFSecurityException ex) {
System.out.println("Error encryption not supported " + ex);
} catch (FileNotFoundException ex) {
System.out.println("Error file not found " + ex);
} catch (IOException ex) {
System.out.println("Error IOException " + ex);
}
float scale = 1.0f;
float rotation = 0f;
for (int i = 0; i < document.getNumberOfPages(); i++) {
BufferedImage image = (BufferedImage) document.getPageImage(
i, GraphicsRenderingHints.PRINT, Page.BOUNDARY_CROPBOX, rotation, scale);
RenderedImage rendImage = image;
try {
System.out.println(" capturing page " + i);
File file = new File("imageCapture1_" + i + ".tif");
ImageIO.write(rendImage, "tiff", file);
} catch (IOException e) {
e.printStackTrace();
}
image.flush();
}
document.dispose();
}
But the image shows square instead of 'ş'. Any idea why?

How can I convert a PDF into a web-browsable image?

I need to create an online viewer which converts PDF files into browsable images, like http://view.samurajdata.se/. I would like to do this in Grails. Does Grails have any plugins for this?
that's is possible by download PDFRenderer.jar fie and writing code is below
downloadedfile = request.getFile('sourceFile');
println "download file->"+downloadedfile
File destFile=new File('web-app/source-pdf/'+downloadedfile+'.pdf');
if(destFile.exists()){
destFile.delete();
}
File file = null;
try{
file = new File('web-app/source-pdf/'+downloadedfile+'.pdf');
downloadedfile.transferTo(file)
println "file->"+file
}catch(Exception e){
System.err.println("File Already Use")
//out.close();
}
File imageFile=new File("web-app/pdf-images");
if(imageFile.isDirectory())
{
String[] list=imageFile.list()
for(int i=0;i<list.length;i++){
File img=new File("web-app/pdf-images/"+i+".png")
img.delete()
}
}
//response.setContentType("image/png");
// response.setHeader("Cache-control", "no-cache");
RandomAccessFile raf;
BufferedImage[] img;
// response.setContentType("image/png");
// response.setHeader("Cache-control", "no-cache");
file=new File('web-app/source-pdf/'+downloadedfile+'.pdf');
try {
raf = new RandomAccessFile(file, "rws");
FileChannel channel = raf.getChannel();
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_WRITE, 0, channel.size());
PDFFile pdffile = new PDFFile(buf);
// draw the first page to an image
int num=pdffile.getNumPages();
img=new BufferedImage[num]
for(int i=0;i<num;i++)
{
PDFPage page = pdffile.getPage(i);
//get the width and height for the doc at the default zoom
int width=(int)page.getBBox().getWidth();
int height=(int)page.getBBox().getHeight();
Rectangle rect = new Rectangle(0,0,width,height);
int rotation=page.getRotation();
Rectangle rect1=rect;
if(rotation==90 || rotation==270)
rect1=new Rectangle(0,0,(int)rect.height,(int)rect.width);
//generate the image
img[i] = (BufferedImage)page.getImage(
width,height , //width & height
rect1, // clip rect
null, // null for the ImageObserver
true, // fill background with white
true // block until drawing is done
);
ImageIO.write(img[i], "png",new File("web-app/pdf-images/"+i+".png"));
}
// out.close();
}
catch (FileNotFoundException e1) {
System.err.println(e1.getLocalizedMessage());
} catch (IOException e) {
System.err.println(e.getLocalizedMessage());
}
file = null;
render(view:'save',model:[images:img])