TFlite model slow/no inference - tensorflow

I am trying to get an opencv pipeline working on a REV control hub for FTC with tensorflow. I have a trained TFLite model and I am processing it and retrieving the confidences. It works well on an android device as an android app, but it doesn't seem to work with the REV control hub. You may see that I have a variable named here2, this always evaluates to false unless it is before model.process, showing that the model doesn't get processed. Any idea why this is?
package org.firstinspires.ftc.teamcode.vision;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import org.firstinspires.ftc.robotcontroller.internal.FtcRobotControllerActivity;
import org.firstinspires.ftc.robotcore.external.Telemetry;
import org.firstinspires.ftc.teamcode.ml.ModelUnquant;
import org.opencv.core.Mat;
import org.openftc.easyopencv.OpenCvPipeline;
import org.opencv.android.Utils;
import org.tensorflow.lite.DataType;
import org.tensorflow.lite.support.tensorbuffer.TensorBuffer;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class CircularTagDetectionPipeline extends OpenCvPipeline {
Telemetry telemetry;
public boolean done = false;
public int pos = -1;
public boolean here1 = false;
public boolean here2 = false;
public CircularTagDetectionPipeline(Telemetry telemetry){
this.telemetry = telemetry;
}
#Override
public Mat processFrame(Mat input) {
Bitmap bmp = Bitmap.createBitmap(input.width(), input.height(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(input, bmp);
pos = classifyImage(bmp);
done = true;
return input;
}
public int classifyImage(Bitmap image){
try {
image = Bitmap.createScaledBitmap(image, 224, 224, false);
//image.setWidth(224);
//image.setHeight(224);
ModelUnquant model = ModelUnquant.newInstance(FtcRobotControllerActivity.contextFTC);
int imageWidth = image.getWidth();
int imageHeight = image.getHeight();
TensorBuffer inputFeature0 = TensorBuffer.createFixedSize(new int[]{1, 224, 224, 3}, DataType.FLOAT32);
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4*imageWidth*imageHeight*3);
byteBuffer.order(ByteOrder.nativeOrder());
int[] intValues = new int[imageWidth*imageHeight];
image.getPixels(intValues, 0, imageWidth,0, 0, imageWidth, imageHeight);
int pixel = 0;
for(int i = 0; i < imageWidth; i++){
for(int j = 0; j < imageHeight; j++){
int val = intValues[pixel++];
byteBuffer.putFloat(((val >> 16)&0xFF)*(1.f/255.f));
byteBuffer.putFloat(((val >> 8)&0xFF)*(1.f/255.f));
byteBuffer.putFloat((val & 0xFF)*(1.f/255.f));
}
telemetry.addLine(i+"");
}
here1 = true;
inputFeature0.loadBuffer(byteBuffer);
ModelUnquant.Outputs outputs = model.process(inputFeature0);
TensorBuffer outputFeature0 = outputs.getOutputFeature0AsTensorBuffer();
here2 = true;
float[] confidences = outputFeature0.getFloatArray();
int maxPos = 0;
float maxConfidence = 0;
for(int i = 0; i < confidences.length; i++){
if(confidences[i] > maxConfidence){
maxConfidence = confidences[i];
maxPos = i;
}
}
String[] classes = {"1", "2", "3"};
int posReturn = Integer.parseInt(classes[maxPos]);
model.close();
return posReturn;
} catch (IOException e) {
e.printStackTrace();
return 0;
}
}
}
I am expecting the robot to go to execute the desired trajectory based on the confidences, but confidences never get processed. I tried on an android app and it worked, just not on the control hub.

Related

Comparing to array list through there given index but its returning null exception at file initialization

package adc;
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
class Result {
/*
* Complete the 'sockMerchant' function below.
*
* The function is expected to return an INTEGER.
* The function accepts following parameters:
* 1. INTEGER n
* 2. INTEGER_ARRAY ar
*/
public static int sockMerchant(int n, List<Integer> ar) {
// Write your code here
int count=0;
for(int i=0;i<n;i++)
{
for(int j=i+1;j<=n;j++){
if(ar.get(i)==ar.get(j)){
count++;
}
}
}
return(count);
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); ' BufferedWriter(newFileWriter(System.getenv("F:\\")));'
int n = Integer.parseInt(bufferedReader.readLine().trim());
String[] arTemp = bufferedReader.readLine().replaceAll("\\s+$", "").split(" ");
List<Integer> ar = new ArrayList<>();
for (int i = 0; i < n; i++) {
int arItem = Integer.parseInt(arTemp[i]);
ar.add(arItem);
}
int result = Result.sockMerchant(n, ar);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedReader.close();
bufferedWriter.close();
}
}
Working of code
here inputs are n("number of integer arraylist have")=9
and ar input of arraylist [10, 20, 20, 10, 10, 30, 50, 10, 20]
** In this ar arraylist we have to find the even pair of number and return the number of pair .**
In this example the output is 3.

JavaFX: Linking variables correctly for EventHandler (Timeline)

I need to set up a simulation of a nuclear power plant in JavaFX. The GUI is working perfectly, but I've got problems with getting the simulation run. I have to use a Timeline (as EventHandler) for this, the handler updates the radiation value in each cell every single tick. The radiation is displayed as a circle on each cell. The higher the radiation, the bigger should the circle be. For this, I made an if-else-statement.
The problem is: The if-statement cannot access the variables from the EventHandler. But this is necessary to update the circle size each tick. I already tried to put the if-statements right into the EventHandler, but then, no circles have been shown anymore on my GUI.
These are the three classes so far:
EDIT: I put the if-statements into the Event Handler, new code below.
import javafx.application.Application;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
public class NuclearPowerPlant extends Application {
private static final int HEIGHT = 50;
private static final int WIDTH = 55;
private static final int CELL_SIZE = 40;
#Override
public void start(Stage stage) {
stage.setScene(new Scene(createContent()));
stage.show();
}
private Parent createContent() {
Pane root = new Pane();
root.setPrefSize((WIDTH - 40) * CELL_SIZE, (HEIGHT - 40) * CELL_SIZE); // Size of displayed window
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
Cell cell = new Cell(x, y);
root.getChildren().add(cell);
}
}
return root;
}
public static void main(String[] args) {
launch(args);
}
}
Cell:
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.input.ContextMenuEvent;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.util.Duration;
public class Cell extends StackPane {
private static final int CELL_SIZE = 40;
int x;
int y;
private Rectangle cell;
private Circle radiation; // Radiation is displayed as a circle
int circlesize; // Size of the circle (the higher the radiation, the bigger the circle)
double radiationvalue = 5000; // Initializing of the radiation value of all cells at the beginning (air in all cells)
private Text symbol; // For Explosion
double activity;
double reflection;
public Cell(int x, int y) { // Konstruktor fuer die Zelle
setTranslateX(x * CELL_SIZE);
setTranslateY(y * CELL_SIZE);
cell = new Rectangle(CELL_SIZE - 2, CELL_SIZE - 2, Color.BLUE);
cell.setStroke(Color.WHITE);
EventHandler<ActionEvent> handlerUpdateRadiationvalue = event -> {
double newradiationvalue = activity + reflection * 500;
// System.out.println(newradiationvalue);
if (newradiationvalue < 1000) {
this.circlesize = 2;
} else if (newradiationvalue >= 1000 && newradiationvalue < 3000) {
this.circlesize = 5;
} else if (newradiationvalue >= 3000 && newradiationvalue < 5000) {
this.circlesize = 8;
} else if (newradiationvalue >= 5000 && newradiationvalue < 7000) {
this.circlesize = 11;
} else if (newradiationvalue >= 7000 && newradiationvalue < 9000) {
this.circlesize = 14;
} else if (newradiationvalue >= 9000 && newradiationvalue < 10000) {
this.circlesize = 18;
}
// Explosion:
else if (newradiationvalue >= 10000) {
circlesize = 0;
cell.setFill(Color.RED);
symbol = new Text("X");
symbol.setFont(Font.font(38));
}
};
KeyFrame keyframe = new KeyFrame(Duration.seconds(0.02), handlerUpdateRadiationvalue);
Timeline tl = new Timeline();
tl.getKeyFrames().addAll(keyframe);
tl.setCycleCount(Timeline.INDEFINITE);
tl.play();
radiation = new Circle(circlesize, Color.BLACK);
getChildren().add(cell);
if (radiationvalue < 10000) {
getChildren().add(radiation);
} else {
getChildren().add(symbol);
}
// Context Menu for material change:
ContextMenu contextMenu = new ContextMenu();
MenuItem air = new MenuItem("Luft");
air.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
activity = Material.AIR.getActivity();
reflection = Material.AIR.getReflection();
cell.setFill(Color.BLUE);
}
});
MenuItem uranium = new MenuItem("Uran");
uranium.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
activity = Material.URANIUM.getActivity();
reflection = Material.URANIUM.getReflection();
cell.setFill(Color.GREEN);
}
});
MenuItem lead = new MenuItem("Blei");
lead.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
activity = Material.LEAD.getActivity();
reflection = Material.LEAD.getReflection();
cell.setFill(Color.GREY);
}
});
MenuItem ruleblock = new MenuItem("Regelblock");
ruleblock.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
activity = Material.RULEBLOCK.getActivity();
reflection = Material.RULEBLOCK.getReflection();
cell.setFill(Color.YELLOW);
}
});
contextMenu.getItems().addAll(air, uranium, lead, ruleblock);
cell.setOnContextMenuRequested(new EventHandler<ContextMenuEvent>() {
#Override
public void handle(ContextMenuEvent event) {
contextMenu.show(cell, event.getScreenX(), event.getScreenY());
}
});
}
ENUM:
public enum Material {
AIR (0, 0.99),
URANIUM (1, 1.12),
LEAD (0, 0.7),
RULEBLOCK (0, 0.99);
double activity;
double reflection;
private Material(double activity, double reflection) {
this.activity = activity;
this.reflection = reflection;
}
double getActivity() {
return activity;
}
public void setActivity(double activity) {
this.activity = activity;
}
double getReflection() {
return reflection;
}
public void setReflection(double reflection) {
this.reflection = reflection;
}
}
The if statement always links to the global variable "radiationvalue" instead of the updated value in the event handler. If I try to access the 'newradiationvalue' in the if statement, I get an error that no such variable can be found (because the one in the Event Handler is not visible from outside).
Maybe someone can tell me how to access the variables in the event handler from outside the event handler?! And if it's not possible: How do I need to change my program to make this work as I want?
Thanks very much in advance!

Adjust Brightness, Contrast using Camera.Parameters

I were trying to make a camera application, I'm unable to find a way to change camera brightness, contrast using Camera.Parameters
So my question is how to add Brightness and contrast feature to increase/decrease brightness/contrast. For example if I increase the seekbarit increase the brightness. if I decrease the seekbar it decrease the brightness.
Please edit my code or put your seprate answer to help me.
package com.example.beautymaker;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.hardware.Camera;
import android.hardware.camera2.CameraCharacteristics;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import com.zomato.photofilters.imageprocessors.Filter;
import com.zomato.photofilters.imageprocessors.subfilters.BrightnessSubFilter;
import java.io.IOException;
import java.util.List;
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder mHolder;
private Camera mCamera;
public CameraPreview(Context context, Camera camera) {
super(context);
mCamera = camera;
mHolder = getHolder();
mHolder.addCallback(this);
/*Camera.Parameters params = camera.getParameters();
final int[] previewFpsRange = new int[2];
params.getPreviewFpsRange(previewFpsRange);
if (previewFpsRange[0] == previewFpsRange[1]) {
final List<int[]> supportedFpsRanges = params.getSupportedPreviewFpsRange();
for (int[] range : supportedFpsRanges) {
if (range[0] != range[1]) {
params.setPreviewFpsRange(range[0], range[1]);
break;
}
}
}*/
// deprecated setting, but required on Android versions prior to 3.0
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
try {
// create the surface and start camera preview
if (mCamera == null) {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
}
} catch (IOException e) {
Log.d(VIEW_LOG_TAG, "Error setting camera preview: " + e.getMessage());
}
}
public void refreshCamera(Camera camera) {
if (mHolder.getSurface() == null) {
// preview surface does not exist
return;
}
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e) {
// ignore: tried to stop a non-existent preview
}
// set preview size and make any resize, rotate or
// reformatting changes here
// start preview with new settings
setCamera;
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e) {
Log.d(VIEW_LOG_TAG, "Error starting camera preview: " + e.getMessage());
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it.
refreshCamera(mCamera);
}
public void setCamera(Camera camera) {
//method to set a camera instance
mCamera = camera;
Camera.Parameters parameters = mCamera.getParameters();
// parameters.setPreviewFpsRange(1500,3000);
parameters.setExposureCompensation(parameters.getMaxExposureCompensation());
if(parameters.isAutoExposureLockSupported())
{
parameters.setAutoExposureLock(false);
}
// parameters.setColorEffect(Camera.Parameters.WHITE_BALANCE_INCANDESCENT);
parameters.getAutoExposureLock();
parameters.set("iso",50);
// parameters.setWhiteBalance();
parameters.setAutoWhiteBalanceLock(true);
parameters.setWhiteBalance(Camera.Parameters.WHITE_BALANCE_SHADE);
/*Filter filter = new Filter();
filter.addSubFilter(new BrightnessSubFilter(parameters));*/
mCamera.setParameters(parameters);
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
// mCamera.release();
}
//for brightness
public static Bitmap doBrightness(Bitmap src, int value) {
// image size
int width = src.getWidth();
int height = src.getHeight();
// create output bitmap
Bitmap bmOut = Bitmap.createBitmap(width, height, src.getConfig());
// color information
int A, R, G, B;
int pixel;
// scan through all pixels
for(int x = 0; x < width; ++x) {
for(int y = 0; y < height; ++y) {
// get pixel color
pixel = src.getPixel(x, y);
A = Color.alpha(pixel);
R = Color.red(pixel);
G = Color.green(pixel);
B = Color.blue(pixel);
// increase/decrease each channel
R += value;
if(R > 255) { R = 255; }
else if(R < 0) { R = 0; }
G += value;
if(G > 255) { G = 255; }
else if(G < 0) { G = 0; }
B += value;
if(B > 255) { B = 255; }
else if(B < 0) { B = 0; }
// apply new pixel color to output bitmap
bmOut.setPixel(x, y, Color.argb(A, R, G, B));
}
}
// return final image
return bmOut;
}
}
there is no method in Camera.Parameters to achieve this. You have to read this documentation for this class to check the available parameters and this class is deprecated in API 21 and above.

Highlight words inside existing PDF

I need to highlight a set of words inside an existing PDF given specific coordinates that i have already extracted.
I am working with pdfbox by Apache (last version 2.0.8).
There is an example file I can use to such a purpose (AddAnnotations.java inside the pdfbox website) but I think this example was compiled with an older Java version as the following import does not work:
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationHighlight;
Can anyone help me with that? Which is the simplest way to highlight words by using this library?
Here is the code to highlight ALL the words inside a PDF document. Highlighting only a specific set of words can be easily performed modifying this script. Please note this is only a test and further checks are needed for words that terminates in a new line as well as words placed in negative landscape/portrait PDF pages. Optimizing this script is also possible.
This script was built using Apache PDFBox 2.0.8.
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.TextPosition;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.graphics.color.PDColor;
import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceRGB;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationTextMarkup;
public class TestAnnotatePDF extends PDFTextStripper
{
static List<double[]> coordinates;
static ArrayList tokenStream;
public TestAnnotatePDF() throws IOException
{
//data structed containing coordinates information for each token
coordinates = new ArrayList<>();
//List of words extracted from text (considering a whitespace-based tokenization)
tokenStream = new ArrayList();
}
public static void main(String [] args) throws IOException
{
try
{
//Loading an existing document
File file = new File("MyDocument");
PDDocument document = PDDocument.load(file);
//extended PDFTextStripper class
PDFTextStripper stripper = new TestAnnotatePDF();
//Get number of pages
int number_of_pages = document.getDocumentCatalog().getPages().getCount();
//The method writeText will invoke an override version of writeString
Writer dummy = new OutputStreamWriter(new ByteArrayOutputStream());
stripper.writeText(document, dummy);
//Print collected information
System.out.println(tokenStream);
System.out.println(tokenStream.size());
System.out.println(coordinates.size());
double page_height;
double page_width;
double width, height, minx, maxx, miny, maxy;
int rotation;
//scan each page and highlitht all the words inside them
for (int page_index = 0; page_index < number_of_pages; page_index++)
{
//get current page
PDPage page = document.getPage(page_index);
//Get annotations for the selected page
List<PDAnnotation> annotations = page.getAnnotations();
//Define a color to use for highlighting text
PDColor red = new PDColor(new float[] { 1, 0, 0 }, PDDeviceRGB.INSTANCE);
//Page height and width
page_height = page.getMediaBox().getHeight();
page_width = page.getMediaBox().getWidth();
//Scan collected coordinates
for (int i=0; i<coordinates.size(); i++)
{
//if the current coordinates are not related to the current
//page, ignore them
if ((int) coordinates.get(i)[4] != (page_index+1))
continue;
else
{
//get rotation of the page...portrait..landscape..
rotation = (int) coordinates.get(i)[7];
//page rotated of 90degrees
if (rotation == 90)
{
height = coordinates.get(i)[5];
width = coordinates.get(i)[6];
width = (page_height * width)/page_width;
//define coordinates of a rectangle
maxx = coordinates.get(i)[1];
minx = coordinates.get(i)[1] - height;
miny = coordinates.get(i)[0];
maxy = coordinates.get(i)[0] + width;
}
else //i should add here the cases -90/-180 degrees
{
height = coordinates.get(i)[5];
minx = coordinates.get(i)[0];
maxx = coordinates.get(i)[2];
miny = page_height - coordinates.get(i)[1];
maxy = page_height - coordinates.get(i)[3] + height;
}
//Add an annotation for each scanned word
PDAnnotationTextMarkup txtMark = new PDAnnotationTextMarkup(PDAnnotationTextMarkup.SUB_TYPE_HIGHLIGHT);
txtMark.setColor(red);
txtMark.setConstantOpacity((float)0.3); // 30% transparent
PDRectangle position = new PDRectangle();
position.setLowerLeftX((float) minx);
position.setLowerLeftY((float) miny);
position.setUpperRightX((float) maxx);
position.setUpperRightY((float) ((float) maxy+height));
txtMark.setRectangle(position);
float[] quads = new float[8];
quads[0] = position.getLowerLeftX(); // x1
quads[1] = position.getUpperRightY()-2; // y1
quads[2] = position.getUpperRightX(); // x2
quads[3] = quads[1]; // y2
quads[4] = quads[0]; // x3
quads[5] = position.getLowerLeftY()-2; // y3
quads[6] = quads[2]; // x4
quads[7] = quads[5]; // y5
txtMark.setQuadPoints(quads);
txtMark.setContents(tokenStream.get(i).toString());
annotations.add(txtMark);
}
}
}
//Saving the document in a new file
File highlighted_doc = new File("MyDocument_final.pdf");
document.save(highlighted_doc);
document.close();
}
catch(IOException e)
{
System.out.println(e);
}
}
#Override
protected void writeString(String string, List<TextPosition> textPositions) throws IOException
{
String token = "";
int token_length = textPositions.size();
int counter = 1;
double minx = 0,maxx = 0,miny = 0,maxy =0;
double height = 0;
double width = 0;
int rotation = 0;
for (TextPosition text : textPositions)
{
rotation = text.getRotation();
if (text.getHeight() > height)
height = text.getHeight();
if (text.getWidth() > width)
width = text.getWidth();
//if it is the first char of the current word
if (counter == 1)
{
minx = text.getX();
miny = text.getY();
}
//if it is the last char of the current word
if (counter == token_length)
{
maxx = text.getEndX();
maxy = text.getY();
}
token += text;
counter += 1;
}
tokenStream.add(token);
double word_coordinates [] = {minx,miny,maxx,maxy,this.getCurrentPageNo(), height, width, rotation};
coordinates.add(word_coordinates);
}}
Here is the code to highlight specific words inside a PDF document. Please note this is working for highlighting the line of the search text. Highlight specific words in a PDF is still in progress... Any suggestion to highlight specific words on top of this code will be highly appreciated.
This script was built using Apache PDFBox 2.0.8
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.List;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.graphics.color.PDColor;
import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceRGB;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationTextMarkup;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.TextPosition;
public class PDFhighlightDemo extends PDFTextStripper {
public PDFhighlightDemo() throws IOException {
super();
}
public static void main(String[] args) throws IOException {
PDDocument document = null;
String fileName = "Demo1.pdf";
try {
document = PDDocument.load( new File(fileName) );
PDFTextStripper stripper = new PDFhighlightDemo();
stripper.setSortByPosition( true );
stripper.setStartPage( 0 );
stripper.setEndPage( document.getNumberOfPages() );
Writer dummy = new OutputStreamWriter(new ByteArrayOutputStream());
stripper.writeText(document, dummy);
File file1 = new File("FinalPDF.pdf");
document.save(file1);
}
finally {
if( document != null ) {
document.close();
}
}
}
/**
* Override the default functionality of PDFTextStripper.writeString()
*/
#Override
protected void writeString(String string, List<TextPosition> textPositions) throws IOException {
boolean isFound = false;
float posXInit1 = 0,
posXEnd1 = 0,
posYInit1 = 0,
posYEnd1 = 0,
width1 = 0,
height1 = 0,
fontHeight1 = 0;
String[] criteria = {"angular", "prepared"};
for (int i = 0; i < criteria.length; i++) {
if (string.contains(criteria[i])) {
isFound = true;
}
}
if (isFound) {
for(TextPosition textPosition:textPositions) {
posXInit1 = textPositions.get(0).getXDirAdj();
posXEnd1 = textPositions.get(textPositions.size() - 1).getXDirAdj() + textPositions.get(textPositions.size() - 1).getWidth();
posYInit1 = textPositions.get(0).getPageHeight() - textPositions.get(0).getYDirAdj();
posYEnd1 = textPositions.get(0).getPageHeight() - textPositions.get(textPositions.size() - 1).getYDirAdj();
width1 = textPositions.get(0).getWidthDirAdj();
height1 = textPositions.get(0).getHeightDir();
}
float quadPoints[] = {posXInit1, posYEnd1 + height1 + 2, posXEnd1, posYEnd1 + height1 + 2, posXInit1, posYInit1 - 2, posXEnd1, posYEnd1 - 2};
List<PDAnnotation> annotations = document.getPage(this.getCurrentPageNo() - 1).getAnnotations();
PDAnnotationTextMarkup highlight = new PDAnnotationTextMarkup(PDAnnotationTextMarkup.SUB_TYPE_HIGHLIGHT);
PDRectangle position = new PDRectangle();
position.setLowerLeftX(posXInit1);
position.setLowerLeftY(posYEnd1);
position.setUpperRightX(posXEnd1);
position.setUpperRightY(posYEnd1 + height1);
highlight.setRectangle(position);
// quadPoints is array of x,y coordinates in Z-like order (top-left, top-right, bottom-left,bottom-right)
// of the area to be highlighted
highlight.setQuadPoints(quadPoints);
PDColor yellow = new PDColor(new float[]{1, 1, 1 / 255F}, PDDeviceRGB.INSTANCE);
highlight.setColor(yellow);
annotations.add(highlight);
}
}
}
Highlight specific words in a document using PDFclown.
package com.NLP.demo;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.pdfclown.documents.Page;
import org.pdfclown.documents.contents.ITextString;
import org.pdfclown.documents.contents.TextChar;
import org.pdfclown.documents.interaction.annotations.TextMarkup;
import org.pdfclown.documents.interaction.annotations.TextMarkup.MarkupTypeEnum;
import org.pdfclown.files.SerializationModeEnum;
import org.pdfclown.tools.TextExtractor;
import org.pdfclown.util.math.Interval;
import org.pdfclown.util.math.geom.Quad;
public class PDFCrownDemo {
public static void main() throws IOException {
PDFCrownDemo PDFCrownDemo=new PDFCrownDemo();
PDFCrownDemo.highlighttext();
}
public void highlighttext() throws IOException{
org.pdfclown.files.File file = new org.pdfclown.files.File("src/main/resources/XXX.pdf");
String textRegEx = "Contract";
Pattern pattern = Pattern.compile(textRegEx, Pattern.CASE_INSENSITIVE);
TextExtractor textExtractor = new TextExtractor(true, true);
for(final Page page : file.getDocument().getPages())
{
Map<Rectangle2D,List<ITextString>> textStrings = textExtractor.extract(page);
final Matcher matcher = pattern.matcher(TextExtractor.toString(textStrings));
textExtractor.filter(textStrings,new TextExtractor.IIntervalFilter()
{
#Override
public boolean hasNext()
{return matcher.find();}
#Override
public Interval next()
{return new Interval(matcher.start(), matcher.end());}
#Override
public void process(Interval interval,ITextString match)
{
// Defining the highlight box of the text pattern match...
List highlightQuads = new ArrayList();
{
/*
NOTE: A text pattern match may be split across multiple contiguous lines,
so we have to define a distinct highlight box for each text chunk.
*/
Rectangle2D textBox = null;
for(TextChar textChar : match.getTextChars())
{
Rectangle2D textCharBox = textChar.getBox();
if(textBox == null)
{textBox = (Rectangle2D)textCharBox.clone();}
else
{
if(textCharBox.getY() > textBox.getMaxY())
{
highlightQuads.add(Quad.get(textBox));
textBox = (Rectangle2D)textCharBox.clone();
}
else
{textBox.add(textCharBox);}
}
}
highlightQuads.add(Quad.get(textBox));
}
// Highlight the text pattern match!
new TextMarkup(page,MarkupTypeEnum.Highlight, highlightQuads);
}
#Override
public void remove(
)
{throw new UnsupportedOperationException();}
}
);
}
//file.save(SerializationModeEnum.Incremental);
file.save(new java.io.File("src/main/resources/XXX.pdf"), SerializationModeEnum.Standard);
}
}

Get List of artifacts in an Ivy Repositoty

I manage an Ivy repository with an extensive number of artifacts and i have been requested to list all third party librarys which we have a hundred odd. does anyone know of a a way to retrieve a list of artifacts from an ivy repo?
i found no such way to do this, i wrote a script in java to get the results, thought i might share the answer if people wanted it in the future, it is also formatted to be copied straight into an excel document.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
public class ListArtifacts {
public static void main(String[] args) {
Collection<File> all = new ArrayList<File>();
addTree(new File("."), all);
String delimeter = "\\.";
List<String> remove = new ArrayList<String>();
List<String> everything = new ArrayList<String>();
remove.add("pom");
remove.add("jar");
remove.add("xml");
remove.add("txt");
remove.add("sha1");
remove.add("md5");
remove.add("metadata");
remove.add("tar");
remove.add("gz");
remove.add("zip");
remove.add("rar");
FileWriter fWriter = null;
BufferedWriter writer = null;
try {
fWriter = new FileWriter("info.txt");
writer = new BufferedWriter(fWriter);
Iterator itr = all.iterator();
while (itr.hasNext() == true){
String[] split;
String temp = itr.next().toString();
split = temp.split(delimeter);
int i = 0;
int j = 0;
boolean flag = false;
while (i < split.length){
while (j < remove.size()){
if (split[i].equals(remove.get(j))){
flag = true;
}
j++;
}
j = 0;
i++;
}
if (flag == false){
String output = "";
int k=0;
boolean flag2 = false;
boolean hasVersion = false;
while (k < split.length){
if (flag2 == true){
output += ".";
flag2 = false;
}
output = output + split[k].toString();
boolean lastInt = false;
try{
String last = split[k].substring(split[k].length() - 1);
if (isInteger(last) == true)
lastInt = true;
}catch(Exception e){}
if ((isInteger(split[k].toString()) == true) || (lastInt == true)){
flag2 = true;
hasVersion = true;
}
k++;
}
if (hasVersion == true){
everything.add(output.substring(1));
writer.append(output.substring(1));
writer.newLine();
}
}
}
int i = 0;
String delim = "\\\\";
String finalOutput = "";
String toSplit = "";
while (i < everything.size()){
toSplit = everything.get(i);
String[] split2 = toSplit.split(delim);
finalOutput = split2[0] + "\t";
int j = 1;
while (j < split2.length-2){
finalOutput += split2[j] + ".";
j++;
}
finalOutput += split2[split2.length-2] + "\t";
finalOutput += split2[split2.length-1];
writer.append(finalOutput);
writer.newLine();
i++;
}
writer.close();
} catch (Exception e) {
}
System.out.println(all);
}
public static boolean isInteger(String input )
{
try
{
Integer.parseInt(input);
return true;
}
catch(Exception e)
{
return false;
}
}
static void addTree(File file, Collection<File> all) {
File[] children = file.listFiles();
if (children != null) {
for (File child : children) {
all.add(child);
addTree(child, all);
}
}
}
}
im sure this can be done much more cleanly, but i did no higher thinking just did the first thing i thought of with no revision.
If you are looking to do this using ivy during a build, the report task should help you get a report of all the JARs you are using.
If you are trying to fetch these details from the repository manager (covering all possible users), could you answer the question from #oers? Repository managers often offer some API that you can use to get reports about the artifacts that they store.