问:
Yolo detector in Java

I'm trying to implement Yolo detector in Java (not Android, but desktops - Windows/Ubuntu)

There is already Yolo detector for Android: https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/android

I copied some java classes from that project, added them to IntelliJ IDEA and edited them

I even copied and edited TensorFlowInferenceInterface.java which is from jar file (tensorflow library - libandroid_tensorflow_inference_java.jar) for Android

I'm almost succeeded to get it working.

Result

Console output (class title, confidence, x, y, width, height):

car 0.8836523, 148 166 270 267

car 0.51286024, 147 174 268 274

car 0.05002968, 174 164 275 262

So seems it correctly detected car, determined correct x, y
but something wrong with width and height

What could be wrong?

Here's the full code from my project

Main

public class Main implements Classifier {

    private static final int BLOCK_SIZE = 32;
    private static final int MAX_RESULTS = 3;
    private static final int NUM_CLASSES = 20;
    private static final int NUM_BOXES_PER_BLOCK = 5;
    private static final int INPUT_SIZE = 416;
    private static final String inputName = "input";
    private static final String outputName = "output";

    // Pre-allocated buffers.
    private static int[] intValues;
    private static float[] floatValues;
    private static String[] outputNames;

    // yolo 2
    private static final double[] ANCHORS = { 1.3221, 1.73145, 3.19275, 4.00944, 5.05587, 8.09892, 9.47112, 4.84053, 11.2364, 10.0071 };

    // tiny yolo
    //private static final double[] ANCHORS = { 1.08, 1.19, 3.42, 4.41, 6.63, 11.38, 9.42, 5.11, 16.62, 10.52 };

    private static final String[] LABELS = {
            "aeroplane",
            "bicycle",
            "bird",
            "boat",
            "bottle",
            "bus",
            "car",
            "cat",
            "chair",
            "cow",
            "diningtable",
            "dog",
            "horse",
            "motorbike",
            "person",
            "pottedplant",
            "sheep",
            "sofa",
            "train",
            "tvmonitor"
    };

    private static TensorFlowInferenceInterface inferenceInterface;

    public static void main(String[] args) {

        //String modelDir = "/home/user/JavaProjects/TensorFlowJavaProject"; // Ubuntu
        String modelAndTestImagesDir = "D:\\JavaProjects\\TensorFlowJavaProject"; // Windows
        String imageFile = modelAndTestImagesDir + File.separator + "0.png"; // 416x416 test image

        outputNames = outputName.split(",");
        floatValues = new float[INPUT_SIZE * INPUT_SIZE * 3];

        // yolo 2 voc
        inferenceInterface = new TensorFlowInferenceInterface(Paths.get(modelAndTestImagesDir, "yolo-voc.pb"));

        // tiny yolo voc
        //inferenceInterface = new TensorFlowInferenceInterface(Paths.get(modelAndTestImagesDir, "graph-tiny-yolo-voc.pb"));

        BufferedImage img;

        try {
            img = ImageIO.read(new File(imageFile));

            BufferedImage convertedImg = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_RGB);
            convertedImg.getGraphics().drawImage(img, 0, 0, null);

            intValues = ((DataBufferInt) convertedImg.getRaster().getDataBuffer()).getData() ;

            List<Classifier.Recognition> recognitions = recognizeImage();

            System.out.println("Result length " + recognitions.size());

            Graphics2D graphics = convertedImg.createGraphics();

            for (Recognition recognition : recognitions) {
                RectF rectF = recognition.getLocation();
                System.out.println(recognition.getTitle() + " " + recognition.getConfidence() + ", " +
                        (int) rectF.x + " " + (int) rectF.y + " " + (int) rectF.width + " " + ((int) rectF.height));
                Stroke stroke = graphics.getStroke();
                graphics.setStroke(new BasicStroke(3));
                graphics.setColor(Color.green);
                graphics.drawRoundRect((int) rectF.x, (int) rectF.y, (int) rectF.width, (int) rectF.height, 5, 5);
                graphics.setStroke(stroke);
            }

            graphics.dispose();
            ImageIcon icon=new ImageIcon(convertedImg);
            JFrame frame=new JFrame();
            frame.setLayout(new FlowLayout());
            frame.setSize(convertedImg.getWidth(),convertedImg.getHeight());
            JLabel lbl=new JLabel();
            frame.setTitle("Java (Win/Ubuntu), Tensorflow & Yolo");
            lbl.setIcon(icon);
            frame.add(lbl);
            frame.setVisible(true);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private static List<Classifier.Recognition> recognizeImage() {

        for (int i = 0; i < intValues.length; ++i) {
            floatValues[i * 3 + 0] = ((intValues[i] >> 16) & 0xFF) / 255.0f;
            floatValues[i * 3 + 1] = ((intValues[i] >> 8) & 0xFF) / 255.0f;
            floatValues[i * 3 + 2] = (intValues[i] & 0xFF) / 255.0f;
        }
        inferenceInterface.feed(inputName, floatValues, 1, INPUT_SIZE, INPUT_SIZE, 3);

        inferenceInterface.run(outputNames, false);

        final int gridWidth = INPUT_SIZE / BLOCK_SIZE;
        final int gridHeight = INPUT_SIZE / BLOCK_SIZE;

        final float[] output = new float[gridWidth * gridHeight * (NUM_CLASSES + 5) * NUM_BOXES_PER_BLOCK];

        inferenceInterface.fetch(outputNames[0], output);

        // Find the best detections.
        final PriorityQueue<Classifier.Recognition> pq =
                new PriorityQueue<>(
                        1,
                        new Comparator<Classifier.Recognition>() {
                            @Override
                            public int compare(final Classifier.Recognition lhs, final Classifier.Recognition rhs) {
                                // Intentionally reversed to put high confidence at the head of the queue.
                                return Float.compare(rhs.getConfidence(), lhs.getConfidence());
                            }
                        });

        for (int y = 0; y < gridHeight; ++y) {
            for (int x = 0; x < gridWidth; ++x) {
                for (int b = 0; b < NUM_BOXES_PER_BLOCK; ++b) {
                    final int offset =
                            (gridWidth * (NUM_BOXES_PER_BLOCK * (NUM_CLASSES + 5))) * y
                                    + (NUM_BOXES_PER_BLOCK * (NUM_CLASSES + 5)) * x
                                    + (NUM_CLASSES + 5) * b;

                    final float xPos = (x + expit(output[offset + 0])) * BLOCK_SIZE;
                    final float yPos = (y + expit(output[offset + 1])) * BLOCK_SIZE;

                    final float w = (float) (Math.exp(output[offset + 2]) * ANCHORS[2 * b + 0]) * BLOCK_SIZE;
                    final float h = (float) (Math.exp(output[offset + 3]) * ANCHORS[2 * b + 1]) * BLOCK_SIZE;

                    final RectF rect =
                            new RectF(
                                    Math.max(0, xPos - w / 2),
                                    Math.max(0, yPos - h / 2),
                                    Math.min(INPUT_SIZE - 1, xPos + w / 2),
                                    Math.min(INPUT_SIZE - 1, yPos + h / 2));

                    final float confidence = expit(output[offset + 4]);

                    int detectedClass = -1;
                    float maxClass = 0;

                    final float[] classes = new float[NUM_CLASSES];
                    for (int c = 0; c < NUM_CLASSES; ++c) {
                        classes[c] = output[offset + 5 + c];
                    }
                    softmax(classes);

                    for (int c = 0; c < NUM_CLASSES; ++c) {
                        if (classes[c] > maxClass) {
                            detectedClass = c;
                            maxClass = classes[c];
                        }
                    }

                    final float confidenceInClass = maxClass * confidence;
                    if (confidenceInClass > 0.01) {
                        pq.add(new Classifier.Recognition(detectedClass, LABELS[detectedClass], confidenceInClass, rect));
                    }
                }
            }
        }

        final ArrayList<Classifier.Recognition> recognitions = new ArrayList<>();
        for (int i = 0; i < Math.min(pq.size(), MAX_RESULTS); ++i) {
            recognitions.add(pq.poll());
        }
        return recognitions;

    }

    private static float expit(final float x) {
        return (float) (1. / (1. + Math.exp(-x)));
    }

    private static void softmax(final float[] vals) {
        float max = Float.NEGATIVE_INFINITY;
        for (final float val : vals) {
            max = Math.max(max, val);
        }
        float sum = 0.0f;
        for (int i = 0; i < vals.length; ++i) {
            vals[i] = (float) Math.exp(vals[i] - max);
            sum += vals[i];
        }
        for (int i = 0; i < vals.length; ++i) {
            vals[i] = vals[i] / sum;
        }
    }

    public void close() {
        inferenceInterface.close();
    }
}
```

<p><strong>TensorFlowInferenceInterface</strong></p>

<pre class="lang-py prettyprint-override"><code>public class TensorFlowInferenceInterface {
    private static final String TAG = "TensorFlowInferenceInterface";
    private final Graph g;
    private final Session sess;
    private Runner runner;
    private List<String> feedNames = new ArrayList();
    private List<Tensor> feedTensors = new ArrayList();
    private List<String> fetchNames = new ArrayList();
    private List<Tensor> fetchTensors = new ArrayList();
    private RunStats runStats;

    public TensorFlowInferenceInterface(Path path) {
        this.prepareNativeRuntime();
        this.g = new Graph();
        this.sess = new Session(this.g);
        this.runner = this.sess.runner();

        try {
            this.loadGraph(readAllBytesOrExit(path), this.g);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static byte[] readAllBytesOrExit(Path path) {
        try {
            return Files.readAllBytes(path);
        } catch (IOException e) {
            System.err.println("Failed to read [" + path + "]: " + e.getMessage());
            System.exit(1);
        }
        return null;
    }

    public void run(String[] var1) {
        this.run(var1, false);
    }

    public void run(String[] var1, boolean var2) {
        this.closeFetches();
        String[] var3 = var1;
        int var4 = var1.length;

        for (int var5 = 0; var5 < var4; ++var5) {
            String var6 = var3[var5];
            this.fetchNames.add(var6);
            TensorFlowInferenceInterface.TensorId var7 = TensorFlowInferenceInterface.TensorId.parse(var6);
            this.runner.fetch(var7.name, var7.outputIndex);
        }

        try {
            if (var2) {
                Run var13 = this.runner.setOptions(RunStats.runOptions()).runAndFetchMetadata();
                this.fetchTensors = var13.outputs;
                if (this.runStats == null) {
                    this.runStats = new RunStats();
                }

                this.runStats.add(var13.metadata);
            } else {
                this.fetchTensors = this.runner.run();
            }
        } catch (RuntimeException var11) {
            throw var11;
        } finally {
            this.closeFeeds();
            this.runner = this.sess.runner();
        }

    }

    public Graph graph() {
        return this.g;
    }

    public Operation graphOperation(String var1) {
        Operation var2 = this.g.operation(var1);
        if (var2 == null) {
            throw new RuntimeException("Node '" + var1 + "' does not exist in model '");
        } else {
            return var2;
        }
    }

    public String getStatString() {
        return this.runStats == null ? "" : this.runStats.summary();
    }

    public void close() {
        this.closeFeeds();
        this.closeFetches();
        this.sess.close();
        this.g.close();
        if (this.runStats != null) {
            this.runStats.close();
        }

        this.runStats = null;
    }

    protected void finalize() throws Throwable {
        try {
            this.close();
        } finally {
            super.finalize();
        }

    }

    public void feed(String var1, float[] var2, long... var3) {
        this.addFeed(var1, Tensor.create(var3, FloatBuffer.wrap(var2)));
    }

    public void fetch(String var1, float[] var2) {
        this.fetch(var1, FloatBuffer.wrap(var2));
    }

    public void fetch(String var1, FloatBuffer var2) {
        this.getTensor(var1).writeTo(var2);
    }

    private void prepareNativeRuntime() {
        System.out.println("TensorFlowInferenceInterface Checking to see if TensorFlow native methods are already loaded");

        try {
            new RunStats();
            System.out.println("TensorFlowInferenceInterface TensorFlow native methods already loaded");
        } catch (UnsatisfiedLinkError var4) {
            System.out.println("TensorFlowInferenceInterface TensorFlow native methods not found, attempting to load via tensorflow_inference");
        }

    }

    private void loadGraph(byte[] var1, Graph var2) throws IOException {
        try {
            var2.importGraphDef(var1);
        } catch (IllegalArgumentException var7) {
            throw new IOException("Not a valid TensorFlow Graph serialization: " + var7.getMessage());
        }
    }

    private void addFeed(String var1, Tensor var2) {
        TensorFlowInferenceInterface.TensorId var3 = TensorFlowInferenceInterface.TensorId.parse(var1);
        this.runner.feed(var3.name, var3.outputIndex, var2);
        this.feedNames.add(var1);
        this.feedTensors.add(var2);
    }

    private Tensor getTensor(String var1) {
        int var2 = 0;

        for (Iterator var3 = this.fetchNames.iterator(); var3.hasNext(); ++var2) {
            String var4 = (String) var3.next();
            if (var4.equals(var1)) {
                return this.fetchTensors.get(var2);
            }
        }

        throw new RuntimeException("Node '" + var1 + "' was not provided to run(), so it cannot be read");
    }

    private void closeFeeds() {
        Iterator var1 = this.feedTensors.iterator();

        while (var1.hasNext()) {
            Tensor var2 = (Tensor) var1.next();
            var2.close();
        }

        this.feedTensors.clear();
        this.feedNames.clear();
    }

    private void closeFetches() {
        Iterator var1 = this.fetchTensors.iterator();

        while (var1.hasNext()) {
            Tensor var2 = (Tensor) var1.next();
            var2.close();
        }

        this.fetchTensors.clear();
        this.fetchNames.clear();
    }

    private static class TensorId {
        String name;
        int outputIndex;

        private TensorId() {
        }

        public static TensorFlowInferenceInterface.TensorId parse(String var0) {
            TensorFlowInferenceInterface.TensorId var1 = new TensorFlowInferenceInterface.TensorId();
            int var2 = var0.lastIndexOf(58);
            if (var2 < 0) {
                var1.outputIndex = 0;
                var1.name = var0;
                return var1;
            } else {
                try {
                    var1.outputIndex = Integer.parseInt(var0.substring(var2 + 1));
                    var1.name = var0.substring(0, var2);
                } catch (NumberFormatException var4) {
                    var1.outputIndex = 0;
                    var1.name = var0;
                }

                return var1;
            }
        }
    }
}
</code>```

Classifier

public interface Classifier {

  public class Recognition {

    private final int id;

    private final String title;

    private final Float confidence;

    private RectF location;

    public Recognition(
            final int id, final String title, final Float confidence, final RectF location) {
      this.id = id;
      this.title = title;
      this.confidence = confidence;
      this.location = location;
    }

    public int getId() {
      return id;
    }

    public String getTitle() {
      return title;
    }

    public Float getConfidence() {
      return confidence;
    }

    public RectF getLocation() {
      return new RectF(location);
    }

    public void setLocation(RectF location) {
      this.location = location;
    }
  }

  void close();
}
```

<p><strong>RunStats</strong></p>

<pre class="lang-py prettyprint-override"><code>public class RunStats implements AutoCloseable {
    private long nativeHandle = allocate();
    private static byte[] fullTraceRunOptions = new byte[]{8, 3};

    public static byte[] runOptions() {
        return fullTraceRunOptions;
    }

    public RunStats() {
    }

    public void close() {
        if(this.nativeHandle != 0L) {
            delete(this.nativeHandle);
        }

        this.nativeHandle = 0L;
    }

    public synchronized void add(byte[] var1) {
        add(this.nativeHandle, var1);
    }

    public synchronized String summary() {
        return summary(this.nativeHandle);
    }

    private static native long allocate();

    private static native void delete(long var0);

    private static native void add(long var0, byte[] var2);

    private static native String summary(long var0);
}
</code>```

RectF

public class RectF {

    public float getX() {
        return x;
    }

    public void setX(float x) {
        this.x = x;
    }

    public float getY() {
        return y;
    }

    public void setY(float y) {
        this.y = y;
    }

    public float getWidth() {
        return width;
    }

    public void setWidth(float width) {
        this.width = width;
    }

    public float getHeight() {
        return height;
    }

    public void setHeight(float height) {
        this.height = height;
    }

    public float x = 0f;
    public float y = 0f;
    public float width = 0f;
    public float height = 0f;

    RectF(RectF rectF) {
        this.x = rectF.x;
        this.y = rectF.y;
        this.width = rectF.width;
        this.height = rectF.height;
    }

    RectF(float x, float y, float w, float h) {
        this.x = x;
        this.y = y;
        this.width = w;
        this.height = h;
    }
}
```

答:
solved (I mixed up with x,y,width,height and left,top,right,bottom)

here's an updated RectF:

```<code>public class RectF {
    public float left;
    public float top;
    public float right;
    public float bottom;

    public RectF() {}

    public RectF(float left, float top, float right, float bottom) {
        this.left = left;
        this.top = top;
        this.right = right;
        this.bottom = bottom;
    }

    public RectF(RectF r) {
        if (r == null) {
            left = top = right = bottom = 0.0f;
        } else {
            left = r.left;
            top = r.top;
            right = r.right;
            bottom = r.bottom;
        }
    }

    public String toString() {
        return "RectF(" + left + ", " + top + ", "
                + right + ", " + bottom + ")";
    }

    public final float width() {
        return right - left;
    }

    public final float height() {
        return bottom - top;
    }

    public final float centerX() {
        return (left + right) * 0.5f;
    }

    public final float centerY() {
        return (top + bottom) * 0.5f;
    }
}
</code>```

and then

```<code>graphics.drawRoundRect((int) rectF.left, (int) rectF.top, (int) rectF.width(), (int) rectF.height(), 5, 5);
</code>```

p.s. for TensorFlow 1.4.0 here's an updated TensorFlowInferenceInterface class:

```<code>public class TensorFlowInferenceInterface {
    private final Graph g;
    private final Session sess;
    private Runner runner;
    private List<String> feedNames = new ArrayList();
    private List<Tensor<?>> feedTensors = new ArrayList();
    private List<String> fetchNames = new ArrayList();
    private List<Tensor<?>> fetchTensors = new ArrayList();
    private RunStats runStats;

    public TensorFlowInferenceInterface(Path path) {
        this.prepareNativeRuntime();
        this.g = new Graph();
        this.sess = new Session(this.g);
        this.runner = this.sess.runner();

        try {
            this.loadGraph(readAllBytesOrExit(path), this.g);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static byte[] readAllBytesOrExit(Path path) {
        try {
            return Files.readAllBytes(path);
        } catch (IOException e) {
            System.err.println("Failed to read [" + path + "]: " + e.getMessage());
            System.exit(1);
        }
        return null;
    }

    public void run(String[] var1) {
        this.run(var1, false);
    }

    public void run(String[] var1, boolean var2) {
        this.closeFetches();
        String[] var3 = var1;
        int var4 = var1.length;

        for(int var5 = 0; var5 < var4; ++var5) {
            String var6 = var3[var5];
            this.fetchNames.add(var6);
            TensorFlowInferenceInterface.TensorId var7 = TensorFlowInferenceInterface.TensorId.parse(var6);
            this.runner.fetch(var7.name, var7.outputIndex);
        }

        try {
            if(var2) {
                Run var13 = this.runner.setOptions(RunStats.runOptions()).runAndFetchMetadata();
                this.fetchTensors = var13.outputs;
                if(this.runStats == null) {
                    this.runStats = new RunStats();
                }

                this.runStats.add(var13.metadata);
            } else {
                this.fetchTensors = this.runner.run();
            }
        } catch (RuntimeException var11) {
            System.out.println("Failed to run TensorFlow inference with inputs:["
                    + String.join(", ", this.feedNames)
                    + "], outputs:[" + String.join(", ", this.fetchNames) + "]");
            throw var11;
        } finally {
            this.closeFeeds();
            this.runner = this.sess.runner();
        }

    }

    public Graph graph() {
        return this.g;
    }

    public Operation graphOperation(String var1) {
        Operation var2 = this.g.operation(var1);
        if(var2 == null) {
            throw new RuntimeException("Node '" + var1 + "' does not exist in model '");
        } else {
            return var2;
        }
    }

    public String getStatString() {
        return this.runStats == null?"":this.runStats.summary();
    }

    public void close() {
        this.closeFeeds();
        this.closeFetches();
        this.sess.close();
        this.g.close();
        if(this.runStats != null) {
            this.runStats.close();
        }

        this.runStats = null;
    }

    protected void finalize() throws Throwable {
        try {
            this.close();
        } finally {
            super.finalize();
        }

    }

    public void feed(String var1, float[] var2, long... var3) {
        this.addFeed(var1, Tensor.create(var3, FloatBuffer.wrap(var2)));
    }

    public void feed(String var1, int[] var2, long... var3) {
        this.addFeed(var1, Tensor.create(var3, IntBuffer.wrap(var2)));
    }

    public void feed(String var1, long[] var2, long... var3) {
        this.addFeed(var1, Tensor.create(var3, LongBuffer.wrap(var2)));
    }

    public void feed(String var1, double[] var2, long... var3) {
        this.addFeed(var1, Tensor.create(var3, DoubleBuffer.wrap(var2)));
    }

    public void feed(String var1, byte[] var2, long... var3) {
        this.addFeed(var1, Tensor.create(UInt8.class, var3, ByteBuffer.wrap(var2)));
    }

    public void feedString(String var1, byte[] var2) {
        this.addFeed(var1, Tensors.create(var2));
    }

    public void feedString(String var1, byte[][] var2) {
        this.addFeed(var1, Tensors.create(var2));
    }

    public void feed(String var1, FloatBuffer var2, long... var3) {
        this.addFeed(var1, Tensor.create(var3, var2));
    }

    public void feed(String var1, IntBuffer var2, long... var3) {
        this.addFeed(var1, Tensor.create(var3, var2));
    }

    public void feed(String var1, LongBuffer var2, long... var3) {
        this.addFeed(var1, Tensor.create(var3, var2));
    }

    public void feed(String var1, DoubleBuffer var2, long... var3) {
        this.addFeed(var1, Tensor.create(var3, var2));
    }

    public void feed(String var1, ByteBuffer var2, long... var3) {
        this.addFeed(var1, Tensor.create(UInt8.class, var3, var2));
    }

    public void fetch(String var1, float[] var2) {
        this.fetch(var1, FloatBuffer.wrap(var2));
    }

    public void fetch(String var1, int[] var2) {
        this.fetch(var1, IntBuffer.wrap(var2));
    }

    public void fetch(String var1, long[] var2) {
        this.fetch(var1, LongBuffer.wrap(var2));
    }

    public void fetch(String var1, double[] var2) {
        this.fetch(var1, DoubleBuffer.wrap(var2));
    }

    public void fetch(String var1, byte[] var2) {
        this.fetch(var1, ByteBuffer.wrap(var2));
    }

    public void fetch(String var1, FloatBuffer var2) {
        this.getTensor(var1).writeTo(var2);
    }

    public void fetch(String var1, IntBuffer var2) {
        this.getTensor(var1).writeTo(var2);
    }

    public void fetch(String var1, LongBuffer var2) {
        this.getTensor(var1).writeTo(var2);
    }

    public void fetch(String var1, DoubleBuffer var2) {
        this.getTensor(var1).writeTo(var2);
    }

    public void fetch(String var1, ByteBuffer var2) {
        this.getTensor(var1).writeTo(var2);
    }

    private void prepareNativeRuntime() {
        System.out.println("Checking to see if TensorFlow native methods are already loaded");

        try {
            new RunStats();
            System.out.println("TensorFlow native methods already loaded");
        } catch (UnsatisfiedLinkError var4) {
            System.out.println("TensorFlow native methods not found, attempting to load via tensorflow_inference");

         /*   try {
                System.loadLibrary("tensorflow_inference");
                System.out.println("Successfully loaded TensorFlow native methods (RunStats error may be ignored)");
            } catch (UnsatisfiedLinkError var3) {
                throw new RuntimeException("Native TF methods not found; check that the correct native libraries are present in the APK.");
            }*/
        }

    }

    private void loadGraph(byte[] var1, Graph var2) throws IOException {
        long var3 = System.currentTimeMillis();
        try {
            var2.importGraphDef(var1);
        } catch (IllegalArgumentException var7) {
            throw new IOException("Not a valid TensorFlow Graph serialization: " + var7.getMessage());
        }

        long var5 = System.currentTimeMillis();
        System.out.println("Model load took " + (var5 - var3) + "ms, TensorFlow version: " + TensorFlow.version());
    }

    private void addFeed(String var1, Tensor<?> var2) {
        TensorFlowInferenceInterface.TensorId var3 = TensorFlowInferenceInterface.TensorId.parse(var1);
        this.runner.feed(var3.name, var3.outputIndex, var2);
        this.feedNames.add(var1);
        this.feedTensors.add(var2);
    }

    private Tensor<?> getTensor(String var1) {
        int var2 = 0;

        for(Iterator var3 = this.fetchNames.iterator(); var3.hasNext(); ++var2) {
            String var4 = (String)var3.next();
            if(var4.equals(var1)) {
                return (Tensor)this.fetchTensors.get(var2);
            }
        }

        throw new RuntimeException("Node '" + var1 + "' was not provided to run(), so it cannot be read");
    }

    private void closeFeeds() {
        Iterator var1 = this.feedTensors.iterator();

        while(var1.hasNext()) {
            Tensor var2 = (Tensor)var1.next();
            var2.close();
        }

        this.feedTensors.clear();
        this.feedNames.clear();
    }

    private void closeFetches() {
        Iterator var1 = this.fetchTensors.iterator();

        while(var1.hasNext()) {
            Tensor var2 = (Tensor)var1.next();
            var2.close();
        }

        this.fetchTensors.clear();
        this.fetchNames.clear();
    }

    private static class TensorId {
        String name;
        int outputIndex;

        private TensorId() {
        }

        public static TensorFlowInferenceInterface.TensorId parse(String var0) {
            TensorFlowInferenceInterface.TensorId var1 = new TensorFlowInferenceInterface.TensorId();
            int var2 = var0.lastIndexOf(58);
            if(var2 < 0) {
                var1.outputIndex = 0;
                var1.name = var0;
                return var1;
            } else {
                try {
                    var1.outputIndex = Integer.parseInt(var0.substring(var2 + 1));
                    var1.name = var0.substring(0, var2);
                } catch (NumberFormatException var4) {
                    var1.outputIndex = 0;
                    var1.name = var0;
                }

                return var1;
            }
        }
    }
}
</code>```

Title: Yolo detector in Java

Body:
I'm trying to implement Yolo detector in Java (not Android, but desktops - Windows/Ubuntu)

There is already Yolo detector for Android: https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/android

I copied some java classes from that project, added them to IntelliJ IDEA and edited them

I even copied and edited TensorFlowInferenceInterface.java which is from jar file (tensorflow library - libandroid_tensorflow_inference_java.jar) for Android

I'm almost succeeded to get it working.

Result

Console output (class title, confidence, x, y, width, height):

car 0.8836523, 148 166 270 267

car 0.51286024, 147 174 268 274

car 0.05002968, 174 164 275 262

So seems it correctly detected car, determined correct x, y
but something wrong with width and height

What could be wrong?

Here's the full code from my project

Main

public class Main implements Classifier {

    private static final int BLOCK_SIZE = 32;
    private static final int MAX_RESULTS = 3;
    private static final int NUM_CLASSES = 20;
    private static final int NUM_BOXES_PER_BLOCK = 5;
    private static final int INPUT_SIZE = 416;
    private static final String inputName = "input";
    private static final String outputName = "output";

    // Pre-allocated buffers.
    private static int[] intValues;
    private static float[] floatValues;
    private static String[] outputNames;

    // yolo 2
    private static final double[] ANCHORS = { 1.3221, 1.73145, 3.19275, 4.00944, 5.05587, 8.09892, 9.47112, 4.84053, 11.2364, 10.0071 };

    // tiny yolo
    //private static final double[] ANCHORS = { 1.08, 1.19, 3.42, 4.41, 6.63, 11.38, 9.42, 5.11, 16.62, 10.52 };

    private static final String[] LABELS = {
            "aeroplane",
            "bicycle",
            "bird",
            "boat",
            "bottle",
            "bus",
            "car",
            "cat",
            "chair",
            "cow",
            "diningtable",
            "dog",
            "horse",
            "motorbike",
            "person",
            "pottedplant",
            "sheep",
            "sofa",
            "train",
            "tvmonitor"
    };

    private static TensorFlowInferenceInterface inferenceInterface;

    public static void main(String[] args) {

        //String modelDir = "/home/user/JavaProjects/TensorFlowJavaProject"; // Ubuntu
        String modelAndTestImagesDir = "D:\\JavaProjects\\TensorFlowJavaProject"; // Windows
        String imageFile = modelAndTestImagesDir + File.separator + "0.png"; // 416x416 test image

        outputNames = outputName.split(",");
        floatValues = new float[INPUT_SIZE * INPUT_SIZE * 3];

        // yolo 2 voc
        inferenceInterface = new TensorFlowInferenceInterface(Paths.get(modelAndTestImagesDir, "yolo-voc.pb"));

        // tiny yolo voc
        //inferenceInterface = new TensorFlowInferenceInterface(Paths.get(modelAndTestImagesDir, "graph-tiny-yolo-voc.pb"));

        BufferedImage img;

        try {
            img = ImageIO.read(new File(imageFile));

            BufferedImage convertedImg = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_RGB);
            convertedImg.getGraphics().drawImage(img, 0, 0, null);

            intValues = ((DataBufferInt) convertedImg.getRaster().getDataBuffer()).getData() ;

            List<Classifier.Recognition> recognitions = recognizeImage();

            System.out.println("Result length " + recognitions.size());

            Graphics2D graphics = convertedImg.createGraphics();

            for (Recognition recognition : recognitions) {
                RectF rectF = recognition.getLocation();
                System.out.println(recognition.getTitle() + " " + recognition.getConfidence() + ", " +
                        (int) rectF.x + " " + (int) rectF.y + " " + (int) rectF.width + " " + ((int) rectF.height));
                Stroke stroke = graphics.getStroke();
                graphics.setStroke(new BasicStroke(3));
                graphics.setColor(Color.green);
                graphics.drawRoundRect((int) rectF.x, (int) rectF.y, (int) rectF.width, (int) rectF.height, 5, 5);
                graphics.setStroke(stroke);
            }

            graphics.dispose();
            ImageIcon icon=new ImageIcon(convertedImg);
            JFrame frame=new JFrame();
            frame.setLayout(new FlowLayout());
            frame.setSize(convertedImg.getWidth(),convertedImg.getHeight());
            JLabel lbl=new JLabel();
            frame.setTitle("Java (Win/Ubuntu), Tensorflow & Yolo");
            lbl.setIcon(icon);
            frame.add(lbl);
            frame.setVisible(true);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private static List<Classifier.Recognition> recognizeImage() {

        for (int i = 0; i < intValues.length; ++i) {
            floatValues[i * 3 + 0] = ((intValues[i] >> 16) & 0xFF) / 255.0f;
            floatValues[i * 3 + 1] = ((intValues[i] >> 8) & 0xFF) / 255.0f;
            floatValues[i * 3 + 2] = (intValues[i] & 0xFF) / 255.0f;
        }
        inferenceInterface.feed(inputName, floatValues, 1, INPUT_SIZE, INPUT_SIZE, 3);

        inferenceInterface.run(outputNames, false);

        final int gridWidth = INPUT_SIZE / BLOCK_SIZE;
        final int gridHeight = INPUT_SIZE / BLOCK_SIZE;

        final float[] output = new float[gridWidth * gridHeight * (NUM_CLASSES + 5) * NUM_BOXES_PER_BLOCK];

        inferenceInterface.fetch(outputNames[0], output);

        // Find the best detections.
        final PriorityQueue<Classifier.Recognition> pq =
                new PriorityQueue<>(
                        1,
                        new Comparator<Classifier.Recognition>() {
                            @Override
                            public int compare(final Classifier.Recognition lhs, final Classifier.Recognition rhs) {
                                // Intentionally reversed to put high confidence at the head of the queue.
                                return Float.compare(rhs.getConfidence(), lhs.getConfidence());
                            }
                        });

        for (int y = 0; y < gridHeight; ++y) {
            for (int x = 0; x < gridWidth; ++x) {
                for (int b = 0; b < NUM_BOXES_PER_BLOCK; ++b) {
                    final int offset =
                            (gridWidth * (NUM_BOXES_PER_BLOCK * (NUM_CLASSES + 5))) * y
                                    + (NUM_BOXES_PER_BLOCK * (NUM_CLASSES + 5)) * x
                                    + (NUM_CLASSES + 5) * b;

                    final float xPos = (x + expit(output[offset + 0])) * BLOCK_SIZE;
                    final float yPos = (y + expit(output[offset + 1])) * BLOCK_SIZE;

                    final float w = (float) (Math.exp(output[offset + 2]) * ANCHORS[2 * b + 0]) * BLOCK_SIZE;
                    final float h = (float) (Math.exp(output[offset + 3]) * ANCHORS[2 * b + 1]) * BLOCK_SIZE;

                    final RectF rect =
                            new RectF(
                                    Math.max(0, xPos - w / 2),
                                    Math.max(0, yPos - h / 2),
                                    Math.min(INPUT_SIZE - 1, xPos + w / 2),
                                    Math.min(INPUT_SIZE - 1, yPos + h / 2));

                    final float confidence = expit(output[offset + 4]);

                    int detectedClass = -1;
                    float maxClass = 0;

                    final float[] classes = new float[NUM_CLASSES];
                    for (int c = 0; c < NUM_CLASSES; ++c) {
                        classes[c] = output[offset + 5 + c];
                    }
                    softmax(classes);

                    for (int c = 0; c < NUM_CLASSES; ++c) {
                        if (classes[c] > maxClass) {
                            detectedClass = c;
                            maxClass = classes[c];
                        }
                    }

                    final float confidenceInClass = maxClass * confidence;
                    if (confidenceInClass > 0.01) {
                        pq.add(new Classifier.Recognition(detectedClass, LABELS[detectedClass], confidenceInClass, rect));
                    }
                }
            }
        }

        final ArrayList<Classifier.Recognition> recognitions = new ArrayList<>();
        for (int i = 0; i < Math.min(pq.size(), MAX_RESULTS); ++i) {
            recognitions.add(pq.poll());
        }
        return recognitions;

    }

    private static float expit(final float x) {
        return (float) (1. / (1. + Math.exp(-x)));
    }

    private static void softmax(final float[] vals) {
        float max = Float.NEGATIVE_INFINITY;
        for (final float val : vals) {
            max = Math.max(max, val);
        }
        float sum = 0.0f;
        for (int i = 0; i < vals.length; ++i) {
            vals[i] = (float) Math.exp(vals[i] - max);
            sum += vals[i];
        }
        for (int i = 0; i < vals.length; ++i) {
            vals[i] = vals[i] / sum;
        }
    }

    public void close() {
        inferenceInterface.close();
    }
}

TensorFlowInferenceInterface

public class TensorFlowInferenceInterface {
    private static final String TAG = "TensorFlowInferenceInterface";
    private final Graph g;
    private final Session sess;
    private Runner runner;
    private List<String> feedNames = new ArrayList();
    private List<Tensor> feedTensors = new ArrayList();
    private List<String> fetchNames = new ArrayList();
    private List<Tensor> fetchTensors = new ArrayList();
    private RunStats runStats;

    public TensorFlowInferenceInterface(Path path) {
        this.prepareNativeRuntime();
        this.g = new Graph();
        this.sess = new Session(this.g);
        this.runner = this.sess.runner();

        try {
            this.loadGraph(readAllBytesOrExit(path), this.g);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static byte[] readAllBytesOrExit(Path path) {
        try {
            return Files.readAllBytes(path);
        } catch (IOException e) {
            System.err.println("Failed to read [" + path + "]: " + e.getMessage());
            System.exit(1);
        }
        return null;
    }

    public void run(String[] var1) {
        this.run(var1, false);
    }

    public void run(String[] var1, boolean var2) {
        this.closeFetches();
        String[] var3 = var1;
        int var4 = var1.length;

        for (int var5 = 0; var5 < var4; ++var5) {
            String var6 = var3[var5];
            this.fetchNames.add(var6);
            TensorFlowInferenceInterface.TensorId var7 = TensorFlowInferenceInterface.TensorId.parse(var6);
            this.runner.fetch(var7.name, var7.outputIndex);
        }

        try {
            if (var2) {
                Run var13 = this.runner.setOptions(RunStats.runOptions()).runAndFetchMetadata();
                this.fetchTensors = var13.outputs;
                if (this.runStats == null) {
                    this.runStats = new RunStats();
                }

                this.runStats.add(var13.metadata);
            } else {
                this.fetchTensors = this.runner.run();
            }
        } catch (RuntimeException var11) {
            throw var11;
        } finally {
            this.closeFeeds();
            this.runner = this.sess.runner();
        }

    }

    public Graph graph() {
        return this.g;
    }

    public Operation graphOperation(String var1) {
        Operation var2 = this.g.operation(var1);
        if (var2 == null) {
            throw new RuntimeException("Node '" + var1 + "' does not exist in model '");
        } else {
            return var2;
        }
    }

    public String getStatString() {
        return this.runStats == null ? "" : this.runStats.summary();
    }

    public void close() {
        this.closeFeeds();
        this.closeFetches();
        this.sess.close();
        this.g.close();
        if (this.runStats != null) {
            this.runStats.close();
        }

        this.runStats = null;
    }

    protected void finalize() throws Throwable {
        try {
            this.close();
        } finally {
            super.finalize();
        }

    }

    public void feed(String var1, float[] var2, long... var3) {
        this.addFeed(var1, Tensor.create(var3, FloatBuffer.wrap(var2)));
    }

    public void fetch(String var1, float[] var2) {
        this.fetch(var1, FloatBuffer.wrap(var2));
    }

    public void fetch(String var1, FloatBuffer var2) {
        this.getTensor(var1).writeTo(var2);
    }

    private void prepareNativeRuntime() {
        System.out.println("TensorFlowInferenceInterface Checking to see if TensorFlow native methods are already loaded");

        try {
            new RunStats();
            System.out.println("TensorFlowInferenceInterface TensorFlow native methods already loaded");
        } catch (UnsatisfiedLinkError var4) {
            System.out.println("TensorFlowInferenceInterface TensorFlow native methods not found, attempting to load via tensorflow_inference");
        }

    }

    private void loadGraph(byte[] var1, Graph var2) throws IOException {
        try {
            var2.importGraphDef(var1);
        } catch (IllegalArgumentException var7) {
            throw new IOException("Not a valid TensorFlow Graph serialization: " + var7.getMessage());
        }
    }

    private void addFeed(String var1, Tensor var2) {
        TensorFlowInferenceInterface.TensorId var3 = TensorFlowInferenceInterface.TensorId.parse(var1);
        this.runner.feed(var3.name, var3.outputIndex, var2);
        this.feedNames.add(var1);
        this.feedTensors.add(var2);
    }

    private Tensor getTensor(String var1) {
        int var2 = 0;

        for (Iterator var3 = this.fetchNames.iterator(); var3.hasNext(); ++var2) {
            String var4 = (String) var3.next();
            if (var4.equals(var1)) {
                return this.fetchTensors.get(var2);
            }
        }

        throw new RuntimeException("Node '" + var1 + "' was not provided to run(), so it cannot be read");
    }

    private void closeFeeds() {
        Iterator var1 = this.feedTensors.iterator();

        while (var1.hasNext()) {
            Tensor var2 = (Tensor) var1.next();
            var2.close();
        }

        this.feedTensors.clear();
        this.feedNames.clear();
    }

    private void closeFetches() {
        Iterator var1 = this.fetchTensors.iterator();

        while (var1.hasNext()) {
            Tensor var2 = (Tensor) var1.next();
            var2.close();
        }

        this.fetchTensors.clear();
        this.fetchNames.clear();
    }

    private static class TensorId {
        String name;
        int outputIndex;

        private TensorId() {
        }

        public static TensorFlowInferenceInterface.TensorId parse(String var0) {
            TensorFlowInferenceInterface.TensorId var1 = new TensorFlowInferenceInterface.TensorId();
            int var2 = var0.lastIndexOf(58);
            if (var2 < 0) {
                var1.outputIndex = 0;
                var1.name = var0;
                return var1;
            } else {
                try {
                    var1.outputIndex = Integer.parseInt(var0.substring(var2 + 1));
                    var1.name = var0.substring(0, var2);
                } catch (NumberFormatException var4) {
                    var1.outputIndex = 0;
                    var1.name = var0;
                }

                return var1;
            }
        }
    }
}

Classifier

public interface Classifier {

  public class Recognition {

    private final int id;

    private final String title;

    private final Float confidence;

    private RectF location;

    public Recognition(
            final int id, final String title, final Float confidence, final RectF location) {
      this.id = id;
      this.title = title;
      this.confidence = confidence;
      this.location = location;
    }

    public int getId() {
      return id;
    }

    public String getTitle() {
      return title;
    }

    public Float getConfidence() {
      return confidence;
    }

    public RectF getLocation() {
      return new RectF(location);
    }

    public void setLocation(RectF location) {
      this.location = location;
    }
  }

  void close();
}

RunStats

public class RunStats implements AutoCloseable {
    private long nativeHandle = allocate();
    private static byte[] fullTraceRunOptions = new byte[]{8, 3};

    public static byte[] runOptions() {
        return fullTraceRunOptions;
    }

    public RunStats() {
    }

    public void close() {
        if(this.nativeHandle != 0L) {
            delete(this.nativeHandle);
        }

        this.nativeHandle = 0L;
    }

    public synchronized void add(byte[] var1) {
        add(this.nativeHandle, var1);
    }

    public synchronized String summary() {
        return summary(this.nativeHandle);
    }

    private static native long allocate();

    private static native void delete(long var0);

    private static native void add(long var0, byte[] var2);

    private static native String summary(long var0);
}

RectF

public class RectF {

    public float getX() {
        return x;
    }

    public void setX(float x) {
        this.x = x;
    }

    public float getY() {
        return y;
    }

    public void setY(float y) {
        this.y = y;
    }

    public float getWidth() {
        return width;
    }

    public void setWidth(float width) {
        this.width = width;
    }

    public float getHeight() {
        return height;
    }

    public void setHeight(float height) {
        this.height = height;
    }

    public float x = 0f;
    public float y = 0f;
    public float width = 0f;
    public float height = 0f;

    RectF(RectF rectF) {
        this.x = rectF.x;
        this.y = rectF.y;
        this.width = rectF.width;
        this.height = rectF.height;
    }

    RectF(float x, float y, float w, float h) {
        this.x = x;
        this.y = y;
        this.width = w;
        this.height = h;
    }
}

Body:
solved (I mixed up with x,y,width,height and left,top,right,bottom)

here's an updated RectF:

public class RectF {
    public float left;
    public float top;
    public float right;
    public float bottom;

    public RectF() {}

    public RectF(float left, float top, float right, float bottom) {
        this.left = left;
        this.top = top;
        this.right = right;
        this.bottom = bottom;
    }

    public RectF(RectF r) {
        if (r == null) {
            left = top = right = bottom = 0.0f;
        } else {
            left = r.left;
            top = r.top;
            right = r.right;
            bottom = r.bottom;
        }
    }

    public String toString() {
        return "RectF(" + left + ", " + top + ", "
                + right + ", " + bottom + ")";
    }

    public final float width() {
        return right - left;
    }

    public final float height() {
        return bottom - top;
    }

    public final float centerX() {
        return (left + right) * 0.5f;
    }

    public final float centerY() {
        return (top + bottom) * 0.5f;
    }
}

and then

graphics.drawRoundRect((int) rectF.left, (int) rectF.top, (int) rectF.width(), (int) rectF.height(), 5, 5);

p.s. for TensorFlow 1.4.0 here's an updated TensorFlowInferenceInterface class:

public class TensorFlowInferenceInterface {
    private final Graph g;
    private final Session sess;
    private Runner runner;
    private List<String> feedNames = new ArrayList();
    private List<Tensor<?>> feedTensors = new ArrayList();
    private List<String> fetchNames = new ArrayList();
    private List<Tensor<?>> fetchTensors = new ArrayList();
    private RunStats runStats;

    public TensorFlowInferenceInterface(Path path) {
        this.prepareNativeRuntime();
        this.g = new Graph();
        this.sess = new Session(this.g);
        this.runner = this.sess.runner();

        try {
            this.loadGraph(readAllBytesOrExit(path), this.g);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static byte[] readAllBytesOrExit(Path path) {
        try {
            return Files.readAllBytes(path);
        } catch (IOException e) {
            System.err.println("Failed to read [" + path + "]: " + e.getMessage());
            System.exit(1);
        }
        return null;
    }

    public void run(String[] var1) {
        this.run(var1, false);
    }

    public void run(String[] var1, boolean var2) {
        this.closeFetches();
        String[] var3 = var1;
        int var4 = var1.length;

        for(int var5 = 0; var5 < var4; ++var5) {
            String var6 = var3[var5];
            this.fetchNames.add(var6);
            TensorFlowInferenceInterface.TensorId var7 = TensorFlowInferenceInterface.TensorId.parse(var6);
            this.runner.fetch(var7.name, var7.outputIndex);
        }

        try {
            if(var2) {
                Run var13 = this.runner.setOptions(RunStats.runOptions()).runAndFetchMetadata();
                this.fetchTensors = var13.outputs;
                if(this.runStats == null) {
                    this.runStats = new RunStats();
                }

                this.runStats.add(var13.metadata);
            } else {
                this.fetchTensors = this.runner.run();
            }
        } catch (RuntimeException var11) {
            System.out.println("Failed to run TensorFlow inference with inputs:["
                    + String.join(", ", this.feedNames)
                    + "], outputs:[" + String.join(", ", this.fetchNames) + "]");
            throw var11;
        } finally {
            this.closeFeeds();
            this.runner = this.sess.runner();
        }

    }

    public Graph graph() {
        return this.g;
    }

    public Operation graphOperation(String var1) {
        Operation var2 = this.g.operation(var1);
        if(var2 == null) {
            throw new RuntimeException("Node '" + var1 + "' does not exist in model '");
        } else {
            return var2;
        }
    }

    public String getStatString() {
        return this.runStats == null?"":this.runStats.summary();
    }

    public void close() {
        this.closeFeeds();
        this.closeFetches();
        this.sess.close();
        this.g.close();
        if(this.runStats != null) {
            this.runStats.close();
        }

        this.runStats = null;
    }

    protected void finalize() throws Throwable {
        try {
            this.close();
        } finally {
            super.finalize();
        }

    }

    public void feed(String var1, float[] var2, long... var3) {
        this.addFeed(var1, Tensor.create(var3, FloatBuffer.wrap(var2)));
    }

    public void feed(String var1, int[] var2, long... var3) {
        this.addFeed(var1, Tensor.create(var3, IntBuffer.wrap(var2)));
    }

    public void feed(String var1, long[] var2, long... var3) {
        this.addFeed(var1, Tensor.create(var3, LongBuffer.wrap(var2)));
    }

    public void feed(String var1, double[] var2, long... var3) {
        this.addFeed(var1, Tensor.create(var3, DoubleBuffer.wrap(var2)));
    }

    public void feed(String var1, byte[] var2, long... var3) {
        this.addFeed(var1, Tensor.create(UInt8.class, var3, ByteBuffer.wrap(var2)));
    }

    public void feedString(String var1, byte[] var2) {
        this.addFeed(var1, Tensors.create(var2));
    }

    public void feedString(String var1, byte[][] var2) {
        this.addFeed(var1, Tensors.create(var2));
    }

    public void feed(String var1, FloatBuffer var2, long... var3) {
        this.addFeed(var1, Tensor.create(var3, var2));
    }

    public void feed(String var1, IntBuffer var2, long... var3) {
        this.addFeed(var1, Tensor.create(var3, var2));
    }

    public void feed(String var1, LongBuffer var2, long... var3) {
        this.addFeed(var1, Tensor.create(var3, var2));
    }

    public void feed(String var1, DoubleBuffer var2, long... var3) {
        this.addFeed(var1, Tensor.create(var3, var2));
    }

    public void feed(String var1, ByteBuffer var2, long... var3) {
        this.addFeed(var1, Tensor.create(UInt8.class, var3, var2));
    }

    public void fetch(String var1, float[] var2) {
        this.fetch(var1, FloatBuffer.wrap(var2));
    }

    public void fetch(String var1, int[] var2) {
        this.fetch(var1, IntBuffer.wrap(var2));
    }

    public void fetch(String var1, long[] var2) {
        this.fetch(var1, LongBuffer.wrap(var2));
    }

    public void fetch(String var1, double[] var2) {
        this.fetch(var1, DoubleBuffer.wrap(var2));
    }

    public void fetch(String var1, byte[] var2) {
        this.fetch(var1, ByteBuffer.wrap(var2));
    }

    public void fetch(String var1, FloatBuffer var2) {
        this.getTensor(var1).writeTo(var2);
    }

    public void fetch(String var1, IntBuffer var2) {
        this.getTensor(var1).writeTo(var2);
    }

    public void fetch(String var1, LongBuffer var2) {
        this.getTensor(var1).writeTo(var2);
    }

    public void fetch(String var1, DoubleBuffer var2) {
        this.getTensor(var1).writeTo(var2);
    }

    public void fetch(String var1, ByteBuffer var2) {
        this.getTensor(var1).writeTo(var2);
    }

    private void prepareNativeRuntime() {
        System.out.println("Checking to see if TensorFlow native methods are already loaded");

        try {
            new RunStats();
            System.out.println("TensorFlow native methods already loaded");
        } catch (UnsatisfiedLinkError var4) {
            System.out.println("TensorFlow native methods not found, attempting to load via tensorflow_inference");

         /*   try {
                System.loadLibrary("tensorflow_inference");
                System.out.println("Successfully loaded TensorFlow native methods (RunStats error may be ignored)");
            } catch (UnsatisfiedLinkError var3) {
                throw new RuntimeException("Native TF methods not found; check that the correct native libraries are present in the APK.");
            }*/
        }

    }

    private void loadGraph(byte[] var1, Graph var2) throws IOException {
        long var3 = System.currentTimeMillis();
        try {
            var2.importGraphDef(var1);
        } catch (IllegalArgumentException var7) {
            throw new IOException("Not a valid TensorFlow Graph serialization: " + var7.getMessage());
        }

        long var5 = System.currentTimeMillis();
        System.out.println("Model load took " + (var5 - var3) + "ms, TensorFlow version: " + TensorFlow.version());
    }

    private void addFeed(String var1, Tensor<?> var2) {
        TensorFlowInferenceInterface.TensorId var3 = TensorFlowInferenceInterface.TensorId.parse(var1);
        this.runner.feed(var3.name, var3.outputIndex, var2);
        this.feedNames.add(var1);
        this.feedTensors.add(var2);
    }

    private Tensor<?> getTensor(String var1) {
        int var2 = 0;

        for(Iterator var3 = this.fetchNames.iterator(); var3.hasNext(); ++var2) {
            String var4 = (String)var3.next();
            if(var4.equals(var1)) {
                return (Tensor)this.fetchTensors.get(var2);
            }
        }

        throw new RuntimeException("Node '" + var1 + "' was not provided to run(), so it cannot be read");
    }

    private void closeFeeds() {
        Iterator var1 = this.feedTensors.iterator();

        while(var1.hasNext()) {
            Tensor var2 = (Tensor)var1.next();
            var2.close();
        }

        this.feedTensors.clear();
        this.feedNames.clear();
    }

    private void closeFetches() {
        Iterator var1 = this.fetchTensors.iterator();

        while(var1.hasNext()) {
            Tensor var2 = (Tensor)var1.next();
            var2.close();
        }

        this.fetchTensors.clear();
        this.fetchNames.clear();
    }

    private static class TensorId {
        String name;
        int outputIndex;

        private TensorId() {
        }

        public static TensorFlowInferenceInterface.TensorId parse(String var0) {
            TensorFlowInferenceInterface.TensorId var1 = new TensorFlowInferenceInterface.TensorId();
            int var2 = var0.lastIndexOf(58);
            if(var2 < 0) {
                var1.outputIndex = 0;
                var1.name = var0;
                return var1;
            } else {
                try {
                    var1.outputIndex = Integer.parseInt(var0.substring(var2 + 1));
                    var1.name = var0.substring(0, var2);
                } catch (NumberFormatException var4) {
                    var1.outputIndex = 0;
                    var1.name = var0;
                }

                return var1;
            }
        }
    }
}


来源: stackexchange

问:
What is the best practices to call getActivity() in fragment so that it doesn't return null?
Question is not about solving that null return, it is about best practices to prevent from occurring.

What mistakes should one avoid while working with fragments to avoid getting null on getActivity() method? Especially fragments on viewpagers.

Usually when this happens and under what circumstances?

答:
If you are running code that gets null for getActivity() or getContext() for that matter, that means that your code is running after your fragment has been detached, onDetach() was called.

This happens probably because you were running an async operation, and when the result came back your fragment was detached from the activity, or it might even have been destroyed. So in this case it is valid to find getActivity to return null, and in this case you just need to either:

Do nothing, because you wanted to update the fragment's view, but that's not shown to the user anymore.

Save the data you or the state you got so you can re-use it when/if
the fragment is re-attached again.

ContentLicense: CC BY-SA 3.0


问:
How to Send a Form post Using Ajax in Laravel 5.4
I'm trying to send a form with a POST method but I'm getting a query exception error.

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'post_id'
  cannot be null (SQL: insert into comments (comment, approved,
  user_id, post_id, updated_at, created_at) values (sdfsdfsdff,
  1, 1, , 2017-12-04 07:18:13, 2017-12-04 07:18:13))

'sdfsdfsdff' is the comment that I'm trying to send to the "comment system", 1 is the user id, the blank space is where the post id should be.

Controller

```<code><?php

$this->validate($request, [
    'comment' => 'required'
]);

$post = Post::find($post_id);
$comment = new Comment();
$comment->comment = $request->comment;
$comment->approved = true;
$comment->user_id = auth()->id();
$comment->post_id = $request->id;
$comment->save();

return response()->json([
    'comment' => $comment->comment,
    'user_id' => $comment->user_id,
    'post_id' => $comment->post_id,
    'post_slug' => $post->slug,
    'success' => true
]);
</code>```

Ajax code in the view

```<code>var urlPostComment = '{{ url('comments/store') }}';

$('.send').click(function(e){
   e.preventDefault();
   var dataSerialize = $('#comment-new').serialize();

   $.ajax({
      method: 'post',
      url: urlPostComment,
      data: dataSerialize,
      dataType: 'json', // <- La coma
      success: function (data) {
         console.log(data); // <- Revisar JSON en la consola del navegador
         if( data.success )
         {
            $('#comment-post').append(
               '<p class="store-comment">' + data.comentario + '</p>'
            );
         }

      }, // <- La coma
      error: function () {
         console.log('Error en el AJAX');
      }, // <- La coma
      complete: function () {
         console.log('Termino el ajax');
      }
   });
});
</code>```

Form

```<code><div class="row">
    <div class="col-xs-8 col-md-offset-2 form-create">
        {!! Form::open(['route' => ['comments.store', $post->id], 'method' => 'POST', 'id' => 'add-comment']) !!}
        <p class="error text-center alert alert-danger hidden"></p>
        {{ Form::label('comment', ' Comentario', ['class' => 'glyphicon glyphicon-comment pull-right label-space', 'id' => 'comment-create']) }}
        {{ Form::textarea('comment', null, ['class' => 'form-control comment-text', 'id' => 'comment-new', 'placeholder' => 'Escribe tu comentario']) }}
        <p class="error text-center alert alert-danger hidden"></p>
        {{ Form::submit('Agregar Comentario', ['class' => 'comment-message-guest-button send']) }}
        {!! Form::close() !!}
    </div>
</div>
</code>```

Comments HTML

```<code><div class="row">
        @foreach ($post->comments as $comment)
            <section class="comment-list">
                <article class="row">
                    <div class="col-md-3 col-sm-3 hidden-xs">
                        <figure class="thumbnail">
                            <img class="img-responsive" src="/uploads/avatars/{{ $comment->user->profilepic  }}"/>
                            <figcaption class="text-center">{{ $comment->user->name }}</figcaption>
                        </figure>
                    </div>
                    <div class="col-md-8 col-sm-8">
                        <div class="panel panel-default arrow left">
                            <div class="panel-body">
                                <header class="text-left">
                                    <div class="comment-user"><i class="fa fa-user"></i> {{ $comment->user->name }}
                                    </div>
                                    <time class="comment-date" datetime="{{ $comment->created_at->diffForHumans() }}"><i
                                                class="fa fa-clock-o"></i> {{ $comment->created_at->diffForHumans() }}
                                    </time>
                                </header>
                                <div id="comment-post" data-commentid="{{ $comment->id }}">
                                    <p id="display-comment"
                                       class="store-comment" {{ $comment->id }} {{ $post->id }}>{{ $comment->comment }}</p>
                                </div>
                            </div>

                            <div class="panel-footer list-inline comment-footer">
                                @if(Auth::guest())
                                    No puedes responder ningún comentario si no has ingresado.
                                @else
                                    @if(Auth::user() == $comment->user)
                                        <a href="#" data-toggle="modal" data-target="edit-comment" class="edit-comment">Editar</a>
                                        <a href="#" data-toggle="modal" data-target="delete-comment"
                                           class="delete-comment">Eliminar</a>
                                    @endif
                                    @if(Auth::user() != $comment->user)
                                        <a href="#">Responder</a>
                                    @endif
                                @endif
                            </div>
                        </div>
                    </div>
                </article>
            </section>
        @endforeach
</div>
</code>```

The main error:

POST http://localhost:8000/comments/store 500 (Internal Server Error)
  "from google chrome console"

In my comments table in the database, I do have the foreign key that worked perfectly when I wasn't using Ajax, so I don't think that's a relationship problem. Thank you in advance.

答:
Yes you are right.
It is not relationship problem. But I have the hack I guess,
As you have $post_id here $post = Post::find($post_id); then why do you use $request->id here in this line? $comment->post_id   = $request->id;

I doubt that $request->id is not having post id.

Try using this way:

```<code>$comment->post_id   = $post_id;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to send a form with a POST method but I'm getting a query exception error.

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'post_id'
  cannot be null (SQL: insert into comments (comment, approved,
  user_id, post_id, updated_at, created_at) values (sdfsdfsdff,
  1, 1, , 2017-12-04 07:18:13, 2017-12-04 07:18:13))

'sdfsdfsdff' is the comment that I'm trying to send to the "comment system", 1 is the user id, the blank space is where the post id should be.

Controller

<?php

$this->validate($request, [
    'comment' => 'required'
]);

$post = Post::find($post_id);
$comment = new Comment();
$comment->comment = $request->comment;
$comment->approved = true;
$comment->user_id = auth()->id();
$comment->post_id = $request->id;
$comment->save();

return response()->json([
    'comment' => $comment->comment,
    'user_id' => $comment->user_id,
    'post_id' => $comment->post_id,
    'post_slug' => $post->slug,
    'success' => true
]);

Ajax code in the view

var urlPostComment = '{{ url('comments/store') }}';

$('.send').click(function(e){
   e.preventDefault();
   var dataSerialize = $('#comment-new').serialize();

   $.ajax({
      method: 'post',
      url: urlPostComment,
      data: dataSerialize,
      dataType: 'json', // <- La coma
      success: function (data) {
         console.log(data); // <- Revisar JSON en la consola del navegador
         if( data.success )
         {
            $('#comment-post').append(
               '
' + data.comentario + '
'
            );
         }

      }, // <- La coma
      error: function () {
         console.log('Error en el AJAX');
      }, // <- La coma
      complete: function () {
         console.log('Termino el ajax');
      }
   });
});

Form

        {!! Form::open(['route' => ['comments.store', $post->id], 'method' => 'POST', 'id' => 'add-comment']) !!}

        {{ Form::label('comment', ' Comentario', ['class' => 'glyphicon glyphicon-comment pull-right label-space', 'id' => 'comment-create']) }}
        {{ Form::textarea('comment', null, ['class' => 'form-control comment-text', 'id' => 'comment-new', 'placeholder' => 'Escribe tu comentario']) }}

        {{ Form::submit('Agregar Comentario', ['class' => 'comment-message-guest-button send']) }}
        {!! Form::close() !!}

Comments HTML

        @foreach ($post->comments as $comment)

                            user->profilepic  }}"/>

{{ $comment->user->name }}

 {{ $comment->user->name }}

                                    <time class="comment-date" datetime="{{ $comment->created_at->diffForHumans() }}"> {{ $comment->created_at->diffForHumans() }}
                                    </time>

id }}">

id }} {{ $post->id }}>{{ $comment->comment }}

                                @if(Auth::guest())
                                    No puedes responder ningún comentario si no has ingresado.
                                @else
                                    @if(Auth::user() == $comment->user)
                                        Editar
                                        Eliminar
                                    @endif
                                    @if(Auth::user() != $comment->user)
                                        Responder
                                    @endif
                                @endif

        @endforeach

The main error:

POST http://localhost:8000/comments/store 500 (Internal Server Error)
  "from google chrome console"

In my comments table in the database, I do have the foreign key that worked perfectly when I wasn't using Ajax, so I don't think that's a relationship problem. Thank you in advance.

Body:
Yes you are right.
It is not relationship problem. But I have the hack I guess,
As you have $post_id here $post = Post::find($post_id); then why do you use $request->id here in this line? $comment->post_id   = $request->id;

I doubt that $request->id is not having post id.

Try using this way:

$comment->post_id   = $post_id;


问:
Changing my navigation based on date
I would like my site to display different seasonal projects based on the date. Currently, I call the 'Top Winter Projects' section of my right navigation with the following code:

```<code><?php include (TEMPLATEPATH . '/stub_favorites.php'); ?>
</code>```

Is there a way that I could use a php include based on date? So if its January 14, call /stub_favorites.php, but if its March 10, call stub_favorites1.php? I'm new to php so bear with me.

My website is as followed: http://www.merrimentdesign.com

答:
Take a look at PHPs Date/Time Functions: http://php.net/manual/en/ref.datetime.php

You can do something like:

```<code>if (date('m/d/Y') < date('m/d/Y', strtotime("12/1/2011"))) {
    //Display something
}
else {
    //Display something different
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Changing my navigation based on date

Body:
I would like my site to display different seasonal projects based on the date. Currently, I call the 'Top Winter Projects' section of my right navigation with the following code:

<?php include (TEMPLATEPATH . '/stub_favorites.php'); ?>

Is there a way that I could use a php include based on date? So if its January 14, call /stub_favorites.php, but if its March 10, call stub_favorites1.php? I'm new to php so bear with me.

My website is as followed: http://www.merrimentdesign.com

Body:
Take a look at PHPs Date/Time Functions: http://php.net/manual/en/ref.datetime.php

You can do something like:

if (date('m/d/Y') < date('m/d/Y', strtotime("12/1/2011"))) {
    //Display something
}
else {
    //Display something different
}


问:
Xib file as a Custom TableView Cell crashes
I am using Xib file as a custom Tableview Cell. But everytime i run my application, it crashes. I get this crash logs which i posted below

* Assertion failure in -[UITableView dequeueReusableCellWithIdentifier:forIndexPath:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3600.7.47/UITableView.m:6730
  2017-12-04 17:23:16.070 iCommander[2489:135476] * Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'
  *** First throw call stack:
  (
      0   CoreFoundation                      0x00000001035f6b0b exceptionPreprocess + 171
      1   libobjc.A.dylib                     0x000000010305b141 objc_exception_throw + 48
      2   CoreFoundation                      0x00000001035facf2 +[NSException raise:format:arguments:] + 98
      3   Foundation                          0x0000000102bf5536 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 193
      4   UIKit                               0x00000001042eae45 -[UITableView dequeueReusableCellWithIdentifier:forIndexPath:] + 241
      5   iCommander                          0x0000000101e6b43f _TFC10iCommander25CommentsHistoryController9tableViewfTCSo11UITableView12cellForRowAtV10Foundation9IndexPath_CSo15UITableViewCell + 303
      6   iCommander                          0x0000000101e6ba07 _TToFC10iCommander25CommentsHistoryController9tableViewfTCSo11UITableView12cellForRowAtV10Foundation9IndexPath_CSo15UITableViewCell + 87
      7   UIKit                               0x00000001042fdab2 -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] + 750
      8   UIKit                               0x00000001042fdcf8 -[UITableView _createPreparedCellForGlobalRow:willDisplay:] + 74
      9   UIKit                               0x00000001042d2639 -[UITableView _updateVisibleCellsNow:isRecursive:] + 2845
      10  UIKit                               0x0000000104306ccc -[UITableView _performWithCachedTraitCollection:] + 111
      11  UIKit                               0x00000001042ede7a -[UITableView layoutSubviews] + 233
      12  UIKit                               0x000000010425455b -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1268
      13  QuartzCore                          0x0000000102429904 -[CALayer layoutSublayers] + 146
      14  QuartzCore                          0x000000010241d526 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 370
      15  QuartzCore                          0x000000010241d3a0 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
      16  QuartzCore                          0x00000001023ace92 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 294
      17  QuartzCore                          0x00000001023d9130 _ZN2CA11Transaction6commitEv + 468
      18  QuartzCore                          0x00000001023d9b37 _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 115
      19  CoreFoundation                      0x000000010359c717 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION + 23
      20  CoreFoundation                      0x000000010359c687 __CFRunLoopDoObservers + 391
      21  CoreFoundation                      0x0000000103581720 __CFRunLoopRun + 1200
      22  CoreFoundation                      0x0000000103581016 CFRunLoopRunSpecific + 406
      23  GraphicsServices                    0x00000001091e1a24 GSEventRunModal + 62
      24  UIKit                               0x0000000104191134 UIApplicationMain + 159
      25  iCommander                          0x0000000101e13ea7 main + 55
      26  libdyld.dylib                       0x000000010743e65d start + 1
      27  ???                                 0x0000000000000001 0x0 + 1
  )
  libc++abi.dylib: terminating with uncaught exception of type NSException

Please help. Thanks in advance.

答: Set cell identifier to custom cell in xib file as:


问:
Seeing the result of class object in python
I just wrote this class in python to extract some features from a dataset :

```<code>class Features :

    def __init__ (self , data):
        self.data = data

    def Energy (self) :
        energy=float (sum(self.data**2))
        return (energy)

    def Power (self):
        power = float (sum(self.data**4))
        return power

    def NonlinearEnergy (self) :
        limit1=0
        NLE = 0
        while limit1 < len(self.data):
            NLE += float ((-self.data[limit1]*self.data[limit1-2] + self.data[limit1-1]**2 ))
            limit1+=1

        return NLE

    def CurveLength (self):
        limit2=0
        CL=0
        while limit2 < len(self.data):
            CL += float ((self.data[limit2] - self.data[limit2-1]))
            limit2+=1
</code>```

and when I try to see the result of a dataset's object, the result appears Like that :

<bound method Features.Energy of <__main__.Features object at 0x0000028952C105C0>>

My question is: how can I see the result numerically, or in other words, how can I see my actual result?

答:
This problem happens as a result of calling a method without brackets.

Take a look at the example:

```<code>obj = Features(data)
print (obj.Energy())
</code>```

So, first create a new object for your class and then call your method as obj.Energy(). This is because, whenever an object calls its method, the object itself is passed as the first argument. So, obj.Energy() translates into Features.Energy(obj)

Body:
I just wrote this class in python to extract some features from a dataset :

class Features :

    def __init__ (self , data):
        self.data = data

    def Energy (self) :
        energy=float (sum(self.data**2))
        return (energy)

    def Power (self):
        power = float (sum(self.data**4))
        return power

    def NonlinearEnergy (self) :
        limit1=0
        NLE = 0
        while limit1 < len(self.data):
            NLE += float ((-self.data[limit1]*self.data[limit1-2] + self.data[limit1-1]**2 ))
            limit1+=1

        return NLE

    def CurveLength (self):
        limit2=0
        CL=0
        while limit2 < len(self.data):
            CL += float ((self.data[limit2] - self.data[limit2-1]))
            limit2+=1

and when I try to see the result of a dataset's object, the result appears Like that :

<bound method Features.Energy of <__main__.Features object at 0x0000028952C105C0>>

My question is: how can I see the result numerically, or in other words, how can I see my actual result?

Body:
This problem happens as a result of calling a method without brackets.

Take a look at the example:

obj = Features(data)
print (obj.Energy())

So, first create a new object for your class and then call your method as obj.Energy(). This is because, whenever an object calls its method, the object itself is passed as the first argument. So, obj.Energy() translates into Features.Energy(obj)


问:
toggle pseudo class :active with css/jquery
i have a little css problem.
There is a div which is only display an image of an help mark. What i try is on clicking on this image the next div on the same level is display:inline-block. On a second click it is display:none again.

The display:inline-block on :active is working but it is not toggle.

There is JQuery:

```<code>(function($) {

// Execute after the page was fully
setTimeout( function(){
if ($('#jsonPayload').length) {
// scope to JSD
var banner = jQuery('<div class="helpmark">'
+ '<img class="emoticon" align="adsmiddle" src="@contextPath/plugins/cute/static/resource/SD-CGM-TT/help_16.gif" />'
+ ' @message'
+   '</div>');
banner.insertBefore('div.description');
}
}, 1)
})(jQuery);
</code>```

And the HTML around the Elements we are looking for

```<code><div class="helpmark">
    <img class="emoticon" src="http://*********/plugins/cute/static/resource/SD-CGM-TT/help_16.gif"> </div>
<div class="description">
    <p>Hier können Sie einen kurzen Betreff einfügen</p>
</div>
</code>```

by clicking on .helpmark .description is displayed

And the CSS i have

```<code>.helpmark {
    cursor: pointer;
    display: inline-block;
    margin-top: 5px;
}

.helpmark:active + .description {
    display: inline-block;
}

.description {
    display: none;
}
</code>```

I hope anybody can help me.

Best regards,
Stephan

答:
```<code>// code
(function($) {
// Execute after the page was fully
setTimeout( function(){
if ($('#jsonPayload').length) {
// scope to JSD
var banner = jQuery('<div class="helpmark">'
+ '<img class="emoticon" align="adsmiddle" src="@contextPath/plugins/cute/static/resource/SD-CGM-TT/help_16.gif" />'
+ ' @message'
+   '</div>');
banner.insertBefore('div.description');
$('.helpmark').click(function(){
  $(this).next('.description').toggle();
});
}
}, 1)
})(jQuery);
</code>```

That fix it for me

Body:
i have a little css problem.
There is a div which is only display an image of an help mark. What i try is on clicking on this image the next div on the same level is display:inline-block. On a second click it is display:none again.

The display:inline-block on :active is working but it is not toggle.

There is JQuery:

(function($) {

// Execute after the page was fully
setTimeout( function(){
if ($('#jsonPayload').length) {
// scope to JSD
var banner = jQuery('
'
+ ''
+ ' @message'
+   '
');
banner.insertBefore('div.description');
}
}, 1)
})(jQuery);

And the HTML around the Elements we are looking for

Hier können Sie einen kurzen Betreff einfügen

by clicking on .helpmark .description is displayed

And the CSS i have

.helpmark {
    cursor: pointer;
    display: inline-block;
    margin-top: 5px;
}

.helpmark:active + .description {
    display: inline-block;
}

.description {
    display: none;
}

I hope anybody can help me.

Best regards,
Stephan

Body:
// code
(function($) {
// Execute after the page was fully
setTimeout( function(){
if ($('#jsonPayload').length) {
// scope to JSD
var banner = jQuery('<div class="helpmark">'
+ '<img class="emoticon" align="adsmiddle" src="@contextPath/plugins/cute/static/resource/SD-CGM-TT/help_16.gif" />'
+ ' @message'
+   '</div>');
banner.insertBefore('div.description');
$('.helpmark').click(function(){
  $(this).next('.description').toggle();
});
}
}, 1)
})(jQuery);

That fix it for me


问:
HTML won't display 2 images
I want to display 2 images on the same row like this:

```<code>Image  Same Text  Image
</code>```

If I put one image it works, but if I put both of them I get 404.
I think I am doing something wrong in the code I don't have much experience with HTML and don't know what I am missing.
The files are in same folder.
Here is the code:

```<code><td colspan="8" >
<h1>
<img src="/home/apps/myapp/dynamic/img/myimage1.png" style="float:left; " alt="This is my mage" height="130" width="455">
<b>Same text</b>
<img src="/home/apps/myapp/dynamic/img/myimage2.png" style="float:right; vertical-align:middle;" alt="My second image" height="130" width="454"></h1>
</td>
</code>```

答:
There is an extra start tag in your code, which is giving the error.

The Problem:

```<code><<img src="/home/apps/myapp/dynamic/img/myimage2.png"
style="float:right; vertical-align:middle;" alt="My second image"
height="130" width="454"></h1>
</code>```

The Solution

```<code><img src="/home/apps/myapp/dynamic/img/myimage2.png"
style="float:right; vertical-align:middle;" alt="My second image"
height="130" width="454"></h1>
</code>```

Title: HTML won't display 2 images

Body:
I want to display 2 images on the same row like this:

Image  Same Text  Image

If I put one image it works, but if I put both of them I get 404.
I think I am doing something wrong in the code I don't have much experience with HTML and don't know what I am missing.
The files are in same folder.
Here is the code:

Same text

Body:
There is an extra start tag in your code, which is giving the error.

The Problem:

<<img src="/home/apps/myapp/dynamic/img/myimage2.png"
style="float:right; vertical-align:middle;" alt="My second image"
height="130" width="454"></h1>

The Solution

<img src="/home/apps/myapp/dynamic/img/myimage2.png"
style="float:right; vertical-align:middle;" alt="My second image"
height="130" width="454"></h1>


问:
get sim serial number in codename one using android native code
I want to get sim serial number in codename one using Android native code, following is my native implementation class, I have also added permission in build hint, code doesn't give any error but return null

```<code>    import com.codename1.impl.android.AndroidNativeUtil;
    import android.telephony.TelephonyManager;

    public class MyNativeImpl {

            public String simID() {
            TelephonyManager tMgr=(TelephonyManager) AndroidNativeUtil.getActivity().getSystemService("phone");
            String SIMSerialNumber=tMgr.getSimSerialNumber();
                 return SIMSerialNumber;
            }

             public boolean isSupported() {
                return true;
            }
    }
</code>```

I have added this code,

if(!AndroidNativeUtil.checkForPermission(Manifest.permission.READ_PHONE_STATE, "This should be the description shown to the user...")){ your code here }

but getting error like

error: package Manifest does not exist
                if(!AndroidNativeUtil.checkForPermission(Manifest.permission.READ_PHONE_STATE,
  "App requires the permission to work properly"))
                                                                 ^ Note: Some input files use or override a deprecated API. Note: Recompile
  with -Xlint:deprecation for details. Note: Some input files use
  unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked
  for details. 1 error

答:
I think sim serial Number and sim number is unique. You can try this for get sim serial number and get sim number and Don't forget to add permission in manifest file.

```<code>TelephonyManager telemamanger = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String getSimSerialNumber = telemamanger.getSimSerialNumber();
String getSimNumber = telemamanger.getLine1Number();
</code>```

And add below permission into your Androidmanifest.xml file.

```<code><uses-permission android:name="android.permission.READ_PHONE_STATE"/>
</code>```

Body:
I want to get sim serial number in codename one using Android native code, following is my native implementation class, I have also added permission in build hint, code doesn't give any error but return null

    import com.codename1.impl.android.AndroidNativeUtil;
    import android.telephony.TelephonyManager;

    public class MyNativeImpl {

            public String simID() {
            TelephonyManager tMgr=(TelephonyManager) AndroidNativeUtil.getActivity().getSystemService("phone");
            String SIMSerialNumber=tMgr.getSimSerialNumber();
                 return SIMSerialNumber;
            }

             public boolean isSupported() {
                return true;
            }
    }

I have added this code,

if(!AndroidNativeUtil.checkForPermission(Manifest.permission.READ_PHONE_STATE, "This should be the description shown to the user...")){ your code here }

but getting error like

error: package Manifest does not exist
                if(!AndroidNativeUtil.checkForPermission(Manifest.permission.READ_PHONE_STATE,
  "App requires the permission to work properly"))
                                                                 ^ Note: Some input files use or override a deprecated API. Note: Recompile
  with -Xlint:deprecation for details. Note: Some input files use
  unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked
  for details. 1 error

Body:
I think sim serial Number and sim number is unique. You can try this for get sim serial number and get sim number and Don't forget to add permission in manifest file.

TelephonyManager telemamanger = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String getSimSerialNumber = telemamanger.getSimSerialNumber();
String getSimNumber = telemamanger.getLine1Number();

And add below permission into your Androidmanifest.xml file.

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>


问:
Signature for C function that returns a multidimensional array
If I have:

```<code>char* buffer[8][8];
</code>```

And inside the same file I want to write a function that returns this buffer, what would the signature of that function look like?

In the case of

```<code>char* buffer[8];
</code>```

I could write

```<code>char** get_buff() {
    return buffer;
}
</code>```

But in this case I cannot deference into a multidimensional array. The C compiler will tell me that

```<code>char* buffer[8][8]
</code>```

has type

```<code>char * (*)[8]
</code>```

The problem is that the type it gives isn't valid syntax in a signature, so I have no idea what it expects to go there. What should the signature look like?

答:
A function cannot return an array. In most cases expressions of array type are automatically converted to the pointer of the first element of the array, which is probably exactly what you want (unless you want to return a copy of the buffer, which is a whole different story).

So the return statement in your function should look like this:

```<code> return buffer;
</code>```

The type char * (*)[8] is correct and you absolutely can write a signature with it. It is not too obvious at first but nothing horribly complicated, really:

```<code> char *(*get_buff())[8] {
     return buffer;
 }
</code>```

A rule of thumb is: if a type has a single top level (*) in it, you stick your function name and parameters right after the * to get a signature. Like this:

```<code>      char * ( *   )[8]
                 ^
                 |
             get_buffer()
</code>```

Same thing for multilevel pointers: the function name goes after the last * in (*****....***).

Of course you can use typedefs to simplify the matter a bit.

Body:
If I have:

char* buffer[8][8];

And inside the same file I want to write a function that returns this buffer, what would the signature of that function look like?

In the case of

char* buffer[8];

I could write

char** get_buff() {
    return buffer;
}

But in this case I cannot deference into a multidimensional array. The C compiler will tell me that

char* buffer[8][8]

has type

char * (*)[8]

The problem is that the type it gives isn't valid syntax in a signature, so I have no idea what it expects to go there. What should the signature look like?

Body:
A function cannot return an array. In most cases expressions of array type are automatically converted to the pointer of the first element of the array, which is probably exactly what you want (unless you want to return a copy of the buffer, which is a whole different story).

So the return statement in your function should look like this:

 return buffer;

The type char * (*)[8] is correct and you absolutely can write a signature with it. It is not too obvious at first but nothing horribly complicated, really:

 char *(*get_buff())[8] {
     return buffer;
 }

A rule of thumb is: if a type has a single top level (*) in it, you stick your function name and parameters right after the * to get a signature. Like this:

      char * ( *   )[8]
                 ^
                 |
             get_buffer()

Same thing for multilevel pointers: the function name goes after the last * in (*****....***).

Of course you can use typedefs to simplify the matter a bit.


问:
how to have date time column converted into date and displaying as 103 style
Hi i've a column the_date which is having sample data like
1900-01-01 00:00:00.000
1990-01-01 00:00:00.000
1990-01-02 00:00:00.000
1990-01-03 00:00:00.000
1990-01-04 00:00:00.000
1990-01-05 00:00:00.000
1990-01-06 00:00:00.000
1990-01-07 00:00:00.000

now i just want to select only date only and displaying it into 103 style and convert the column into Date format. i've tried this syntaxconvert(varchar,THE_DATE , 103) but then the column is not in Date format.
any help please.

答:
thanks for all your answer but for anyone who has my same query i got the solution from here
  solution </p>


问:
No return statement in sub-functions? [Javascript]
I'm in Chapter 3 - Functions of Eloquent Javascript.

Everything about the following code makes sense to me -- except one thing.

Why don't the sub-functions (for lack of a better term) have return statements?

```<code>var landscape = function() {
var result = "";
var flat = function(size) {
    for (var count = 0; count < size; count++)
      result += "_";
  };
  var mountain = function(size) {
    result += "/";
    for (var count = 0; count < size; count++)
      result += "'";
    result += "\\";
  };

  flat(3);
  mountain(4);
  flat(6);
  mountain(1);
  flat(1);
  return result;
};

console.log(landscape());
// → ___/''''\______/'\_
</code>```

Maybe I'm missing something fundamental about the purpose of the return statement, even after reading different definitions from different sources.

I've tried adding return statements to the sub-functions. I've found that it'll either terminate the sub-function pre-maturely, or produce the same result as if it was never there.

Thanks for reading.

答: Because your sub-functions affect your global landscape variable - result and in the end, function return result variable..This example shows you that you can change global variables into sub-functions..</p>

Body:
I'm in Chapter 3 - Functions of Eloquent Javascript.

Everything about the following code makes sense to me -- except one thing.

Why don't the sub-functions (for lack of a better term) have return statements?

var landscape = function() {
var result = "";
var flat = function(size) {
    for (var count = 0; count < size; count++)
      result += "_";
  };
  var mountain = function(size) {
    result += "/";
    for (var count = 0; count < size; count++)
      result += "'";
    result += "\\";
  };

  flat(3);
  mountain(4);
  flat(6);
  mountain(1);
  flat(1);
  return result;
};

console.log(landscape());
// → ___/''''\______/'\_

Maybe I'm missing something fundamental about the purpose of the return statement, even after reading different definitions from different sources.

I've tried adding return statements to the sub-functions. I've found that it'll either terminate the sub-function pre-maturely, or produce the same result as if it was never there.

Thanks for reading.


问:
How can I initialize a std::vector with a size parameter and have each object constructed independently?
I like creating vectors with a given size and value, for example like this:

```<code>std::vector<std::string> names(10);
</code>```

However, this a few times this led to unexpected results. For example in the following code each UniqueNumber turns out to have the same value:

```<code>#include <iostream>
#include <string>
#include <vector>

struct UniqueNumber
{
    UniqueNumber() : mValue(sInstanceCount++)
    {
    }

    inline unsigned int value() const
    {
        return mValue;
    }

private:
    static unsigned int sInstanceCount;
    unsigned int mValue;
};

int UniqueNumber::sInstanceCount(0);

int main()
{
    std::vector<UniqueNumber> numbers(10);
    for (size_t i = 0; i < numbers.size(); ++i)
    {
        std::cout << numbers[i].value() << " ";
    }
}
</code>```

Console output:

```<code>0 0 0 0 0 0 0 0 0 0
</code>```

It does make sense when looking at std::vector's constructor:

```<code>explicit vector(size_type __n,
                const value_type& __value = value_type(),
                const allocator_type& __a = allocator_type());
</code>```

Apparently the vector was initialized with copies of the same object.

Is there also a way to have each object default constructed?

答:
generate or generate_n are purpose-designed for just what you want to do.  Here's a complete example:

```<code>#include <algorithm>
#include <vector>
#include <iterator>
#include <iostream>
using namespace std;

class Foo
{
public:
    Foo() : n_(++water_) {};
    operator unsigned () const { return n_; }
private:
    static unsigned water_;
    unsigned n_;
};

Foo make_foo()
{
    return Foo();
}

unsigned Foo::water_ = 0;

int main()
{
    vector<Foo> v_foo;
    generate_n(back_inserter(v_foo), 10, &make_foo);
    copy(v_foo.begin(), v_foo.end(), ostream_iterator<unsigned>(cout, " "));
}
</code>```

Output: 1 2 3 4 5 6 7 8 9 10

Body:
I like creating vectors with a given size and value, for example like this:

std::vector<std::string> names(10);

However, this a few times this led to unexpected results. For example in the following code each UniqueNumber turns out to have the same value:

#include <iostream>
#include <string>
#include <vector>

struct UniqueNumber
{
    UniqueNumber() : mValue(sInstanceCount++)
    {
    }

    inline unsigned int value() const
    {
        return mValue;
    }

private:
    static unsigned int sInstanceCount;
    unsigned int mValue;
};

int UniqueNumber::sInstanceCount(0);

int main()
{
    std::vector<UniqueNumber> numbers(10);
    for (size_t i = 0; i < numbers.size(); ++i)
    {
        std::cout << numbers[i].value() << " ";
    }
}

Console output:

0 0 0 0 0 0 0 0 0 0

It does make sense when looking at std::vector's constructor:

explicit vector(size_type __n,
                const value_type& __value = value_type(),
                const allocator_type& __a = allocator_type());

Apparently the vector was initialized with copies of the same object.

Is there also a way to have each object default constructed?

Body:
generate or generate_n are purpose-designed for just what you want to do.  Here's a complete example:

#include <algorithm>
#include <vector>
#include <iterator>
#include <iostream>
using namespace std;

class Foo
{
public:
    Foo() : n_(++water_) {};
    operator unsigned () const { return n_; }
private:
    static unsigned water_;
    unsigned n_;
};

Foo make_foo()
{
    return Foo();
}

unsigned Foo::water_ = 0;

int main()
{
    vector<Foo> v_foo;
    generate_n(back_inserter(v_foo), 10, &make_foo);
    copy(v_foo.begin(), v_foo.end(), ostream_iterator<unsigned>(cout, " "));
}

Output: 1 2 3 4 5 6 7 8 9 10


问:
x-frame-options sameorigin while loading extrenal page in my webpage
we need to Load external web site and show it as a live website tile in our application where x-frame-options set to same origin for the external website.

We followed below approaches but nothing is working.

Please help us to know any framework/approach to achieve this.

Iframe :

Ajax Approach : Ajax HttpGet Call to the external web siteand get the html and render on our website.But replacing the image, css and html links from html is not working properly.

Web Request Approach : Server side HttpGet Call to the external web siteand get the html and render on our website.But replacing the image, css and html links from html is not working properly.

答:
Don't think that you can do this. The whole idea behind x-frame-options with the same-orign setting is to prevent what you are trying to do. It is to avoid clickjacking attacks.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options