问:
JavaFX application with an ImageIO call on a thread other than JavaFX Application Thread hangs on Mac OS X
Consider I have a sample JavaFX application which updates its UI with an image read from the application's JAR, and does so in a delayed manner (i.e. the image is painted after the UI is shown):

```<code>import javafx.application.Application;
import javafx.application.Platform;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

public final class SameThreadAsync extends Application {
    @Override
    public void start(final Stage primaryStage) {
        final ImageView imageView = new ImageView();
        imageView.setPreserveRatio(true);
        imageView.setSmooth(true);
        imageView.setFitWidth(300.0);
        imageView.setFitHeight(300.0);

        Platform.runLater(() -> {
            final BufferedImage image = getIcon();
            imageView.setImage(SwingFXUtils.toFXImage(image, null));
        });

        final Node label = new Label(null, imageView);

        final StackPane root = new StackPane();
        root.getChildren().add(label);
        primaryStage.setScene(new Scene(root, 300.0, 300.0));
        primaryStage.show();
    }

    private BufferedImage getIcon() {
        System.out.println("Reading an image from thread " + Thread.currentThread().getName());

        try (final InputStream in = new BufferedInputStream(getClass().getResourceAsStream("logo1.png"))) {
            return ImageIO.read(in);
        } catch (final IOException ioe) {
            ioe.printStackTrace();
            return new BufferedImage(0, 0, BufferedImage.TYPE_INT_ARGB);
        }
    }

    public static void main(final String ... args) {
        launch(args);
    }
}
</code>```

The above code works fine. Now, consider I want to load the image in a separate thread and process the result on the JavaFX Application Thread, so I'll rewrite the code as follows:

```<code>import javafx.application.Application;
import javafx.application.Platform;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public final class SeparateThreadAsync extends Application {
    private static final ExecutorService IO_EXECUTOR = Executors.newSingleThreadExecutor(r -> new Thread(r, "I/O Queue"));

    @Override
    public void start(final Stage primaryStage) {
        final ImageView imageView = new ImageView();
        imageView.setPreserveRatio(true);
        imageView.setSmooth(true);
        imageView.setFitWidth(300.0);
        imageView.setFitHeight(300.0);

        IO_EXECUTOR.submit(() -> {
            final BufferedImage image = getIcon();
            Platform.runLater(() -> imageView.setImage(SwingFXUtils.toFXImage(image, null)));
        });

        final Node label = new Label(null, imageView);

        final StackPane root = new StackPane();
        root.getChildren().add(label);
        primaryStage.setScene(new Scene(root, 300.0, 300.0));
        primaryStage.show();
    }

    private BufferedImage getIcon() {
        System.out.println("Reading an image from thread " + Thread.currentThread().getName());

        try (final InputStream in = new BufferedInputStream(getClass().getResourceAsStream("logo1.png"))) {
            return ImageIO.read(in);
        } catch (final IOException ioe) {
            ioe.printStackTrace();
            return new BufferedImage(0, 0, BufferedImage.TYPE_INT_ARGB);
        }
    }

    public static void main(final String ... args) {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            IO_EXECUTOR.shutdown();
            System.out.println("I/O Queue shut down.");
        }));

        launch(args);
    }
}
</code>```

The rewritten code works fine on both Linux and Windows but hangs on Mac OS X 10.14.5 (Mojave), Oracle JDK 1.8.0_192 and also JetBrains Runtime 1.8.0_202.

The partial thread dump is:

```<code>"I/O Queue" #19 prio=5 os_prio=31 tid=0x00007ffe3d85a000 nid=0x12007 runnable [0x0000700004822000]
   java.lang.Thread.State: RUNNABLE
    at java.lang.ClassLoader$NativeLibrary.load(Native Method)
    at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1941)
    - locked <0x000000076ab068a8> (a java.util.Vector)
    - locked <0x000000076ab06900> (a java.util.Vector)
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1824)
    at java.lang.Runtime.load0(Runtime.java:809)
    - locked <0x000000076ab1dea8> (a java.lang.Runtime)
    at java.lang.System.load(System.java:1086)
    at java.lang.ClassLoader$NativeLibrary.load(Native Method)
    at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1941)
    - locked <0x000000076ab068a8> (a java.util.Vector)
    - locked <0x000000076ab06900> (a java.util.Vector)
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1845)
    at java.lang.Runtime.loadLibrary0(Runtime.java:870)
    - locked <0x000000076ab1dea8> (a java.lang.Runtime)
    at java.lang.System.loadLibrary(System.java:1122)
    at java.awt.Toolkit$3.run(Toolkit.java:1636)
    at java.awt.Toolkit$3.run(Toolkit.java:1634)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.awt.Toolkit.loadLibraries(Toolkit.java:1633)
    at java.awt.Toolkit.<clinit>(Toolkit.java:1670)
    at sun.awt.AppContext$2.run(AppContext.java:277)
    at sun.awt.AppContext$2.run(AppContext.java:266)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.awt.AppContext.initMainAppContext(AppContext.java:266)
    at sun.awt.AppContext.access$400(AppContext.java:135)
    at sun.awt.AppContext$3.run(AppContext.java:321)
    - locked <0x000000076c238c00> (a sun.awt.AppContext$GetAppContextLock)
    at sun.awt.AppContext$3.run(AppContext.java:304)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.awt.AppContext.getAppContext(AppContext.java:303)
    at javax.imageio.spi.IIORegistry.getDefaultInstance(IIORegistry.java:154)
    at javax.imageio.ImageIO.<clinit>(ImageIO.java:66)
    at com.example.SeparateThreadAsync.getIcon(SeparateThreadAsync.java:49)
    at com.example.SeparateThreadAsync.lambda$start$2(SeparateThreadAsync.java:33)
    at com.example.SeparateThreadAsync$$Lambda$61/1820086024.run(Unknown Source)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"JavaFX Application Thread" #15 prio=5 os_prio=31 tid=0x00007ffe3b0e4000 nid=0x307 waiting for monitor entry [0x00007ffee75f1000]
   java.lang.Thread.State: BLOCKED (on object monitor)
    at java.lang.Runtime.load0(Runtime.java:801)
    - waiting to lock <0x000000076ab1dea8> (a java.lang.Runtime)
    at java.lang.System.load(System.java:1086)
    at com.sun.glass.utils.NativeLibLoader.loadLibraryFullPath(NativeLibLoader.java:201)
    at com.sun.glass.utils.NativeLibLoader.loadLibraryInternal(NativeLibLoader.java:94)
    at com.sun.glass.utils.NativeLibLoader.loadLibrary(NativeLibLoader.java:39)
    - locked <0x000000076b4185c0> (a java.lang.Class for com.sun.glass.utils.NativeLibLoader)
    at com.sun.javafx.font.PrismFontFactory.lambda$static$244(PrismFontFactory.java:100)
    at com.sun.javafx.font.PrismFontFactory$$Lambda$70/1988937384.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.font.PrismFontFactory.<clinit>(PrismFontFactory.java:98)
    at com.sun.javafx.text.PrismTextLayout.<clinit>(PrismTextLayout.java:67)
    at com.sun.javafx.text.PrismTextLayoutFactory.<clinit>(PrismTextLayoutFactory.java:33)
    at com.sun.javafx.tk.quantum.QuantumToolkit.getTextLayoutFactory(QuantumToolkit.java:1086)
    at com.sun.javafx.scene.control.skin.Utils.<clinit>(Utils.java:90)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at com.sun.javafx.css.StyleManager.getURL(StyleManager.java:863)
    at com.sun.javafx.css.StyleManager.loadStylesheetUnPrivileged(StyleManager.java:1075)
    - locked <0x000000076c3bc948> (a java.lang.Object)
    at com.sun.javafx.css.StyleManager.loadStylesheet(StyleManager.java:935)
    at com.sun.javafx.css.StyleManager._setDefaultUserAgentStylesheet(StyleManager.java:1395)
    - locked <0x000000076c3bc948> (a java.lang.Object)
    at com.sun.javafx.css.StyleManager.setUserAgentStylesheets(StyleManager.java:1227)
    - locked <0x000000076c3bc948> (a java.lang.Object)
    at com.sun.javafx.application.PlatformImpl.lambda$_setPlatformUserAgentStylesheet$181(PlatformImpl.java:698)
    at com.sun.javafx.application.PlatformImpl$$Lambda$65/566730701.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl._setPlatformUserAgentStylesheet(PlatformImpl.java:697)
    at com.sun.javafx.application.PlatformImpl.setPlatformUserAgentStylesheet(PlatformImpl.java:548)
    at com.sun.javafx.application.PlatformImpl.setDefaultPlatformUserAgentStylesheet(PlatformImpl.java:512)
    at javafx.scene.control.Control.<clinit>(Control.java:87)
    at com.example.SeparateThreadAsync.start(SeparateThreadAsync.java:37)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$161(LauncherImpl.java:863)
    at com.sun.javafx.application.LauncherImpl$$Lambda$56/1315653396.run(Unknown Source)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$174(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl$$Lambda$47/1212899836.run(Unknown Source)
    at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295)
    at com.sun.javafx.application.PlatformImpl$$Lambda$49/1963951195.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294)
    at com.sun.javafx.application.PlatformImpl$$Lambda$48/1289696681.run(Unknown Source)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
</code>```

so it seems like some sort of a race condition. Interestingly, a similar JFC/Swing application doesn't hang at all.

I first encountered this behaviour while playing with coroutines in Kotlin. For example, this code doesn't hang while this one does.

Questions:

Can anyone explain the above behaviour? Is there any chance I'm missing something rather than seeing a bug in the JDK?

How can I further diagnose the problem?

答: The above behaviour seems to be a bug in the Mac OS X implementation of Oracle JDK -- the problem shows up only with Java 1.8.0, I was unable to reproduce it against either Java 9.0.4 or 10.0.2.

Body:
Consider I have a sample JavaFX application which updates its UI with an image read from the application's JAR, and does so in a delayed manner (i.e. the image is painted after the UI is shown):

import javafx.application.Application;
import javafx.application.Platform;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

public final class SameThreadAsync extends Application {
    @Override
    public void start(final Stage primaryStage) {
        final ImageView imageView = new ImageView();
        imageView.setPreserveRatio(true);
        imageView.setSmooth(true);
        imageView.setFitWidth(300.0);
        imageView.setFitHeight(300.0);

        Platform.runLater(() -> {
            final BufferedImage image = getIcon();
            imageView.setImage(SwingFXUtils.toFXImage(image, null));
        });

        final Node label = new Label(null, imageView);

        final StackPane root = new StackPane();
        root.getChildren().add(label);
        primaryStage.setScene(new Scene(root, 300.0, 300.0));
        primaryStage.show();
    }

    private BufferedImage getIcon() {
        System.out.println("Reading an image from thread " + Thread.currentThread().getName());

        try (final InputStream in = new BufferedInputStream(getClass().getResourceAsStream("logo1.png"))) {
            return ImageIO.read(in);
        } catch (final IOException ioe) {
            ioe.printStackTrace();
            return new BufferedImage(0, 0, BufferedImage.TYPE_INT_ARGB);
        }
    }

    public static void main(final String ... args) {
        launch(args);
    }
}

The above code works fine. Now, consider I want to load the image in a separate thread and process the result on the JavaFX Application Thread, so I'll rewrite the code as follows:

import javafx.application.Application;
import javafx.application.Platform;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public final class SeparateThreadAsync extends Application {
    private static final ExecutorService IO_EXECUTOR = Executors.newSingleThreadExecutor(r -> new Thread(r, "I/O Queue"));

    @Override
    public void start(final Stage primaryStage) {
        final ImageView imageView = new ImageView();
        imageView.setPreserveRatio(true);
        imageView.setSmooth(true);
        imageView.setFitWidth(300.0);
        imageView.setFitHeight(300.0);

        IO_EXECUTOR.submit(() -> {
            final BufferedImage image = getIcon();
            Platform.runLater(() -> imageView.setImage(SwingFXUtils.toFXImage(image, null)));
        });

        final Node label = new Label(null, imageView);

        final StackPane root = new StackPane();
        root.getChildren().add(label);
        primaryStage.setScene(new Scene(root, 300.0, 300.0));
        primaryStage.show();
    }

    private BufferedImage getIcon() {
        System.out.println("Reading an image from thread " + Thread.currentThread().getName());

        try (final InputStream in = new BufferedInputStream(getClass().getResourceAsStream("logo1.png"))) {
            return ImageIO.read(in);
        } catch (final IOException ioe) {
            ioe.printStackTrace();
            return new BufferedImage(0, 0, BufferedImage.TYPE_INT_ARGB);
        }
    }

    public static void main(final String ... args) {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            IO_EXECUTOR.shutdown();
            System.out.println("I/O Queue shut down.");
        }));

        launch(args);
    }
}

The rewritten code works fine on both Linux and Windows but hangs on Mac OS X 10.14.5 (Mojave), Oracle JDK 1.8.0_192 and also JetBrains Runtime 1.8.0_202.

The partial thread dump is:

"I/O Queue" #19 prio=5 os_prio=31 tid=0x00007ffe3d85a000 nid=0x12007 runnable [0x0000700004822000]
   java.lang.Thread.State: RUNNABLE
    at java.lang.ClassLoader$NativeLibrary.load(Native Method)
    at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1941)
    - locked <0x000000076ab068a8> (a java.util.Vector)
    - locked <0x000000076ab06900> (a java.util.Vector)
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1824)
    at java.lang.Runtime.load0(Runtime.java:809)
    - locked <0x000000076ab1dea8> (a java.lang.Runtime)
    at java.lang.System.load(System.java:1086)
    at java.lang.ClassLoader$NativeLibrary.load(Native Method)
    at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1941)
    - locked <0x000000076ab068a8> (a java.util.Vector)
    - locked <0x000000076ab06900> (a java.util.Vector)
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1845)
    at java.lang.Runtime.loadLibrary0(Runtime.java:870)
    - locked <0x000000076ab1dea8> (a java.lang.Runtime)
    at java.lang.System.loadLibrary(System.java:1122)
    at java.awt.Toolkit$3.run(Toolkit.java:1636)
    at java.awt.Toolkit$3.run(Toolkit.java:1634)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.awt.Toolkit.loadLibraries(Toolkit.java:1633)
    at java.awt.Toolkit.<clinit>(Toolkit.java:1670)
    at sun.awt.AppContext$2.run(AppContext.java:277)
    at sun.awt.AppContext$2.run(AppContext.java:266)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.awt.AppContext.initMainAppContext(AppContext.java:266)
    at sun.awt.AppContext.access$400(AppContext.java:135)
    at sun.awt.AppContext$3.run(AppContext.java:321)
    - locked <0x000000076c238c00> (a sun.awt.AppContext$GetAppContextLock)
    at sun.awt.AppContext$3.run(AppContext.java:304)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.awt.AppContext.getAppContext(AppContext.java:303)
    at javax.imageio.spi.IIORegistry.getDefaultInstance(IIORegistry.java:154)
    at javax.imageio.ImageIO.<clinit>(ImageIO.java:66)
    at com.example.SeparateThreadAsync.getIcon(SeparateThreadAsync.java:49)
    at com.example.SeparateThreadAsync.lambda$start$2(SeparateThreadAsync.java:33)
    at com.example.SeparateThreadAsync$$Lambda$61/1820086024.run(Unknown Source)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"JavaFX Application Thread" #15 prio=5 os_prio=31 tid=0x00007ffe3b0e4000 nid=0x307 waiting for monitor entry [0x00007ffee75f1000]
   java.lang.Thread.State: BLOCKED (on object monitor)
    at java.lang.Runtime.load0(Runtime.java:801)
    - waiting to lock <0x000000076ab1dea8> (a java.lang.Runtime)
    at java.lang.System.load(System.java:1086)
    at com.sun.glass.utils.NativeLibLoader.loadLibraryFullPath(NativeLibLoader.java:201)
    at com.sun.glass.utils.NativeLibLoader.loadLibraryInternal(NativeLibLoader.java:94)
    at com.sun.glass.utils.NativeLibLoader.loadLibrary(NativeLibLoader.java:39)
    - locked <0x000000076b4185c0> (a java.lang.Class for com.sun.glass.utils.NativeLibLoader)
    at com.sun.javafx.font.PrismFontFactory.lambda$static$244(PrismFontFactory.java:100)
    at com.sun.javafx.font.PrismFontFactory$$Lambda$70/1988937384.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.font.PrismFontFactory.<clinit>(PrismFontFactory.java:98)
    at com.sun.javafx.text.PrismTextLayout.<clinit>(PrismTextLayout.java:67)
    at com.sun.javafx.text.PrismTextLayoutFactory.<clinit>(PrismTextLayoutFactory.java:33)
    at com.sun.javafx.tk.quantum.QuantumToolkit.getTextLayoutFactory(QuantumToolkit.java:1086)
    at com.sun.javafx.scene.control.skin.Utils.<clinit>(Utils.java:90)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at com.sun.javafx.css.StyleManager.getURL(StyleManager.java:863)
    at com.sun.javafx.css.StyleManager.loadStylesheetUnPrivileged(StyleManager.java:1075)
    - locked <0x000000076c3bc948> (a java.lang.Object)
    at com.sun.javafx.css.StyleManager.loadStylesheet(StyleManager.java:935)
    at com.sun.javafx.css.StyleManager._setDefaultUserAgentStylesheet(StyleManager.java:1395)
    - locked <0x000000076c3bc948> (a java.lang.Object)
    at com.sun.javafx.css.StyleManager.setUserAgentStylesheets(StyleManager.java:1227)
    - locked <0x000000076c3bc948> (a java.lang.Object)
    at com.sun.javafx.application.PlatformImpl.lambda$_setPlatformUserAgentStylesheet$181(PlatformImpl.java:698)
    at com.sun.javafx.application.PlatformImpl$$Lambda$65/566730701.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl._setPlatformUserAgentStylesheet(PlatformImpl.java:697)
    at com.sun.javafx.application.PlatformImpl.setPlatformUserAgentStylesheet(PlatformImpl.java:548)
    at com.sun.javafx.application.PlatformImpl.setDefaultPlatformUserAgentStylesheet(PlatformImpl.java:512)
    at javafx.scene.control.Control.<clinit>(Control.java:87)
    at com.example.SeparateThreadAsync.start(SeparateThreadAsync.java:37)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$161(LauncherImpl.java:863)
    at com.sun.javafx.application.LauncherImpl$$Lambda$56/1315653396.run(Unknown Source)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$174(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl$$Lambda$47/1212899836.run(Unknown Source)
    at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295)
    at com.sun.javafx.application.PlatformImpl$$Lambda$49/1963951195.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294)
    at com.sun.javafx.application.PlatformImpl$$Lambda$48/1289696681.run(Unknown Source)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)

so it seems like some sort of a race condition. Interestingly, a similar JFC/Swing application doesn't hang at all.

I first encountered this behaviour while playing with coroutines in Kotlin. For example, this code doesn't hang while this one does.

Questions:

Can anyone explain the above behaviour? Is there any chance I'm missing something rather than seeing a bug in the JDK?

How can I further diagnose the problem?


来源: stackexchange

问:
Is there a way to initialize a variable in a controller, and use it in FXML?
So, I was making a menu in FXML and I was using a Group so I had to set a prefWidth otherwise it'd look weird. To do that, I wanted to initialize a variable with the screen width in the controller, and then use the width variable while setting up the menu in FXML. But I just couldn't find a way to do that.

Generalizing this problem, I want to initialize a variable in a controller and then use it in FXML like this:

[Controller]

package sample;

import javafx.fxml.Initializable;
import java.net.URL;
import java.util.ResourceBundle;

public class Controller implements Initializable {
    @Override
    public void initialize (URL url, ResourceBundle resourceBundle) {
        String text = "test";
    }
}
```

<p>[FXML]</p>

```<?import javafx.scene.control.Label?>
<?import javafx.scene.BorderPane?>

<BorderPane>

</BorderPane>
```

I know, there are other ways to do it (like id-ing it and setting the text in the controller) but I just wanna see if it is possible to do it this way.

答:
Instead of a variable use a property. Place it at the class level.

```<code>public class Controller implements Initializable {

    private String text; // or use binding property

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        text = "hello";
    }
}
</code>```

FXML

```<code><BorderPane fx:controller="sample.Controller"
            xmlns:fx="http://javafx.com/fxml">

    <center>
        <Label text="${controller.text}"/>

    </center>
</BorderPane>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
So, I was making a menu in FXML and I was using a Group so I had to set a prefWidth otherwise it'd look weird. To do that, I wanted to initialize a variable with the screen width in the controller, and then use the width variable while setting up the menu in FXML. But I just couldn't find a way to do that.

Generalizing this problem, I want to initialize a variable in a controller and then use it in FXML like this:

[Controller]

package sample;

import javafx.fxml.Initializable;
import java.net.URL;
import java.util.ResourceBundle;

public class Controller implements Initializable {
    @Override
    public void initialize (URL url, ResourceBundle resourceBundle) {
        String text = "test";
    }
}

[FXML]

<?import javafx.scene.control.Label?>
<?import javafx.scene.BorderPane?>

<BorderPane>

</BorderPane>

I know, there are other ways to do it (like id-ing it and setting the text in the controller) but I just wanna see if it is possible to do it this way.

Body:
Instead of a variable use a property. Place it at the class level.

public class Controller implements Initializable {

    private String text; // or use binding property

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        text = "hello";
    }
}

FXML

<BorderPane fx:controller="sample.Controller"
            xmlns:fx="http://javafx.com/fxml">

    <center>
        <Label text="${controller.text}"/>

    </center>
</BorderPane>


问:
Divide subplots onto multiple screens
I want to plot some data from a csv file using dataframe.

My code currently displays 266=14*19 separate subplots. Currently, it is coded to display all 266 subplots on one screen and each is small and difficult to read.

I tried to use a 1x1 plot

```<code>#fig, cx=plt.subplots(1,1, sharex=False, sharey=False, figsize=(18,12))
</code>```

Main code:

```<code>fig, cx=plt.subplots(14,19, sharex=False, sharey=False, figsize=(18,12))
#fig, cx=plt.subplots(1,1, sharex=False, sharey=False, figsize=(18,12))

plt.subplots_adjust(hspace=0.5)

cx = cx.ravel()

for i in range(0,len(Bond)):
    cx[i].plot(VelLog[Bond[i]], color='b')
    cx[i].set_xlabel('Time (ms)')
    cx[i].set_ylabel('Velocity (m/s)')
    cx[i].set_ylim(-250,150)
    cx[i].set_title(Bond[i])

plt.savefig('Velocity.png', dpi=120)
plt.show()
##################################
Error message when I un-comment Line 1
cx[i].plot(VelLog[Bond[i]], color='b')
IndexError: index 209 is out of bounds for axis 0 with size 209
</code>```

How can I only display a few subplots on a screen at a time to increase readability?

Like 5x5 + 5x5 + 5x5 + 5x5 + 5x5,+ 5x5 + 5x5 + 5x5 + 5x5 + 5x5 + 4x4 = 266

11 different screens.

Is there a way to add a chart filter as an alternative?

Here is my updated code with your suggestions. It now creates 11 figures. I was able to plot all 266 graphs but each graph looks the same

```<code>Nrows, Ncols = 14, 19
Nplots = Nrows*Ncols

nrows, ncols = 5, 5
naxes = nrows*ncols

nfigures = Nplots//naxes

count = 0
figures = []

for fignum in range(nfigures+1):
    fig, axes = plt.subplots(nrows, ncols,  sharex=False, sharey=False, figsize=(18,12))
    plt.subplots_adjust(hspace=0.5)
    #axes = axes.ravel()
    figures.append(fig)
    axes = axes.flat
    for ax in axes:
        #print(count)
        if count<Nplots:
            for i in range(0,len(Bond)):
                cvs_row, cvs_col = divmod(count, Ncols)
                cvs_row, cvs_col = cvs_row+1, cvs_col+1
                ax.plot(VelLog[Bond[i]], color='b', label='%d,%d'%(cvs_row, cvs_col))
                ax.set_xlabel('Time (ms)')
                ax.set_ylabel('Velocity (m/s)')
                ax.set_ylim(-250,150)
                ax.set_title(Bond[i])
            count = count+1

plt.savefig('Velocity.png', dpi=120)
plt.show()

</code>```

Here is the result for one figure
enter image description here

答:
Here I plot the same function 14*19 times, but you can get an idea

We have two problems, keeping track of what we are plotting and
delaying the actual plotting until we are finished with all of them.

The first issue is solved here using a global counter and the divmod
builtin, the second storing all the figures in a list and calling
plt.show() only at the very end of the plotting phase.

To show what I mean with "keeping track" I have added a label and a
legend to each individual subplot.

To keep things reasonable I don't check if the last figure is empty
and also I don't check is some subplots of the last figures are empty,
but remember that you can remove some subplots from a figure if you
want a clean last figure.

```<code>import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, np.pi, 31)
y = np.sin(x)

Nrows, Ncols = 14, 19
Nplots = Nrows*Ncols

nrows, ncols = 5, 5
naxes = nrows*ncols

nfigures = Nplots//naxes

count = 0
figures = []

for fignum in range(nfigures+1):
    fig, axes = plt.subplots(nrows, ncols)
    figures.append(fig)
    axes = axes.flat
    for ax in axes:
        print(count)
        if count<Nplots:
            cvs_row, cvs_col = divmod(count, Ncols)
            cvs_row, cvs_col = cvs_row+1, cvs_col+1
            ax.plot(x, y, label='%d,%d'%(cvs_row, cvs_col))
            ax.legend()
            count = count+1

plt.show()
</code>```

Here I show just the last figure, to show what I mean with "empty
subplots"...

Title: Divide subplots onto multiple screens

Body:
I want to plot some data from a csv file using dataframe.

My code currently displays 266=14*19 separate subplots. Currently, it is coded to display all 266 subplots on one screen and each is small and difficult to read.

I tried to use a 1x1 plot

#fig, cx=plt.subplots(1,1, sharex=False, sharey=False, figsize=(18,12))

Main code:

fig, cx=plt.subplots(14,19, sharex=False, sharey=False, figsize=(18,12))
#fig, cx=plt.subplots(1,1, sharex=False, sharey=False, figsize=(18,12))

plt.subplots_adjust(hspace=0.5)

cx = cx.ravel()

for i in range(0,len(Bond)):
    cx[i].plot(VelLog[Bond[i]], color='b')
    cx[i].set_xlabel('Time (ms)')
    cx[i].set_ylabel('Velocity (m/s)')
    cx[i].set_ylim(-250,150)
    cx[i].set_title(Bond[i])

plt.savefig('Velocity.png', dpi=120)
plt.show()
##################################
Error message when I un-comment Line 1
cx[i].plot(VelLog[Bond[i]], color='b')
IndexError: index 209 is out of bounds for axis 0 with size 209

How can I only display a few subplots on a screen at a time to increase readability?

Like 5x5 + 5x5 + 5x5 + 5x5 + 5x5,+ 5x5 + 5x5 + 5x5 + 5x5 + 5x5 + 4x4 = 266

11 different screens.

Is there a way to add a chart filter as an alternative?

Here is my updated code with your suggestions. It now creates 11 figures. I was able to plot all 266 graphs but each graph looks the same

Nrows, Ncols = 14, 19
Nplots = Nrows*Ncols

nrows, ncols = 5, 5
naxes = nrows*ncols

nfigures = Nplots//naxes

count = 0
figures = []

for fignum in range(nfigures+1):
    fig, axes = plt.subplots(nrows, ncols,  sharex=False, sharey=False, figsize=(18,12))
    plt.subplots_adjust(hspace=0.5)
    #axes = axes.ravel()
    figures.append(fig)
    axes = axes.flat
    for ax in axes:
        #print(count)
        if count<Nplots:
            for i in range(0,len(Bond)):
                cvs_row, cvs_col = divmod(count, Ncols)
                cvs_row, cvs_col = cvs_row+1, cvs_col+1
                ax.plot(VelLog[Bond[i]], color='b', label='%d,%d'%(cvs_row, cvs_col))
                ax.set_xlabel('Time (ms)')
                ax.set_ylabel('Velocity (m/s)')
                ax.set_ylim(-250,150)
                ax.set_title(Bond[i])
            count = count+1

plt.savefig('Velocity.png', dpi=120)
plt.show()

Here is the result for one figure
enter image description here

Body:
Here I plot the same function 14*19 times, but you can get an idea

We have two problems, keeping track of what we are plotting and
delaying the actual plotting until we are finished with all of them.

The first issue is solved here using a global counter and the divmod
builtin, the second storing all the figures in a list and calling
plt.show() only at the very end of the plotting phase.

To show what I mean with "keeping track" I have added a label and a
legend to each individual subplot.

To keep things reasonable I don't check if the last figure is empty
and also I don't check is some subplots of the last figures are empty,
but remember that you can remove some subplots from a figure if you
want a clean last figure.

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, np.pi, 31)
y = np.sin(x)

Nrows, Ncols = 14, 19
Nplots = Nrows*Ncols

nrows, ncols = 5, 5
naxes = nrows*ncols

nfigures = Nplots//naxes

count = 0
figures = []

for fignum in range(nfigures+1):
    fig, axes = plt.subplots(nrows, ncols)
    figures.append(fig)
    axes = axes.flat
    for ax in axes:
        print(count)
        if count<Nplots:
            cvs_row, cvs_col = divmod(count, Ncols)
            cvs_row, cvs_col = cvs_row+1, cvs_col+1
            ax.plot(x, y, label='%d,%d'%(cvs_row, cvs_col))
            ax.legend()
            count = count+1

plt.show()

Here I show just the last figure, to show what I mean with "empty
subplots"...


问:
How to remove invalid UTF-8 characters from a JavaScript string?
I'd like to remove all invalid UTF-8 characters from a string in JavaScript. I've tried with this JavaScript:

strTest = strTest.replace(/([\x00-\x7F]|[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3})|./g, "$1");

It seems that the UTF-8 validation regex described here (link removed) is more complete and I adapted it in the same way like:

strTest = strTest.replace(/([\x09\x0A\x0D\x20-\x7E]|[\xC2-\xDF][\x80-\xBF]|\xE0[\xA0-\xBF][\x80-\xBF]|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}|\xED[\x80-\x9F][\x80-\xBF]|\xF0[\x90-\xBF][\x80-\xBF]{2}|[\xF1-\xF3][\x80-\xBF]{3}|\xF4[\x80-\x8F][\x80-\xBF]{2})|./g, "$1");

Both of these pieces of code seem to be allowing valid UTF-8 through, but aren't filtering out hardly any of the bad UTF-8 characters from my test data: UTF-8 decoder capability and stress test.  Either the bad characters come through unchanged or seem to have some of their bytes removed creating a new, invalid character.

I'm not very familiar with the UTF-8 standard or with multibyte in JavaScript so I'm not sure if I'm failing to represent proper UTF-8 in the regex or if I'm applying that regex improperly in JavaScript.

Edit: added global flag to my regex per Tomalak's comment - however this still isn't working for me.  I'm abandoning doing this on the client side per bobince's comment.

答:
I have put together some solutions proposed above to be error-safe</p>

```<code>       var removeNonUtf8 = (characters) => {
            try {
                // ignore invalid char ranges
                var bytelike = unescape(encodeURIComponent(characters));
                characters = decodeURIComponent(escape(bytelike));
            } catch (error) { }
            // remove �
            characters = characters.replace(/\uFFFD/g, '');
            return characters;
        },
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have put together some solutions proposed above to be error-safe

       var removeNonUtf8 = (characters) => {
            try {
                // ignore invalid char ranges
                var bytelike = unescape(encodeURIComponent(characters));
                characters = decodeURIComponent(escape(bytelike));
            } catch (error) { }
            // remove �
            characters = characters.replace(/\uFFFD/g, '');
            return characters;
        },


问:
Name depends on the number of characters
How to write a conditional statement acting as follows:

If "% name%" has 1 character, name: 00 "% name%"

If "% name%" has 2, name: 0 "% name%"

If "% name%" has 3 , name: "% name%"

```<code>    action.SetDynamicParameter("FileName", ((((((("%version%" + "_")  _

                + String.Join(", ", array2))  _

                + "_")  _

                + "%name%")  _

                + ".jpg"))
</code>```

I will be grateful for your help.

答:
It looks to me like your just trying to pad a number as a string with leading zeros to a length of 3.  Is that correct?  If so, try this:

```<code>Private Function FormatMyName(ByVal Name As String) As String
    Return Name.PadLeft(3, "0")
End Function
</code>```

If created it as a function so it's easier for you to add the additional formatting you need (e.g. adding a .jpg extension)

Body:
How to write a conditional statement acting as follows:

If "% name%" has 1 character, name: 00 "% name%"

If "% name%" has 2, name: 0 "% name%"

If "% name%" has 3 , name: "% name%"

    action.SetDynamicParameter("FileName", ((((((("%version%" + "_")  _

                + String.Join(", ", array2))  _

                + "_")  _

                + "%name%")  _

                + ".jpg"))

I will be grateful for your help.

Body:
It looks to me like your just trying to pad a number as a string with leading zeros to a length of 3.  Is that correct?  If so, try this:

Private Function FormatMyName(ByVal Name As String) As String
    Return Name.PadLeft(3, "0")
End Function

If created it as a function so it's easier for you to add the additional formatting you need (e.g. adding a .jpg extension)


问:
Why first line in pom.xml in spring-boot Application showing error... <?xml version="1.0" encoding="UTF-8"?>
```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
    </parent>
    <groupId>com.app</groupId>
    <artifactId>Demo</artifactId>
    <version>1.0</version>
    <name>Demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

答:
This happening with 2.1.5.RELEASE. Add the following entry to your pom to fix that issue.

```<code><properties>
    <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
</properties>
</code>```

Why does change from Spring boot version 2.1.4 to 2.1.5 gives unknown configuration Maven error?

Body:
This happening with 2.1.5.RELEASE. Add the following entry to your pom to fix that issue.

<properties>
    <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
</properties>

Why does change from Spring boot version 2.1.4 to 2.1.5 gives unknown configuration Maven error?


问:
Accessing google cloud storage bucket from cloud functions throws 500 error
I'm trying to access google cloud storage bucket from cloud functions (python) instance and it's throwing mystic 500 error.

I have given the service account editor role too. It didn't make any change.

I also checked if any of the quota is going off limit. The limits were not even close.

Please, anyone can help me find cause of this error?

here is the code

    from google.cloud import storage
    import os
    import base64

    storage_client = storage.Client()

    def init_analysis(event, context):
        print("event", event)
        pubsub_message = base64.b64decode(event['data']).decode('utf-8')

        print(pubsub_message)
        bucket_name = 'my-bucket'
        bucket = storage_client.get_bucket(bucket_name)
        blobs = bucket.list_blobs()
        for blob in blobs:
            print(blob.name)

```

<p>Error: </p>

```    Traceback (most recent call last): File "/env/local/lib/python3.7/site-packages/google/auth/compute_engine/credentials.py", line 99, in refresh service_account=self._service_account_email) File "/env/local/lib/python3.7/site-packages/google/auth/compute_engine/_metadata.py", line 208, in get_service_account_token 'instance/service-accounts/{0}/token'.format(service_account)) File "/env/local/lib/python3.7/site-packages/google/auth/compute_engine/_metadata.py", line 140, in get url, response.status, response.data), response) google.auth.exceptions.TransportError: ("Failed to retrieve http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/my-project@appspot.gserviceaccount.com/token from the Google Compute Enginemetadata service. Status: 500 Response:\nb'Could not fetch URI /computeMetadata/v1/instance/service-accounts/my-project@appspot.gserviceaccount.com/token\\n'", <google.auth.transport.requests._Response object at 0x2b0ef9edf438>) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py", line 383, in run_background_function _function_handler.invoke_user_function(event_object) File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py", line 217, in invoke_user_function return call_user_function(request_or_event) File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py", line 214, in call_user_function event_context.Context(**request_or_event.context)) File "/user_code/main.py", line 21, in init_analysis bucket = storage_client.get_bucket(bucket_name) File "/env/local/lib/python3.7/site-packages/google/cloud/storage/client.py", line 227, in get_bucket bucket.reload(client=self) File "/env/local/lib/python3.7/site-packages/google/cloud/storage/_helpers.py", line 130, in reload _target_object=self, File "/env/local/lib/python3.7/site-packages/google/cloud/_http.py", line 315, in api_request target_object=_target_object, File "/env/local/lib/python3.7/site-packages/google/cloud/_http.py", line 192, in _make_request return self._do_request(method, url, headers, data, target_object) File "/env/local/lib/python3.7/site-packages/google/cloud/_http.py", line 221, in _do_request return self.http.request(url=url, method=method, headers=headers, data=data) File "/env/local/lib/python3.7/site-packages/google/auth/transport/requests.py", line 205, in request self._auth_request, method, url, request_headers) File "/env/local/lib/python3.7/site-packages/google/auth/credentials.py", line 122, in before_request self.refresh(request) File "/env/local/lib/python3.7/site-packages/google/auth/compute_engine/credentials.py", line 102, in refresh six.raise_from(new_exc, caught_exc) File "<string>", line 3, in raise_from google.auth.exceptions.RefreshError: ("Failed to retrieve http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/my-project@appspot.gserviceaccount.com/token from the Google Compute Enginemetadata service. Status: 500 Response:\nb'Could not fetch URI /computeMetadata/v1/instance/service-accounts/my-project@appspot.gserviceaccount.com/token\\n'", <google.auth.transport.requests._Response object at 0x2b0ef9edf438>)
google.auth.exceptions.TransportError: ("Failed to retrieve http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/my-project@appspot.gserviceaccount.com/token from the Google Compute Enginemetadata service. Status: 500 Response:\nb'Could not fetch URI /computeMetadata/v1/instance/service-accounts/my-project@appspot.gserviceaccount.com/token\\n'"
```

答:
The error you are getting it's because your Cloud Functions service account doesn't have the cloudfunctions.serviceAgent role. As you can see on the documentation:

Authenticating as the runtime service account from inside your function may fail if you change the Cloud Functions service account's permissions.

However, I found that sometimes you can not add this role as it doesn't show up as an option. I have reported this issue to the Google Cloud Functions engineering team and they are working to solve it.

Nevertheless, you can add the role again using this gcloud command:

```<code>gcloud projects add-iam-policy-binding <project_name> --role=roles/cloudfunctions.serviceAgent --member=serviceAccount:service-<project_number>@gcf-admin-robot.iam.gserviceaccount.com
</code>```

Body:
I'm trying to access google cloud storage bucket from cloud functions (python) instance and it's throwing mystic 500 error.

I have given the service account editor role too. It didn't make any change.

I also checked if any of the quota is going off limit. The limits were not even close.

Please, anyone can help me find cause of this error?

here is the code

    from google.cloud import storage
    import os
    import base64

    storage_client = storage.Client()

    def init_analysis(event, context):
        print("event", event)
        pubsub_message = base64.b64decode(event['data']).decode('utf-8')

        print(pubsub_message)
        bucket_name = 'my-bucket'
        bucket = storage_client.get_bucket(bucket_name)
        blobs = bucket.list_blobs()
        for blob in blobs:
            print(blob.name)

Error:

    Traceback (most recent call last): File "/env/local/lib/python3.7/site-packages/google/auth/compute_engine/credentials.py", line 99, in refresh service_account=self._service_account_email) File "/env/local/lib/python3.7/site-packages/google/auth/compute_engine/_metadata.py", line 208, in get_service_account_token 'instance/service-accounts/{0}/token'.format(service_account)) File "/env/local/lib/python3.7/site-packages/google/auth/compute_engine/_metadata.py", line 140, in get url, response.status, response.data), response) google.auth.exceptions.TransportError: ("Failed to retrieve http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/my-project@appspot.gserviceaccount.com/token from the Google Compute Enginemetadata service. Status: 500 Response:\nb'Could not fetch URI /computeMetadata/v1/instance/service-accounts/my-project@appspot.gserviceaccount.com/token\\n'", <google.auth.transport.requests._Response object at 0x2b0ef9edf438>) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py", line 383, in run_background_function _function_handler.invoke_user_function(event_object) File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py", line 217, in invoke_user_function return call_user_function(request_or_event) File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py", line 214, in call_user_function event_context.Context(**request_or_event.context)) File "/user_code/main.py", line 21, in init_analysis bucket = storage_client.get_bucket(bucket_name) File "/env/local/lib/python3.7/site-packages/google/cloud/storage/client.py", line 227, in get_bucket bucket.reload(client=self) File "/env/local/lib/python3.7/site-packages/google/cloud/storage/_helpers.py", line 130, in reload _target_object=self, File "/env/local/lib/python3.7/site-packages/google/cloud/_http.py", line 315, in api_request target_object=_target_object, File "/env/local/lib/python3.7/site-packages/google/cloud/_http.py", line 192, in _make_request return self._do_request(method, url, headers, data, target_object) File "/env/local/lib/python3.7/site-packages/google/cloud/_http.py", line 221, in _do_request return self.http.request(url=url, method=method, headers=headers, data=data) File "/env/local/lib/python3.7/site-packages/google/auth/transport/requests.py", line 205, in request self._auth_request, method, url, request_headers) File "/env/local/lib/python3.7/site-packages/google/auth/credentials.py", line 122, in before_request self.refresh(request) File "/env/local/lib/python3.7/site-packages/google/auth/compute_engine/credentials.py", line 102, in refresh six.raise_from(new_exc, caught_exc) File "<string>", line 3, in raise_from google.auth.exceptions.RefreshError: ("Failed to retrieve http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/my-project@appspot.gserviceaccount.com/token from the Google Compute Enginemetadata service. Status: 500 Response:\nb'Could not fetch URI /computeMetadata/v1/instance/service-accounts/my-project@appspot.gserviceaccount.com/token\\n'", <google.auth.transport.requests._Response object at 0x2b0ef9edf438>)
google.auth.exceptions.TransportError: ("Failed to retrieve http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/my-project@appspot.gserviceaccount.com/token from the Google Compute Enginemetadata service. Status: 500 Response:\nb'Could not fetch URI /computeMetadata/v1/instance/service-accounts/my-project@appspot.gserviceaccount.com/token\\n'"

Body:
The error you are getting it's because your Cloud Functions service account doesn't have the cloudfunctions.serviceAgent role. As you can see on the documentation:

Authenticating as the runtime service account from inside your function may fail if you change the Cloud Functions service account's permissions.

However, I found that sometimes you can not add this role as it doesn't show up as an option. I have reported this issue to the Google Cloud Functions engineering team and they are working to solve it.

Nevertheless, you can add the role again using this gcloud command:

gcloud projects add-iam-policy-binding <project_name> --role=roles/cloudfunctions.serviceAgent --member=serviceAccount:service-<project_number>@gcf-admin-robot.iam.gserviceaccount.com


问:
How to fix issue: no rule to process file /FBSDKCoreKit.modulemap' of type 'sourcecode.module-map' for architecture x86_64
I'm creating an app and I'm on the first step of setting up Firebase social login and I got this error suddenly,

Showing Recent Issues

:-1: no rule to process file
  '/Users/Al/Desktop/CB.FireBaseSocialLogin/Pods/FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit/Basics/FBSDKCoreKit.modulemap'
  of type 'sourcecode.module-map' for architecture 'x86_64' (in target
  'FBSDKCoreKit')

no other errors are showing and the app runs with a blank white screen. the header files in my compiler sources are AppDelegate.swift and ViewController.swift.

I'm using Xcode 10.2.1

///this is the output i'm seeing:

2019-05-28 12:43:56.393901+0300 CB.FireBaseSocialLogin[7764:612343]
  : Please set a value for FacebookAutoLogAppEventsEnabled. Set
  the flag to TRUE if you want to collect app install, app launch and
  in-app purchase events automatically. To request user consent before
  collecting data, set the flag value to FALSE, then change to TRUE once
  user consent is received. Learn more:
  https://developers.facebook.com/docs/app-events/getting-started-app-events-ios#disable-auto-events.
  2019-05-28 12:43:56.394525+0300 CB.FireBaseSocialLogin[7764:612343]
  : You haven't set a value for
  FacebookAdvertiserIDCollectionEnabled. Set the flag to TRUE if you
  want to collect Advertiser ID for better advertising and analytics
  results. To request user consent before collecting data, set the flag
  value to FALSE, then change to TRUE once user consent is received.
  Learn more:
  https://developers.facebook.com/docs/app-events/getting-started-app-events-ios#disable-auto-events.
  2019-05-28 12:43:56.437230+0300 CB.FireBaseSocialLogin[7764:612343]
  libMobileGestalt MobileGestalt.c:890: MGIsDeviceOneOfType is not
  supported on this platform. 2019-05-28 12:43:56.440128+0300
  CB.FireBaseSocialLogin[7764:612520]  - [I-ACS036002]
  Analytics screen reporting is enabled. Call +[FIRAnalytics
  setScreenName:setScreenClass:] to set the screen name or override the
  default screen class name. To disable screen reporting, set the flag
  FirebaseScreenReportingEnabled to NO (boolean) in the Info.plist
  2019-05-28 12:43:56.497990+0300 CB.FireBaseSocialLogin[7764:612343]
  Unknown class _TtC22CB_FireBaseSocialLogin14ViewController in
  Interface Builder file. 2019-05-28 12:43:56.535539+0300
  CB.FireBaseSocialLogin[7764:612343] Falling back to loading access
  token from NSUserDefaults because of simulator bug 2019-05-28
  12:43:56.535719+0300 CB.FireBaseSocialLogin[7764:612343] Falling back
  to storing access token in NSUserDefaults because of simulator bug
  2019-05-28 12:43:56.566347+0300 CB.FireBaseSocialLogin[7764:612343]
  FBSDKLog: FBSDKGraphRequestConnection cannot be started before
  Facebook SDK initialized. 2019-05-28 12:43:56.582737+0300
  CB.FireBaseSocialLogin[7764:612343] FBSDKLog:
  FBSDKGraphRequestConnection cannot be started before Facebook SDK
  initialized. 2019-05-28 12:43:56.583098+0300
  CB.FireBaseSocialLogin[7764:612343] FBSDKLog:
  FBSDKGraphRequestConnection cannot be started before Facebook SDK
  initialized. 2019-05-28 12:43:56.588004+0300
  CB.FireBaseSocialLogin[7764:612526] 6.0.0 -
  [Firebase/Analytics][I-ACS023007] Analytics v.60000000 started
  2019-05-28 12:43:56.588883+0300 CB.FireBaseSocialLogin[7764:612526]
  6.0.0 - [Firebase/Analytics][I-ACS023008] To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled (see
  http:1234567890) 2019-05-28 12:43:56.621611+0300
  CB.FireBaseSocialLogin[7764:612343] [MC] System group container for
  systemgroup.com.apple.configurationprofiles path is
  /Users/Al/Library/Developer/CoreSimulator/Devices/A4CCED21-B5C8-4C67-81A5-2BC39E842757/data/Containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles
  2019-05-28 12:43:56.621979+0300 CB.FireBaseSocialLogin[7764:612343]
  [MC] Reading from private effective user settings. 2019-05-28
  12:43:57.138534+0300 CB.FireBaseSocialLogin[7764:612526] [BoringSSL]
  nw_protocol_boringssl_get_output_frames(1301) [C1.1:2][0x7f9759a04710]
  get output frames failed, state 8196 2019-05-28 12:43:57.138675+0300
  CB.FireBaseSocialLogin[7764:612526] [BoringSSL]
  nw_protocol_boringssl_get_output_frames(1301) [C1.1:2][0x7f9759a04710]
  get output frames failed, state 8196 2019-05-28 12:43:57.139153+0300
  CB.FireBaseSocialLogin[7764:612526] TIC Read Status [1:0x0]: 1:57
  2019-05-28 12:43:57.139250+0300 CB.FireBaseSocialLogin[7764:612526]
  TIC Read Status [1:0x0]: 1:57 2019-05-28 12:43:57.215138+0300
  CB.FireBaseSocialLogin[7764:612528] [BoringSSL]
  nw_protocol_boringssl_get_output_frames(1301) [C2.1:2][0x7f9759b01f60]
  get output frames failed, state 8196 2019-05-28 12:43:57.215290+0300
  CB.FireBaseSocialLogin[7764:612528] [BoringSSL]
  nw_protocol_boringssl_get_output_frames(1301) [C2.1:2][0x7f9759b01f60]
  get output frames failed, state 8196 2019-05-28 12:43:57.215539+0300
  CB.FireBaseSocialLogin[7764:612528] TIC Read Status [2:0x0]: 1:57
  2019-05-28 12:43:57.215624+0300 CB.FireBaseSocialLogin[7764:612528]
  TIC Read Status [2:0x0]: 1:57 2019-05-28 12:43:57.366695+0300
  CB.FireBaseSocialLogin[7764:612528] [BoringSSL]
  nw_protocol_boringssl_get_output_frames(1301) [C3.1:2][0x7f97574138a0]
  get output frames failed, state 8196 2019-05-28 12:43:57.366837+0300
  CB.FireBaseSocialLogin[7764:612528] [BoringSSL]
  nw_protocol_boringssl_get_output_frames(1301) [C3.1:2][0x7f97574138a0]
  get output frames failed, state 8196 2019-05-28 12:43:57.367263+0300
  CB.FireBaseSocialLogin[7764:612528] TIC Read Status [3:0x0]: 1:57
  2019-05-28 12:43:57.367555+0300 CB.FireBaseSocialLogin[7764:612528]
  TIC Read Status [3:0x0]: 1:57

答:
Found How to remove the warning..

Select Your Pods Project

In Targets list select FBSDKCoreKit

Select "Build Phases" Tab from Top.

Expand the Compile Sources Tab

Search for "FBSDKCoreKit.modulemap" in the list.. (Uggghhhhh)

Select it.. Scroll down.. and click "-" (MINUS).

Have a happy warning free life!


问:
Laravel: Pass a variable to a tab without using Javascript
I am building an index page in whicgh I show the orders separated in three tables: "incoming", "in_progress", "ready"

Essencially is this same table shown three times (and separated into a different tab)

```<code><table class="table table-striped table-hover dataTables-example">
    <thead class="thead-dark">
        <tr>
            <th>Id</th>
            <th>Eingang</th>
            <th>Auftrag id</th>
            <th>Ort</th>
        </tr>
    </thead>
    <tbody>
        @foreach($all_ as $element)
        @if($element->status === 'in_progress')
        <tr>
            <td>{{$element->id}}</td>
            <td class="gradeX">{!! $element->created_at->format('D j M Y, G:i:s') !!}</td>
            <td><a href="{{route('orders.show', $element->title)}}">{!! $element->title !!}</a></td>
            <td>{!! $element->address->plz->locality !!}</td>
        </tr>
        @endif
        @endforeach
    </tbody>
</table>
</code>```

I saved the table in a different file and I called it like this:  @include('dashboard.orders.includes.table_orders')

```<code>....
<div class="tab-content py-3 px-3 px-sm-0" id="nav-tabContent">
    <div class="tab-pane fade show active" id="nav-home" role="tabpanel" aria-labelledby="nav-home-tab">
        <!-- I need to call here the partial and pass status="incoming" -->
        @include('dashboard.orders.includes.table_orders')
    </div>

    <div class="tab-pane fade" id="nav-profile" role="tabpanel" aria-labelledby="nav-profile-tab">
        <!-- I need to call here the partial and pass status="in progress" -->
        @include('dashboard.orders.includes.table_orders')
    </div>

    <div class="tab-pane fade" id="nav-contact" role="tabpanel" aria-labelledby="nav-contact-tab">
        <!-- I need to call here the partial and pass status="ready" -->
        @include('dashboard.orders.includes.table_orders')
    </div>
</div>
</code>```

The model looks lilke this:

```<code>$element [
    "id" => 1
    "title" => "KFZ_0001_May_2019"
    "details" => "Lorem Ipsums dolor..."
    "status" => "in progress"    // <---or incoming or ready
    "created_at" => "2019-05-31 09:14:02"
    "updated_at" => "2019-05-31 11:16:55"
    "deleted_at" => null
  ]
</code>```

The question is:

How do I call the external partial and pass the "status" variable in order to show the orders separated each in its corresponding table?

All the three tables are show in the same page!

I would like to avoid using of javascript just for that.

答:
As far I understood you, I would do something like this:

```<code>@include('dashboard.orders.includes.table_orders', ['status' => 'incoming'])
</code>```

and then

```<code>@foreach($all_ as $element)
    @if($element->status === $status)
        ...
    @endif
@endforeach
</code>```

If you want to output some data three times and the difference just in some variables, you won't break DRY principle.

Body:
I am building an index page in whicgh I show the orders separated in three tables: "incoming", "in_progress", "ready"

Essencially is this same table shown three times (and separated into a different tab)

            Id
            Eingang
            Auftrag id
            Ort

        @foreach($all_ as $element)
        @if($element->status === 'in_progress')

            {{$element->id}}
            {!! $element->created_at->format('D j M Y, G:i:s') !!}
            title)}}">{!! $element->title !!}
            {!! $element->address->plz->locality !!}

        @endif
        @endforeach

I saved the table in a different file and I called it like this:  @include('dashboard.orders.includes.table_orders')

....

        @include('dashboard.orders.includes.table_orders')

        @include('dashboard.orders.includes.table_orders')

        @include('dashboard.orders.includes.table_orders')

The model looks lilke this:

$element [
    "id" => 1
    "title" => "KFZ_0001_May_2019"
    "details" => "Lorem Ipsums dolor..."
    "status" => "in progress"    // <---or incoming or ready
    "created_at" => "2019-05-31 09:14:02"
    "updated_at" => "2019-05-31 11:16:55"
    "deleted_at" => null
  ]

The question is:

How do I call the external partial and pass the "status" variable in order to show the orders separated each in its corresponding table?

All the three tables are show in the same page!

I would like to avoid using of javascript just for that.

Body:
As far I understood you, I would do something like this:

@include('dashboard.orders.includes.table_orders', ['status' => 'incoming'])

and then

@foreach($all_ as $element)
    @if($element->status === $status)
        ...
    @endif
@endforeach

If you want to output some data three times and the difference just in some variables, you won't break DRY principle.


问:
Handling asynchronous threads
I (think that I) understand the differences between threads and tasks.

Threads allow us to do multiple things in parallel (they are CPU-bound).

Asynchronous tasks release the processor time while some I/O work is done (they are I/O-bound).

Now, let's say I want to do multiple asynchronous tasks in parallel. For example, I want to download several pages of a paged response at the same time. Or, I want to write new data into two different databases. What is the correct way to handle the threads? Should they be async and awaited? Or can the async operation be just inside the thread? What is the best practice for error handling?

I have tried creating my own utility method to start a new async thread, but I have a feeling that it can go horribly wrong.

```<code>public static Task<Thread> RunInThreadAsync<T>(T actionParam, Func<T, Task> asyncAction)
{
    var thread = new Thread(async () => await asyncAction(actionParam));
    thread.Start();
    return thread;
}
</code>```

Is this ok? Or should the method be public static async Task<Thread>? If yes, what should be awaited? There is no thread.StartAsync(). Or should I use Task.Run instead?

Note: Using await Task.WhenAll or similar approaches without an explicit new thread is not an option for me. The "worker" thread is run in background (to avoid blocking the main thread) and is later processed by other services in the system.

答:
I (think that I) understand the differences between threads and tasks.

There's one important concept missing here: concurrency. Concurrency is doing more than one thing at a time. This is different than "parallel", which is a term most developers use to mean "doing more than one thing at a time using threads". So, parallelism is one form of concurrency, and asynchrony is another form of concurrency.

Now, let's say I want to do multiple asynchronous tasks in parallel.

And here's the problem: mixing two forms of concurrency. What you really want to do is multiple asynchronous tasks concurrently. And the way to do this is via Task.WhenAll.

Using await Task.WhenAll or similar approaches without an explicit new thread is not an option for me. The "worker" thread is run in background (to avoid blocking the main thread) and is later processed by other services in the system.

This argument doesn't make any sense. Asynchronous code won't block the main thread because it's asynchronous. There's no explicit thread necessary.

If, for some unknown reason, you really do need a background thread, then just wrap your code in Task.Run. Thread should only ever be used for COM interop; any other use of Thread is legacy code as soon as it is written.

Title: Handling asynchronous threads

Body:
I (think that I) understand the differences between threads and tasks.

Threads allow us to do multiple things in parallel (they are CPU-bound).

Asynchronous tasks release the processor time while some I/O work is done (they are I/O-bound).

Now, let's say I want to do multiple asynchronous tasks in parallel. For example, I want to download several pages of a paged response at the same time. Or, I want to write new data into two different databases. What is the correct way to handle the threads? Should they be async and awaited? Or can the async operation be just inside the thread? What is the best practice for error handling?

I have tried creating my own utility method to start a new async thread, but I have a feeling that it can go horribly wrong.

public static Task<Thread> RunInThreadAsync<T>(T actionParam, Func<T, Task> asyncAction)
{
    var thread = new Thread(async () => await asyncAction(actionParam));
    thread.Start();
    return thread;
}

Is this ok? Or should the method be public static async Task<Thread>? If yes, what should be awaited? There is no thread.StartAsync(). Or should I use Task.Run instead?

Note: Using await Task.WhenAll or similar approaches without an explicit new thread is not an option for me. The "worker" thread is run in background (to avoid blocking the main thread) and is later processed by other services in the system.


问:
Flyway fails to detect new migration files
I'm trying to run the flywayMigrate task from Gradle in my project after adding a new migration file but Flyway doesn't pick it up. I get this output:

```<code>Flyway Community Edition 5.2.4 by Boxfuse
Database: jdbc:postgresql://localhost:5432/mydb (PostgreSQL 10.6)
Successfully validated 6 migrations (execution time 00:00.105s)
Current version of schema "public": 5
Schema "public" is up to date. No migration necessary.
</code>```

So it detects that I have 6 migrations but it doesn't execute the new file I just added (V6) and insists on saying that the schema is up to date even if it isn't.

This is how my config looks like:

```<code>{
    url = database_url
    user = database_user
    password = database_password
    driver = database_driver
    schemas = ["public"]
    locations = ["filesystem:shared/src/main/resources/db/migration"]
    table = "flyway_schema_history"
    sqlMigrationPrefix = "V"
    sqlMigrationSuffix = ".sql"
    placeholderPrefix = "\${"
    placeholderSuffix = "}"
    target = "5.1"
}
</code>```

I checked every setting and it is ok, It picks up the first 5 migration files if I delete all tables but for some reason the 6th one is not picked up. (I even tried adding a 7th one but it is not working either)

I tried to run the sql in the 6th migration file and it runs OK so there is probably a problem with Flyway.

If I run with the debug flag I can see that it even parses and reads out the sql from the file but all migrations are filtered out. What am I doing wrong?

```<code>...
15:23:34.893 [DEBUG] [org.flywaydb.core.internal.sqlscript.SqlScript] Parsing V5__some_migration_5.sql ...
15:23:34.893 [DEBUG] [org.flywaydb.core.internal.sqlscript.SqlScript] Found statement at line 1: ...
...
15:23:34.894 [DEBUG] [org.flywaydb.core.internal.sqlscript.SqlScript] Parsing V6__some_migration_6.sql ...
15:23:34.894 [DEBUG] [org.flywaydb.core.internal.sqlscript.SqlScript] Found statement at line 1: ...
15:23:34.894 [DEBUG] [org.flywaydb.core.internal.scanner.Scanner] Filtering out resource: shared/src/main/resources/db/migration/V1__some_migration_1.sql (filename: V1__some_migration_1.sql)
15:23:34.895 [DEBUG] [org.flywaydb.core.internal.scanner.Scanner] Filtering out resource: shared/src/main/resources/db/migration/V2__some_migration_2.sql (filename: V2__some_migration_2.sql)
15:23:34.895 [DEBUG] [org.flywaydb.core.internal.scanner.Scanner] Filtering out resource: shared/src/main/resources/db/migration/V3__some_migration_3.sql (filename: V3__some_migration_3.sql)
15:23:34.895 [DEBUG] [org.flywaydb.core.internal.scanner.Scanner] Filtering out resource: shared/src/main/resources/db/migration/V4__some_migration_4.sql (filename: V4__some_migration_4.sql)
15:23:34.895 [DEBUG] [org.flywaydb.core.internal.scanner.Scanner] Filtering out resource: shared/src/main/resources/db/migration/V5__some_migration_5.sql (filename: V5__some_migration_5.sql)
15:23:34.895 [DEBUG] [org.flywaydb.core.internal.scanner.Scanner] Filtering out resource: shared/src/main/resources/db/migration/V6__some_migration_6.sql (filename: V6__some_migration_6.sql)
15:23:34.899 [DEBUG] [org.postgresql.jdbc.PgConnection]   setAutoCommit = true
15:23:34.899 [INFO] [org.flywaydb.core.internal.command.DbValidate] Successfully validated 6 migrations (execution time 00:00.016s)
15:23:34.899 [DEBUG] [org.postgresql.jdbc.PgConnection]   setAutoCommit = false
15:23:34.899 [DEBUG] [org.flywaydb.core.internal.command.DbSchemas] Schema "public" already exists. Skipping schema creation.
15:23:34.900 [DEBUG] [org.postgresql.jdbc.PgConnection]   setAutoCommit = true
15:23:34.915 [INFO] [org.flywaydb.core.internal.command.DbMigrate] Current version of schema "public": 5
15:23:34.915 [INFO] [org.flywaydb.core.internal.command.DbMigrate] Schema "public" is up to date. No migration necessary.
</code>```

What I see in the flyway_schema_history is consistent with what the log says:

```<code>installed_rank  version description type    script  checksum    installed_by    installed_on    execution_time  success
1   1   some migration 1    SQL V1__some_migration_1.sql    1640479949  myuser  2019-05-31 15:17:19.354850  26  true
2   2   some migration 2    SQL V2__some_migration_2.sql    1463373644  myuser  2019-05-31 15:17:19.394065  1   true
3   3   some migration 3    SQL V3__some_migration_3.sql    1872028758  myuser  2019-05-31 15:17:19.398957  9   true
4   4   some migration 4    SQL V4__some_migration_4.sql    762610066   myuser  2019-05-31 15:17:19.410718  5   true
5   5   some migration 5    SQL V5__some_migration_5.sql    -355256115  myuser  2019-05-31 15:17:19.418077  1   true
</code>```

答:
:-)

You have target = "5.1" in your config, but

```<code>target  NO  latest version

The target version up to which Flyway should run migrations.
Migrations with a higher version number will not be applied.
The string 'current' will be interpreted as MigrationVersion.CURRENT,
a placeholder for the latest version that has been applied to the database.
</code>```

Look at Gradle Task: flywayMigrate

This is why you cannot process migration > 5.1

Body:
I'm trying to run the flywayMigrate task from Gradle in my project after adding a new migration file but Flyway doesn't pick it up. I get this output:

Flyway Community Edition 5.2.4 by Boxfuse
Database: jdbc:postgresql://localhost:5432/mydb (PostgreSQL 10.6)
Successfully validated 6 migrations (execution time 00:00.105s)
Current version of schema "public": 5
Schema "public" is up to date. No migration necessary.

So it detects that I have 6 migrations but it doesn't execute the new file I just added (V6) and insists on saying that the schema is up to date even if it isn't.

This is how my config looks like:

{
    url = database_url
    user = database_user
    password = database_password
    driver = database_driver
    schemas = ["public"]
    locations = ["filesystem:shared/src/main/resources/db/migration"]
    table = "flyway_schema_history"
    sqlMigrationPrefix = "V"
    sqlMigrationSuffix = ".sql"
    placeholderPrefix = "\${"
    placeholderSuffix = "}"
    target = "5.1"
}

I checked every setting and it is ok, It picks up the first 5 migration files if I delete all tables but for some reason the 6th one is not picked up. (I even tried adding a 7th one but it is not working either)

I tried to run the sql in the 6th migration file and it runs OK so there is probably a problem with Flyway.

If I run with the debug flag I can see that it even parses and reads out the sql from the file but all migrations are filtered out. What am I doing wrong?

...
15:23:34.893 [DEBUG] [org.flywaydb.core.internal.sqlscript.SqlScript] Parsing V5__some_migration_5.sql ...
15:23:34.893 [DEBUG] [org.flywaydb.core.internal.sqlscript.SqlScript] Found statement at line 1: ...
...
15:23:34.894 [DEBUG] [org.flywaydb.core.internal.sqlscript.SqlScript] Parsing V6__some_migration_6.sql ...
15:23:34.894 [DEBUG] [org.flywaydb.core.internal.sqlscript.SqlScript] Found statement at line 1: ...
15:23:34.894 [DEBUG] [org.flywaydb.core.internal.scanner.Scanner] Filtering out resource: shared/src/main/resources/db/migration/V1__some_migration_1.sql (filename: V1__some_migration_1.sql)
15:23:34.895 [DEBUG] [org.flywaydb.core.internal.scanner.Scanner] Filtering out resource: shared/src/main/resources/db/migration/V2__some_migration_2.sql (filename: V2__some_migration_2.sql)
15:23:34.895 [DEBUG] [org.flywaydb.core.internal.scanner.Scanner] Filtering out resource: shared/src/main/resources/db/migration/V3__some_migration_3.sql (filename: V3__some_migration_3.sql)
15:23:34.895 [DEBUG] [org.flywaydb.core.internal.scanner.Scanner] Filtering out resource: shared/src/main/resources/db/migration/V4__some_migration_4.sql (filename: V4__some_migration_4.sql)
15:23:34.895 [DEBUG] [org.flywaydb.core.internal.scanner.Scanner] Filtering out resource: shared/src/main/resources/db/migration/V5__some_migration_5.sql (filename: V5__some_migration_5.sql)
15:23:34.895 [DEBUG] [org.flywaydb.core.internal.scanner.Scanner] Filtering out resource: shared/src/main/resources/db/migration/V6__some_migration_6.sql (filename: V6__some_migration_6.sql)
15:23:34.899 [DEBUG] [org.postgresql.jdbc.PgConnection]   setAutoCommit = true
15:23:34.899 [INFO] [org.flywaydb.core.internal.command.DbValidate] Successfully validated 6 migrations (execution time 00:00.016s)
15:23:34.899 [DEBUG] [org.postgresql.jdbc.PgConnection]   setAutoCommit = false
15:23:34.899 [DEBUG] [org.flywaydb.core.internal.command.DbSchemas] Schema "public" already exists. Skipping schema creation.
15:23:34.900 [DEBUG] [org.postgresql.jdbc.PgConnection]   setAutoCommit = true
15:23:34.915 [INFO] [org.flywaydb.core.internal.command.DbMigrate] Current version of schema "public": 5
15:23:34.915 [INFO] [org.flywaydb.core.internal.command.DbMigrate] Schema "public" is up to date. No migration necessary.

What I see in the flyway_schema_history is consistent with what the log says:

installed_rank  version description type    script  checksum    installed_by    installed_on    execution_time  success
1   1   some migration 1    SQL V1__some_migration_1.sql    1640479949  myuser  2019-05-31 15:17:19.354850  26  true
2   2   some migration 2    SQL V2__some_migration_2.sql    1463373644  myuser  2019-05-31 15:17:19.394065  1   true
3   3   some migration 3    SQL V3__some_migration_3.sql    1872028758  myuser  2019-05-31 15:17:19.398957  9   true
4   4   some migration 4    SQL V4__some_migration_4.sql    762610066   myuser  2019-05-31 15:17:19.410718  5   true
5   5   some migration 5    SQL V5__some_migration_5.sql    -355256115  myuser  2019-05-31 15:17:19.418077  1   true

Body:
:-)

You have target = "5.1" in your config, but

target  NO  latest version

The target version up to which Flyway should run migrations.
Migrations with a higher version number will not be applied.
The string 'current' will be interpreted as MigrationVersion.CURRENT,
a placeholder for the latest version that has been applied to the database.

Look at Gradle Task: flywayMigrate

This is why you cannot process migration > 5.1


问:
C#, calling an instance of a class from a string
I've been struggling for a while to find a way of calling an instance of a class from a user defined input.

Essentially I want to call an instance from my StandardVehicle class that has already been defined, however the problem is that the name of the instance that I'm calling is defined by a users selection on a combo box on a form.

This is how I assumed it would be formatted, however I get an error when I try calling the instance saying that I cannot complicitly convert from string to StandardVehicle.

```<code>        StandardVehicle VauxhallB = new StandardVehicle();
        VauxhallB.Model = "B";
        VauxhallB.Manufacturer = "Vauxhall";
        VauxhallB.Doors = 5;
        VauxhallB.HorsePower = 200;
        VauxhallB.Transmission = "Manual";
        VauxhallB.Year = 2009;
        VauxhallB.Cylinders = 6;
        VauxhallB.Seats = 7;
        VauxhallB.Price = 17000;
        VauxhallB.Registration = "abc1243";

        StandardVehicle objname = comboBox1.Text;
</code>```

I'm assuming it's just a case of formatting the string, but I've been searching for hours and can't figure out what format it needs to be in to define it as an instance.

Any help would be appreciated.

Regards,
S.

答:
It's a little more complicated than your sample. I'm going to start with the quick and easy approach, which, while IS quick and easy, is kind of an anti-pattern, but I 'll explain that at the end:

```<code>IBritishAuto car;

switch
{
    case "Vauxhall":
    {
        car = new Vauxhall(standardVehicle);
        break;
    }
    case "Jaguar":
    {
        car = new Jaguar(standardVehicle);
    }
    ...etc.
}
</code>```

The reason why this is sub-optimal is that every time you want to add a new car type, you have to modify the original code block, and risk regression. If you're happy with this solution, and don't care, you can stop reading now.

Still there?

This pattern is called a "conditional dispatcher". There are two main strategies to improve it: refactor to a Command pattern (that's capped because it's a Gang of Four pattern), or a broader implementation of a concept called 'inversion of control'. If you're interested, here are your Google terms:

"refactor conditional dispatcher"
"inversion of control".

Good luck.

Body:
I've been struggling for a while to find a way of calling an instance of a class from a user defined input.

Essentially I want to call an instance from my StandardVehicle class that has already been defined, however the problem is that the name of the instance that I'm calling is defined by a users selection on a combo box on a form.

This is how I assumed it would be formatted, however I get an error when I try calling the instance saying that I cannot complicitly convert from string to StandardVehicle.

        StandardVehicle VauxhallB = new StandardVehicle();
        VauxhallB.Model = "B";
        VauxhallB.Manufacturer = "Vauxhall";
        VauxhallB.Doors = 5;
        VauxhallB.HorsePower = 200;
        VauxhallB.Transmission = "Manual";
        VauxhallB.Year = 2009;
        VauxhallB.Cylinders = 6;
        VauxhallB.Seats = 7;
        VauxhallB.Price = 17000;
        VauxhallB.Registration = "abc1243";

        StandardVehicle objname = comboBox1.Text;

I'm assuming it's just a case of formatting the string, but I've been searching for hours and can't figure out what format it needs to be in to define it as an instance.

Any help would be appreciated.

Regards,
S.

Body:
It's a little more complicated than your sample. I'm going to start with the quick and easy approach, which, while IS quick and easy, is kind of an anti-pattern, but I 'll explain that at the end:

IBritishAuto car;

switch
{
    case "Vauxhall":
    {
        car = new Vauxhall(standardVehicle);
        break;
    }
    case "Jaguar":
    {
        car = new Jaguar(standardVehicle);
    }
    ...etc.
}

The reason why this is sub-optimal is that every time you want to add a new car type, you have to modify the original code block, and risk regression. If you're happy with this solution, and don't care, you can stop reading now.

Still there?

This pattern is called a "conditional dispatcher". There are two main strategies to improve it: refactor to a Command pattern (that's capped because it's a Gang of Four pattern), or a broader implementation of a concept called 'inversion of control'. If you're interested, here are your Google terms:

"refactor conditional dispatcher"
"inversion of control".

Good luck.


问:
Selenium - User prompt of type promptUserAndPass is not supported
For a long time I've been using a python bot to do some work task. Among others things, the bot has to pass an authentication window.

The code of this in the python program is the following:

```<code>driver = webdriver.Firefox(firefox_profile=profile)
...
driver.get('https://example.com')
driver.switch_to.alert.send_keys('123456' + Keys.TAB + '123456')
driver.switch_to.alert.accept()
</code>```

But yesterday it throwed this error:

selenium.common.exceptions.WebDriverException: Message: User prompt of
  type promptUserAndPass is not supported

I've been googling but I even don't find results about this kind of exception and how to deal with this problem.

Any ideas?

Thanks in advance!

答:
I don't have enough rep to comment and I know this isn't "solving" the problem, but I was able to work around this problem by using the Firefox ESR.

You can install the ESR parallel to your main Firefox installation, and then specify which binary the FirefoxDriver will use:

```<code>driver = webdriver.Firefox(firefox_profile=profile, firefox_binary="/path/to/esr/binary")
</code>```

Body:
For a long time I've been using a python bot to do some work task. Among others things, the bot has to pass an authentication window.

The code of this in the python program is the following:

driver = webdriver.Firefox(firefox_profile=profile)
...
driver.get('https://example.com')
driver.switch_to.alert.send_keys('123456' + Keys.TAB + '123456')
driver.switch_to.alert.accept()

But yesterday it throwed this error:

selenium.common.exceptions.WebDriverException: Message: User prompt of
  type promptUserAndPass is not supported

I've been googling but I even don't find results about this kind of exception and how to deal with this problem.

Any ideas?

Thanks in advance!

Body:
I don't have enough rep to comment and I know this isn't "solving" the problem, but I was able to work around this problem by using the Firefox ESR.

You can install the ESR parallel to your main Firefox installation, and then specify which binary the FirefoxDriver will use:

driver = webdriver.Firefox(firefox_profile=profile, firefox_binary="/path/to/esr/binary")


问:
How to connect a field that sometimes has an empty amount to a table
Pasteid Field is a field that is sometimes empty and refers to the post table when it is full, and the post table connects to the user table with the Userid field.

```<code>select `posts`.`id` as `pid`, `posts`.`media` as `pmedia`, `posts`.`created_at` as `pcreated_at`, `posts`.`txt`, `users`.`media` as `umedia`, `users`.`id`, `users`.`name` as `name`, `users`.`username`, `posts`.`options`, `posts`.`likes`, `posts`.`comments`, `posts`.`copyid`, `posts`.`pasteid`, `u`.`name` as `replayname`, `u`.`name` as `replayuser`
from `posts`
inner join `usersq` on `users`.`id` = `posts`.`userid`
inner join `posts` as `p` on `posts`.`pasteid` = `p`.`id`
inner join `users` as `u` on `u`.`id` = `p`.`userid`
where (`posts`.`block` = 0 and `users`.`view` = 1) and `users`.`status` not in (1, 3)
order by `posts`.`created_at` desc
limit 30
</code>```

In fact, we want to know if the post has been copied, and from which copy it was copied.
The problem with the above code is that it only contains the records that the Pasteid field must be filled in and, if empty, does not include the output

post table
id txt media pasteid userid
1  eee 1.jpg           1
2  rrr                 1
3  eee 1.jpg    1      2

user table
id name
 1  Ali
 2  jack

As you can see, the jack has been copied from behind. Now I need to get Ali's name from the users table and put it in the replayname field

答:
Just use LEFT JOIN instead of INNER JOIN.
The LEFT JOIN will return all records from the left table  even if they have no match in the right table.

```<code>select `posts`.`id` as `pid`, `posts`.`media` as `pmedia`, `posts`.`created_at` as `pcreated_at`, `posts`.`txt`, `users`.`media` as `umedia`, `users`.`id`, `users`.`name` as `name`, `users`.`username`, `posts`.`options`, `posts`.`likes`, `posts`.`comments`, `posts`.`copyid`, `posts`.`pasteid`, `u`.`name` as `replayname`, `u`.`name` as `replayuser`
from `posts`
inner join `usersq` on `users`.`id` = `posts`.`userid`
left join `posts` as `p` on `posts`.`pasteid` = `p`.`id`
left join `users` as `u` on `u`.`id` = `p`.`userid`
where (`posts`.`block` = 0 and `users`.`view` = 1) and `users`.`status` not in (1, 3)
order by `posts`.`created_at` desc
limit 30
</code>```

Body:
Pasteid Field is a field that is sometimes empty and refers to the post table when it is full, and the post table connects to the user table with the Userid field.

select `posts`.`id` as `pid`, `posts`.`media` as `pmedia`, `posts`.`created_at` as `pcreated_at`, `posts`.`txt`, `users`.`media` as `umedia`, `users`.`id`, `users`.`name` as `name`, `users`.`username`, `posts`.`options`, `posts`.`likes`, `posts`.`comments`, `posts`.`copyid`, `posts`.`pasteid`, `u`.`name` as `replayname`, `u`.`name` as `replayuser`
from `posts`
inner join `usersq` on `users`.`id` = `posts`.`userid`
inner join `posts` as `p` on `posts`.`pasteid` = `p`.`id`
inner join `users` as `u` on `u`.`id` = `p`.`userid`
where (`posts`.`block` = 0 and `users`.`view` = 1) and `users`.`status` not in (1, 3)
order by `posts`.`created_at` desc
limit 30

In fact, we want to know if the post has been copied, and from which copy it was copied.
The problem with the above code is that it only contains the records that the Pasteid field must be filled in and, if empty, does not include the output

post table
id txt media pasteid userid
1  eee 1.jpg           1
2  rrr                 1
3  eee 1.jpg    1      2

user table
id name
 1  Ali
 2  jack

As you can see, the jack has been copied from behind. Now I need to get Ali's name from the users table and put it in the replayname field

Body:
Just use LEFT JOIN instead of INNER JOIN.
The LEFT JOIN will return all records from the left table  even if they have no match in the right table.

select `posts`.`id` as `pid`, `posts`.`media` as `pmedia`, `posts`.`created_at` as `pcreated_at`, `posts`.`txt`, `users`.`media` as `umedia`, `users`.`id`, `users`.`name` as `name`, `users`.`username`, `posts`.`options`, `posts`.`likes`, `posts`.`comments`, `posts`.`copyid`, `posts`.`pasteid`, `u`.`name` as `replayname`, `u`.`name` as `replayuser`
from `posts`
inner join `usersq` on `users`.`id` = `posts`.`userid`
left join `posts` as `p` on `posts`.`pasteid` = `p`.`id`
left join `users` as `u` on `u`.`id` = `p`.`userid`
where (`posts`.`block` = 0 and `users`.`view` = 1) and `users`.`status` not in (1, 3)
order by `posts`.`created_at` desc
limit 30


问:
Namespce OneTimeTearDownAttirbute () and OneTimeSetUpttirbute () does not exist in NUnit.Framework showing error in auto generated specflow(.cs) file
Facing build error The type or namespace name "OneTimeSetUpAttribute" and "OneTimeTearDownAttribute" doesnot exist

Xamarin.UITest-Version 3.0.0
Nunit- Version 2.6.4
NunitTestAdapter- Version 2.0.0
Specflow -Version 2.1.0.0

答: In NUnit 2.6.4, a SetUpFixture used SetUpAttribute and TearDownAttribute. This changed to OneTimeSetUpAttribute and OneTimeTearDownAttribute in NUnit 3. The hange that @Chris refers to also took place, but it affectsTestFixture not SetUpFixture.


问:
Unit tests working well with maven but won't run when using them with IntelliJ
I have some unit tests in a Scala project that are working fine when using mvn clean test to run them (scalatest-maven-plugin version 1.0).

However, when I try to use IntelliJ UI to run them I get this error:

```<code>objc[56331]: Class JavaLaunchHelper is implemented in both /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/bin/java (0x10f8774c0) and /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/libinstrument.dylib (0x1102d24e0). One of the two will be used. Which one is undefined.
java.lang.IllegalArgumentException: ERROR: -r has been deprecated for a very long time and is no longer supported, to prepare for reusing it for a different purpose in the near future. Please change all uses of -r to -C.
    at org.scalatest.tools.ArgsParser$.checkArgsForValidity(ArgsParser.scala:41)
    at org.scalatest.tools.Runner$.runOptionallyWithPassFailReporter(Runner.scala:857)
    at org.scalatest.tools.Runner$.run(Runner.scala:850)
    at org.scalatest.tools.Runner.run(Runner.scala)
    at org.jetbrains.plugins.scala.testingSupport.scalaTest.ScalaTestRunner.runScalaTest2(ScalaTestRunner.java:131)
    at org.jetbrains.plugins.scala.testingSupport.scalaTest.ScalaTestRunner.main(ScalaTestRunner.java:28)
</code>```

Probably it has something to do with a dependency that I have in the pom. It is a dependency to an artifact that I have developed in a separated project. If I remove that dependency, this error disappears.

I need that dependency and I cannot figure out what is wrong with it. Maven is working just fine but I would like to have access to the debugger in IntelliJ.

Any suggestions? I have run out of ideas now and Google is not giving me anything useful so far.

Also, other colleagues are experiencing the same, so I doubt it has something to do with my local configuration.

Thanks in advance!

答:
The "scalatest" library does not like the way that IntelliJ is invoking it.

Try updating your Scala plugin in IntelliJ?

UPDATE:

I have done some digging in the source code of IntelliJ and Scalatest (both can be seen in the stack trace you showed above):

1) Scalatest rejects this "-r" arg that IntelliJ is passing it here:

https://github.com/scalatest/scalatest/blob/b97f944f4a2690744c26dc875097407baba7e21d/scalatest/src/main/scala/org/scalatest/tools/ArgsParser.scala#L41

2) The IntelliJ code which passes arg "-r" is here:

https://github.com/JetBrains/intellij-scala/blob/88317c1dd8a8cd6b8578adc17c1ead36a2a5a77a/scala/runners/src/org/jetbrains/plugins/scala/testingSupport/scalaTest/ScalaTestRunner.java#L131

Notice that this is not the latest version of the IntelliJ scala plugin.

Interestingly, the "-r" arg is only passed if this code has set isOlderScalaTestVersion true (see line 94), which appears to be if the detected ScalaTest version is 1.x (see line 261)

So my current guess (without the benefit of a repro case) is that something about your linked library is causing IntelliJ Scala plugin to think that you are using ScalaTest 1.x, but actually you are using ScalaTest 3.x? Does the linked library have a transitive dependency on an old ScalaTest?

Body:
I have some unit tests in a Scala project that are working fine when using mvn clean test to run them (scalatest-maven-plugin version 1.0).

However, when I try to use IntelliJ UI to run them I get this error:

objc[56331]: Class JavaLaunchHelper is implemented in both /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/bin/java (0x10f8774c0) and /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/libinstrument.dylib (0x1102d24e0). One of the two will be used. Which one is undefined.
java.lang.IllegalArgumentException: ERROR: -r has been deprecated for a very long time and is no longer supported, to prepare for reusing it for a different purpose in the near future. Please change all uses of -r to -C.
    at org.scalatest.tools.ArgsParser$.checkArgsForValidity(ArgsParser.scala:41)
    at org.scalatest.tools.Runner$.runOptionallyWithPassFailReporter(Runner.scala:857)
    at org.scalatest.tools.Runner$.run(Runner.scala:850)
    at org.scalatest.tools.Runner.run(Runner.scala)
    at org.jetbrains.plugins.scala.testingSupport.scalaTest.ScalaTestRunner.runScalaTest2(ScalaTestRunner.java:131)
    at org.jetbrains.plugins.scala.testingSupport.scalaTest.ScalaTestRunner.main(ScalaTestRunner.java:28)

Probably it has something to do with a dependency that I have in the pom. It is a dependency to an artifact that I have developed in a separated project. If I remove that dependency, this error disappears.

I need that dependency and I cannot figure out what is wrong with it. Maven is working just fine but I would like to have access to the debugger in IntelliJ.

Any suggestions? I have run out of ideas now and Google is not giving me anything useful so far.

Also, other colleagues are experiencing the same, so I doubt it has something to do with my local configuration.

Thanks in advance!


问:
Google PubSub and duplicated messages from the TOPIC
How to prevent duplicated msg from happening in Google Cloud PubSub?

Say, I have a code that handles the msg that it is subscribed for.

Say, I have 2 nodes with the same Service that has this code.

Once one has received the msg but not yet acknowledged it, another node will receive the same message. And this is where there's the problem that we have two duplicated msgs.

```<code>void messageReceiver(PubsubMessage pubsubMessage, AckReplyConsumer ackReply) {

        submitHandler.handle(toMessage(pubsubMessage))
                .doOnSuccess((response) -> {
                    log.info("Acknowledging the successfully processed message id: {}, response {}", pubsubMessage.getMessageId(), response);
                    ackReply.ack();  // <---- acknowledged
                })
                .doOnError((e) -> {
                    log.error("Not acknowledging due to an exception", e);
                    ackReply.nack();
                })
                .doOnTerminate(span::finish)
                .subscribe();
    }
</code>```

What is the solution for this? Is it normal behaviour?

答: You can use Redis from Memorystore in order to deduplicate messages. Your publisher should add trace iD to the message body just before publishing it to PubSub. On the other side client (subscriber) should check if the trace ID is in the cache - skip the message. If there is no such message - process the message and add trace ID to cache with 7-8 days expiry time (PubSub deadline is 7 days). In such a simple way You can grant the correct messages received.</p>

Body:
How to prevent duplicated msg from happening in Google Cloud PubSub?

Say, I have a code that handles the msg that it is subscribed for.

Say, I have 2 nodes with the same Service that has this code.

Once one has received the msg but not yet acknowledged it, another node will receive the same message. And this is where there's the problem that we have two duplicated msgs.

void messageReceiver(PubsubMessage pubsubMessage, AckReplyConsumer ackReply) {

        submitHandler.handle(toMessage(pubsubMessage))
                .doOnSuccess((response) -> {
                    log.info("Acknowledging the successfully processed message id: {}, response {}", pubsubMessage.getMessageId(), response);
                    ackReply.ack();  // <---- acknowledged
                })
                .doOnError((e) -> {
                    log.error("Not acknowledging due to an exception", e);
                    ackReply.nack();
                })
                .doOnTerminate(span::finish)
                .subscribe();
    }

What is the solution for this? Is it normal behaviour?