问:
Building LLVM with CMake error: NMake Makefiles does not support toolset specification
I am trying to build LLVM on Windows 10 using this tutorial from the LLVM docs.

However, CMake gives the error NMake Makefiles does not support toolset specification, but toolset host=x64 was specified, which I have sadly been unable to surmount.

Error:

In the VS2022 developer prompt, I get to configure LLVM using CMake (step #12), which results in the following error:

```<code>C:\Users\Name\Documents\name\code\tools\llvm> cmake -S .\llvm -B build -DLLVM_ENABLE_PROJECTS=clang -DLLVM_TARGETS_TO_BUILD=X86

CMake Error at CMakeLists.txt:44 (project):
  Generator

    NMake Makefiles

  does not support toolset specification, but toolset

    host=x64

  was specified.

CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage
CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage
CMake Error: CMAKE_ASM_COMPILER not set, after EnableLanguage
-- Configuring incomplete, errors occurred!

See also "C:/Users/Name/Documents/name/code/tools/llvm/build/CMakeFiles/CMakeOutput.log".
</code>```

And CMakeOutput.log simply reads:

```<code>The system is: Windows - 10.0.19042 - AMD64
</code>```

Attempts at remediation:

I referred to this answer but was unclear as to what to do.
Line 44 simply consists of:

```<code>project(LLVM
  VERSION ${LLVM_VERSION_MAJOR}.${LLVM_VERSION_MINOR}.${LLVM_VERSION_PATCH}
  LANGUAGES C CXX ASM)
</code>```

Again, thank you very much in advance for any help on this issue!

Update #1

As per tsyvarev's suggestion, I tried: cmake -G "Visual Studio 17 2022" -A x64 -S .\llvm -B build -DLLVM_ENABLE_PROJECTS=clang -DLLVM_TARGETS_TO_BUILD=X86 -Thost=x64

This results in:

```<code>-- Selecting Windows SDK version 10.0.22000.0 to target Windows 10.0.19042.
-- The C compiler identification is MSVC 19.30.30705.0
-- The CXX compiler identification is MSVC 19.30.30705.0
-- The ASM compiler identification is MSVC
-- Found assembler: C:/Program Files/Microsoft Visual Studio/2022/Community/VC/Tools/MSVC/14.30.30705/bin/Hostx64/x64/cl.exe
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: C:/Program Files/Microsoft Visual Studio/2022/Community/VC/Tools/MSVC/14.30.30705/bin/Hostx64/x64/cl.exe - skipped
-- Detecting C compile features
-- Detecting C compile features - done
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: C:/Program Files/Microsoft Visual Studio/2022/Community/VC/Tools/MSVC/14.30.30705/bin/Hostx64/x64/cl.exe - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- clang project is enabled
-- clang-tools-extra project is disabled
-- compiler-rt project is disabled
-- cross-project-tests project is disabled
-- libc project is disabled
-- libclc project is disabled
-- libcxx project is disabled
-- libcxxabi project is disabled
-- libunwind project is disabled
-- lld project is disabled
-- lldb project is disabled
-- mlir project is disabled
-- openmp project is disabled
-- polly project is disabled
-- pstl project is disabled
-- flang project is disabled
-- Looking for dlfcn.h
-- Looking for dlfcn.h - not found
-- Looking for errno.h
-- Looking for errno.h - found
-- Looking for fcntl.h
-- Looking for fcntl.h - found
-- Looking for link.h
-- Looking for link.h - not found
-- Looking for malloc/malloc.h
-- Looking for malloc/malloc.h - not found
-- Looking for signal.h
-- Looking for signal.h - found
-- Looking for sys/ioctl.h
-- Looking for sys/ioctl.h - not found
-- Looking for sys/mman.h
-- Looking for sys/mman.h - not found
-- Looking for sys/param.h
-- Looking for sys/param.h - not found
-- Looking for sys/resource.h
-- Looking for sys/resource.h - not found
-- Looking for sys/stat.h
-- Looking for sys/stat.h - found
-- Looking for sys/time.h
-- Looking for sys/time.h - not found
-- Looking for sys/types.h
-- Looking for sys/types.h - found
-- Looking for sysexits.h
-- Looking for sysexits.h - not found
-- Looking for termios.h
-- Looking for termios.h - not found
-- Looking for unistd.h
-- Looking for unistd.h - not found
-- Looking for valgrind/valgrind.h
-- Looking for valgrind/valgrind.h - not found
-- Looking for fenv.h
-- Looking for fenv.h - found
-- Looking for FE_ALL_EXCEPT
-- Looking for FE_ALL_EXCEPT - found
-- Looking for FE_INEXACT
-- Looking for FE_INEXACT - found
-- Looking for mach/mach.h
-- Looking for mach/mach.h - not found
-- Looking for histedit.h
-- Looking for histedit.h - not found
-- Looking for CrashReporterClient.h
-- Looking for CrashReporterClient.h - not found
-- Looking for pfm_initialize in pfm
-- Looking for pfm_initialize in pfm - not found
-- Could NOT find ZLIB (missing: ZLIB_LIBRARY) (found version "1.2.11")
-- Could NOT find LibXml2 (missing: LIBXML2_LIBRARY) (found version "2.9.9")
-- Looking for xar_open in xar
-- Looking for xar_open in xar - not found
-- Looking for arc4random
-- Looking for arc4random - not found
-- Looking for backtrace
-- Looking for backtrace - not found
-- Could NOT find Backtrace (missing: Backtrace_LIBRARY Backtrace_INCLUDE_DIR)
-- Performing Test C_SUPPORTS_WERROR_UNGUARDED_AVAILABILITY_NEW
-- Performing Test C_SUPPORTS_WERROR_UNGUARDED_AVAILABILITY_NEW - Failed
-- Looking for __register_frame
-- Looking for __register_frame - not found
-- Looking for __deregister_frame
-- Looking for __deregister_frame - not found
-- Looking for __unw_add_dynamic_fde
-- Looking for __unw_add_dynamic_fde - not found
-- Looking for _Unwind_Backtrace
-- Looking for _Unwind_Backtrace - not found
-- Looking for getpagesize
-- Looking for getpagesize - not found
-- Looking for sysconf
-- Looking for sysconf - not found
-- Looking for getrusage
-- Looking for getrusage - not found
-- Looking for setrlimit
-- Looking for setrlimit - not found
-- Looking for isatty
-- Looking for isatty - not found
-- Looking for futimens
-- Looking for futimens - not found
-- Looking for futimes
-- Looking for futimes - not found
-- Looking for posix_fallocate
-- Looking for posix_fallocate - not found
-- Looking for sigaltstack
-- Looking for sigaltstack - not found
-- Looking for lseek64
-- Looking for lseek64 - not found
-- Looking for mallctl
-- Looking for mallctl - not found
-- Looking for mallinfo
-- Looking for mallinfo - not found
-- Looking for mallinfo2
-- Looking for mallinfo2 - not found
-- Looking for malloc_zone_statistics
-- Looking for malloc_zone_statistics - not found
-- Looking for getrlimit
-- Looking for getrlimit - not found
-- Looking for posix_spawn
-- Looking for posix_spawn - not found
-- Looking for pread
-- Looking for pread - not found
-- Looking for sbrk
-- Looking for sbrk - not found
-- Looking for strerror
-- Looking for strerror - found
-- Looking for strerror_r
-- Looking for strerror_r - not found
-- Looking for strerror_s
-- Looking for strerror_s - found
-- Looking for setenv
-- Looking for setenv - not found
-- Looking for _chsize_s
-- Looking for _chsize_s - found
-- Looking for _alloca
-- Looking for _alloca - not found
-- Looking for __alloca
-- Looking for __alloca - not found
-- Looking for __chkstk
-- Looking for __chkstk - found
-- Looking for __chkstk_ms
-- Looking for __chkstk_ms - not found
-- Looking for ___chkstk
-- Looking for ___chkstk - not found
-- Looking for ___chkstk_ms
-- Looking for ___chkstk_ms - not found
-- Looking for __ashldi3
-- Looking for __ashldi3 - not found
-- Looking for __ashrdi3
-- Looking for __ashrdi3 - not found
-- Looking for __divdi3
-- Looking for __divdi3 - not found
-- Looking for __fixdfdi
-- Looking for __fixdfdi - not found
-- Looking for __fixsfdi
-- Looking for __fixsfdi - not found
-- Looking for __floatdidf
-- Looking for __floatdidf - not found
-- Looking for __lshrdi3
-- Looking for __lshrdi3 - not found
-- Looking for __moddi3
-- Looking for __moddi3 - not found
-- Looking for __udivdi3
-- Looking for __udivdi3 - not found
-- Looking for __umoddi3
-- Looking for __umoddi3 - not found
-- Looking for __main
-- Looking for __main - not found
-- Looking for __cmpdi2
-- Looking for __cmpdi2 - not found
-- Performing Test HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC
-- Performing Test HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC - Failed
-- Performing Test HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC
-- Performing Test HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC - Failed
-- Looking for __GLIBC__
-- Looking for __GLIBC__ - not found
-- Looking for proc_pid_rusage
-- Looking for proc_pid_rusage - not found
-- Performing Test HAVE_STD_IS_TRIVIALLY_COPYABLE
-- Performing Test HAVE_STD_IS_TRIVIALLY_COPYABLE - Success
-- Performing Test LLVM_HAS_ATOMICS
-- Performing Test LLVM_HAS_ATOMICS - Success
-- Performing Test SUPPORTS_VARIADIC_MACROS_FLAG
-- Performing Test SUPPORTS_VARIADIC_MACROS_FLAG - Failed
-- Performing Test SUPPORTS_GNU_ZERO_VARIADIC_MACRO_ARGUMENTS_FLAG
-- Performing Test SUPPORTS_GNU_ZERO_VARIADIC_MACRO_ARGUMENTS_FLAG - Failed
-- Native target architecture is X86
-- Threads enabled.
-- Doxygen disabled.
-- Go bindings disabled.
-- Could NOT find OCaml (missing: OCAMLFIND OCAML_VERSION OCAML_STDLIB_PATH)
-- OCaml bindings disabled.
-- Could NOT find Python module pygments
-- Could NOT find Python module pygments.lexers.c_cpp
-- Could NOT find Python module yaml
-- LLVM host triple: x86_64-pc-windows-msvc
-- LLVM default target triple: x86_64-pc-windows-msvc
-- Using Debug VC++ CRT: MDd
-- Using Release VC++ CRT: MD
-- Using MinSizeRel VC++ CRT: MD
-- Using RelWithDebInfo VC++ CRT: MD
-- Looking for os_signpost_interval_begin
-- Looking for os_signpost_interval_begin - not found
-- Found Python3: C:/Users/Name/AppData/Local/Programs/Python/Python39/python.exe (found suitable version "3.9.5", minimum required is "3.6") found components: Interpreter
-- Performing Test HAS_WERROR_GLOBAL_CTORS
-- Performing Test HAS_WERROR_GLOBAL_CTORS - Failed
CMake Error at CMakeLists.txt:1008 (add_subdirectory):
  add_subdirectory given source "utils/TableGen" which is not an existing
  directory.

CMake Error at cmake/modules/TableGen.cmake:9 (message):
  LLVM_TABLEGEN_EXE not set
Call Stack (most recent call first):
  include/llvm/IR/CMakeLists.txt:2 (tablegen)

-- Configuring incomplete, errors occurred!
See also "C:/Users/Name/Documents/name/code/tools/llvm/build/CMakeFiles/CMakeOutput.log".
See also "C:/Users/Name/Documents/name/code/tools/llvm/build/CMakeFiles/CMakeError.log".
</code>```

答:
I encountered similar issues, and found a comment on the MSDN blog site:

It’s better to mention that the toolset name working with cmake is “ClangCL”. I’ve tried clang-cl, clang, llvm. None of them works untils I’ve found this page https://tracker.dev.opencascade.org/view.php?id=31060 mentioning the “ClangCL”

And the follow-up comment to it from Tim Hutton [MSFT]:

And for 64-bit builds, set the CMake toolset to ‘ClangCL,host=x64’ https://cmake.org/cmake/help/latest/variable/CMAKE_GENERATOR_TOOLSET.html

Sure enough, using -T ClangCL,host=x64 in the cmake command line worked for me.

Body:
I am trying to build LLVM on Windows 10 using this tutorial from the LLVM docs.

However, CMake gives the error NMake Makefiles does not support toolset specification, but toolset host=x64 was specified, which I have sadly been unable to surmount.

Error:

In the VS2022 developer prompt, I get to configure LLVM using CMake (step #12), which results in the following error:

C:\Users\Name\Documents\name\code\tools\llvm> cmake -S .\llvm -B build -DLLVM_ENABLE_PROJECTS=clang -DLLVM_TARGETS_TO_BUILD=X86

CMake Error at CMakeLists.txt:44 (project):
  Generator

    NMake Makefiles

  does not support toolset specification, but toolset

    host=x64

  was specified.

CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage
CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage
CMake Error: CMAKE_ASM_COMPILER not set, after EnableLanguage
-- Configuring incomplete, errors occurred!

See also "C:/Users/Name/Documents/name/code/tools/llvm/build/CMakeFiles/CMakeOutput.log".

And CMakeOutput.log simply reads:

The system is: Windows - 10.0.19042 - AMD64

Attempts at remediation:

I referred to this answer but was unclear as to what to do.
Line 44 simply consists of:

project(LLVM
  VERSION ${LLVM_VERSION_MAJOR}.${LLVM_VERSION_MINOR}.${LLVM_VERSION_PATCH}
  LANGUAGES C CXX ASM)

Again, thank you very much in advance for any help on this issue!

Update #1

As per tsyvarev's suggestion, I tried: cmake -G "Visual Studio 17 2022" -A x64 -S .\llvm -B build -DLLVM_ENABLE_PROJECTS=clang -DLLVM_TARGETS_TO_BUILD=X86 -Thost=x64

This results in:

-- Selecting Windows SDK version 10.0.22000.0 to target Windows 10.0.19042.
-- The C compiler identification is MSVC 19.30.30705.0
-- The CXX compiler identification is MSVC 19.30.30705.0
-- The ASM compiler identification is MSVC
-- Found assembler: C:/Program Files/Microsoft Visual Studio/2022/Community/VC/Tools/MSVC/14.30.30705/bin/Hostx64/x64/cl.exe
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: C:/Program Files/Microsoft Visual Studio/2022/Community/VC/Tools/MSVC/14.30.30705/bin/Hostx64/x64/cl.exe - skipped
-- Detecting C compile features
-- Detecting C compile features - done
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: C:/Program Files/Microsoft Visual Studio/2022/Community/VC/Tools/MSVC/14.30.30705/bin/Hostx64/x64/cl.exe - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- clang project is enabled
-- clang-tools-extra project is disabled
-- compiler-rt project is disabled
-- cross-project-tests project is disabled
-- libc project is disabled
-- libclc project is disabled
-- libcxx project is disabled
-- libcxxabi project is disabled
-- libunwind project is disabled
-- lld project is disabled
-- lldb project is disabled
-- mlir project is disabled
-- openmp project is disabled
-- polly project is disabled
-- pstl project is disabled
-- flang project is disabled
-- Looking for dlfcn.h
-- Looking for dlfcn.h - not found
-- Looking for errno.h
-- Looking for errno.h - found
-- Looking for fcntl.h
-- Looking for fcntl.h - found
-- Looking for link.h
-- Looking for link.h - not found
-- Looking for malloc/malloc.h
-- Looking for malloc/malloc.h - not found
-- Looking for signal.h
-- Looking for signal.h - found
-- Looking for sys/ioctl.h
-- Looking for sys/ioctl.h - not found
-- Looking for sys/mman.h
-- Looking for sys/mman.h - not found
-- Looking for sys/param.h
-- Looking for sys/param.h - not found
-- Looking for sys/resource.h
-- Looking for sys/resource.h - not found
-- Looking for sys/stat.h
-- Looking for sys/stat.h - found
-- Looking for sys/time.h
-- Looking for sys/time.h - not found
-- Looking for sys/types.h
-- Looking for sys/types.h - found
-- Looking for sysexits.h
-- Looking for sysexits.h - not found
-- Looking for termios.h
-- Looking for termios.h - not found
-- Looking for unistd.h
-- Looking for unistd.h - not found
-- Looking for valgrind/valgrind.h
-- Looking for valgrind/valgrind.h - not found
-- Looking for fenv.h
-- Looking for fenv.h - found
-- Looking for FE_ALL_EXCEPT
-- Looking for FE_ALL_EXCEPT - found
-- Looking for FE_INEXACT
-- Looking for FE_INEXACT - found
-- Looking for mach/mach.h
-- Looking for mach/mach.h - not found
-- Looking for histedit.h
-- Looking for histedit.h - not found
-- Looking for CrashReporterClient.h
-- Looking for CrashReporterClient.h - not found
-- Looking for pfm_initialize in pfm
-- Looking for pfm_initialize in pfm - not found
-- Could NOT find ZLIB (missing: ZLIB_LIBRARY) (found version "1.2.11")
-- Could NOT find LibXml2 (missing: LIBXML2_LIBRARY) (found version "2.9.9")
-- Looking for xar_open in xar
-- Looking for xar_open in xar - not found
-- Looking for arc4random
-- Looking for arc4random - not found
-- Looking for backtrace
-- Looking for backtrace - not found
-- Could NOT find Backtrace (missing: Backtrace_LIBRARY Backtrace_INCLUDE_DIR)
-- Performing Test C_SUPPORTS_WERROR_UNGUARDED_AVAILABILITY_NEW
-- Performing Test C_SUPPORTS_WERROR_UNGUARDED_AVAILABILITY_NEW - Failed
-- Looking for __register_frame
-- Looking for __register_frame - not found
-- Looking for __deregister_frame
-- Looking for __deregister_frame - not found
-- Looking for __unw_add_dynamic_fde
-- Looking for __unw_add_dynamic_fde - not found
-- Looking for _Unwind_Backtrace
-- Looking for _Unwind_Backtrace - not found
-- Looking for getpagesize
-- Looking for getpagesize - not found
-- Looking for sysconf
-- Looking for sysconf - not found
-- Looking for getrusage
-- Looking for getrusage - not found
-- Looking for setrlimit
-- Looking for setrlimit - not found
-- Looking for isatty
-- Looking for isatty - not found
-- Looking for futimens
-- Looking for futimens - not found
-- Looking for futimes
-- Looking for futimes - not found
-- Looking for posix_fallocate
-- Looking for posix_fallocate - not found
-- Looking for sigaltstack
-- Looking for sigaltstack - not found
-- Looking for lseek64
-- Looking for lseek64 - not found
-- Looking for mallctl
-- Looking for mallctl - not found
-- Looking for mallinfo
-- Looking for mallinfo - not found
-- Looking for mallinfo2
-- Looking for mallinfo2 - not found
-- Looking for malloc_zone_statistics
-- Looking for malloc_zone_statistics - not found
-- Looking for getrlimit
-- Looking for getrlimit - not found
-- Looking for posix_spawn
-- Looking for posix_spawn - not found
-- Looking for pread
-- Looking for pread - not found
-- Looking for sbrk
-- Looking for sbrk - not found
-- Looking for strerror
-- Looking for strerror - found
-- Looking for strerror_r
-- Looking for strerror_r - not found
-- Looking for strerror_s
-- Looking for strerror_s - found
-- Looking for setenv
-- Looking for setenv - not found
-- Looking for _chsize_s
-- Looking for _chsize_s - found
-- Looking for _alloca
-- Looking for _alloca - not found
-- Looking for __alloca
-- Looking for __alloca - not found
-- Looking for __chkstk
-- Looking for __chkstk - found
-- Looking for __chkstk_ms
-- Looking for __chkstk_ms - not found
-- Looking for ___chkstk
-- Looking for ___chkstk - not found
-- Looking for ___chkstk_ms
-- Looking for ___chkstk_ms - not found
-- Looking for __ashldi3
-- Looking for __ashldi3 - not found
-- Looking for __ashrdi3
-- Looking for __ashrdi3 - not found
-- Looking for __divdi3
-- Looking for __divdi3 - not found
-- Looking for __fixdfdi
-- Looking for __fixdfdi - not found
-- Looking for __fixsfdi
-- Looking for __fixsfdi - not found
-- Looking for __floatdidf
-- Looking for __floatdidf - not found
-- Looking for __lshrdi3
-- Looking for __lshrdi3 - not found
-- Looking for __moddi3
-- Looking for __moddi3 - not found
-- Looking for __udivdi3
-- Looking for __udivdi3 - not found
-- Looking for __umoddi3
-- Looking for __umoddi3 - not found
-- Looking for __main
-- Looking for __main - not found
-- Looking for __cmpdi2
-- Looking for __cmpdi2 - not found
-- Performing Test HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC
-- Performing Test HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC - Failed
-- Performing Test HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC
-- Performing Test HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC - Failed
-- Looking for __GLIBC__
-- Looking for __GLIBC__ - not found
-- Looking for proc_pid_rusage
-- Looking for proc_pid_rusage - not found
-- Performing Test HAVE_STD_IS_TRIVIALLY_COPYABLE
-- Performing Test HAVE_STD_IS_TRIVIALLY_COPYABLE - Success
-- Performing Test LLVM_HAS_ATOMICS
-- Performing Test LLVM_HAS_ATOMICS - Success
-- Performing Test SUPPORTS_VARIADIC_MACROS_FLAG
-- Performing Test SUPPORTS_VARIADIC_MACROS_FLAG - Failed
-- Performing Test SUPPORTS_GNU_ZERO_VARIADIC_MACRO_ARGUMENTS_FLAG
-- Performing Test SUPPORTS_GNU_ZERO_VARIADIC_MACRO_ARGUMENTS_FLAG - Failed
-- Native target architecture is X86
-- Threads enabled.
-- Doxygen disabled.
-- Go bindings disabled.
-- Could NOT find OCaml (missing: OCAMLFIND OCAML_VERSION OCAML_STDLIB_PATH)
-- OCaml bindings disabled.
-- Could NOT find Python module pygments
-- Could NOT find Python module pygments.lexers.c_cpp
-- Could NOT find Python module yaml
-- LLVM host triple: x86_64-pc-windows-msvc
-- LLVM default target triple: x86_64-pc-windows-msvc
-- Using Debug VC++ CRT: MDd
-- Using Release VC++ CRT: MD
-- Using MinSizeRel VC++ CRT: MD
-- Using RelWithDebInfo VC++ CRT: MD
-- Looking for os_signpost_interval_begin
-- Looking for os_signpost_interval_begin - not found
-- Found Python3: C:/Users/Name/AppData/Local/Programs/Python/Python39/python.exe (found suitable version "3.9.5", minimum required is "3.6") found components: Interpreter
-- Performing Test HAS_WERROR_GLOBAL_CTORS
-- Performing Test HAS_WERROR_GLOBAL_CTORS - Failed
CMake Error at CMakeLists.txt:1008 (add_subdirectory):
  add_subdirectory given source "utils/TableGen" which is not an existing
  directory.

CMake Error at cmake/modules/TableGen.cmake:9 (message):
  LLVM_TABLEGEN_EXE not set
Call Stack (most recent call first):
  include/llvm/IR/CMakeLists.txt:2 (tablegen)

-- Configuring incomplete, errors occurred!
See also "C:/Users/Name/Documents/name/code/tools/llvm/build/CMakeFiles/CMakeOutput.log".
See also "C:/Users/Name/Documents/name/code/tools/llvm/build/CMakeFiles/CMakeError.log".


来源: stackexchange

问:
Sum specific properties values of objects in array if they have same property name and return unique array as result using java script
my problem is to map two array of objects and sum their specifics properties if they have same name value.

For example if I would like to sum x and y of all objects where property name is 'v' etc.
Here is my code

```<code>var arr = [{name:'v', x:1, b:2, c:3},{name:'r', x:2, b:0, c:3},{name:'v', x:4, b:3, c:3}, {name:'v', x:1, b:1, c:3}];
let arr2 = []
let obj = {name:null, x:null, b: null, c:null}
arr.map(item => {
for(let i=0; i<= arr.length; i++){

    if(item.name === arr[i].name){
     let a = arr.reduce((a, b) => ({x: a.x + b.x, b: a.b + b.b}));
      obj.name = item.name, obj.x = a.x, obj.b = a.b, obj.c = item.c
    } else {
    obj.name = item.name, obj.x=item.x, obj.b=item.b, obj.c=item.c
        }
  arr2.push(obj)
        }
  }
)

console.log(arr2)
</code>```

As result i would like to return array like this

```<code>arr2 = [{name: 'v', x: 6, b: 6, c: 3}, {name: 'r', x:2, b:0, c:1}]
</code>```

答:
```<code>const sumProperties = (arr) => {
  const result = [];
  const map = new Map();
  for (const obj of arr) {
    const key = obj.name;
    if (!map.has(key)) {
      map.set(key, obj);
    } else {
      const oldObj = map.get(key);
      const newObj = { ...oldObj, ...obj };
      map.set(key, newObj);
    }
  }
  map.forEach((value) => {
    result.push(value);
  });
  return result;
}
console.log(sumProperties(arr));
</code>```

ContentLicense: CC BY-SA 4.0

Body:
my problem is to map two array of objects and sum their specifics properties if they have same name value.

For example if I would like to sum x and y of all objects where property name is 'v' etc.
Here is my code

var arr = [{name:'v', x:1, b:2, c:3},{name:'r', x:2, b:0, c:3},{name:'v', x:4, b:3, c:3}, {name:'v', x:1, b:1, c:3}];
let arr2 = []
let obj = {name:null, x:null, b: null, c:null}
arr.map(item => {
for(let i=0; i<= arr.length; i++){

    if(item.name === arr[i].name){
     let a = arr.reduce((a, b) => ({x: a.x + b.x, b: a.b + b.b}));
      obj.name = item.name, obj.x = a.x, obj.b = a.b, obj.c = item.c
    } else {
    obj.name = item.name, obj.x=item.x, obj.b=item.b, obj.c=item.c
        }
  arr2.push(obj)
        }
  }
)

console.log(arr2)

As result i would like to return array like this

arr2 = [{name: 'v', x: 6, b: 6, c: 3}, {name: 'r', x:2, b:0, c:1}]


问:
Robotframework - appium : WebDriver' object has no attribute 'w3c'
I am trying to perform scroll operation using robot framework - appium, but I end up with the error:-
WebDriver' object has no attribute 'w3c'

My code:

```<code>
*** Settings ***
Library  AppiumLibrary

*** Test Cases ***
test_case1
    Open Application    http://localhost:4723/wd/hub    platformName=Android  deviceName=xxx
    appPackage=com.android.settings  appActivity=com.android.settings.Settings
    automationName=Uiautomator2

    Swipe  200  300  200  100

</code>```

Error observed:-
AttributeError: 'WebDriver' object has no attribute 'w3c'

Note:- Other keywords like click element etc are working fine.

答:
Today I have the exact same error as yours. It take me more than 1 hour to figure out what happen.

The problem is the Appium_Python_Client-2.1.2 library. Try to uninstall and reinstall it. And it will fix your error.

Body:
I am trying to perform scroll operation using robot framework - appium, but I end up with the error:-
WebDriver' object has no attribute 'w3c'

My code:

*** Settings ***
Library  AppiumLibrary

*** Test Cases ***
test_case1
    Open Application    http://localhost:4723/wd/hub    platformName=Android  deviceName=xxx
    appPackage=com.android.settings  appActivity=com.android.settings.Settings
    automationName=Uiautomator2

    Swipe  200  300  200  100

Error observed:-
AttributeError: 'WebDriver' object has no attribute 'w3c'

Note:- Other keywords like click element etc are working fine.


问:
Error: wsl.exe exited with code 4294967295 on Installing Rancher Desktop
I am getting the below error when installing the latest stable Rancher Desktop in my Virtual Machine.

Could someone please help?

Error:

Error: wsl.exe exited with code 4294967295

Command:

```<code>wsl --distribution rancher-desktop --exec mkdir -p /mnt/wsl/rancher-desktop/run/data
</code>```

Logs:

2022-02-02T09:58:39.490Z: Running command wsl --distribution
rancher-desktop --exec wslpath -a -u
C:\Users\VIVEK~1.NUN\AppData\Local\Temp\rd-distro-gGd3SG\distro.tar...
2022-02-02T09:58:40.641Z: Running command wsl --distribution
rancher-desktop --exec tar -cf
/mnt/c/Users/VIVEK~1.NUN/AppData/Local/Temp/rd-distro-gGd3SG/distro.tar
-C / /bin/busybox /bin/mount /bin/sh /lib /etc/wsl.conf /etc/passwd /etc/rancher /var/lib... 2022-02-02T09:58:42.628Z: Running command wsl
--import rancher-desktop-data C:\Users\Vivek.Nuna\AppData\Local\rancher-desktop\distro-data
C:\Users\VIVEK~1.NUN\AppData\Local\Temp\rd-distro-gGd3SG\distro.tar
--version 2... 2022-02-02T09:58:44.025Z: Running command wsl --distribution rancher-desktop-data --exec /bin/busybox [ ! -d /etc/rancher ]... 2022-02-02T09:58:44.025Z: Running command wsl
--distribution rancher-desktop-data --exec /bin/busybox [ ! -d /var/lib ]... 2022-02-02T10:03:54.533Z: Running command wsl
--terminate rancher-desktop... 2022-02-02T10:03:54.534Z: Running command wsl --terminate rancher-desktop-data...
2022-02-02T10:03:54.971Z: Running command wsl --distribution
rancher-desktop --exec mkdir -p /mnt/wsl/rancher-desktop/run/data...
2022-02-02T10:04:03.418Z: WSL: executing: mkdir -p
/mnt/wsl/rancher-desktop/run/data: Error: wsl.exe exited with code
4294967295

答:
I resolved the issue by following steps 4 and 5 here:
https://learn.microsoft.com/en-us/windows/wsl/install-manual#step-4---download-the-linux-kernel-update-package

I found this answer by looking in %USERPROFILE%\AppData\Local\rancher-desktop\logs\wsl-exec.log which revealed:
"WSL 2 requires an update to its kernel component. For information please visit https://aka.ms/wsl2kernel"

Body:
I am getting the below error when installing the latest stable Rancher Desktop in my Virtual Machine.

Could someone please help?

Error:

Error: wsl.exe exited with code 4294967295

Command:

wsl --distribution rancher-desktop --exec mkdir -p /mnt/wsl/rancher-desktop/run/data

Logs:

2022-02-02T09:58:39.490Z: Running command wsl --distribution
rancher-desktop --exec wslpath -a -u
C:\Users\VIVEK~1.NUN\AppData\Local\Temp\rd-distro-gGd3SG\distro.tar...
2022-02-02T09:58:40.641Z: Running command wsl --distribution
rancher-desktop --exec tar -cf
/mnt/c/Users/VIVEK~1.NUN/AppData/Local/Temp/rd-distro-gGd3SG/distro.tar
-C / /bin/busybox /bin/mount /bin/sh /lib /etc/wsl.conf /etc/passwd /etc/rancher /var/lib... 2022-02-02T09:58:42.628Z: Running command wsl
--import rancher-desktop-data C:\Users\Vivek.Nuna\AppData\Local\rancher-desktop\distro-data
C:\Users\VIVEK~1.NUN\AppData\Local\Temp\rd-distro-gGd3SG\distro.tar
--version 2... 2022-02-02T09:58:44.025Z: Running command wsl --distribution rancher-desktop-data --exec /bin/busybox [ ! -d /etc/rancher ]... 2022-02-02T09:58:44.025Z: Running command wsl
--distribution rancher-desktop-data --exec /bin/busybox [ ! -d /var/lib ]... 2022-02-02T10:03:54.533Z: Running command wsl
--terminate rancher-desktop... 2022-02-02T10:03:54.534Z: Running command wsl --terminate rancher-desktop-data...
2022-02-02T10:03:54.971Z: Running command wsl --distribution
rancher-desktop --exec mkdir -p /mnt/wsl/rancher-desktop/run/data...
2022-02-02T10:04:03.418Z: WSL: executing: mkdir -p
/mnt/wsl/rancher-desktop/run/data: Error: wsl.exe exited with code
4294967295


问:
how to use a shortcode parameter without "="
I have this super simple wordpress shortcode:

```<code>add_shortcode( 'mytest', 'showMyTest' );
function showMyTest( $atts ) {
    $test =  $atts['test'];
    return $test;
}
</code>```

Usage is this:

```<code>[mytest test="whatever text"]
</code>```

This works. But since I only use one parameter, I want to simplify this simple code so that I don't have to use "test="

I just want to make it work with this:

```<code>[mytest "whatever text"]
</code>```

Any ideas?

答:
When using no attribute name, which is what I want, the values (or values) are stored in an array. Accessing them is easy:

```<code>add_shortcode( 'mytest', 'showMyTest' );
function showMyTest( $atts ) {
    $test =  $atts[0];
    return $test;
}
</code>```

When using this shortcode:

```<code>[mytest "Hello World"]
</code>```

It will produce "Hello World" (without the quotes)

Body:
I have this super simple wordpress shortcode:

add_shortcode( 'mytest', 'showMyTest' );
function showMyTest( $atts ) {
    $test =  $atts['test'];
    return $test;
}

Usage is this:

[mytest test="whatever text"]

This works. But since I only use one parameter, I want to simplify this simple code so that I don't have to use "test="

I just want to make it work with this:

[mytest "whatever text"]

Any ideas?

Body:
When using no attribute name, which is what I want, the values (or values) are stored in an array. Accessing them is easy:

add_shortcode( 'mytest', 'showMyTest' );
function showMyTest( $atts ) {
    $test =  $atts[0];
    return $test;
}

When using this shortcode:

[mytest "Hello World"]

It will produce "Hello World" (without the quotes)


问:
How to build Json 'body' of http call to API
I am trying to contact a GraphQL API and retrieve the data in Flutter

I have a working call in postman giving me the data back.

I have been referred to an example of a working http call but can't get the body to work. I used an encoded version in my postman call but have been advised to un-encode the "data-raw" of my Postman call and pass Json into the query.

I have the main query and then the variable which is the lat/long

A) Is this the correct approach, using pure Json as opposed to encoded like in my postman call (Example below)

```<code>    {"query":"query ($lat: Float!, $lng: Float!) {\n  vehicles(lat: $lat, lng: $lng) {\n    id\n...
</code>```

B) How can I get the query and variable into the Map data = if this is the correct thing to do?

Here is where I am at, using un-encoded Json in Map data = which isn't being accepted and the $lat $long aren't transferred into query from variables

```<code>Future<http.Response> showMicroMob () async {

  var url ='https://flow-api.fluctuo.com/v1?access_token=my_token';

  Map data = {
    'query': query ($lat: Float!, $lng: Float!) {
  vehicles (lat: $lat, lng: $lng) {
    id
    type
    publicId
    provider {
      slug
    }
    lat
    lng
    propulsion
    battery
    attributes
    ... on Station {
      isVirtual
      availableVehicles
      availableStands
      stationVehicleDetails {
        vehicleType
        propulsion
        availableVehicles
      }
      vehicles {
        id
        publicId
        type
        propulsion
        battery
      }
    }
  }
}
    'variables': {"lat":51.492591,"lng":-0.157221}
  };

  //encode Map to JSON
  var body = json.encode(data);

  var response = await http.post(Uri.parse(url),
      headers: {"Content-Type": "application/json"},
      body: body
  );
  print("${response.statusCode}");
  print("${response.body}");
  return response;
}
</code>```

Original example

```<code>Future<http.Response> postRequest () async {
  var url ='https://pae.ipportalegre.pt/testes2/wsjson/api/app/ws-authenticate';

  Map data = {
    'apikey': '12345678901234567890'
  }
  //encode Map to JSON
  var body = json.encode(data);

  var response = await http.post(url,
      headers: {"Content-Type": "application/json"},
      body: body
  );
  print("${response.statusCode}");
  print("${response.body}");
  return response;
}
</code>```

Update of call

If I shift variable up to make a complete String it no longer recognises the $lat $long fields or the actual lat/long numbers as values and makes them orange text. When I move variables down like in my postman request it of course throws errors, but the numbers are recognised as such ($Lat/$Long still not able to take the value. Tried just hard placing lat/ling figures in and returned

```<code>    flutter: 400 flutter: Bad Request
</code>```

Should I try passing the variables in another way?

```<code>Future<http.Response> showMicroMob () async {

  var url ='https://flow-api.fluctuo.com/v1?access_token=x';

  var response = await http.post(Uri.parse(url),
      headers: {"Content-Type": "application/json"},
      body: utf8.encode(r'{"query":"query ($lat: Float!, $lng: Float!) {\n  vehicles(lat: $lat, lng: $lng) {\n    id\n    lat\n    lng\n    type\n    publicId\n    attributes\n    propulsion\n    battery\n    provider {\n      name\n      slug\n      website\n      discountCode\n      app {\n        android\n        ios\n        __typename\n      }\n      deepLink {\n        android\n        ios\n        __typename\n      }\n      stationVehicleTypes\n      __typename\n    }\n    pricing {\n      currency\n      unlock\n      perKm {\n        start\n        interval\n        price\n        __typename\n      }\n      perMin {\n        start\n        interval\n        price\n        __typename\n      }\n      perMinPause {\n        start\n        interval\n        price\n        __typename\n      }\n      includeVat\n      __typename\n    }\n    ... on Station {\n      availableVehicles\n      availableStands\n      isVirtual\n      stationVehicleDetails {\n        vehicleType\n        propulsion\n        availableVehicles\n        __typename\n      }\n      __typename\n    }\n    ... on Car {\n      carClass\n      carModel\n      __typename\n    }\n    __typename\n  }\n}\n"
      ,"variables":{"lat":51.492591,"lng":-0.157221}}'));

  print("${response.statusCode}");
  print("${response.body}");
  return response;
}
</code>```

答:
copy your response and past it on quicktype.io.
quicktype will give you a model class.

Body:
I am trying to contact a GraphQL API and retrieve the data in Flutter

I have a working call in postman giving me the data back.

I have been referred to an example of a working http call but can't get the body to work. I used an encoded version in my postman call but have been advised to un-encode the "data-raw" of my Postman call and pass Json into the query.

I have the main query and then the variable which is the lat/long

A) Is this the correct approach, using pure Json as opposed to encoded like in my postman call (Example below)

    {"query":"query ($lat: Float!, $lng: Float!) {\n  vehicles(lat: $lat, lng: $lng) {\n    id\n...

B) How can I get the query and variable into the Map data = if this is the correct thing to do?

Here is where I am at, using un-encoded Json in Map data = which isn't being accepted and the $lat $long aren't transferred into query from variables

Future<http.Response> showMicroMob () async {

  var url ='https://flow-api.fluctuo.com/v1?access_token=my_token';

  Map data = {
    'query': query ($lat: Float!, $lng: Float!) {
  vehicles (lat: $lat, lng: $lng) {
    id
    type
    publicId
    provider {
      slug
    }
    lat
    lng
    propulsion
    battery
    attributes
    ... on Station {
      isVirtual
      availableVehicles
      availableStands
      stationVehicleDetails {
        vehicleType
        propulsion
        availableVehicles
      }
      vehicles {
        id
        publicId
        type
        propulsion
        battery
      }
    }
  }
}
    'variables': {"lat":51.492591,"lng":-0.157221}
  };

  //encode Map to JSON
  var body = json.encode(data);

  var response = await http.post(Uri.parse(url),
      headers: {"Content-Type": "application/json"},
      body: body
  );
  print("${response.statusCode}");
  print("${response.body}");
  return response;
}

Original example

Future<http.Response> postRequest () async {
  var url ='https://pae.ipportalegre.pt/testes2/wsjson/api/app/ws-authenticate';

  Map data = {
    'apikey': '12345678901234567890'
  }
  //encode Map to JSON
  var body = json.encode(data);

  var response = await http.post(url,
      headers: {"Content-Type": "application/json"},
      body: body
  );
  print("${response.statusCode}");
  print("${response.body}");
  return response;
}

Update of call

If I shift variable up to make a complete String it no longer recognises the $lat $long fields or the actual lat/long numbers as values and makes them orange text. When I move variables down like in my postman request it of course throws errors, but the numbers are recognised as such ($Lat/$Long still not able to take the value. Tried just hard placing lat/ling figures in and returned

    flutter: 400 flutter: Bad Request

Should I try passing the variables in another way?

Future<http.Response> showMicroMob () async {

  var url ='https://flow-api.fluctuo.com/v1?access_token=x';

  var response = await http.post(Uri.parse(url),
      headers: {"Content-Type": "application/json"},
      body: utf8.encode(r'{"query":"query ($lat: Float!, $lng: Float!) {\n  vehicles(lat: $lat, lng: $lng) {\n    id\n    lat\n    lng\n    type\n    publicId\n    attributes\n    propulsion\n    battery\n    provider {\n      name\n      slug\n      website\n      discountCode\n      app {\n        android\n        ios\n        __typename\n      }\n      deepLink {\n        android\n        ios\n        __typename\n      }\n      stationVehicleTypes\n      __typename\n    }\n    pricing {\n      currency\n      unlock\n      perKm {\n        start\n        interval\n        price\n        __typename\n      }\n      perMin {\n        start\n        interval\n        price\n        __typename\n      }\n      perMinPause {\n        start\n        interval\n        price\n        __typename\n      }\n      includeVat\n      __typename\n    }\n    ... on Station {\n      availableVehicles\n      availableStands\n      isVirtual\n      stationVehicleDetails {\n        vehicleType\n        propulsion\n        availableVehicles\n        __typename\n      }\n      __typename\n    }\n    ... on Car {\n      carClass\n      carModel\n      __typename\n    }\n    __typename\n  }\n}\n"
      ,"variables":{"lat":51.492591,"lng":-0.157221}}'));

  print("${response.statusCode}");
  print("${response.body}");
  return response;
}


问:
Stringformat a MultiIndex DatetimeIndex using Babel's format_datetime() for Localization

Python 3.7.0

pandas 1.1.5

numpy 1.21.4

Babel 2.9.1

Problem

I have a dataset that is first evaluated, then completed with calculations and then converted into a pd.MultiIndex by grouping it with the pd.Grouper. The result looks something like this:

```<code>                           delta (secs)
identifier   start_dt
FOO          '2021-11-30'  10738.823
BAR          '2021-11-30'    116.000
</code>```

And the index looks like this:

```<code>MultiIndex([('FOO', '2021-11-30'),
            ('BAR', '2021-11-30')],
           names=['identifier', 'start_dt'])
</code>```

For better readability, I want to use Babel to properly localize the datetime output in the index columns according to a the locale.

When I try to apply Babel's format_datetime() function to the DateTimeIndex like so:

```<code>mi_frame.index = mi_frame.index.set_levels(
    format_datetime(
        mi_frame.index,
        format=time_format,
        tzinfo=get_timezone('Europe/Berlin'),
        locale="de_DE"),
    level=1)
</code>```

I get the error AttributeError: 'DatetimeIndex' object has no attribute 'replace'. Other methods such as .apply() returned the same error.

The problem lies in the MultiIndex's Index data type (DateTimeIndex), that only allows its own string manipulation / representation method .strftime(time_format).

答:
Thanks to this answer on type conversion by @jezrael from a DateTimeIndex to a Python datetime object, one can pipe it into Babel's functions as they expect a native Python datetime object.

So the solution to my problem is not very elegant, but it works:

Cast the DatetimeIndex to a a numpy array of datetime objects

Cast to a list to perform a list comprehension

Use Babel's format_datetime() to convert the datetime objects into the desired string representations

re-assign the list to the MultiIndex index at the previous level (here: level=1) using pandas' MultiIndex.index.set_levels()

```<code>dt_array = list(mi_frame.index.levels[1].to_pydatetime())

dt_array = [format_datetime(idx, format="MMM", tzinfo=get_timezone('Europe/Berlin'), locale="de_DE")
            for idx in dt_array]
mi_frame.index = mi_frame.index.set_levels(dt_array, level=1)
</code>```

Which yields (after some arithmetic added):

```<code>                             delta  percentage
identifier   start_dt
FOO          Nov.        10738.823         0.4
BAR          Nov.          116.000         0.0
</code>```

The Nov. results according to the "MMM" format string described in the official Babel documentation.

Body:
Python 3.7.0

pandas 1.1.5

numpy 1.21.4

Babel 2.9.1

Problem

I have a dataset that is first evaluated, then completed with calculations and then converted into a pd.MultiIndex by grouping it with the pd.Grouper. The result looks something like this:

                           delta (secs)
identifier   start_dt
FOO          '2021-11-30'  10738.823
BAR          '2021-11-30'    116.000

And the index looks like this:

MultiIndex([('FOO', '2021-11-30'),
            ('BAR', '2021-11-30')],
           names=['identifier', 'start_dt'])

For better readability, I want to use Babel to properly localize the datetime output in the index columns according to a the locale.

When I try to apply Babel's format_datetime() function to the DateTimeIndex like so:

mi_frame.index = mi_frame.index.set_levels(
    format_datetime(
        mi_frame.index,
        format=time_format,
        tzinfo=get_timezone('Europe/Berlin'),
        locale="de_DE"),
    level=1)

I get the error AttributeError: 'DatetimeIndex' object has no attribute 'replace'. Other methods such as .apply() returned the same error.

The problem lies in the MultiIndex's Index data type (DateTimeIndex), that only allows its own string manipulation / representation method .strftime(time_format).

Body:
Thanks to this answer on type conversion by @jezrael from a DateTimeIndex to a Python datetime object, one can pipe it into Babel's functions as they expect a native Python datetime object.

So the solution to my problem is not very elegant, but it works:

Cast the DatetimeIndex to a a numpy array of datetime objects

Cast to a list to perform a list comprehension

Use Babel's format_datetime() to convert the datetime objects into the desired string representations

re-assign the list to the MultiIndex index at the previous level (here: level=1) using pandas' MultiIndex.index.set_levels()

dt_array = list(mi_frame.index.levels[1].to_pydatetime())

dt_array = [format_datetime(idx, format="MMM", tzinfo=get_timezone('Europe/Berlin'), locale="de_DE")
            for idx in dt_array]
mi_frame.index = mi_frame.index.set_levels(dt_array, level=1)

Which yields (after some arithmetic added):

                             delta  percentage
identifier   start_dt
FOO          Nov.        10738.823         0.4
BAR          Nov.          116.000         0.0

The Nov. results according to the "MMM" format string described in the official Babel documentation.


问:
How to force a GPRS connection instead of 3G or Wifi?
I am writing an application where I need to have specifically a GPRS connection, even if wifi or 3G (or better) is available. I have figured out how to disable wifi (by using WifiManager), however, I can't seem to find out how I can programmatically disable 3G and only use a GPRS connection, with equal effect as changing this manually in the device settings.

Is there a way to do this with code?

UPDATE: What I am looking for does not necessarily have to be in the public Android APIs. It might as well be in one of the undocumented APIs, or as a last resort, device-specific APIs, I just need something that works. However, I'd rather not have to root a device to use these functions.

答:
In android framework, TelephonyManager is the object providing Telephony service to android application.

see http://developer.android.com/reference/android/telephony/TelephonyManager.html

The service do provide several methods to know state and information of your physical radio component.

But there is no way to modify the way the physical radio component of your device do its job. Its a private logic of your device manufacturer that try to do its best to comply radiophony industrial standard and provide the best end user experience quality

This is an public api android point of view (over dalvik) answer, do not answer in context of private android api, nor native way nor root privileged way.

ContentLicense: CC BY-SA 3.0


问:
Google Sheets most frequent and just one value
I'm trying to count the number of most frequent text in a column, I have this formula that I used before in excel...

```<code>=INDEX(E9:E18,MODE(IF((E9:E18<>"")*ISNA(MATCH(E9:E18,$B$1:$B1,0)),MATCH(E9:E18,E9:E18,0))))
</code>```

This works, but when I get some repited value shows #N/A
Here is an capture from this I would like to know how can I resolve this I tried with

```<code>=INDEX(E9:E18,MODE(IF(AND(E9:E18<>"")*ISNA(MATCH(E9:E18,$B$1:$B1,0)),MATCH(E9:E18,E9:E18,0))))
</code>```

But I get lost trying to put a condition like only one value = value
Some help or code that I could use?

So this is my problem

答:
With Office 365:
=INDEX( SORTBY(UNIQUE(A1:A10), COUNTIF( A1:A10, UNIQUE(A1:A10) ),-1), 1 )

Oops - i just saw the Google sheets edit.

For most frequent:

```<code>=INDEX( SORT(UNIQUE(A1:A10), COUNTIF( A1:A10, UNIQUE(A1:A10) ),0), 1 )
</code>```

For Just One Value:

```<code>=FILTER(UNIQUE(A1:A10),COUNTIF(A1:A10,UNIQUE(A1:A10))=1)
</code>```

Body:
I'm trying to count the number of most frequent text in a column, I have this formula that I used before in excel...

=INDEX(E9:E18,MODE(IF((E9:E18<>"")*ISNA(MATCH(E9:E18,$B$1:$B1,0)),MATCH(E9:E18,E9:E18,0))))

This works, but when I get some repited value shows #N/A
Here is an capture from this I would like to know how can I resolve this I tried with

=INDEX(E9:E18,MODE(IF(AND(E9:E18<>"")*ISNA(MATCH(E9:E18,$B$1:$B1,0)),MATCH(E9:E18,E9:E18,0))))

But I get lost trying to put a condition like only one value = value
Some help or code that I could use?

So this is my problem

Body:
With Office 365:
=INDEX( SORTBY(UNIQUE(A1:A10), COUNTIF( A1:A10, UNIQUE(A1:A10) ),-1), 1 )

Oops - i just saw the Google sheets edit.

For most frequent:

=INDEX( SORT(UNIQUE(A1:A10), COUNTIF( A1:A10, UNIQUE(A1:A10) ),0), 1 )

For Just One Value:

=FILTER(UNIQUE(A1:A10),COUNTIF(A1:A10,UNIQUE(A1:A10))=1)


问:
Python list max element allowed
I am reading file and putting all the data of file in list. file size is quite big  about 80k records. In python is good practice to store these number of data in list?

Later i am splitting this list and building the request to send to API.

here is example

```<code>content_list = []
    with open("file") as reader:
        for line in reader:
            content_list .append(line)
</code>```

答:
the object has readlines method as default

```<code>with open("file") as f:
        content_list = f.readlines()
        #or
        #content_list = list(f)

</code>```

Title: Python list max element allowed

Body:
I am reading file and putting all the data of file in list. file size is quite big  about 80k records. In python is good practice to store these number of data in list?

Later i am splitting this list and building the request to send to API.

here is example

content_list = []
    with open("file") as reader:
        for line in reader:
            content_list .append(line)

Body:
the object has readlines method as default

with open("file") as f:
        content_list = f.readlines()
        #or
        #content_list = list(f)


问:
KQL group by or summarize count by see the rest of the columns
I would like to ask your help with a kql query:

```<code>DeviceEvents
| distinct InitiatingProcessAccountUpn,DeviceName,DeviceId
| join DeviceTvmSoftwareVulnerabilities on $left.DeviceId == $right.DeviceId
| summarize count() by SoftwareName, DeviceId
</code>```

The problem is I used summarize count by there are many software versions and I just want to see the version of the software from each machine, and it did the tick but I can not re-add the missing columns from the table.

I tried to rejoin with the same table but wasn't successfull.

What I would like to see is from one machine one software.
Now, if I have this, I can see the name of the software and ID but I want to see in the final report the rest column as well.

Do you have any idea what I can do better?
Thanks

答:
you can use take_any:

```<code>summarize take_any(SomeOtherColumns)
</code>```

Or you could add the other column as a grouping key and then do another summarize and aggregate it somehow (also take_any(), max(), arg_max(), make_list() etc)

Body:
I would like to ask your help with a kql query:

DeviceEvents
| distinct InitiatingProcessAccountUpn,DeviceName,DeviceId
| join DeviceTvmSoftwareVulnerabilities on $left.DeviceId == $right.DeviceId
| summarize count() by SoftwareName, DeviceId

The problem is I used summarize count by there are many software versions and I just want to see the version of the software from each machine, and it did the tick but I can not re-add the missing columns from the table.

I tried to rejoin with the same table but wasn't successfull.

What I would like to see is from one machine one software.
Now, if I have this, I can see the name of the software and ID but I want to see in the final report the rest column as well.

Do you have any idea what I can do better?
Thanks

Body:
you can use take_any:

summarize take_any(SomeOtherColumns)

Or you could add the other column as a grouping key and then do another summarize and aggregate it somehow (also take_any(), max(), arg_max(), make_list() etc)


问:
json_decode creates unnecessary arrays
I got this JSON which I need to convert to associative PHP array

```<code>[
    {
        "32": {
            "name": "Price File Jan 2022.xlsx",
            "datastartingrow": "1"
        }
    },
    {
        "33": {
            "name": "Price File Feb 2022.xlsx",
            "datastartingrow": "2"
        }
    }
]
</code>```

$decoded = json_decode($json, true) creates unnecessary arrays [0] and [1], so I can't access $decoded[32] without double looping.

```<code>Array
(
    [0] => Array
        (
            [32] => Array
                (
                    [name] => Price File Jan 2022.xlsx
                    [datastartingrow] => 1
                )

        )

    [1] => Array
        (
            [33] => Array
                (
                    [name] => Price File Feb 2022.xlsx
                    [datastartingrow] => 2
                )

        )

)
</code>```

Is there an elegant way of accessing each array by using key [32] and [33]?

Thanks.

答:
Somthing like this should be appropriate for a start

```<code><?php
$data = '{"32":{"name":"Price File Jan 2022.xlsx","datastartingrow":"1"},"33":{"name":"Price File Feb 2022.xlsx","datastartingrow":"2"}}';

$decoded = json_decode($data, true);

foreach($decoded as $key => $element){
  echo 'element key is '.$key.' and item is '. json_encode($element). ' |||||||||||||||||| ' ;
}

?>
</code>```

Check out the live example here

Title: json_decode creates unnecessary arrays

Body:
I got this JSON which I need to convert to associative PHP array

[
    {
        "32": {
            "name": "Price File Jan 2022.xlsx",
            "datastartingrow": "1"
        }
    },
    {
        "33": {
            "name": "Price File Feb 2022.xlsx",
            "datastartingrow": "2"
        }
    }
]

$decoded = json_decode($json, true) creates unnecessary arrays [0] and [1], so I can't access $decoded[32] without double looping.

Array
(
    [0] => Array
        (
            [32] => Array
                (
                    [name] => Price File Jan 2022.xlsx
                    [datastartingrow] => 1
                )

        )

    [1] => Array
        (
            [33] => Array
                (
                    [name] => Price File Feb 2022.xlsx
                    [datastartingrow] => 2
                )

        )

)

Is there an elegant way of accessing each array by using key [32] and [33]?

Thanks.

Body:
Somthing like this should be appropriate for a start

<?php
$data = '{"32":{"name":"Price File Jan 2022.xlsx","datastartingrow":"1"},"33":{"name":"Price File Feb 2022.xlsx","datastartingrow":"2"}}';

$decoded = json_decode($data, true);

foreach($decoded as $key => $element){
  echo 'element key is '.$key.' and item is '. json_encode($element). ' |||||||||||||||||| ' ;
}

?>

Check out the live example here


问:
the trait `Future` is not implemented for `Result<std::net::TcpListener, std::io::Error>
I try to initialize a server in rust with async functionality using Tokio library:

```<code>use std::net::TcpListener;

#[tokio::main]
async fn main() {
    // let listener=TcpListener::bind("localhost:8080").await.unwrap();
    let listener = TcpListener::bind("127.0.0.1:8080").await.unwrap();
    let (socket,_addr)=listener.accept().await.unwrap();
}
</code>```

This throws an error saying that:

```<code> the trait `Future` is not implemented for `Result<std::net::TcpListener, std::io::Error>`
</code>```

When I hover over listener its type is unknown.

答:
You have:

```<code>use std::net::TcpListener;
</code>```

And you probably want to have:

```<code>use tokio::net::TcpListener;
</code>```

Here is an example from tokio's docs:

```<code>use tokio::net::TcpListener;

use std::io;

async fn process_socket<T>(socket: T) {
    // do work with socket here
}

#[tokio::main]
async fn main() -> io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:8080").await?;

    loop {
        let (socket, _) = listener.accept().await?;
        process_socket(socket).await;
    }
}
</code>```

Body:
I try to initialize a server in rust with async functionality using Tokio library:

use std::net::TcpListener;

#[tokio::main]
async fn main() {
    // let listener=TcpListener::bind("localhost:8080").await.unwrap();
    let listener = TcpListener::bind("127.0.0.1:8080").await.unwrap();
    let (socket,_addr)=listener.accept().await.unwrap();
}

This throws an error saying that:

 the trait `Future` is not implemented for `Result<std::net::TcpListener, std::io::Error>`

When I hover over listener its type is unknown.

Body:
You have:

use std::net::TcpListener;

And you probably want to have:

use tokio::net::TcpListener;

Here is an example from tokio's docs:

use tokio::net::TcpListener;

use std::io;

async fn process_socket<T>(socket: T) {
    // do work with socket here
}

#[tokio::main]
async fn main() -> io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:8080").await?;

    loop {
        let (socket, _) = listener.accept().await?;
        process_socket(socket).await;
    }
}


问:
how can I select only specific .nc files from long list to work with cdo?
How can I merge only specific .nc files to work with cdo?
from a long list of files that look like this:

var_1-2.nc

var_3-4.nc

var_5-6.nc

.

.

var_99-100.nc

I would like to to a cdo mergetime only to the last e.g 10 files
Anyone could help me with the syntax here?

答:
Just to add to Rob's answer, it is perhaps more robust to do

```<code>cdo mergetime var_9?-*.nc out.nc
</code>```

The ? can only be replaced by a single character so this would pick up all the 90s files but ignore var9-10.nc

Of course if you wanted only the last 7 files then this wouldn't work and your tail solution is better.

As Rob mentions in his comments, in general it is a good idea to pad file name indices with zeros when generating them, so that a list command like ls will give them in correct numerical order - you can do this with seq -w i1 i2 for example.

Body:
Just to add to Rob's answer, it is perhaps more robust to do

cdo mergetime var_9?-*.nc out.nc

The ? can only be replaced by a single character so this would pick up all the 90s files but ignore var9-10.nc

Of course if you wanted only the last 7 files then this wouldn't work and your tail solution is better.

As Rob mentions in his comments, in general it is a good idea to pad file name indices with zeros when generating them, so that a list command like ls will give them in correct numerical order - you can do this with seq -w i1 i2 for example.


问:
INSERT INTO database table, from form not working. SQL
lets get straight to my problem, the code I have written here does not write to my database and I cannot figue out why. At the moment I am simply trying to get to grips with php and sql so there is no point to this form other than learning. Here is the error i am getting(the first sentence 'connected to database' is from my if statement):

"Connected to databaseError: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''test' ('name') VALUES ('daniel')' at line 1"

The code I have may look a little confusing as some of it is from w3schools and some is from a friend. I cannot figure out why this code isn't working, I have tried many variations of the syntax based on loads of articles I have found online and on stackoverflow but none seem to work. I fear that maybe I am not even connectec to the database, although my if statement tells me otherwise, so that could be a problem?

Hopefully if this gets solved this question will clarify database connection and writing to a database from a form in one hit. Thanks in advance guys and here's my code.

HTML

```<code><form action="insert.php" method="post">
Name: <input type="text" name="namefield" />
<input type="submit" />
</form>
</code>```

PHP (insert.php)

```<code><?php
$dbhost  = 'localhost';
$dbname  = 'carbon_db';
$dbuser  = 'username';
$dbpass  = 'password';

$con = mysql_connect($dbhost, $dbuser, $dbpass);

if($con == FALSE)
{
    echo 'Cannot connect to database' . mysql_error();
}
else
{
    echo 'Connected to database';
}

mysql_select_db($dbname, $con);

$sql="INSERT INTO 'test' ('name')
VALUES ('$_POST[namefield]')";

if (!mysql_query($sql, $con))
{
    die('Error: ' . mysql_error());
}
echo "1 record added";

mysql_close($con)
?>
</code>```

答:
It's often best to use backticks for MySQL as like any other storage engines it has it's own reserved names and it's own reserved insert practices.

try with

```<code>$sql = "INSERT INTO `test` (`name`) VALUES ('".$_POST['namefield']."')";
</code>```

Body:
lets get straight to my problem, the code I have written here does not write to my database and I cannot figue out why. At the moment I am simply trying to get to grips with php and sql so there is no point to this form other than learning. Here is the error i am getting(the first sentence 'connected to database' is from my if statement):

"Connected to databaseError: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''test' ('name') VALUES ('daniel')' at line 1"

The code I have may look a little confusing as some of it is from w3schools and some is from a friend. I cannot figure out why this code isn't working, I have tried many variations of the syntax based on loads of articles I have found online and on stackoverflow but none seem to work. I fear that maybe I am not even connectec to the database, although my if statement tells me otherwise, so that could be a problem?

Hopefully if this gets solved this question will clarify database connection and writing to a database from a form in one hit. Thanks in advance guys and here's my code.

HTML

<form action="insert.php" method="post">
Name: <input type="text" name="namefield" />
<input type="submit" />
</form>

PHP (insert.php)

<?php
$dbhost  = 'localhost';
$dbname  = 'carbon_db';
$dbuser  = 'username';
$dbpass  = 'password';

$con = mysql_connect($dbhost, $dbuser, $dbpass);

if($con == FALSE)
{
    echo 'Cannot connect to database' . mysql_error();
}
else
{
    echo 'Connected to database';
}

mysql_select_db($dbname, $con);

$sql="INSERT INTO 'test' ('name')
VALUES ('$_POST[namefield]')";

if (!mysql_query($sql, $con))
{
    die('Error: ' . mysql_error());
}
echo "1 record added";

mysql_close($con)
?>

Body:
It's often best to use backticks for MySQL as like any other storage engines it has it's own reserved names and it's own reserved insert practices.

try with

$sql = "INSERT INTO `test` (`name`) VALUES ('".$_POST['namefield']."')";


问:
Proper way to query in Hugo using goTemplates with multiple nested arguments, is it possible?
I'm working with Hugo and have a question regarding where clause. Currently I am doing the following and it works fine. I attempted to add one more where argument and I got the error below:

Question: How do I add multiple nested arguments to Hugo where clause. I will continue to test it out in the meantime.

Error calling where: can't evaluate the array by no match argument or more than or equal to two arg:uments

Works:

```<code>{{ range where (where site.Pages "Type" "post") "Params.type" "featured"  }}
                <div class="ph1-ns w-50-ns flex">
                    {{ .Render "li" }}
                </div>
            {{ end }}
        </div>
</code>```

Fails:

```<code>{{ range where (where site.Pages "Type" "post") "Params.type" "featured" "Params.location" "nashville" }}
                    <div class="ph1-ns w-50-ns flex">
                        {{ .Render "li" }}
                    </div>
                {{ end }}
            </div>
</code>```

Per Hugo:
Nest where Clauses
You can also nest where clauses to drill down on lists of content by more than one parameter. The following first grabs all pages in the “blog” section and then ranges through the result of the first where clause and finds all pages that are not featured:

答:
I was able to resolve this, after reading some additional information at https://pkg.go.dev/text/template#pkg-overview; I went with the below.</p>
```<code><div class="w-100 flex-ns mhn1-ns flex-wrap mb3">
        {{ range where (where site.Pages "Type" "post") "Params.featured" "!=" nil  }}
        {{ if(eq .Params.location "nashville")}}
            <div class="ph1-ns w-50-ns flex">
                {{ .Render "li" }}
            </div>
        {{ else}}
         Coming Soon
        {{end}}
        {{end}}
    </div>
</code>```

Body:
I'm working with Hugo and have a question regarding where clause. Currently I am doing the following and it works fine. I attempted to add one more where argument and I got the error below:

Question: How do I add multiple nested arguments to Hugo where clause. I will continue to test it out in the meantime.

Error calling where: can't evaluate the array by no match argument or more than or equal to two arg:uments

Works:

{{ range where (where site.Pages "Type" "post") "Params.type" "featured"  }}

                    {{ .Render "li" }}

            {{ end }}

Fails:

{{ range where (where site.Pages "Type" "post") "Params.type" "featured" "Params.location" "nashville" }}

                        {{ .Render "li" }}

                {{ end }}

Per Hugo:
Nest where Clauses
You can also nest where clauses to drill down on lists of content by more than one parameter. The following first grabs all pages in the “blog” section and then ranges through the result of the first where clause and finds all pages that are not featured:

Body:
I was able to resolve this, after reading some additional information at https://pkg.go.dev/text/template#pkg-overview; I went with the below.

<div class="w-100 flex-ns mhn1-ns flex-wrap mb3">
        {{ range where (where site.Pages "Type" "post") "Params.featured" "!=" nil  }}
        {{ if(eq .Params.location "nashville")}}
            <div class="ph1-ns w-50-ns flex">
                {{ .Render "li" }}
            </div>
        {{ else}}
         Coming Soon
        {{end}}
        {{end}}
    </div>


问:
reducing the If else condtion code in javascript
I wrote a code to fetch the data present and store it in Array format but I thing I have wrote code multiple times can It be possible to minimize the code as its too long

let topicsValue = ["requiredType.*", "Entry.*", "token.*", "RestAPI.*"];

let Topic = [],
  rest = ["required", "unrequired"],
  final = ["createInput", "mustPossible", "finalOutput"];
topicsValue.map((data) => {
  let requiredType, entries, token, restAPI;
  if (data.split(".")[1].includes("*")) {
    if (data.split(".")[0].includes("requiredType")) {
      for (const value of final) {
        requiredType = data
          .split(".")[0]
          .replace("requiredType", "required_type")
          .concat(`.${value}`);
        Topic.push(requiredType);
      }
    }
    if (data.split(".")[0].includes("Entry")) {
      for (const value of final) {
        entries = data
          .split(".")[0]
          .replace("Entry", "entries")
          .concat(`.${value}`);
        Topic.push(entries);
      }
      for (const value of rest) {
        entries = data
          .split(".")[0]
          .replace("Entry", "entries")
          .concat(`.${value}`);
        Topic.push(entries);
      }
    }
    if (data.split(".")[0].includes("token")) {
      for (const value of final) {
        token = data
          .split(".")[0]
          .replace("token", "tokens")
          .concat(`.${value}`);
        Topic.push(token);
      }
      for (const value of rest) {
        token = data
          .split(".")[0]
          .replace("token", "tokens")
          .concat(`.${value}`);
        Topic.push(token);
      }
    }
    if (
      data.split(".")[0].includes("RestAPI") &&
      !data.split(".")[0].includes("RestAPIAction")
    ) {
      restAPI = data
        .split(".")[0]
        .replace("RestAPI", "restAPI")
        .concat(`.deploy`);
      Topic.push(restAPI);
    }
  } else {
    if (data.split(".")[0].includes("requiredType")) {
      if (!rest.includes(data.split(".")[1])) {
        requiredType = data
          .split(".")[0]
          .replace("requiredType", "required_type")
          .concat(`.${data.split(".")[1]}`);
        Topic.push(requiredType);
      }
    }
    if (data.split(".")[0].includes("Entry")) {
      if (rest.includes(data.split(".")[1])) {
        entries = data
          .split(".")[0]
          .replace("Entry", "entries")
          .concat(`.${data.split(".")[1]}.demo`);
        Topic.push(entries);
      } else {
        entries = data
          .split(".")[0]
          .replace("Entry", "entries")
          .concat(`.${data.split(".")[1]}.demo`);
        Topic.push(entries);
      }
    }
    if (data.split(".")[0].includes("token")) {
      if (rest.includes(data.split(".")[1])) {
        token = data
          .split(".")[0]
          .replace("token", "tokens")
          .concat(`.${data.split(".")[1]}`);
        Topic.push(token);
      } else {
        token = data
          .split(".")[0]
          .replace("token", "tokens")
          .concat(`.${data.split(".")[1]}`);
        Topic.push(token);
      }
    }
    if (
      data.split(".")[0].includes("RestAPI") &&
      !data.split(".")[0].includes("RestAPIAction")
    ) {
      restAPI = data
        .split(".")[0]
        .replace("RestAPI", "restAPI")
        .concat(`.deploy`);
      Topic.push(restAPI);
    }
  }
});

console.log(Topic);```

Is there any possible way I can reduce the code without effecting the output

As the requirement of the code is like if the topicValue contain * or the other value so I wrote this long code and now I am trying to minimize the code so its look short and effective.

答:
Try using the && operator.

```<code>if(y==1 && x == 1) {
do somthing
}

</code>```

it only runs if both statements are true.

Body:
I wrote a code to fetch the data present and store it in Array format but I thing I have wrote code multiple times can It be possible to minimize the code as its too long

let topicsValue = ["requiredType.*", "Entry.*", "token.*", "RestAPI.*"];

let Topic = [],
  rest = ["required", "unrequired"],
  final = ["createInput", "mustPossible", "finalOutput"];
topicsValue.map((data) => {
  let requiredType, entries, token, restAPI;
  if (data.split(".")[1].includes("*")) {
    if (data.split(".")[0].includes("requiredType")) {
      for (const value of final) {
        requiredType = data
          .split(".")[0]
          .replace("requiredType", "required_type")
          .concat(`.${value}`);
        Topic.push(requiredType);
      }
    }
    if (data.split(".")[0].includes("Entry")) {
      for (const value of final) {
        entries = data
          .split(".")[0]
          .replace("Entry", "entries")
          .concat(`.${value}`);
        Topic.push(entries);
      }
      for (const value of rest) {
        entries = data
          .split(".")[0]
          .replace("Entry", "entries")
          .concat(`.${value}`);
        Topic.push(entries);
      }
    }
    if (data.split(".")[0].includes("token")) {
      for (const value of final) {
        token = data
          .split(".")[0]
          .replace("token", "tokens")
          .concat(`.${value}`);
        Topic.push(token);
      }
      for (const value of rest) {
        token = data
          .split(".")[0]
          .replace("token", "tokens")
          .concat(`.${value}`);
        Topic.push(token);
      }
    }
    if (
      data.split(".")[0].includes("RestAPI") &&
      !data.split(".")[0].includes("RestAPIAction")
    ) {
      restAPI = data
        .split(".")[0]
        .replace("RestAPI", "restAPI")
        .concat(`.deploy`);
      Topic.push(restAPI);
    }
  } else {
    if (data.split(".")[0].includes("requiredType")) {
      if (!rest.includes(data.split(".")[1])) {
        requiredType = data
          .split(".")[0]
          .replace("requiredType", "required_type")
          .concat(`.${data.split(".")[1]}`);
        Topic.push(requiredType);
      }
    }
    if (data.split(".")[0].includes("Entry")) {
      if (rest.includes(data.split(".")[1])) {
        entries = data
          .split(".")[0]
          .replace("Entry", "entries")
          .concat(`.${data.split(".")[1]}.demo`);
        Topic.push(entries);
      } else {
        entries = data
          .split(".")[0]
          .replace("Entry", "entries")
          .concat(`.${data.split(".")[1]}.demo`);
        Topic.push(entries);
      }
    }
    if (data.split(".")[0].includes("token")) {
      if (rest.includes(data.split(".")[1])) {
        token = data
          .split(".")[0]
          .replace("token", "tokens")
          .concat(`.${data.split(".")[1]}`);
        Topic.push(token);
      } else {
        token = data
          .split(".")[0]
          .replace("token", "tokens")
          .concat(`.${data.split(".")[1]}`);
        Topic.push(token);
      }
    }
    if (
      data.split(".")[0].includes("RestAPI") &&
      !data.split(".")[0].includes("RestAPIAction")
    ) {
      restAPI = data
        .split(".")[0]
        .replace("RestAPI", "restAPI")
        .concat(`.deploy`);
      Topic.push(restAPI);
    }
  }
});

console.log(Topic);

Is there any possible way I can reduce the code without effecting the output

As the requirement of the code is like if the topicValue contain * or the other value so I wrote this long code and now I am trying to minimize the code so its look short and effective.

Body:
Try using the && operator.

if(y==1 && x == 1) {
do somthing
}

it only runs if both statements are true.


问:
PowerApps - If the user selects a value from the dropdown to navigate to a specific screen
I have completed all my screens in PowerApps and I am now trying to setup the navigation.

My dropdown is named Dropdown1

The dropdown value in question is Employement

The screen that I want the user to go to if he/she selects Employement in the dropdown is called Section 3 Other Mirror

the screen that I want the user to go to if he/she selects any other choice in the dropdown is called Section 4 VP Setup

Current formula:
If(Dropdown1.Selected.Value = "Employement"; Navigate('Section 3 Other Mirror',ScreenTransition.Cover)

Error: Unexpected characters. 'ParenClose' where 'Eof' is expected.

答: Fixed. I had to turn on the OnSelect in order to reach the values.


问:
What features are people looking forward to in .Net 4.0 - 4.1
I am very interested in learning what features people are interested in in the forthcoming .net framework(s)?

Whether these be new classes or new controls I am curious to know people views.

答:
Optional parameters in C#

More so than than .NET 4.0, I'm really looking forward to Visual Studio 2010, same as jirwin's response.

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Cory Larson

LastEditorDisplayName: Cory Larson


问:
filtering objects from List with foreach
Hi Ive got a list of objects but how do I filter it out to another list?

Ex:

```<code>public class Person
{
    public string FirstName;
    public string Language;

    public Person (string FirstName, string Language)
    {
        this.FirstName = FirstName;
        this.LastName = Language;
    }
 }
</code>```

Creates a list:

```<code>public List<Person> createDummyList()
{
  List<Person> dummyList = new List<Person>();
  dummyList.Add(new Person("Per", "English"));
  dummyList.Add(new Person("Linda", "Spanish"));
}
</code>```

How can I get a List with just the language and then bind it to say a dropdown.? Ive tryed something like this but got a null reference...

```<code>public void filterList(List<Person> ListToBeFiltered)
{
    List<string> LanguageList = new List<string>();
    ListToBeFiltered.ForEach(delegate(Person P)
    {
       LanguageList.Add(P.Language);
    });
    DropDown.datasource = LanguageList;
    DropDown.databind();
 }
</code>```

Anyone can point me in the right direction?

答:
```<code>public void filterList(List<Person> ListToBeFiltered)
{
        DropDown.datasource = ListToBeFiltered.Select(p=>p.Language).Distinct();
        DropDown.databind();
}
</code>```

Body:
Hi Ive got a list of objects but how do I filter it out to another list?

Ex:

public class Person
{
    public string FirstName;
    public string Language;

    public Person (string FirstName, string Language)
    {
        this.FirstName = FirstName;
        this.LastName = Language;
    }
 }

Creates a list:

public List<Person> createDummyList()
{
  List<Person> dummyList = new List<Person>();
  dummyList.Add(new Person("Per", "English"));
  dummyList.Add(new Person("Linda", "Spanish"));
}

How can I get a List with just the language and then bind it to say a dropdown.? Ive tryed something like this but got a null reference...

public void filterList(List<Person> ListToBeFiltered)
{
    List<string> LanguageList = new List<string>();
    ListToBeFiltered.ForEach(delegate(Person P)
    {
       LanguageList.Add(P.Language);
    });
    DropDown.datasource = LanguageList;
    DropDown.databind();
 }

Anyone can point me in the right direction?


问:
sqlalchemy column_property in self-referential
I can't describe the column "invited_name" (column_property). I don't know how to do this correctly.

```<code>class Worker(declarative_base()):
    __tablename__ = "staff_worker_info"

    id = Column(Integer, primary_key=True)
    first_name = Column(String(40), nullable=False)
    last_name = Column(String(40), nullable=False)

    invited_id = Column(Integer, ForeignKey('staff_worker_info.id'))
    invited = relationship("Worker", uselist=False, remote_side=[id], join_depth=1)

    # I don't know how to describe this column
    invited_name = column_property(
         select([Worker.first_name]). \
         where(Worker.id == invited_id).\
         label('invited_n'))
</code>```

I understand why this doesn't work, but I don't know how to write it differently.

I should get such a SQL query.

```<code>SELECT staff_worker_info.id, staff_worker_info.first_name staff_worker_info.last_name, staff_worker_info.invited_id,
        (SELECT worker_invited.first_name
         FROM staff_worker_info AS worker_invited
         WHERE staff_worker_info.invited_id = worker_invited.id) AS invited_n,
FROM staff_worker_info
</code>```

答:
Might be a bit late, but I recently faced a similar question. I think your problem is quite easy to solve with only the relationship. If you want you can also solve it by using a column_property.

First, using the relationship. If you make the invited relationship joined, then the actual query that is send to the database is a self-join. You can access the first name via that relationship (reference https://docs.sqlalchemy.org/en/14/orm/self_referential.html).

class Worker(declarative_base()):
    __tablename__ = "staff_worker_info"

    id = Column(Integer, primary_key=True)
    first_name = Column(String(40), nullable=False)
    last_name = Column(String(40), nullable=False)

    invited_id = Column(Integer, ForeignKey('staff_worker_info.id'))
    invited = relationship("Worker", uselist=False, remote_side=[id], join_depth=1, lazy='joined')

    @property
    def invited_name(self):
        return self.invited.first_name
```
<p>Then, if the query you want to do is more complex, and it requires you to create a <code>column_property</code>, you can also do it as follows (reference https://docs.sqlalchemy.org/en/14/orm/mapped_sql_expr.html):</p>
<pre class="lang-py prettyprint-override"><code>from sqlalchemy import inspect
from sqlalchemy.orm import aliased

class Worker(declarative_base()):
    __tablename__ = "staff_worker_info"

    id = Column(Integer, primary_key=True)
    first_name = Column(String(40), nullable=False)
    last_name = Column(String(40), nullable=False)

    invited_id = Column(Integer, ForeignKey('staff_worker_info.id'))
    invited = relationship("Worker", uselist=False, remote_side=[id], join_depth=1)

# Requires alias
worker = aliased(Worker)
inspect(Worker).add_property(
   "invited_name",
   column_property(
         select([worker.first_name]). \
         where(worker.id == Worker.invited_id)
   )
)

</code>```

Body:
I can't describe the column "invited_name" (column_property). I don't know how to do this correctly.

class Worker(declarative_base()):
    __tablename__ = "staff_worker_info"

    id = Column(Integer, primary_key=True)
    first_name = Column(String(40), nullable=False)
    last_name = Column(String(40), nullable=False)

    invited_id = Column(Integer, ForeignKey('staff_worker_info.id'))
    invited = relationship("Worker", uselist=False, remote_side=[id], join_depth=1)

    # I don't know how to describe this column
    invited_name = column_property(
         select([Worker.first_name]). \
         where(Worker.id == invited_id).\
         label('invited_n'))

I understand why this doesn't work, but I don't know how to write it differently.

I should get such a SQL query.

SELECT staff_worker_info.id, staff_worker_info.first_name staff_worker_info.last_name, staff_worker_info.invited_id,
        (SELECT worker_invited.first_name
         FROM staff_worker_info AS worker_invited
         WHERE staff_worker_info.invited_id = worker_invited.id) AS invited_n,
FROM staff_worker_info

Body:
Might be a bit late, but I recently faced a similar question. I think your problem is quite easy to solve with only the relationship. If you want you can also solve it by using a column_property.

First, using the relationship. If you make the invited relationship joined, then the actual query that is send to the database is a self-join. You can access the first name via that relationship (reference https://docs.sqlalchemy.org/en/14/orm/self_referential.html).

class Worker(declarative_base()):
    __tablename__ = "staff_worker_info"

    id = Column(Integer, primary_key=True)
    first_name = Column(String(40), nullable=False)
    last_name = Column(String(40), nullable=False)

    invited_id = Column(Integer, ForeignKey('staff_worker_info.id'))
    invited = relationship("Worker", uselist=False, remote_side=[id], join_depth=1, lazy='joined')

    @property
    def invited_name(self):
        return self.invited.first_name

Then, if the query you want to do is more complex, and it requires you to create a column_property, you can also do it as follows (reference https://docs.sqlalchemy.org/en/14/orm/mapped_sql_expr.html):

from sqlalchemy import inspect
from sqlalchemy.orm import aliased

class Worker(declarative_base()):
    __tablename__ = "staff_worker_info"

    id = Column(Integer, primary_key=True)
    first_name = Column(String(40), nullable=False)
    last_name = Column(String(40), nullable=False)

    invited_id = Column(Integer, ForeignKey('staff_worker_info.id'))
    invited = relationship("Worker", uselist=False, remote_side=[id], join_depth=1)

# Requires alias
worker = aliased(Worker)
inspect(Worker).add_property(
   "invited_name",
   column_property(
         select([worker.first_name]). \
         where(worker.id == Worker.invited_id)
   )
)


问:
Why do I get strange result when & (anding) bits on __int64 variable?
Here is the code:

```<code>#include <iostream>

using namespace std;

template<class T>
void printbinary3(T num){
   for(int i = sizeof(T) * 8 - 1; i >= 0 ; --i) {
      if((1 << i) &  num)
         cout << "1";
      else
         cout << "0";
   }
   cout << endl;
}

int main ()
{
   char a = 1;
   short b = 1;
   int c = 1;
   long d = 1;
   __int64 e = 1;
   unsigned __int64 f = 1;

   printbinary3(a);
   printbinary3(b);
   printbinary3(c);
   printbinary3(d);
   printbinary3(e);
   printbinary3(f);
   return 0;
}
</code>```

Here is the output:

```
00000001
0000000000000001
00000000000000000000000000000001
00000000000000000000000000000001
0000000000000000000000000000000100000000000000000000000000000001
```

When compiling I get this error for the unsigned __int64 variable - f.

```<code>1> : warning C4334: '<<' : result of 32-bit shift implicitly converted to
     64 bits (was 64-bit shift intended?)
1>   xx.cpp(66) : see reference to function template instantiation
     'void printbinary3<unsigned __int64>(T)' being compiled
</code>```

Why am I not seeing

```
0000000000000000000000000000000000000000000000000000000000000001
```

as the output for the 64 bit integer?

Angus

答:
In your printbinary3 function:

```<code>void printbinary3(T num){
   for(int i = sizeof(T) * 8 - 1; i >= 0 ; --i) {
      if((1 << i) &  num)
</code>```

Here, you are creating a literal 1 of type int, which most probably is 32 bit.  If T = __int64, you will shift it for too many bits, leading to an overflow and the warning.

Instead of using implicit int, explicitely create a T instead:

```<code>      if((T(1) << i) &  num)
</code>```

This should fix the warning and the output.

Body:
Here is the code:

#include <iostream>

using namespace std;

template<class T>
void printbinary3(T num){
   for(int i = sizeof(T) * 8 - 1; i >= 0 ; --i) {
      if((1 << i) &  num)
         cout << "1";
      else
         cout << "0";
   }
   cout << endl;
}

int main ()
{
   char a = 1;
   short b = 1;
   int c = 1;
   long d = 1;
   __int64 e = 1;
   unsigned __int64 f = 1;

   printbinary3(a);
   printbinary3(b);
   printbinary3(c);
   printbinary3(d);
   printbinary3(e);
   printbinary3(f);
   return 0;
}

Here is the output:

00000001
0000000000000001
00000000000000000000000000000001
00000000000000000000000000000001
0000000000000000000000000000000100000000000000000000000000000001

When compiling I get this error for the unsigned __int64 variable - f.

1> : warning C4334: '<<' : result of 32-bit shift implicitly converted to
     64 bits (was 64-bit shift intended?)
1>   xx.cpp(66) : see reference to function template instantiation
     'void printbinary3<unsigned __int64>(T)' being compiled

Why am I not seeing

0000000000000000000000000000000000000000000000000000000000000001

as the output for the 64 bit integer?

Angus

Body:
In your printbinary3 function:

void printbinary3(T num){
   for(int i = sizeof(T) * 8 - 1; i >= 0 ; --i) {
      if((1 << i) &  num)

Here, you are creating a literal 1 of type int, which most probably is 32 bit.  If T = __int64, you will shift it for too many bits, leading to an overflow and the warning.

Instead of using implicit int, explicitely create a T instead:

      if((T(1) << i) &  num)

This should fix the warning and the output.


问:
How to do I sum these postgresql two tables and group by week and year?
I am trying to sum two tables sales + waste with results grouped by week and year. If I run each section by itself I get accurate results, but when I try my current query I get an error of "[42601] ERROR: subquery must return only one column"

This is what I currently have...

```<code>SELECT
(
    SELECT date_part('week', w."createdAt"),
        SUM("Quantity")
    FROM waste as w
     WHERE date_trunc('year', w."createdAt"::timestamptz at time zone 'America/Denver') =
           date_trunc('year', current_date - interval '1 year')
    group by 1
)
    +
(
    SELECT date_part('week', sh.”createdAt"),
           SUM(quantity)
    FROM sales_hourly as sh
    WHERE date_trunc('year', sh."createdAt"::timestamptz at time zone 'America/Denver') =
          date_trunc('year', current_date - interval '1 year')
    group by 1
) AS weekly_total
</code>```

答:
You can join both tables, but as both tables could have different weeks, you need a FULL OUTER JOIN which will cost time.

If it is guaranteed that both SELECTs have the same weeks , a INNER JOIN will suffice.

```<code>CREATE tABLE waste("createdAt" timestamp  , "Quantity" integer )
</code>```

```<code>CREATE tABLE sales_hourly("createdAt" timestamp  , "Quantity" integer)
</code>```

```<code>SELECT t1.week_t1,COALESCE(sum_t1,0) sum_waste,t2.week_t2,  COALESCE(sum_t2,0) sum_slaes
FROM
(
    SELECT date_part('week', w."createdAt") week_t1,
        SUM("Quantity") sum_t1
    FROM waste as w
     WHERE date_trunc('year', w."createdAt"::timestamptz at time zone 'America/Denver') =
           date_trunc('year', current_date - interval '1 year')
    group by 1
) t1
    FULL OUTER JOIN
(
    SELECT date_part('week', sh."createdAt") week_t2,
        SUM("Quantity") sum_t2
    FROM sales_hourly as sh
     WHERE date_trunc('year', sh."createdAt"::timestamptz at time zone 'America/Denver') =
           date_trunc('year', current_date - interval '1 year')
    group by 1) t2 ON t1.week_t1 = t2.week_t2
</code>```

```
week_t1 | sum_waste | week_t2 | sum_slaes
:------ | --------: | :------ | --------:
```

db<>fiddle here

Body:
I am trying to sum two tables sales + waste with results grouped by week and year. If I run each section by itself I get accurate results, but when I try my current query I get an error of "[42601] ERROR: subquery must return only one column"

This is what I currently have...

SELECT
(
    SELECT date_part('week', w."createdAt"),
        SUM("Quantity")
    FROM waste as w
     WHERE date_trunc('year', w."createdAt"::timestamptz at time zone 'America/Denver') =
           date_trunc('year', current_date - interval '1 year')
    group by 1
)
    +
(
    SELECT date_part('week', sh.”createdAt"),
           SUM(quantity)
    FROM sales_hourly as sh
    WHERE date_trunc('year', sh."createdAt"::timestamptz at time zone 'America/Denver') =
          date_trunc('year', current_date - interval '1 year')
    group by 1
) AS weekly_total

Body:
You can join both tables, but as both tables could have different weeks, you need a FULL OUTER JOIN which will cost time.

If it is guaranteed that both SELECTs have the same weeks , a INNER JOIN will suffice.

CREATE tABLE waste("createdAt" timestamp  , "Quantity" integer )

CREATE tABLE sales_hourly("createdAt" timestamp  , "Quantity" integer)

SELECT t1.week_t1,COALESCE(sum_t1,0) sum_waste,t2.week_t2,  COALESCE(sum_t2,0) sum_slaes
FROM
(
    SELECT date_part('week', w."createdAt") week_t1,
        SUM("Quantity") sum_t1
    FROM waste as w
     WHERE date_trunc('year', w."createdAt"::timestamptz at time zone 'America/Denver') =
           date_trunc('year', current_date - interval '1 year')
    group by 1
) t1
    FULL OUTER JOIN
(
    SELECT date_part('week', sh."createdAt") week_t2,
        SUM("Quantity") sum_t2
    FROM sales_hourly as sh
     WHERE date_trunc('year', sh."createdAt"::timestamptz at time zone 'America/Denver') =
           date_trunc('year', current_date - interval '1 year')
    group by 1) t2 ON t1.week_t1 = t2.week_t2

week_t1 | sum_waste | week_t2 | sum_slaes
:------ | --------: | :------ | --------:

db<>fiddle here


问:
How to modify request headers in Next.js
I have a need to add a header to each request to the server.

I do it this using _midleware like this:

```<code>export async function middleware(req: NextRequest): Promise<NextResponse> {
    req.headers.append('x-custom-header', '1337');
    return NextResponse.next();
}
</code>```

If I do console.log(req.headers) I see that the request header has been added:

```<code>BaseHeaders [Headers] {
    [Symbol(map)]: {
      accept: [ '*/*' ],
      'accept-encoding': [ 'gzip, deflate, br' ],
      'accept-language': [ 'en-GB,en-US;q=0.9,en;q=0.8' ],
      'cache-control': [ 'no-cache' ],
      connection: [ 'keep-alive' ],
      cookie: ...,
      host: ...,
      pragma: [ 'no-cache' ],
      referer: ...,
      ...,
      'x-custom-header': [ '1337' ]
    }
  }
</code>```

However, this does not modify the request: there is no request header in the browser.

Why is the request not modified? Are there alternative ways to modify request headers in Next.js?

答:
You can add custom headers in a similar way you would by adding security headers, by using headers in your next.config.js:

```<code>// next.config.js

// You can choose which headers to add to the list
// after learning more below.
const securityHeaders = []

module.exports = {
  async headers() {
    return [
      {
        // Apply these headers to all routes in your application.
        source: '/:path*',
        headers: securityHeaders,
      },
    ]
  },
}
</code>```

Body:
I have a need to add a header to each request to the server.

I do it this using _midleware like this:

export async function middleware(req: NextRequest): Promise<NextResponse> {
    req.headers.append('x-custom-header', '1337');
    return NextResponse.next();
}

If I do console.log(req.headers) I see that the request header has been added:

BaseHeaders [Headers] {
    [Symbol(map)]: {
      accept: [ '*/*' ],
      'accept-encoding': [ 'gzip, deflate, br' ],
      'accept-language': [ 'en-GB,en-US;q=0.9,en;q=0.8' ],
      'cache-control': [ 'no-cache' ],
      connection: [ 'keep-alive' ],
      cookie: ...,
      host: ...,
      pragma: [ 'no-cache' ],
      referer: ...,
      ...,
      'x-custom-header': [ '1337' ]
    }
  }

However, this does not modify the request: there is no request header in the browser.

Why is the request not modified? Are there alternative ways to modify request headers in Next.js?

Body:
You can add custom headers in a similar way you would by adding security headers, by using headers in your next.config.js:

// next.config.js

// You can choose which headers to add to the list
// after learning more below.
const securityHeaders = []

module.exports = {
  async headers() {
    return [
      {
        // Apply these headers to all routes in your application.
        source: '/:path*',
        headers: securityHeaders,
      },
    ]
  },
}


问:
Copy file from container to host using Dockerfile or Docker-compose
Good afternoon

I'm a new user of Docker and I have a question please:

I created a container named "container_worker" which running a Python script to create some data.
The data created is stored in the container in a file named "data".

I want to copy this "data" file to my host to be able to use it for another purpose.
I saw it's possible to do it with the "docker cp" command but I want to do it directly in my Dockerfile or my Docker-compose file.

Here are my files:

Dockerfile:

```<code>FROM archlinux

RUN pacman-db-upgrade \
&& pacman -Syyu --noconfirm \
&& pacman -S python --noconfirm \
&& pacman -S python-pip --noconfirm \
&& pip install requests

COPY /worker/script.py .

CMD python3 vmtracer.py >> data
</code>```

docker-compose.yml

```<code>version: "3"
services:
  worker:
    image: image_worker
    container_name: container_worker
    build:
      dockerfile: ./worker/Dockerfile
</code>```

Thank you very much.

答:
You can bind/mount volume from your local machine to container and put the output to that shared location.

Use command docker volume create my-vol , to create volume.

Use command docker volume ls ,to list your volumes.

Use parameter volumes: {your-volume-name} in docker-compose file to use the created volume.

Refer the link for more : https://docs.docker.com/storage/volumes/

Body:
Good afternoon

I'm a new user of Docker and I have a question please:

I created a container named "container_worker" which running a Python script to create some data.
The data created is stored in the container in a file named "data".

I want to copy this "data" file to my host to be able to use it for another purpose.
I saw it's possible to do it with the "docker cp" command but I want to do it directly in my Dockerfile or my Docker-compose file.

Here are my files:

Dockerfile:

FROM archlinux

RUN pacman-db-upgrade \
&& pacman -Syyu --noconfirm \
&& pacman -S python --noconfirm \
&& pacman -S python-pip --noconfirm \
&& pip install requests

COPY /worker/script.py .

CMD python3 vmtracer.py >> data

docker-compose.yml

version: "3"
services:
  worker:
    image: image_worker
    container_name: container_worker
    build:
      dockerfile: ./worker/Dockerfile

Thank you very much.


问:
SICP The Picture Language Exercise Lambda Argument
```<code>(define (segments->painter segment-list)
  (lambda (frame)
    (for-each
      (lambda (segment)
        (draw-line
          ((frame-coord-map frame)
           (start-segment segment))
          ((frame-coord-map frame)
           (end-segment segment))))
      segment-list)))
</code>```

Some of you have already seen this sicp example before but for the first timers a brief explanation: segments->painter procedure takes arguments from segment list which has values are segments made up from vectors. for-each procedure acts like map but instead returns a list of value, it does operations like printing or in this code it draws lines. frame-coord-map scales frames according to unit square frame. What I don't understand in this code is where does first lambda function takes its argument (frame) from.

答:
Let's look at a simpler example:

```<code>(define (adder x)
  (lambda (y)
    (+ x y))
</code>```

The analogous question would be, "Where does y come from, if you can call adder with only x?" As discussed in the comments, it comes from whoever calls the lambda that adder returns. You may write:

```<code>(define plus5 (adder 5))
(plus5 8) ; 13
(plus5 1) ; 6
</code>```

At the point that you call adder, there is no y. In the next call, y is 8, and after that it is 1.

Likewise in your actual code, there is no frame until someone calls the returned lambda.

Body:
(define (segments->painter segment-list)
  (lambda (frame)
    (for-each
      (lambda (segment)
        (draw-line
          ((frame-coord-map frame)
           (start-segment segment))
          ((frame-coord-map frame)
           (end-segment segment))))
      segment-list)))

Some of you have already seen this sicp example before but for the first timers a brief explanation: segments->painter procedure takes arguments from segment list which has values are segments made up from vectors. for-each procedure acts like map but instead returns a list of value, it does operations like printing or in this code it draws lines. frame-coord-map scales frames according to unit square frame. What I don't understand in this code is where does first lambda function takes its argument (frame) from.

Body:
Let's look at a simpler example:

(define (adder x)
  (lambda (y)
    (+ x y))

The analogous question would be, "Where does y come from, if you can call adder with only x?" As discussed in the comments, it comes from whoever calls the lambda that adder returns. You may write:

(define plus5 (adder 5))
(plus5 8) ; 13
(plus5 1) ; 6

At the point that you call adder, there is no y. In the next call, y is 8, and after that it is 1.

Likewise in your actual code, there is no frame until someone calls the returned lambda.