问:
How to port code using sys/ioctl.h to MinGW gcc?
My codes (https://github.com/fangq/mmc, https://github.com/fangq/mcxcl) have been compiled out-of-box using gcc on Linux & Mac, cygwin-gcc or msys2-gcc on Windows, but not with MinGW compilers (x86-64-mingw64-* compilers for cygwin64, msys2, mingw64 or TDM-GCC, or matlab mingw64 support (mingw64 gcc 4.9.6)) because it complains that it misses a set of header files (sys/ioctl.h, ieee754.h etc), so I included a copy of these header files in my source code, and added -I./mingw64/include to make most of them compile

https://github.com/fangq/mmc/tree/master/src/mingw64/include

however, when compiling the matlab mex file using this script on MATLAB R2016/2018, I received the below error

```<code>Error using mex
mcx_utils.o: In function `mcx_progressbar':
D:/Users/fangq/Gitroot/Project/mmc/src/mcx_utils.c:1054: undefined reference to `ioctl'
collect2.exe: error: ld returned 1 exit status
</code>```

I am wondering why compiling inside matlab and outside matlab are different. Is there a library that I can link to fix the undefined reference to "ioctl" error?

Here is the log when compiling using gcc on msys2:

```<code>fangq@zen:~/space/git/Project/mmc/src$ make mex
Building built/xorshift128p_rand.o
cc -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -I../src -I"./mingw64/include" -o built/xorshift128p_rand.o  xorshift128p_rand.c
Building built/simpmesh.o
cc -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -I../src -I"./mingw64/include" -o built/simpmesh.o  simpmesh.c
Building built/tettracing.o
cc -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -I../src -I"./mingw64/include" -o built/tettracing.o  tettracing.c
Building built/mcx_utils.o
cc -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -I../src -I"./mingw64/include" -o built/mcx_utils.o  mcx_utils.c
Building built/tictoc.o
cc -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -I../src -I"./mingw64/include" -o built/tictoc.o  tictoc.c
Building built/mmc.o
cc -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -I../src -I"./mingw64/include" -o built/mmc.o  mmc.c
Building built/cjson/cJSON.o
cc -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -I../src -I"./mingw64/include" -o built/cjson/cJSON.o  cjson/cJSON.c
Building built/mmc_host.o
cc -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -I../src -I"./mingw64/include" -o built/mmc_host.o  mmc_host.c
Building built/highordermesh.o
g++ -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -I../src -I"./mingw64/include" -o built/highordermesh.o  highordermesh.cpp
Building built/mmc_cl_utils.o
cc -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -I../src -I"./mingw64/include" -o built/mmc_cl_utils.o  mmc_cl_utils.c
Building built/mmc_cl_host.o
cc -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -I../src -I"./mingw64/include" -o built/mmc_cl_host.o  mmc_cl_host.c
Building bin/mmc
cmd //c mex.bat   -v -f mexopts_msys2_gcc.xml COMPFLAGS='$COMPFLAGS -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT' LDFLAGS='$LDFLAGS -static -fopenmp "c:\Windows\System32\OpenCL.dll" -fopenmp'  -outdir ../mmclab mmclab.cpp -I../src -I"./mingw64/include" -output bin/mmc built/xorshift128p_rand.o built/simpmesh.o built/tettracing.o built/mcx_utils.o built/tictoc.o built/mmc.o built/cjson/cJSON.o built/mmc_host.o built/highordermesh.o built/mmc_cl_utils.o built/mmc_cl_host.o
Verbose mode is on.
... Looking for compiler 'MinGW64 Compiler (C++)' ...
... Looking for environment variable 'MW_MINGW64_LOC' ...Yes ('C:/msys64/usr/').
... Looking for file 'C:\msys64\usr\bin\g++.exe' ...Yes.
... Looking for folder 'C:\msys64\usr' ...Yes.
... Looking for environment variable 'MW_MINGW64_LOC' ...Yes ('C:/msys64/usr/').
... Executing command 'C:\msys64\usr\bin\g++ -dumpmachine' ...Yes ('x86_64-pc-msys').
Found installed compiler 'MinGW64 Compiler (C++)'.
Set PATH = C:\msys64\usr\bin;C:\Program Files\MATLAB\R2018a\extern\include\win64;C:\Program Files\MATLAB\R2018a\extern\include;C:\Program Files\MATLAB\R2018a\simulink\include;C:\Program Files\MATLAB\R2018a\lib\win64;.;C:\msys64\opt\local\bin;C:\msys64\usr\local\cuda\bin\;.;C:\msys64\pub\bin;C:\msys64\pub\pgi\linux86-64\18.4\bin;C:\msys64\mingw64\bin;C:\msys64\usr\local\bin;C:\msys64\usr\bin;C:\msys64\usr\bin;C:\Windows\System32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\msys64\usr\bin\site_perl;C:\msys64\usr\bin\vendor_perl;C:\msys64\usr\bin\core_perl;C:\msys64\usr\local\bin;C:\msys64\home\users\fangq\space\Download\MCXStudio;C;C:\Program Files\MATLAB\R2018a\bin;C:\msys64\usr\lib\gcc\x86_64-pc-msys\9.3.0\
Set INCLUDE = C:\msys64\usr\include;C:\msys64\usr\x86_64-pc-msys\include\c++;C:\msys64\usr\x86_64-pc-msys\include;C:\msys64\usr\x86_64-pc-msys\include\c++\x86_64-pc-msys;C:\msys64\usr\x86_64-pc-msys\include\c++\backward;
Set LIB = C:\msys64\usr\lib;;
Set MW_TARGET_ARCH = win64;
Set LIBPATH = C:\Program Files\MATLAB\R2018a\extern\lib\win64;
Options file details
-------------------------------------------------------------------
        Compiler location: C:\msys64\usr
        Options file: C:\msys64\home\fangq\space\git\Project\mmc\src\mexopts_msys2_gcc.xml
        CMDLINE2 : C:\msys64\usr\bin\g++ -m64 -Wl,--no-undefined -static -fopenmp "c:\Windows\System32\OpenCL.dll" -fopenmp -shared -static -s -Wl,"C:\Program Files\MATLAB\R2018a/extern/lib/win64/mingw64/exportsmexfileversion.def" C:\msys64\tmp\mex_1481040925092289_7396\mmclab.obj C:\msys64\tmp\mex_1481040925092289_7396\cpp_mexapi_version.obj "built/xorshift128p_rand.o" "built/simpmesh.o" "built/tettracing.o" "built/mcx_utils.o" "built/tictoc.o" "built/mmc.o" "built/cjson/cJSON.o" "built/mmc_host.o" "built/highordermesh.o" "built/mmc_cl_utils.o" "built/mmc_cl_host.o"  -L"C:\Program Files\MATLAB\R2018a\extern\lib\win64\mingw64" -llibmx -llibmex -llibmat -o C:\msys64\home\fangq\space\git\Project\mmc\mmclab\mmc.mexw64
        CXX : C:\msys64\usr\bin\g++
        COMPILER : C:\msys64\usr\bin\g++
        DEFINES : -DMATLAB_DEFAULT_RELEASE=R2017b  -DUSE_MEX_CMD   -m64 -DMATLAB_MEX_FILE
        MATLABMEX : -DMATLAB_MEX_FILE
        CFLAGS :  -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -fexceptions -fno-omit-frame-pointer
        CXXFLAGS :  -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -fexceptions -fno-omit-frame-pointer
        INCLUDE : -I"..\src" -I".\mingw64\include"  -I"C:\msys64\usr\usr\include" -I"C:\Program Files\MATLAB\R2018a/extern/include" -I"C:\Program Files\MATLAB\R2018a/simulink/include"
        CXXOPTIMFLAGS : -O -DNDEBUG
        CXXDEBUGFLAGS : -g
        LDXX : C:\msys64\usr\bin\g++
        LINKER : C:\msys64\usr\bin\g++
        LDFLAGS : -m64 -Wl,--no-undefined -static -fopenmp "c:\Windows\System32\OpenCL.dll" -fopenmp
        LDTYPE : -shared -static
        LINKEXPORT : -Wl,"C:\Program Files\MATLAB\R2018a/extern/lib/win64/mingw64/mexFunction.def"
        LINKEXPORTVER : -Wl,"C:\Program Files\MATLAB\R2018a/extern/lib/win64/mingw64/exportsmexfileversion.def"
        LIBLOC : C:\Program Files\MATLAB\R2018a\extern\lib\win64\mingw64
        LINKLIBS : -L"C:\Program Files\MATLAB\R2018a\extern\lib\win64\mingw64" -llibmx -llibmex -llibmat
        LDOPTIMFLAGS : -s
        LDDEBUGFLAGS : -g
        OBJEXT : .obj
        LDEXT : .mexw64
        SETENV : set COMPILER=C:\msys64\usr\bin\gcc
                set CXXCOMPILER=C:\msys64\usr\bin\g++
                set COMPFLAGS=-c  -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -fexceptions -fno-omit-frame-pointer -DMATLAB_DEFAULT_RELEASE=R2017b  -DUSE_MEX_CMD   -m64 -DMATLAB_MEX_FILE  -DMATLAB_MEX_FILE
                set CXXCOMPFLAGS=-c  -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -DMATLAB_DEFAULT_RELEASE=R2017b  -DUSE_MEX_CMD   -m64 -DMATLAB_MEX_FILE  -DMATLAB_MEX_FILE
                set OPTIMFLAGS=-O -DNDEBUG
                set DEBUGFLAGS=-g
                set LINKER=C:\msys64\usr\bin\gcc
                set CXXLINKER=C:\msys64\usr\bin\g++
                set LINKFLAGS=-m64 -Wl,--no-undefined -static -fopenmp "c:\Windows\System32\OpenCL.dll" -fopenmp -shared -static -L"C:\Program Files\MATLAB\R2018a\extern\lib\win64\mingw64" -llibmx -llibmex -llibmat -Wl,"C:\Program Files\MATLAB\R2018a/extern/lib/win64/mingw64/mexFunction.def"
                set LINKDEBUGFLAGS=-g
                set NAME_OUTPUT= -o "%OUTDIR%%MEX_NAME%%MEX_EXT%"
        MINGWROOT : C:\msys64\usr
        MINGWTARGET : x86_64-pc-msys
        MATLABROOT : C:\Program Files\MATLAB\R2018a
        ARCH : win64
        SRC : "C:\msys64\home\fangq\space\git\Project\mmc\src\mmclab.cpp";"C:\Program Files\MATLAB\R2018a\extern\version\cpp_mexapi_version.cpp"
        OBJ : C:\msys64\tmp\mex_1481040925092289_7396\mmclab.obj;C:\msys64\tmp\mex_1481040925092289_7396\cpp_mexapi_version.obj
        OBJS : C:\msys64\tmp\mex_1481040925092289_7396\mmclab.obj C:\msys64\tmp\mex_1481040925092289_7396\cpp_mexapi_version.obj "built/xorshift128p_rand.o" "built/simpmesh.o" "built/tettracing.o" "built/mcx_utils.o" "built/tictoc.o" "built/mmc.o" "built/cjson/cJSON.o" "built/mmc_host.o" "built/highordermesh.o" "built/mmc_cl_utils.o" "built/mmc_cl_host.o"
        SRCROOT : C:\msys64\home\fangq\space\git\Project\mmc\src\mmclab
        DEF : C:\msys64\tmp\mex_1481040925092289_7396\mmc.def
        EXP : "C:\msys64\home\fangq\space\git\Project\mmc\mmclab\mmc.exp"
        LIB : "C:\msys64\home\fangq\space\git\Project\mmc\mmclab\mmc.lib"
        EXE : C:\msys64\home\fangq\space\git\Project\mmc\mmclab\mmc.mexw64
        ILK : "C:\msys64\home\fangq\space\git\Project\mmc\mmclab\mmc.ilk"
        MANIFEST : "C:\msys64\home\fangq\space\git\Project\mmc\mmclab\mmc.mexw64.manifest"
        TEMPNAME : C:\msys64\home\fangq\space\git\Project\mmc\mmclab\mmc
        EXEDIR : C:\msys64\home\fangq\space\git\Project\mmc\mmclab\
        EXENAME : mmc
        COMPFLAGS :  -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT
        OPTIM : -O -DNDEBUG
        LINKOPTIM : -s
        CMDLINE1_0 : C:\msys64\usr\bin\g++ -c -DMATLAB_DEFAULT_RELEASE=R2017b  -DUSE_MEX_CMD   -m64 -DMATLAB_MEX_FILE  -I"..\src" -I".\mingw64\include"  -I"C:\msys64\usr\usr\include" -I"C:\Program Files\MATLAB\R2018a/extern/include" -I"C:\Program Files\MATLAB\R2018a/simulink/include"  -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -fexceptions -fno-omit-frame-pointer -O -DNDEBUG "C:\msys64\home\fangq\space\git\Project\mmc\src\mmclab.cpp" -o C:\msys64\tmp\mex_1481040925092289_7396\mmclab.obj
        CMDLINE1_1 : C:\msys64\usr\bin\g++ -c -DMATLAB_DEFAULT_RELEASE=R2017b  -DUSE_MEX_CMD   -m64 -DMATLAB_MEX_FILE  -I"..\src" -I".\mingw64\include"  -I"C:\msys64\usr\usr\include" -I"C:\Program Files\MATLAB\R2018a/extern/include" -I"C:\Program Files\MATLAB\R2018a/simulink/include"  -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -fexceptions -fno-omit-frame-pointer -O -DNDEBUG "C:\Program Files\MATLAB\R2018a\extern\version\cpp_mexapi_version.cpp" -o C:\msys64\tmp\mex_1481040925092289_7396\cpp_mexapi_version.obj
-------------------------------------------------------------------
Building with 'MinGW64 Compiler (C++)'.
Warning: You are using an unsupported version of MinGW Compiler. To install the supported version of MinGW compiler, visit https://www.mathworks.com/help/matlab/matlab_external/install-mingw-support-package.html.
 For a list of currently supported compilers see: https://www.mathworks.com/support/compilers.
C:\msys64\usr\bin\g++ -c -DMATLAB_DEFAULT_RELEASE=R2017b  -DUSE_MEX_CMD   -m64 -DMATLAB_MEX_FILE  -I"..\src" -I".\mingw64\include"  -I"C:\msys64\usr\usr\include" -I"C:\Program Files\MATLAB\R2018a/extern/include" -I"C:\Program Files\MATLAB\R2018a/simulink/include"  -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -fexceptions -fno-omit-frame-pointer -O -DNDEBUG "C:\msys64\home\fangq\space\git\Project\mmc\src\mmclab.cpp" -o C:\msys64\tmp\mex_1481040925092289_7396\mmclab.obj
C:\msys64\usr\bin\g++ -c -DMATLAB_DEFAULT_RELEASE=R2017b  -DUSE_MEX_CMD   -m64 -DMATLAB_MEX_FILE  -I"..\src" -I".\mingw64\include"  -I"C:\msys64\usr\usr\include" -I"C:\Program Files\MATLAB\R2018a/extern/include" -I"C:\Program Files\MATLAB\R2018a/simulink/include"  -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -fexceptions -fno-omit-frame-pointer -O -DNDEBUG "C:\Program Files\MATLAB\R2018a\extern\version\cpp_mexapi_version.cpp" -o C:\msys64\tmp\mex_1481040925092289_7396\cpp_mexapi_version.obj
C:\msys64\usr\bin\g++ -m64 -Wl,--no-undefined -static -fopenmp "c:\Windows\System32\OpenCL.dll" -fopenmp -shared -static -s -Wl,"C:\Program Files\MATLAB\R2018a/extern/lib/win64/mingw64/exportsmexfileversion.def" C:\msys64\tmp\mex_1481040925092289_7396\mmclab.obj C:\msys64\tmp\mex_1481040925092289_7396\cpp_mexapi_version.obj "built/xorshift128p_rand.o" "built/simpmesh.o" "built/tettracing.o" "built/mcx_utils.o" "built/tictoc.o" "built/mmc.o" "built/cjson/cJSON.o" "built/mmc_host.o" "built/highordermesh.o" "built/mmc_cl_utils.o" "built/mmc_cl_host.o"  -L"C:\Program Files\MATLAB\R2018a\extern\lib\win64\mingw64" -llibmx -llibmex -llibmat -o C:\msys64\home\fangq\space\git\Project\mmc\mmclab\mmc.mexw64
Recompile embedded version with '-DMATLAB_MEXCMD_RELEASE=R2017b'
C:\msys64\usr\bin\g++ -c -DMATLAB_DEFAULT_RELEASE=R2017b  -DUSE_MEX_CMD   -m64 -DMATLAB_MEX_FILE  -I"..\src" -I".\mingw64\include"  -I"C:\msys64\usr\usr\include" -I"C:\Program Files\MATLAB\R2018a/extern/include" -I"C:\Program Files\MATLAB\R2018a/simulink/include"  -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -fexceptions -fno-omit-frame-pointer -O -DNDEBUG "C:\Program Files\MATLAB\R2018a\extern\version\cpp_mexapi_version.cpp" -o C:\msys64\tmp\mex_1481040925092289_7396\cpp_mexapi_version.obj -DMATLAB_MEXCMD_RELEASE=R2017b
C:\msys64\usr\bin\g++ -m64 -Wl,--no-undefined -static -fopenmp "c:\Windows\System32\OpenCL.dll" -fopenmp -shared -static -s -Wl,"C:\Program Files\MATLAB\R2018a/extern/lib/win64/mingw64/exportsmexfileversion.def" C:\msys64\tmp\mex_1481040925092289_7396\mmclab.obj C:\msys64\tmp\mex_1481040925092289_7396\cpp_mexapi_version.obj "built/xorshift128p_rand.o" "built/simpmesh.o" "built/tettracing.o" "built/mcx_utils.o" "built/tictoc.o" "built/mmc.o" "built/cjson/cJSON.o" "built/mmc_host.o" "built/highordermesh.o" "built/mmc_cl_utils.o" "built/mmc_cl_host.o"  -L"C:\Program Files\MATLAB\R2018a\extern\lib\win64\mingw64" -llibmx -llibmex -llibmat -o C:\msys64\home\fangq\space\git\Project\mmc\mmclab\mmc.mexw64
MEX completed successfully.
fangq@zen:~/space/git/Project/mmc/src$ which gcc
/usr/bin/gcc
fangq@zen:~/space/git/Project/mmc/src$ which g++
/usr/bin/g++
fangq@zen:~/space/git/Project/mmc/src$ which cc
/usr/bin/cc
fangq@zen:~/space/git/Project/mmc/src$ gcc --version
gcc (GCC) 9.3.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
</code>```

答:
What is the reason you included ioctl.h?

Copying that header from somewhere else is a bad idea. At best it will define functions for which libraries don't exist causing linker errors.

Typically you would need to use Windows alternatives for whatever IOCTL stuff you do on other platforms.

I tried to compile MMC on Windows with MSYS2 removing this include and the build succeeded:

```<code>patch -ulbf src/mcx_utils.c << EOF
@@ -35,3 +35,5 @@
 #include <time.h>
+#ifndef _WIN32
 #include <sys/ioctl.h>
+#endif
 #include "mcx_utils.h"
EOF
sed -i.bak -e "s/^EXTRALIB\s*+*=.*$/& -Wl,--as-needed -lwinmm/" commons/Makefile_common.mk
~/buildstatus.sh build &&
 make -Csrc CC=gcc PLATFORM=MINGW32 &&
 echo Success
</code>```

Body:
My codes (https://github.com/fangq/mmc, https://github.com/fangq/mcxcl) have been compiled out-of-box using gcc on Linux & Mac, cygwin-gcc or msys2-gcc on Windows, but not with MinGW compilers (x86-64-mingw64-* compilers for cygwin64, msys2, mingw64 or TDM-GCC, or matlab mingw64 support (mingw64 gcc 4.9.6)) because it complains that it misses a set of header files (sys/ioctl.h, ieee754.h etc), so I included a copy of these header files in my source code, and added -I./mingw64/include to make most of them compile

https://github.com/fangq/mmc/tree/master/src/mingw64/include

however, when compiling the matlab mex file using this script on MATLAB R2016/2018, I received the below error

Error using mex
mcx_utils.o: In function `mcx_progressbar':
D:/Users/fangq/Gitroot/Project/mmc/src/mcx_utils.c:1054: undefined reference to `ioctl'
collect2.exe: error: ld returned 1 exit status

I am wondering why compiling inside matlab and outside matlab are different. Is there a library that I can link to fix the undefined reference to "ioctl" error?

Here is the log when compiling using gcc on msys2:

fangq@zen:~/space/git/Project/mmc/src$ make mex
Building built/xorshift128p_rand.o
cc -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -I../src -I"./mingw64/include" -o built/xorshift128p_rand.o  xorshift128p_rand.c
Building built/simpmesh.o
cc -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -I../src -I"./mingw64/include" -o built/simpmesh.o  simpmesh.c
Building built/tettracing.o
cc -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -I../src -I"./mingw64/include" -o built/tettracing.o  tettracing.c
Building built/mcx_utils.o
cc -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -I../src -I"./mingw64/include" -o built/mcx_utils.o  mcx_utils.c
Building built/tictoc.o
cc -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -I../src -I"./mingw64/include" -o built/tictoc.o  tictoc.c
Building built/mmc.o
cc -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -I../src -I"./mingw64/include" -o built/mmc.o  mmc.c
Building built/cjson/cJSON.o
cc -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -I../src -I"./mingw64/include" -o built/cjson/cJSON.o  cjson/cJSON.c
Building built/mmc_host.o
cc -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -I../src -I"./mingw64/include" -o built/mmc_host.o  mmc_host.c
Building built/highordermesh.o
g++ -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -I../src -I"./mingw64/include" -o built/highordermesh.o  highordermesh.cpp
Building built/mmc_cl_utils.o
cc -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -I../src -I"./mingw64/include" -o built/mmc_cl_utils.o  mmc_cl_utils.c
Building built/mmc_cl_host.o
cc -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -I../src -I"./mingw64/include" -o built/mmc_cl_host.o  mmc_cl_host.c
Building bin/mmc
cmd //c mex.bat   -v -f mexopts_msys2_gcc.xml COMPFLAGS='$COMPFLAGS -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT' LDFLAGS='$LDFLAGS -static -fopenmp "c:\Windows\System32\OpenCL.dll" -fopenmp'  -outdir ../mmclab mmclab.cpp -I../src -I"./mingw64/include" -output bin/mmc built/xorshift128p_rand.o built/simpmesh.o built/tettracing.o built/mcx_utils.o built/tictoc.o built/mmc.o built/cjson/cJSON.o built/mmc_host.o built/highordermesh.o built/mmc_cl_utils.o built/mmc_cl_host.o
Verbose mode is on.
... Looking for compiler 'MinGW64 Compiler (C++)' ...
... Looking for environment variable 'MW_MINGW64_LOC' ...Yes ('C:/msys64/usr/').
... Looking for file 'C:\msys64\usr\bin\g++.exe' ...Yes.
... Looking for folder 'C:\msys64\usr' ...Yes.
... Looking for environment variable 'MW_MINGW64_LOC' ...Yes ('C:/msys64/usr/').
... Executing command 'C:\msys64\usr\bin\g++ -dumpmachine' ...Yes ('x86_64-pc-msys').
Found installed compiler 'MinGW64 Compiler (C++)'.
Set PATH = C:\msys64\usr\bin;C:\Program Files\MATLAB\R2018a\extern\include\win64;C:\Program Files\MATLAB\R2018a\extern\include;C:\Program Files\MATLAB\R2018a\simulink\include;C:\Program Files\MATLAB\R2018a\lib\win64;.;C:\msys64\opt\local\bin;C:\msys64\usr\local\cuda\bin\;.;C:\msys64\pub\bin;C:\msys64\pub\pgi\linux86-64\18.4\bin;C:\msys64\mingw64\bin;C:\msys64\usr\local\bin;C:\msys64\usr\bin;C:\msys64\usr\bin;C:\Windows\System32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\msys64\usr\bin\site_perl;C:\msys64\usr\bin\vendor_perl;C:\msys64\usr\bin\core_perl;C:\msys64\usr\local\bin;C:\msys64\home\users\fangq\space\Download\MCXStudio;C;C:\Program Files\MATLAB\R2018a\bin;C:\msys64\usr\lib\gcc\x86_64-pc-msys\9.3.0\
Set INCLUDE = C:\msys64\usr\include;C:\msys64\usr\x86_64-pc-msys\include\c++;C:\msys64\usr\x86_64-pc-msys\include;C:\msys64\usr\x86_64-pc-msys\include\c++\x86_64-pc-msys;C:\msys64\usr\x86_64-pc-msys\include\c++\backward;
Set LIB = C:\msys64\usr\lib;;
Set MW_TARGET_ARCH = win64;
Set LIBPATH = C:\Program Files\MATLAB\R2018a\extern\lib\win64;
Options file details
-------------------------------------------------------------------
        Compiler location: C:\msys64\usr
        Options file: C:\msys64\home\fangq\space\git\Project\mmc\src\mexopts_msys2_gcc.xml
        CMDLINE2 : C:\msys64\usr\bin\g++ -m64 -Wl,--no-undefined -static -fopenmp "c:\Windows\System32\OpenCL.dll" -fopenmp -shared -static -s -Wl,"C:\Program Files\MATLAB\R2018a/extern/lib/win64/mingw64/exportsmexfileversion.def" C:\msys64\tmp\mex_1481040925092289_7396\mmclab.obj C:\msys64\tmp\mex_1481040925092289_7396\cpp_mexapi_version.obj "built/xorshift128p_rand.o" "built/simpmesh.o" "built/tettracing.o" "built/mcx_utils.o" "built/tictoc.o" "built/mmc.o" "built/cjson/cJSON.o" "built/mmc_host.o" "built/highordermesh.o" "built/mmc_cl_utils.o" "built/mmc_cl_host.o"  -L"C:\Program Files\MATLAB\R2018a\extern\lib\win64\mingw64" -llibmx -llibmex -llibmat -o C:\msys64\home\fangq\space\git\Project\mmc\mmclab\mmc.mexw64
        CXX : C:\msys64\usr\bin\g++
        COMPILER : C:\msys64\usr\bin\g++
        DEFINES : -DMATLAB_DEFAULT_RELEASE=R2017b  -DUSE_MEX_CMD   -m64 -DMATLAB_MEX_FILE
        MATLABMEX : -DMATLAB_MEX_FILE
        CFLAGS :  -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -fexceptions -fno-omit-frame-pointer
        CXXFLAGS :  -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -fexceptions -fno-omit-frame-pointer
        INCLUDE : -I"..\src" -I".\mingw64\include"  -I"C:\msys64\usr\usr\include" -I"C:\Program Files\MATLAB\R2018a/extern/include" -I"C:\Program Files\MATLAB\R2018a/simulink/include"
        CXXOPTIMFLAGS : -O -DNDEBUG
        CXXDEBUGFLAGS : -g
        LDXX : C:\msys64\usr\bin\g++
        LINKER : C:\msys64\usr\bin\g++
        LDFLAGS : -m64 -Wl,--no-undefined -static -fopenmp "c:\Windows\System32\OpenCL.dll" -fopenmp
        LDTYPE : -shared -static
        LINKEXPORT : -Wl,"C:\Program Files\MATLAB\R2018a/extern/lib/win64/mingw64/mexFunction.def"
        LINKEXPORTVER : -Wl,"C:\Program Files\MATLAB\R2018a/extern/lib/win64/mingw64/exportsmexfileversion.def"
        LIBLOC : C:\Program Files\MATLAB\R2018a\extern\lib\win64\mingw64
        LINKLIBS : -L"C:\Program Files\MATLAB\R2018a\extern\lib\win64\mingw64" -llibmx -llibmex -llibmat
        LDOPTIMFLAGS : -s
        LDDEBUGFLAGS : -g
        OBJEXT : .obj
        LDEXT : .mexw64
        SETENV : set COMPILER=C:\msys64\usr\bin\gcc
                set CXXCOMPILER=C:\msys64\usr\bin\g++
                set COMPFLAGS=-c  -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -fexceptions -fno-omit-frame-pointer -DMATLAB_DEFAULT_RELEASE=R2017b  -DUSE_MEX_CMD   -m64 -DMATLAB_MEX_FILE  -DMATLAB_MEX_FILE
                set CXXCOMPFLAGS=-c  -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -DMATLAB_DEFAULT_RELEASE=R2017b  -DUSE_MEX_CMD   -m64 -DMATLAB_MEX_FILE  -DMATLAB_MEX_FILE
                set OPTIMFLAGS=-O -DNDEBUG
                set DEBUGFLAGS=-g
                set LINKER=C:\msys64\usr\bin\gcc
                set CXXLINKER=C:\msys64\usr\bin\g++
                set LINKFLAGS=-m64 -Wl,--no-undefined -static -fopenmp "c:\Windows\System32\OpenCL.dll" -fopenmp -shared -static -L"C:\Program Files\MATLAB\R2018a\extern\lib\win64\mingw64" -llibmx -llibmex -llibmat -Wl,"C:\Program Files\MATLAB\R2018a/extern/lib/win64/mingw64/mexFunction.def"
                set LINKDEBUGFLAGS=-g
                set NAME_OUTPUT= -o "%OUTDIR%%MEX_NAME%%MEX_EXT%"
        MINGWROOT : C:\msys64\usr
        MINGWTARGET : x86_64-pc-msys
        MATLABROOT : C:\Program Files\MATLAB\R2018a
        ARCH : win64
        SRC : "C:\msys64\home\fangq\space\git\Project\mmc\src\mmclab.cpp";"C:\Program Files\MATLAB\R2018a\extern\version\cpp_mexapi_version.cpp"
        OBJ : C:\msys64\tmp\mex_1481040925092289_7396\mmclab.obj;C:\msys64\tmp\mex_1481040925092289_7396\cpp_mexapi_version.obj
        OBJS : C:\msys64\tmp\mex_1481040925092289_7396\mmclab.obj C:\msys64\tmp\mex_1481040925092289_7396\cpp_mexapi_version.obj "built/xorshift128p_rand.o" "built/simpmesh.o" "built/tettracing.o" "built/mcx_utils.o" "built/tictoc.o" "built/mmc.o" "built/cjson/cJSON.o" "built/mmc_host.o" "built/highordermesh.o" "built/mmc_cl_utils.o" "built/mmc_cl_host.o"
        SRCROOT : C:\msys64\home\fangq\space\git\Project\mmc\src\mmclab
        DEF : C:\msys64\tmp\mex_1481040925092289_7396\mmc.def
        EXP : "C:\msys64\home\fangq\space\git\Project\mmc\mmclab\mmc.exp"
        LIB : "C:\msys64\home\fangq\space\git\Project\mmc\mmclab\mmc.lib"
        EXE : C:\msys64\home\fangq\space\git\Project\mmc\mmclab\mmc.mexw64
        ILK : "C:\msys64\home\fangq\space\git\Project\mmc\mmclab\mmc.ilk"
        MANIFEST : "C:\msys64\home\fangq\space\git\Project\mmc\mmclab\mmc.mexw64.manifest"
        TEMPNAME : C:\msys64\home\fangq\space\git\Project\mmc\mmclab\mmc
        EXEDIR : C:\msys64\home\fangq\space\git\Project\mmc\mmclab\
        EXENAME : mmc
        COMPFLAGS :  -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT
        OPTIM : -O -DNDEBUG
        LINKOPTIM : -s
        CMDLINE1_0 : C:\msys64\usr\bin\g++ -c -DMATLAB_DEFAULT_RELEASE=R2017b  -DUSE_MEX_CMD   -m64 -DMATLAB_MEX_FILE  -I"..\src" -I".\mingw64\include"  -I"C:\msys64\usr\usr\include" -I"C:\Program Files\MATLAB\R2018a/extern/include" -I"C:\Program Files\MATLAB\R2018a/simulink/include"  -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -fexceptions -fno-omit-frame-pointer -O -DNDEBUG "C:\msys64\home\fangq\space\git\Project\mmc\src\mmclab.cpp" -o C:\msys64\tmp\mex_1481040925092289_7396\mmclab.obj
        CMDLINE1_1 : C:\msys64\usr\bin\g++ -c -DMATLAB_DEFAULT_RELEASE=R2017b  -DUSE_MEX_CMD   -m64 -DMATLAB_MEX_FILE  -I"..\src" -I".\mingw64\include"  -I"C:\msys64\usr\usr\include" -I"C:\Program Files\MATLAB\R2018a/extern/include" -I"C:\Program Files\MATLAB\R2018a/simulink/include"  -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -fexceptions -fno-omit-frame-pointer -O -DNDEBUG "C:\Program Files\MATLAB\R2018a\extern\version\cpp_mexapi_version.cpp" -o C:\msys64\tmp\mex_1481040925092289_7396\cpp_mexapi_version.obj
-------------------------------------------------------------------
Building with 'MinGW64 Compiler (C++)'.
Warning: You are using an unsupported version of MinGW Compiler. To install the supported version of MinGW compiler, visit https://www.mathworks.com/help/matlab/matlab_external/install-mingw-support-package.html.
 For a list of currently supported compilers see: https://www.mathworks.com/support/compilers.
C:\msys64\usr\bin\g++ -c -DMATLAB_DEFAULT_RELEASE=R2017b  -DUSE_MEX_CMD   -m64 -DMATLAB_MEX_FILE  -I"..\src" -I".\mingw64\include"  -I"C:\msys64\usr\usr\include" -I"C:\Program Files\MATLAB\R2018a/extern/include" -I"C:\Program Files\MATLAB\R2018a/simulink/include"  -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -fexceptions -fno-omit-frame-pointer -O -DNDEBUG "C:\msys64\home\fangq\space\git\Project\mmc\src\mmclab.cpp" -o C:\msys64\tmp\mex_1481040925092289_7396\mmclab.obj
C:\msys64\usr\bin\g++ -c -DMATLAB_DEFAULT_RELEASE=R2017b  -DUSE_MEX_CMD   -m64 -DMATLAB_MEX_FILE  -I"..\src" -I".\mingw64\include"  -I"C:\msys64\usr\usr\include" -I"C:\Program Files\MATLAB\R2018a/extern/include" -I"C:\Program Files\MATLAB\R2018a/simulink/include"  -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -fexceptions -fno-omit-frame-pointer -O -DNDEBUG "C:\Program Files\MATLAB\R2018a\extern\version\cpp_mexapi_version.cpp" -o C:\msys64\tmp\mex_1481040925092289_7396\cpp_mexapi_version.obj
C:\msys64\usr\bin\g++ -m64 -Wl,--no-undefined -static -fopenmp "c:\Windows\System32\OpenCL.dll" -fopenmp -shared -static -s -Wl,"C:\Program Files\MATLAB\R2018a/extern/lib/win64/mingw64/exportsmexfileversion.def" C:\msys64\tmp\mex_1481040925092289_7396\mmclab.obj C:\msys64\tmp\mex_1481040925092289_7396\cpp_mexapi_version.obj "built/xorshift128p_rand.o" "built/simpmesh.o" "built/tettracing.o" "built/mcx_utils.o" "built/tictoc.o" "built/mmc.o" "built/cjson/cJSON.o" "built/mmc_host.o" "built/highordermesh.o" "built/mmc_cl_utils.o" "built/mmc_cl_host.o"  -L"C:\Program Files\MATLAB\R2018a\extern\lib\win64\mingw64" -llibmx -llibmex -llibmat -o C:\msys64\home\fangq\space\git\Project\mmc\mmclab\mmc.mexw64
Recompile embedded version with '-DMATLAB_MEXCMD_RELEASE=R2017b'
C:\msys64\usr\bin\g++ -c -DMATLAB_DEFAULT_RELEASE=R2017b  -DUSE_MEX_CMD   -m64 -DMATLAB_MEX_FILE  -I"..\src" -I".\mingw64\include"  -I"C:\msys64\usr\usr\include" -I"C:\Program Files\MATLAB\R2018a/extern/include" -I"C:\Program Files\MATLAB\R2018a/simulink/include"  -c -Wall -g -DMCX_EMBED_CL -fno-strict-aliasing -m64 -DMMC_USE_SSE -DHAVE_SSE2 -msse -msse2 -msse3 -mssse3 -msse4.1 -O3 -fopenmp   -DMCX_CONTAINER -DUSE_OS_TIMER -DUSE_OPENCL -DMMC_XORSHIFT -fexceptions -fno-omit-frame-pointer -O -DNDEBUG "C:\Program Files\MATLAB\R2018a\extern\version\cpp_mexapi_version.cpp" -o C:\msys64\tmp\mex_1481040925092289_7396\cpp_mexapi_version.obj -DMATLAB_MEXCMD_RELEASE=R2017b
C:\msys64\usr\bin\g++ -m64 -Wl,--no-undefined -static -fopenmp "c:\Windows\System32\OpenCL.dll" -fopenmp -shared -static -s -Wl,"C:\Program Files\MATLAB\R2018a/extern/lib/win64/mingw64/exportsmexfileversion.def" C:\msys64\tmp\mex_1481040925092289_7396\mmclab.obj C:\msys64\tmp\mex_1481040925092289_7396\cpp_mexapi_version.obj "built/xorshift128p_rand.o" "built/simpmesh.o" "built/tettracing.o" "built/mcx_utils.o" "built/tictoc.o" "built/mmc.o" "built/cjson/cJSON.o" "built/mmc_host.o" "built/highordermesh.o" "built/mmc_cl_utils.o" "built/mmc_cl_host.o"  -L"C:\Program Files\MATLAB\R2018a\extern\lib\win64\mingw64" -llibmx -llibmex -llibmat -o C:\msys64\home\fangq\space\git\Project\mmc\mmclab\mmc.mexw64
MEX completed successfully.
fangq@zen:~/space/git/Project/mmc/src$ which gcc
/usr/bin/gcc
fangq@zen:~/space/git/Project/mmc/src$ which g++
/usr/bin/g++
fangq@zen:~/space/git/Project/mmc/src$ which cc
/usr/bin/cc
fangq@zen:~/space/git/Project/mmc/src$ gcc --version
gcc (GCC) 9.3.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Body:
What is the reason you included ioctl.h?

Copying that header from somewhere else is a bad idea. At best it will define functions for which libraries don't exist causing linker errors.

Typically you would need to use Windows alternatives for whatever IOCTL stuff you do on other platforms.

I tried to compile MMC on Windows with MSYS2 removing this include and the build succeeded:

patch -ulbf src/mcx_utils.c << EOF
@@ -35,3 +35,5 @@
 #include <time.h>
+#ifndef _WIN32
 #include <sys/ioctl.h>
+#endif
 #include "mcx_utils.h"
EOF
sed -i.bak -e "s/^EXTRALIB\s*+*=.*$/& -Wl,--as-needed -lwinmm/" commons/Makefile_common.mk
~/buildstatus.sh build &&
 make -Csrc CC=gcc PLATFORM=MINGW32 &&
 echo Success


来源: stackexchange

问:
How to set the dragging state properly when user drags out of the dragging zone using react and typescript?
i want to be able to drag and drop file into the DropZone div. when user drags in or drags out of the DropZone div i want the background color of the DropZone div to be grey.

Below is my code,

```<code>function MainComponent () {
return (
    <Wrapper>
        <SomeOtheComponent/>
        <DragAndDrop>
            <ListContent> //this is the children for the DragAndDrop component and want this to
                //render within DragAndDrop component
                {condition_true && (
                    <FirstList/>
                )}
                {condition_true && (
                    <SecondList/>
                )}
            </ListContent>
        </Wrapper>
    );
}

const DragAndDrop: React.FC = ({ children }) => { //here i am passing children
    const [dragging, setDragging] = useState(false);
    const [dragCounter, setDragCounter] = useState(0);

    React.useEffect(() => {
        // componentDidMount()
        setDragCounter(0);
    }, []);

    const handleDrag = (e: any) => {
        e.preventDefault();
        e.stopPropagation();
    };

    const handleDragIn = (e: any) => {
        e.preventDefault();
        e.stopPropagation();
        setDragCounter((prev: number) => prev + 1);
        if (e.dataTransfer.files) {
            setDragging(true);
        }

    };

    const handleDragOut = (e: any) => {
        e.preventDefault();
        e.stopPropagation();
        setDragCounter((prev: number) => prev - 1);
        if (dragCounter === 0) {
            setDragging(false);
        }
    };

    const handleDrop = (e: any) => {
        e.preventDefault();
        e.stopPropagation();
        setDragging(false);
        if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
            e.dataTransfer.clearData();
            setDragCounter(0);
        }
    };

    return (
        <DropZone //this is a styled component div and dropzone area where user can drop files
            onDragEnter={handleDragIn}
            dragging={dragging}
            onDragLeave={handleDragOut}
            onDragOver={handleDrag}
            onDrop={handleDrop}
        >
    );
};
</code>```

Now this works fine however, when user drags file onto dropzone div dragging state is true and now if user drags file out of dropzone div (which is handleDragOut) the dragging state is still true.

It should be false...also i am not sure if i am setting dragcounter value correct or is needed.

Could someone help me fix this. thanks.

答:
Your handleDragOut handler checks if dragCounter is zero, but this state hasn't been updated yet.

Here's an updated version:

    const handleDragOut = (e: any) => {
        e.preventDefault();
        e.stopPropagation();
        setDragCounter((prev: number) => prev - 1);

        if (dragCounter > 1) return;
        setDragging(false);
    };
```

<p>And <code>handleDrop</code> should reset the counter regardless:</p>

<pre class="lang-js prettyprint-override"><code>  const handleDrop = (e) => {
      e.preventDefault();
      e.stopPropagation();
      setDragging(false);
      setDragCounter(0);
      if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
          e.dataTransfer.clearData();
      }
  };
</code>```

In my opinion, a cleaner solution would be to use useRef for the counter. That way, counter updates won't cause unnecessary renders, and the counter is up-to-date right after it has been incremented/decremented.

Here's an example:

const DragAndDrop = ({ onUpload, children }) => {
  const [isDragging, setIsDragging] = React.useState(false);

  const dragCount = React.useRef(0);

  const handleDragIn = (e) => {
    e.preventDefault();
    e.stopPropagation();

    dragCount.current++;
    setIsDragging(true);
  };

  const handleDrag = (e) => {
    e.preventDefault();
    e.stopPropagation();

    setIsDragging(true);
  };

  const handleDragOut = (e) => {
    e.preventDefault();
    e.stopPropagation();

    dragCount.current--;
    if (dragCount.current > 0) return;
    setIsDragging(false);
  };

  const handleDrop = (e) => {
    e.preventDefault();
    e.stopPropagation();

    setIsDragging(false);
    dragCount.current = 0;
    const dt = e.dataTransfer;
    const files = dt.files; // FileList

    // Handle files ...
  };

  return (

      Drag here

A nested div

  );
};
```

In your case, instead of rendering a div, render the DropZone styled component like you did previously.

ContentLicense: CC BY-SA 4.0

Body:
i want to be able to drag and drop file into the DropZone div. when user drags in or drags out of the DropZone div i want the background color of the DropZone div to be grey.

Below is my code,

function MainComponent () {
return (
    <Wrapper>
        <SomeOtheComponent/>
        <DragAndDrop>
            <ListContent> //this is the children for the DragAndDrop component and want this to
                //render within DragAndDrop component
                {condition_true && (
                    <FirstList/>
                )}
                {condition_true && (
                    <SecondList/>
                )}
            </ListContent>
        </Wrapper>
    );
}

const DragAndDrop: React.FC = ({ children }) => { //here i am passing children
    const [dragging, setDragging] = useState(false);
    const [dragCounter, setDragCounter] = useState(0);

    React.useEffect(() => {
        // componentDidMount()
        setDragCounter(0);
    }, []);

    const handleDrag = (e: any) => {
        e.preventDefault();
        e.stopPropagation();
    };

    const handleDragIn = (e: any) => {
        e.preventDefault();
        e.stopPropagation();
        setDragCounter((prev: number) => prev + 1);
        if (e.dataTransfer.files) {
            setDragging(true);
        }

    };

    const handleDragOut = (e: any) => {
        e.preventDefault();
        e.stopPropagation();
        setDragCounter((prev: number) => prev - 1);
        if (dragCounter === 0) {
            setDragging(false);
        }
    };

    const handleDrop = (e: any) => {
        e.preventDefault();
        e.stopPropagation();
        setDragging(false);
        if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
            e.dataTransfer.clearData();
            setDragCounter(0);
        }
    };

    return (
        <DropZone //this is a styled component div and dropzone area where user can drop files
            onDragEnter={handleDragIn}
            dragging={dragging}
            onDragLeave={handleDragOut}
            onDragOver={handleDrag}
            onDrop={handleDrop}
        >
    );
};

Now this works fine however, when user drags file onto dropzone div dragging state is true and now if user drags file out of dropzone div (which is handleDragOut) the dragging state is still true.

It should be false...also i am not sure if i am setting dragcounter value correct or is needed.

Could someone help me fix this. thanks.

Body:
Your handleDragOut handler checks if dragCounter is zero, but this state hasn't been updated yet.

Here's an updated version:

    const handleDragOut = (e: any) => {
        e.preventDefault();
        e.stopPropagation();
        setDragCounter((prev: number) => prev - 1);

        if (dragCounter > 1) return;
        setDragging(false);
    };

And handleDrop should reset the counter regardless:

  const handleDrop = (e) => {
      e.preventDefault();
      e.stopPropagation();
      setDragging(false);
      setDragCounter(0);
      if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
          e.dataTransfer.clearData();
      }
  };

In my opinion, a cleaner solution would be to use useRef for the counter. That way, counter updates won't cause unnecessary renders, and the counter is up-to-date right after it has been incremented/decremented.

Here's an example:

const DragAndDrop = ({ onUpload, children }) => {
  const [isDragging, setIsDragging] = React.useState(false);

  const dragCount = React.useRef(0);

  const handleDragIn = (e) => {
    e.preventDefault();
    e.stopPropagation();

    dragCount.current++;
    setIsDragging(true);
  };

  const handleDrag = (e) => {
    e.preventDefault();
    e.stopPropagation();

    setIsDragging(true);
  };

  const handleDragOut = (e) => {
    e.preventDefault();
    e.stopPropagation();

    dragCount.current--;
    if (dragCount.current > 0) return;
    setIsDragging(false);
  };

  const handleDrop = (e) => {
    e.preventDefault();
    e.stopPropagation();

    setIsDragging(false);
    dragCount.current = 0;
    const dt = e.dataTransfer;
    const files = dt.files; // FileList

    // Handle files ...
  };

  return (
    <div
      style={{ backgroundColor: isDragging ? 'red' : 'gray', padding: '20px'}}
      onDragEnter={handleDragIn}
      onDragOver={handleDrag}
      onDragLeave={handleDragOut}
      onDrop={handleDrop}
    >
      Drag here
      <div>A nested div</div>
    </div>
  );
};

In your case, instead of rendering a div, render the DropZone styled component like you did previously.


Title: How can I convert matrix to different matrices in R?

Body:
Here I have some codes generating a matrix like this:

N = 200
T = 10
mu_0 <- matrix(diag(1, T))
dim(mu_0) <- c(T,T)
mu_t_0 <- matrix(rep(t(mu_0), N), ncol = T, byrow = TRUE)

And generally the result looks like this

   V1   V2  V3  V4  V5  V6  V7  V8  V9 V10
1   1   0   0   0   0   0   0   0   0   0
2   0   1   0   0   0   0   0   0   0   0
3   0   0   1   0   0   0   0   0   0   0
4   0   0   0   1   0   0   0   0   0   0
5   0   0   0   0   1   0   0   0   0   0
6   0   0   0   0   0   1   0   0   0   0
7   0   0   0   0   0   0   1   0   0   0
8   0   0   0   0   0   0   0   1   0   0
9   0   0   0   0   0   0   0   0   1   0
10  0   0   0   0   0   0   0   0   0   1
11  1   0   0   0   0   0   0   0   0   0
12  0   1   0   0   0   0   0   0   0   0
13  0   0   1   0   0   0   0   0   0   0
14  0   0   0   1   0   0   0   0   0   0
15  0   0   0   0   1   0   0   0   0   0
16  0   0   0   0   0   1   0   0   0   0
17  0   0   0   0   0   0   1   0   0   0
18  0   0   0   0   0   0   0   1   0   0
19  0   0   0   0   0   0   0   0   1   0
20  0   0   0   0   0   0   0   0   0   1
...

Now for later calculation I want to split this large matrix into different small matrices like this:

Matrix One:

1
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
...

Matrix Two:

0
1
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
...

I tried the split function but I cannot get what I want. Are there any solutions?

Body:
You can use asplit to split an array or matrix by its margin.

x <- asplit(mu_t_0, 2)
str(x)
#List of 10
# $ : num [1:2000(1d)] 1 0 0 0 0 0 0 0 0 0 ...
# $ : num [1:2000(1d)] 0 1 0 0 0 0 0 0 0 0 ...
# $ : num [1:2000(1d)] 0 0 1 0 0 0 0 0 0 0 ...
# $ : num [1:2000(1d)] 0 0 0 1 0 0 0 0 0 0 ...
# $ : num [1:2000(1d)] 0 0 0 0 1 0 0 0 0 0 ...
# $ : num [1:2000(1d)] 0 0 0 0 0 1 0 0 0 0 ...
# $ : num [1:2000(1d)] 0 0 0 0 0 0 1 0 0 0 ...
# $ : num [1:2000(1d)] 0 0 0 0 0 0 0 1 0 0 ...
# $ : num [1:2000(1d)] 0 0 0 0 0 0 0 0 1 0 ...
# $ : num [1:2000(1d)] 0 0 0 0 0 0 0 0 0 1 ...
# - attr(*, "dim")= int 10


问:
Doing while with html and php
Hello i have done whiles with php but never html...
I have a script that works fine but looks ugly so a friend has made me a html layout.

Here is my php script.

```<code><p>

    <?php
        /* Place code to connect to your DB here.     */

        $tbl_name="adds";        //your table name
        // How many adjacent pages should be shown on each side?
        $adjacents = 3;
        /*
        First get total number of rows in data table.
        If you have a WHERE clause in your query, make sure you mirror it here.
        */

        $query = "SELECT COUNT(*) as num FROM adds ";
        $total_pages = mysql_fetch_array(mysql_query($query));
        $total_pages = $total_pages['num'];
        /* Setup vars for query. */
        $targetpage = "earn.php";     //your file name  (the name of this file)
        $limit = 6;
        //how many items to show per page
        $page = isset($_GET['page']) ? $_GET['page'] : 0;
        if($page)
            $start = ($page - 1) * $limit;
        //first item to display on this page
        else
            $start = 0;                                //if no page var is given, set start to 0
        /* Get data. */
        $sql = "SELECT * FROM $tbl_name LIMIT $start, $limit ";
        $result = mysql_query($sql);
        /* Setup page vars for display. */
        if ($page == 0) $page = 1;                    //if no page var is given, default to 1.
        $prev = $page - 1;                            //previous page is page - 1
        $next = $page + 1;                            //next page is page + 1
        $lastpage = ceil($total_pages/$limit);        //lastpage is = total pages / items per page, rounded up.
        $lpm1 = $lastpage - 1;                        //last page minus 1
        /*
        Now we apply our rules and draw the pagination object.
        We're actually saving the code to a variable in case
        we want to draw it more than once.
        */

        $pagination = "";
        if($lastpage > 1)
        {
            $pagination .= "<div class=\"pagination\">";         //previous button
            if ($page > 1)
                $pagination.= "<a href=\"$targetpage?page=$prev\">« previous</a>";
            else
                $pagination.= "<span class=\"disabled\">« previous</span>";
            //pages
            if ($lastpage < 7 + ($adjacents * 2))    //not enough pages to bother breaking it up
            {
                for ($counter = 1; $counter <= $lastpage; $counter++)             {
                    if ($counter == $page)
                        $pagination.= "<span class=\"current\">$counter</span>";
                    else
                        $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>";
            }         }         elseif($lastpage > 5 + ($adjacents * 2))    //enough pages to hide some
            {
                //close to beginning; only hide later pages
                if($page < 1 + ($adjacents * 2))                     {
                    for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
                    {
                        if ($counter == $page)
                            $pagination.= "<span class=\"current\">$counter</span>";
                        else
                            $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>";
                    }
                    $pagination.= "...";
                    $pagination.= "<a href=\"$targetpage?page=$lpm1\">$lpm1</a>";
                    $pagination.= "<a href=\"$targetpage?page=$lastpage\">$lastpage</a>";
                }             //in middle; hide some front and some back
                elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))             {
                    $pagination.= "<a href=\"$targetpage?page=1\">1</a>";
                    $pagination.= "<a href=\"$targetpage?page=2\">2</a>";
                    $pagination.= "...";
                    for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
                    {
                        if ($counter == $page)
                            $pagination.= "<span class=\"current\">$counter</span>";
                        else
                            $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>";
                    }
                    $pagination.= "...";
                    $pagination.= "<a href=\"$targetpage?page=$lpm1\">$lpm1</a>";
                    $pagination.= "<a href=\"$targetpage?page=$lastpage\">$lastpage</a>";
                }             //close to end; only hide early pages
                else
                {
                    $pagination.= "<a href=\"$targetpage?page=1\">1</a>";
                    $pagination.= "<a href=\"$targetpage?page=2\">2</a>";
                    $pagination.= "...";
                    for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
                    {
                        if ($counter == $page)
                            $pagination.= "<span class=\"current\">$counter</span>";
                        else
                            $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>";
            }             }         }
            //next button
            if ($page < $counter - 1)
                $pagination.= "<a href=\"$targetpage?page=$next\">next »</a>";
            else
                $pagination.= "<span class=\"disabled\">next »</span>";
            $pagination.= "</div>\n";
    } ?>

    <?php
        while($row = mysql_fetch_array($result))
        {
            echo '<a href="http://geatzo.com/do123.php?uid='.$row['id'].'"><img src="http://www.geatzo.com/images/coins.jpg" height="100px" width="100px"/>';
            echo '"<p> </p>';
            echo '"You will earn<b>"'.$row['coins'].'"</b>Coins"<p> </p>';
            echo '"Posted By "'.$row['username'].'<p> </p>';
            echo '"Site you will be viewing "'.$row['url'].'<p> </p>';
        }
    ?>

    <?=$pagination?>

</p>
</code>```

I want to put that php in a a html div
here is the html

```<code><div class="ptcbox-link"><a href="http://www.mysite.com/gpt.php?v=entry&type=ptc&id=6960&sid=TWk0Mk1Ea3hORGc1TVRB&sid2=TWk0M&siduid=186998&"></a></div>
                <div class="ptcbox-value-w1">
                    <div class="ptcbox-value">$2</div>
                    <div class="ptcbox-seconds">30 seconds</div>
                </div>
</code>```

I want there to be like http://img841.imageshack.us/img841/6651/unledfte.png the div tags for each different result a new box for each result

Thanks

P.s the html code and php code works both works i just wanna put them together in a while

答:
To have a better seperation of model and view I highly suggest you to do the following things

do all the data catching stuff, insert it into variables

build an extra file which consists only out of HTML and echoing variables and loops. try to use alternative syntax like <?php foreach ( $text as $block): ?> to make it visiually more appealing

include this extra file at the end of your main file.

an very easy example could be:

$data being an array of arrays, where each one has a link, value, and seconds

```<code>$data = array(
    array(
        'link' => "http://www.mysite.com/gpt.php?v=entry&type=ptc&id=6960&sid=TWk0Mk1Ea3hORGc1TVRB&sid2=TWk0M&siduid=186998&",
        'value' => 2,
        'seconds' => 30
    )
);
</code>```

you need to build this array in your first file.
In the view you just need the following code:

```<code><?php foreach ( $data as $ptcbox ): ?>
   <div class="ptcbox-link"><a href="<?php echo $ptcbox['link']; ?>"></a></div>
   <div class="ptcbox-value-w1">
        <div class="ptcbox-value">$<?php echo $ptcbox['value']; ?></div>
        <div class="ptcbox-seconds"><?php echo $ptcbox['seconds']; ?> seconds</div>
   </div>
<?php endforeach; ?>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Doing while with html and php

Body:
Hello i have done whiles with php but never html...
I have a script that works fine but looks ugly so a friend has made me a html layout.

Here is my php script.

    <?php
        /* Place code to connect to your DB here.     */

        $tbl_name="adds";        //your table name
        // How many adjacent pages should be shown on each side?
        $adjacents = 3;
        /*
        First get total number of rows in data table.
        If you have a WHERE clause in your query, make sure you mirror it here.
        */

        $query = "SELECT COUNT(*) as num FROM adds ";
        $total_pages = mysql_fetch_array(mysql_query($query));
        $total_pages = $total_pages['num'];
        /* Setup vars for query. */
        $targetpage = "earn.php";     //your file name  (the name of this file)
        $limit = 6;
        //how many items to show per page
        $page = isset($_GET['page']) ? $_GET['page'] : 0;
        if($page)
            $start = ($page - 1) * $limit;
        //first item to display on this page
        else
            $start = 0;                                //if no page var is given, set start to 0
        /* Get data. */
        $sql = "SELECT * FROM $tbl_name LIMIT $start, $limit ";
        $result = mysql_query($sql);
        /* Setup page vars for display. */
        if ($page == 0) $page = 1;                    //if no page var is given, default to 1.
        $prev = $page - 1;                            //previous page is page - 1
        $next = $page + 1;                            //next page is page + 1
        $lastpage = ceil($total_pages/$limit);        //lastpage is = total pages / items per page, rounded up.
        $lpm1 = $lastpage - 1;                        //last page minus 1
        /*
        Now we apply our rules and draw the pagination object.
        We're actually saving the code to a variable in case
        we want to draw it more than once.
        */

        $pagination = "";
        if($lastpage > 1)
        {
            $pagination .= "
";         //previous button
            if ($page > 1)
                $pagination.= "« previous";
            else
                $pagination.= "« previous";
            //pages
            if ($lastpage < 7 + ($adjacents * 2))    //not enough pages to bother breaking it up
            {
                for ($counter = 1; $counter <= $lastpage; $counter++)             {
                    if ($counter == $page)
                        $pagination.= "$counter";
                    else
                        $pagination.= "$counter";
            }         }         elseif($lastpage > 5 + ($adjacents * 2))    //enough pages to hide some
            {
                //close to beginning; only hide later pages
                if($page < 1 + ($adjacents * 2))                     {
                    for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
                    {
                        if ($counter == $page)
                            $pagination.= "$counter";
                        else
                            $pagination.= "$counter";
                    }
                    $pagination.= "...";
                    $pagination.= "$lpm1";
                    $pagination.= "$lastpage";
                }             //in middle; hide some front and some back
                elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))             {
                    $pagination.= "1";
                    $pagination.= "2";
                    $pagination.= "...";
                    for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
                    {
                        if ($counter == $page)
                            $pagination.= "$counter";
                        else
                            $pagination.= "$counter";
                    }
                    $pagination.= "...";
                    $pagination.= "$lpm1";
                    $pagination.= "$lastpage";
                }             //close to end; only hide early pages
                else
                {
                    $pagination.= "1";
                    $pagination.= "2";
                    $pagination.= "...";
                    for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
                    {
                        if ($counter == $page)
                            $pagination.= "$counter";
                        else
                            $pagination.= "$counter";
            }             }         }
            //next button
            if ($page < $counter - 1)
                $pagination.= "next »";
            else
                $pagination.= "next »";
            $pagination.= "
\n";
    } ?>

    <?php
        while($row = mysql_fetch_array($result))
        {
            echo '';
            echo '"

';
            echo '"You will earn"'.$row['coins'].'"Coins"

';
            echo '"Posted By "'.$row['username'].'

';
            echo '"Site you will be viewing "'.$row['url'].'

';
        }
    ?>

    <?=$pagination?>

I want to put that php in a a html div
here is the html

$2

30 seconds

I want there to be like http://img841.imageshack.us/img841/6651/unledfte.png the div tags for each different result a new box for each result

Thanks

P.s the html code and php code works both works i just wanna put them together in a while

Body:
To have a better seperation of model and view I highly suggest you to do the following things

do all the data catching stuff, insert it into variables

build an extra file which consists only out of HTML and echoing variables and loops. try to use alternative syntax like <?php foreach ( $text as $block): ?> to make it visiually more appealing

include this extra file at the end of your main file.

an very easy example could be:

$data being an array of arrays, where each one has a link, value, and seconds

$data = array(
    array(
        'link' => "http://www.mysite.com/gpt.php?v=entry&amp;type=ptc&amp;id=6960&amp;sid=TWk0Mk1Ea3hORGc1TVRB&amp;sid2=TWk0M&amp;siduid=186998&amp;",
        'value' => 2,
        'seconds' => 30
    )
);

you need to build this array in your first file.
In the view you just need the following code:

<?php foreach ( $data as $ptcbox ): ?>
   <div class="ptcbox-link"><a href="<?php echo $ptcbox['link']; ?>"></a></div>
   <div class="ptcbox-value-w1">
        <div class="ptcbox-value">$<?php echo $ptcbox['value']; ?></div>
        <div class="ptcbox-seconds"><?php echo $ptcbox['seconds']; ?> seconds</div>
   </div>
<?php endforeach; ?>


问:
When and why would I want to use i8 instead of i32?
I think the default size in rust is 32 bits, signed, when assigning a variable to an integer value.

Provided I'm dealing with a value that fits in 16 bits (e.g 15000) or even 8 bits (e.g 120), why would I want to NOT still just use the default?

I'd probably be saving some memory - but is this worth the consideration?
And is there any speed advantage?
What else, if anything?

答:
TL;DR: For Performance.

Quickly

Performance is a complex topic, in general, so which type to choose will vary wildly between usecases.

In general, though, there are two major reasons to choose smaller data-types:

Better cache utilization.

SIMD.

Better cache utilization

Modern CPUs have gotten faster, and RAM did not follow. Long are the days where the frequency of the RAM was equal to that of the CPU.

This is where caches come in: L1, L2, and L3 on a typical desktop CPU. The problem is that physical limits are at play, which themselves limit the size of those caches. A typical L1 cache is 32KB instructions / 32KB data, with 64 bytes cache lines.

32KB data is:

8K i32.

16K i16.

32K i8.

Tighter data-packing can therefore be used to:

Fit more data in L1 (or L2, L3, ...).

Fit the data in less cache lines.

In short, tighter packing enables better cache utilization.

SIMD

One of the latest hash-table design in Abseil's Swiss Table.

Abseil's Swiss Table main trick is creating groups of 16 elements, and having a 16 bytes header for each group which contains a 1-byte (u8) hash residual for each element of the group.

A single SIMD instruction (SSE2 is 16-bytes wide) allows looking up for the hash residual across all 16 elements, and identifying which elements match!

This is a general theme in SIMD, the instructions have very limited operands:

SSE is 16 bytes (128 bits),

AVX is 32 bytes (256 bits),

AVX-512 is 64 bytes (512 bits).

With SIMD instructions, dividing the size of the element by 2 immediately means processing 2x as many elements in a single instruction, thereby speeding algorithms up to 2x.


问:
React Native Image non-looping animated gif lost when application sent to background
As can be seen from this snack, I embedded 2 identical animated gifs back to back.

The first one that loops for ever functions as expected.

But the second, the non-looping animated gif is lost when the application is sent to background and retrieved back to foreground.

Is there anything that can be done to avoid this?

import testAniGif from '../assets/test.gif';
import testAniGif2 from '../assets/test2.gif';

export default function AssetExample() {
  return (
    <View>
      <Image style={styles.logo} source={testAniGif} />
      <Image style={styles.logo} source={testAniGif2} />
    </View>
  );
}
```

答:
I think you just need to implement proper syntax for Image attribute

```<code><Image style={styles.logo} source={require(testAniGif)} />
<Image style={styles.logo} source={require(testAniGif2)} />
</code>```

Have a look Image syntax https://reactnative.dev/docs/image

For better understanding you can follow this answer too : https://stackoverflow.com/a/40717686/3840093

Body:
I think you just need to implement proper syntax for Image attribute

<Image style={styles.logo} source={require(testAniGif)} />
<Image style={styles.logo} source={require(testAniGif2)} />

Have a look Image syntax https://reactnative.dev/docs/image

For better understanding you can follow this answer too : https://stackoverflow.com/a/40717686/3840093


问:
How to test HTML content with React testing library
Currently I am writing a test to test the content that is inside (HTML content), but it seems I cannot test that properly with React testing library. It can find the id value of that, but how do I get the HTML content inside that element.

import React from 'react';

export const TopBar = () => {
    return (

Dashboard Menu

    )
}

import React from "react";
import { render } from "@testing-library/react";
import { TopBar } from "./TopBar";
import { Provider } from "react-redux";
import { store } from "../../Store";
import { screen } from "@testing-library/dom";
import "@testing-library/jest-dom/extend-expect";

test("It should check if content matches", () => {
    render(
        <Provider store={store}>
            <TopBar/>
        </Provider>
    )
    const checkContent = screen.getAllByTestId("title-content");
    expect(checkContent.text()).toBe("Dashboard Menu");
});```

答:
Use getByText</p>

```<code>test("It should check if content matches", () => {
  const { getByText } = render(<Provider store={store}><TopBar /></Provider>)
  expect(getByText(/dashboard menu/i)).toBeTruthy();
});
</code>```

Body:
Use getByText

test("It should check if content matches", () => {
  const { getByText } = render(<Provider store={store}><TopBar /></Provider>)
  expect(getByText(/dashboard menu/i)).toBeTruthy();
});


问:
Convert custom Convolution from PyTorch to Tensorflow (2.2.0)
I am currently attempting to convert a custom convolution from PyTorch to Tensorflow (V. 2.2.0).

The convolution is defined in PyTorch as:

```<code>    self.quantizer = q = nn.Conv1d(1, 2*nq, kernel_size=1, bias=True)
    a = (nq-1) / gap
    #1st half = lines passing to (min+x,1) and (min+x+1/a,0) with x = {nq-1..0}*gap/(nq-1)
    q.weight.data[:nq] = -a
    q.bias.data[:nq] = torch.from_numpy(a*min + np.arange(nq, 0, -1)) # b = 1 + a*(min+x)
    #2nd half = lines passing to (min+x,1) and (min+x-1/a,0) with x = {nq-1..0}*gap/(nq-1)
    q.weight.data[nq:] = a
    q.bias.data[nq:] = torch.from_numpy(np.arange(2-nq, 2, 1) - a*min) # b = 1 - a*(min+x)
    # first and last one are special: just horizontal straight line
    q.weight.data[0] = q.weight.data[-1] = 0
    q.bias.data[0] = q.bias.data[-1] = 1
</code>```

where nq = 20, min = 0 and max = 1.

My reimplementation looks like this:

```<code>my_weight = my_init_weight((1,1,nq*2))
q = tf.nn.convolution(input_q, my_weight)
q = tf.nn.bias_add(q, my_init_bias((40,1), tf.float32))
</code>```

with these these functions as weight and bias initialization:

```<code>def my_init_weight(shape, dtype=None):

    weights = np.zeros(shape, dtype=np.float32)
    weights[:, :, :nq] = -a
    weights[:, :, nq:] = a
    weights[:, :, 0] = weights[:, :, -1] = 0
    return tf.convert_to_tensor(weights, dtype=tf.float32)
def my_init_bias(shape, dtype=None):
    weights = np.zeros(shape[0], dtype=np.float32)
    weights[:nq] = a*min + np.arange(nq, 0, -1)
    weights[nq:] = np.arange(2-nq, 2, 1) - a*min
    weights[0] = weights[-1] = 1
    return weights
</code>```

The input is a matrix with shape 1681, 1, 1600 for PyTorch (as it uses channels first) and 1681, 1600, 1 for Tensorflow (as it uses channels last) and the out put is 1681, 40, 1600 or 1681, 1600, 40. So it should be correct, however, the output of both convolutions is different.

Input, Output: Tensorflow on a random 100, 100 image:

```<code>my_weight = my_init_weight((1,1,nq*2))
my_weight = tf.nn.bias_add(my_weight, my_init_bias((40,1), tf.float32))
q = tf.nn.convolution(test_conv, my_weight)

q_left, q_right = tf.split(q, 2, axis=2)
q = tf.math.minimum(q_left, q_right)
nbs = tf.reduce_sum(q, axis=0)
</code>```

Input, Output: PyTorch on a random 100, 100 image:

```<code>output = q(input_t_t)
output = torch.min(output[:,:nq], output[:,nq:]).clamp(min=0)
nbs = output.sum(dim=-1)
</code>```

答:
Okay, I found the solution:

I forgot to add the .clamp(min=0).

Adding q = tf.clip_by_value(q, 0, tf.keras.backend.max(q)) to

```<code>my_weight = my_init_weight((1,1,nq*2))
my_weight = tf.nn.bias_add(my_weight, my_init_bias((40,1), tf.float32))
q = tf.nn.convolution(test_conv, my_weight)

q_left, q_right = tf.split(q, 2, axis=2)
q = tf.math.minimum(q_left, q_right)
q = tf.clip_by_value(q, 0, tf.keras.backend.max(q)) <-----------
nbs = tf.reduce_sum(q, axis=0)
</code>```

fixed the problem.

Body:
I am currently attempting to convert a custom convolution from PyTorch to Tensorflow (V. 2.2.0).

The convolution is defined in PyTorch as:

    self.quantizer = q = nn.Conv1d(1, 2*nq, kernel_size=1, bias=True)
    a = (nq-1) / gap
    #1st half = lines passing to (min+x,1) and (min+x+1/a,0) with x = {nq-1..0}*gap/(nq-1)
    q.weight.data[:nq] = -a
    q.bias.data[:nq] = torch.from_numpy(a*min + np.arange(nq, 0, -1)) # b = 1 + a*(min+x)
    #2nd half = lines passing to (min+x,1) and (min+x-1/a,0) with x = {nq-1..0}*gap/(nq-1)
    q.weight.data[nq:] = a
    q.bias.data[nq:] = torch.from_numpy(np.arange(2-nq, 2, 1) - a*min) # b = 1 - a*(min+x)
    # first and last one are special: just horizontal straight line
    q.weight.data[0] = q.weight.data[-1] = 0
    q.bias.data[0] = q.bias.data[-1] = 1

where nq = 20, min = 0 and max = 1.

My reimplementation looks like this:

my_weight = my_init_weight((1,1,nq*2))
q = tf.nn.convolution(input_q, my_weight)
q = tf.nn.bias_add(q, my_init_bias((40,1), tf.float32))

with these these functions as weight and bias initialization:

def my_init_weight(shape, dtype=None):

    weights = np.zeros(shape, dtype=np.float32)
    weights[:, :, :nq] = -a
    weights[:, :, nq:] = a
    weights[:, :, 0] = weights[:, :, -1] = 0
    return tf.convert_to_tensor(weights, dtype=tf.float32)
def my_init_bias(shape, dtype=None):
    weights = np.zeros(shape[0], dtype=np.float32)
    weights[:nq] = a*min + np.arange(nq, 0, -1)
    weights[nq:] = np.arange(2-nq, 2, 1) - a*min
    weights[0] = weights[-1] = 1
    return weights

The input is a matrix with shape 1681, 1, 1600 for PyTorch (as it uses channels first) and 1681, 1600, 1 for Tensorflow (as it uses channels last) and the out put is 1681, 40, 1600 or 1681, 1600, 40. So it should be correct, however, the output of both convolutions is different.

Input, Output: Tensorflow on a random 100, 100 image:

my_weight = my_init_weight((1,1,nq*2))
my_weight = tf.nn.bias_add(my_weight, my_init_bias((40,1), tf.float32))
q = tf.nn.convolution(test_conv, my_weight)

q_left, q_right = tf.split(q, 2, axis=2)
q = tf.math.minimum(q_left, q_right)
nbs = tf.reduce_sum(q, axis=0)

Input, Output: PyTorch on a random 100, 100 image:

output = q(input_t_t)
output = torch.min(output[:,:nq], output[:,nq:]).clamp(min=0)
nbs = output.sum(dim=-1)

Body:
Okay, I found the solution:

I forgot to add the .clamp(min=0).

Adding q = tf.clip_by_value(q, 0, tf.keras.backend.max(q)) to

my_weight = my_init_weight((1,1,nq*2))
my_weight = tf.nn.bias_add(my_weight, my_init_bias((40,1), tf.float32))
q = tf.nn.convolution(test_conv, my_weight)

q_left, q_right = tf.split(q, 2, axis=2)
q = tf.math.minimum(q_left, q_right)
q = tf.clip_by_value(q, 0, tf.keras.backend.max(q)) <-----------
nbs = tf.reduce_sum(q, axis=0)

fixed the problem.


问:
PHP: Extract string from another
i have some strings (address), all like this:

2 rue lambda, 75018, PARIS

I want to get the postal code, in this exemple "75018". I've been trying different solution, but i'm not familiar with escaped characters , and don't know how to detect coma in the string. Which function should i use to extract the postal code?

答:
If the commas are always there, it is as simple as explode()

```<code>$parts = explode(",", "2 rue lambda, 75018, PARIS");
$postcode = trim($parts[1]);
</code>```

Title: PHP: Extract string from another

Body:
If the commas are always there, it is as simple as explode()

$parts = explode(",", "2 rue lambda, 75018, PARIS");
$postcode = trim($parts[1]);


问:
Show Cron expression as text in Hangfire Dashboard in mvc core
Q1- I used Hangfire Dashboard in ASP.NET MVC Core 2.2, but I need to show a cron expression in "Recurring Job" as Text.

Example:  when cron value is * * * * *  show text in table is  "Every minute"

```<code>       when cron value is 0 8 * * *   show text in table is "At 08:00"
</code>```

And so on ...... as show in attachment image

Q2- Can I edit on Hangfire Dashboard code or do I have access to Hangfire Dashboard code and edit it as HTML?

答: You can use the attribute [DisplayName("...")] on the method you hand over to HangFire as your job. The text given to DisplayName is then shown on the HangFire dashboard</p>

Body:
Q1- I used Hangfire Dashboard in ASP.NET MVC Core 2.2, but I need to show a cron expression in "Recurring Job" as Text.

Example:  when cron value is * * * * *  show text in table is  "Every minute"

       when cron value is 0 8 * * *   show text in table is "At 08:00"

And so on ...... as show in attachment image

Q2- Can I edit on Hangfire Dashboard code or do I have access to Hangfire Dashboard code and edit it as HTML?


问:
html send array inside form onsubmit
I'm wondering if it's possible to send array of values for javascript function via onsubmit inside the form.
Let's say I have five inputs in form, and in the form I have:

```<code>onsubmit="return checkvalues(value1, value2, value3, value4, value5)"
</code>```

So the checkvalues() function can validate the inputed values.
But I'm wondering how not to send 5 values but one array, so something like:

```<code>onsubmit="return checkvalues(array(value1, value2, value3, value4, value5))"
</code>```

is it possible so the Javascript function will recognize "someArray" as array?:

```<code>function checkvalues(array someArray) {
    somehow_loop_through_array someArray
}
</code>```

答:
Submit the values in an array and define the function such that it accepts one parameter. You don't have to specify that this parameter should be an array in the function definition in JavaScript, just deal with the parameter as an array inside the function.</p>

```<code>onsubmit="return checkvalues([value1, value2, value3, value4, value5])"

function checkvalues(someArray) {
  for(var i = 0; i < someArray.length; i++) {
    // do something with the array elements
  }
}
</code>```

Title: html send array inside form onsubmit

Body:
I'm wondering if it's possible to send array of values for javascript function via onsubmit inside the form.
Let's say I have five inputs in form, and in the form I have:

onsubmit="return checkvalues(value1, value2, value3, value4, value5)"

So the checkvalues() function can validate the inputed values.
But I'm wondering how not to send 5 values but one array, so something like:

onsubmit="return checkvalues(array(value1, value2, value3, value4, value5))"

is it possible so the Javascript function will recognize "someArray" as array?:

function checkvalues(array someArray) {
    somehow_loop_through_array someArray
}

Body:
Submit the values in an array and define the function such that it accepts one parameter. You don't have to specify that this parameter should be an array in the function definition in JavaScript, just deal with the parameter as an array inside the function.

onsubmit="return checkvalues([value1, value2, value3, value4, value5])"

function checkvalues(someArray) {
  for(var i = 0; i < someArray.length; i++) {
    // do something with the array elements
  }
}


问:
What is function designator and actual call?
According to C99 Standard:

The order of evaluation of the function designator, the actual arguments, and subexpressions within the actual arguments is unspecified, but there is a sequence point before the actual call.

Could anyone explain clearly what is function designator and actual call; and what is difference between them ?

答:
A function designator is an expression with function type. That is, when you type func(a,b); to call a function, func is the function designator.

(Such a function designator when present in an expression normally "decays" into a pointer to function, much like arrays decay into a pointer to the first element.)

The meaning of "sequence point before the actual call" is that all operands must be fully evaluated (executed) before the function is called.
If you have func(a(), b()), it is unspecified if a() or b() is executed first, but you know that both of them are definitely executed before func is called.

So if a() for example modified a global variable that is also used by func, that would be fine because the access to that variable would be sequenced in a well-defined order.

EDIT - sources

There's C17 6.5.2.2 requiring a function pointer whenever a function is called:

Constraints

The expression that denotes the called function shall have type pointer to function returning void or returning a complete object type other than an array type.

This is made possible by mandatory "function decay", C17 6.3.2.1/4:

A function designator is an expression that has function type. Except when it is the operand of the sizeof operator, or the unary & operator, a function designator with type "function returning type" is converted to an expression that has type "pointer to function returning type".


问:
Doctrine entity repository with additional aggregated fields
I have an entity Client, with a relation to an entity Contract. Contract has got a field amount and a field payingDelay.

Client.php

```<code>/**
 * @ORM\OneToMany(targetEntity="Contract", mappedBy="client")
 * @ORM\JoinColumn(name="contract_id", referencedColumnName="id")
 */
private $contract;
</code>```

I'd like to show a list of all clients with some basic client fields and also some calculated (SUM, etc.) information on contracts, like this:

```<code>name - num contracts    - sum(amounts)  - aggregated risk
John - COUNT(contracts) - SUM(C.amount) - SUM(C.amount * C.payingDelay)

This is my basic `findClientWithCalculations()` method in `ClientRepository`:

        return $this->createQueryBuilder('CLI')
            ->join('CLI.contract', 'CON')
            ->orderBy('CON.startDate', 'DESC')
            ->getQuery()
            ->getResult();

Is there a way I can add extra columns to this QueryBuilder, even if the final structure doesn't match the structure of a Client object or this must be done outside from a repository?

If not, maybe I can build a custom query in a controller and pass the query result to a twig template to show this structure.

Thank you.

</code>```

答:
Although not trivial, the question is not correctly formulated. I thought that an entitity repository method had to implement always some kind of findBy() method and return an object or a collection of objects of that entity to which this repository belongs.

Actually, an entitity repository method can return anything, so this problem can be solved using native query inside the entitity repository method.

For example:

ClientRepository.php:

```<code>public function findWithContractStatus($contractStatusShortname)
{
    $em = $this->getEntityManager();

    $clientQuery = "select distinct CLI.id, CLI.name, COUNT(contracts) as ncontracts, SUM(C.amount) as amount from client CLI join contract CON on CON.client_id = CON.id group by CLI.id, CLI.name"

    $rsm = new ResultSetMapping();
    $rsm->addScalarResult('id', 'id');
    $rsm->addScalarResult('name', 'name');
    $rsm->addScalarResult('ncontracts', 'ncontracts');
    $rsm->addScalarResult('amount', 'amount');

    $query = $em->createNativeQuery($clientQuery, $rsm);
    return $query->getResult();
}
</code>```

This will return an array with the given structure - id, name, ncontracts, amount  - which can be iterated in controller, twig template or whereever.

Body:
I have an entity Client, with a relation to an entity Contract. Contract has got a field amount and a field payingDelay.

Client.php

/**
 * @ORM\OneToMany(targetEntity="Contract", mappedBy="client")
 * @ORM\JoinColumn(name="contract_id", referencedColumnName="id")
 */
private $contract;

I'd like to show a list of all clients with some basic client fields and also some calculated (SUM, etc.) information on contracts, like this:

name - num contracts    - sum(amounts)  - aggregated risk
John - COUNT(contracts) - SUM(C.amount) - SUM(C.amount * C.payingDelay)

This is my basic `findClientWithCalculations()` method in `ClientRepository`:

        return $this->createQueryBuilder('CLI')
            ->join('CLI.contract', 'CON')
            ->orderBy('CON.startDate', 'DESC')
            ->getQuery()
            ->getResult();

Is there a way I can add extra columns to this QueryBuilder, even if the final structure doesn't match the structure of a Client object or this must be done outside from a repository?

If not, maybe I can build a custom query in a controller and pass the query result to a twig template to show this structure.

Thank you.

Body:
Although not trivial, the question is not correctly formulated. I thought that an entitity repository method had to implement always some kind of findBy() method and return an object or a collection of objects of that entity to which this repository belongs.

Actually, an entitity repository method can return anything, so this problem can be solved using native query inside the entitity repository method.

For example:

ClientRepository.php:

public function findWithContractStatus($contractStatusShortname)
{
    $em = $this->getEntityManager();

    $clientQuery = "select distinct CLI.id, CLI.name, COUNT(contracts) as ncontracts, SUM(C.amount) as amount from client CLI join contract CON on CON.client_id = CON.id group by CLI.id, CLI.name"

    $rsm = new ResultSetMapping();
    $rsm->addScalarResult('id', 'id');
    $rsm->addScalarResult('name', 'name');
    $rsm->addScalarResult('ncontracts', 'ncontracts');
    $rsm->addScalarResult('amount', 'amount');

    $query = $em->createNativeQuery($clientQuery, $rsm);
    return $query->getResult();
}

This will return an array with the given structure - id, name, ncontracts, amount  - which can be iterated in controller, twig template or whereever.


问:
How to open popup for a specific marker inside a leaflet MarkerClusterGroup?
I want to open a popup for a marker that is under a markercluster when the map is zoomed out. This function is called when a user clicks on a search result.

This is the code that I am using:

```<code>map.eachLayer(function (layer) {
    if (layer.options && layer.options.pane === "markerPane") {
        if (layer.options.title == locationId) {
            layer.openPopup()
        }
    }
});
</code>```

I tried adding this code but it didn't work as well:

```<code>layer.zoomToBounds({padding: [20, 20]});
</code>```

答:
So you want to so something about a cluster's marker whenever a specific marker in such cluster fulfills a condition.

You can iterate through all visible cluster markers, then leverage getAllChildMarkers; but that will get messy soon, as you will have to deal with the fact that a cluster and the cluster's marker are different entities, so iterating through visible markers doesn't necessarily mean iterating through the visible clusters.

I suggest an approach based on getVisibleParent. Store a reference to each original marker, indexed by the ID you'll be using later for lookup, e.g. ...

```<code>var clusterGroup = L.markerClusterGroup();
var markers = {};   // Yay using Object as a hashmap!
for (var i in dataset) {
    // Create individual marker based on a item in the dataset, e.g.
    var marker = L.marker(dataset[i].latlng);

    // Add that to the clusterGroup (but not to the map)
    clusterGroup.addMarker(marker);

    // Save the individual marker in the hashmap, indexed by the
    // desired property, e.g. "locationId"
    markers[ dataset[i].locationId ] = marker;
}

// Adding the cluster to the map after all items have been inserted should
// be slightly more performant than doing that before.
clusterGroup.addTo(map);
</code>```

So with that, one should be able to look up the marker by the desired ID, see if it's in a cluster or directly visible, and do something about it:

```<code>function highlightLocationId(id) {
  // hashmap lookup
  var marker = markers[i];

  // Sanity check
  if (!marker) { return; }

  // What cluster is this marker in?
  var cluster = clusterGroup.getVisibleParent(marker);

  // Is the marker really in a cluster, or visible standalone?
  if (cluster) {
    // It's in a cluster, do something about its cluster.
    cluster.openPopup();
  } else {
    // It's not in a cluster but directly in the map, do something about it.
    marker.openPopup();
  }
}
</code>```

Body:
I want to open a popup for a marker that is under a markercluster when the map is zoomed out. This function is called when a user clicks on a search result.

This is the code that I am using:

map.eachLayer(function (layer) {
    if (layer.options && layer.options.pane === "markerPane") {
        if (layer.options.title == locationId) {
            layer.openPopup()
        }
    }
});

I tried adding this code but it didn't work as well:

layer.zoomToBounds({padding: [20, 20]});

Body:
So you want to so something about a cluster's marker whenever a specific marker in such cluster fulfills a condition.

You can iterate through all visible cluster markers, then leverage getAllChildMarkers; but that will get messy soon, as you will have to deal with the fact that a cluster and the cluster's marker are different entities, so iterating through visible markers doesn't necessarily mean iterating through the visible clusters.

I suggest an approach based on getVisibleParent. Store a reference to each original marker, indexed by the ID you'll be using later for lookup, e.g. ...

var clusterGroup = L.markerClusterGroup();
var markers = {};   // Yay using Object as a hashmap!
for (var i in dataset) {
    // Create individual marker based on a item in the dataset, e.g.
    var marker = L.marker(dataset[i].latlng);

    // Add that to the clusterGroup (but not to the map)
    clusterGroup.addMarker(marker);

    // Save the individual marker in the hashmap, indexed by the
    // desired property, e.g. "locationId"
    markers[ dataset[i].locationId ] = marker;
}

// Adding the cluster to the map after all items have been inserted should
// be slightly more performant than doing that before.
clusterGroup.addTo(map);

So with that, one should be able to look up the marker by the desired ID, see if it's in a cluster or directly visible, and do something about it:

function highlightLocationId(id) {
  // hashmap lookup
  var marker = markers[i];

  // Sanity check
  if (!marker) { return; }

  // What cluster is this marker in?
  var cluster = clusterGroup.getVisibleParent(marker);

  // Is the marker really in a cluster, or visible standalone?
  if (cluster) {
    // It's in a cluster, do something about its cluster.
    cluster.openPopup();
  } else {
    // It's not in a cluster but directly in the map, do something about it.
    marker.openPopup();
  }
}


Title: How do I calculate perimeter of xy points in R?

Body:
I am looking to calculate the perimeter of xy points (including all the points in sequential order), where the first and last point aren't always equal. I can't figure out why the code below for calculating perimeter isn't working.

Ideally, I would like a method which flags when the first and last xy points are different.

Thanks

  m
       x       y
 [1,]  606.3   95.4
 [2,]  612.4  178.7
 [3,]  610.2  222.6
 [4,]  610.2  222.8
 [5,]  625.8  249.8
 [6,]  625.8  250.1
 [7,]  633.9  268.9
 [8,]  668.7  272.2
 [9,]  693.7  222.6
[10,]  723.2  157.0
[11,]  738.6  109.9
[12,]  681.2   90.5
[13,]  606.3   95.4
[14,]  833.3  154.6
[15,]  753.7  267.5
[16,]  747.8  305.1
[17,]  773.8  354.7
[18,]  767.0  393.8
[19,]  763.0  442.0
[20,]  817.4  446.9
[21,]  817.6  446.9
[22,]  840.2  412.3
[23,]  892.1  317.7
[24,]  875.3  218.8
[25,]  833.3  154.6

library(geosphere)
perimeter(m)

**Error in perimeter(m) : could not find function "perimeter"**

Body:
This will do the trick..

sample data

library( data.table )
m <- fread("x       y
  606.3   95.4
  612.4  178.7
  610.2  222.6
  610.2  222.8
  625.8  249.8
  625.8  250.1
  633.9  268.9
  668.7  272.2
  693.7  222.6
  723.2  157.0
  738.6  109.9
  681.2   90.5
  606.3   95.4
  833.3  154.6
  753.7  267.5
  747.8  305.1
  773.8  354.7
  767.0  393.8
  763.0  442.0
  817.4  446.9
  817.6  446.9
  840.2  412.3
  892.1  317.7
  875.3  218.8
  833.3  154.6")

code

library( grDevices )

hull <- chull( m ) #create coordinates of convex hull
coords <- m[ c( hull, hull[1]), ]  # create a closed perimeter-polygon

#plot it
plot(m)        #plot points
lines(coords, col="red") #plot perimeter


问:
Is there something wrong with this SQL query
I am new to SQL queries and trying to understand it a little better.
Is this SQL query valid regarding the picture below
The question I was given was:

"For each book authored (or co-authored) by "Stephen King", retrieve the title and the number of copies owned by the librarybranch whose name is "Central"

```<code>SELECT Title
FROM BOOK
WHERE BookID =
(
 SELECT BookID
 FROM BOOK_AUTHORS
 WHERE AuthorName = 'Stephen King'
)
AND
BookID =
(
 SELECT BookID, No_Of_Copies
 FROM BOOK_COPIES
 WHERE BranchID =
 (
  SELECT BranchID
  FROM LIBRARY_BRANCH
  WHERE BranchName = 'Central'
 )
)
</code>```

答:
Your version obviously does not answer the question because it does not return a count.

The most common way to approach a problem like this uses JOINs and GROUP BY:

```<code>SELECT b.Title, COUNT(lb.branch_id)
FROM BOOK_AUTHORS ba JOIN
     BOOK b
     ON ba.BookID = b.BookId LEFT JOIN
     BANK_COPIES bc
     ON ba.book_id = b.book_id LEFT JOIN
     LIBRARY_BRANCH lb
     ON lb.branch_id = bc.branch_id AND
        lb.BranchName = 'Central'
WHERE ba.AuthorName = 'Stephen King'
GROUP BY ba.BookID, ba.Title;
</code>```

Note the use of LEFT JOIN.  The question appears to want all titles, even those with no copies.

Body:
I am new to SQL queries and trying to understand it a little better.
Is this SQL query valid regarding the picture below
The question I was given was:

"For each book authored (or co-authored) by "Stephen King", retrieve the title and the number of copies owned by the librarybranch whose name is "Central"

SELECT Title
FROM BOOK
WHERE BookID =
(
 SELECT BookID
 FROM BOOK_AUTHORS
 WHERE AuthorName = 'Stephen King'
)
AND
BookID =
(
 SELECT BookID, No_Of_Copies
 FROM BOOK_COPIES
 WHERE BranchID =
 (
  SELECT BranchID
  FROM LIBRARY_BRANCH
  WHERE BranchName = 'Central'
 )
)

Body:
Your version obviously does not answer the question because it does not return a count.

The most common way to approach a problem like this uses JOINs and GROUP BY:

SELECT b.Title, COUNT(lb.branch_id)
FROM BOOK_AUTHORS ba JOIN
     BOOK b
     ON ba.BookID = b.BookId LEFT JOIN
     BANK_COPIES bc
     ON ba.book_id = b.book_id LEFT JOIN
     LIBRARY_BRANCH lb
     ON lb.branch_id = bc.branch_id AND
        lb.BranchName = 'Central'
WHERE ba.AuthorName = 'Stephen King'
GROUP BY ba.BookID, ba.Title;

Note the use of LEFT JOIN.  The question appears to want all titles, even those with no copies.