问:
How to adjust the size of UITextField.leftView?
I am trying to change adjust the size of the a UIImageView that is the leftView of my UITextField without any success.  The image is always huge.  I would like it to have the same height as my UITextField.  Here is what i have tried:

Result:

```<code>let topContainer: UIView = {
    let view = UIView()
    view.layer.borderWidth = 1.0
    view.layer.borderColor = UIColor.appGrayExtraLightGray.cgColor
    view.layer.cornerRadius = 5
    view.clipsToBounds = true
    view.translatesAutoresizingMaskIntoConstraints = false
    return view
}()

let emailField: UITextField = {
    let view = UITextField()
    view.backgroundColor = UIColor.orange
    view.text = "myEmailAddress@gmail.com"
    view.font = UIFont.systemFont(ofSize: 14)
    view.translatesAutoresizingMaskIntoConstraints = false
    return view
}()

let s = view.safeAreaLayoutGuide

    topContainer.addSubview(emailField)
    emailField.topAnchor.constraint(equalTo: topContainer.topAnchor, constant: spacing).isActive = true
    emailField.leadingAnchor.constraint(equalTo: topContainer.leadingAnchor, constant: spacing).isActive = true
    emailField.trailingAnchor.constraint(equalTo: topContainer.trailingAnchor, constant: -spacing).isActive = true
    emailField.bottomAnchor.constraint(equalTo: topContainer.bottomAnchor, constant: -spacing).isActive = true

    /**Mail and clear button on eitherisde of textField*/
    let mailView = UIImageView.init(frame: CGRect.init(x: 0, y: 0, width: 15, height: 15)) // Chaning the GREct has no effect on the size!!
    mailView.image = UIImage.init(named: "mailGrayFilled")
    emailField.leftView = mailView
    emailField.leftViewMode = .always
    emailField.clearButtonMode = .always

    view.addSubview(topContainer)
    topContainer.topAnchor.constraint(equalTo: s.topAnchor, constant: spacing).isActive = true
    topContainer.leadingAnchor.constraint(equalTo: s.leadingAnchor, constant: spacing).isActive = true
    topContainer.trailingAnchor.constraint(equalTo: s.trailingAnchor, constant: -spacing).isActive = true
</code>```

答:
Putting the UIImageView into a Container UIView seems to fix the issue when I test your code.  This may also allow you to adjust the padding to suit your needs.

```<code>let iconContainer = UIView(frame: CGRect(x: 0, y: 0, width: 25, height: 15))
let mailView = UIImageView(frame: CGRect(x: 0, y: 0, width: 15, height: 15))
mailView.image = UIImage(named: "mailGrayFilled")
mailView.contentMode = .scaleAspectFit
iconContainer.addSubview(mailView)
emailField.leftViewMode = .always
emailField.leftView = iconContainer
emailField.clearButtonMode = .always
</code>```

Body:
I am trying to change adjust the size of the a UIImageView that is the leftView of my UITextField without any success.  The image is always huge.  I would like it to have the same height as my UITextField.  Here is what i have tried:

Result:

let topContainer: UIView = {
    let view = UIView()
    view.layer.borderWidth = 1.0
    view.layer.borderColor = UIColor.appGrayExtraLightGray.cgColor
    view.layer.cornerRadius = 5
    view.clipsToBounds = true
    view.translatesAutoresizingMaskIntoConstraints = false
    return view
}()

let emailField: UITextField = {
    let view = UITextField()
    view.backgroundColor = UIColor.orange
    view.text = "myEmailAddress@gmail.com"
    view.font = UIFont.systemFont(ofSize: 14)
    view.translatesAutoresizingMaskIntoConstraints = false
    return view
}()

let s = view.safeAreaLayoutGuide

    topContainer.addSubview(emailField)
    emailField.topAnchor.constraint(equalTo: topContainer.topAnchor, constant: spacing).isActive = true
    emailField.leadingAnchor.constraint(equalTo: topContainer.leadingAnchor, constant: spacing).isActive = true
    emailField.trailingAnchor.constraint(equalTo: topContainer.trailingAnchor, constant: -spacing).isActive = true
    emailField.bottomAnchor.constraint(equalTo: topContainer.bottomAnchor, constant: -spacing).isActive = true

    /**Mail and clear button on eitherisde of textField*/
    let mailView = UIImageView.init(frame: CGRect.init(x: 0, y: 0, width: 15, height: 15)) // Chaning the GREct has no effect on the size!!
    mailView.image = UIImage.init(named: "mailGrayFilled")
    emailField.leftView = mailView
    emailField.leftViewMode = .always
    emailField.clearButtonMode = .always

    view.addSubview(topContainer)
    topContainer.topAnchor.constraint(equalTo: s.topAnchor, constant: spacing).isActive = true
    topContainer.leadingAnchor.constraint(equalTo: s.leadingAnchor, constant: spacing).isActive = true
    topContainer.trailingAnchor.constraint(equalTo: s.trailingAnchor, constant: -spacing).isActive = true

Body:
Putting the UIImageView into a Container UIView seems to fix the issue when I test your code.  This may also allow you to adjust the padding to suit your needs.

let iconContainer = UIView(frame: CGRect(x: 0, y: 0, width: 25, height: 15))
let mailView = UIImageView(frame: CGRect(x: 0, y: 0, width: 15, height: 15))
mailView.image = UIImage(named: "mailGrayFilled")
mailView.contentMode = .scaleAspectFit
iconContainer.addSubview(mailView)
emailField.leftViewMode = .always
emailField.leftView = iconContainer
emailField.clearButtonMode = .always


来源: stackexchange

问:
SimpleXML - How do I use an attribute as a selector?
Given this XML:

```<code><?php
$xml = <<<XML
<?xml version="1.0" encoding="UTF-8" ?>
    <root>
        <project type="residential">
            <item>
                <description><![CDATA[Node 1 text]]></description>
            </item>
            <item>
                <description><![CDATA[Node 2 text]]></description>
            </item>
        </project>
    </root>
XML;
?>
</code>```

I would like to list the content of all of the of the  fields.

This is what I have. It fails with an error "member function xpath() on a non-object".

```<code>// load xml file
include 'xml/portfolio_xml.php';
$portfolio = simplexml_load_string($xml);

foreach ($portfolio->xpath('//project[@type="residential"]/item') as $item) {
    echo $item->description;
}
</code>```

UPDATE

Actually, this example does work. Obviously pulling the sample out of the context of the rest of my application was what I needed.

答:
You need to check that simple_xml_load_string succeeded. Its failing right now because $portfolio isnt an object.

This is partially why i prefer using the real constructor instead of the function. I prefer to catch exceptions and handle errors that way:

```<code>try
{
  $portfolio = new SimpleXmlElement($xml);

  foreach ($portfolio->xpath('//project[@type="residential"]/item') as $item) {
    echo $item->description;
  }
}
catch(Exception $e)
{
  // do something.. or nothing on an error
}
</code>```

This way not only can you handle the error but you can take specific action based on the Exception type, code, message, or all of the above.

Additionally, depending on the type of errors you may want to keep them internal to libxml.

ContentLicense: CC BY-SA 3.0

Body:
Given this XML:

<?php
$xml = <<<XML
<?xml version="1.0" encoding="UTF-8" ?>
    <root>
        <project type="residential">
            <item>
                <description><![CDATA[Node 1 text]]></description>
            </item>
            <item>
                <description><![CDATA[Node 2 text]]></description>
            </item>
        </project>
    </root>
XML;
?>

I would like to list the content of all of the of the  fields.

This is what I have. It fails with an error "member function xpath() on a non-object".

// load xml file
include 'xml/portfolio_xml.php';
$portfolio = simplexml_load_string($xml);

foreach ($portfolio->xpath('//project[@type="residential"]/item') as $item) {
    echo $item->description;
}

UPDATE

Actually, this example does work. Obviously pulling the sample out of the context of the rest of my application was what I needed.

Body:
You need to check that simple_xml_load_string succeeded. Its failing right now because $portfolio isnt an object.

This is partially why i prefer using the real constructor instead of the function. I prefer to catch exceptions and handle errors that way:

try
{
  $portfolio = new SimpleXmlElement($xml);

  foreach ($portfolio->xpath('//project[@type="residential"]/item') as $item) {
    echo $item->description;
  }
}
catch(Exception $e)
{
  // do something.. or nothing on an error
}

This way not only can you handle the error but you can take specific action based on the Exception type, code, message, or all of the above.

Additionally, depending on the type of errors you may want to keep them internal to libxml.


问:
How to filter duplicate types from tuple C++
How does one filter duplicate types from a tuple?

For example:

```<code>using Tuple = std::tuple<int, double, int, double, std::string, std::string>
using FilteredTuple = without_duplicates<Tuple>;
</code>```

In which without_duplicates is implemented in such a way that it generates the following FilteredTuple type:

```<code>std::tuple<int, double, std::string>
</code>```

答:
Piotr's code is very concise and should be prefered. Here an extended version for general variadic templated classes which works on C++17 (e.g. std::variant or custom containers):

#include <type_traits>

// end of recursive call: tuple is forwared using `type`
template <typename T, typename... Ts>
struct unique_impl {using type = T;};

// recursive call: 1. Consumes the first type of the variadic arguments,
//                    if not repeated add it to the tuple.
//                 2. Call this again with the rest of arguments
template <template<class...> class Tuple, typename... Ts, typename U, typename... Us>
struct unique_impl<Tuple<Ts...>, U, Us...>
    : std::conditional_t<(std::is_same_v || ...)
                       , unique_impl<Tuple<Ts...>, Us...>
                       , unique_impl<Tuple<Ts..., U>, Us...>> {};

// forward definition
template <class Tuple>
struct unique_tuple;

// class specialization so that tuple arguments can be extracted from type
template <template<class...>class Tuple, typename... Ts>
struct unique_tuple<Tuple<Ts...>> : public unique_impl<Tuple<>, Ts...> {};
```

Live Demo

If you need C++11 you just need to replace the fold expression (std::is_same_v || ...) to use a self-made disjunction<...> (see cppreference possible implementation).

ContentLicense: CC BY-SA 4.0

Body:
How does one filter duplicate types from a tuple?

For example:

using Tuple = std::tuple<int, double, int, double, std::string, std::string>
using FilteredTuple = without_duplicates<Tuple>;

In which without_duplicates is implemented in such a way that it generates the following FilteredTuple type:

std::tuple<int, double, std::string>

Body:
Piotr's code is very concise and should be prefered. Here an extended version for general variadic templated classes which works on C++17 (e.g. std::variant or custom containers):

#include <type_traits>

// end of recursive call: tuple is forwared using `type`
template <typename T, typename... Ts>
struct unique_impl {using type = T;};

// recursive call: 1. Consumes the first type of the variadic arguments,
//                    if not repeated add it to the tuple.
//                 2. Call this again with the rest of arguments
template <template<class...> class Tuple, typename... Ts, typename U, typename... Us>
struct unique_impl<Tuple<Ts...>, U, Us...>
    : std::conditional_t<(std::is_same_v<U, Ts> || ...)
                       , unique_impl<Tuple<Ts...>, Us...>
                       , unique_impl<Tuple<Ts..., U>, Us...>> {};

// forward definition
template <class Tuple>
struct unique_tuple;

// class specialization so that tuple arguments can be extracted from type
template <template<class...>class Tuple, typename... Ts>
struct unique_tuple<Tuple<Ts...>> : public unique_impl<Tuple<>, Ts...> {};

Live Demo

If you need C++11 you just need to replace the fold expression (std::is_same_v<U, Ts> || ...) to use a self-made disjunction<...> (see cppreference possible implementation).


问:
Change JavaFX 11 implementation in IntelliJ from "build and run with jvm options inside IDE" to "create runtime image"

EDIT #3 (SOLUTION)

I have solved this issue using none of the proposed answers. At the end of this I have some folders and files that I can zip and send around, that do not require a java installation and that can be run by double-clicking a .bat-file. The following procedure worked for me:

Create a new gradle project from scratch

Add all modules/code into the src/main/java folder

create an AppLauncher.java that calls the main-method

move all fxml/css from inside one of the java-folders to the resources-folder

make sure your calls to fxml-/css-files are not being refactored erroneously and use the following code:

//Main start method
Parent root = FXMLLoader.load(new File("fxml/main.fxml").toURI().toURL());

//Other FXML loading operations
FXMLLoader loader = null;
try { loader = new FXMLLoader(new File("fxml/GRAPHISO_proof.fxml").toURI().toURL()); }
...
```

<p>and for stylesheets:</p>

<pre class="lang-java prettyprint-override"><code>scene.getStylesheets().add("file:///" + new File("css/text-field-red-border.css").getAbsolutePath().replace('\\', '/'));
</code>```

create module-info.java inside of src/main/java folder with this structure:

module XYZ {
    requires javafx.controls;
    requires javafx.graphics;
    requires java.desktop;
    requires javafx.fxml;
    requires javafx.base;

    opens main.controller to javafx.fxml;
    //Open ALL controller-modules (all of my modules have a controller-submodule, e.g. main/controller, dlog/controller, graphiso/controller, ...) to javafx.fxml
    //...

    exports main;
}
```

<ul>
<li><p>make sure gradle/wrapper/gradle-wrapper.properties is set to a not-so-old version of gradle (<code>distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-bin.zip</code>)</p></li>
<li><p>use this as your build.gradle:</p></li>
</ul>

```buildscript {
    repositories {
        maven {
            url "https://plugins.gradle.org/m2/"
        }
    }
    dependencies {
        classpath 'org.openjfx:javafx-plugin:0.0.8'
        classpath 'com.github.jengelman.gradle.plugins:shadow:5.2.0'
    }
}

plugins {
    id 'java'
    id 'org.beryx.jlink' version '2.19.0'
}

apply plugin: 'org.openjfx.javafxplugin'
apply plugin: 'com.github.johnrengelman.shadow'

group 'org.example.abc'
version '1.0'

sourceCompatibility = 1.14

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

javafx {
    sdk = 'C:\\Program Files\\Java\\javafx-sdk-14.0.1'
    modules = [ 'javafx.controls', 'javafx.fxml', 'javafx.base' ]
}

jlink {
    mainClassName = 'main.AppLauncher'
    launcher {
        name = 'Whatever you want as name'
    }
}

tasks.jlink.doLast {
    copy {
        from('src/main/resources')
        into("$buildDir/image/bin")
    }
    copy {
        from 'C:\\Program Files\\Java\\javafx-sdk-14.0.1\\bin\\glass.dll',
             'C:\\Program Files\\Java\\javafx-sdk-14.0.1\\bin\\javafx_font.dll',
             'C:\\Program Files\\Java\\javafx-sdk-14.0.1\\bin\\prism_d3d.dll',
             'C:\\Program Files\\Java\\javafx-sdk-14.0.1\\bin\\prism_sw.dll'
        into("$buildDir/image/bin")
    }
}
```

Note how I included some dll-files in tasks.jlink.doLast. Without them, the program keeps crashing and refers to the QuantumRenderer.

install openjdk-14.0.1 binaries and set your %JAVA_HOME% accordingly, also install openjfx-14.0.1 (program needs some DLLs as mentioned above)

Original Question

I am trying to create a runtime image from a project that I have implemented in JavaFX 11 by just using the "run configuration" functionality in IntelliJ. It seems to me a big problem here is that my knowledge of maven/gradle are almost non-existent and that those build tools are crucial for this step.

Inside of C:\Program Files\Java I've installed:

javafx-sdk-11.0.2 and

jdk-13.0.2

I configured the VM options inside IntellJ's "run configuration" to be --module-path "C:\Program Files\Java\javafx-sdk-11.0.2\lib" --add-modules javafx.controls,javafx.fxml and set the Main Class to "main.Main".

My project structure looks like this: Project folder structure

The highlighted Main.java is an usual Main-file (extending Application, calling launch(args) inside of main). It can load other windows located in the other packages. It is not a Launcher-file that doesn't extend Application and calls the actual main-file (as suggested by a few solutions for gradle-building).

Initially I've tried to get a .jar-file that can be run without any further parameters on Windows and Linux. After some reading I figured that this wouldn't be a clean solution and a lot of sources stated that in modern solutions the .jar-files will be put together and shipped with a .bat/.sh file that includes all necessary parameters.

My question is: How do I best proceed and which configurations/additional files do I need to transform this "click-to-run-inside-IDE" project into an "standalone-application" that I can share through e-mail or similar?

I have tried to create a new gradle project through IntelliJ (following https://openjfx.io/openjfx-docs) and copy-pasted the source files into src/main/java. I then tried out the provided build.gradle-file and - after that didn't work - made some changes suggested by various blogs/forums/etc. None of them allowed me to run the project through IntelliJ or from the command line.

Most of these approaches let me build the project but when trying to run using either "gradlew run" or calling the "java -jar file.jar" I got error messages due to class exceptions or saying I am still missing the javafx modules. I've also tried an approach to convert my current project into a gradle-project but that wouldn't even let me build the project afterwards.

EDIT #1 (JPackageScriptFX)

I have looked at the JPackageScriptFX-link. Now I am getting an installer (using mvn clean install) that works on my machine, but when running the resulting executable, I receive an error message that says "Failed to launch JVM".

What I have done so far is:

installed jdk-14.0.1 and set JAVA_HOME, installed wix311

created a new IntelliJ maven project called "bachelor_maven"

removed initial src-folder

added new module "ZKP_Inspector" and my old modules inside of the resulting src/main/java folder

added and edited src/main/logo/windows/duke.ico, the two pom.xml files and build_app.bat from JPackageScriptFX

implemented AppLauncher.java that calls Main.java

My configuration files:

New project structure: Imgur

pom.xml (Project level, bachelor_maven): Pastebin

pom.xml (module level, ZKP_Inspector): Pastebin

build_app.bat: Pastebin

EDIT #2

I tried removing --runtime-image target/java-runtime ^ from the jpackage parameters in the build_app.bat file as to let jpackage decide what to include. This increased the file size of the installer (as expected) but lead to the same error when trying to execute the resulting program.

I have also downloaded the JMOD files and used them in the jlink task in the build_app.bat as hinted here.

So I replaced --add-modules %detected_modules%,%manual_modules% ^ with

--module-path "C:\Program Files\Java\javafx-jmods-11.0.2" --add-modules %detected_modules%,%manual_modules%,javafx.controls,javafx.fxml

This produced another installer that ran fine and whose resulting program threw the same error.

答:
I have solved this issue using an almost self-built solution now. At the end of this I have some folders and files that I can zip and send around, that do not require a java installation and that can be run by double-clicking a .bat-file. The following procedure worked for me:

Create a new gradle project from scratch

Add all modules/code into the src/main/java folder

create an AppLauncher.java that calls the main-method

move all fxml/css from inside one of the java-folders to the resources-folder

make sure your calls to fxml-/css-files are not being refactored erroneously and use the following code:

//Main start method
Parent root = FXMLLoader.load(new File("fxml/main.fxml").toURI().toURL());

//Other FXML loading operations
FXMLLoader loader = null;
try { loader = new FXMLLoader(new File("fxml/GRAPHISO_proof.fxml").toURI().toURL()); }
...
```

<p>and for stylesheets:</p>

<pre class="lang-java prettyprint-override"><code>scene.getStylesheets().add("file:///" + new File("css/text-field-red-border.css").getAbsolutePath().replace('\\', '/'));
</code>```

create module-info.java inside of src/main/java folder with this structure:

module XYZ {
    requires javafx.controls;
    requires javafx.graphics;
    requires java.desktop;
    requires javafx.fxml;
    requires javafx.base;

    opens main.controller to javafx.fxml;
    //Open ALL controller-modules (all of my modules have a controller-submodule, e.g. main/controller, dlog/controller, graphiso/controller, ...) to javafx.fxml
    //...

    exports main;
}
```

<ul>
<li><p>make sure gradle/wrapper/gradle-wrapper.properties is set to a not-so-old version of gradle (<code>distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-bin.zip</code>)</p></li>
<li><p>use this as your build.gradle:</p></li>
</ul>

```buildscript {
    repositories {
        maven {
            url "https://plugins.gradle.org/m2/"
        }
    }
    dependencies {
        classpath 'org.openjfx:javafx-plugin:0.0.8'
        classpath 'com.github.jengelman.gradle.plugins:shadow:5.2.0'
    }
}

plugins {
    id 'java'
    id 'org.beryx.jlink' version '2.19.0'
}

apply plugin: 'org.openjfx.javafxplugin'
apply plugin: 'com.github.johnrengelman.shadow'

group 'org.example.abc'
version '1.0'

sourceCompatibility = 1.14

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

javafx {
    sdk = 'C:\\Program Files\\Java\\javafx-sdk-14.0.1'
    modules = [ 'javafx.controls', 'javafx.fxml', 'javafx.base' ]
}

jlink {
    mainClassName = 'main.AppLauncher'
    launcher {
        name = 'Whatever you want as name'
    }
}

tasks.jlink.doLast {
    copy {
        from('src/main/resources')
        into("$buildDir/image/bin")
    }
    copy {
        from 'C:\\Program Files\\Java\\javafx-sdk-14.0.1\\bin\\glass.dll',
             'C:\\Program Files\\Java\\javafx-sdk-14.0.1\\bin\\javafx_font.dll',
             'C:\\Program Files\\Java\\javafx-sdk-14.0.1\\bin\\prism_d3d.dll',
             'C:\\Program Files\\Java\\javafx-sdk-14.0.1\\bin\\prism_sw.dll'
        into("$buildDir/image/bin")
    }
}
```

Note how I included some dll-files in tasks.jlink.doLast. Without them, the program keeps crashing and refers to the QuantumRenderer.

install openjdk-14.0.1 binaries and set your %JAVA_HOME% accordingly, also install openjfx-14.0.1 (program needs some DLLs as mentioned above)

Body:
EDIT #3 (SOLUTION)

I have solved this issue using none of the proposed answers. At the end of this I have some folders and files that I can zip and send around, that do not require a java installation and that can be run by double-clicking a .bat-file. The following procedure worked for me:

Create a new gradle project from scratch

Add all modules/code into the src/main/java folder

create an AppLauncher.java that calls the main-method

move all fxml/css from inside one of the java-folders to the resources-folder

make sure your calls to fxml-/css-files are not being refactored erroneously and use the following code:

//Main start method
Parent root = FXMLLoader.load(new File("fxml/main.fxml").toURI().toURL());

//Other FXML loading operations
FXMLLoader loader = null;
try { loader = new FXMLLoader(new File("fxml/GRAPHISO_proof.fxml").toURI().toURL()); }
...

and for stylesheets:

scene.getStylesheets().add("file:///" + new File("css/text-field-red-border.css").getAbsolutePath().replace('\\', '/'));

create module-info.java inside of src/main/java folder with this structure:

module XYZ {
    requires javafx.controls;
    requires javafx.graphics;
    requires java.desktop;
    requires javafx.fxml;
    requires javafx.base;

    opens main.controller to javafx.fxml;
    //Open ALL controller-modules (all of my modules have a controller-submodule, e.g. main/controller, dlog/controller, graphiso/controller, ...) to javafx.fxml
    //...

    exports main;
}

make sure gradle/wrapper/gradle-wrapper.properties is set to a not-so-old version of gradle (distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-bin.zip)

use this as your build.gradle:

buildscript {
    repositories {
        maven {
            url "https://plugins.gradle.org/m2/"
        }
    }
    dependencies {
        classpath 'org.openjfx:javafx-plugin:0.0.8'
        classpath 'com.github.jengelman.gradle.plugins:shadow:5.2.0'
    }
}

plugins {
    id 'java'
    id 'org.beryx.jlink' version '2.19.0'
}

apply plugin: 'org.openjfx.javafxplugin'
apply plugin: 'com.github.johnrengelman.shadow'

group 'org.example.abc'
version '1.0'

sourceCompatibility = 1.14

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

javafx {
    sdk = 'C:\\Program Files\\Java\\javafx-sdk-14.0.1'
    modules = [ 'javafx.controls', 'javafx.fxml', 'javafx.base' ]
}

jlink {
    mainClassName = 'main.AppLauncher'
    launcher {
        name = 'Whatever you want as name'
    }
}

tasks.jlink.doLast {
    copy {
        from('src/main/resources')
        into("$buildDir/image/bin")
    }
    copy {
        from 'C:\\Program Files\\Java\\javafx-sdk-14.0.1\\bin\\glass.dll',
             'C:\\Program Files\\Java\\javafx-sdk-14.0.1\\bin\\javafx_font.dll',
             'C:\\Program Files\\Java\\javafx-sdk-14.0.1\\bin\\prism_d3d.dll',
             'C:\\Program Files\\Java\\javafx-sdk-14.0.1\\bin\\prism_sw.dll'
        into("$buildDir/image/bin")
    }
}

Note how I included some dll-files in tasks.jlink.doLast. Without them, the program keeps crashing and refers to the QuantumRenderer.

install openjdk-14.0.1 binaries and set your %JAVA_HOME% accordingly, also install openjfx-14.0.1 (program needs some DLLs as mentioned above)

Original Question

I am trying to create a runtime image from a project that I have implemented in JavaFX 11 by just using the "run configuration" functionality in IntelliJ. It seems to me a big problem here is that my knowledge of maven/gradle are almost non-existent and that those build tools are crucial for this step.

Inside of C:\Program Files\Java I've installed:

javafx-sdk-11.0.2 and

jdk-13.0.2

I configured the VM options inside IntellJ's "run configuration" to be --module-path "C:\Program Files\Java\javafx-sdk-11.0.2\lib" --add-modules javafx.controls,javafx.fxml and set the Main Class to "main.Main".

My project structure looks like this: Project folder structure

The highlighted Main.java is an usual Main-file (extending Application, calling launch(args) inside of main). It can load other windows located in the other packages. It is not a Launcher-file that doesn't extend Application and calls the actual main-file (as suggested by a few solutions for gradle-building).

Initially I've tried to get a .jar-file that can be run without any further parameters on Windows and Linux. After some reading I figured that this wouldn't be a clean solution and a lot of sources stated that in modern solutions the .jar-files will be put together and shipped with a .bat/.sh file that includes all necessary parameters.

My question is: How do I best proceed and which configurations/additional files do I need to transform this "click-to-run-inside-IDE" project into an "standalone-application" that I can share through e-mail or similar?

I have tried to create a new gradle project through IntelliJ (following https://openjfx.io/openjfx-docs) and copy-pasted the source files into src/main/java. I then tried out the provided build.gradle-file and - after that didn't work - made some changes suggested by various blogs/forums/etc. None of them allowed me to run the project through IntelliJ or from the command line.

Most of these approaches let me build the project but when trying to run using either "gradlew run" or calling the "java -jar file.jar" I got error messages due to class exceptions or saying I am still missing the javafx modules. I've also tried an approach to convert my current project into a gradle-project but that wouldn't even let me build the project afterwards.

EDIT #1 (JPackageScriptFX)

I have looked at the JPackageScriptFX-link. Now I am getting an installer (using mvn clean install) that works on my machine, but when running the resulting executable, I receive an error message that says "Failed to launch JVM".

What I have done so far is:

installed jdk-14.0.1 and set JAVA_HOME, installed wix311

created a new IntelliJ maven project called "bachelor_maven"

removed initial src-folder

added new module "ZKP_Inspector" and my old modules inside of the resulting src/main/java folder

added and edited src/main/logo/windows/duke.ico, the two pom.xml files and build_app.bat from JPackageScriptFX

implemented AppLauncher.java that calls Main.java

My configuration files:

New project structure: Imgur

pom.xml (Project level, bachelor_maven): Pastebin

pom.xml (module level, ZKP_Inspector): Pastebin

build_app.bat: Pastebin

EDIT #2

I tried removing --runtime-image target/java-runtime ^ from the jpackage parameters in the build_app.bat file as to let jpackage decide what to include. This increased the file size of the installer (as expected) but lead to the same error when trying to execute the resulting program.

I have also downloaded the JMOD files and used them in the jlink task in the build_app.bat as hinted here.

So I replaced --add-modules %detected_modules%,%manual_modules% ^ with

--module-path "C:\Program Files\Java\javafx-jmods-11.0.2" --add-modules %detected_modules%,%manual_modules%,javafx.controls,javafx.fxml

This produced another installer that ran fine and whose resulting program threw the same error.

Body:
I have solved this issue using an almost self-built solution now. At the end of this I have some folders and files that I can zip and send around, that do not require a java installation and that can be run by double-clicking a .bat-file. The following procedure worked for me:

Create a new gradle project from scratch

Add all modules/code into the src/main/java folder

create an AppLauncher.java that calls the main-method

move all fxml/css from inside one of the java-folders to the resources-folder

make sure your calls to fxml-/css-files are not being refactored erroneously and use the following code:

//Main start method
Parent root = FXMLLoader.load(new File("fxml/main.fxml").toURI().toURL());

//Other FXML loading operations
FXMLLoader loader = null;
try { loader = new FXMLLoader(new File("fxml/GRAPHISO_proof.fxml").toURI().toURL()); }
...

and for stylesheets:

scene.getStylesheets().add("file:///" + new File("css/text-field-red-border.css").getAbsolutePath().replace('\\', '/'));

create module-info.java inside of src/main/java folder with this structure:

module XYZ {
    requires javafx.controls;
    requires javafx.graphics;
    requires java.desktop;
    requires javafx.fxml;
    requires javafx.base;

    opens main.controller to javafx.fxml;
    //Open ALL controller-modules (all of my modules have a controller-submodule, e.g. main/controller, dlog/controller, graphiso/controller, ...) to javafx.fxml
    //...

    exports main;
}

make sure gradle/wrapper/gradle-wrapper.properties is set to a not-so-old version of gradle (distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-bin.zip)

use this as your build.gradle:

buildscript {
    repositories {
        maven {
            url "https://plugins.gradle.org/m2/"
        }
    }
    dependencies {
        classpath 'org.openjfx:javafx-plugin:0.0.8'
        classpath 'com.github.jengelman.gradle.plugins:shadow:5.2.0'
    }
}

plugins {
    id 'java'
    id 'org.beryx.jlink' version '2.19.0'
}

apply plugin: 'org.openjfx.javafxplugin'
apply plugin: 'com.github.johnrengelman.shadow'

group 'org.example.abc'
version '1.0'

sourceCompatibility = 1.14

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

javafx {
    sdk = 'C:\\Program Files\\Java\\javafx-sdk-14.0.1'
    modules = [ 'javafx.controls', 'javafx.fxml', 'javafx.base' ]
}

jlink {
    mainClassName = 'main.AppLauncher'
    launcher {
        name = 'Whatever you want as name'
    }
}

tasks.jlink.doLast {
    copy {
        from('src/main/resources')
        into("$buildDir/image/bin")
    }
    copy {
        from 'C:\\Program Files\\Java\\javafx-sdk-14.0.1\\bin\\glass.dll',
             'C:\\Program Files\\Java\\javafx-sdk-14.0.1\\bin\\javafx_font.dll',
             'C:\\Program Files\\Java\\javafx-sdk-14.0.1\\bin\\prism_d3d.dll',
             'C:\\Program Files\\Java\\javafx-sdk-14.0.1\\bin\\prism_sw.dll'
        into("$buildDir/image/bin")
    }
}

Note how I included some dll-files in tasks.jlink.doLast. Without them, the program keeps crashing and refers to the QuantumRenderer.

install openjdk-14.0.1 binaries and set your %JAVA_HOME% accordingly, also install openjfx-14.0.1 (program needs some DLLs as mentioned above)


问:
pyautogui to detect the button change
pyautogui works well when using it to click on the buttons (of a software ) on the screen
but is there any way to detect the change in button state, because when the first click is completed and the required task is accomplished then the button disappears and a new "yes" button appears and if the task is not accomplished then the "NO" button appears , the problem is , both buttons appear at the same x and y coordinates i mean either yes or no appears at that place , is there any way to find out if yes appeared or no appeared? and then clicking if yes appeared ?</p>

答:
You can use image recognition technique in pyautogui package.
You can use locateOnScreen function of pyautogui. First you can screenshot and save yes and no button image. You crop the image tightly around the button.
And then save them into "yes.png", and "no.png" respectively.
And then,</p>

```<code>btnYesButton = None
btnNoButton = None
while btnYesButton == None and btnNoButton == None:
    btnYesButton = pyautogui.locateOnScreen("yes.png")
    btnNoButton = pyautogui.locateOnScreen("no.png")
if btnYesButton:
    tmpCenter = pyautogui.center(btnYesButton)
    pyautogui.click(tmpCenter)
</code>```

Title: pyautogui to detect the button change

Body:
You can use image recognition technique in pyautogui package.
You can use locateOnScreen function of pyautogui. First you can screenshot and save yes and no button image. You crop the image tightly around the button.
And then save them into "yes.png", and "no.png" respectively.
And then,

btnYesButton = None
btnNoButton = None
while btnYesButton == None and btnNoButton == None:
    btnYesButton = pyautogui.locateOnScreen("yes.png")
    btnNoButton = pyautogui.locateOnScreen("no.png")
if btnYesButton:
    tmpCenter = pyautogui.center(btnYesButton)
    pyautogui.click(tmpCenter)


问:
When should we go for Spark-sql and when should we go for Spark RDD
On which scenario we should prefer spark RDD to write a solution and on which scenario we should choose to go for spark-sql. I know spark-sql gives better performance and it works best with structure and semistructure data. But what else factors are there that we need to take into consideration while choosing betweeen spark Rdd and spark-sql.</p>

答:
I found using DFs easier to use than DSs - the latter are still subject to development imho. The comment on pyspark indeed still relevant.

RDDs still handy for zipWithIndex to put asc, contiguous sequence numbers on items.

DFs / DSs have a columnar store and have a better Catalyst (Optimizer) support.

Also, may things with RDDs are painful, like a JOIN requiring a key, value and multi-step join if needing to JOIN more than 2 tables. They are legacy. Problem is the internet is full of legacy and thus RDD jazz.


问:
Update functions in Hash Table in Racket
I am a beginner in Racket and I am trying to updare a hash table using hash-update! where the value is a mutable set. Below are the code lines:

```<code>(hash-update! hash key (curryr set-add! new_val) (mutable-set 1))
</code>```

However I receive an error

```<code> expected: set?
given: #<void>
argument position: 1st
other arguments...:
  x: 2
</code>```

where I tried 2 as the new_val

Any suggestions ?

答:
This is because the updater is supposed to be a function that takes a value as input and produces a new value output. Since the set is mutable and you're using set-add! to mutate it, the "updater" isn't returning a new value, just mutating the old one and producing void.

There are two ways to fix this:

Mutable sets as values, mutate them separately, not inside hash-update!.

Immutable sets as values, use a functional updater inside hash-update!.

Since you specified you want the values as mutable sets, I will show (1).

The most basic thing you can do is hash-ref to get a mutable-set, and then use set-add! on that.

```<code>(set-add! (hash-ref hash key) new-val)
</code>```

However, this doesn't work when there is no mutable-set value for that key yet. It needs to be added to the table when it doesn't exist yet which why is why you have the (mutable-set 1) failure-result argument. The solution to this isn't hash-update!, it's hash-ref!.

```<code>(set-add! (hash-ref! hash key (mutable-set 1)) new-val)
</code>```

Although it would probably be better if you wrapped the failure-result in a thunk

```<code>(set-add! (hash-ref! hash key (λ () (mutable-set 1))) new-val)
</code>```

Body:
I am a beginner in Racket and I am trying to updare a hash table using hash-update! where the value is a mutable set. Below are the code lines:

(hash-update! hash key (curryr set-add! new_val) (mutable-set 1))

However I receive an error

 expected: set?
given: #<void>
argument position: 1st
other arguments...:
  x: 2

where I tried 2 as the new_val

Any suggestions ?

Body:
This is because the updater is supposed to be a function that takes a value as input and produces a new value output. Since the set is mutable and you're using set-add! to mutate it, the "updater" isn't returning a new value, just mutating the old one and producing void.

There are two ways to fix this:

Mutable sets as values, mutate them separately, not inside hash-update!.

Immutable sets as values, use a functional updater inside hash-update!.

Since you specified you want the values as mutable sets, I will show (1).

The most basic thing you can do is hash-ref to get a mutable-set, and then use set-add! on that.

(set-add! (hash-ref hash key) new-val)

However, this doesn't work when there is no mutable-set value for that key yet. It needs to be added to the table when it doesn't exist yet which why is why you have the (mutable-set 1) failure-result argument. The solution to this isn't hash-update!, it's hash-ref!.

(set-add! (hash-ref! hash key (mutable-set 1)) new-val)

Although it would probably be better if you wrapped the failure-result in a thunk

(set-add! (hash-ref! hash key (λ () (mutable-set 1))) new-val)


问:
Angular Async Validator FormControls don't update until blurred
My Async Validator looks like this:

```<code>asyncValidator(service:ApiCallsService):AsyncValidatorFn{
    return (control:FormControl):Promise<ValidationErrors | null> | Observable<ValidationErrors | null> =>{
    let timer$ = timer(2000);
     return timer$.pipe(
      take(1),
      switchMap(()=> {
        let videoId = service.checkUrl(control.value);
        return service.getVideoDescription(videoId).toPromise().then((val:any)=>{

          return (!val.id) ? {"invalidUrl": true} : null;
        })
      })
    )
    }
  }
</code>```

The problem with my Async Validator is that my FormControls that are added into my FormArray do not pick up on the current 'status' of themselves until they are blurred.

This is my FormArray and my FormControl inside it:

```<code><div class="url-con" formArrayName="urls" >
    <div *ngFor="let url of urls.controls; let i=index" class="url-input-con">
        <input  minLength="5" placeholder="Video Url" class="url-input" [formControlName]="i">
        <div class="url-pending" *ngIf="urls.controls[i].pending && !urls.controls[i].valid">Validating...</div>
    </div>
</div>
</code>```

The div with the class "url-pending" appears, and then it doesn't disappear - even though the FormControl it depends upon is validated by the backend - until the user blurs the FormControl that the div depends on.

The only other stackoverflow question that is similar to this is this link. I could not fully understand the instructions of that link, and an additional complication I had compared to the poster of the link is that I have an icon in my form shaped as a plus sign so that the user can add more FormControls to the FormArray. I couldn't figure out how to add directives to the FormControls that the user added by interacting with the form.

I will answer my own question because I figured out how to solve this question, but I solved it in a 'hackish' way. If anybody else knows a better answer to this, please reply.

答:
This has to do with touched state of the form. Until control is untouched, it is treated as "maybe user did not yet finished the input".

So you was almost right about the symptoms, but there's also a simpler better way to "touch" a control.
The crucial part is usage of deafault ReactiveForm API to make the control touched. See how it was in my finalize part:

component.ts

```<code>
public emailControl = new FormControl('',
  /* sync */
  [
    control => control.value && /.+@.+/.test(control.value) ? null : { invalidEmail: true },
  ],
  /* async */
  [
    control => control.value ? this.debouncedCheck(control.value) : of(null)
  ]
);

private debouncedCheck(value): Observable<ValidationErrors> {
  // debounce (although it will be PENDING even during those 500ms!!)
  return timer(500).pipe(

    // Handle validation
    switchMap(     () => this.doAsyncCheck(value)),
    tap(checkResponse => /* ... handle validation response ... */),
    catchError( error => /* ... handle runtime errors ... */),

    // "Touch" the control since its data was already sent and used somewhere
    finalize(() => this.lookupEmail.markAsTouched()),

  );
}
</code>```

template.html

```<code><mat-form-field>
    <mat-label>Find by email</mat-label>

    <input matInput [formControl]="emailControl">
    <mat-spinner matSuffix *ngIf="emailControl.pending" [diameter]="15"></mat-spinner>

    <mat-error *ngIf="emailControl.hasError('invalidEmail')">Email is invalid</mat-error>
    <mat-error *ngIf="emailControl.hasError('noRecords')">No records found for email</mat-error>
</mat-form-field>
</code>```

I personally faced this issue when were trying to implement simple /.+@.+/ email validation.
The thing is that input should not scream at user "INVALID!!" after the first letter into writing. It should wait until input is presumably "complete": when user continues to the next input field (postal address, nickname, whatever).
When the user leaves the control it gets touched: true and all the validation is rendered (it were still computing in the background but it was not rendering exactly due to touched: false state). Now the user may come back to the touched input (and it remains touched, until state is manually reset!) and will see all validation updated in realtime.

In the example above control was invalid until it's not a "valid" email and it does not even try to do the async check (since failed with sync), but it DOES NOT SHOW IT while control it touched: false.
But when it finally something@like.this, the async check is triggered, "pending operation"-spinner appears and the control itself becomes touched: true and reveals validation results upon resolution.

Body:
My Async Validator looks like this:

asyncValidator(service:ApiCallsService):AsyncValidatorFn{
    return (control:FormControl):Promise<ValidationErrors | null> | Observable<ValidationErrors | null> =>{
    let timer$ = timer(2000);
     return timer$.pipe(
      take(1),
      switchMap(()=> {
        let videoId = service.checkUrl(control.value);
        return service.getVideoDescription(videoId).toPromise().then((val:any)=>{

          return (!val.id) ? {"invalidUrl": true} : null;
        })
      })
    )
    }
  }

The problem with my Async Validator is that my FormControls that are added into my FormArray do not pick up on the current 'status' of themselves until they are blurred.

This is my FormArray and my FormControl inside it:

        <input  minLength="5" placeholder="Video Url" class="url-input" [formControlName]="i">

Validating...

The div with the class "url-pending" appears, and then it doesn't disappear - even though the FormControl it depends upon is validated by the backend - until the user blurs the FormControl that the div depends on.

The only other stackoverflow question that is similar to this is this link. I could not fully understand the instructions of that link, and an additional complication I had compared to the poster of the link is that I have an icon in my form shaped as a plus sign so that the user can add more FormControls to the FormArray. I couldn't figure out how to add directives to the FormControls that the user added by interacting with the form.

I will answer my own question because I figured out how to solve this question, but I solved it in a 'hackish' way. If anybody else knows a better answer to this, please reply.

Body:
This has to do with touched state of the form. Until control is untouched, it is treated as "maybe user did not yet finished the input".

So you was almost right about the symptoms, but there's also a simpler better way to "touch" a control.
The crucial part is usage of deafault ReactiveForm API to make the control touched. See how it was in my finalize part:

component.ts

public emailControl = new FormControl('',
  /* sync */
  [
    control => control.value && /.+@.+/.test(control.value) ? null : { invalidEmail: true },
  ],
  /* async */
  [
    control => control.value ? this.debouncedCheck(control.value) : of(null)
  ]
);

private debouncedCheck(value): Observable<ValidationErrors> {
  // debounce (although it will be PENDING even during those 500ms!!)
  return timer(500).pipe(

    // Handle validation
    switchMap(     () => this.doAsyncCheck(value)),
    tap(checkResponse => /* ... handle validation response ... */),
    catchError( error => /* ... handle runtime errors ... */),

    // "Touch" the control since its data was already sent and used somewhere
    finalize(() => this.lookupEmail.markAsTouched()),

  );
}

template.html

<mat-form-field>
    <mat-label>Find by email</mat-label>

    <input matInput [formControl]="emailControl">
    <mat-spinner matSuffix *ngIf="emailControl.pending" [diameter]="15"></mat-spinner>

    <mat-error *ngIf="emailControl.hasError('invalidEmail')">Email is invalid</mat-error>
    <mat-error *ngIf="emailControl.hasError('noRecords')">No records found for email</mat-error>
</mat-form-field>

I personally faced this issue when were trying to implement simple /.+@.+/ email validation.
The thing is that input should not scream at user "INVALID!!" after the first letter into writing. It should wait until input is presumably "complete": when user continues to the next input field (postal address, nickname, whatever).
When the user leaves the control it gets touched: true and all the validation is rendered (it were still computing in the background but it was not rendering exactly due to touched: false state). Now the user may come back to the touched input (and it remains touched, until state is manually reset!) and will see all validation updated in realtime.

In the example above control was invalid until it's not a "valid" email and it does not even try to do the async check (since failed with sync), but it DOES NOT SHOW IT while control it touched: false.
But when it finally something@like.this, the async check is triggered, "pending operation"-spinner appears and the control itself becomes touched: true and reveals validation results upon resolution.


问:
How to Fix: TypeError: Super expression must either be null or a function
Im making a little app and connecting it with an API to retrieve some info and show it. I had seen a way of doing it in a class and wanted to try it out, but it keeps giving the following error: "TypeError: Super expression must either be null or a function".

I did make the page in App.js, which I'm not sure might be a problem or not, since I wasnt sure how to load a component/screen on launch of the app. I changed the export default function App() to class App extends React.component to be able to use a state to save the data from the api.

I already tried changing export class ShowCustomerOrders extends React.Component to export class ShowCustomerOrders extends Component. But the result doesn't change.

```<code>import React, { Component } from 'react';
import { StyleSheet, Text, View, Image } from 'react-native';
import MapScreen from './components/MapScreen';
import { createStackNavigator } from '@react-navigation/stack';
import { FlatList, TouchableOpacity } from 'react-native-gesture-handler';

const Stack = createStackNavigator();

class App extends React.component {
  constructor(){
    super();
    this.state = {
      orders: []
    };
  }

  render(){
    getOrders();
  return (
      <View style={styles.container}>
          <Image style={styles.Map} source={{
              uri: 'https://open.mapquestapi.com/staticmap/v5/map?center=eindhoven,5611DE,kerkstraat+7&locations=eindhoven,5611DE,kerkstraat+7|marker-md-FF0000-M&size=@2x&key=lYrP4vF3Uk5zgTiGGuEzQGwGIVDGuy24'
          }}/>
          <FlatList data={this.state.orders}
          renderItem={({ item }) => <ShowCustomerOrders navigation={this.props.navigation} order={item}/>}/>
      </View>
    );
  }
}

function Map(){
  return(
    <Stack.Navigator>
      <Stack.Screen name="Map" component={MapScreen}/>
    </Stack.Navigator>
  );
}

getOrders = async() =>{
  const response =
    await fetch('https://api.summa.1ku.nl/mad/oefenexamen/');
  const data = await response.json();

  this.setState({
      orders: data.orders
  });
}

export class ShowCustomerOrders extends React.Component{
  render(){
    return(
      <TouchableOpacity onPress={() => this.props.Navigation.navigate('Map', {order:this.props.order})}>
        <Text> {this.props.order.naam} </Text>
        <Text> {this.props.order.adres} </Text>
      </TouchableOpacity>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  Map: {
    width: '80%',
    height: '40%',
    bottom: '20%'
  }
});
</code>```

答:
I've noticed several mistakes in your code.

1) You must pass props to the constructor.

2) In this class method, you need to call a function with this reference.

3) In ShowCustomerOrders component, you must write the contractor with props in order to use props.

4) There was no default export in App.js

Here is the code I edited. You can check if it works.

```<code>import React, { Component } from 'react';
import { StyleSheet, Text, View, Image } from 'react-native';
import MapScreen from './components/MapScreen';
import { createStackNavigator } from '@react-navigation/stack';
import { FlatList, TouchableOpacity } from 'react-native-gesture-handler';

const Stack = createStackNavigator();

export default class App extends React.component {
  constructor(props){
    super(props);
    this.state = {
      orders: []
    };
  }

  getOrders = async() =>{
    const response =
      await fetch('https://api.summa.1ku.nl/mad/oefenexamen/');
    const data = await response.json();

    this.setState({
        orders: data.orders
    });
  }

  render(){
    this.getOrders();

    return (
        <View style={styles.container}>
            <Image style={styles.Map} source={{
                uri: 'https://open.mapquestapi.com/staticmap/v5/map?center=eindhoven,5611DE,kerkstraat+7&locations=eindhoven,5611DE,kerkstraat+7|marker-md-FF0000-M&size=@2x&key=lYrP4vF3Uk5zgTiGGuEzQGwGIVDGuy24'
            }}/>
            <FlatList data={this.state.orders}
            renderItem={({ item }) => <ShowCustomerOrders navigation={this.props.navigation} order={item}/>}/>
        </View>
      );
    }
}

function Map(){
  return(
    <Stack.Navigator>
      <Stack.Screen name="Map" component={MapScreen}/>
    </Stack.Navigator>
  );
}

export class ShowCustomerOrders extends React.Component{
  constructor(props){
    super(props);
  }

  render(){
    return(
      <TouchableOpacity onPress={() => this.props.Navigation.navigate('Map', {order:this.props.order})}>
        <Text> {this.props.order.naam} </Text>
        <Text> {this.props.order.adres} </Text>
      </TouchableOpacity>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  Map: {
    width: '80%',
    height: '40%',
    bottom: '20%'
  }
});
</code>```

I recommend you to work with hooks (uses function instead of a class) since it has a lot of advantages. With that method also, you can use states without any problem.

Body:
Im making a little app and connecting it with an API to retrieve some info and show it. I had seen a way of doing it in a class and wanted to try it out, but it keeps giving the following error: "TypeError: Super expression must either be null or a function".

I did make the page in App.js, which I'm not sure might be a problem or not, since I wasnt sure how to load a component/screen on launch of the app. I changed the export default function App() to class App extends React.component to be able to use a state to save the data from the api.

I already tried changing export class ShowCustomerOrders extends React.Component to export class ShowCustomerOrders extends Component. But the result doesn't change.

import React, { Component } from 'react';
import { StyleSheet, Text, View, Image } from 'react-native';
import MapScreen from './components/MapScreen';
import { createStackNavigator } from '@react-navigation/stack';
import { FlatList, TouchableOpacity } from 'react-native-gesture-handler';

const Stack = createStackNavigator();

class App extends React.component {
  constructor(){
    super();
    this.state = {
      orders: []
    };
  }

  render(){
    getOrders();
  return (
      <View style={styles.container}>
          <Image style={styles.Map} source={{
              uri: 'https://open.mapquestapi.com/staticmap/v5/map?center=eindhoven,5611DE,kerkstraat+7&locations=eindhoven,5611DE,kerkstraat+7|marker-md-FF0000-M&size=@2x&key=lYrP4vF3Uk5zgTiGGuEzQGwGIVDGuy24'
          }}/>
          <FlatList data={this.state.orders}
          renderItem={({ item }) => <ShowCustomerOrders navigation={this.props.navigation} order={item}/>}/>
      </View>
    );
  }
}

function Map(){
  return(
    <Stack.Navigator>
      <Stack.Screen name="Map" component={MapScreen}/>
    </Stack.Navigator>
  );
}

getOrders = async() =>{
  const response =
    await fetch('https://api.summa.1ku.nl/mad/oefenexamen/');
  const data = await response.json();

  this.setState({
      orders: data.orders
  });
}

export class ShowCustomerOrders extends React.Component{
  render(){
    return(
      <TouchableOpacity onPress={() => this.props.Navigation.navigate('Map', {order:this.props.order})}>
        <Text> {this.props.order.naam} </Text>
        <Text> {this.props.order.adres} </Text>
      </TouchableOpacity>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  Map: {
    width: '80%',
    height: '40%',
    bottom: '20%'
  }
});

Body:
I've noticed several mistakes in your code.

1) You must pass props to the constructor.

2) In this class method, you need to call a function with this reference.

3) In ShowCustomerOrders component, you must write the contractor with props in order to use props.

4) There was no default export in App.js

Here is the code I edited. You can check if it works.

import React, { Component } from 'react';
import { StyleSheet, Text, View, Image } from 'react-native';
import MapScreen from './components/MapScreen';
import { createStackNavigator } from '@react-navigation/stack';
import { FlatList, TouchableOpacity } from 'react-native-gesture-handler';

const Stack = createStackNavigator();

export default class App extends React.component {
  constructor(props){
    super(props);
    this.state = {
      orders: []
    };
  }

  getOrders = async() =>{
    const response =
      await fetch('https://api.summa.1ku.nl/mad/oefenexamen/');
    const data = await response.json();

    this.setState({
        orders: data.orders
    });
  }

  render(){
    this.getOrders();

    return (
        <View style={styles.container}>
            <Image style={styles.Map} source={{
                uri: 'https://open.mapquestapi.com/staticmap/v5/map?center=eindhoven,5611DE,kerkstraat+7&locations=eindhoven,5611DE,kerkstraat+7|marker-md-FF0000-M&size=@2x&key=lYrP4vF3Uk5zgTiGGuEzQGwGIVDGuy24'
            }}/>
            <FlatList data={this.state.orders}
            renderItem={({ item }) => <ShowCustomerOrders navigation={this.props.navigation} order={item}/>}/>
        </View>
      );
    }
}

function Map(){
  return(
    <Stack.Navigator>
      <Stack.Screen name="Map" component={MapScreen}/>
    </Stack.Navigator>
  );
}

export class ShowCustomerOrders extends React.Component{
  constructor(props){
    super(props);
  }

  render(){
    return(
      <TouchableOpacity onPress={() => this.props.Navigation.navigate('Map', {order:this.props.order})}>
        <Text> {this.props.order.naam} </Text>
        <Text> {this.props.order.adres} </Text>
      </TouchableOpacity>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  Map: {
    width: '80%',
    height: '40%',
    bottom: '20%'
  }
});

I recommend you to work with hooks (uses function instead of a class) since it has a lot of advantages. With that method also, you can use states without any problem.


问:
Securing PHP MySQL code
I have a PHP search suggestion script which uses MySQL as its back-end. I am aware there are many vunerabilities in my code, I was just wondering what I can do to make it more secure.

Here is my code:

```<code><?php
$database=new mysqli('localhost','username','password','database');
if(isset($_POST['query'])){
    $query=$database->real_escape_string($_POST['query']);
    if(strlen($query)>0){
        $suggestions=$database->query(
            "SELECT * FROM search WHERE name LIKE '%" . $query .
             "%' ORDER BY value DESC LIMIT 5");
        if($suggestions){
            while($result=$suggestions->fetch_object()){
                 echo '<a>'.$result->name.'</a>';
            }
        }
    }
}
?>
</code>```

答:
Some tips from me:

use PDO,

don't concatenate query parameters, use prepared statements in PDO,

don't put "*" in SELECT statement, get only the columns you'll need,

use fetchAll() in PDO, don't fetch records in while() loop.

Title: Securing PHP MySQL code

Body:
I have a PHP search suggestion script which uses MySQL as its back-end. I am aware there are many vunerabilities in my code, I was just wondering what I can do to make it more secure.

Here is my code:

<?php
$database=new mysqli('localhost','username','password','database');
if(isset($_POST['query'])){
    $query=$database->real_escape_string($_POST['query']);
    if(strlen($query)>0){
        $suggestions=$database->query(
            "SELECT * FROM search WHERE name LIKE '%" . $query .
             "%' ORDER BY value DESC LIMIT 5");
        if($suggestions){
            while($result=$suggestions->fetch_object()){
                 echo ''.$result->name.'';
            }
        }
    }
}
?>


问:
How to get the argmax of last 2 axes?
Let's say I have an array which it's dimensions are 10 X 20 X 12 X 12 X 2 X 2. What should I do if I want to get the maximum values indices of the last two axes? meaning I want a function which will output (if the described array is the input) an array of shape: 10 X 20 X 12 X 12. So (array is the described array):

array[indices] == np.amax(array, (-2,-1))

答:
A simple solution is to call the function twice, once for each axis:

```<code>A = np.arange(1000).reshape((10,10,10))
np.amax(np.amax(A, axis=-1), axis=-1)
</code>```

For np.argmax you can basically do the same. But of course the indices are  changing. You need to correct for this.

Title: How to get the argmax of last 2 axes?

Body:
A simple solution is to call the function twice, once for each axis:

A = np.arange(1000).reshape((10,10,10))
np.amax(np.amax(A, axis=-1), axis=-1)

For np.argmax you can basically do the same. But of course the indices are  changing. You need to correct for this.


问:
Apexcharts - Label colours do not match
I've assigned three different colours to the labels, but the colour dots always show up as Blue, Green and Yellow. I'm pretty sure I've done something wrong.

The code I've written is:

```<code>var pieSimpleChart = {
  chart: {
    height: 350,
    type: 'pie',
  },
  legend: {
    position: 'bottom'
  },
  labels: ["IT", "Product Development", "Sales"],
  series: [2, 2, 6],
  fill: {
    colors: ["#447b40", "#cc7870", "#e74ce4"]
  }
}

var chart = new ApexCharts(document.querySelector("#task-pie-chart"), pieSimpleChart);
chart.render();
</code>```

How can I match the labels to my selected colours?

答:
I fixed it by removing "fill" option.
Now code looks like: </p>

```<code>    var pieSimpleChart =
    {
        chart:
        {
            height: 350,
            type: 'pie',
        },
        legend:
        {
            position: 'bottom'
        },
        labels: ["IT", "Product Development", "Sales"],
        series: [2, 2, 6],
        colors: ["#447b40", "#cc7870", "#e74ce4"]
    }
</code>```

Title: Apexcharts - Label colours do not match

Body:
I've assigned three different colours to the labels, but the colour dots always show up as Blue, Green and Yellow. I'm pretty sure I've done something wrong.

The code I've written is:

var pieSimpleChart = {
  chart: {
    height: 350,
    type: 'pie',
  },
  legend: {
    position: 'bottom'
  },
  labels: ["IT", "Product Development", "Sales"],
  series: [2, 2, 6],
  fill: {
    colors: ["#447b40", "#cc7870", "#e74ce4"]
  }
}

var chart = new ApexCharts(document.querySelector("#task-pie-chart"), pieSimpleChart);
chart.render();

How can I match the labels to my selected colours?

Body:
I fixed it by removing "fill" option.
Now code looks like:

    var pieSimpleChart =
    {
        chart:
        {
            height: 350,
            type: 'pie',
        },
        legend:
        {
            position: 'bottom'
        },
        labels: ["IT", "Product Development", "Sales"],
        series: [2, 2, 6],
        colors: ["#447b40", "#cc7870", "#e74ce4"]
    }


问:
Keras fit and datagenerator return "Error when checking input: expected input_1 to have 3 dimensions, but got array with shape (None, 1)"
I am trying to create a generator using a dataframe stored in pickle. The targets are 3 columns whith their name starting by "target". The features are stored in the "input" column. Each cell of "input" are np.array. Their dimensions are 51x7 (7 is the number of channels).
(I am trying to just focus on the datagenerator for now)

```<code># General Libraries
import os
import math
import pickle
import numpy as np
import pandas as pd
from numpy import random

# Tensorflow and Keras
import tensorflow as tf
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.models import Model
from tensorflow.keras.utils import Sequence
from tensorflow.keras.layers import Input, Conv1D, Dense, Dropout, MaxPooling1D, Flatten

# Project Libraries
import config

class DataGenerator(Sequence):
    def __init__(self, path_experiment, batch_size, mode='train', validation_ratio=0.1):
        self.path_pickle = os.path.join(path_experiment, 'dataframe.pkl')
        self.dataframe = self.load_dataframe()
        self.batch_size = batch_size
        self.mode = mode
        self.indexes = None

        if mode == 'validation':
            self.dataframe = self.dataframe[-int(len(self.dataframe) * validation_ratio):].copy()
        else:
            self.dataframe = self.dataframe[:-int(len(self.dataframe) * validation_ratio)].copy()

        self.name_targets = [col for col in self.dataframe if col.startswith('target')]
        self.dataframe[self.name_targets] = np.log(self.dataframe[self.name_targets])

        self.targets = self.dataframe[self.name_targets].values
        self.inputs = self.dataframe['input'].values

    def load_dataframe(self):
        with open(self.path_pickle, 'rb') as f:
            return pickle.load(f)

    def __len__(self):
        return int(math.ceil(len(self.dataframe) / float(self.batch_size)))

    def on_epoch_end(self):
        self.indexes = range(len(self.dataframe))
        if self.mode == 'train':
            # Shuffles indexes after each epoch if in training mode
            self.indexes = random.sample(self.indexes, k=len(self.indexes))

    def get_batch_labels(self, idx):
        # Fetch a batch of labels
        return self.targets[idx * self.batch_size: (idx + 1) * self.batch_size]

    def get_batch_features(self, idx):
        # Fetch a batch of inputs
        return self.inputs[idx * self.batch_size: (idx + 1) * self.batch_size]

    def __getitem__(self, idx):
        batch_x = self.get_batch_features(idx)
        batch_y = self.get_batch_labels(idx)
        # print(batch_x[0].shape)  # Display (51,7)
        # print(batch_x[0].shape)  # Display (3,)
        return batch_x, batch_y

path = os.path.join(config.path_model_input, 'experiment_2', '2')
train_generator = DataGenerator(path, batch_size=32, mode='train')
validation_generator = DataGenerator(path, batch_size=32, mode='validation')

input_shape = (51, 7)
i = Input(shape=input_shape)
x = Flatten()(i)
x = Dense(10, activation='relu')(x)
output = Dense(3, activation='linear')(x)
model = Model(inputs=i, outputs=output)

def RMSE(label, prediction):
    return tf.sqrt(tf.losses.mean_squared_error(label, prediction))

optimizer = Adam(lr=0.0001)
model.compile(optimizer=optimizer, loss=RMSE)
model.fit(train_generator, epochs=100, verbose=1, use_multiprocessing=False, workers=1)
</code>```

When I am trying to run this code I got this error :

```<code>---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-7-6dde9c267440> in <module>
      7 optimizer = Adam(lr=0.0001)
      8 model.compile(optimizer=optimizer, loss=RMSE)
----> 9 model.fit(train_generator, epochs=100, verbose=1, use_multiprocessing=False, workers=1)#, validation_data=validation_generator)

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\keras\engine\training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_freq, max_queue_size, workers, use_multiprocessing, **kwargs)
    817         max_queue_size=max_queue_size,
    818         workers=workers,
--> 819         use_multiprocessing=use_multiprocessing)
    820
    821   def evaluate(self,

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\keras\engine\training_v2.py in fit(self, model, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_freq, max_queue_size, workers, use_multiprocessing, **kwargs)
    233           max_queue_size=max_queue_size,
    234           workers=workers,
--> 235           use_multiprocessing=use_multiprocessing)
    236
    237       total_samples = _get_total_number_of_samples(training_data_adapter)

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\keras\engine\training_v2.py in _process_training_inputs(model, x, y, batch_size, epochs, sample_weights, class_weights, steps_per_epoch, validation_split, validation_data, validation_steps, shuffle, distribution_strategy, max_queue_size, workers, use_multiprocessing)
    591         max_queue_size=max_queue_size,
    592         workers=workers,
--> 593         use_multiprocessing=use_multiprocessing)
    594     val_adapter = None
    595     if validation_data:

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\keras\engine\training_v2.py in _process_inputs(model, mode, x, y, batch_size, epochs, sample_weights, class_weights, shuffle, steps, distribution_strategy, max_queue_size, workers, use_multiprocessing)
    704       max_queue_size=max_queue_size,
    705       workers=workers,
--> 706       use_multiprocessing=use_multiprocessing)
    707
    708   return adapter

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\keras\engine\data_adapter.py in __init__(self, x, y, sample_weights, standardize_function, shuffle, workers, use_multiprocessing, max_queue_size, **kwargs)
    950         use_multiprocessing=use_multiprocessing,
    951         max_queue_size=max_queue_size,
--> 952         **kwargs)
    953
    954   @staticmethod

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\keras\engine\data_adapter.py in __init__(self, x, y, sample_weights, standardize_function, workers, use_multiprocessing, max_queue_size, **kwargs)
    765
    766     if standardize_function is not None:
--> 767       dataset = standardize_function(dataset)
    768
    769     if kwargs.get("shuffle", False) and self.get_size() is not None:

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\keras\engine\training_v2.py in standardize_function(dataset)
    682           return x, y
    683         return x, y, sample_weights
--> 684       return dataset.map(map_fn, num_parallel_calls=dataset_ops.AUTOTUNE)
    685
    686   if mode == ModeKeys.PREDICT:

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\data\ops\dataset_ops.py in map(self, map_func, num_parallel_calls)
   1589     else:
   1590       return ParallelMapDataset(
-> 1591           self, map_func, num_parallel_calls, preserve_cardinality=True)
   1592
   1593   def flat_map(self, map_func):

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\data\ops\dataset_ops.py in __init__(self, input_dataset, map_func, num_parallel_calls, use_inter_op_parallelism, preserve_cardinality, use_legacy_function)
   3924         self._transformation_name(),
   3925         dataset=input_dataset,
-> 3926         use_legacy_function=use_legacy_function)
   3927     self._num_parallel_calls = ops.convert_to_tensor(
   3928         num_parallel_calls, dtype=dtypes.int32, name="num_parallel_calls")

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\data\ops\dataset_ops.py in __init__(self, func, transformation_name, dataset, input_classes, input_shapes, input_types, input_structure, add_to_graph, use_legacy_function, defun_kwargs)
   3145       with tracking.resource_tracker_scope(resource_tracker):
   3146         # TODO(b/141462134): Switch to using garbage collection.
-> 3147         self._function = wrapper_fn._get_concrete_function_internal()
   3148
   3149         if add_to_graph:

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\eager\function.py in _get_concrete_function_internal(self, *args, **kwargs)
   2393     """Bypasses error checking when getting a graph function."""
   2394     graph_function = self._get_concrete_function_internal_garbage_collected(
-> 2395         *args, **kwargs)
   2396     # We're returning this concrete function to someone, and they may keep a
   2397     # reference to the FuncGraph without keeping a reference to the

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\eager\function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs)
   2387       args, kwargs = None, None
   2388     with self._lock:
-> 2389       graph_function, _, _ = self._maybe_define_function(args, kwargs)
   2390     return graph_function
   2391

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\eager\function.py in _maybe_define_function(self, args, kwargs)
   2701
   2702       self._function_cache.missed.add(call_context_key)
-> 2703       graph_function = self._create_graph_function(args, kwargs)
   2704       self._function_cache.primary[cache_key] = graph_function
   2705       return graph_function, args, kwargs

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\eager\function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)
   2591             arg_names=arg_names,
   2592             override_flat_arg_shapes=override_flat_arg_shapes,
-> 2593             capture_by_value=self._capture_by_value),
   2594         self._function_attributes,
   2595         # Tell the ConcreteFunction to clean up its graph once it goes out of

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\framework\func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes)
    976                                           converted_func)
    977
--> 978       func_outputs = python_func(*func_args, **func_kwargs)
    979
    980       # invariant: `func_outputs` contains only Tensors, CompositeTensors,

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\data\ops\dataset_ops.py in wrapper_fn(*args)
   3138           attributes=defun_kwargs)
   3139       def wrapper_fn(*args):  # pylint: disable=missing-docstring
-> 3140         ret = _wrapper_helper(*args)
   3141         ret = structure.to_tensor_list(self._output_structure, ret)
   3142         return [ops.convert_to_tensor(t) for t in ret]

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\data\ops\dataset_ops.py in _wrapper_helper(*args)
   3080         nested_args = (nested_args,)
   3081
-> 3082       ret = autograph.tf_convert(func, ag_ctx)(*nested_args)
   3083       # If `func` returns a list of tensors, `nest.flatten()` and
   3084       # `ops.convert_to_tensor()` would conspire to attempt to stack

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\autograph\impl\api.py in wrapper(*args, **kwargs)
    235       except Exception as e:  # pylint:disable=broad-except
    236         if hasattr(e, 'ag_error_metadata'):
--> 237           raise e.ag_error_metadata.to_exception(e)
    238         else:
    239           raise

ValueError: in converted code:

    C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\keras\engine\training_v2.py:677 map_fn
        batch_size=None)
    C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\keras\engine\training.py:2410 _standardize_tensors
        exception_prefix='input')
    C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\keras\engine\training_utils.py:573 standardize_input_data
        'with shape ' + str(data_shape))

    ValueError: Error when checking input: expected input_1 to have 3 dimensions, but got array with shape (None, 1)
</code>```

I passed quite some time on this issue and I can't seem to find the reason of this error, I checked several time all the dimensions of the inputs/outputs and I can't see the mistake that I made.
Any help would be much appreciated !

EDIT:
print(self.inputs.shape) and print(self.targets.shape) give (1101,) and (1101, 3) respectively.

I tried to do self.dataframe['input']=self.dataframe['input'].apply(lambda x: np.array(x)) before taking the values, but it still return (1101,) instead of (1101,57,3)

I also checked the shape of all the array in the column input:

```<code>train_generator.dataframe['input_shape']=train_generator.dataframe['input'].apply(lambda x: x.shape)
train_generator.dataframe['input_shape'].unique()
</code>```

It returns : array([(51, 7)], dtype=object)
I am not sure If it is normal that it returns "object" as type of the column

答:
There must be some problem from your dataframe which means there is some problem in the stored file causing mismatching shape when it is loaded

To verify that is where the problem is, I keep your model creation and fitting code exactly the same, but write a testing generator is also almost the same as your original code except the data is generated on the fly, which correct shape.

```<code>class DataGenerator(Sequence):
    def __init__(self, path_experiment, batch_size, mode='train', validation_ratio=0.1):
        self.batch_size = batch_size
        self.mode = mode
        self.indexes = None

        self.inputs =  np.random.random([batch_size,51,7] )
        self.targets = np.random.random([batch_size,3] )

    def __len__(self):
        return int((51*7) / float(self.batch_size))

    def get_batch_labels(self, idx):
        # Fetch a batch of labels
        return self.targets[idx * self.batch_size: (idx + 1) * self.batch_size]

    def get_batch_features(self, idx):
        # Fetch a batch of inputs
        return self.inputs[idx * self.batch_size: (idx + 1) * self.batch_size]

    def __getitem__(self, idx):
        batch_x = self.get_batch_features(idx)
        batch_y = self.get_batch_labels(idx)
        # print(batch_x[0].shape)  # Display (51,7)
        # print(batch_x[0].shape)  # Display (3,)
        return batch_x, batch_y

path=''
train_generator = DataGenerator(path, batch_size=32, mode='train')
validation_generator = DataGenerator(path, batch_size=32, mode='validation')
</code>```

Here I make sure the input is the shape as [batch, 51,7]. Run your model creating code and fit, it works

```<code>Epoch 1/100
11/11 [==============================] - 0s 1ms/step - loss: 0.3640
Epoch 2/100
11/11 [==============================] - 0s 884us/step - loss: 0.3508
Epoch 3/100
11/11 [==============================] - 0s 1ms/step - loss: 0.3350
</code>```

The problem must be in self.dataframe['input'].values. Add print(self.dataframe['input'].values.shape) to see what is it

Body:
I am trying to create a generator using a dataframe stored in pickle. The targets are 3 columns whith their name starting by "target". The features are stored in the "input" column. Each cell of "input" are np.array. Their dimensions are 51x7 (7 is the number of channels).
(I am trying to just focus on the datagenerator for now)

# General Libraries
import os
import math
import pickle
import numpy as np
import pandas as pd
from numpy import random

# Tensorflow and Keras
import tensorflow as tf
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.models import Model
from tensorflow.keras.utils import Sequence
from tensorflow.keras.layers import Input, Conv1D, Dense, Dropout, MaxPooling1D, Flatten

# Project Libraries
import config

class DataGenerator(Sequence):
    def __init__(self, path_experiment, batch_size, mode='train', validation_ratio=0.1):
        self.path_pickle = os.path.join(path_experiment, 'dataframe.pkl')
        self.dataframe = self.load_dataframe()
        self.batch_size = batch_size
        self.mode = mode
        self.indexes = None

        if mode == 'validation':
            self.dataframe = self.dataframe[-int(len(self.dataframe) * validation_ratio):].copy()
        else:
            self.dataframe = self.dataframe[:-int(len(self.dataframe) * validation_ratio)].copy()

        self.name_targets = [col for col in self.dataframe if col.startswith('target')]
        self.dataframe[self.name_targets] = np.log(self.dataframe[self.name_targets])

        self.targets = self.dataframe[self.name_targets].values
        self.inputs = self.dataframe['input'].values

    def load_dataframe(self):
        with open(self.path_pickle, 'rb') as f:
            return pickle.load(f)

    def __len__(self):
        return int(math.ceil(len(self.dataframe) / float(self.batch_size)))

    def on_epoch_end(self):
        self.indexes = range(len(self.dataframe))
        if self.mode == 'train':
            # Shuffles indexes after each epoch if in training mode
            self.indexes = random.sample(self.indexes, k=len(self.indexes))

    def get_batch_labels(self, idx):
        # Fetch a batch of labels
        return self.targets[idx * self.batch_size: (idx + 1) * self.batch_size]

    def get_batch_features(self, idx):
        # Fetch a batch of inputs
        return self.inputs[idx * self.batch_size: (idx + 1) * self.batch_size]

    def __getitem__(self, idx):
        batch_x = self.get_batch_features(idx)
        batch_y = self.get_batch_labels(idx)
        # print(batch_x[0].shape)  # Display (51,7)
        # print(batch_x[0].shape)  # Display (3,)
        return batch_x, batch_y

path = os.path.join(config.path_model_input, 'experiment_2', '2')
train_generator = DataGenerator(path, batch_size=32, mode='train')
validation_generator = DataGenerator(path, batch_size=32, mode='validation')

input_shape = (51, 7)
i = Input(shape=input_shape)
x = Flatten()(i)
x = Dense(10, activation='relu')(x)
output = Dense(3, activation='linear')(x)
model = Model(inputs=i, outputs=output)

def RMSE(label, prediction):
    return tf.sqrt(tf.losses.mean_squared_error(label, prediction))

optimizer = Adam(lr=0.0001)
model.compile(optimizer=optimizer, loss=RMSE)
model.fit(train_generator, epochs=100, verbose=1, use_multiprocessing=False, workers=1)

When I am trying to run this code I got this error :

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-7-6dde9c267440> in <module>
      7 optimizer = Adam(lr=0.0001)
      8 model.compile(optimizer=optimizer, loss=RMSE)
----> 9 model.fit(train_generator, epochs=100, verbose=1, use_multiprocessing=False, workers=1)#, validation_data=validation_generator)

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\keras\engine\training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_freq, max_queue_size, workers, use_multiprocessing, **kwargs)
    817         max_queue_size=max_queue_size,
    818         workers=workers,
--> 819         use_multiprocessing=use_multiprocessing)
    820
    821   def evaluate(self,

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\keras\engine\training_v2.py in fit(self, model, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_freq, max_queue_size, workers, use_multiprocessing, **kwargs)
    233           max_queue_size=max_queue_size,
    234           workers=workers,
--> 235           use_multiprocessing=use_multiprocessing)
    236
    237       total_samples = _get_total_number_of_samples(training_data_adapter)

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\keras\engine\training_v2.py in _process_training_inputs(model, x, y, batch_size, epochs, sample_weights, class_weights, steps_per_epoch, validation_split, validation_data, validation_steps, shuffle, distribution_strategy, max_queue_size, workers, use_multiprocessing)
    591         max_queue_size=max_queue_size,
    592         workers=workers,
--> 593         use_multiprocessing=use_multiprocessing)
    594     val_adapter = None
    595     if validation_data:

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\keras\engine\training_v2.py in _process_inputs(model, mode, x, y, batch_size, epochs, sample_weights, class_weights, shuffle, steps, distribution_strategy, max_queue_size, workers, use_multiprocessing)
    704       max_queue_size=max_queue_size,
    705       workers=workers,
--> 706       use_multiprocessing=use_multiprocessing)
    707
    708   return adapter

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\keras\engine\data_adapter.py in __init__(self, x, y, sample_weights, standardize_function, shuffle, workers, use_multiprocessing, max_queue_size, **kwargs)
    950         use_multiprocessing=use_multiprocessing,
    951         max_queue_size=max_queue_size,
--> 952         **kwargs)
    953
    954   @staticmethod

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\keras\engine\data_adapter.py in __init__(self, x, y, sample_weights, standardize_function, workers, use_multiprocessing, max_queue_size, **kwargs)
    765
    766     if standardize_function is not None:
--> 767       dataset = standardize_function(dataset)
    768
    769     if kwargs.get("shuffle", False) and self.get_size() is not None:

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\keras\engine\training_v2.py in standardize_function(dataset)
    682           return x, y
    683         return x, y, sample_weights
--> 684       return dataset.map(map_fn, num_parallel_calls=dataset_ops.AUTOTUNE)
    685
    686   if mode == ModeKeys.PREDICT:

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\data\ops\dataset_ops.py in map(self, map_func, num_parallel_calls)
   1589     else:
   1590       return ParallelMapDataset(
-> 1591           self, map_func, num_parallel_calls, preserve_cardinality=True)
   1592
   1593   def flat_map(self, map_func):

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\data\ops\dataset_ops.py in __init__(self, input_dataset, map_func, num_parallel_calls, use_inter_op_parallelism, preserve_cardinality, use_legacy_function)
   3924         self._transformation_name(),
   3925         dataset=input_dataset,
-> 3926         use_legacy_function=use_legacy_function)
   3927     self._num_parallel_calls = ops.convert_to_tensor(
   3928         num_parallel_calls, dtype=dtypes.int32, name="num_parallel_calls")

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\data\ops\dataset_ops.py in __init__(self, func, transformation_name, dataset, input_classes, input_shapes, input_types, input_structure, add_to_graph, use_legacy_function, defun_kwargs)
   3145       with tracking.resource_tracker_scope(resource_tracker):
   3146         # TODO(b/141462134): Switch to using garbage collection.
-> 3147         self._function = wrapper_fn._get_concrete_function_internal()
   3148
   3149         if add_to_graph:

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\eager\function.py in _get_concrete_function_internal(self, *args, **kwargs)
   2393     """Bypasses error checking when getting a graph function."""
   2394     graph_function = self._get_concrete_function_internal_garbage_collected(
-> 2395         *args, **kwargs)
   2396     # We're returning this concrete function to someone, and they may keep a
   2397     # reference to the FuncGraph without keeping a reference to the

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\eager\function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs)
   2387       args, kwargs = None, None
   2388     with self._lock:
-> 2389       graph_function, _, _ = self._maybe_define_function(args, kwargs)
   2390     return graph_function
   2391

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\eager\function.py in _maybe_define_function(self, args, kwargs)
   2701
   2702       self._function_cache.missed.add(call_context_key)
-> 2703       graph_function = self._create_graph_function(args, kwargs)
   2704       self._function_cache.primary[cache_key] = graph_function
   2705       return graph_function, args, kwargs

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\eager\function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)
   2591             arg_names=arg_names,
   2592             override_flat_arg_shapes=override_flat_arg_shapes,
-> 2593             capture_by_value=self._capture_by_value),
   2594         self._function_attributes,
   2595         # Tell the ConcreteFunction to clean up its graph once it goes out of

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\framework\func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes)
    976                                           converted_func)
    977
--> 978       func_outputs = python_func(*func_args, **func_kwargs)
    979
    980       # invariant: `func_outputs` contains only Tensors, CompositeTensors,

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\data\ops\dataset_ops.py in wrapper_fn(*args)
   3138           attributes=defun_kwargs)
   3139       def wrapper_fn(*args):  # pylint: disable=missing-docstring
-> 3140         ret = _wrapper_helper(*args)
   3141         ret = structure.to_tensor_list(self._output_structure, ret)
   3142         return [ops.convert_to_tensor(t) for t in ret]

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\data\ops\dataset_ops.py in _wrapper_helper(*args)
   3080         nested_args = (nested_args,)
   3081
-> 3082       ret = autograph.tf_convert(func, ag_ctx)(*nested_args)
   3083       # If `func` returns a list of tensors, `nest.flatten()` and
   3084       # `ops.convert_to_tensor()` would conspire to attempt to stack

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\autograph\impl\api.py in wrapper(*args, **kwargs)
    235       except Exception as e:  # pylint:disable=broad-except
    236         if hasattr(e, 'ag_error_metadata'):
--> 237           raise e.ag_error_metadata.to_exception(e)
    238         else:
    239           raise

ValueError: in converted code:

    C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\keras\engine\training_v2.py:677 map_fn
        batch_size=None)
    C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\keras\engine\training.py:2410 _standardize_tensors
        exception_prefix='input')
    C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\keras\engine\training_utils.py:573 standardize_input_data
        'with shape ' + str(data_shape))

    ValueError: Error when checking input: expected input_1 to have 3 dimensions, but got array with shape (None, 1)

I passed quite some time on this issue and I can't seem to find the reason of this error, I checked several time all the dimensions of the inputs/outputs and I can't see the mistake that I made.
Any help would be much appreciated !

EDIT:
print(self.inputs.shape) and print(self.targets.shape) give (1101,) and (1101, 3) respectively.

I tried to do self.dataframe['input']=self.dataframe['input'].apply(lambda x: np.array(x)) before taking the values, but it still return (1101,) instead of (1101,57,3)

I also checked the shape of all the array in the column input:

train_generator.dataframe['input_shape']=train_generator.dataframe['input'].apply(lambda x: x.shape)
train_generator.dataframe['input_shape'].unique()

It returns : array([(51, 7)], dtype=object)
I am not sure If it is normal that it returns "object" as type of the column

Body:
There must be some problem from your dataframe which means there is some problem in the stored file causing mismatching shape when it is loaded

To verify that is where the problem is, I keep your model creation and fitting code exactly the same, but write a testing generator is also almost the same as your original code except the data is generated on the fly, which correct shape.

class DataGenerator(Sequence):
    def __init__(self, path_experiment, batch_size, mode='train', validation_ratio=0.1):
        self.batch_size = batch_size
        self.mode = mode
        self.indexes = None

        self.inputs =  np.random.random([batch_size,51,7] )
        self.targets = np.random.random([batch_size,3] )

    def __len__(self):
        return int((51*7) / float(self.batch_size))

    def get_batch_labels(self, idx):
        # Fetch a batch of labels
        return self.targets[idx * self.batch_size: (idx + 1) * self.batch_size]

    def get_batch_features(self, idx):
        # Fetch a batch of inputs
        return self.inputs[idx * self.batch_size: (idx + 1) * self.batch_size]

    def __getitem__(self, idx):
        batch_x = self.get_batch_features(idx)
        batch_y = self.get_batch_labels(idx)
        # print(batch_x[0].shape)  # Display (51,7)
        # print(batch_x[0].shape)  # Display (3,)
        return batch_x, batch_y

path=''
train_generator = DataGenerator(path, batch_size=32, mode='train')
validation_generator = DataGenerator(path, batch_size=32, mode='validation')

Here I make sure the input is the shape as [batch, 51,7]. Run your model creating code and fit, it works

Epoch 1/100
11/11 [==============================] - 0s 1ms/step - loss: 0.3640
Epoch 2/100
11/11 [==============================] - 0s 884us/step - loss: 0.3508
Epoch 3/100
11/11 [==============================] - 0s 1ms/step - loss: 0.3350

The problem must be in self.dataframe['input'].values. Add print(self.dataframe['input'].values.shape) to see what is it


问:
MATLAB Concatenate matrices with unequal dimensions
Is there any easy way to concatenate matrices with unequal dimensions using zero padding?

```<code>short = [1 2 3]';
long = [4 5 6 7]';
desiredResult = horzcat(short, long);
</code>```

I would like something like:

```<code>desiredResult =
1 4
2 5
3 6
0 7
</code>```

答:
EDIT:

I have edited my earlier solution so that you won't have to supply a maxLength parameter to the function. The function calculates it before doing the padding.

```<code>function out=joinUnevenVectors(varargin)
%#Horizontally catenate multiple column vectors by appending zeros
%#at the ends of the shorter vectors
%#
%#SYNTAX: out = joinUnevenVectors(vec1, vec2, ... , vecN)

    maxLength=max(cellfun(@numel,varargin));
    out=cell2mat(cellfun(@(x)cat(1,x,zeros(maxLength-length(x),1)),varargin,'UniformOutput',false));
</code>```

The convenience of having it as a function is that you can easily join multiple uneven vectors in a single line as joinUnevenVectors(vec1,vec2,vec3,vec4) and so on, without having to manually enter it in each line.

EXAMPLE:

```<code>short = [1 2 3]';
long = [4 5 6 7]';
joinUnevenVectors(short,long)

ans =

     1     4
     2     5
     3     6
     0     7
</code>```

Body:
Is there any easy way to concatenate matrices with unequal dimensions using zero padding?

short = [1 2 3]';
long = [4 5 6 7]';
desiredResult = horzcat(short, long);

I would like something like:

desiredResult =
1 4
2 5
3 6
0 7

Body:
EDIT:

I have edited my earlier solution so that you won't have to supply a maxLength parameter to the function. The function calculates it before doing the padding.

function out=joinUnevenVectors(varargin)
%#Horizontally catenate multiple column vectors by appending zeros
%#at the ends of the shorter vectors
%#
%#SYNTAX: out = joinUnevenVectors(vec1, vec2, ... , vecN)

    maxLength=max(cellfun(@numel,varargin));
    out=cell2mat(cellfun(@(x)cat(1,x,zeros(maxLength-length(x),1)),varargin,'UniformOutput',false));

The convenience of having it as a function is that you can easily join multiple uneven vectors in a single line as joinUnevenVectors(vec1,vec2,vec3,vec4) and so on, without having to manually enter it in each line.

EXAMPLE:

short = [1 2 3]';
long = [4 5 6 7]';
joinUnevenVectors(short,long)

ans =

     1     4
     2     5
     3     6
     0     7


问:
Media queries - not responding on devices
```<code>@media screen (max-width: 750px) or (screen and (max-width: 750px) (-webkit-min-device-pixel-ratio: 2),(min-resolution: 192dpi)) {
        div.body, div.body div.links, div.body div.links div, div.footer, div.footer div {
            display: block !important;
            overflow: hidden !important;
}
</code>```

another version

```<code>@media screen and (max-width: 750px) {
        div.body, div.body div.links, div.body div.links div, div.footer, div.footer div, table, td, tr{
            display: block !important;
            overflow: hidden !important;
        }
</code>```

Hi all,

Above is my media queries for my code. This code is for a news letter and for some reason the media queries will have no effect went sent to a mobile device. Is there something that I am missing in the media queries? The phone I am using to test is an iPhone XR.

Thank you so much in advance!

Dom

答:
In both your queries you seem to be missing a <code>}</code> </p>

```<code>@media screen (max-width: 750px) or (screen and (max-width: 750px) (-webkit-min-device-pixel-ratio: 2),(min-resolution: 192dpi)) {
  div.body, div.body div.links, div.body div.links div, div.footer, div.footer div {
     display: block !important;
     overflow: hidden !important;
  }
}

@media screen and (max-width: 750px) {
   div.body, div.body div.links, div.body div.links div, div.footer, div.footer div, table, td, tr{
      display: block !important;
      overflow: hidden !important;
   }
}
</code>```

Body:
@media screen (max-width: 750px) or (screen and (max-width: 750px) (-webkit-min-device-pixel-ratio: 2),(min-resolution: 192dpi)) {
        div.body, div.body div.links, div.body div.links div, div.footer, div.footer div {
            display: block !important;
            overflow: hidden !important;
}

another version

@media screen and (max-width: 750px) {
        div.body, div.body div.links, div.body div.links div, div.footer, div.footer div, table, td, tr{
            display: block !important;
            overflow: hidden !important;
        }

Hi all,

Above is my media queries for my code. This code is for a news letter and for some reason the media queries will have no effect went sent to a mobile device. Is there something that I am missing in the media queries? The phone I am using to test is an iPhone XR.

Thank you so much in advance!

Dom

Body:
In both your queries you seem to be missing a }

@media screen (max-width: 750px) or (screen and (max-width: 750px) (-webkit-min-device-pixel-ratio: 2),(min-resolution: 192dpi)) {
  div.body, div.body div.links, div.body div.links div, div.footer, div.footer div {
     display: block !important;
     overflow: hidden !important;
  }
}

@media screen and (max-width: 750px) {
   div.body, div.body div.links, div.body div.links div, div.footer, div.footer div, table, td, tr{
      display: block !important;
      overflow: hidden !important;
   }
}