问:
Cannot compile wxWidgets Hello World
So, I was trying to compile hello world example provided by wxWidgets but was unsuccessful in doing so. I will explain what I have done step by step to the current point where I am stuck.

Compiling wxWidgets

First of all, my compiler of choice is MinGw-w64, and since wxWidgets advise to build their library from source (downloaded from wxWidgets download),  I decided to do so using CMake.

I created a directory called cmake inside the root directory of wxWidgets (in my case: C:\C++\wxWidgets-3.1.3). Also I created bin directory for storing the compiled binaries.

I then navigated to the cmake directory and run the following CMake configuration command:```$ cmake -G "MinGW Makefiles" .. -D "wxBUILD_SHARED=OFF" -D "wxBUILD_MONOLITHIC=OFF" -D "CMAKE_BUILD_TYPE=debug" -D "CMAKE_C_COMPILER=gcc.exe" -D "CMAKE_CXX_COMPILER=g++.exe"```then I started the build by using the following command:```$ cmake --build . --target all```The resulting .a files (static library files) were placed in the bin directory.

I repeated the step 3 with the -D "CMAKE_BUILD_TYPE=release" parameter.

The generated lib\gcc_x64_lib\mswu and lib\gcc_x64_lib\mswud directories into the include directory for the convenience (as they contain setup.h header file).

As the result my C:\C++\wxWidgets-3.1.3\bin directory contains following files: ```libwxexpat.a   libwxpngd.a        libwxtiff.a   wxbase31u_net.a   wxmsw31u_adv.a   wxmsw31u_media.a     wxmsw31u_stc.a      wxmsw31ud_core.a      wxmsw31ud_qa.a        wxmsw31ud_xrc.a
libwxexpatd.a  libwxregexu.a      libwxtiffd.a  wxbase31u_xml.a   wxmsw31u_aui.a   wxmsw31u_propgrid.a  wxmsw31u_webview.a  wxmsw31ud_gl.a        wxmsw31ud_ribbon.a    wxrc.exe*
libwxjpeg.a    libwxregexud.a     libwxzlib.a   wxbase31ud.a      wxmsw31u_core.a  wxmsw31u_qa.a        wxmsw31u_xrc.a      wxmsw31ud_html.a      wxmsw31ud_richtext.a
libwxjpegd.a   libwxscintilla.a   libwxzlibd.a  wxbase31ud_net.a  wxmsw31u_gl.a    wxmsw31u_ribbon.a    wxmsw31ud_adv.a     wxmsw31ud_media.a     wxmsw31ud_stc.a
libwxpng.a     libwxscintillad.a  wxbase31u.a   wxbase31ud_xml.a  wxmsw31u_html.a  wxmsw31u_richtext.a  wxmsw31ud_aui.a     wxmsw31ud_propgrid.a  wxmsw31ud_webview.a```

Creating Hello World project

I created simple wxWidgets hello world project with the following file structure: ```app
|   build
|   headers
|   sources
|   |    main.cpp
|   CMakeLists.txt```

The contents of main.cpp:

// wxWidgets "Hello World" Program
// For compilers that support precompilation, includes "wx/wx.h".
#include <wx/wxprec.h>

#ifndef WX_PRECOMP
    #include <wx/wx.h>
#endif

class MyApp : public wxApp {
public:
    virtual bool OnInit();
};

class MyFrame : public wxFrame {
public:
    MyFrame();

private:
    void OnHello(wxCommandEvent& event);
    void OnExit(wxCommandEvent& event);
    void OnAbout(wxCommandEvent& event);
};

enum {
    ID_Hello = 1
};

wxIMPLEMENT_APP(MyApp);

bool MyApp::OnInit() {
    MyFrame *frame = new MyFrame();
    frame->Show(true);
    return true;
}

MyFrame::MyFrame(): wxFrame(NULL, wxID_ANY, "Hello World") {
    wxMenu *menuFile = new wxMenu;
    menuFile->Append(ID_Hello, "&Hello...\tCtrl-H", "Help string shown in status bar for this menu item");
    menuFile->AppendSeparator();
    menuFile->Append(wxID_EXIT);

    wxMenu *menuHelp = new wxMenu;
    menuHelp->Append(wxID_ABOUT);

    wxMenuBar *menuBar = new wxMenuBar;
    menuBar->Append(menuFile, "&File");
    menuBar->Append(menuHelp, "&Help");

    SetMenuBar( menuBar );
    CreateStatusBar();
    SetStatusText("Welcome to wxWidgets!");

    Bind(wxEVT_MENU, &MyFrame::OnHello, this, ID_Hello);
    Bind(wxEVT_MENU, &MyFrame::OnAbout, this, wxID_ABOUT);
    Bind(wxEVT_MENU, &MyFrame::OnExit, this, wxID_EXIT);
}

void MyFrame::OnExit(wxCommandEvent& event) {
    Close(true);
}

void MyFrame::OnAbout(wxCommandEvent& event) {
    wxMessageBox("This is a wxWidgets Hello World example", "About Hello World", wxOK | wxICON_INFORMATION);
}

void MyFrame::OnHello(wxCommandEvent& event) {
    wxLogMessage("Hello world from wxWidgets!");
}
```

<p>The contents of <strong><code>CMakeLists.txt</code></strong>:</p>

```cmake_minimum_required(VERSION 2.8)

project(hello_world)

if (MINGW)
    add_compile_options(--static)
endif()

set(wx_libraries_path "C:\\C++\\wxWidgets-3.1.3\\bin")

if(CMAKE_BUILD_TYPE STREQUAL "Debug")
    include_directories("C:\\C++\\wxWidgets-3.1.3\\include\\mswud")
    find_library(libwxexpat       NAMES libwxexpatd        PATH ${wx_libraries_path})
    find_library(libwxjpeg        NAMES libwxjpegd         PATH ${wx_libraries_path})
    find_library(libwxpng         NAMES libwxpngd          PATH ${wx_libraries_path})
    find_library(libwxregexu      NAMES libwxregexud       PATH ${wx_libraries_path})
    find_library(libwxscintilla   NAMES libwxscintillad    PATH ${wx_libraries_path})
    find_library(libwxtiff        NAMES libwxtiffd         PATH ${wx_libraries_path})
    find_library(libwxzlib        NAMES libwxzlibd         PATH ${wx_libraries_path})
    find_library(wxbase31u        NAMES wxbase31ud         PATH ${wx_libraries_path})
    find_library(wxbase31u_xml    NAMES wxbase31ud_net     PATH ${wx_libraries_path})
    find_library(wxbase31u_net    NAMES wxbase31ud_xml     PATH ${wx_libraries_path})
    find_library(wxmsw31u_adv     NAMES wxmsw31ud_adv      PATH ${wx_libraries_path})
    find_library(wxmsw31u_aui     NAMES wxmsw31ud_aui      PATH ${wx_libraries_path})
    find_library(wxmsw31u_core    NAMES wxmsw31ud_core     PATH ${wx_libraries_path})
    find_library(wxmsw31u_gl      NAMES wxmsw31ud_gl       PATH ${wx_libraries_path})
    find_library(wxmsw31u_html    NAMES wxmsw31ud_html     PATH ${wx_libraries_path})
    find_library(wxmsw31u_media   NAMES wxmsw31ud_media    PATH ${wx_libraries_path})
    find_library(wxmsw31u_propgri NAMES wxmsw31ud_propgrid PATH ${wx_libraries_path})
    find_library(wxmsw31u_qa      NAMES wxmsw31ud_qa       PATH ${wx_libraries_path})
    find_library(wxmsw31u_ribbon  NAMES wxmsw31ud_ribbon   PATH ${wx_libraries_path})
    find_library(wxmsw31u_richtex NAMES wxmsw31ud_richtext PATH ${wx_libraries_path})
    find_library(wxmsw31u_stc     NAMES wxmsw31ud_stc      PATH ${wx_libraries_path})
    find_library(wxmsw31u_webview NAMES wxmsw31ud_webview  PATH ${wx_libraries_path})
    find_library(wxmsw31u_xrc     NAMES wxmsw31ud_xrc      PATH ${wx_libraries_path})
endif()

if(CMAKE_BUILD_TYPE STREQUAL "Release")
    include_directories("C:\\C++\\wxWidgets-3.1.3\\include\\mswu")
    find_library(libwxexpat       NAMES libwxexpat       PATH ${wx_libraries_path})
    find_library(libwxjpeg        NAMES libwxjpeg        PATH ${wx_libraries_path})
    find_library(libwxpng         NAMES libwxpng         PATH ${wx_libraries_path})
    find_library(libwxregexu      NAMES libwxregexu      PATH ${wx_libraries_path})
    find_library(libwxscintilla   NAMES libwxscintilla   PATH ${wx_libraries_path})
    find_library(libwxtiff        NAMES libwxtiff        PATH ${wx_libraries_path})
    find_library(libwxzlib        NAMES libwxzlib        PATH ${wx_libraries_path})
    find_library(wxbase31u        NAMES wxbase31u        PATH ${wx_libraries_path})
    find_library(wxbase31u_xml    NAMES wxbase31u_xml    PATH ${wx_libraries_path})
    find_library(wxbase31u_net    NAMES wxbase31u_net    PATH ${wx_libraries_path})
    find_library(wxmsw31u_adv     NAMES wxmsw31u_adv     PATH ${wx_libraries_path})
    find_library(wxmsw31u_aui     NAMES wxmsw31u_aui     PATH ${wx_libraries_path})
    find_library(wxmsw31u_core    NAMES wxmsw31u_core    PATH ${wx_libraries_path})
    find_library(wxmsw31u_gl      NAMES wxmsw31u_gl      PATH ${wx_libraries_path})
    find_library(wxmsw31u_html    NAMES wxmsw31u_html    PATH ${wx_libraries_path})
    find_library(wxmsw31u_media   NAMES wxmsw31u_media   PATH ${wx_libraries_path})
    find_library(wxmsw31u_propgri NAMES wxmsw31u_propgri PATH ${wx_libraries_path})
    find_library(wxmsw31u_qa      NAMES wxmsw31u_qa      PATH ${wx_libraries_path})
    find_library(wxmsw31u_ribbon  NAMES wxmsw31u_ribbon  PATH ${wx_libraries_path})
    find_library(wxmsw31u_richtex NAMES wxmsw31u_richtex PATH ${wx_libraries_path})
    find_library(wxmsw31u_stc     NAMES wxmsw31u_stc     PATH ${wx_libraries_path})
    find_library(wxmsw31u_webview NAMES wxmsw31u_webview PATH ${wx_libraries_path})
    find_library(wxmsw31u_xrc     NAMES wxmsw31u_xrc     PATH ${wx_libraries_path})
endif()

include_directories("C:\\C++\\wxWidgets-3.1.3\\include")
link_directories("C:\\C++\\wxWidgets-3.1.3\\bin")

add_executable(app sources/main.cpp)

message(STATUS "${libwxexpat}")
target_link_libraries(app PRIVATE
    ${libwxexpat}
    ${libwxjpeg}
    ${libwxpng}
    ${libwxregexu}
    ${libwxscintilla}
    ${libwxtiff}
    ${libwxzlib}
    ${wxbase31u}
    ${wxbase31u_xml}
    ${wxbase31u_net}
    ${wxmsw31u_adv}
    ${wxmsw31u_aui}
    ${wxmsw31u_core}
    ${wxmsw31u_gl}
    ${wxmsw31u_html}
    ${wxmsw31u_media}
    ${wxmsw31u_propgrid}
    ${wxmsw31u_qa}
    ${wxmsw31u_ribbon}
    ${wxmsw31u_richtext}
    ${wxmsw31u_stc}
    ${wxmsw31u_webview}
    ${wxmsw31u_xrc}
)
```

<p>After I created project files I executed following CMake command to configure the project:```cmake -G "MinGW Makefiles" .. -D "CMAKE_C_COMPILER=gcc.exe" -D "CMAKE_CXX_COMPILER=g++.exe" -D "CMAKE_BUILD_TYPE=Debug" -D "CMAKE_VERBOSE_MAKEFILE:BOOL=ON"```
Then I tried and failed to build the project with the following CMake command:```cmake --build .```</p>

<h3>Compilation errors</h3>

<p>Unfortunately, the program fails to compile with, here is the output:</p>

```"C:\Program Files\CMake\bin\cmake.exe" -E cmake_progress_start C:\Users\Oiltanker\Git\Pepega-Inject\installer\build\CMakeFiles C:\Users\Oiltanker\Git\Pepega-Inject\installer\build\CMakeFiles\progress.marks
C:/C++/MingGW-w64/mingw64/bin/mingw32-make.exe -f CMakeFiles\Makefile2 all
mingw32-make.exe[1]: Entering directory 'C:/Users/Oiltanker/Git/Pepega-Inject/installer/build'
C:/C++/MingGW-w64/mingw64/bin/mingw32-make.exe -f CMakeFiles\app.dir\build.make CMakeFiles/app.dir/depend
mingw32-make.exe[2]: Entering directory 'C:/Users/Oiltanker/Git/Pepega-Inject/installer/build'
"C:\Program Files\CMake\bin\cmake.exe" -E cmake_depends "MinGW Makefiles" C:\Users\Oiltanker\Git\Pepega-Inject\installer C:\Users\Oiltanker\Git\Pepega-Inject\installer C:\Users\Oiltanker\Git\Pepega-Inject\installer\build C:\Users\Oiltanker\Git\Pepega-Inject\installer\build C:\Users\Oiltanker\Git\Pepega-Inject\installer\build\CMakeFiles\app.dir\DependInfo.cmake --color=
Dependee "C:\Users\Oiltanker\Git\Pepega-Inject\installer\build\CMakeFiles\app.dir\DependInfo.cmake" is newer than depender "C:/Users/Oiltanker/Git/Pepega-Inject/installer/build/CMakeFiles/app.dir/depend.internal".
Dependee "C:/Users/Oiltanker/Git/Pepega-Inject/installer/build/CMakeFiles/CMakeDirectoryInformation.cmake" is newer than depender "C:/Users/Oiltanker/Git/Pepega-Inject/installer/build/CMakeFiles/app.dir/depend.internal".
Scanning dependencies of target app
mingw32-make.exe[2]: Leaving directory 'C:/Users/Oiltanker/Git/Pepega-Inject/installer/build'
C:/C++/MingGW-w64/mingw64/bin/mingw32-make.exe -f CMakeFiles\app.dir\build.make CMakeFiles/app.dir/build
mingw32-make.exe[2]: Entering directory 'C:/Users/Oiltanker/Git/Pepega-Inject/installer/build'
[ 50%] Building CXX object CMakeFiles/app.dir/sources/main.cpp.obj
C:\C++\MingGW-w64\mingw64\bin\g++.exe   @CMakeFiles/app.dir/includes_CXX.rsp -g   --static -o CMakeFiles\app.dir\sources\main.cpp.obj -c C:\Users\Oiltanker\Git\Pepega-Inject\installer\sources\main.cpp
[100%] Linking CXX executable app.exe
"C:\Program Files\CMake\bin\cmake.exe" -E cmake_link_script CMakeFiles\app.dir\link.txt --verbose=1
"C:\Program Files\CMake\bin\cmake.exe" -E remove -f CMakeFiles\app.dir/objects.a
C:\C++\MingGW-w64\mingw64\bin\ar.exe cr CMakeFiles\app.dir/objects.a @CMakeFiles\app.dir\objects1.rsp
C:\C++\MingGW-w64\mingw64\bin\g++.exe -g   -Wl,--whole-archive CMakeFiles\app.dir/objects.a -Wl,--no-whole-archive  -o app.exe -Wl,--out-implib,libapp.dll.a -Wl,--major-image-version,0,--minor-image-version,0 @CMakeFiles\app.dir\linklibs.rsp
C:/C++/wxWidgets-3.1.3/bin/wxbase31ud.a(dlmsw.cpp.obj): In function `GetFileVersion':
C:/C++/wxWidgets-3.1.3/src/msw/dlmsw.cpp:67: undefined reference to `GetFileVersionInfoSizeW'
      .......
C:/C++/wxWidgets-3.1.3/src/common/geometry.cpp:350: undefined reference to `wxDataInputStream::Read32()'
collect2.exe: error: ld returned 1 exit status
mingw32-make.exe[2]: *** [CMakeFiles\app.dir\build.make:110: app.exe] Error 1
mingw32-make.exe[2]: Leaving directory 'C:/Users/Oiltanker/Git/Pepega-Inject/installer/build'
mingw32-make.exe[1]: *** [CMakeFiles\Makefile2:78: CMakeFiles/app.dir/all] Error 2
mingw32-make.exe[1]: Leaving directory 'C:/Users/Oiltanker/Git/Pepega-Inject/installer/build'
mingw32-make.exe: *** [Makefile:86: all] Error 2```
</code>```

答:
GetFileVersionInfoSizeW() lives in version.dll, so you need to link with version.lib to get it.

wxDataInputStream::Read32() is more surprising, it really should be present in wxbase library that you're linking with. Try checking if it's really there using nm or objdump.

Title: Cannot compile wxWidgets Hello World

Body:
So, I was trying to compile hello world example provided by wxWidgets but was unsuccessful in doing so. I will explain what I have done step by step to the current point where I am stuck.

Compiling wxWidgets

First of all, my compiler of choice is MinGw-w64, and since wxWidgets advise to build their library from source (downloaded from wxWidgets download),  I decided to do so using CMake.

I created a directory called cmake inside the root directory of wxWidgets (in my case: C:\C++\wxWidgets-3.1.3). Also I created bin directory for storing the compiled binaries.

I then navigated to the cmake directory and run the following CMake configuration command:
$ cmake -G "MinGW Makefiles" .. -D "wxBUILD_SHARED=OFF" -D "wxBUILD_MONOLITHIC=OFF" -D "CMAKE_BUILD_TYPE=debug" -D "CMAKE_C_COMPILER=gcc.exe" -D "CMAKE_CXX_COMPILER=g++.exe"
then I started the build by using the following command:
$ cmake --build . --target all
The resulting .a files (static library files) were placed in the bin directory.

I repeated the step 3 with the -D "CMAKE_BUILD_TYPE=release" parameter.

The generated lib\gcc_x64_lib\mswu and lib\gcc_x64_lib\mswud directories into the include directory for the convenience (as they contain setup.h header file).

As the result my C:\C++\wxWidgets-3.1.3\bin directory contains following files:
libwxexpat.a   libwxpngd.a        libwxtiff.a   wxbase31u_net.a   wxmsw31u_adv.a   wxmsw31u_media.a     wxmsw31u_stc.a      wxmsw31ud_core.a      wxmsw31ud_qa.a        wxmsw31ud_xrc.a
libwxexpatd.a  libwxregexu.a      libwxtiffd.a  wxbase31u_xml.a   wxmsw31u_aui.a   wxmsw31u_propgrid.a  wxmsw31u_webview.a  wxmsw31ud_gl.a        wxmsw31ud_ribbon.a    wxrc.exe*
libwxjpeg.a    libwxregexud.a     libwxzlib.a   wxbase31ud.a      wxmsw31u_core.a  wxmsw31u_qa.a        wxmsw31u_xrc.a      wxmsw31ud_html.a      wxmsw31ud_richtext.a
libwxjpegd.a   libwxscintilla.a   libwxzlibd.a  wxbase31ud_net.a  wxmsw31u_gl.a    wxmsw31u_ribbon.a    wxmsw31ud_adv.a     wxmsw31ud_media.a     wxmsw31ud_stc.a
libwxpng.a     libwxscintillad.a  wxbase31u.a   wxbase31ud_xml.a  wxmsw31u_html.a  wxmsw31u_richtext.a  wxmsw31ud_aui.a     wxmsw31ud_propgrid.a  wxmsw31ud_webview.a

Creating Hello World project

I created simple wxWidgets hello world project with the following file structure:
app
|   build
|   headers
|   sources
|   |    main.cpp
|   CMakeLists.txt

The contents of main.cpp:

// wxWidgets "Hello World" Program
// For compilers that support precompilation, includes "wx/wx.h".
#include <wx/wxprec.h>

#ifndef WX_PRECOMP
    #include <wx/wx.h>
#endif

class MyApp : public wxApp {
public:
    virtual bool OnInit();
};

class MyFrame : public wxFrame {
public:
    MyFrame();

private:
    void OnHello(wxCommandEvent& event);
    void OnExit(wxCommandEvent& event);
    void OnAbout(wxCommandEvent& event);
};

enum {
    ID_Hello = 1
};

wxIMPLEMENT_APP(MyApp);

bool MyApp::OnInit() {
    MyFrame *frame = new MyFrame();
    frame->Show(true);
    return true;
}

MyFrame::MyFrame(): wxFrame(NULL, wxID_ANY, "Hello World") {
    wxMenu *menuFile = new wxMenu;
    menuFile->Append(ID_Hello, "&Hello...\tCtrl-H", "Help string shown in status bar for this menu item");
    menuFile->AppendSeparator();
    menuFile->Append(wxID_EXIT);

    wxMenu *menuHelp = new wxMenu;
    menuHelp->Append(wxID_ABOUT);

    wxMenuBar *menuBar = new wxMenuBar;
    menuBar->Append(menuFile, "&File");
    menuBar->Append(menuHelp, "&Help");

    SetMenuBar( menuBar );
    CreateStatusBar();
    SetStatusText("Welcome to wxWidgets!");

    Bind(wxEVT_MENU, &MyFrame::OnHello, this, ID_Hello);
    Bind(wxEVT_MENU, &MyFrame::OnAbout, this, wxID_ABOUT);
    Bind(wxEVT_MENU, &MyFrame::OnExit, this, wxID_EXIT);
}

void MyFrame::OnExit(wxCommandEvent& event) {
    Close(true);
}

void MyFrame::OnAbout(wxCommandEvent& event) {
    wxMessageBox("This is a wxWidgets Hello World example", "About Hello World", wxOK | wxICON_INFORMATION);
}

void MyFrame::OnHello(wxCommandEvent& event) {
    wxLogMessage("Hello world from wxWidgets!");
}

The contents of CMakeLists.txt:

cmake_minimum_required(VERSION 2.8)

project(hello_world)

if (MINGW)
    add_compile_options(--static)
endif()

set(wx_libraries_path "C:\\C++\\wxWidgets-3.1.3\\bin")

if(CMAKE_BUILD_TYPE STREQUAL "Debug")
    include_directories("C:\\C++\\wxWidgets-3.1.3\\include\\mswud")
    find_library(libwxexpat       NAMES libwxexpatd        PATH ${wx_libraries_path})
    find_library(libwxjpeg        NAMES libwxjpegd         PATH ${wx_libraries_path})
    find_library(libwxpng         NAMES libwxpngd          PATH ${wx_libraries_path})
    find_library(libwxregexu      NAMES libwxregexud       PATH ${wx_libraries_path})
    find_library(libwxscintilla   NAMES libwxscintillad    PATH ${wx_libraries_path})
    find_library(libwxtiff        NAMES libwxtiffd         PATH ${wx_libraries_path})
    find_library(libwxzlib        NAMES libwxzlibd         PATH ${wx_libraries_path})
    find_library(wxbase31u        NAMES wxbase31ud         PATH ${wx_libraries_path})
    find_library(wxbase31u_xml    NAMES wxbase31ud_net     PATH ${wx_libraries_path})
    find_library(wxbase31u_net    NAMES wxbase31ud_xml     PATH ${wx_libraries_path})
    find_library(wxmsw31u_adv     NAMES wxmsw31ud_adv      PATH ${wx_libraries_path})
    find_library(wxmsw31u_aui     NAMES wxmsw31ud_aui      PATH ${wx_libraries_path})
    find_library(wxmsw31u_core    NAMES wxmsw31ud_core     PATH ${wx_libraries_path})
    find_library(wxmsw31u_gl      NAMES wxmsw31ud_gl       PATH ${wx_libraries_path})
    find_library(wxmsw31u_html    NAMES wxmsw31ud_html     PATH ${wx_libraries_path})
    find_library(wxmsw31u_media   NAMES wxmsw31ud_media    PATH ${wx_libraries_path})
    find_library(wxmsw31u_propgri NAMES wxmsw31ud_propgrid PATH ${wx_libraries_path})
    find_library(wxmsw31u_qa      NAMES wxmsw31ud_qa       PATH ${wx_libraries_path})
    find_library(wxmsw31u_ribbon  NAMES wxmsw31ud_ribbon   PATH ${wx_libraries_path})
    find_library(wxmsw31u_richtex NAMES wxmsw31ud_richtext PATH ${wx_libraries_path})
    find_library(wxmsw31u_stc     NAMES wxmsw31ud_stc      PATH ${wx_libraries_path})
    find_library(wxmsw31u_webview NAMES wxmsw31ud_webview  PATH ${wx_libraries_path})
    find_library(wxmsw31u_xrc     NAMES wxmsw31ud_xrc      PATH ${wx_libraries_path})
endif()

if(CMAKE_BUILD_TYPE STREQUAL "Release")
    include_directories("C:\\C++\\wxWidgets-3.1.3\\include\\mswu")
    find_library(libwxexpat       NAMES libwxexpat       PATH ${wx_libraries_path})
    find_library(libwxjpeg        NAMES libwxjpeg        PATH ${wx_libraries_path})
    find_library(libwxpng         NAMES libwxpng         PATH ${wx_libraries_path})
    find_library(libwxregexu      NAMES libwxregexu      PATH ${wx_libraries_path})
    find_library(libwxscintilla   NAMES libwxscintilla   PATH ${wx_libraries_path})
    find_library(libwxtiff        NAMES libwxtiff        PATH ${wx_libraries_path})
    find_library(libwxzlib        NAMES libwxzlib        PATH ${wx_libraries_path})
    find_library(wxbase31u        NAMES wxbase31u        PATH ${wx_libraries_path})
    find_library(wxbase31u_xml    NAMES wxbase31u_xml    PATH ${wx_libraries_path})
    find_library(wxbase31u_net    NAMES wxbase31u_net    PATH ${wx_libraries_path})
    find_library(wxmsw31u_adv     NAMES wxmsw31u_adv     PATH ${wx_libraries_path})
    find_library(wxmsw31u_aui     NAMES wxmsw31u_aui     PATH ${wx_libraries_path})
    find_library(wxmsw31u_core    NAMES wxmsw31u_core    PATH ${wx_libraries_path})
    find_library(wxmsw31u_gl      NAMES wxmsw31u_gl      PATH ${wx_libraries_path})
    find_library(wxmsw31u_html    NAMES wxmsw31u_html    PATH ${wx_libraries_path})
    find_library(wxmsw31u_media   NAMES wxmsw31u_media   PATH ${wx_libraries_path})
    find_library(wxmsw31u_propgri NAMES wxmsw31u_propgri PATH ${wx_libraries_path})
    find_library(wxmsw31u_qa      NAMES wxmsw31u_qa      PATH ${wx_libraries_path})
    find_library(wxmsw31u_ribbon  NAMES wxmsw31u_ribbon  PATH ${wx_libraries_path})
    find_library(wxmsw31u_richtex NAMES wxmsw31u_richtex PATH ${wx_libraries_path})
    find_library(wxmsw31u_stc     NAMES wxmsw31u_stc     PATH ${wx_libraries_path})
    find_library(wxmsw31u_webview NAMES wxmsw31u_webview PATH ${wx_libraries_path})
    find_library(wxmsw31u_xrc     NAMES wxmsw31u_xrc     PATH ${wx_libraries_path})
endif()

include_directories("C:\\C++\\wxWidgets-3.1.3\\include")
link_directories("C:\\C++\\wxWidgets-3.1.3\\bin")

add_executable(app sources/main.cpp)

message(STATUS "${libwxexpat}")
target_link_libraries(app PRIVATE
    ${libwxexpat}
    ${libwxjpeg}
    ${libwxpng}
    ${libwxregexu}
    ${libwxscintilla}
    ${libwxtiff}
    ${libwxzlib}
    ${wxbase31u}
    ${wxbase31u_xml}
    ${wxbase31u_net}
    ${wxmsw31u_adv}
    ${wxmsw31u_aui}
    ${wxmsw31u_core}
    ${wxmsw31u_gl}
    ${wxmsw31u_html}
    ${wxmsw31u_media}
    ${wxmsw31u_propgrid}
    ${wxmsw31u_qa}
    ${wxmsw31u_ribbon}
    ${wxmsw31u_richtext}
    ${wxmsw31u_stc}
    ${wxmsw31u_webview}
    ${wxmsw31u_xrc}
)

After I created project files I executed following CMake command to configure the project:
cmake -G "MinGW Makefiles" .. -D "CMAKE_C_COMPILER=gcc.exe" -D "CMAKE_CXX_COMPILER=g++.exe" -D "CMAKE_BUILD_TYPE=Debug" -D "CMAKE_VERBOSE_MAKEFILE:BOOL=ON"

Then I tried and failed to build the project with the following CMake command:
cmake --build .

Compilation errors

Unfortunately, the program fails to compile with, here is the output:

"C:\Program Files\CMake\bin\cmake.exe" -E cmake_progress_start C:\Users\Oiltanker\Git\Pepega-Inject\installer\build\CMakeFiles C:\Users\Oiltanker\Git\Pepega-Inject\installer\build\CMakeFiles\progress.marks
C:/C++/MingGW-w64/mingw64/bin/mingw32-make.exe -f CMakeFiles\Makefile2 all
mingw32-make.exe[1]: Entering directory 'C:/Users/Oiltanker/Git/Pepega-Inject/installer/build'
C:/C++/MingGW-w64/mingw64/bin/mingw32-make.exe -f CMakeFiles\app.dir\build.make CMakeFiles/app.dir/depend
mingw32-make.exe[2]: Entering directory 'C:/Users/Oiltanker/Git/Pepega-Inject/installer/build'
"C:\Program Files\CMake\bin\cmake.exe" -E cmake_depends "MinGW Makefiles" C:\Users\Oiltanker\Git\Pepega-Inject\installer C:\Users\Oiltanker\Git\Pepega-Inject\installer C:\Users\Oiltanker\Git\Pepega-Inject\installer\build C:\Users\Oiltanker\Git\Pepega-Inject\installer\build C:\Users\Oiltanker\Git\Pepega-Inject\installer\build\CMakeFiles\app.dir\DependInfo.cmake --color=
Dependee "C:\Users\Oiltanker\Git\Pepega-Inject\installer\build\CMakeFiles\app.dir\DependInfo.cmake" is newer than depender "C:/Users/Oiltanker/Git/Pepega-Inject/installer/build/CMakeFiles/app.dir/depend.internal".
Dependee "C:/Users/Oiltanker/Git/Pepega-Inject/installer/build/CMakeFiles/CMakeDirectoryInformation.cmake" is newer than depender "C:/Users/Oiltanker/Git/Pepega-Inject/installer/build/CMakeFiles/app.dir/depend.internal".
Scanning dependencies of target app
mingw32-make.exe[2]: Leaving directory 'C:/Users/Oiltanker/Git/Pepega-Inject/installer/build'
C:/C++/MingGW-w64/mingw64/bin/mingw32-make.exe -f CMakeFiles\app.dir\build.make CMakeFiles/app.dir/build
mingw32-make.exe[2]: Entering directory 'C:/Users/Oiltanker/Git/Pepega-Inject/installer/build'
[ 50%] Building CXX object CMakeFiles/app.dir/sources/main.cpp.obj
C:\C++\MingGW-w64\mingw64\bin\g++.exe   @CMakeFiles/app.dir/includes_CXX.rsp -g   --static -o CMakeFiles\app.dir\sources\main.cpp.obj -c C:\Users\Oiltanker\Git\Pepega-Inject\installer\sources\main.cpp
[100%] Linking CXX executable app.exe
"C:\Program Files\CMake\bin\cmake.exe" -E cmake_link_script CMakeFiles\app.dir\link.txt --verbose=1
"C:\Program Files\CMake\bin\cmake.exe" -E remove -f CMakeFiles\app.dir/objects.a
C:\C++\MingGW-w64\mingw64\bin\ar.exe cr CMakeFiles\app.dir/objects.a @CMakeFiles\app.dir\objects1.rsp
C:\C++\MingGW-w64\mingw64\bin\g++.exe -g   -Wl,--whole-archive CMakeFiles\app.dir/objects.a -Wl,--no-whole-archive  -o app.exe -Wl,--out-implib,libapp.dll.a -Wl,--major-image-version,0,--minor-image-version,0 @CMakeFiles\app.dir\linklibs.rsp
C:/C++/wxWidgets-3.1.3/bin/wxbase31ud.a(dlmsw.cpp.obj): In function `GetFileVersion':
C:/C++/wxWidgets-3.1.3/src/msw/dlmsw.cpp:67: undefined reference to `GetFileVersionInfoSizeW'
      .......
C:/C++/wxWidgets-3.1.3/src/common/geometry.cpp:350: undefined reference to `wxDataInputStream::Read32()'
collect2.exe: error: ld returned 1 exit status
mingw32-make.exe[2]: *** [CMakeFiles\app.dir\build.make:110: app.exe] Error 1
mingw32-make.exe[2]: Leaving directory 'C:/Users/Oiltanker/Git/Pepega-Inject/installer/build'
mingw32-make.exe[1]: *** [CMakeFiles\Makefile2:78: CMakeFiles/app.dir/all] Error 2
mingw32-make.exe[1]: Leaving directory 'C:/Users/Oiltanker/Git/Pepega-Inject/installer/build'
mingw32-make.exe: *** [Makefile:86: all] Error 2```


来源: stackexchange

问:
React Navigation: Navigate Back To Root using NavigationActions.reset, goBack and getStateForAction
Say I've navigated through 4 screens in my StackNavigator App and now I want to go back to the first screen. There seems to be three different ways to do this and they do navigate to where I want to do, however each way has an animation that cycles through each previous screen.

Is there a clean way to navigate from SCREEN_D to SCREEN_A?

In other words, I don't want to see SCREEN_C and SCREEN_B a split of a second before seeing SCREEN_A when navigating backwards from SCREEN_D

```<code>navigation.navigate(SCREEN_A);
...
navigation.navigate(SCREEN_B);
...
navigation.navigate(SCREEN_C);
...
navigation.navigate(SCREEN_D);
</code>```

Three ways to do this:

1.

```<code>return this.props.navigation
               .dispatch(NavigationActions.reset(
                 {
                    index: 0,
                    actions: [NavigationActions.navigate({ routeName: 'SCREEN_A'})]
                  }));
</code>```

2.

```<code> const {SCREEN_B_KEY} = this.props.navigation.state.params
 this.props.navigation.goBack(SCREEN_B_KEY)
</code>```

3.

```<code>const defaultGetStateForAction = Navigation.router.getStateForAction;

Navigation.router.getStateForAction = (action, state) =>{
  if(action.type === "Navigation/BACK"){
    const routes = [
      {routeName: 'First'},
    ];
    return {
      ...state,
      routes,
      index: 0,
    };
  }
  return defaultGetStateForAction (action,state);
}
</code>```

答:
For 2020 / react-navigation-stack I use the following code when setting up the StackNavigator:

```<code>import { createStackNavigator, CardStyleInterpolators } from 'react-navigation-stack';
import { Easing } from 'react-native';

const Navigator = createStackNavigator({
  // ...
}, {
  defaultNavigationOptions: ({ navigation }) => {
    const animation = navigation.getParam('_animation');
    return {
      // ...
      cardStyleInterpolator: CardStyleInterpolators.forHorizontalIOS,
      ...(animation === 'back' && {
        gestureDirection: 'horizontal-inverted',
      }),
      ...(animation === 'skip' && {
        transitionSpec: {
          open: { animation: 'timing', config: { duration: 0, easing: Easing.step1 }, },
          close: { animation: 'timing', config: { duration: 0, easing: Easing.step0 }, },
        },
      }),
    };
  },
});

</code>```

and the the _animation param to override the animation style

```<code>// replace to a route not in the stack normally creates a forward animation, but
// we want a backwards animation
this.props.navigation.dispatch(
  StackActions.replace({ routeName: 'Login', params: { _animation: 'back' } })
);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Say I've navigated through 4 screens in my StackNavigator App and now I want to go back to the first screen. There seems to be three different ways to do this and they do navigate to where I want to do, however each way has an animation that cycles through each previous screen.

Is there a clean way to navigate from SCREEN_D to SCREEN_A?

In other words, I don't want to see SCREEN_C and SCREEN_B a split of a second before seeing SCREEN_A when navigating backwards from SCREEN_D

navigation.navigate(SCREEN_A);
...
navigation.navigate(SCREEN_B);
...
navigation.navigate(SCREEN_C);
...
navigation.navigate(SCREEN_D);

Three ways to do this:

1.

return this.props.navigation
               .dispatch(NavigationActions.reset(
                 {
                    index: 0,
                    actions: [NavigationActions.navigate({ routeName: 'SCREEN_A'})]
                  }));

2.

 const {SCREEN_B_KEY} = this.props.navigation.state.params
 this.props.navigation.goBack(SCREEN_B_KEY)

3.

const defaultGetStateForAction = Navigation.router.getStateForAction;

Navigation.router.getStateForAction = (action, state) =>{
  if(action.type === "Navigation/BACK"){
    const routes = [
      {routeName: 'First'},
    ];
    return {
      ...state,
      routes,
      index: 0,
    };
  }
  return defaultGetStateForAction (action,state);
}

Body:
For 2020 / react-navigation-stack I use the following code when setting up the StackNavigator:

import { createStackNavigator, CardStyleInterpolators } from 'react-navigation-stack';
import { Easing } from 'react-native';

const Navigator = createStackNavigator({
  // ...
}, {
  defaultNavigationOptions: ({ navigation }) => {
    const animation = navigation.getParam('_animation');
    return {
      // ...
      cardStyleInterpolator: CardStyleInterpolators.forHorizontalIOS,
      ...(animation === 'back' && {
        gestureDirection: 'horizontal-inverted',
      }),
      ...(animation === 'skip' && {
        transitionSpec: {
          open: { animation: 'timing', config: { duration: 0, easing: Easing.step1 }, },
          close: { animation: 'timing', config: { duration: 0, easing: Easing.step0 }, },
        },
      }),
    };
  },
});

and the the _animation param to override the animation style

// replace to a route not in the stack normally creates a forward animation, but
// we want a backwards animation
this.props.navigation.dispatch(
  StackActions.replace({ routeName: 'Login', params: { _animation: 'back' } })
);

ContentLicense: CC BY-SA 4.0


问:
Breaking up a string into a list of tokens using another string as a delimiter?
Let's say I have this string:

```<code>char *myTestString = "Hello AND test AND test2";
</code>```

I want to break this down into the set { Hello, test, test2 }, which I can finally iterate over.

Or I have

```<code>char *myTestString2 = "Hi AND there AND test AND test2";
</code>```

I want to break this down into the set { Hi, there, test, test2 }, which I can later iterate over.

How do I achieve this using C?

EDIT:
Another example is splitting "Hello there AND test" should give out set { Hello there, test }.
For clarification "AND" is delimiter here.

答:
Here you are.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char ** split( const char *s1, const char *s2 )
{
    char **tokens = malloc( sizeof( char * ) );
    int success = tokens != NULL;

    if ( success )
    {
        const char *delim = " \t";
        *tokens = NULL;

        for ( size_t n = 1, len = strlen( s2 ); success && *s1; )
        {
            s1 += strspn( s1, delim );

            if ( *s1 )
            {
                const char *p = s1;

                s1 += strcspn( s1, delim );

                if ( strncmp( p, s2, len ) != 0 )
                {
                    char **tmp = realloc( tokens, ( n + 1 ) * sizeof( char * ) );

                    if ( ( success = tmp != NULL ) )
                    {
                        tokens = tmp;

                        success = ( tokens[n-1] = calloc( 1, s1 - p + 1 ) )  != NULL;
                        strncpy( tokens[n-1], p, s1 - p );
                        tokens[n] = NULL;
                        ++n;
                    }

                    if ( !success )
                    {
                        for ( size_t i = 0; i < n; i++ ) free( tokens[i] );
                        free( tokens );
                    }
                }
            }
        }
    }

    return tokens;
}

int main(void)
{
    const char *s1 = "Hi AND there AND test AND test2";
    const char *s2 = "AND";

    char **tokens = split( s1, s2 );

    if ( tokens != NULL )
    {
        for ( char **p = tokens; *p != NULL; ++p )
        {
            puts( *p );
        }

        char **p = tokens;
        do
        {
            free( *p );
        } while ( *p++ != NULL );

        free( tokens );
    }

    return 0;
}
</code>```

The program output is

```<code>Hi
there
test
test2
</code>```

The function returns NULL if a memory allocation was not successful. Otherwise it returns a pointer to an array of the element type char * the last element of which is null pointer.

The words in the source string are splited by tabs and spaces. You can change the delimiters as you like.

After your comment to my previous solution it seems you need the following

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char ** split( const char *s1, const char *s2 )
{
    char **tokens = malloc( sizeof( char * ) );
    int success = tokens != NULL;

    if ( success )
    {
        const char *delim = " \t";
        *tokens = NULL;

        for ( size_t n = 1, len2 = strlen( s2 ); success && *s1; )
        {
            for ( int empty = 1; empty; )
            {
                s1 += strspn( s1, delim );
                if ( ( empty = strncmp( s1, s2, len2 ) == 0 ) )
                {
                    s1 += len2;
                }
            }

            if ( *s1 )
            {
                const char *p = strstr( s1, s2 );

                size_t len1 = p == NULL ? strlen( s1 ) : p - s1;

                char **tmp = realloc( tokens, ( n + 1 ) * sizeof( char * ) );

                if ( ( success = tmp != NULL ) )
                {
                    tokens = tmp;

                    success = ( tokens[n-1] = calloc( 1, len1 +  1 ) )  != NULL;
                    strncpy( tokens[n-1], s1, len1 );
                    tokens[n] = NULL;
                    ++n;

                    s1 += p == NULL ? len1 : len1 + len2;
                }

                if ( !success )
                {
                    for ( size_t i = 0; i < n; i++ ) free( tokens[i] );
                    free( tokens );
                }
            }
        }
    }

    return tokens;
}

int main(void)
{
    const char *s1 = "Hi there AND test test2";
    const char *s2 = "AND";

    char **tokens = split( s1, s2 );

    if ( tokens != NULL )
    {
        for ( char **p = tokens; *p != NULL; ++p )
        {
            puts( *p );
        }

        char **p = tokens;
        do
        {
            free( *p );
        } while ( *p++ != NULL );

        free( tokens );
    }

    return 0;
}
</code>```

The program output is

```<code>Hi there
test test2
</code>```

Maybe you need also to remove trailing blanks of a extracted sub-string that I hope you can do yourself.:).

Body:
Let's say I have this string:

char *myTestString = "Hello AND test AND test2";

I want to break this down into the set { Hello, test, test2 }, which I can finally iterate over.

Or I have

char *myTestString2 = "Hi AND there AND test AND test2";

I want to break this down into the set { Hi, there, test, test2 }, which I can later iterate over.

How do I achieve this using C?

EDIT:
Another example is splitting "Hello there AND test" should give out set { Hello there, test }.
For clarification "AND" is delimiter here.

Body:
Here you are.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char ** split( const char *s1, const char *s2 )
{
    char **tokens = malloc( sizeof( char * ) );
    int success = tokens != NULL;

    if ( success )
    {
        const char *delim = " \t";
        *tokens = NULL;

        for ( size_t n = 1, len = strlen( s2 ); success && *s1; )
        {
            s1 += strspn( s1, delim );

            if ( *s1 )
            {
                const char *p = s1;

                s1 += strcspn( s1, delim );

                if ( strncmp( p, s2, len ) != 0 )
                {
                    char **tmp = realloc( tokens, ( n + 1 ) * sizeof( char * ) );

                    if ( ( success = tmp != NULL ) )
                    {
                        tokens = tmp;

                        success = ( tokens[n-1] = calloc( 1, s1 - p + 1 ) )  != NULL;
                        strncpy( tokens[n-1], p, s1 - p );
                        tokens[n] = NULL;
                        ++n;
                    }

                    if ( !success )
                    {
                        for ( size_t i = 0; i < n; i++ ) free( tokens[i] );
                        free( tokens );
                    }
                }
            }
        }
    }

    return tokens;
}

int main(void)
{
    const char *s1 = "Hi AND there AND test AND test2";
    const char *s2 = "AND";

    char **tokens = split( s1, s2 );

    if ( tokens != NULL )
    {
        for ( char **p = tokens; *p != NULL; ++p )
        {
            puts( *p );
        }

        char **p = tokens;
        do
        {
            free( *p );
        } while ( *p++ != NULL );

        free( tokens );
    }

    return 0;
}

The program output is

Hi
there
test
test2

The function returns NULL if a memory allocation was not successful. Otherwise it returns a pointer to an array of the element type char * the last element of which is null pointer.

The words in the source string are splited by tabs and spaces. You can change the delimiters as you like.

After your comment to my previous solution it seems you need the following

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char ** split( const char *s1, const char *s2 )
{
    char **tokens = malloc( sizeof( char * ) );
    int success = tokens != NULL;

    if ( success )
    {
        const char *delim = " \t";
        *tokens = NULL;

        for ( size_t n = 1, len2 = strlen( s2 ); success && *s1; )
        {
            for ( int empty = 1; empty; )
            {
                s1 += strspn( s1, delim );
                if ( ( empty = strncmp( s1, s2, len2 ) == 0 ) )
                {
                    s1 += len2;
                }
            }

            if ( *s1 )
            {
                const char *p = strstr( s1, s2 );

                size_t len1 = p == NULL ? strlen( s1 ) : p - s1;

                char **tmp = realloc( tokens, ( n + 1 ) * sizeof( char * ) );

                if ( ( success = tmp != NULL ) )
                {
                    tokens = tmp;

                    success = ( tokens[n-1] = calloc( 1, len1 +  1 ) )  != NULL;
                    strncpy( tokens[n-1], s1, len1 );
                    tokens[n] = NULL;
                    ++n;

                    s1 += p == NULL ? len1 : len1 + len2;
                }

                if ( !success )
                {
                    for ( size_t i = 0; i < n; i++ ) free( tokens[i] );
                    free( tokens );
                }
            }
        }
    }

    return tokens;
}

int main(void)
{
    const char *s1 = "Hi there AND test test2";
    const char *s2 = "AND";

    char **tokens = split( s1, s2 );

    if ( tokens != NULL )
    {
        for ( char **p = tokens; *p != NULL; ++p )
        {
            puts( *p );
        }

        char **p = tokens;
        do
        {
            free( *p );
        } while ( *p++ != NULL );

        free( tokens );
    }

    return 0;
}

The program output is

Hi there
test test2

Maybe you need also to remove trailing blanks of a extracted sub-string that I hope you can do yourself.:).


问:
Best way to write a conversion function
Let's say that I'm writing a function to convert between temperature scales. I want to support at least Celsius, Fahrenheit, and Kelvin. Is it better to pass the source scale and target scale as separate parameters of the function, or some sort of combined parameter?

Example 1 - separate parameters:
function convertTemperature("celsius", "fahrenheit", 22)

Example 2 - combined parameter:
function convertTemperature("c-f", 22)

The code inside the function is probably where it counts. With two parameters, the logic to determine what formula we're going to use is slightly more complicated, but a single parameter doesn't feel right somehow.

Thoughts?

答:
I wish there was some way to accept multiple answers. Based on everyone's recommendations, I think I will stick with the multiple parameters, changing the strings to enums/constants, and moving the value to be converted to the first position in the parameter list. Inside the function, I'll use Kelvin as a common middle ground.

Previously I had written individual functions for each conversion and the overall convertTemperature() function was merely a wrapper with nested switch statements. I'm writing in both classic ASP and PHP, but I wanted to leave the question open to any language.

ContentLicense: CC BY-SA 2.5

Title: Best way to write a conversion function

OwnerDisplayName: Scott


问:
How do you load .js files with ASP.NET?
```<code><%@ Page Language="VB"  %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
  <script runat="server">

Sub Page_Load(ByVal e As System.EventArgs)
Page.ClientScript.RegisterClientScriptInclude("basicjs", "basic.js")
End Sub

</script>
    <title>RegisterClientScriptBlock Example</title>
  </head>
  <body>
<form runat="server">
    <input type="button" id="button1" value="clickme" onclick="click()"/>
</form>
  </body>
</html>
</code>```

I'm using ASP.net (just learning) with VB. I can't seem to get Javascript code to work with ASP VB code. My main problem seems to be that .js files are not loading. In the example, basic.js just contains a function click() that calls an alert() message. How do I get .js files to load with ASP code?

答:
You don't need any server-side code to load a JavaScript file.  Just put this in your :

```<code><script src="basic.js"></script>
</code>```

Title: How do you load .js files with ASP.NET?

Body:
<%@ Page Language="VB"  %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>RegisterClientScriptBlock Example</title>

<form runat="server">
    <input type="button" id="button1" value="clickme" onclick="click()"/>
</form>

I'm using ASP.net (just learning) with VB. I can't seem to get Javascript code to work with ASP VB code. My main problem seems to be that .js files are not loading. In the example, basic.js just contains a function click() that calls an alert() message. How do I get .js files to load with ASP code?

Body:
You don't need any server-side code to load a JavaScript file.  Just put this in your <head>:

<script src="basic.js"></script>


问:
Insert full path of images into MySQL using c#
I need to store the full path of images into MySQL database from c# form and write the following code to achieve this:

```<code>string correctFileName3 = System.IO.Path.GetFileName(dialog.FileName);
string ApplicationPath = Application.StartupPath.Substring(0, Application.StartupPath.Length - 10);
ApplicationPath = ApplicationPath.Replace("\\", "\\\\");
string consultant_logo = ApplicationPath + "\\images\\" + correctFileName3;
</code>```

I want to insert consultant_logo as a string in the database by this insert query:

```<code> String insertQuery = "Insert Into ubc.projectinfo(`projectName`, `companyName`, `projectNumber`,
`projAddress`, `nameOfConCompany`, `consultantPhone`, `nameOfEng1`, `nameOfEng2`, `nameOfEng3`,
`consultantAddress`, `phoneEng1`, `phoneEng2`, `phoneEng3`,`ubc_logo`, `company_logo`, `consultant_logo`)
 VALUES ('" + projectNameText.Text + "','" + companyNameText.Text + "' ,'" + projectNumber.Text + "','"+
 projAddress.Text+ "','"+ nameOfConCompany.Text+ "','"+consultantPhone.Text+"', '"+ nameOfEng1.Text + "',
 '"+ nameOfEng2.Text+ "', '"+ nameOfEng3.Text+ "' , '"+consultantAddress.Text+"','"+ phoneEng1.Text+ "',
'"+ phoneEng2.Text + "','"+ phoneEng3.Text + "', '"+ubc_logo+"','"+company_logo+"',
'"+consultant_logo+"')";
</code>```

but this error occurred "you have an error in your SQL syntax";

答:
Save image path in database - bad idea. Every time, when you transfer you program, you should copy folder with images. I recommend you to save images as byte array into database - not path.

Try to use new syntaxys of string in C#. Like this:

string query = $"INSERT INTO 'testTable' ( 'testColumn' ) VALUES( { youVariable } )";

In MySQL query you don't need to mark the variable with quotation marks like this:

"VALUES ( 'myVariable1', 'myVariable2' )" - wrong

"VALUES ( myVariable1, myVariable2 )" - true

When you use "dialog.FileName" you already have file path and you don't need to get it again with System.IO;

So try this query:

insertQuery = $"Insert Into ubc.projectinfo ('projectName', 'companyName', 'projectNumber', 'projAddress', 'nameOfConCompany', 'consultantPhone', 'nameOfEng1', 'nameOfEng2', 'nameOfEng3', 'consultantAddress', 'phoneEng1', 'phoneEng2', 'phoneEng3','ubc_logo', 'company_logo', 'consultant_logo') VALUES ( {projectNameText.Text}, {companyNameText.Text}, {projectNumber.Text}, {projAddress.Text}, {nameOfConCompany.Text}, {consultantPhone.Text}, {nameOfEng1.Text}, {nameOfEng2.Text}, {nameOfEng3.Text}, {consultantAddress.Text}, {phoneEng1.Text}, {phoneEng2.Text}, {phoneEng3.Text}, {ubc_logo}, {company_logo}, {consultant_logo})";

Body:
I need to store the full path of images into MySQL database from c# form and write the following code to achieve this:

string correctFileName3 = System.IO.Path.GetFileName(dialog.FileName);
string ApplicationPath = Application.StartupPath.Substring(0, Application.StartupPath.Length - 10);
ApplicationPath = ApplicationPath.Replace("\\", "\\\\");
string consultant_logo = ApplicationPath + "\\images\\" + correctFileName3;

I want to insert consultant_logo as a string in the database by this insert query:

 String insertQuery = "Insert Into ubc.projectinfo(`projectName`, `companyName`, `projectNumber`,
`projAddress`, `nameOfConCompany`, `consultantPhone`, `nameOfEng1`, `nameOfEng2`, `nameOfEng3`,
`consultantAddress`, `phoneEng1`, `phoneEng2`, `phoneEng3`,`ubc_logo`, `company_logo`, `consultant_logo`)
 VALUES ('" + projectNameText.Text + "','" + companyNameText.Text + "' ,'" + projectNumber.Text + "','"+
 projAddress.Text+ "','"+ nameOfConCompany.Text+ "','"+consultantPhone.Text+"', '"+ nameOfEng1.Text + "',
 '"+ nameOfEng2.Text+ "', '"+ nameOfEng3.Text+ "' , '"+consultantAddress.Text+"','"+ phoneEng1.Text+ "',
'"+ phoneEng2.Text + "','"+ phoneEng3.Text + "', '"+ubc_logo+"','"+company_logo+"',
'"+consultant_logo+"')";

but this error occurred "you have an error in your SQL syntax";


问:
Stack class in java.util a violation of Liskov substitution principle?
From the documentation of https://docs.oracle.com/javase/7/docs/api/java/util/Stack.html

```<code>public class Stack<E> extends Vector<E>
</code>```

Isn't this a violation of the Liskov substitution principle? The LSP in simple terms states that objects of the same superclass should be able to be swapped with each other without breaking anything.

For example: Let us say that I have a function that takes a Vector as an input. If while calling a function I start passing it a Stack then it might break because Stack prevents random access of elements.

```<code>import java.util.*;

class Book {}

class TextBook extends Book {}

public class Sample {
    public static void process(Vector<Book> books) {
        # This should not be allowed for Stack, Stack is FILO
        System.out.println(books.get(1));
    }

    public static void main(String[] args) {
        Vector<Book> books = new Vector<>();
        books.add(new Book());
        books.add(new Book());
        books.add(new Book());
        process(books);
        System.out.println("ok");

        Stack<Book> bookz = new Stack();
        bookz.add(new Book());
        bookz.add(new Book());
        bookz.add(new Book());
        process(bookz);
        System.out.println("ok");
    }
}
</code>```

答:
Yes, it is.

A stack should only allow for pushing and popping, but because Stack extends Vector it's possible to call the full set of Vector methods. Items can be inserted and removed anywhere in the stack, not just at the top. Conceptually, one should only call push() and pop(), but that's not enforced at the language level due to the backwards inheritance relationship.

Stack's code doesn't violate the LSP, but its contract does: "The Stack class represents a last-in-first-out (LIFO) stack of objects." The fact that it doesn't enforce its own contract doesn't mean that it adheres to the LSP. Documentation matters, too.

A better hierarchy would have a Stack interface with a concrete implementation that is backed by a Vector but does not provide access to the full set of Vector methods.

```<code>public interface Stack<E> {
    E push(E item);
    E pop();
}

public class VectorStack<E> implements Stack<E> {
    private Vector<E> backingVector = new Vector<>();

    ...
}

Stack<E> stack = new VectorStack<>();
</code>```

Stack and Vector date back to the very first 1.0 version of Java. Java 1.2 introduced a much better set of collection classes in the form of the Collection and List interfaces and their various concrete implementations.

Stack and co. are effectively deprecated and should not be used in modern code. The Stack API documentation recommends using Deque instead:

A more complete and consistent set of LIFO stack operations is provided by the Deque interface and its implementations, which should be used in preference to this class. For example:

```<code>Deque<Integer> stack = new ArrayDeque<Integer>();
</code>```

Body:
From the documentation of https://docs.oracle.com/javase/7/docs/api/java/util/Stack.html

public class Stack<E> extends Vector<E>

Isn't this a violation of the Liskov substitution principle? The LSP in simple terms states that objects of the same superclass should be able to be swapped with each other without breaking anything.

For example: Let us say that I have a function that takes a Vector as an input. If while calling a function I start passing it a Stack then it might break because Stack prevents random access of elements.

import java.util.*;

class Book {}

class TextBook extends Book {}

public class Sample {
    public static void process(Vector<Book> books) {
        # This should not be allowed for Stack, Stack is FILO
        System.out.println(books.get(1));
    }

    public static void main(String[] args) {
        Vector<Book> books = new Vector<>();
        books.add(new Book());
        books.add(new Book());
        books.add(new Book());
        process(books);
        System.out.println("ok");

        Stack<Book> bookz = new Stack();
        bookz.add(new Book());
        bookz.add(new Book());
        bookz.add(new Book());
        process(bookz);
        System.out.println("ok");
    }
}

Body:
Yes, it is.

A stack should only allow for pushing and popping, but because Stack extends Vector it's possible to call the full set of Vector methods. Items can be inserted and removed anywhere in the stack, not just at the top. Conceptually, one should only call push() and pop(), but that's not enforced at the language level due to the backwards inheritance relationship.

Stack's code doesn't violate the LSP, but its contract does: "The Stack class represents a last-in-first-out (LIFO) stack of objects." The fact that it doesn't enforce its own contract doesn't mean that it adheres to the LSP. Documentation matters, too.

A better hierarchy would have a Stack interface with a concrete implementation that is backed by a Vector but does not provide access to the full set of Vector methods.

public interface Stack<E> {
    E push(E item);
    E pop();
}

public class VectorStack<E> implements Stack<E> {
    private Vector<E> backingVector = new Vector<>();

    ...
}

Stack<E> stack = new VectorStack<>();

Stack and Vector date back to the very first 1.0 version of Java. Java 1.2 introduced a much better set of collection classes in the form of the Collection and List interfaces and their various concrete implementations.

Stack and co. are effectively deprecated and should not be used in modern code. The Stack API documentation recommends using Deque instead:

A more complete and consistent set of LIFO stack operations is provided by the Deque interface and its implementations, which should be used in preference to this class. For example:

Deque<Integer> stack = new ArrayDeque<Integer>();


问:
Date causing an error, not sure where to proceed
Every time I enter the date 2020, My program throws a Conversion error. It tells me that nvarchar to data type tiny int is wrong.
My question is How would i go about fixing that? This is the part of the code where the error is being thrown. </p>

```<code>           StrQuery = "UPDATE Schedule" &
           "SET JobEvents = JobEvents"  &
           " @JobEvents"  &
           "Where JobNumber = @JobNumber AND JobPhase = @JobPhase"

          SQLQuery.Parameters.AddWithValue("@JobEvents", StrEvent)
          SQLQuery.Parameters.AdddWithValue("@JobNumber", StrJobNumber)
          If StrJobPhase = "" Then
          SQLQuery.Parameters.AddWithValue( "@JobPhase", 0)
          Else
          SQLQuery.Parameters.AddWithValue("@JobPhase", StrJobPhase)
          End If
          SQLQuery.CommandText = StrQuery
</code>```

答:
IF you would just print out your SQL statement, it'd be really easy to see what's wrong:

```<code>UPDATE ScheduleSET JobEvents = JobEvents @JobEventsWhere JobNumber = @JobNumber AND JobPhase = @JobPhase"
</code>```

You have no space between the table name Schedule and the SET keyword, and also your assignment is totally broken - what is this??

```<code>SET JobEvents = JobEvents @JobEvents
</code>```

and also, there's again no space between @JobEvents and the where keyword.....

You need to be a lot more careful when constructing those SQL statements from string concatenation!

Body:
Every time I enter the date 2020, My program throws a Conversion error. It tells me that nvarchar to data type tiny int is wrong.
My question is How would i go about fixing that? This is the part of the code where the error is being thrown.

           StrQuery = "UPDATE Schedule" &
           "SET JobEvents = JobEvents"  &
           " @JobEvents"  &
           "Where JobNumber = @JobNumber AND JobPhase = @JobPhase"

          SQLQuery.Parameters.AddWithValue("@JobEvents", StrEvent)
          SQLQuery.Parameters.AdddWithValue("@JobNumber", StrJobNumber)
          If StrJobPhase = "" Then
          SQLQuery.Parameters.AddWithValue( "@JobPhase", 0)
          Else
          SQLQuery.Parameters.AddWithValue("@JobPhase", StrJobPhase)
          End If
          SQLQuery.CommandText = StrQuery

Body:
IF you would just print out your SQL statement, it'd be really easy to see what's wrong:

UPDATE ScheduleSET JobEvents = JobEvents @JobEventsWhere JobNumber = @JobNumber AND JobPhase = @JobPhase"

You have no space between the table name Schedule and the SET keyword, and also your assignment is totally broken - what is this??

SET JobEvents = JobEvents @JobEvents

and also, there's again no space between @JobEvents and the where keyword.....

You need to be a lot more careful when constructing those SQL statements from string concatenation!


问:
How to uninstall the libraries in ubuntu
In ubuntu 9.10, I execute the following command to download/install the following libraries:

```<code>sudo aptitude build-dep openjdk-6

sudo aptitude install openjdk-6-jdk
</code>```

Can you please tell me how to uninstall the libraries I installed using the above command.

答:
$ dpkg --get-selections | grep -v deinstall | grep software_name | awk '{ print $1 }'

$ sudo apt-get purge package_name

Body:
In ubuntu 9.10, I execute the following command to download/install the following libraries:

sudo aptitude build-dep openjdk-6

sudo aptitude install openjdk-6-jdk

Can you please tell me how to uninstall the libraries I installed using the above command.


问:
Blurry pixel paint on scaled canvas drawBitmap on Samsung devices
Some users encountered blurry pixels issue on Samsung devices. I don't have any Samsung device to check, but there is no problems with phones I have.

I can't understand what is different on Samsung and why there is no issue with other devices! It will be very nice if someone could help me to understand!

Thank you!

How it looks on samsung

My code:

```<code>protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    canvas.save();
    canvas.translate(imagePosition.getX(), imagePosition.getY());
    canvas.scale(mScaleFactor, mScaleFactor);

    boolean hasBackground = backgroundImage != null;

    if (hasBackground) {

        canvas.drawBitmap(backgroundImage, 0, 0, backgroundPaint);

        if (currentMode != ColoringModeEnum.NONE && activity.getAppSettings().highlightActiveSquares) {
            canvas.drawBitmap(hintBitmap, 0, 0, paint);
        }
    }

    canvas.drawBitmap(coloringBitmap, 0, 0, paint);
    canvas.restore();
}

private final Paint paint = new Paint();
</code>```

答:
Your bitmap looks filtered. To fix this, you can call:

backgroundPaint.setFilterBitmap(false)

The question then becomes, why does it only appear to do this on Samsung devices? Obviously, app programmers must be able to predict which state their Paint objects are in, otherwise their apps will break (as yours did).

So, I ran this past a few devices in my test lab. It appears that the default isFilterBitmap() setting (FILTER_BITMAP_FLAG) changed on API 29, although I'm unable to find it in the source code (if anyone can find it, or has more insight, please add a comment, or suggest an edit!)

```<code>Device                API level     isFilterBitmap() default
---------------------------------------------------------------------
Pixel 3 XL            29            true
Pixel 2 XL emulator   29            true
Pixel 2 XL emulator   28            false
Pixel 2 emulator      26            false
Samsung S6            25            false
Samsung S4            21            false
Droid RAZR            16            false
</code>```

Body:
Some users encountered blurry pixels issue on Samsung devices. I don't have any Samsung device to check, but there is no problems with phones I have.

I can't understand what is different on Samsung and why there is no issue with other devices! It will be very nice if someone could help me to understand!

Thank you!

How it looks on samsung

My code:

protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    canvas.save();
    canvas.translate(imagePosition.getX(), imagePosition.getY());
    canvas.scale(mScaleFactor, mScaleFactor);

    boolean hasBackground = backgroundImage != null;

    if (hasBackground) {

        canvas.drawBitmap(backgroundImage, 0, 0, backgroundPaint);

        if (currentMode != ColoringModeEnum.NONE && activity.getAppSettings().highlightActiveSquares) {
            canvas.drawBitmap(hintBitmap, 0, 0, paint);
        }
    }

    canvas.drawBitmap(coloringBitmap, 0, 0, paint);
    canvas.restore();
}

private final Paint paint = new Paint();

Body:
Your bitmap looks filtered. To fix this, you can call:

backgroundPaint.setFilterBitmap(false)

The question then becomes, why does it only appear to do this on Samsung devices? Obviously, app programmers must be able to predict which state their Paint objects are in, otherwise their apps will break (as yours did).

So, I ran this past a few devices in my test lab. It appears that the default isFilterBitmap() setting (FILTER_BITMAP_FLAG) changed on API 29, although I'm unable to find it in the source code (if anyone can find it, or has more insight, please add a comment, or suggest an edit!)

Device                API level     isFilterBitmap() default
---------------------------------------------------------------------
Pixel 3 XL            29            true
Pixel 2 XL emulator   29            true
Pixel 2 XL emulator   28            false
Pixel 2 emulator      26            false
Samsung S6            25            false
Samsung S4            21            false
Droid RAZR            16            false


问:
How to enable TLSv1.0 on haproxy config
We have an a haproxy instance and one of our application only supports TLSv1.0. when it tries to connect via this haproxy, it fails with handshake failure.

How can i enable TLSv1.0 support on this haproxy instance.
Below is my haproxy.cfg

```<code>global
daemon

log         /var/log local0 debug
maxconn     4000

ssl-default-bind-options   no-sslv3
tune.ssl.default-dh-param  2048

stats socket /var/lib/haproxy/stats

#---------------------------------------------------------------------
defaults
mode                    http
log                     global
option                  httplog
option                  dontlognull
option                  http-server-close
option                  forwardfor       except 127.0.0.0/8
option                  redispatch
retries                 3

timeout http-request    10m
timeout connect         10s
timeout client          10s
timeout server          10s

#---------------------------------------------------------------------
frontend api_passthrough

bind *:443 ssl crt /usr/local/etc/certs/ ciphers CECPQ1-RSA-AES256-GCM-SHA384:CECPQ1-RSA-CHACHA20-POLY1305-SHA256:DHE-RSA-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-RSA-AES128-CCM:DHE-RSA-AES256-CCM:DHE-RSA-AES128-CCM8:DHE-RSA-AES256-CCM8:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-CAMELLIA128-SHA256:DHE-RSA-CAMELLIA256-SHA256:DHE-RSA-CHACHA20-POLY1305:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-CAMELLIA128-SHA256:ECDHE-RSA-CAMELLIA256-SHA384:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:CECPQ1-ECDSA-AES256-GCM-SHA384:CECPQ1-ECDSA-CHACHA20-POLY1305-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES128-CCM:ECDHE-ECDSA-AES256-CCM:ECDHE-ECDSA-AES128-CCM8:ECDHE-ECDSA-AES256-CCM8:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-ECDSA-CAMELLIA128-SHA256:ECDHE-ECDSA-CAMELLIA256-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-ECDSA-CHACHA20-POLY1305:DHE-DSS-AES128-SHA256:DHE-DSS-AES256-SHA:DHE-DSS-AES128-GCM-SHA256:DHE-DSS-AES256-GCM-SHA384:DHE-DSS-CAMELLIA128-SHA256:DHE-DSS-CAMELLIA256-SHA256
log /dev/log local0 debug
use_backend hapstats if { path_beg /stats }
default_backend api-gateway

#---------------------------------------------------------------------
backend api-gateway
http-request add-header x-amz-apigw-id xxxxxx

server vpce-1 10.xx.xx.xxx:443 check ssl verify none
server vpce-2 10.xx.xxx.xxx:443 check ssl verify none
server vpce-3 10.xx.xx.xx:443 check ssl verify none

backend hapstats
server haproxy 127.0.0.1:8888 check

listen stats
bind 127.0.0.1:8888
mode http
log global
maxconn 10
timeout client 100s
timeout server 100s
timeout connect 100s
timeout queue 100s

stats enable
stats admin if TRUE
stats hide-version
stats refresh 30s
stats show-node
stats uri /stats
stats auth admin:admin
</code>```

I have gone through some post which suggested to add

```<code> ssl-default-bind-options TLSv1.0 ssl-min-ver
</code>```

I have tried it and getting the error while reloading the config

```<code>unknown option 'TLSv1.0' on global statement 'ssl-default-bind-options'
</code>```

答:
ssl-default-bind-options TLSv1.0 ssl-min-ver

The syntax is not correct.

Reading the documentation yo can see that the correct syntax would be ssl-default-bind-options ssl-min-ver TLSv1.0

Title: How to enable TLSv1.0 on haproxy config

Body:
We have an a haproxy instance and one of our application only supports TLSv1.0. when it tries to connect via this haproxy, it fails with handshake failure.

How can i enable TLSv1.0 support on this haproxy instance.
Below is my haproxy.cfg

global
daemon

log         /var/log local0 debug
maxconn     4000

ssl-default-bind-options   no-sslv3
tune.ssl.default-dh-param  2048

stats socket /var/lib/haproxy/stats

#---------------------------------------------------------------------
defaults
mode                    http
log                     global
option                  httplog
option                  dontlognull
option                  http-server-close
option                  forwardfor       except 127.0.0.0/8
option                  redispatch
retries                 3

timeout http-request    10m
timeout connect         10s
timeout client          10s
timeout server          10s

#---------------------------------------------------------------------
frontend api_passthrough

bind *:443 ssl crt /usr/local/etc/certs/ ciphers CECPQ1-RSA-AES256-GCM-SHA384:CECPQ1-RSA-CHACHA20-POLY1305-SHA256:DHE-RSA-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-RSA-AES128-CCM:DHE-RSA-AES256-CCM:DHE-RSA-AES128-CCM8:DHE-RSA-AES256-CCM8:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-CAMELLIA128-SHA256:DHE-RSA-CAMELLIA256-SHA256:DHE-RSA-CHACHA20-POLY1305:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-CAMELLIA128-SHA256:ECDHE-RSA-CAMELLIA256-SHA384:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:CECPQ1-ECDSA-AES256-GCM-SHA384:CECPQ1-ECDSA-CHACHA20-POLY1305-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES128-CCM:ECDHE-ECDSA-AES256-CCM:ECDHE-ECDSA-AES128-CCM8:ECDHE-ECDSA-AES256-CCM8:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-ECDSA-CAMELLIA128-SHA256:ECDHE-ECDSA-CAMELLIA256-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-ECDSA-CHACHA20-POLY1305:DHE-DSS-AES128-SHA256:DHE-DSS-AES256-SHA:DHE-DSS-AES128-GCM-SHA256:DHE-DSS-AES256-GCM-SHA384:DHE-DSS-CAMELLIA128-SHA256:DHE-DSS-CAMELLIA256-SHA256
log /dev/log local0 debug
use_backend hapstats if { path_beg /stats }
default_backend api-gateway

#---------------------------------------------------------------------
backend api-gateway
http-request add-header x-amz-apigw-id xxxxxx

server vpce-1 10.xx.xx.xxx:443 check ssl verify none
server vpce-2 10.xx.xxx.xxx:443 check ssl verify none
server vpce-3 10.xx.xx.xx:443 check ssl verify none

backend hapstats
server haproxy 127.0.0.1:8888 check

listen stats
bind 127.0.0.1:8888
mode http
log global
maxconn 10
timeout client 100s
timeout server 100s
timeout connect 100s
timeout queue 100s

stats enable
stats admin if TRUE
stats hide-version
stats refresh 30s
stats show-node
stats uri /stats
stats auth admin:admin

I have gone through some post which suggested to add

 ssl-default-bind-options TLSv1.0 ssl-min-ver

I have tried it and getting the error while reloading the config

unknown option 'TLSv1.0' on global statement 'ssl-default-bind-options'


问:
Grails in Eclipse
I'm trying to follow some of the introduction to Grails tutorials and am at the point where I want to try to see if I can use a debugger in Eclipse with my Grails applications. My grails application runs fine when I use the command to execute, but when I tried to use the Eclipse run configuration, I get the following error:

```<code>Exception in thread "main" java.lang.NullPointerException
at java.io.File.<init>(File.java:194)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:494)
at org.codehaus.groovy.reflection.CachedConstructor.invoke(CachedConstructor.java:77)
at org.codehaus.groovy.runtime.callsite.ConstructorSite$ConstructorSiteNoUnwrapNoCoerce.callConstructor(ConstructorSite.java:107)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallConstructor(CallSiteArray.java:52)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:192)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:200)
at grails.util.GrailsMain.run(GrailsMain.groovy:27)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:86)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:234)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1062)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:893)
at org.codehaus.groovy.runtime.InvokerHelper.invokePogoMethod(InvokerHelper.java:744)
at org.codehaus.groovy.runtime.InvokerHelper.invokeMethod(InvokerHelper.java:727)
at org.codehaus.groovy.runtime.InvokerHelper.runScript(InvokerHelper.java:383)
at org.codehaus.groovy.runtime.InvokerHelper$runScript.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:40)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:117)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:129)
at grails.util.GrailsMain.main(GrailsMain.groovy)
</code>```

I figure it's a configuration issue (I did recently set the GRAILS_HOME environment variable and that seems to be correct) but that error message doesn't really give me much to go.

Suggestions?

答:
Grails does work in Eclipse. Based on my observations I would actually say that it is the preferred IDE for Grails development (well the STS version).

A) You could choose to install the Eclipse groovy plug in. Can be a little fiddly http://groovy.codehaus.org/Eclipse+Plugin

B) Or you could used the Spring tool suite (STS) IDE and install Grails support from the extensions menu. http://grails.org/STS+Integration (Just works!)

STS is built on Eclipse

I personally have found STS to have better Grails support than Netbeans. Its developed by the same organisation that backs Grails

Title: Grails in Eclipse

Body:
I'm trying to follow some of the introduction to Grails tutorials and am at the point where I want to try to see if I can use a debugger in Eclipse with my Grails applications. My grails application runs fine when I use the command to execute, but when I tried to use the Eclipse run configuration, I get the following error:

Exception in thread "main" java.lang.NullPointerException
at java.io.File.<init>(File.java:194)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:494)
at org.codehaus.groovy.reflection.CachedConstructor.invoke(CachedConstructor.java:77)
at org.codehaus.groovy.runtime.callsite.ConstructorSite$ConstructorSiteNoUnwrapNoCoerce.callConstructor(ConstructorSite.java:107)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallConstructor(CallSiteArray.java:52)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:192)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:200)
at grails.util.GrailsMain.run(GrailsMain.groovy:27)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:86)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:234)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1062)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:893)
at org.codehaus.groovy.runtime.InvokerHelper.invokePogoMethod(InvokerHelper.java:744)
at org.codehaus.groovy.runtime.InvokerHelper.invokeMethod(InvokerHelper.java:727)
at org.codehaus.groovy.runtime.InvokerHelper.runScript(InvokerHelper.java:383)
at org.codehaus.groovy.runtime.InvokerHelper$runScript.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:40)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:117)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:129)
at grails.util.GrailsMain.main(GrailsMain.groovy)

I figure it's a configuration issue (I did recently set the GRAILS_HOME environment variable and that seems to be correct) but that error message doesn't really give me much to go.

Suggestions?


问:
how get value using jQuery?
i have two form and a validate button, i want form1 to display and form2 to hide, and when i click on validate button i want form1 to hide and form2 to display and for the date i want to display date now.
also the values of form1 display in form2 each by its place.

also the values of form1 display in form2 each by its place.

form1

```<code>  <script src="https://code.jquery.com/jquery-3.3.1.js"></script>

  <!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

  <!-------------------------------->
  <div id="form1">
          <label for="titre">DAY pointage</label>
          <input type="date" name="datep" class="form-control">
          <br>
              <label for="titre">Chantier</label>
              <select class="form-control" id="chantier_id">
                <option selected disabled>Select Location</option>
                <option value="1">azilal</option>
                <option value="2">asfalou</option>
                <option value="3">ihjamn</option>
              </select>
          <br>
             <label for="titre">Ouvrage</label>
              <select class="form-control" id="ouvrage_id">
                        <option value="0" selected disabled>- Select -</option>
                        <option value="1">assinissement</option>
                        <option value="2">installation</option>
              </select>
          <br>
             <label for="titre">default nbre day</label>
             <input type="text" name="nbre" class="form-control" value="1">
          <br>
            <button class="btn btn-theme " type="submit" >valider</button>
          <br>
          <br>

</div>
</code>```

form2

```<code><div id="form2">

              <br>
              <div>Day : dayPointage , Chantier : chantierSelected , Ouvrage : ouvrageSelected</div>
              <table id="example" class="table table-striped table-bordered" style="width:100%">
                 <thead>
                  <tr>
                    <th><input type="checkbox" id="check_all"></th>
                    <th>nom prenom</th>
                    <th>cin</th>
                    <th>matricule</th>
                    <th>default nbre day</th>
                  </tr>
                 </thead>
                <tbody>
                  <tr id="1">
                    <td><input type="checkbox" class="checkbox" name="customer_id[]" value="1" /></td>
                    <td>MARZOUK NAJIB</td>
                    <td>Pa130191</td>
                    <td>2925019599</td>
                    <td value="1"><input type="text" name="nbre" class="form-control" value="default nbre day"></td>
                  </tr>
                   <tr id="2">
                    <td><input type="checkbox" class="checkbox" name="customer_id[]" value="2" /></td>
                    <td>achraf bourki</td>
                    <td>pa5000</td>
                    <td>202020</td>
                    <td value="2"><input type="text" name="nbre" class="form-control" value="default nbre day"></td>
                  </tr>
                </tbody>
              </table>
</div>
</code>```

jQuery

    $(document).ready(function () {

```<code>    $('#check_all').on('click', function(e) {
     if($(this).is(':checked',true))
     {
        $(".checkbox").prop('checked', true);
     } else {
        $(".checkbox").prop('checked',false);
     }
    });
     $('.checkbox').on('click',function(){
        if($('.checkbox:checked').length == $('.checkbox').length){
            $('#check_all').prop('checked',true);
        }else{
            $('#check_all').prop('checked',false);
        }
     });
     });
</code>```

答:
$('#form2 [name=nbre]').val($('#form1 [name=nbre]').val())

And same for each input

Title: how get value using jQuery?

Body:
i have two form and a validate button, i want form1 to display and form2 to hide, and when i click on validate button i want form1 to hide and form2 to display and for the date i want to display date now.
also the values of form1 display in form2 each by its place.

also the values of form1 display in form2 each by its place.

form1

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

          DAY pointage
          <input type="date" name="datep" class="form-control">

              Chantier
              <select class="form-control" id="chantier_id">
                <option selected disabled>Select Location</option>
                <option value="1">azilal</option>
                <option value="2">asfalou</option>
                <option value="3">ihjamn</option>
              </select>

             Ouvrage
              <select class="form-control" id="ouvrage_id">
                        <option value="0" selected disabled>- Select -</option>
                        <option value="1">assinissement</option>
                        <option value="2">installation</option>
              </select>

             default nbre day
             <input type="text" name="nbre" class="form-control" value="1">

            <button class="btn btn-theme " type="submit" >valider</button>

form2

Day : dayPointage , Chantier : chantierSelected , Ouvrage : ouvrageSelected

                    <input type="checkbox" id="check_all">
                    nom prenom
                    cin
                    matricule
                    default nbre day

                    <input type="checkbox" class="checkbox" name="customer_id[]" value="1" />
                    MARZOUK NAJIB
                    Pa130191
                    2925019599
                    <input type="text" name="nbre" class="form-control" value="default nbre day">

                    <input type="checkbox" class="checkbox" name="customer_id[]" value="2" />
                    achraf bourki
                    pa5000
                    202020
                    <input type="text" name="nbre" class="form-control" value="default nbre day">

jQuery

    $(document).ready(function () {

    $('#check_all').on('click', function(e) {
     if($(this).is(':checked',true))
     {
        $(".checkbox").prop('checked', true);
     } else {
        $(".checkbox").prop('checked',false);
     }
    });
     $('.checkbox').on('click',function(){
        if($('.checkbox:checked').length == $('.checkbox').length){
            $('#check_all').prop('checked',true);
        }else{
            $('#check_all').prop('checked',false);
        }
     });
     });


问:
std::list<const SomeClass> can not be defined
I'm trying to define a constant list of constant objects and I can't seem to get it done.
Here is my example that compiles fine:

```<code>#include <string>
#include <list>

class Person { public:
    std::string name;
    Person(const std::string &in_name){name=in_name;}
};

class MyClass { public:
    const std::list</* const */Person> l;
    MyClass(const std::list</* const */Person> &in_l):l(in_l){}
};

int main(int argc, char **argv) {
    Person dave("dave");
    MyClass c(std::list<const Person>(dave));
    return 0;
}
</code>```

When I remove the comments from const in those 2 places,
I get the following errors:

```<code>In file included from /usr/include/x86_64-linux-gnu/c++/7/bits/c++allocator.h:33:0,
                 from /usr/include/c++/7/bits/allocator.h:46,
                 from /usr/include/c++/7/string:41,
                 from main66.cpp:1:
/usr/include/c++/7/ext/new_allocator.h: In instantiation of ‘class __gnu_cxx::new_allocator<const Person>’:
/usr/include/c++/7/bits/allocator.h:108:11:   required from ‘class std::allocator<const Person>’
main66.cpp:11:53:   required from here
/usr/include/c++/7/ext/new_allocator.h:93:7: error: ‘const _Tp* __gnu_cxx::new_allocator<_Tp>::address(__gnu_cxx::new_allocator<_Tp>::const_reference) const [with _Tp = const Person; __gnu_cxx::new_allocator<_Tp>::const_pointer = const Person*; __gnu_cxx::new_allocator<_Tp>::const_reference = const Person&]’ cannot be overloaded
       address(const_reference __x) const _GLIBCXX_NOEXCEPT
       ^~~~~~~
/usr/include/c++/7/ext/new_allocator.h:89:7: error: with ‘_Tp* __gnu_cxx::new_allocator<_Tp>::address(__gnu_cxx::new_allocator<_Tp>::reference) const [with _Tp = const Person; __gnu_cxx::new_allocator<_Tp>::pointer = const Person*; __gnu_cxx::new_allocator<_Tp>::reference = const Person&]’
       address(reference __x) const _GLIBCXX_NOEXCEPT
       ^~~~~~~
</code>```

Is there any way to define a std::list of const objects?

答: std::list must have a non-const, non-volatile value_type.</p>

Body:
I'm trying to define a constant list of constant objects and I can't seem to get it done.
Here is my example that compiles fine:

#include <string>
#include <list>

class Person { public:
    std::string name;
    Person(const std::string &in_name){name=in_name;}
};

class MyClass { public:
    const std::list</* const */Person> l;
    MyClass(const std::list</* const */Person> &in_l):l(in_l){}
};

int main(int argc, char **argv) {
    Person dave("dave");
    MyClass c(std::list<const Person>(dave));
    return 0;
}

When I remove the comments from const in those 2 places,
I get the following errors:

In file included from /usr/include/x86_64-linux-gnu/c++/7/bits/c++allocator.h:33:0,
                 from /usr/include/c++/7/bits/allocator.h:46,
                 from /usr/include/c++/7/string:41,
                 from main66.cpp:1:
/usr/include/c++/7/ext/new_allocator.h: In instantiation of ‘class __gnu_cxx::new_allocator<const Person>’:
/usr/include/c++/7/bits/allocator.h:108:11:   required from ‘class std::allocator<const Person>’
main66.cpp:11:53:   required from here
/usr/include/c++/7/ext/new_allocator.h:93:7: error: ‘const _Tp* __gnu_cxx::new_allocator<_Tp>::address(__gnu_cxx::new_allocator<_Tp>::const_reference) const [with _Tp = const Person; __gnu_cxx::new_allocator<_Tp>::const_pointer = const Person*; __gnu_cxx::new_allocator<_Tp>::const_reference = const Person&]’ cannot be overloaded
       address(const_reference __x) const _GLIBCXX_NOEXCEPT
       ^~~~~~~
/usr/include/c++/7/ext/new_allocator.h:89:7: error: with ‘_Tp* __gnu_cxx::new_allocator<_Tp>::address(__gnu_cxx::new_allocator<_Tp>::reference) const [with _Tp = const Person; __gnu_cxx::new_allocator<_Tp>::pointer = const Person*; __gnu_cxx::new_allocator<_Tp>::reference = const Person&]’
       address(reference __x) const _GLIBCXX_NOEXCEPT
       ^~~~~~~

Is there any way to define a std::list of const objects?


问:
Using JavaScript NPM package with import
I am using the kahoot-api NPM module (GitHub, NPM) and it requires using JavaScript import. (edit, this is a Node.js package. I didn't know the difference between JS and Node.js at the time of writing this, this is why this question was created).

The documentation says to use the following JavaScript import script to import Session and Adapters:

import { Session, Adapters } from 'kahoot-api';
```

<p>This throws an error saying that I need to use a relative reference.</p>

<blockquote>
  <p>Failed to resolve module specifier "kahoot-api". Relative references must start with either "/", "./", or "../".</p>
</blockquote>

<p>My files and folders are structured as so:</p>

<blockquote>
  <ul>
  <li>index.php</li>
  <li>node_modules

  <ul>
  <li>@omegaboot

  <ul>
  <li>kahoot-api</li>
  </ul></li>
  </ul></li>
  </ul>
</blockquote>

<p>All of the NPM files for <code>kahoot-api</code> are inside of the <code>kahoot-api</code> folder.</p>

<p>I have modified my JavaScript code to use a relative reference, as shown below.</p>

<pre class="lang-js prettyprint-override"><code>import { Session, Adapters } from './node_modules/@omegaboot/kahoot-api/';
</code>```

No errors are thrown, however the two imported statements Session and Adapters are not available, and still undefined.

import { Session, Adapters } from './node_modules/@omegaboot/kahoot-api/';

const session = new Session('000000');
session.openSocket() //Connect
  .then(socket => {
    const player = new Adapters.Player(socket); //Create player class
    player.join('test') //Join with name
      .then(() => {
         console.log('Success!');
      });
  });
```

There are multiple JavaScript files inside of the kahoot-api folder, and I have tried including each JavaScript file with the JavaScript import, but to no avail.

Also, I am using the code in index.php with a

答:
idiidk here (the author of the package)

The package @omegaboot/kahoot-api is not the version that people should be using. This package uses some hard coded defaults for easier integration with our build process for omegaboot.com.

The "normal" kahoot-api package https://www.npmjs.com/package/kahoot-api is to be used by third parties, although it hasn't been updated in a bit. Please open an issue on the github page if anything is broken and I'll be sure to take a look.

Body:
I am using the kahoot-api NPM module (GitHub, NPM) and it requires using JavaScript import. (edit, this is a Node.js package. I didn't know the difference between JS and Node.js at the time of writing this, this is why this question was created).

The documentation says to use the following JavaScript import script to import Session and Adapters:

import { Session, Adapters } from 'kahoot-api';

This throws an error saying that I need to use a relative reference.

Failed to resolve module specifier "kahoot-api". Relative references must start with either "/", "./", or "../".

My files and folders are structured as so:

index.php

node_modules

@omegaboot

kahoot-api

All of the NPM files for kahoot-api are inside of the kahoot-api folder.

I have modified my JavaScript code to use a relative reference, as shown below.

import { Session, Adapters } from './node_modules/@omegaboot/kahoot-api/';

No errors are thrown, however the two imported statements Session and Adapters are not available, and still undefined.

import { Session, Adapters } from './node_modules/@omegaboot/kahoot-api/';

const session = new Session('000000');
session.openSocket() //Connect
  .then(socket => {
    const player = new Adapters.Player(socket); //Create player class
    player.join('test') //Join with name
      .then(() => {
         console.log('Success!');
      });
  });

There are multiple JavaScript files inside of the kahoot-api folder, and I have tried including each JavaScript file with the JavaScript import, but to no avail.

Also, I am using the code in index.php with a


问:
Spring Integration - Adding custom headers in Message
I am using Spring Integration filter to do a structural validation of the incoming payload and if the validation fails then i want to add some custom headers to the original message.

The filter code is below :

```<code>@Service("structureValidationFilter")
public class StructureValidationFilter implements MessageSelector {

@Override
public boolean accept(Message<?> message) {
    // TODO Auto-generated method stub
    boolean status=true;

    if(message.getPayload() instanceof CFKRequestBody) {
        CFKRequestBody body=(CFKRequestBody)message.getPayload();
        if(!body.getInitiatingPartyId().equalsIgnoreCase("BPKV")) {
            message = MutableMessageBuilder.fromMessage(message).
                    setHeader("BPKV_ERROR_CODE", "Ïnvalid Initiating part id").
                    setHeader("HTTP_STATUS", "400").build();

            return false;
        }

    }
    return status;
}

}
</code>```

But the headers are not populating in the Message.
Not able to see the headers added in the next component.
What am i doing wrong here.

答:
You can't replace a parameter and expect it to be propagated to the next component; Java doesn't work that way; your new message is simply discarded.

Use a service activator instead of a filter and return the new message, or null which is a signal to end the flow at that point.

Body:
I am using Spring Integration filter to do a structural validation of the incoming payload and if the validation fails then i want to add some custom headers to the original message.

The filter code is below :

@Service("structureValidationFilter")
public class StructureValidationFilter implements MessageSelector {

@Override
public boolean accept(Message<?> message) {
    // TODO Auto-generated method stub
    boolean status=true;

    if(message.getPayload() instanceof CFKRequestBody) {
        CFKRequestBody body=(CFKRequestBody)message.getPayload();
        if(!body.getInitiatingPartyId().equalsIgnoreCase("BPKV")) {
            message = MutableMessageBuilder.fromMessage(message).
                    setHeader("BPKV_ERROR_CODE", "Ïnvalid Initiating part id").
                    setHeader("HTTP_STATUS", "400").build();

            return false;
        }

    }
    return status;
}

}

But the headers are not populating in the Message.
Not able to see the headers added in the next component.
What am i doing wrong here.


问:
Difference between state data and destructuring in react
This is very basic of React but I really need to understand why it is behaving in this way.
Is there any difference between this part of code :
Example1:

```<code>increment = () => {
const { count } = this.state; // doing destructure ...
this.setState({ count: count + 1 }, () => {
console.log("Clicked times: ", count);
});
};

</code>```

and this part Example2:

```<code>increment = () => {
//const { count } = this.state;
this.setState({ count: this.state.count + 1 }, () => { //putting "this.state.count" directly
console.log("Clicked times: ", this.state.count);
});
};

</code>```

Because when I do the second way (Example2), then I get the correct output:
Its asynchronous way and show the same data both in browser and in console. Why the first example does not work in correct way, is it because I am saving the value in a new variable ( by doing de-structuring).
Here is my Whole code link: https://codesandbox.io/s/counting-in-react-j0uyc

Any help will be appreciated! Thanks

答:
Yes, they are the same. The reason decroment does not look like it is working is because you are making a copy of this.state.count

For example. If this.state.count was 1. At the top of the decrement function, you are making a local variable count with the value 1. You are then updating this.state.count to 2, however, the local count is a full copy (not a reference) so will not be affected by this update.

You can see they are the same if you replace console.log("Clicked times: ", count); with console.log("Clicked times: ", this.state.count);

Body:
This is very basic of React but I really need to understand why it is behaving in this way.
Is there any difference between this part of code :
Example1:

increment = () => {
const { count } = this.state; // doing destructure ...
this.setState({ count: count + 1 }, () => {
console.log("Clicked times: ", count);
});
};

and this part Example2:

increment = () => {
//const { count } = this.state;
this.setState({ count: this.state.count + 1 }, () => { //putting "this.state.count" directly
console.log("Clicked times: ", this.state.count);
});
};

Because when I do the second way (Example2), then I get the correct output:
Its asynchronous way and show the same data both in browser and in console. Why the first example does not work in correct way, is it because I am saving the value in a new variable ( by doing de-structuring).
Here is my Whole code link: https://codesandbox.io/s/counting-in-react-j0uyc

Any help will be appreciated! Thanks


问:
Need to port Nodejs REST api server to a java api server
I have a nodejs server application that provides API. Due to some client issues, we need to implement the same server using java.
In node server, for GET or POST we simply execute SQL, GET or POST data to database using JSON.
But in Java, I have seen using spring boot, I have to create a Bean class and in my controller return a List in @GetMapping.

For all my APIs, I would have to create so many beans. Can I return data just like in nodejs, executing SQL query, getting and returning JSON data as it is in Java?
Also, if possible, is this approach recommended or the creating Bean approach is better? I am new to java so, have less idea about this.

答:
I see nothing wrong in creating beans to transfer data from the database to consumer. I don't see any kind of performance or efficiency you would achieve by directly transferring data from SQL database to consumer using Spring MVC to send over HTTP, It even adds more complexity in Java specifically at persistence layer.
You should have been aware of that Java is verbose language before switching from NodeJS. It is better to create an equivalent POJOs.

If you still wanted to go with your own way of doing, following any of these existing posts you will achieve your expectation.

How to read/retrieve data from Database to JSON using JDBC?

Most efficient conversion of ResultSet to JSON?

Json object from database in java


问:
How to extract elements from JSON File with python?
I have the JSON file below and i am trying to extract the value dob_year from each item if the name element is jim.

This is my try:

```<code>import json

with open('j.json') as json_file:
    data = json.load(json_file)
    if data['name'] == 'jim'
        print(data['dob_year'])
</code>```

Error:

```<code>File "extractjson.py", line 6 if data['name'] == 'jim' ^ SyntaxError: invalid syntax
</code>```

this is my file.

```<code>[
      {
        "name": "jim",
        "age": "10",
        "sex": "male",
        "dob_year": "2007",
        "ssn": "123-23-1234"
      },
      {
        "name": "jill",
        "age": "6",
        "sex": "female",
        "dob_year": "2011",
        "ssn": "123-23-1235"
      }
    ]
</code>```

答:
```<code>json.load()
</code>```

returns a list of entries, the way you have saved it. You have to iterate through all list items, then search for your field in the list item.
Also, if it is a repetitive task, make a function out of it. You can pass different files, fields to be extracted, etc. this way, and it can make your job easier.

Example:

```<code>def extract_info(search_field, extract_field, name, filename):

import json

with open(filename) as json_file:
    data = json.load(json_file)
    for item in data:
        if item[search_field] == name:
            print(item[extract_field])

extract_info('name','dob_year','jim','j.json')
</code>```

Body:
I have the JSON file below and i am trying to extract the value dob_year from each item if the name element is jim.

This is my try:

import json

with open('j.json') as json_file:
    data = json.load(json_file)
    if data['name'] == 'jim'
        print(data['dob_year'])

Error:

File "extractjson.py", line 6 if data['name'] == 'jim' ^ SyntaxError: invalid syntax

this is my file.

[
      {
        "name": "jim",
        "age": "10",
        "sex": "male",
        "dob_year": "2007",
        "ssn": "123-23-1234"
      },
      {
        "name": "jill",
        "age": "6",
        "sex": "female",
        "dob_year": "2011",
        "ssn": "123-23-1235"
      }
    ]

Body:
json.load()

returns a list of entries, the way you have saved it. You have to iterate through all list items, then search for your field in the list item.
Also, if it is a repetitive task, make a function out of it. You can pass different files, fields to be extracted, etc. this way, and it can make your job easier.

Example:

def extract_info(search_field, extract_field, name, filename):

import json

with open(filename) as json_file:
    data = json.load(json_file)
    for item in data:
        if item[search_field] == name:
            print(item[extract_field])

extract_info('name','dob_year','jim','j.json')


问:
Ubuntu: After uninstalling package, it is still there
I uninstalled gem. Now if I give in the command:

```<code>sudo apt-get remove gem
</code>```

It returns:

```<code>Reading package lists... Done
Building dependency tree
Reading state information... Done
Package 'gem' is not installed, so not removed
0 upgraded, 0 newly installed, 0 to remove and 41 not upgraded
</code>```

So I assume it is successfully uninstalled. However, if I ask the version, it still works:

```<code>gem --version
</code>```

It returns:

```<code>2.5.2.1
</code>```

Also, if I write "ge" and then hit the tab, I get the auto-completion for gem.
Why is this? And what is the "41 not upgraded" ? Thank you!

答:
for getting package name write following command

$ dpkg --get-selections | grep -v deinstall | grep software_name | awk '{ print $1 }'

for remove package

$ sudo apt-get purge package_name

Body:
I uninstalled gem. Now if I give in the command:

sudo apt-get remove gem

It returns:

Reading package lists... Done
Building dependency tree
Reading state information... Done
Package 'gem' is not installed, so not removed
0 upgraded, 0 newly installed, 0 to remove and 41 not upgraded

So I assume it is successfully uninstalled. However, if I ask the version, it still works:

gem --version

It returns:

2.5.2.1

Also, if I write "ge" and then hit the tab, I get the auto-completion for gem.
Why is this? And what is the "41 not upgraded" ? Thank you!