问:
run.do_compile error on poky-dunfell release
When I am bitbaking my custom image recipe for STM32MP1 based Avenger96 board I am facing some errors related to analyze.l:466:19: error: format not a string literal and no format arguments [-Werror=format-security]. I don't understand why I am getting this error as this is the first I am facing it. Please find the below complete log:

```<code>DEBUG: Executing python function autotools_aclocals
DEBUG: SITE files ['endian-little', 'bit-32', 'arm-common', 'arm-32', 'common-linux', 'common-glibc', 'arm-linux', 'arm-linux-gnueabi', 'common']
DEBUG: Python function autotools_aclocals finished
DEBUG: Executing shell function do_compile
NOTE: make -j 8
make  all-recursive
make[1]: Entering directory '/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0/build'
Making all in src
make[2]: Entering directory '/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0/build/src'
Making all in libcommon
make[3]: Entering directory '/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0/build/src/libcommon'
make[3]: Nothing to be done for 'all'.
make[3]: Leaving directory '/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0/build/src/libcommon'
Making all in libkbdfile
make[3]: Entering directory '/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0/build/src/libkbdfile'
make[3]: Nothing to be done for 'all'.
make[3]: Leaving directory '/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0/build/src/libkbdfile'
Making all in libkeymap
make[3]: Entering directory '/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0/build/src/libkeymap'
make  all-am
make[4]: Entering directory '/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0/build/src/libkeymap'
../../arm-poky-linux-gnueabi-libtool  --tag=CC   --mode=compile arm-poky-linux-gnueabi-gcc  -mthumb -mfpu=neon-vfpv4 -mfloat-abi=hard -mcpu=cortex-a7 -fstack-protector-strong  -D_FORTIFY_SOURCE=2 -Wformat -Wformat-security -Werror=format-security --sysroot=/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0/recipe-sysroot -DHAVE_CONFIG_H -I. -I../../../kbd-2.2.0/src/libkeymap -I../..   -I../../../kbd-2.2.0/src/libkeymap -I. -I../../../kbd-2.2.0/src/libkeymap/.. -I./.. -I../../../kbd-2.2.0/src/libkeymap/../libcommon -I./../libcommon -I../../../kbd-2.2.0/src/libkeymap/../libkbdfile -I./../libkbdfile -DDATADIR=\"/usr/share\" -DLOCALEDIR=\"/usr/share/locale\" -U_GNU_SOURCE -funit-at-a-time   -g -O2 -D_FORTIFY_SOURCE=2  -O2 -pipe -g -feliminate-unused-debug-types -fmacro-prefix-map=/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0=/usr/src/debug/kbd/2.2.0-r0                      -fdebug-prefix-map=/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0=/usr/src/debug/kbd/2.2.0-r0                      -fdebug-prefix-map=/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0/recipe-sysroot=                      -fdebug-prefix-map=/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0/recipe-sysroot-native=  -Waggregate-return -Wall -Wcast-align -Wconversion -Wdisabled-optimization -Wextra -Wmissing-declarations -Wmissing-format-attribute -Wmissing-noreturn -Wmissing-prototypes -Wpointer-arith -Wredundant-decls -Wshadow -Wstrict-prototypes -Wwrite-strings -c -o analyze.lo ../../../kbd-2.2.0/src/libkeymap/analyze.c
arm-poky-linux-gnueabi-libtool: compile:  arm-poky-linux-gnueabi-gcc -mthumb -mfpu=neon-vfpv4 -mfloat-abi=hard -mcpu=cortex-a7 -fstack-protector-strong -D_FORTIFY_SOURCE=2 -Wformat -Wformat-security -Werror=format-security --sysroot=/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0/recipe-sysroot -DHAVE_CONFIG_H -I. -I../../../kbd-2.2.0/src/libkeymap -I../.. -I../../../kbd-2.2.0/src/libkeymap -I. -I../../../kbd-2.2.0/src/libkeymap/.. -I./.. -I../../../kbd-2.2.0/src/libkeymap/../libcommon -I./../libcommon -I../../../kbd-2.2.0/src/libkeymap/../libkbdfile -I./../libkbdfile -DDATADIR=\"/usr/share\" -DLOCALEDIR=\"/usr/share/locale\" -U_GNU_SOURCE -funit-at-a-time -g -O2 -D_FORTIFY_SOURCE=2 -O2 -pipe -g -feliminate-unused-debug-types -fmacro-prefix-map=/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0=/usr/src/debug/kbd/2.2.0-r0 -fdebug-prefix-map=/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0=/usr/src/debug/kbd/2.2.0-r0 -fdebug-prefix-map=/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0/recipe-sysroot= -fdebug-prefix-map=/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0/recipe-sysroot-native= -Waggregate-return -Wall -Wcast-align -Wconversion -Wdisabled-optimization -Wextra -Wmissing-declarations -Wmissing-format-attribute -Wmissing-noreturn -Wmissing-prototypes -Wpointer-arith -Wredundant-decls -Wshadow -Wstrict-prototypes -Wwrite-strings -c ../../../kbd-2.2.0/src/libkeymap/analyze.c  -fPIC -DPIC -o .libs/analyze.o
analyze.l: In function 'find_incl_file_near_fn':
analyze.l:141:24: warning: passing argument 2 of 'kbdfile_find' from incompatible pointer type [-Wincompatible-pointer-types]
In file included from ../../../kbd-2.2.0/src/libkeymap/keymap/kmap.h:36,
                 from ../../../kbd-2.2.0/src/libkeymap/keymap.h:8,
                 from ../../../kbd-2.2.0/src/libkeymap/analyze.c:1:
../../../kbd-2.2.0/src/libkeymap/../libkbdfile/kbdfile.h:40:37: note: expected 'char **' but argument is of type 'const char **'
   40 | int kbdfile_find(char *fnam, char **dirpath, char **suffixes, struct kbdfile *fp);
      |                              ~~~~~~~^~~~~~~
analyze.l:141:42: warning: passing argument 3 of 'kbdfile_find' from incompatible pointer type [-Wincompatible-pointer-types]
In file included from ../../../kbd-2.2.0/src/libkeymap/keymap/kmap.h:36,
                 from ../../../kbd-2.2.0/src/libkeymap/keymap.h:8,
                 from ../../../kbd-2.2.0/src/libkeymap/analyze.c:1:
../../../kbd-2.2.0/src/libkeymap/../libkbdfile/kbdfile.h:40:53: note: expected 'char **' but argument is of type 'const char * const*'
   40 | int kbdfile_find(char *fnam, char **dirpath, char **suffixes, struct kbdfile *fp);
      |                                              ~~~~~~~^~~~~~~~
analyze.l: In function 'find_standard_incl_file':
analyze.l:168:22: warning: passing argument 2 of 'kbdfile_find' from incompatible pointer type [-Wincompatible-pointer-types]
In file included from ../../../kbd-2.2.0/src/libkeymap/keymap/kmap.h:36,
                 from ../../../kbd-2.2.0/src/libkeymap/keymap.h:8,
                 from ../../../kbd-2.2.0/src/libkeymap/analyze.c:1:
../../../kbd-2.2.0/src/libkeymap/../libkbdfile/kbdfile.h:40:37: note: expected 'char **' but argument is of type 'const char * const*'
   40 | int kbdfile_find(char *fnam, char **dirpath, char **suffixes, struct kbdfile *fp);
      |                              ~~~~~~~^~~~~~~
analyze.l:168:40: warning: passing argument 3 of 'kbdfile_find' from incompatible pointer type [-Wincompatible-pointer-types]
In file included from ../../../kbd-2.2.0/src/libkeymap/keymap/kmap.h:36,
                 from ../../../kbd-2.2.0/src/libkeymap/keymap.h:8,
                 from ../../../kbd-2.2.0/src/libkeymap/analyze.c:1:
../../../kbd-2.2.0/src/libkeymap/../libkbdfile/kbdfile.h:40:53: note: expected 'char **' but argument is of type 'const char * const*'
   40 | int kbdfile_find(char *fnam, char **dirpath, char **suffixes, struct kbdfile *fp);
      |                                              ~~~~~~~^~~~~~~~
analyze.l:197:24: warning: passing argument 2 of 'kbdfile_find' from incompatible pointer type [-Wincompatible-pointer-types]
In file included from ../../../kbd-2.2.0/src/libkeymap/keymap/kmap.h:36,
                 from ../../../kbd-2.2.0/src/libkeymap/keymap.h:8,
                 from ../../../kbd-2.2.0/src/libkeymap/analyze.c:1:
../../../kbd-2.2.0/src/libkeymap/../libkbdfile/kbdfile.h:40:37: note: expected 'char **' but argument is of type 'const char * const*'
   40 | int kbdfile_find(char *fnam, char **dirpath, char **suffixes, struct kbdfile *fp);
      |                              ~~~~~~~^~~~~~~
analyze.l:197:42: warning: passing argument 3 of 'kbdfile_find' from incompatible pointer type [-Wincompatible-pointer-types]
In file included from ../../../kbd-2.2.0/src/libkeymap/keymap/kmap.h:36,
                 from ../../../kbd-2.2.0/src/libkeymap/keymap.h:8,
                 from ../../../kbd-2.2.0/src/libkeymap/analyze.c:1:
../../../kbd-2.2.0/src/libkeymap/../libkbdfile/kbdfile.h:40:53: note: expected 'char **' but argument is of type 'const char * const*'
   40 | int kbdfile_find(char *fnam, char **dirpath, char **suffixes, struct kbdfile *fp);
      |                                              ~~~~~~~^~~~~~~~
analyze.l: In function 'find_incl_file':
analyze.l:210:27: warning: passing argument 2 of 'kbdfile_find' from incompatible pointer type [-Wincompatible-pointer-types]
In file included from ../../../kbd-2.2.0/src/libkeymap/keymap/kmap.h:36,
                 from ../../../kbd-2.2.0/src/libkeymap/keymap.h:8,
                 from ../../../kbd-2.2.0/src/libkeymap/analyze.c:1:
../../../kbd-2.2.0/src/libkeymap/../libkbdfile/kbdfile.h:40:37: note: expected 'char **' but argument is of type 'const char * const*'
   40 | int kbdfile_find(char *fnam, char **dirpath, char **suffixes, struct kbdfile *fp);
      |                              ~~~~~~~^~~~~~~
analyze.l:210:45: warning: passing argument 3 of 'kbdfile_find' from incompatible pointer type [-Wincompatible-pointer-types]
In file included from ../../../kbd-2.2.0/src/libkeymap/keymap/kmap.h:36,
                 from ../../../kbd-2.2.0/src/libkeymap/keymap.h:8,
                 from ../../../kbd-2.2.0/src/libkeymap/analyze.c:1:
../../../kbd-2.2.0/src/libkeymap/../libkbdfile/kbdfile.h:40:53: note: expected 'char **' but argument is of type 'const char * const*'
   40 | int kbdfile_find(char *fnam, char **dirpath, char **suffixes, struct kbdfile *fp);
      |                                              ~~~~~~~^~~~~~~~
analyze.l:225:26: warning: passing argument 2 of 'kbdfile_find' from incompatible pointer type [-Wincompatible-pointer-types]
In file included from ../../../kbd-2.2.0/src/libkeymap/keymap/kmap.h:36,
                 from ../../../kbd-2.2.0/src/libkeymap/keymap.h:8,
                 from ../../../kbd-2.2.0/src/libkeymap/analyze.c:1:
../../../kbd-2.2.0/src/libkeymap/../libkbdfile/kbdfile.h:40:37: note: expected 'char **' but argument is of type 'const char **'
   40 | int kbdfile_find(char *fnam, char **dirpath, char **suffixes, struct kbdfile *fp);
      |                              ~~~~~~~^~~~~~~
analyze.l:225:36: warning: passing argument 3 of 'kbdfile_find' from incompatible pointer type [-Wincompatible-pointer-types]
In file included from ../../../kbd-2.2.0/src/libkeymap/keymap/kmap.h:36,
                 from ../../../kbd-2.2.0/src/libkeymap/keymap.h:8,
                 from ../../../kbd-2.2.0/src/libkeymap/analyze.c:1:
../../../kbd-2.2.0/src/libkeymap/../libkbdfile/kbdfile.h:40:53: note: expected 'char **' but argument is of type 'const char * const*'
   40 | int kbdfile_find(char *fnam, char **dirpath, char **suffixes, struct kbdfile *fp);
      |                                              ~~~~~~~^~~~~~~~
In file included from analyze.l:10:
analyze.l: In function 'yylex':
analyze.l:466:19: error: format not a string literal and no format arguments [-Werror=format-security]
../../../kbd-2.2.0/src/libkeymap/contextP.h:79:55: note: in definition of macro 'lk_log_cond'
   79 |    lk_log(ctx, level, __FILE__, __LINE__, __func__, ##arg); \
      |                                                       ^~~
analyze.l:466:6: note: in expansion of macro 'ERR'
cc1: some warnings being treated as errors
make[4]: *** [Makefile:604: analyze.lo] Error 1
make[4]: Leaving directory '/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0/build/src/libkeymap'
make[3]: *** [Makefile:476: all] Error 2
make[3]: Leaving directory '/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0/build/src/libkeymap'
make[2]: *** [Makefile:1083: all-recursive] Error 1
make[2]: Leaving directory '/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0/build/src'
make[1]: *** [Makefile:471: all-recursive] Error 1
make[1]: Leaving directory '/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0/build'
ERROR: oe_runmake failed
make: *** [Makefile:402: all] Error 2
WARNING: exit code 1 from a shell command.
ERROR: Execution of '/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0/temp/run.do_compile.380' failed with exit code 1
</code>```

When I checked the sources/poky/meta/recipes-core/kbd, add missing string format patch patch is already available and included in kbd_2.2.0.bb recipe. And same patch is also present in build/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0. But still I am getting above error.

I have no idea what this error means and why am I getting this all of a sudden.

Can anyone please let me know how to fix this issue?

Your help will be much appreciated.

Thanks in advance.

答:
You should NOT do the following, its likely your code compiles just fine on an older version of GCC, but GCC adds new warnings and errors for security purposes, you should really look at the code and fix it properly, it is also very likely you just need to use a newer version of kbd that builds contains these fixes (kbd is at 2.4.0 in the latest branch: https://git.yoctoproject.org/poky/tree/meta/recipes-core/kbd/kbd_2.4.0.bb).

But if you want to temporarily disable the GCC error to check if your build works while you either fix the kbd code or upgrade to a new version of kbd, you could set:

```<code>CFLAGS += "-Wno-error=format-security"
</code>```

Which will suppress the compilation error, I cannot stress this enough, the fix is to actually fix the kbd code.

Body:
When I am bitbaking my custom image recipe for STM32MP1 based Avenger96 board I am facing some errors related to analyze.l:466:19: error: format not a string literal and no format arguments [-Werror=format-security]. I don't understand why I am getting this error as this is the first I am facing it. Please find the below complete log:

DEBUG: Executing python function autotools_aclocals
DEBUG: SITE files ['endian-little', 'bit-32', 'arm-common', 'arm-32', 'common-linux', 'common-glibc', 'arm-linux', 'arm-linux-gnueabi', 'common']
DEBUG: Python function autotools_aclocals finished
DEBUG: Executing shell function do_compile
NOTE: make -j 8
make  all-recursive
make[1]: Entering directory '/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0/build'
Making all in src
make[2]: Entering directory '/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0/build/src'
Making all in libcommon
make[3]: Entering directory '/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0/build/src/libcommon'
make[3]: Nothing to be done for 'all'.
make[3]: Leaving directory '/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0/build/src/libcommon'
Making all in libkbdfile
make[3]: Entering directory '/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0/build/src/libkbdfile'
make[3]: Nothing to be done for 'all'.
make[3]: Leaving directory '/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0/build/src/libkbdfile'
Making all in libkeymap
make[3]: Entering directory '/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0/build/src/libkeymap'
make  all-am
make[4]: Entering directory '/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0/build/src/libkeymap'
../../arm-poky-linux-gnueabi-libtool  --tag=CC   --mode=compile arm-poky-linux-gnueabi-gcc  -mthumb -mfpu=neon-vfpv4 -mfloat-abi=hard -mcpu=cortex-a7 -fstack-protector-strong  -D_FORTIFY_SOURCE=2 -Wformat -Wformat-security -Werror=format-security --sysroot=/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0/recipe-sysroot -DHAVE_CONFIG_H -I. -I../../../kbd-2.2.0/src/libkeymap -I../..   -I../../../kbd-2.2.0/src/libkeymap -I. -I../../../kbd-2.2.0/src/libkeymap/.. -I./.. -I../../../kbd-2.2.0/src/libkeymap/../libcommon -I./../libcommon -I../../../kbd-2.2.0/src/libkeymap/../libkbdfile -I./../libkbdfile -DDATADIR=\"/usr/share\" -DLOCALEDIR=\"/usr/share/locale\" -U_GNU_SOURCE -funit-at-a-time   -g -O2 -D_FORTIFY_SOURCE=2  -O2 -pipe -g -feliminate-unused-debug-types -fmacro-prefix-map=/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0=/usr/src/debug/kbd/2.2.0-r0                      -fdebug-prefix-map=/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0=/usr/src/debug/kbd/2.2.0-r0                      -fdebug-prefix-map=/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0/recipe-sysroot=                      -fdebug-prefix-map=/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0/recipe-sysroot-native=  -Waggregate-return -Wall -Wcast-align -Wconversion -Wdisabled-optimization -Wextra -Wmissing-declarations -Wmissing-format-attribute -Wmissing-noreturn -Wmissing-prototypes -Wpointer-arith -Wredundant-decls -Wshadow -Wstrict-prototypes -Wwrite-strings -c -o analyze.lo ../../../kbd-2.2.0/src/libkeymap/analyze.c
arm-poky-linux-gnueabi-libtool: compile:  arm-poky-linux-gnueabi-gcc -mthumb -mfpu=neon-vfpv4 -mfloat-abi=hard -mcpu=cortex-a7 -fstack-protector-strong -D_FORTIFY_SOURCE=2 -Wformat -Wformat-security -Werror=format-security --sysroot=/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0/recipe-sysroot -DHAVE_CONFIG_H -I. -I../../../kbd-2.2.0/src/libkeymap -I../.. -I../../../kbd-2.2.0/src/libkeymap -I. -I../../../kbd-2.2.0/src/libkeymap/.. -I./.. -I../../../kbd-2.2.0/src/libkeymap/../libcommon -I./../libcommon -I../../../kbd-2.2.0/src/libkeymap/../libkbdfile -I./../libkbdfile -DDATADIR=\"/usr/share\" -DLOCALEDIR=\"/usr/share/locale\" -U_GNU_SOURCE -funit-at-a-time -g -O2 -D_FORTIFY_SOURCE=2 -O2 -pipe -g -feliminate-unused-debug-types -fmacro-prefix-map=/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0=/usr/src/debug/kbd/2.2.0-r0 -fdebug-prefix-map=/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0=/usr/src/debug/kbd/2.2.0-r0 -fdebug-prefix-map=/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0/recipe-sysroot= -fdebug-prefix-map=/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0/recipe-sysroot-native= -Waggregate-return -Wall -Wcast-align -Wconversion -Wdisabled-optimization -Wextra -Wmissing-declarations -Wmissing-format-attribute -Wmissing-noreturn -Wmissing-prototypes -Wpointer-arith -Wredundant-decls -Wshadow -Wstrict-prototypes -Wwrite-strings -c ../../../kbd-2.2.0/src/libkeymap/analyze.c  -fPIC -DPIC -o .libs/analyze.o
analyze.l: In function 'find_incl_file_near_fn':
analyze.l:141:24: warning: passing argument 2 of 'kbdfile_find' from incompatible pointer type [-Wincompatible-pointer-types]
In file included from ../../../kbd-2.2.0/src/libkeymap/keymap/kmap.h:36,
                 from ../../../kbd-2.2.0/src/libkeymap/keymap.h:8,
                 from ../../../kbd-2.2.0/src/libkeymap/analyze.c:1:
../../../kbd-2.2.0/src/libkeymap/../libkbdfile/kbdfile.h:40:37: note: expected 'char **' but argument is of type 'const char **'
   40 | int kbdfile_find(char *fnam, char **dirpath, char **suffixes, struct kbdfile *fp);
      |                              ~~~~~~~^~~~~~~
analyze.l:141:42: warning: passing argument 3 of 'kbdfile_find' from incompatible pointer type [-Wincompatible-pointer-types]
In file included from ../../../kbd-2.2.0/src/libkeymap/keymap/kmap.h:36,
                 from ../../../kbd-2.2.0/src/libkeymap/keymap.h:8,
                 from ../../../kbd-2.2.0/src/libkeymap/analyze.c:1:
../../../kbd-2.2.0/src/libkeymap/../libkbdfile/kbdfile.h:40:53: note: expected 'char **' but argument is of type 'const char * const*'
   40 | int kbdfile_find(char *fnam, char **dirpath, char **suffixes, struct kbdfile *fp);
      |                                              ~~~~~~~^~~~~~~~
analyze.l: In function 'find_standard_incl_file':
analyze.l:168:22: warning: passing argument 2 of 'kbdfile_find' from incompatible pointer type [-Wincompatible-pointer-types]
In file included from ../../../kbd-2.2.0/src/libkeymap/keymap/kmap.h:36,
                 from ../../../kbd-2.2.0/src/libkeymap/keymap.h:8,
                 from ../../../kbd-2.2.0/src/libkeymap/analyze.c:1:
../../../kbd-2.2.0/src/libkeymap/../libkbdfile/kbdfile.h:40:37: note: expected 'char **' but argument is of type 'const char * const*'
   40 | int kbdfile_find(char *fnam, char **dirpath, char **suffixes, struct kbdfile *fp);
      |                              ~~~~~~~^~~~~~~
analyze.l:168:40: warning: passing argument 3 of 'kbdfile_find' from incompatible pointer type [-Wincompatible-pointer-types]
In file included from ../../../kbd-2.2.0/src/libkeymap/keymap/kmap.h:36,
                 from ../../../kbd-2.2.0/src/libkeymap/keymap.h:8,
                 from ../../../kbd-2.2.0/src/libkeymap/analyze.c:1:
../../../kbd-2.2.0/src/libkeymap/../libkbdfile/kbdfile.h:40:53: note: expected 'char **' but argument is of type 'const char * const*'
   40 | int kbdfile_find(char *fnam, char **dirpath, char **suffixes, struct kbdfile *fp);
      |                                              ~~~~~~~^~~~~~~~
analyze.l:197:24: warning: passing argument 2 of 'kbdfile_find' from incompatible pointer type [-Wincompatible-pointer-types]
In file included from ../../../kbd-2.2.0/src/libkeymap/keymap/kmap.h:36,
                 from ../../../kbd-2.2.0/src/libkeymap/keymap.h:8,
                 from ../../../kbd-2.2.0/src/libkeymap/analyze.c:1:
../../../kbd-2.2.0/src/libkeymap/../libkbdfile/kbdfile.h:40:37: note: expected 'char **' but argument is of type 'const char * const*'
   40 | int kbdfile_find(char *fnam, char **dirpath, char **suffixes, struct kbdfile *fp);
      |                              ~~~~~~~^~~~~~~
analyze.l:197:42: warning: passing argument 3 of 'kbdfile_find' from incompatible pointer type [-Wincompatible-pointer-types]
In file included from ../../../kbd-2.2.0/src/libkeymap/keymap/kmap.h:36,
                 from ../../../kbd-2.2.0/src/libkeymap/keymap.h:8,
                 from ../../../kbd-2.2.0/src/libkeymap/analyze.c:1:
../../../kbd-2.2.0/src/libkeymap/../libkbdfile/kbdfile.h:40:53: note: expected 'char **' but argument is of type 'const char * const*'
   40 | int kbdfile_find(char *fnam, char **dirpath, char **suffixes, struct kbdfile *fp);
      |                                              ~~~~~~~^~~~~~~~
analyze.l: In function 'find_incl_file':
analyze.l:210:27: warning: passing argument 2 of 'kbdfile_find' from incompatible pointer type [-Wincompatible-pointer-types]
In file included from ../../../kbd-2.2.0/src/libkeymap/keymap/kmap.h:36,
                 from ../../../kbd-2.2.0/src/libkeymap/keymap.h:8,
                 from ../../../kbd-2.2.0/src/libkeymap/analyze.c:1:
../../../kbd-2.2.0/src/libkeymap/../libkbdfile/kbdfile.h:40:37: note: expected 'char **' but argument is of type 'const char * const*'
   40 | int kbdfile_find(char *fnam, char **dirpath, char **suffixes, struct kbdfile *fp);
      |                              ~~~~~~~^~~~~~~
analyze.l:210:45: warning: passing argument 3 of 'kbdfile_find' from incompatible pointer type [-Wincompatible-pointer-types]
In file included from ../../../kbd-2.2.0/src/libkeymap/keymap/kmap.h:36,
                 from ../../../kbd-2.2.0/src/libkeymap/keymap.h:8,
                 from ../../../kbd-2.2.0/src/libkeymap/analyze.c:1:
../../../kbd-2.2.0/src/libkeymap/../libkbdfile/kbdfile.h:40:53: note: expected 'char **' but argument is of type 'const char * const*'
   40 | int kbdfile_find(char *fnam, char **dirpath, char **suffixes, struct kbdfile *fp);
      |                                              ~~~~~~~^~~~~~~~
analyze.l:225:26: warning: passing argument 2 of 'kbdfile_find' from incompatible pointer type [-Wincompatible-pointer-types]
In file included from ../../../kbd-2.2.0/src/libkeymap/keymap/kmap.h:36,
                 from ../../../kbd-2.2.0/src/libkeymap/keymap.h:8,
                 from ../../../kbd-2.2.0/src/libkeymap/analyze.c:1:
../../../kbd-2.2.0/src/libkeymap/../libkbdfile/kbdfile.h:40:37: note: expected 'char **' but argument is of type 'const char **'
   40 | int kbdfile_find(char *fnam, char **dirpath, char **suffixes, struct kbdfile *fp);
      |                              ~~~~~~~^~~~~~~
analyze.l:225:36: warning: passing argument 3 of 'kbdfile_find' from incompatible pointer type [-Wincompatible-pointer-types]
In file included from ../../../kbd-2.2.0/src/libkeymap/keymap/kmap.h:36,
                 from ../../../kbd-2.2.0/src/libkeymap/keymap.h:8,
                 from ../../../kbd-2.2.0/src/libkeymap/analyze.c:1:
../../../kbd-2.2.0/src/libkeymap/../libkbdfile/kbdfile.h:40:53: note: expected 'char **' but argument is of type 'const char * const*'
   40 | int kbdfile_find(char *fnam, char **dirpath, char **suffixes, struct kbdfile *fp);
      |                                              ~~~~~~~^~~~~~~~
In file included from analyze.l:10:
analyze.l: In function 'yylex':
analyze.l:466:19: error: format not a string literal and no format arguments [-Werror=format-security]
../../../kbd-2.2.0/src/libkeymap/contextP.h:79:55: note: in definition of macro 'lk_log_cond'
   79 |    lk_log(ctx, level, __FILE__, __LINE__, __func__, ##arg); \
      |                                                       ^~~
analyze.l:466:6: note: in expansion of macro 'ERR'
cc1: some warnings being treated as errors
make[4]: *** [Makefile:604: analyze.lo] Error 1
make[4]: Leaving directory '/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0/build/src/libkeymap'
make[3]: *** [Makefile:476: all] Error 2
make[3]: Leaving directory '/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0/build/src/libkeymap'
make[2]: *** [Makefile:1083: all-recursive] Error 1
make[2]: Leaving directory '/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0/build/src'
make[1]: *** [Makefile:471: all-recursive] Error 1
make[1]: Leaving directory '/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0/build'
ERROR: oe_runmake failed
make: *** [Makefile:402: all] Error 2
WARNING: exit code 1 from a shell command.
ERROR: Execution of '/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0/temp/run.do_compile.380' failed with exit code 1

When I checked the sources/poky/meta/recipes-core/kbd, add missing string format patch patch is already available and included in kbd_2.2.0.bb recipe. And same patch is also present in build/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/kbd/2.2.0-r0. But still I am getting above error.

I have no idea what this error means and why am I getting this all of a sudden.

Can anyone please let me know how to fix this issue?

Your help will be much appreciated.

Thanks in advance.

Body:
You should NOT do the following, its likely your code compiles just fine on an older version of GCC, but GCC adds new warnings and errors for security purposes, you should really look at the code and fix it properly, it is also very likely you just need to use a newer version of kbd that builds contains these fixes (kbd is at 2.4.0 in the latest branch: https://git.yoctoproject.org/poky/tree/meta/recipes-core/kbd/kbd_2.4.0.bb).

But if you want to temporarily disable the GCC error to check if your build works while you either fix the kbd code or upgrade to a new version of kbd, you could set:

CFLAGS += "-Wno-error=format-security"

Which will suppress the compilation error, I cannot stress this enough, the fix is to actually fix the kbd code.


来源: stackexchange

问:
Head & tail string in one line - possible?
I want to retrieve the first X and the last Y characters from a string (standard ascii, so no worries about unicode).

I understand that I can do this as seperate actions, i.e. :

```<code>FIRST=$(echo foobar | head -c 3)
LAST=$(echo foobar | tail -c 3)
COMBINED= "${FIRST}${LAST}"
</code>```

But is there a cleaner way to do this ?

I would prefer to use common standard utils (i.e. bash built-ins, sed, awk etc.).  At a push, a Perl one-liner is OK, but no Python or anything else.

答:
$ perl -E '($s, $x, $y) = @ARGV; substr $s, $x, -$y, ""; say $s' abcdefgh 2 3
abfgh
```

The four argument variant of substr replaces the given portion of the string with the last argument. Here, we replace from position $x to position -$y (negative numbers count from the end of the string), and use an empty string as replacement, i.e. we remove the middle part.

ContentLicense: CC BY-SA 4.0

Body:
I want to retrieve the first X and the last Y characters from a string (standard ascii, so no worries about unicode).

I understand that I can do this as seperate actions, i.e. :

FIRST=$(echo foobar | head -c 3)
LAST=$(echo foobar | tail -c 3)
COMBINED= "${FIRST}${LAST}"

But is there a cleaner way to do this ?

I would prefer to use common standard utils (i.e. bash built-ins, sed, awk etc.).  At a push, a Perl one-liner is OK, but no Python or anything else.

Body:
$ perl -E '($s, $x, $y) = @ARGV; substr $s, $x, -$y, ""; say $s' abcdefgh 2 3
abfgh

The four argument variant of substr replaces the given portion of the string with the last argument. Here, we replace from position $x to position -$y (negative numbers count from the end of the string), and use an empty string as replacement, i.e. we remove the middle part.


问:
How do I set EOF on an istream without reading formatted input?
I'm doing a read in on a file character by character using istream::get(). How do I end this function with something to check if there's nothing left to read in formatted in the file (eg. only whitespace) and set the corresponding flags (EOF, bad, etc)?</p>

答:
How do I end this function with something to check if there's nothing left to read in formatted in the file (eg. only whitespace)?

Whitespace characters are characters in the stream. You cannot assume that the stream will do intelligent processing for you. Until and unless, you write your own filtering stream.

OwnerDisplayName: Stuart P. Bentley

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Stuart P. Bentley

OwnerDisplayName: dirkgently

LastEditorDisplayName: dirkgently


问:
Dynamicly apply css changes on html code with js
here's the situation

I have a select element in my html code, with many option. One of these options is "Other". What I want is, when I select "Other", without refreshing the page, display an input element right under the select one with JS. The problem is that I have to refresh the page to see the change. Can you help me? :)

There's my code :

```<code><label for="select-tribunal" class="form-label">Cadre Légal</label>
            <select id="select-tribunal" required class="form-select" aria-label="Default select example">
                <?php
                foreach ($tribunaux as $tribunal){
                    echo '<option value="'.$tribunal['id'].'">'.$tribunal['nom'].'</option>';
                }
                ?>
                <option value="0">Autre Tribunal</option>
            </select>
                <input type="text" class="form-control" id="tribunal" style="visibility: hidden" placeholder="Entrez le nom du tribunal">
            <script>
                var tribunal = document.getElementById("select-tribunal");
                    if (tribunal.options[tribunal.selectedIndex].value === '0') {
                        document.getElementById('tribunal').style.visibility = 'visible';
                    } else  {
                        document.getElementById('tribunal').style.visibility = 'hidden';
                    }
            </script>
</code>```

Thanks in advance :)

答:
Since php is running on server the page have to reload in order to see the changes you need to use JavaScript for for this task since you want to see the changes without reload

var select = document.querySelector("#mySelect");
var input = document.querySelector("#myInput");
select.addEventListener("change", function(event){
  if(event.target.value === "other"){
    input.style.display="block"
  }else{
    input.style.display="none"
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select id="mySelect">
    <option value="a">A</option>
    <option value="a">B</option>
    <option value="c">C</option>
    <option value="other">Other</option>
</select>
<input style="display: none" type="text" id="myInput"></code>```

Body:
here's the situation

I have a select element in my html code, with many option. One of these options is "Other". What I want is, when I select "Other", without refreshing the page, display an input element right under the select one with JS. The problem is that I have to refresh the page to see the change. Can you help me? :)

There's my code :

Cadre Légal
            <select id="select-tribunal" required class="form-select" aria-label="Default select example">
                <?php
                foreach ($tribunaux as $tribunal){
                    echo '<option value="'.$tribunal['id'].'">'.$tribunal['nom'].'</option>';
                }
                ?>
                <option value="0">Autre Tribunal</option>
            </select>
                <input type="text" class="form-control" id="tribunal" style="visibility: hidden" placeholder="Entrez le nom du tribunal">

Thanks in advance :)

Body:
Since php is running on server the page have to reload in order to see the changes you need to use JavaScript for for this task since you want to see the changes without reload

var select = document.querySelector("#mySelect");
var input = document.querySelector("#myInput");
select.addEventListener("change", function(event){
  if(event.target.value === "other"){
    input.style.display="block"
  }else{
    input.style.display="none"
  }
})

<select id="mySelect">
    <option value="a">A</option>
    <option value="a">B</option>
    <option value="c">C</option>
    <option value="other">Other</option>
</select>
<input style="display: none" type="text" id="myInput">


问:
UsageStatsManager is not working in android 11 with permission of PACKAGE_USAGE_STATS
my application is working perfectly for 10 and lower versions of android. I have checked the documentation they said something changed about usage stats functionality(i.e https://developer.android.com/about/versions/11/behavior-changes-all#app-usage-stats) Any help?</p>

答:
After two days of struggle I have got the solution for my problem. Actually
context.getPackageManager().getInstalledApplications(PackageManager.GET_META_DATA);  Should return the list of all the installed apps but in android 11 it'll only return the list of system apps. To get the list of all the applications(system+user) we need to provide an additional permission to the application i.e


问:
Find 3rd largest element in an array without sorting
I have these similar kinds of questions over and over again in python. I want to master the way to solve this kind of problem. Please help me.

The questions are like "Find the 3rd largest (or 2nd largest or sometimes kth largest) element(or item) in an array without sorting" sometimes there comes another condition "with a minimum number of comparison" or "in O(n) time". How do I approach? or how to write an algorithm for this?

Thanks!

答:
```<code>from heapq import heapify,heappop,heappush

class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        heap = []
        # this creates min-heap
        heapify(heap)
        for e in nums:
            #  with O(log n) push and O(log n) pop
            heappush(heap,e)
            if len(heap)>k:
                heappop(heap)
        return heappop(heap)
</code>```


问:
React component displayed regardless of URL input
I'm following a tutorial using the react-router-dom React library.

The problem I have is that my navigation header is displayed regardless of which URL I write in the address bar after localhost:3000, (for ex localhost:3000/dflkjfhdlkfjhdf will actually display the navigation header instead of saying it's an invalid URL)

index.js:

```<code>ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.getElementById("root")
</code>```

App.js:

```<code>function App() {
  return (
    <div>
      <MainNavigation />
      <Routes>
        <Route path="/" element={<AllMeetupsPage />} />
        <Route path="/new-meetup" element={<NewMeetupPage />} />
        <Route path="/favorites" element={<FavoritesPage />} />
      </Routes>
    </div>
  );
}
</code>```

MainNavigation.js:

```<code>function MainNavigation() {
  return (
    <header className={classes.header}>
      <div className={classes.logo}> React Meetups </div>
      <nav>
        <ul>
          <li>
            <Link to="/">All Meetups</Link>
          </li>
          <li>
            <Link to="/new-meetup">Add New Meetup</Link>
          </li>
          <li>
            <Link to="/favorites">My Favorites</Link>
          </li>
        </ul>
      </nav>
    </header>
  );
}
</code>```

with all the necessary import statements.

I think the problem might be that <MainNavigation />is in the App() function which is wrapped in <BrowserRouter> tags in index.js.

However I don't understand the mechanism or how to prevent this from happening (or whether it matters in the first place since it probably won't happen once I deploy the app).

EDIT: To be clear I want the <MainNavigation /> component in App.js because I want that component displayed on every page, but maybe not on localhost:3000/dfkjldfkjh

答:
The issue it seems is that your app doesn't do anything to "avoid" URL paths it doesn't exclusively have a match for. With a path like "/dfkjldfkjh" the Routes component will check for a match, and not find any, and correctly not return any matched routed component to render. The MainNavigation will still render regardless of any route path matching.

The solution then is to add a redirect route to your app to handle any "unknown" paths and redirect the app back to a known, handled route.

```<code><Route path="*" element={<Navigate to="/" replace />} />
</code>```

Navigate

Example:

```<code>import { Routes, Route, Navigation } from 'react-router-dom';

function App() {
  return (
    <div>
      <MainNavigation />
      <Routes>
        <Route path="/" element={<AllMeetupsPage />} />
        <Route path="/new-meetup" element={<NewMeetupPage />} />
        <Route path="/favorites" element={<FavoritesPage />} />
        <Route path="*" element={<Navigate to="/" replace />} />
      </Routes>
    </div>
  );
}
</code>```

Body:
I'm following a tutorial using the react-router-dom React library.

The problem I have is that my navigation header is displayed regardless of which URL I write in the address bar after localhost:3000, (for ex localhost:3000/dflkjfhdlkfjhdf will actually display the navigation header instead of saying it's an invalid URL)

index.js:

ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.getElementById("root")

App.js:

function App() {
  return (

      <MainNavigation />
      <Routes>
        <Route path="/" element={<AllMeetupsPage />} />
        <Route path="/new-meetup" element={<NewMeetupPage />} />
        <Route path="/favorites" element={<FavoritesPage />} />
      </Routes>

  );
}

MainNavigation.js:

function MainNavigation() {
  return (

 React Meetups

            <Link to="/">All Meetups</Link>

            <Link to="/new-meetup">Add New Meetup</Link>

            <Link to="/favorites">My Favorites</Link>

  );
}

with all the necessary import statements.

I think the problem might be that <MainNavigation />is in the App() function which is wrapped in <BrowserRouter> tags in index.js.

However I don't understand the mechanism or how to prevent this from happening (or whether it matters in the first place since it probably won't happen once I deploy the app).

EDIT: To be clear I want the <MainNavigation /> component in App.js because I want that component displayed on every page, but maybe not on localhost:3000/dfkjldfkjh

Body:
The issue it seems is that your app doesn't do anything to "avoid" URL paths it doesn't exclusively have a match for. With a path like "/dfkjldfkjh" the Routes component will check for a match, and not find any, and correctly not return any matched routed component to render. The MainNavigation will still render regardless of any route path matching.

The solution then is to add a redirect route to your app to handle any "unknown" paths and redirect the app back to a known, handled route.

<Route path="*" element={<Navigate to="/" replace />} />

Navigate

Example:

import { Routes, Route, Navigation } from 'react-router-dom';

function App() {
  return (
    <div>
      <MainNavigation />
      <Routes>
        <Route path="/" element={<AllMeetupsPage />} />
        <Route path="/new-meetup" element={<NewMeetupPage />} />
        <Route path="/favorites" element={<FavoritesPage />} />
        <Route path="*" element={<Navigate to="/" replace />} />
      </Routes>
    </div>
  );
}


问:
showing error message returned from server validation in react
Below is axios request sent to server for data submit and in return I am getting validation errors if any,

```<code>  const storeExpense = async (expenseData) => {

    const response = await axios.post('/api/expenses/store/', expenseData).catch(function (error) {
      if (error.response) {
        return error.response.data;

      } else if (error.request) {
        console.log(error.request);
      } else {

        console.log('Error', error.message);
      }
    });
    return response;
  }
</code>```

In another component, I storing return in variable,

```<code>const response = await storeExpense(values)

if('errors' in response)
{
  setValErrors(Object.values(response))
  setStatus({ success: false });
  setErrors({ submit: response.errors });
  setSubmitting(false);
  setRequestStatus(true)
}

</code>```

Below is the return response, it's an array and with objects.

```<code>Array [ "The given data was invalid.", {…} ]

0: "The given data was invalid."

1: Object { expense_description: (1) […], accountcustomtype_id: (1) […], expense_date: (1) […], … }

accountcustomtype_id: Array [ "Expense account is required." ]

expense_amount: Array [ "Expense amount is required." ]

expense_date: Array [ "Expense date is required." ]

expense_description: Array [ "Expense description is required." ]

paymentoption_id: Array [ "Payment with is required." ]

taxgroup_id: Array [ "Tax is required." ]

</code>```

How can I print each validation error messages? with .map()?

Thank you,

答:
Updated after @rjcode comment

You can try to get all errors as an array like this:

const errorsArr = [].concat(...Object.values(responce[1]))
```
<p>And after that you are able to print all errors from this array in <code><li></code>, as an example:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const responce = ["The given data was invalid.",
  {
    expense_description: ["Expense account is required."],
    accountcustomtype_id: ["Expense account is required."],
    expense_date: ["Expense date is required."],
    paymentoption_id: ["Payment with is required."],
    taxgroup_id: ["Tax is required."]
  }
]

const errorsArr = [].concat(...Object.values(responce[1]))

class LoopThrough extends React.Component {
  render() {
    return (
      <div>
        {this.props.errors.map(error => (
          <li key={error} >{error}</li>
        ))}
      </div>
    );
  }
}

ReactDOM.render(
  <LoopThrough errors={errorsArr} />,
  document.getElementById('container')
);</code>```

```

Body:
Below is axios request sent to server for data submit and in return I am getting validation errors if any,

  const storeExpense = async (expenseData) => {

    const response = await axios.post('/api/expenses/store/', expenseData).catch(function (error) {
      if (error.response) {
        return error.response.data;

      } else if (error.request) {
        console.log(error.request);
      } else {

        console.log('Error', error.message);
      }
    });
    return response;
  }

In another component, I storing return in variable,

const response = await storeExpense(values)

if('errors' in response)
{
  setValErrors(Object.values(response))
  setStatus({ success: false });
  setErrors({ submit: response.errors });
  setSubmitting(false);
  setRequestStatus(true)
}

Below is the return response, it's an array and with objects.

Array [ "The given data was invalid.", {…} ]

0: "The given data was invalid."

1: Object { expense_description: (1) […], accountcustomtype_id: (1) […], expense_date: (1) […], … }

accountcustomtype_id: Array [ "Expense account is required." ]

expense_amount: Array [ "Expense amount is required." ]

expense_date: Array [ "Expense date is required." ]

expense_description: Array [ "Expense description is required." ]

paymentoption_id: Array [ "Payment with is required." ]

taxgroup_id: Array [ "Tax is required." ]

How can I print each validation error messages? with .map()?

Thank you,

Body:
Updated after @rjcode comment

You can try to get all errors as an array like this:

const errorsArr = [].concat(...Object.values(responce[1]))

And after that you are able to print all errors from this array in <li>, as an example:

const responce = ["The given data was invalid.",
  {
    expense_description: ["Expense account is required."],
    accountcustomtype_id: ["Expense account is required."],
    expense_date: ["Expense date is required."],
    paymentoption_id: ["Payment with is required."],
    taxgroup_id: ["Tax is required."]
  }
]

const errorsArr = [].concat(...Object.values(responce[1]))

class LoopThrough extends React.Component {
  render() {
    return (
      <div>
        {this.props.errors.map(error => (
          <li key={error} >{error}</li>
        ))}
      </div>
    );
  }
}

ReactDOM.render(
  <LoopThrough errors={errorsArr} />,
  document.getElementById('container')
);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="container">
</div>


问:
Xcode Error Analyzing App Version when validating app in archive organizer
I am running Xcode Version 13.0 (13A233)

My build process that is normally run through fastlane stopped working recently ( was working fine up until a few days ago ).

I've been trying to get the build process working again through Xcode before tackling any issues that might still persist with Fastlane.

I archive my app through Xcode and that completes successfully with no issues. Then in the archives section under the organizer. I try clicking 'Validate App' and get the following error:

Error Analyzing App Version

Build number request failed with error: BuildsService: ResponseErrors (1): Error status: 403, code: FORBIDDEN_ERROR, title: 'This request is forbidden for security reasons', detail: 'The API key in use does not allow this request', id: a147f6b6-dcd4-42a6-9cfc-b7d1fa500a85

I have not configured Xcode to use the App Store Connect API at all, nor could I find anywhere to do so. Normally it just ran through my developer account.

I have tried using the App Store Connect API through Fastlane to see if that would fix the issue, however it stays the same.

What might be causing this and how I can go about fixing it?

答:
You can view the error log，and you may find account conflicts.
Operation process：Xcode->Preferences->Accounts,remove other account and try again.</p>


问:
Installing MSSQL functions in PHP
I'm trying to connect to my SQL server through PHP. Obviously using MySQL php functions do not work, how do I go about installing MSSQL functions for PHP on OSX? After exhausting google, I thought there would be a lot more tutorials are resources available which suggests to me this isn't the best way to connect to an SQL server.

Thank you in advance!

答:
Example:

```<code>function read($id){
$myServer = "xx.xx.x.x";
$myUser = "us";
$myPass = "pas";
$myDB = "db";

//connection to the database
$dbhandle = mssql_connect($myServer, $myUser, $myPass)
  or die("Couldn't connect to SQL Server on $myServer");

$dbhandle =  mssql_select_db($myDB,$dbhandle);

echo "Connected";

//declare the SQL statement that will query the database
$query = " SELECT col1 from table1";

//execute the SQL query and return records
$result = mssql_query($query) or die("Couldn't execute query");

$numRows = mssql_num_rows($result);
echo "<h1>" . $numRows . " Row" .$numRows. ($numRows == 1 ? "" : "s") . " Returned </h1>";

//display the results
while($row = mssql_fetch_array($result))
{
...
}

//close the connection
mssql_close($dbhandle);
}
</code>```

For further detail, see this link

http://php.net/manual/en/book.mssql.php

ContentLicense: CC BY-SA 3.0

Title: Installing MSSQL functions in PHP

Body:
Example:

function read($id){
$myServer = "xx.xx.x.x";
$myUser = "us";
$myPass = "pas";
$myDB = "db";

//connection to the database
$dbhandle = mssql_connect($myServer, $myUser, $myPass)
  or die("Couldn't connect to SQL Server on $myServer");

$dbhandle =  mssql_select_db($myDB,$dbhandle);

echo "Connected";

//declare the SQL statement that will query the database
$query = " SELECT col1 from table1";

//execute the SQL query and return records
$result = mssql_query($query) or die("Couldn't execute query");

$numRows = mssql_num_rows($result);
echo "<h1>" . $numRows . " Row" .$numRows. ($numRows == 1 ? "" : "s") . " Returned </h1>";

//display the results
while($row = mssql_fetch_array($result))
{
...
}

//close the connection
mssql_close($dbhandle);
}

For further detail, see this link

http://php.net/manual/en/book.mssql.php


问:
Why is my iteration not working inside the function?
```<code>#Password Checker Program
def lengthCheck(pWord):
    if len(pWord) >= 6 and len(pWord) <= 12:
        return True
    else:
        return False

def checkUpper(pWord):
    for letters in pWord: #Why is my iteration not working?
        upperLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        if upperLetters in pWord:
            return True
        else:
            return False

def checkLower(pWord):
    for letters in pWord: #Why is my iteration not working?
        upperLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        lowerLetters = upperLetters.lower()
        if lowerLetters in pWord:
            return True
        else:
            return False

def checkDigit(pWord):
    for letters in pWord: #Why is my iteration not working?
        digitNumbers = "0123456789"
        if digitNumbers in pWord:
            return True
        else:
            return False

def complexCheck(pWord):
    if checkUpper(pWord) and checkLower(pWord) and checkDigit(pWord):
        return True
    else:
        return False

def passCheck(pWord):
    if lengthCheck(pWord) and complexCheck(pWord):
        return True
    else:
        return False

goodPWord = True
pWord = ""
pWord = input("Please enter your password: ")
goodPWord = passCheck(pWord)
if goodPWord:
    print(pWord, " is a good password.")
else:
    print(pWord, " is not a good password")
</code>```

I need help with this problem, I can't the errors myself so plz help me. This my homework assignment from school I need help with this problem, I can't the errors myself so plz help me. This my homework assignment from schoolI need help with this problem, I can't the errors myself so plz help me. This my homework assignment from school
enter image description here

答:
I'll focus on checkUpper and then you can replicate in the other two functions.

You have two main problems.

The first problem is that you're trying to match the entire string of upperLetters to see if it exists in pWord, even though you're looping pWord. Instead, you need to check if the currently looped letter is inside upperLetters.

This:

if upperLetters in pWord:

Should be this instead:

if letters in upperLetters:

You're looping pWord and getting a letter at a time (which you called letters). That's what you need to compare to upperLetters, not the whole pWord.

The second problem is that you're returning true or false after the first check so if the first letter isn't an uppercase letter then the rest of the password is ignored! Instead you need to keep a boolean variable that is returned false only if none of the letters match upperLetters.

So the whole function becomes this:

```<code>def checkUpper(pWord):
    upperLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" #Moved here so you don't define it on every iteration of the loop
    atLeastOne = False #Start as false
    for letters in pWord: #Loop through all letters
        if letters in upperLetters: #Does the current letter exist in upperLetters?
            atLeastOne = True #If so the flag becomes True
            break #exit the loop
    return atLeastOne #Returns false only if none of the letters were upper case
</code>```

You can also avoid the flag entirely (as below), but I think the above is clearer to read and understand, and would be more useful if in the future you want to check if they have more than 1 upper case letter, for example, by keeping a counter instead of a boolean.

```<code>def checkUpper(pWord):
    upperLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" #Moved here so you don't define it on every iteration of the loop
    for letters in pWord: #Loop through all letters
        if letters in upperLetters: #Does the current letter exist in upperLetters?
            return True
    return False #If none matched
</code>```

Just replicate these changes to the remaining functions.

Body:
#Password Checker Program
def lengthCheck(pWord):
    if len(pWord) >= 6 and len(pWord) <= 12:
        return True
    else:
        return False

def checkUpper(pWord):
    for letters in pWord: #Why is my iteration not working?
        upperLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        if upperLetters in pWord:
            return True
        else:
            return False

def checkLower(pWord):
    for letters in pWord: #Why is my iteration not working?
        upperLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        lowerLetters = upperLetters.lower()
        if lowerLetters in pWord:
            return True
        else:
            return False

def checkDigit(pWord):
    for letters in pWord: #Why is my iteration not working?
        digitNumbers = "0123456789"
        if digitNumbers in pWord:
            return True
        else:
            return False

def complexCheck(pWord):
    if checkUpper(pWord) and checkLower(pWord) and checkDigit(pWord):
        return True
    else:
        return False

def passCheck(pWord):
    if lengthCheck(pWord) and complexCheck(pWord):
        return True
    else:
        return False

goodPWord = True
pWord = ""
pWord = input("Please enter your password: ")
goodPWord = passCheck(pWord)
if goodPWord:
    print(pWord, " is a good password.")
else:
    print(pWord, " is not a good password")

I need help with this problem, I can't the errors myself so plz help me. This my homework assignment from school I need help with this problem, I can't the errors myself so plz help me. This my homework assignment from schoolI need help with this problem, I can't the errors myself so plz help me. This my homework assignment from school
enter image description here

Body:
I'll focus on checkUpper and then you can replicate in the other two functions.

You have two main problems.

The first problem is that you're trying to match the entire string of upperLetters to see if it exists in pWord, even though you're looping pWord. Instead, you need to check if the currently looped letter is inside upperLetters.

This:

if upperLetters in pWord:

Should be this instead:

if letters in upperLetters:

You're looping pWord and getting a letter at a time (which you called letters). That's what you need to compare to upperLetters, not the whole pWord.

The second problem is that you're returning true or false after the first check so if the first letter isn't an uppercase letter then the rest of the password is ignored! Instead you need to keep a boolean variable that is returned false only if none of the letters match upperLetters.

So the whole function becomes this:

def checkUpper(pWord):
    upperLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" #Moved here so you don't define it on every iteration of the loop
    atLeastOne = False #Start as false
    for letters in pWord: #Loop through all letters
        if letters in upperLetters: #Does the current letter exist in upperLetters?
            atLeastOne = True #If so the flag becomes True
            break #exit the loop
    return atLeastOne #Returns false only if none of the letters were upper case

You can also avoid the flag entirely (as below), but I think the above is clearer to read and understand, and would be more useful if in the future you want to check if they have more than 1 upper case letter, for example, by keeping a counter instead of a boolean.

def checkUpper(pWord):
    upperLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" #Moved here so you don't define it on every iteration of the loop
    for letters in pWord: #Loop through all letters
        if letters in upperLetters: #Does the current letter exist in upperLetters?
            return True
    return False #If none matched

Just replicate these changes to the remaining functions.


问:
How to align elements in three columns, even when resizing
Desired outcome: I have three columns. I need them to be all the same width, as well as text and buttons to be on the same level in all three of them.

Problem: Depending on the number of words, columns become wider and buttons start to jump when text is resizing, and all three texts are resizing on a different points. I need to prevent that. How can I achieve this?

HTML:

```<code><section class="sub-offer">
      <div class="offer-container">
        <div class="offer-up">
          <h2>Lorem, ipsum.</h2>
          <img src="https://via.placeholder.com/150x150.png/09f/fff" alt="" />
        </div>
        <div class="offer-down">
          <p>
            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minus a
            rerum sapiente odit porro obcaecati fugit, maxime modi veritatis
            quis!
          </p>
        </div>
        <div class="more-btn">
          <a href="#">Lorem, ipsum.</a>
        </div>
      </div>

      <div class="offer-container">
        <div class="offer-up">
          <h2>Lorem, ipsum.</h2>
          <img src="https://via.placeholder.com/150x150.png/09f/fff" alt="" />
        </div>
        <div class="offer-down">
          <p>
            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Excepturi
            perspiciatis voluptas qui iste, voluptatem atque ab rerum illum quia
            incidunt odio?
          </p>
        </div>
        <div class="more-btn">
          <a href="#">Lorem, ipsum.</a>
        </div>
      </div>

      <div class="offer-container">
        <div class="offer-up">
          <h2>Lorem, ipsum.</h2>
          <img src="https://via.placeholder.com/150x150.png/09f/fff" alt="" />
        </div>
        <div class="offer-down">
          <p>
            Lorem ipsum dolor sit amet consectetur adipisicing elit. Beatae
            vitae aut fugit dicta repellendus dolorem, quam, accusamus hic nemo
            ullam quod porro atque error?
          </p>
        </div>
        <div class="more-btn">
          <a href="#">Lorem, ipsum.</a>
        </div>
      </div>
    </section>
</code>```

CSS:

```<code>.sub-offer {
  text-align: center;
  display: flex;
  position: relative;

  .offer-container {
    background: linear-gradient(to bottom right, #2e2e3b, #0f1519);
  }

  h2 {
    font-family: 'Playfair Display', serif;
    font-size: 15px;
    position: absolute;
    margin-left: auto;
    margin-right: auto;
    margin-top: 4.3em;
    width: 33%;
    text-align: center;
  }

  p {
    font-size: 12px;
    margin-top: 2em;
    padding: 0 0.5em 0 0.5em;
    font-family: 'Montserrat', sans-serif;
  }

  a {
    display: inline-block;
    font-family: 'Montserrat', sans-serif;
    font-size: 12px;
    background: white;
    margin: 3em 0 2.5em 0;
    padding: 0.5em;
    text-decoration: none;
    color: black;

    &:hover {
      background: #e5e5e5;
    }
  }
}
</code>```

How they look now:

答:
You can add a media query to change the flex-direction when the screen resizes.

Add the following indie .sub-offer class.

@media(max-width: 600px){
  flex-direction: column;
}
```
<ol start="2">
<li>Add the following inside <code>h2</code> element.</li>
</ol>
<pre class="lang-css prettyprint-override"><code>@media(max-width: 600px){
  width: 100%;
}
</code>```

Body:
Desired outcome: I have three columns. I need them to be all the same width, as well as text and buttons to be on the same level in all three of them.

Problem: Depending on the number of words, columns become wider and buttons start to jump when text is resizing, and all three texts are resizing on a different points. I need to prevent that. How can I achieve this?

HTML:

Lorem, ipsum.

            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minus a
            rerum sapiente odit porro obcaecati fugit, maxime modi veritatis
            quis!

          Lorem, ipsum.

Lorem, ipsum.

            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Excepturi
            perspiciatis voluptas qui iste, voluptatem atque ab rerum illum quia
            incidunt odio?

          Lorem, ipsum.

Lorem, ipsum.

            Lorem ipsum dolor sit amet consectetur adipisicing elit. Beatae
            vitae aut fugit dicta repellendus dolorem, quam, accusamus hic nemo
            ullam quod porro atque error?

          Lorem, ipsum.

CSS:

.sub-offer {
  text-align: center;
  display: flex;
  position: relative;

  .offer-container {
    background: linear-gradient(to bottom right, #2e2e3b, #0f1519);
  }

  h2 {
    font-family: 'Playfair Display', serif;
    font-size: 15px;
    position: absolute;
    margin-left: auto;
    margin-right: auto;
    margin-top: 4.3em;
    width: 33%;
    text-align: center;
  }

  p {
    font-size: 12px;
    margin-top: 2em;
    padding: 0 0.5em 0 0.5em;
    font-family: 'Montserrat', sans-serif;
  }

  a {
    display: inline-block;
    font-family: 'Montserrat', sans-serif;
    font-size: 12px;
    background: white;
    margin: 3em 0 2.5em 0;
    padding: 0.5em;
    text-decoration: none;
    color: black;

    &:hover {
      background: #e5e5e5;
    }
  }
}

How they look now:

Body:
You can add a media query to change the flex-direction when the screen resizes.

Add the following indie .sub-offer class.

@media(max-width: 600px){
  flex-direction: column;
}

Add the following inside h2 element.

@media(max-width: 600px){
  width: 100%;
}


问:
TYPO3 Exception: Could not determine pid
While trying to add a new fe_users record, on save I get

```<code>(1/1) Exception
Could not determine pid
</code>```

It's TYPO3 9.5.20.

We already have a lot of entries in multiple folders which could be edited without problem.

But those records were imported (by EXT:ig_ldap_sso_auth or with mysql terminal)

These records are used only to be shown (no login is used).

What configuration is missing or could be wrong?

EDIT:

as @biesior mentioned: the error message does not come from the core but from an extension. It's EXT:solrfal (in version 7.0.0)

答:
Hi just got the same problem.

The error message was called in solrfal ConsistencyAspect::getRecordPageId() which was called by ConsistencyAspect::getDetectorsForSiteExclusiveRecord(). I remember that I have added various tablenames to siteExclusiveRecordTables of Extension Settings of solrfal. And yes, there was one table without pid. After removing this table from list, deleting files works again.

Body:
While trying to add a new fe_users record, on save I get

(1/1) Exception
Could not determine pid

It's TYPO3 9.5.20.

We already have a lot of entries in multiple folders which could be edited without problem.

But those records were imported (by EXT:ig_ldap_sso_auth or with mysql terminal)

These records are used only to be shown (no login is used).

What configuration is missing or could be wrong?

EDIT:

as @biesior mentioned: the error message does not come from the core but from an extension. It's EXT:solrfal (in version 7.0.0)


问:
Next js creates different mysql connection pools if behind nginx
this is my first question, hope I do it right!

I'm actually working on a Centos server with nginx as reverse proxy and a NextJs web application.

Until now I've made a single connection for every query to my db, but I want to switch to pool connection to my DB (with npm module mysql2), but apparently there's something I'm missing...

If I run my application local, or on the server without nginx, with yarn start, it opens just one pool (I can see them by running the query SHOW PROCESSLIST on the DB in use). But in the moment I add nginx as reverse proxy, every request my app receives opens a pool and the latter never gets closed or called again (apart from the one pool opened if someone visits the page for which I use the nextjs function router.push(/url)).

It happens also if I run yarn dev: it opens a connection pool for every new page next has to build in development or if I make some changes to pages and save. But this behaviour I understand.

The nginx configuration is a normal configuration, and everything works fine.

I've surfed the web far and wide, but didn't find anything that could help me understand what could be going on between nginx-next-mysqldb, and no one reported any problem whatsoever. Is this how it's supposed to be or there's something that I should do to make it work?

答:
Oops... my bad...
Transitioning from single db connections to pool, I left a function which made a single connection, which I was not closing.

So there's no problem and nothing to uncover behind nginx-next-mysql.

Don't know if anyone will stumble upon this problem, ever, but, just make sure you don't have any single connection to your db... And make sure to close them :)


问:
Failed to load SWC binary
When trying to run the command using Next.js npm run dev shows error - failed to load SWC binary see more info here: https://nextjs.org/docs/messages/failed-loading-swc.

```<code>PS D:\web-development\new-project\explore> npm run dev

> dev
> next dev

ready - started server on 0.0.0.0:3000, url: http://localhost:3000
Error: The specified module could not be found.
\\?\D:\web-development\new-project\explore\node_modules\@next\swc-win32-x64-msvc\next-swc.win32-x64-msvc.node
    at Object.Module._extensions..node (node:internal/modules/cjs/loader:1179:18)
    at Module.load (node:internal/modules/cjs/loader:975:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:999:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at loadNative (D:\web-development\new-project\explore\node_modules\next\dist\build\swc\index.js:84:28)
    at loadBindings (D:\web-development\new-project\explore\node_modules\next\dist\build\swc\index.js:41:32)
    at async Object.isWasm (D:\web-development\new-project\explore\node_modules\next\dist\build\swc\index.js:146:20)
    at async D:\web-development\new-project\explore\node_modules\next\dist\build\webpack\loaders\next-swc-loader.js:62:178 {
  code: 'ERR_DLOPEN_FAILED'
}
error - Failed to load SWC binary, see more info here: https://nextjs.org/docs/messages/failed-loading-swc
PS D:\web-development\new-project\explore>
</code>```

答:
The best way to solve this issue

I solved this issue by removing node_modules and reinstall packages. I think it's the best solution.

Just run

```<code>rm -rf node_modules      // Linux
rmdir /S node_modules   // Windows
</code>```

And them install packages

```<code>npm install
</code>```

Finally run

```<code>npm run dev
</code>```

Title: Failed to load SWC binary

Body:
When trying to run the command using Next.js npm run dev shows error - failed to load SWC binary see more info here: https://nextjs.org/docs/messages/failed-loading-swc.

PS D:\web-development\new-project\explore> npm run dev

> dev
> next dev

ready - started server on 0.0.0.0:3000, url: http://localhost:3000
Error: The specified module could not be found.
\\?\D:\web-development\new-project\explore\node_modules\@next\swc-win32-x64-msvc\next-swc.win32-x64-msvc.node
    at Object.Module._extensions..node (node:internal/modules/cjs/loader:1179:18)
    at Module.load (node:internal/modules/cjs/loader:975:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:999:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at loadNative (D:\web-development\new-project\explore\node_modules\next\dist\build\swc\index.js:84:28)
    at loadBindings (D:\web-development\new-project\explore\node_modules\next\dist\build\swc\index.js:41:32)
    at async Object.isWasm (D:\web-development\new-project\explore\node_modules\next\dist\build\swc\index.js:146:20)
    at async D:\web-development\new-project\explore\node_modules\next\dist\build\webpack\loaders\next-swc-loader.js:62:178 {
  code: 'ERR_DLOPEN_FAILED'
}
error - Failed to load SWC binary, see more info here: https://nextjs.org/docs/messages/failed-loading-swc
PS D:\web-development\new-project\explore>

Body:
The best way to solve this issue

I solved this issue by removing node_modules and reinstall packages. I think it's the best solution.

Just run

rm -rf node_modules      // Linux
rmdir /S node_modules   // Windows

And them install packages

npm install

Finally run

npm run dev


问:
How to take values from a column and assign them to other columns
Here's what I have:

```<code>DECLARE @keyString2 nvarchar(500)
SET @keyString2 =
    (SELECT TOP (1) Key_analysis
    FROM  testing.dbo.[nameWIthoutSpecialChars])
IF CHARINDEX('Limit of Insurance Relativity Factors' , @keyString2) > 0
   EXEC sp_rename 'testing.dbo.nameWIthoutSpecialChars.Key2',
                  'Limit of Insurance Relativity Factors',
                  'COLUMN';
</code>```

Basically what I'm doing with that code is renaming column names
with values that are from a different column. Though, if you see, there's a hardcoded string in CHARINDEX, I'd have to already know what's inside of that variable which makes it a real manual process. I could essentially just hardcode the EXEC and run it over and over without even needing the IF statement.

What I'm trying to accomplish is to rename columns based off of values inside of another.

To make it more clear I have a table like this:

```<code>+--------------------------------+---------+---------+
| Description                    | Column2 | Column3 |
+--------------------------------+---------+---------+
| string value 1, string value2  |         |         |
+--------------------------------+---------+---------+
| string value 1, string value2  |         |         |
+--------------------------------+---------+---------+
| string value 1, string value 2 |         |         |
+--------------------------------+---------+---------+
</code>```

The values in the "Description" column will be the same throughout the table. What I want to have happen is that those values replace the other columns like so

```<code>+--------------------------------+----------------+----------------+
| Description                    | string value 1 | string value 2 |
+--------------------------------+----------------+----------------+
| string value 1, string value2  |                |                |
+--------------------------------+----------------+----------------+
| string value 1, string value2  |                |                |
+--------------------------------+----------------+----------------+
| string value 1, string value 2 |                |                |
+--------------------------------+----------------+----------------+
</code>```

The only other caveat here is that there may be more or less string values than the 2 shown, I want to run this through multiple tables. Every table has 10 columns that are just like "Column1" and "Column2" in the example, meaning 10 potential columns that need to be renamed considering how many values are in the "Description" column

答:
Experimental table,I didn't use #temporary table or table variable.

```<code>create TABLE bbbb  (
   Description VARCHAR(30) NOT NULL
  ,column2     VARCHAR(30)
  ,column3     VARCHAR(30)
);
INSERT INTO bbbb(Description,column2,column3) VALUES
('string value 1,string value2',NULL,NULL),
('string value 1,string value2',NULL,NULL),
('string value 1,string value2',NULL,NULL);
</code>```

final query

```<code>declare @a varchar(100);
declare @b varchar(100);
set @a=(select distinct PARSENAME(REPLACE(Description,',','.'),1) from bbbb)
set @b=(select distinct PARSENAME(REPLACE(Description,',','.'),2) from bbbb)
EXEC sp_rename '[bbbb].[column2]', @a, 'COLUMN';
EXEC sp_rename '[bbbb].[column3]', @b, 'COLUMN';

select  * from bbbb
</code>```

Body:
Here's what I have:

DECLARE @keyString2 nvarchar(500)
SET @keyString2 =
    (SELECT TOP (1) Key_analysis
    FROM  testing.dbo.[nameWIthoutSpecialChars])
IF CHARINDEX('Limit of Insurance Relativity Factors' , @keyString2) > 0
   EXEC sp_rename 'testing.dbo.nameWIthoutSpecialChars.Key2',
                  'Limit of Insurance Relativity Factors',
                  'COLUMN';

Basically what I'm doing with that code is renaming column names
with values that are from a different column. Though, if you see, there's a hardcoded string in CHARINDEX, I'd have to already know what's inside of that variable which makes it a real manual process. I could essentially just hardcode the EXEC and run it over and over without even needing the IF statement.

What I'm trying to accomplish is to rename columns based off of values inside of another.

To make it more clear I have a table like this:

+--------------------------------+---------+---------+
| Description                    | Column2 | Column3 |
+--------------------------------+---------+---------+
| string value 1, string value2  |         |         |
+--------------------------------+---------+---------+
| string value 1, string value2  |         |         |
+--------------------------------+---------+---------+
| string value 1, string value 2 |         |         |
+--------------------------------+---------+---------+

The values in the "Description" column will be the same throughout the table. What I want to have happen is that those values replace the other columns like so

+--------------------------------+----------------+----------------+
| Description                    | string value 1 | string value 2 |
+--------------------------------+----------------+----------------+
| string value 1, string value2  |                |                |
+--------------------------------+----------------+----------------+
| string value 1, string value2  |                |                |
+--------------------------------+----------------+----------------+
| string value 1, string value 2 |                |                |
+--------------------------------+----------------+----------------+

The only other caveat here is that there may be more or less string values than the 2 shown, I want to run this through multiple tables. Every table has 10 columns that are just like "Column1" and "Column2" in the example, meaning 10 potential columns that need to be renamed considering how many values are in the "Description" column

Body:
Experimental table,I didn't use #temporary table or table variable.

create TABLE bbbb  (
   Description VARCHAR(30) NOT NULL
  ,column2     VARCHAR(30)
  ,column3     VARCHAR(30)
);
INSERT INTO bbbb(Description,column2,column3) VALUES
('string value 1,string value2',NULL,NULL),
('string value 1,string value2',NULL,NULL),
('string value 1,string value2',NULL,NULL);

final query

declare @a varchar(100);
declare @b varchar(100);
set @a=(select distinct PARSENAME(REPLACE(Description,',','.'),1) from bbbb)
set @b=(select distinct PARSENAME(REPLACE(Description,',','.'),2) from bbbb)
EXEC sp_rename '[bbbb].[column2]', @a, 'COLUMN';
EXEC sp_rename '[bbbb].[column3]', @b, 'COLUMN';

select  * from bbbb


问:
NHapi PipeParser throws exception in Azure Function
I have a .net core 3.1 Azure Function which is using the latest version of NHApi (3.0.4). The following lines of code throws an exception when running locally:

```<code>var pipeParser = new PipeParser();
var messageObject = pipeParser.Parse(messageString);
</code>```

The exception is the following:

The type initializer for 'NHapi.Base.PackageManager' threw an exception. NHapi.Base: The type initializer for 'NHapi.Base.PackageManager' threw an exception. NHapi.Base: Could not load file or assembly 'System.Configuration.ConfigurationManager, Version=5.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. The system cannot find the file specified.

Looking at my build folder in bin\Debug\netcoreapp3.1, i can see a System.Configuration.ConfigurationManager.dll. However i need to copy this file to bin\Debug\netcoreapp3.1\bin for the error to go away. It seems that this assembly doesn't get copied to the \bin subfolder (which contains all the other referenced assmblies) by default. Does someone know why this is the case? Short of adding some post build step to do this file copy, what's the solution ?

答:
It looks like you are missing the System.Configuration.ConfigurationManager reference, auburg provided a link to help you include it in your azure function.

How do you copy files into Azure Function bin folder?

Body:
I have a .net core 3.1 Azure Function which is using the latest version of NHApi (3.0.4). The following lines of code throws an exception when running locally:

var pipeParser = new PipeParser();
var messageObject = pipeParser.Parse(messageString);

The exception is the following:

The type initializer for 'NHapi.Base.PackageManager' threw an exception. NHapi.Base: The type initializer for 'NHapi.Base.PackageManager' threw an exception. NHapi.Base: Could not load file or assembly 'System.Configuration.ConfigurationManager, Version=5.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. The system cannot find the file specified.

Looking at my build folder in bin\Debug\netcoreapp3.1, i can see a System.Configuration.ConfigurationManager.dll. However i need to copy this file to bin\Debug\netcoreapp3.1\bin for the error to go away. It seems that this assembly doesn't get copied to the \bin subfolder (which contains all the other referenced assmblies) by default. Does someone know why this is the case? Short of adding some post build step to do this file copy, what's the solution ?


问:
Merging data on time column, but different "accuracy" of timedata
I have two dataframes with different data. The data was recorded at the same time but one was measured only with seconds and one was measured with milliseconds. This gave me the two data frames:

DF1

```<code>TIME                Col1             Col2
2021-09-27 14:23:08 This is data     This is data2
2021-09-27 14:23:08 This is data3    This is data4
2021-09-27 14:23:08 This is data5    This is data6
2021-09-27 14:23:08 This is data7    This is data8
... (ten rows of time data at 08 seconds)
2021-09-27 14:23:09 This is data     This is data
</code>```

DF 2

```<code>TIME                  Col1             Col2
2021-09-27 14:23:08.0 This is data     This is data2
2021-09-27 14:23:08.1 This is data3    This is data4
2021-09-27 14:23:08.2 This is data5    This is data6
2021-09-27 14:23:08.3 This is data7    This is data8
... (ten rows of time data at 08.x seconds)
2021-09-27 14:23:09.0 This is data     This is data
</code>```

I want to compare this data by using the merge_asof method but as you can see there is a problem regarding the time data. One time column has a greater accuracy than the other resulting in the time data being unmergeable. Any ideas on how I can proceed? I have tried using the merge_asof in hope that it would merge time by index and seconds but this resulted in duplication of rows.

DESIRED OUTPUT

```<code>TIME                Col1             Col2          Col1.1           Col2.1
2021-09-27 14:23:08 This is data     This is data2 This is data     This is data2
2021-09-27 14:23:08 This is data3    This is data4 This is data3    This is data4
2021-09-27 14:23:08 This is data5    This is data6 This is data5    This is data6
2021-09-27 14:23:08 This is data7    This is data8 This is data7    This is data8
... (ten rows of time data at 08 seconds)
2021-09-27 14:23:09 This is data     This is data  This is data     This is data
</code>```

My ideas so far is to perhaps add milliseconds to DF1. With other words, adding 0.1 to row1 and 0.2 to row 2 etc and then rounding DF2. But this would both be time consuming and inefficient.

```<code>from this import d
from turtle import xcor
from xml.sax.handler import DTDHandler
import pandas as pd
import numpy as np
import tkinter as tk
import os
import math
import glob
from os import listdir
from os.path import isfile, join

xcordi=21.551802
eq1 = -0.2094480490623*xcordi + 69.7792952182
eq2 = (-0.2094480490623*xcordi + 69.7792952182)+0.01

print(eq1)

pd.set_option("display.max_rows", None, "display.max_columns", None)

#BLOCK GEOFENCE

max_x_value = 21.555706
min_x_value = 21.530232

datapath = r"C:\Users\a384663\Desktop\TASKS\LENNART\Piteå\Friction\Data_pitea.csv"
outputfile = r"C:\Users\a384663\Desktop\TASKS\LENNART\Piteå\Friction\output_pitea.csv"

df1 = pd.read_csv(datapath)
#print(df1.loc[[]])
df1.drop([0,1,2,3,4,5,6,7,8,9,10,11,12])
df1['row'] = df1.index
print(len(df1))

df1['divided'] = df1['row']/21

df1= df1[df1['divided'].astype(int) < df1['divided']]
print(len(df1))

df1filt = df1

print(len(df1))
print(len(df1filt))

print(len(df1))

df1filt = df1filt[df1filt['roadeye_friction'].notna()]

print(len(df1filt))

print(df1filt.dtypes)

i=3
count = 0

df1filt = df1filt[(df1filt['Longitude'] >= 21.538851)]
df1filt = df1filt[(df1filt['Longitude'] <= 21.589464)]

df1filt = df1filt[(df1filt['Latitude'] >= 65.251439)]
df1filt = df1filt[(df1filt['Latitude'] <= 65.271148)]

df1filt['TimeUTC'] = df1filt['TimeUTC'].astype('datetime64[ns]')

df1filt['TimeUTC'] = df1filt['TimeUTC'].dt.strftime("%Y-%m-%d %H:%M:%S.%f")

path = r'C:\Users\a384663\Desktop\piteå\smaller' # use your path

onlyfiles = [f for f in listdir(path) if isfile(join(path, f))]
print(onlyfiles)

filen=1
os.chdir(r'C:\Users\a384663\Desktop\piteå\smaller')

list_of_dataframes = []
for filename in onlyfiles:
    print("READING FILE",filen)
    if filen ==1:
        #try:
        #merged_df=pd.read_csv(filename, encoding='iso-8859-1',skiprows=43, usecols=[1, 19, 30, 31, 33, 83, 155, 157])
        merged_df=pd.read_csv(filename, encoding='iso-8859-1',skiprows=43, usecols=[1, 31, 33, 83, 99, 155, 157])

        #except:
        #    pass
    if filen > 1:
        try:
            #merged_df.append(pd.read_csv(filename, encoding='iso-8859-1',skiprows=47, usecols=[1, 19, 30, 31, 33, 83, 155, 157]))
            merged_df.append(pd.read_csv(filename, encoding='iso-8859-1',skiprows=47, usecols=[1, 31, 33, 83, 99, 155, 157]))
        except:
            print("EXCEPTION", filename)
    filen+=1

print(merged_df.columns)

#all_files = glob.glob(path + "/*.csv")

print(merged_df.columns)

merged_df['99ea25ba-4460-4b0c-a99b-a8a180372037: Time_abs'] = pd.to_datetime(merged_df['99ea25ba-4460-4b0c-a99b-a8a180372037: Time_abs'], errors='coerce')
merged_df = merged_df.dropna(subset=['99ea25ba-4460-4b0c-a99b-a8a180372037: Time_abs'])

df1filt['TimeUTC'] = pd.to_datetime(df1filt['TimeUTC'], errors='coerce')
df1filt = df1filt.dropna(subset=['TimeUTC'])

print(df1filt['TimeUTC'])

merged_df.drop([44, 45, 46, 47])

df1filt.rename(columns={"TimeUTC": "TIME"}, inplace=True)
merged_df.rename(columns={"99ea25ba-4460-4b0c-a99b-a8a180372037: Time_abs": "TIME"}, inplace=True)

print(merged_df['TIME'])

#merged_df['TIME'] = merged_df['TIME'].astype('datetime64[ns]')

(df1filt.assign(group=df1filt.groupby('TIME').cumcount()).merge(merged_df.assign(TIME=merged_df['TIME'].dt.round('s'),group=lambda d: d.groupby('TIME').cumcount()),on=['TIME', 'group'],suffixes=('', '.1')).drop('group', axis=1).to_string()
)

df1filt.to_csv(outputfile, index = False)

</code>```

IMAGES FOR ANSWER

df1 and df2

output

Thank you in advance!

答:
IIUC, it looks like you want to merge in order of the common times, not using merge_asof. For this you could use a de-duplication group:

```<code># if not datetime:
# df1['TIME'] = pd.to_datetime(df1['TIME'])
# df2['TIME'] = pd.to_datetime(df2['TIME'])

(df1.assign(group=df1.groupby('TIME').cumcount())
    .merge(df2.assign(TIME=df2['TIME'].dt.round('s'),
                      group=lambda d: d.groupby('TIME').cumcount()
                       ),
           on=['TIME', 'group'],
           suffixes=('', '.1')
          )
    .drop('group', axis=1).to_string()
)
</code>```

output:

```<code>                 TIME           Col1           Col2         Col1.1         Col2.1
0 2021-09-27 14:23:08   This is data  This is data2   This is data  This is data2
1 2021-09-27 14:23:08  This is data3  This is data4  This is data3  This is data4
2 2021-09-27 14:23:08  This is data5  This is data6  This is data5  This is data6
3 2021-09-27 14:23:08  This is data7  This is data8  This is data7  This is data8
4 2021-09-27 14:23:09   This is data   This is data   This is data   This is data
</code>```

input:

```<code>df1 = pd.DataFrame({'TIME': ['2021-09-27 14:23:08', '2021-09-27 14:23:08', '2021-09-27 14:23:08', '2021-09-27 14:23:08', '2021-09-27 14:23:09'], 'Col1': ['This is data', 'This is data3', 'This is data5', 'This is data7', 'This is data'], 'Col2': ['This is data2', 'This is data4', 'This is data6', 'This is data8', 'This is data']})
df2 = pd.DataFrame({'TIME': ['2021-09-27 14:23:08.0', '2021-09-27 14:23:08.1', '2021-09-27 14:23:08.2', '2021-09-27 14:23:08.3', '2021-09-27 14:23:09.0'], 'Col1': ['This is data', 'This is data3', 'This is data5', 'This is data7', 'This is data'], 'Col2': ['This is data2', 'This is data4', 'This is data6', 'This is data8', 'This is data']})
df1['TIME'] = pd.to_datetime(df1['TIME'])
df2['TIME'] = pd.to_datetime(df2['TIME'])
</code>```

Body:
I have two dataframes with different data. The data was recorded at the same time but one was measured only with seconds and one was measured with milliseconds. This gave me the two data frames:

DF1

TIME                Col1             Col2
2021-09-27 14:23:08 This is data     This is data2
2021-09-27 14:23:08 This is data3    This is data4
2021-09-27 14:23:08 This is data5    This is data6
2021-09-27 14:23:08 This is data7    This is data8
... (ten rows of time data at 08 seconds)
2021-09-27 14:23:09 This is data     This is data

DF 2

TIME                  Col1             Col2
2021-09-27 14:23:08.0 This is data     This is data2
2021-09-27 14:23:08.1 This is data3    This is data4
2021-09-27 14:23:08.2 This is data5    This is data6
2021-09-27 14:23:08.3 This is data7    This is data8
... (ten rows of time data at 08.x seconds)
2021-09-27 14:23:09.0 This is data     This is data

I want to compare this data by using the merge_asof method but as you can see there is a problem regarding the time data. One time column has a greater accuracy than the other resulting in the time data being unmergeable. Any ideas on how I can proceed? I have tried using the merge_asof in hope that it would merge time by index and seconds but this resulted in duplication of rows.

DESIRED OUTPUT

TIME                Col1             Col2          Col1.1           Col2.1
2021-09-27 14:23:08 This is data     This is data2 This is data     This is data2
2021-09-27 14:23:08 This is data3    This is data4 This is data3    This is data4
2021-09-27 14:23:08 This is data5    This is data6 This is data5    This is data6
2021-09-27 14:23:08 This is data7    This is data8 This is data7    This is data8
... (ten rows of time data at 08 seconds)
2021-09-27 14:23:09 This is data     This is data  This is data     This is data

My ideas so far is to perhaps add milliseconds to DF1. With other words, adding 0.1 to row1 and 0.2 to row 2 etc and then rounding DF2. But this would both be time consuming and inefficient.

from this import d
from turtle import xcor
from xml.sax.handler import DTDHandler
import pandas as pd
import numpy as np
import tkinter as tk
import os
import math
import glob
from os import listdir
from os.path import isfile, join

xcordi=21.551802
eq1 = -0.2094480490623*xcordi + 69.7792952182
eq2 = (-0.2094480490623*xcordi + 69.7792952182)+0.01

print(eq1)

pd.set_option("display.max_rows", None, "display.max_columns", None)

#BLOCK GEOFENCE

max_x_value = 21.555706
min_x_value = 21.530232

datapath = r"C:\Users\a384663\Desktop\TASKS\LENNART\Piteå\Friction\Data_pitea.csv"
outputfile = r"C:\Users\a384663\Desktop\TASKS\LENNART\Piteå\Friction\output_pitea.csv"

df1 = pd.read_csv(datapath)
#print(df1.loc[[]])
df1.drop([0,1,2,3,4,5,6,7,8,9,10,11,12])
df1['row'] = df1.index
print(len(df1))

df1['divided'] = df1['row']/21

df1= df1[df1['divided'].astype(int) < df1['divided']]
print(len(df1))

df1filt = df1

print(len(df1))
print(len(df1filt))

print(len(df1))

df1filt = df1filt[df1filt['roadeye_friction'].notna()]

print(len(df1filt))

print(df1filt.dtypes)

i=3
count = 0

df1filt = df1filt[(df1filt['Longitude'] >= 21.538851)]
df1filt = df1filt[(df1filt['Longitude'] <= 21.589464)]

df1filt = df1filt[(df1filt['Latitude'] >= 65.251439)]
df1filt = df1filt[(df1filt['Latitude'] <= 65.271148)]

df1filt['TimeUTC'] = df1filt['TimeUTC'].astype('datetime64[ns]')

df1filt['TimeUTC'] = df1filt['TimeUTC'].dt.strftime("%Y-%m-%d %H:%M:%S.%f")

path = r'C:\Users\a384663\Desktop\piteå\smaller' # use your path

onlyfiles = [f for f in listdir(path) if isfile(join(path, f))]
print(onlyfiles)

filen=1
os.chdir(r'C:\Users\a384663\Desktop\piteå\smaller')

list_of_dataframes = []
for filename in onlyfiles:
    print("READING FILE",filen)
    if filen ==1:
        #try:
        #merged_df=pd.read_csv(filename, encoding='iso-8859-1',skiprows=43, usecols=[1, 19, 30, 31, 33, 83, 155, 157])
        merged_df=pd.read_csv(filename, encoding='iso-8859-1',skiprows=43, usecols=[1, 31, 33, 83, 99, 155, 157])

        #except:
        #    pass
    if filen > 1:
        try:
            #merged_df.append(pd.read_csv(filename, encoding='iso-8859-1',skiprows=47, usecols=[1, 19, 30, 31, 33, 83, 155, 157]))
            merged_df.append(pd.read_csv(filename, encoding='iso-8859-1',skiprows=47, usecols=[1, 31, 33, 83, 99, 155, 157]))
        except:
            print("EXCEPTION", filename)
    filen+=1

print(merged_df.columns)

#all_files = glob.glob(path + "/*.csv")

print(merged_df.columns)

merged_df['99ea25ba-4460-4b0c-a99b-a8a180372037: Time_abs'] = pd.to_datetime(merged_df['99ea25ba-4460-4b0c-a99b-a8a180372037: Time_abs'], errors='coerce')
merged_df = merged_df.dropna(subset=['99ea25ba-4460-4b0c-a99b-a8a180372037: Time_abs'])

df1filt['TimeUTC'] = pd.to_datetime(df1filt['TimeUTC'], errors='coerce')
df1filt = df1filt.dropna(subset=['TimeUTC'])

print(df1filt['TimeUTC'])

merged_df.drop([44, 45, 46, 47])

df1filt.rename(columns={"TimeUTC": "TIME"}, inplace=True)
merged_df.rename(columns={"99ea25ba-4460-4b0c-a99b-a8a180372037: Time_abs": "TIME"}, inplace=True)

print(merged_df['TIME'])

#merged_df['TIME'] = merged_df['TIME'].astype('datetime64[ns]')

(df1filt.assign(group=df1filt.groupby('TIME').cumcount()).merge(merged_df.assign(TIME=merged_df['TIME'].dt.round('s'),group=lambda d: d.groupby('TIME').cumcount()),on=['TIME', 'group'],suffixes=('', '.1')).drop('group', axis=1).to_string()
)

df1filt.to_csv(outputfile, index = False)

IMAGES FOR ANSWER

df1 and df2

output

Thank you in advance!

Body:
IIUC, it looks like you want to merge in order of the common times, not using merge_asof. For this you could use a de-duplication group:

# if not datetime:
# df1['TIME'] = pd.to_datetime(df1['TIME'])
# df2['TIME'] = pd.to_datetime(df2['TIME'])

(df1.assign(group=df1.groupby('TIME').cumcount())
    .merge(df2.assign(TIME=df2['TIME'].dt.round('s'),
                      group=lambda d: d.groupby('TIME').cumcount()
                       ),
           on=['TIME', 'group'],
           suffixes=('', '.1')
          )
    .drop('group', axis=1).to_string()
)

output:

                 TIME           Col1           Col2         Col1.1         Col2.1
0 2021-09-27 14:23:08   This is data  This is data2   This is data  This is data2
1 2021-09-27 14:23:08  This is data3  This is data4  This is data3  This is data4
2 2021-09-27 14:23:08  This is data5  This is data6  This is data5  This is data6
3 2021-09-27 14:23:08  This is data7  This is data8  This is data7  This is data8
4 2021-09-27 14:23:09   This is data   This is data   This is data   This is data

input:

df1 = pd.DataFrame({'TIME': ['2021-09-27 14:23:08', '2021-09-27 14:23:08', '2021-09-27 14:23:08', '2021-09-27 14:23:08', '2021-09-27 14:23:09'], 'Col1': ['This is data', 'This is data3', 'This is data5', 'This is data7', 'This is data'], 'Col2': ['This is data2', 'This is data4', 'This is data6', 'This is data8', 'This is data']})
df2 = pd.DataFrame({'TIME': ['2021-09-27 14:23:08.0', '2021-09-27 14:23:08.1', '2021-09-27 14:23:08.2', '2021-09-27 14:23:08.3', '2021-09-27 14:23:09.0'], 'Col1': ['This is data', 'This is data3', 'This is data5', 'This is data7', 'This is data'], 'Col2': ['This is data2', 'This is data4', 'This is data6', 'This is data8', 'This is data']})
df1['TIME'] = pd.to_datetime(df1['TIME'])
df2['TIME'] = pd.to_datetime(df2['TIME'])