问:
webdev error when ran without pub on windows
I do AngularDart development on Windows 10. I'm getting strange behavior with webdev recently. I have to run webdev like this:

```<code>C:\Users\galankus>C:\tools\dart-sdk\bin\pub.bat global run webdev
A tool to develop Dart web projects.

Usage: webdev <command> [arguments]

Global options:
-h, --help    Print this usage information.

Available commands:
  build   Run builders to build a package.
  help    Display help information for webdev.
  serve   Run a local web development server and a file system watcher that re-builds on changes.

Run "webdev help <command>" for more information about a command.
</code>```

If I try to run it directly, the below is what I get. Any ideas on how I can debug/fix this?

```<code>C:\Users\galankus>webdev
Crash when formatting: [Encoding] Unable to decode bytes as UTF-8.
RangeError (index): Invalid value: Not in range 0..271500, inclusive: 271792
#0      _StringBase.[] (dart:core/runtime/libstring_patch.dart:233:55)
#1      Source.getTextLine (package:kernel/ast.dart:5772:42)
#2      getSourceLine (package:front_end/src/fasta/messages.dart:27:9)
#3      format (package:front_end/src/fasta/command_line_reporting.dart:80:27)
#4      ProcessedOptions.format (package:front_end/src/base/processed_options.dart:206:32)
#5      ProcessedOptions.report (package:front_end/src/base/processed_options.dart:215:22)
#6      CompilerContext.report (package:front_end/src/fasta/compiler_context.dart:67:13)
#7      Loader.addMessage (package:front_end/src/fasta/loader.dart:258:20)
#8      Loader.addCompileTimeError (package:front_end/src/fasta/loader.dart:207:5)
#9      LibraryBuilder.addCompileTimeError (package:front_end/src/fasta/builder/library_builder.dart:89:12)
#10     SourceLoader.tokenize (package:front_end/src/fasta/source/source_loader.dart:174:17)
<asynchronous suspension>
#11     SourceLoader.buildOutline (package:front_end/src/fasta/source/source_loader.dart:192:26)
<asynchronous suspension>
#12     Loader.buildOutlines (package:front_end/src/fasta/loader.dart:176:13)
<asynchronous suspension>
#13     KernelTarget.buildOutlines (package:front_end/src/fasta/kernel/kernel_target.dart:237:20)
<asynchronous suspension>
#14     IncrementalCompiler.computeDelta.<anonymous closure> (package:front_end/src/fasta/incremental_compiler.dart:232:24)
<asynchronous suspension>
#15     CompilerContext.runInContext.<anonymous closure>.<anonymous closure> (package:front_end/src/fasta/compiler_context.dart:118:46)
#16     new Future.sync (dart:async/future.dart:222:31)
#17     CompilerContext.runInContext.<anonymous closure> (package:front_end/src/fasta/compiler_context.dart:118:19)
#18     _rootRun (dart:async/zone.dart:1126:13)
#19     _CustomZone.run (dart:async/zone.dart:1023:19)
#20     _runZoned (dart:async/zone.dart:1518:10)
#21     runZoned (dart:async/zone.dart:1465:12)
#22     CompilerContext.runInContext (package:front_end/src/fasta/compiler_context.dart:117:12)
#23     IncrementalCompiler.computeDelta (package:front_end/src/fasta/incremental_compiler.dart:102:20)
<asynchronous suspension>
#24     IncrementalCompiler.compile (package:vm/incremental_compiler.dart:38:44)
<asynchronous suspension>
#25     IncrementalCompilerWrapper.compileInternal (file:///E:/b/build/slave/dart-sdk-windows-dev/build/sdk/pkg/vm/bin/kernel_service.dart:158:28)
<asynchronous suspension>
#26     Compiler.compile.<anonymous closure> (file:///E:/b/build/slave/dart-sdk-windows-dev/build/sdk/pkg/vm/bin/kernel_service.dart:132:39)
#27     new Future.<anonymous closure> (dart:async/future.dart:174:37)
#28     _rootRun (dart:async/zone.dart:1122:38)
#29     _CustomZone.run (dart:async/zone.dart:1023:19)
#30     _CustomZone.runGuarded (dart:async/zone.dart:925:7)
#31     _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:965:23)
#32     _rootRun (dart:async/zone.dart:1126:13)
#33     _CustomZone.run (dart:async/zone.dart:1023:19)
#34     _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:949:23)
#35     Timer._createTimer.<anonymous closure> (dart:async/runtime/libtimer_patch.dart:21:15)
#36     _Timer._runTimers (dart:isolate/runtime/libtimer_impl.dart:382:19)
#37     _Timer._handleMessage (dart:isolate/runtime/libtimer_impl.dart:416:5)
#38     _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:165:12)

Crash when compiling file:///C:/Users/galankus/AppData/Roaming/Pub/Cache/global_packages/webdev/bin/webdev.dart.snapshot,
at character offset 264110:
RangeError (index): Invalid value: Not in range 0..271500, inclusive: 271792
#0      _StringBase.[] (dart:core/runtime/libstring_patch.dart:233:55)
#1      Source.getTextLine (package:kernel/ast.dart:5772:42)
#2      getSourceLine (package:front_end/src/fasta/messages.dart:27:9)
#3      format (package:front_end/src/fasta/command_line_reporting.dart:80:27)
#4      ProcessedOptions.format (package:front_end/src/base/processed_options.dart:206:32)
#5      ProcessedOptions.report (package:front_end/src/base/processed_options.dart:215:22)
#6      CompilerContext.report (package:front_end/src/fasta/compiler_context.dart:67:13)
#7      Loader.addMessage (package:front_end/src/fasta/loader.dart:258:20)
#8      Loader.addCompileTimeError (package:front_end/src/fasta/loader.dart:207:5)
#9      LibraryBuilder.addCompileTimeError (package:front_end/src/fasta/builder/library_builder.dart:89:12)
#10     SourceLoader.tokenize (package:front_end/src/fasta/source/source_loader.dart:174:17)
<asynchronous suspension>
#11     SourceLoader.buildOutline (package:front_end/src/fasta/source/source_loader.dart:192:26)
<asynchronous suspension>
#12     Loader.buildOutlines (package:front_end/src/fasta/loader.dart:176:13)
<asynchronous suspension>
#13     KernelTarget.buildOutlines (package:front_end/src/fasta/kernel/kernel_target.dart:237:20)
<asynchronous suspension>
#14     IncrementalCompiler.computeDelta.<anonymous closure> (package:front_end/src/fasta/incremental_compiler.dart:232:24)
<asynchronous suspension>
#15     CompilerContext.runInContext.<anonymous closure>.<anonymous closure> (package:front_end/src/fasta/compiler_context.dart:118:46)
#16     new Future.sync (dart:async/future.dart:222:31)
#17     CompilerContext.runInContext.<anonymous closure> (package:front_end/src/fasta/compiler_context.dart:118:19)
#18     _rootRun (dart:async/zone.dart:1126:13)
#19     _CustomZone.run (dart:async/zone.dart:1023:19)
#20     _runZoned (dart:async/zone.dart:1518:10)
#21     runZoned (dart:async/zone.dart:1465:12)
#22     CompilerContext.runInContext (package:front_end/src/fasta/compiler_context.dart:117:12)
#23     IncrementalCompiler.computeDelta (package:front_end/src/fasta/incremental_compiler.dart:102:20)
<asynchronous suspension>
#24     IncrementalCompiler.compile (package:vm/incremental_compiler.dart:38:44)
<asynchronous suspension>
#25     IncrementalCompilerWrapper.compileInternal (file:///E:/b/build/slave/dart-sdk-windows-dev/build/sdk/pkg/vm/bin/kernel_service.dart:158:28)
<asynchronous suspension>
#26     Compiler.compile.<anonymous closure> (file:///E:/b/build/slave/dart-sdk-windows-dev/build/sdk/pkg/vm/bin/kernel_service.dart:132:39)
#27     new Future.<anonymous closure> (dart:async/future.dart:174:37)
#28     _rootRun (dart:async/zone.dart:1122:38)
#29     _CustomZone.run (dart:async/zone.dart:1023:19)
#30     _CustomZone.runGuarded (dart:async/zone.dart:925:7)
#31     _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:965:23)
#32     _rootRun (dart:async/zone.dart:1126:13)
#33     _CustomZone.run (dart:async/zone.dart:1023:19)
#34     _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:949:23)
#35     Timer._createTimer.<anonymous closure> (dart:async/runtime/libtimer_patch.dart:21:15)
#36     _Timer._runTimers (dart:isolate/runtime/libtimer_impl.dart:382:19)
#37     _Timer._handleMessage (dart:isolate/runtime/libtimer_impl.dart:416:5)
#38     _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:165:12)

#0      _StringBase.[] (dart:core/runtime/libstring_patch.dart:233:55)
#1      Source.getTextLine (package:kernel/ast.dart:5772:42)
#2      getSourceLine (package:front_end/src/fasta/messages.dart:27:9)
#3      format (package:front_end/src/fasta/command_line_reporting.dart:80:27)
#4      ProcessedOptions.format (package:front_end/src/base/processed_options.dart:206:32)
#5      ProcessedOptions.report (package:front_end/src/base/processed_options.dart:215:22)
#6      CompilerContext.report (package:front_end/src/fasta/compiler_context.dart:67:13)
#7      Loader.addMessage (package:front_end/src/fasta/loader.dart:258:20)
#8      Loader.addCompileTimeError (package:front_end/src/fasta/loader.dart:207:5)
#9      LibraryBuilder.addCompileTimeError (package:front_end/src/fasta/builder/library_builder.dart:89:12)
#10     SourceLoader.tokenize (package:front_end/src/fasta/source/source_loader.dart:174:17)
<asynchronous suspension>
#11     SourceLoader.buildOutline (package:front_end/src/fasta/source/source_loader.dart:192:26)
<asynchronous suspension>
#12     Loader.buildOutlines (package:front_end/src/fasta/loader.dart:176:13)
<asynchronous suspension>
#13     KernelTarget.buildOutlines (package:front_end/src/fasta/kernel/kernel_target.dart:237:20)
<asynchronous suspension>
#14     IncrementalCompiler.computeDelta.<anonymous closure> (package:front_end/src/fasta/incremental_compiler.dart:232:24)
<asynchronous suspension>
#15     CompilerContext.runInContext.<anonymous closure>.<anonymous closure> (package:front_end/src/fasta/compiler_context.dart:118:46)
#16     new Future.sync (dart:async/future.dart:222:31)
#17     CompilerContext.runInContext.<anonymous closure> (package:front_end/src/fasta/compiler_context.dart:118:19)
#18     _rootRun (dart:async/zone.dart:1126:13)
#19     _CustomZone.run (dart:async/zone.dart:1023:19)
#20     _runZoned (dart:async/zone.dart:1518:10)
#21     runZoned (dart:async/zone.dart:1465:12)
#22     CompilerContext.runInContext (package:front_end/src/fasta/compiler_context.dart:117:12)
#23     IncrementalCompiler.computeDelta (package:front_end/src/fasta/incremental_compiler.dart:102:20)
<asynchronous suspension>
#24     IncrementalCompiler.compile (package:vm/incremental_compiler.dart:38:44)
<asynchronous suspension>
#25     IncrementalCompilerWrapper.compileInternal (file:///E:/b/build/slave/dart-sdk-windows-dev/build/sdk/pkg/vm/bin/kernel_service.dart:158:28)
<asynchronous suspension>
#26     Compiler.compile.<anonymous closure> (file:///E:/b/build/slave/dart-sdk-windows-dev/build/sdk/pkg/vm/bin/kernel_service.dart:132:39)
#27     new Future.<anonymous closure> (dart:async/future.dart:174:37)
#28     _rootRun (dart:async/zone.dart:1122:38)
#29     _CustomZone.run (dart:async/zone.dart:1023:19)
#30     _CustomZone.runGuarded (dart:async/zone.dart:925:7)
#31     _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:965:23)
#32     _rootRun (dart:async/zone.dart:1126:13)
#33     _CustomZone.run (dart:async/zone.dart:1023:19)
#34     _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:949:23)
#35     Timer._createTimer.<anonymous closure> (dart:async/runtime/libtimer_patch.dart:21:15)
#36     _Timer._runTimers (dart:isolate/runtime/libtimer_impl.dart:382:19)
#37     _Timer._handleMessage (dart:isolate/runtime/libtimer_impl.dart:416:5)
#38     _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:165:12)
</code>```

Edit: the below did not change anything, I still get the error above.

```<code>C:\Users\galankus>pub global activate webdev
Package webdev is currently active at version 0.2.3.
Resolving dependencies...
+ args 1.4.3
+ charcode 1.1.1
+ collection 1.14.10
+ io 0.3.2+1
+ meta 1.1.5
+ path 1.6.1
+ pub_semver 1.4.1
+ source_span 1.4.0
+ stack_trace 1.9.2
+ string_scanner 1.0.2
+ webdev 0.2.3
+ yaml 2.1.14
Precompiling executables...
Precompiled webdev:bin\webdev.
Installed executable webdev.
Activated webdev 0.2.3.
</code>```

答:
Use this Command to activate WebDev</p>
```<code>dart pub global activate webdev
</code>```

Body:
I do AngularDart development on Windows 10. I'm getting strange behavior with webdev recently. I have to run webdev like this:

C:\Users\galankus>C:\tools\dart-sdk\bin\pub.bat global run webdev
A tool to develop Dart web projects.

Usage: webdev <command> [arguments]

Global options:
-h, --help    Print this usage information.

Available commands:
  build   Run builders to build a package.
  help    Display help information for webdev.
  serve   Run a local web development server and a file system watcher that re-builds on changes.

Run "webdev help <command>" for more information about a command.

If I try to run it directly, the below is what I get. Any ideas on how I can debug/fix this?

C:\Users\galankus>webdev
Crash when formatting: [Encoding] Unable to decode bytes as UTF-8.
RangeError (index): Invalid value: Not in range 0..271500, inclusive: 271792
#0      _StringBase.[] (dart:core/runtime/libstring_patch.dart:233:55)
#1      Source.getTextLine (package:kernel/ast.dart:5772:42)
#2      getSourceLine (package:front_end/src/fasta/messages.dart:27:9)
#3      format (package:front_end/src/fasta/command_line_reporting.dart:80:27)
#4      ProcessedOptions.format (package:front_end/src/base/processed_options.dart:206:32)
#5      ProcessedOptions.report (package:front_end/src/base/processed_options.dart:215:22)
#6      CompilerContext.report (package:front_end/src/fasta/compiler_context.dart:67:13)
#7      Loader.addMessage (package:front_end/src/fasta/loader.dart:258:20)
#8      Loader.addCompileTimeError (package:front_end/src/fasta/loader.dart:207:5)
#9      LibraryBuilder.addCompileTimeError (package:front_end/src/fasta/builder/library_builder.dart:89:12)
#10     SourceLoader.tokenize (package:front_end/src/fasta/source/source_loader.dart:174:17)
<asynchronous suspension>
#11     SourceLoader.buildOutline (package:front_end/src/fasta/source/source_loader.dart:192:26)
<asynchronous suspension>
#12     Loader.buildOutlines (package:front_end/src/fasta/loader.dart:176:13)
<asynchronous suspension>
#13     KernelTarget.buildOutlines (package:front_end/src/fasta/kernel/kernel_target.dart:237:20)
<asynchronous suspension>
#14     IncrementalCompiler.computeDelta.<anonymous closure> (package:front_end/src/fasta/incremental_compiler.dart:232:24)
<asynchronous suspension>
#15     CompilerContext.runInContext.<anonymous closure>.<anonymous closure> (package:front_end/src/fasta/compiler_context.dart:118:46)
#16     new Future.sync (dart:async/future.dart:222:31)
#17     CompilerContext.runInContext.<anonymous closure> (package:front_end/src/fasta/compiler_context.dart:118:19)
#18     _rootRun (dart:async/zone.dart:1126:13)
#19     _CustomZone.run (dart:async/zone.dart:1023:19)
#20     _runZoned (dart:async/zone.dart:1518:10)
#21     runZoned (dart:async/zone.dart:1465:12)
#22     CompilerContext.runInContext (package:front_end/src/fasta/compiler_context.dart:117:12)
#23     IncrementalCompiler.computeDelta (package:front_end/src/fasta/incremental_compiler.dart:102:20)
<asynchronous suspension>
#24     IncrementalCompiler.compile (package:vm/incremental_compiler.dart:38:44)
<asynchronous suspension>
#25     IncrementalCompilerWrapper.compileInternal (file:///E:/b/build/slave/dart-sdk-windows-dev/build/sdk/pkg/vm/bin/kernel_service.dart:158:28)
<asynchronous suspension>
#26     Compiler.compile.<anonymous closure> (file:///E:/b/build/slave/dart-sdk-windows-dev/build/sdk/pkg/vm/bin/kernel_service.dart:132:39)
#27     new Future.<anonymous closure> (dart:async/future.dart:174:37)
#28     _rootRun (dart:async/zone.dart:1122:38)
#29     _CustomZone.run (dart:async/zone.dart:1023:19)
#30     _CustomZone.runGuarded (dart:async/zone.dart:925:7)
#31     _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:965:23)
#32     _rootRun (dart:async/zone.dart:1126:13)
#33     _CustomZone.run (dart:async/zone.dart:1023:19)
#34     _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:949:23)
#35     Timer._createTimer.<anonymous closure> (dart:async/runtime/libtimer_patch.dart:21:15)
#36     _Timer._runTimers (dart:isolate/runtime/libtimer_impl.dart:382:19)
#37     _Timer._handleMessage (dart:isolate/runtime/libtimer_impl.dart:416:5)
#38     _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:165:12)

Crash when compiling file:///C:/Users/galankus/AppData/Roaming/Pub/Cache/global_packages/webdev/bin/webdev.dart.snapshot,
at character offset 264110:
RangeError (index): Invalid value: Not in range 0..271500, inclusive: 271792
#0      _StringBase.[] (dart:core/runtime/libstring_patch.dart:233:55)
#1      Source.getTextLine (package:kernel/ast.dart:5772:42)
#2      getSourceLine (package:front_end/src/fasta/messages.dart:27:9)
#3      format (package:front_end/src/fasta/command_line_reporting.dart:80:27)
#4      ProcessedOptions.format (package:front_end/src/base/processed_options.dart:206:32)
#5      ProcessedOptions.report (package:front_end/src/base/processed_options.dart:215:22)
#6      CompilerContext.report (package:front_end/src/fasta/compiler_context.dart:67:13)
#7      Loader.addMessage (package:front_end/src/fasta/loader.dart:258:20)
#8      Loader.addCompileTimeError (package:front_end/src/fasta/loader.dart:207:5)
#9      LibraryBuilder.addCompileTimeError (package:front_end/src/fasta/builder/library_builder.dart:89:12)
#10     SourceLoader.tokenize (package:front_end/src/fasta/source/source_loader.dart:174:17)
<asynchronous suspension>
#11     SourceLoader.buildOutline (package:front_end/src/fasta/source/source_loader.dart:192:26)
<asynchronous suspension>
#12     Loader.buildOutlines (package:front_end/src/fasta/loader.dart:176:13)
<asynchronous suspension>
#13     KernelTarget.buildOutlines (package:front_end/src/fasta/kernel/kernel_target.dart:237:20)
<asynchronous suspension>
#14     IncrementalCompiler.computeDelta.<anonymous closure> (package:front_end/src/fasta/incremental_compiler.dart:232:24)
<asynchronous suspension>
#15     CompilerContext.runInContext.<anonymous closure>.<anonymous closure> (package:front_end/src/fasta/compiler_context.dart:118:46)
#16     new Future.sync (dart:async/future.dart:222:31)
#17     CompilerContext.runInContext.<anonymous closure> (package:front_end/src/fasta/compiler_context.dart:118:19)
#18     _rootRun (dart:async/zone.dart:1126:13)
#19     _CustomZone.run (dart:async/zone.dart:1023:19)
#20     _runZoned (dart:async/zone.dart:1518:10)
#21     runZoned (dart:async/zone.dart:1465:12)
#22     CompilerContext.runInContext (package:front_end/src/fasta/compiler_context.dart:117:12)
#23     IncrementalCompiler.computeDelta (package:front_end/src/fasta/incremental_compiler.dart:102:20)
<asynchronous suspension>
#24     IncrementalCompiler.compile (package:vm/incremental_compiler.dart:38:44)
<asynchronous suspension>
#25     IncrementalCompilerWrapper.compileInternal (file:///E:/b/build/slave/dart-sdk-windows-dev/build/sdk/pkg/vm/bin/kernel_service.dart:158:28)
<asynchronous suspension>
#26     Compiler.compile.<anonymous closure> (file:///E:/b/build/slave/dart-sdk-windows-dev/build/sdk/pkg/vm/bin/kernel_service.dart:132:39)
#27     new Future.<anonymous closure> (dart:async/future.dart:174:37)
#28     _rootRun (dart:async/zone.dart:1122:38)
#29     _CustomZone.run (dart:async/zone.dart:1023:19)
#30     _CustomZone.runGuarded (dart:async/zone.dart:925:7)
#31     _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:965:23)
#32     _rootRun (dart:async/zone.dart:1126:13)
#33     _CustomZone.run (dart:async/zone.dart:1023:19)
#34     _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:949:23)
#35     Timer._createTimer.<anonymous closure> (dart:async/runtime/libtimer_patch.dart:21:15)
#36     _Timer._runTimers (dart:isolate/runtime/libtimer_impl.dart:382:19)
#37     _Timer._handleMessage (dart:isolate/runtime/libtimer_impl.dart:416:5)
#38     _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:165:12)

#0      _StringBase.[] (dart:core/runtime/libstring_patch.dart:233:55)
#1      Source.getTextLine (package:kernel/ast.dart:5772:42)
#2      getSourceLine (package:front_end/src/fasta/messages.dart:27:9)
#3      format (package:front_end/src/fasta/command_line_reporting.dart:80:27)
#4      ProcessedOptions.format (package:front_end/src/base/processed_options.dart:206:32)
#5      ProcessedOptions.report (package:front_end/src/base/processed_options.dart:215:22)
#6      CompilerContext.report (package:front_end/src/fasta/compiler_context.dart:67:13)
#7      Loader.addMessage (package:front_end/src/fasta/loader.dart:258:20)
#8      Loader.addCompileTimeError (package:front_end/src/fasta/loader.dart:207:5)
#9      LibraryBuilder.addCompileTimeError (package:front_end/src/fasta/builder/library_builder.dart:89:12)
#10     SourceLoader.tokenize (package:front_end/src/fasta/source/source_loader.dart:174:17)
<asynchronous suspension>
#11     SourceLoader.buildOutline (package:front_end/src/fasta/source/source_loader.dart:192:26)
<asynchronous suspension>
#12     Loader.buildOutlines (package:front_end/src/fasta/loader.dart:176:13)
<asynchronous suspension>
#13     KernelTarget.buildOutlines (package:front_end/src/fasta/kernel/kernel_target.dart:237:20)
<asynchronous suspension>
#14     IncrementalCompiler.computeDelta.<anonymous closure> (package:front_end/src/fasta/incremental_compiler.dart:232:24)
<asynchronous suspension>
#15     CompilerContext.runInContext.<anonymous closure>.<anonymous closure> (package:front_end/src/fasta/compiler_context.dart:118:46)
#16     new Future.sync (dart:async/future.dart:222:31)
#17     CompilerContext.runInContext.<anonymous closure> (package:front_end/src/fasta/compiler_context.dart:118:19)
#18     _rootRun (dart:async/zone.dart:1126:13)
#19     _CustomZone.run (dart:async/zone.dart:1023:19)
#20     _runZoned (dart:async/zone.dart:1518:10)
#21     runZoned (dart:async/zone.dart:1465:12)
#22     CompilerContext.runInContext (package:front_end/src/fasta/compiler_context.dart:117:12)
#23     IncrementalCompiler.computeDelta (package:front_end/src/fasta/incremental_compiler.dart:102:20)
<asynchronous suspension>
#24     IncrementalCompiler.compile (package:vm/incremental_compiler.dart:38:44)
<asynchronous suspension>
#25     IncrementalCompilerWrapper.compileInternal (file:///E:/b/build/slave/dart-sdk-windows-dev/build/sdk/pkg/vm/bin/kernel_service.dart:158:28)
<asynchronous suspension>
#26     Compiler.compile.<anonymous closure> (file:///E:/b/build/slave/dart-sdk-windows-dev/build/sdk/pkg/vm/bin/kernel_service.dart:132:39)
#27     new Future.<anonymous closure> (dart:async/future.dart:174:37)
#28     _rootRun (dart:async/zone.dart:1122:38)
#29     _CustomZone.run (dart:async/zone.dart:1023:19)
#30     _CustomZone.runGuarded (dart:async/zone.dart:925:7)
#31     _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:965:23)
#32     _rootRun (dart:async/zone.dart:1126:13)
#33     _CustomZone.run (dart:async/zone.dart:1023:19)
#34     _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:949:23)
#35     Timer._createTimer.<anonymous closure> (dart:async/runtime/libtimer_patch.dart:21:15)
#36     _Timer._runTimers (dart:isolate/runtime/libtimer_impl.dart:382:19)
#37     _Timer._handleMessage (dart:isolate/runtime/libtimer_impl.dart:416:5)
#38     _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:165:12)

Edit: the below did not change anything, I still get the error above.

C:\Users\galankus>pub global activate webdev
Package webdev is currently active at version 0.2.3.
Resolving dependencies...
+ args 1.4.3
+ charcode 1.1.1
+ collection 1.14.10
+ io 0.3.2+1
+ meta 1.1.5
+ path 1.6.1
+ pub_semver 1.4.1
+ source_span 1.4.0
+ stack_trace 1.9.2
+ string_scanner 1.0.2
+ webdev 0.2.3
+ yaml 2.1.14
Precompiling executables...
Precompiled webdev:bin\webdev.
Installed executable webdev.
Activated webdev 0.2.3.

Body:
Use this Command to activate WebDev

dart pub global activate webdev


来源: stackexchange

问:
Pandas: how to index dataframe for certain value or string without knowing the column name
Although it seems very detrimental, I am having a hard time getting the index of a dataframe for a certain string or value at a random position in the dataframe.

I made an example dataframe:

```<code>fruits = {
    'column1':["Apples","Pears","Bananas","Oranges","Strawberries"],
    'column2':[1,2,3,4,5],
    'column3':["Kiwis","Mangos","Pineapples","Grapes","Melons"]
          }

df = pd.DataFrame(fruits)

        column1  column2     column3
0        Apples        1       Kiwis
1         Pears        2      Mangos
2       Bananas        3  Pineapples
3       Oranges        4      Grapes
4  Strawberries        5      Melons
</code>```

Now I want to get the position index of Mangos, without having the knowledge in which column or row it exists. So far I succeeded in getting the row index:

```<code>print(df.loc[df.isin(["Mangos"]).any(axis=1)].index)
</code>```

Which results in:

```<code>Int64Index([1], dtype='int64')
</code>```

But now I would also like to retrieve the column index or column name.

This thread is a very simplified version of Get column name where value is something in pandas dataframe, but I could not figure out the code using the other thread.

答:
You can simply do:

```<code>df.columns[df.isin(['Mangos']).any()])
</code>```
```<code>Index(['column3'], dtype='object')
</code>```

Or to just get the column name:

```<code>df.columns[df.isin(['Mangos']).any()][0]
# column3
</code>```

To get the index of the column, try:

```<code>df.columns.get_indexer(df.columns[df.isin(['Mangos']).any()])
# [2]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Although it seems very detrimental, I am having a hard time getting the index of a dataframe for a certain string or value at a random position in the dataframe.

I made an example dataframe:

fruits = {
    'column1':["Apples","Pears","Bananas","Oranges","Strawberries"],
    'column2':[1,2,3,4,5],
    'column3':["Kiwis","Mangos","Pineapples","Grapes","Melons"]
          }

df = pd.DataFrame(fruits)

        column1  column2     column3
0        Apples        1       Kiwis
1         Pears        2      Mangos
2       Bananas        3  Pineapples
3       Oranges        4      Grapes
4  Strawberries        5      Melons

Now I want to get the position index of Mangos, without having the knowledge in which column or row it exists. So far I succeeded in getting the row index:

print(df.loc[df.isin(["Mangos"]).any(axis=1)].index)

Which results in:

Int64Index([1], dtype='int64')

But now I would also like to retrieve the column index or column name.

This thread is a very simplified version of Get column name where value is something in pandas dataframe, but I could not figure out the code using the other thread.

Body:
You can simply do:

df.columns[df.isin(['Mangos']).any()])

Index(['column3'], dtype='object')

Or to just get the column name:

df.columns[df.isin(['Mangos']).any()][0]
# column3

To get the index of the column, try:

df.columns.get_indexer(df.columns[df.isin(['Mangos']).any()])
# [2]


问:
Application exit with code -8 before even tries to divide by 0?
I have code like this:

```<code>#include <stdio.h>
#include <stdint.h>

int main() {
    uint8_t result = 0;
    uint8_t a = 0;
    printf("Trying to divide by %d...\n", a);
    result = (1/a != 0);
    printf("%d\n", result);

    return 0;
}
</code>```

I have tried this in online compiler here: https://www.mycompiler.io/new/c

And this is the result:

[Execution complete with exit code -8]

I expected "Trying to divide by 0..." to be printed out, and then application should exit.

But the application exits before it prints anything.

Is it normal C behavior or some glitch of online compiler?

答:
I can see two possible explanations here

First, it's important to know that undefined behavior can time travel back in time. There is no guarantee that the program will run fine until the problematic line. This may occur because the compiler might think that it would be better to reorder things like this:

```<code>uint8_t a = 0;
uint8_t result = (1/a != 0);
printf("Trying to divide by %d...\n", a);
</code>```

The compiler is allowed to do this, because it's allowed to assume that division by zero will never happen.

Second, it could be the case that the output needs to be flushed. Whenever you want to make sure that a printout gets visible on screen before doing something else, use fflush(stdout). It might make a difference if you do this:

```<code>printf("Trying to divide by %d...\n", a);
fflush(stdout);
result = (1/a != 0);
</code>```

Body:
I have code like this:

#include <stdio.h>
#include <stdint.h>

int main() {
    uint8_t result = 0;
    uint8_t a = 0;
    printf("Trying to divide by %d...\n", a);
    result = (1/a != 0);
    printf("%d\n", result);

    return 0;
}

I have tried this in online compiler here: https://www.mycompiler.io/new/c

And this is the result:

[Execution complete with exit code -8]

I expected "Trying to divide by 0..." to be printed out, and then application should exit.

But the application exits before it prints anything.

Is it normal C behavior or some glitch of online compiler?

Body:
I can see two possible explanations here

First, it's important to know that undefined behavior can time travel back in time. There is no guarantee that the program will run fine until the problematic line. This may occur because the compiler might think that it would be better to reorder things like this:

uint8_t a = 0;
uint8_t result = (1/a != 0);
printf("Trying to divide by %d...\n", a);

The compiler is allowed to do this, because it's allowed to assume that division by zero will never happen.

Second, it could be the case that the output needs to be flushed. Whenever you want to make sure that a printout gets visible on screen before doing something else, use fflush(stdout). It might make a difference if you do this:

printf("Trying to divide by %d...\n", a);
fflush(stdout);
result = (1/a != 0);


问:
How to 'melt' a wide table/array in google app script?
I have an array/table in Google Sheets with data in the following format:

Catergory1
A
A
A
A
A
B
B
B
B
B
C
C
C
C
C

Catergory2
Q1
Q2
Q3
Q4
Q5
Q1
Q2
Q3
Q4
Q5
Q1
Q2
Q3
Q4
Q5

Propotions
34%
66%
9%
49%
31%
36%
69%
1%
10%
20%
98%
38%
21%
57%
76%

I want to use Google App Script to convert this array into the following format:

Catergory1
Q1
Q2
Q3
Q4
Q5

A
34%
66%
9%
49%
31%

B
36%
69%
1%
10%
20%

C
98%
38%
21%
57%
76%

Thanks in advance.

答:
Here is my variant:

```<code>function myFunction() {
  var sheet = SpreadsheetApp.getActiveSheet();

  // get the data (without first column)
  var data = sheet.getDataRange().getDisplayValues().map(x => x.slice(1));

  // get rows and columns names
  var rows = Array.from(new Set(data[0])); // A, B, C...
  var cols = Array.from(new Set(data[1])); // Q1, Q2, Q3...

  // create the empty table
  var table = Array(rows.length).fill('')
    .map(x => x = Array(cols.length).fill(''));

  // fill the table with values from third row of data ('Proportions')
  for (let i in data[0]) {
    let row = rows.indexOf(data[0][i]);
    let col = cols.indexOf(data[1][i]);
    table[row][col] = data[2][i];
  }

  // add the header and first column (A,B,C...) to the table
  var header = ['Category', ...cols];
  var body = table.map((x,i) => [rows[i], ...x]);
  table = [header, ...body];

  // put the table on the sheet
  sheet.clear().getRange(1,1,table.length,table[0].length).setValues(table);

  // set font of the header to 'Bold'
  sheet.getRange(1,1,1,sheet.getLastColumn()).setFontWeight('Bold');
}
</code>```

It should work for any number of categories and letters. And it doesn't even need to sort the columns, they can be like: Q1, Q3, Q1, Q2... etc

If your data always sorted the script can be a little bit simpler and probably more efficient:

function myFunction2() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var data = sheet.getDataRange().getDisplayValues();

  var letters = Array.from(new Set(data[0].slice(1)));    // A,B,C
  var categories = Array.from(new Set(data[1].slice(1))); // Q1,Q2,Q3,Q4,Q5
  var proportions = data[2].slice(1);                     // %,%,%...

  // make a table from the proportions
  var table = [];
  var rows = letters.length
  while (rows--) {
    var row = [];
    var cols = categories.length;
    while (cols--) row.push(proportions.shift());
    table.push(row);
  }

  // add a header and first column to the table
  var header = ['Categories', ...categories];
  var body = table.map(x => [letters.shift(), ...x]);
  table = [header, ...body];

  // put the table on the sheet
  sheet.clear().getRange(1,1,table.length,table[0].length).setValues(table);
}```

Body:
Here is my variant:

function myFunction() {
  var sheet = SpreadsheetApp.getActiveSheet();

  // get the data (without first column)
  var data = sheet.getDataRange().getDisplayValues().map(x => x.slice(1));

  // get rows and columns names
  var rows = Array.from(new Set(data[0])); // A, B, C...
  var cols = Array.from(new Set(data[1])); // Q1, Q2, Q3...

  // create the empty table
  var table = Array(rows.length).fill('')
    .map(x => x = Array(cols.length).fill(''));

  // fill the table with values from third row of data ('Proportions')
  for (let i in data[0]) {
    let row = rows.indexOf(data[0][i]);
    let col = cols.indexOf(data[1][i]);
    table[row][col] = data[2][i];
  }

  // add the header and first column (A,B,C...) to the table
  var header = ['Category', ...cols];
  var body = table.map((x,i) => [rows[i], ...x]);
  table = [header, ...body];

  // put the table on the sheet
  sheet.clear().getRange(1,1,table.length,table[0].length).setValues(table);

  // set font of the header to 'Bold'
  sheet.getRange(1,1,1,sheet.getLastColumn()).setFontWeight('Bold');
}

It should work for any number of categories and letters. And it doesn't even need to sort the columns, they can be like: Q1, Q3, Q1, Q2... etc

If your data always sorted the script can be a little bit simpler and probably more efficient:

function myFunction2() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var data = sheet.getDataRange().getDisplayValues();

  var letters = Array.from(new Set(data[0].slice(1)));    // A,B,C
  var categories = Array.from(new Set(data[1].slice(1))); // Q1,Q2,Q3,Q4,Q5
  var proportions = data[2].slice(1);                     // %,%,%...

  // make a table from the proportions
  var table = [];
  var rows = letters.length
  while (rows--) {
    var row = [];
    var cols = categories.length;
    while (cols--) row.push(proportions.shift());
    table.push(row);
  }

  // add a header and first column to the table
  var header = ['Categories', ...categories];
  var body = table.map(x => [letters.shift(), ...x]);
  table = [header, ...body];

  // put the table on the sheet
  sheet.clear().getRange(1,1,table.length,table[0].length).setValues(table);
}


问:
How to store data from a .TIFF file to then modify it with my C program
I know few about this and i'm trying to keep building upon it. My goal is to do image stacking with some criteria using C language, as i came upon some cool ideas i think i should be capable of doing with my photos. My C background should be enough to understand what i may need. That being said...

So far i've learned how to read an existing .TIFF file and save it into a char array. The problem is i don't know in which way its data is contained so that i can then be able to analize individual pixels and modify them, or build another .TIFF file from data i previously read.
I've read some things about (a so called) libtiff.h which may be usefull but i can't find where to get it, neither how to install it.

Does anyone know how a .TIFF file data is stored so that i can read it and apply changes to it?

Also,
Does anyone have any experience with handling image files and editing in C? Where did you learn it from?
Do you know of any place i could search for information/tutorials?

Any help will be very usefull,
Thanks in advance.

答:
You can do an enormous amount of very sophisticated processing on TIFFs, or any one of 190+ other formats with ImageMagick without any need to understand TIFF format or write any C. Try searching on Stack Overflow for [imagemagick]

If you want to do processing yourself, consider https://cimg.eu

Another option might be to convert your TIFFs to NetPBM which is much, much simpler to read and write in C. That would be as follows with ImageMagick:

```<code>magick INPUT.TIFF -compress none OUTPUT.PPM
</code>```

Body:
You can do an enormous amount of very sophisticated processing on TIFFs, or any one of 190+ other formats with ImageMagick without any need to understand TIFF format or write any C. Try searching on Stack Overflow for [imagemagick]

If you want to do processing yourself, consider https://cimg.eu

Another option might be to convert your TIFFs to NetPBM which is much, much simpler to read and write in C. That would be as follows with ImageMagick:

magick INPUT.TIFF -compress none OUTPUT.PPM


问:
Issue dispatching an overloaded operator to base in C++
Please forgive me if I fundamentally misunderstand something about dispatch in C++!

The code as pasted below works as intended.

However, if I uncomment/add the additional operator<< method in Derived (which should handle a different agrument type), C++ is then unable to resolve the previously-working dispatch "*this << something" (which, in the absence of that method, is successfully dispatched to Base as intended).

It says:

main.cpp:25:15: Invalid operands to binary expression ('Derived' and 'Something')

Please could someone explain to me why this happens?

Thanks in advance

(Mac OS Monterey 12.2.1, xCode 13.2.1)

```<code>#include <iostream>

class Something { };
class SomethingUnrelated { };

class Base {
public:
    virtual void method() = 0;
    void operator<<(Something something) {
        method();
    }
};

class Derived : public Base {
public:
    void method() { std::cout << "Derived::method() - Yay!" << std::endl; }
    void work(Something something) {
        *this << something;
    }
    // void operator<<(SomethingUnrelated somethingUnrelated) { }
};

int main(int argc, const char * argv[]) {
    Something something;
    Derived derived;
    derived.work(something);
    return 0;
}
</code>```

答:
The names in the parent class are hidden while building a lookup set for the unqualified name lookup. You may bring the parent's operator to a child lookup set by using directive. I can't find the duplicated question, but I'm pretty sure the duplicated question exists.

```<code>class Derived : public Base {
public:
    void method() { std::cout << "Derived::method() - Yay!" << std::endl; }
    void work(Something something) {
        *this << something;
    }
    using Base::operator<<;
    void operator<<(SomethingUnrelated somethingUnrelated) { }
};
</code>```

Body:
Please forgive me if I fundamentally misunderstand something about dispatch in C++!

The code as pasted below works as intended.

However, if I uncomment/add the additional operator<< method in Derived (which should handle a different agrument type), C++ is then unable to resolve the previously-working dispatch "*this << something" (which, in the absence of that method, is successfully dispatched to Base as intended).

It says:

main.cpp:25:15: Invalid operands to binary expression ('Derived' and 'Something')

Please could someone explain to me why this happens?

Thanks in advance

(Mac OS Monterey 12.2.1, xCode 13.2.1)

#include <iostream>

class Something { };
class SomethingUnrelated { };

class Base {
public:
    virtual void method() = 0;
    void operator<<(Something something) {
        method();
    }
};

class Derived : public Base {
public:
    void method() { std::cout << "Derived::method() - Yay!" << std::endl; }
    void work(Something something) {
        *this << something;
    }
    // void operator<<(SomethingUnrelated somethingUnrelated) { }
};

int main(int argc, const char * argv[]) {
    Something something;
    Derived derived;
    derived.work(something);
    return 0;
}

Body:
The names in the parent class are hidden while building a lookup set for the unqualified name lookup. You may bring the parent's operator to a child lookup set by using directive. I can't find the duplicated question, but I'm pretty sure the duplicated question exists.

class Derived : public Base {
public:
    void method() { std::cout << "Derived::method() - Yay!" << std::endl; }
    void work(Something something) {
        *this << something;
    }
    using Base::operator<<;
    void operator<<(SomethingUnrelated somethingUnrelated) { }
};


问:
Airflow - Custom XCom backend on Ubuntu
I'm trying to implement custom XCOM backend.

Those are the steps I did:

Created "include" directory at the main Airflow dir (AIRFLOW_HOME).

Created these "custom_xcom_backend.py" file inside:

```<code>from typing import Any
from airflow.models.xcom import BaseXCom

import pandas as pd

class CustomXComBackend(BaseXCom):

    @staticmethod
    def serialize_value(value: Any):
        if isinstance(value, pd.DataFrame):
            value = value.to_json(orient='records')
        return BaseXCom.serialize_value(value)

    @staticmethod
    def deserialize_value(result) -> Any:
        result = BaseXCom.deserialize_value(result)
        result = df = pd.read_json(result)
        return result

</code>```

Set at config file:

```<code>xcom_backend = include.custom_xcom_backend.CustomXComBackend
</code>```

When I restarted webserver I got:

```<code>airflow.exceptions.AirflowConfigException: The object could not be loaded. Please check "xcom_backend" key in "core" section. Current value: "include.cust...
</code>```

My guess is that it not recognizing the "include" folder

But how can I fix it?

*Note: There is no docker. It is installed on a Ubuntu machine.

Thanks!

答:
So I solved it:

Put custom_xcom_backend.py into the plugins directory

set at config file:

```<code>xcom_backend = custom_xcom_backend.CustomXComBackend
</code>```

Restart all airflow related services

*Note: Do not store DataFrames that way (bad practice).

Sources I used:
https://www.youtube.com/watch?v=iI0ymwOij88

Title: Airflow - Custom XCom backend on Ubuntu

Body:
I'm trying to implement custom XCOM backend.

Those are the steps I did:

Created "include" directory at the main Airflow dir (AIRFLOW_HOME).

Created these "custom_xcom_backend.py" file inside:

from typing import Any
from airflow.models.xcom import BaseXCom

import pandas as pd

class CustomXComBackend(BaseXCom):

    @staticmethod
    def serialize_value(value: Any):
        if isinstance(value, pd.DataFrame):
            value = value.to_json(orient='records')
        return BaseXCom.serialize_value(value)

    @staticmethod
    def deserialize_value(result) -> Any:
        result = BaseXCom.deserialize_value(result)
        result = df = pd.read_json(result)
        return result

Set at config file:

xcom_backend = include.custom_xcom_backend.CustomXComBackend

When I restarted webserver I got:

airflow.exceptions.AirflowConfigException: The object could not be loaded. Please check "xcom_backend" key in "core" section. Current value: "include.cust...

My guess is that it not recognizing the "include" folder

But how can I fix it?

*Note: There is no docker. It is installed on a Ubuntu machine.

Thanks!

Body:
So I solved it:

Put custom_xcom_backend.py into the plugins directory

set at config file:

xcom_backend = custom_xcom_backend.CustomXComBackend

Restart all airflow related services

*Note: Do not store DataFrames that way (bad practice).

Sources I used:
https://www.youtube.com/watch?v=iI0ymwOij88


问:
Barrier Option Pricing in Python
We have a barrier call option of European type with strike price  K>0 and a barrier value

0 < b< S0 ,

where S_0 is the starting price.According to the contract, the times  0<t_1<...<t_k<T  the price must be checked S(t_k)>b  for every k.

Assuming the S(t) is described with the binomial option model with u=1.1  and  d = 0.9,r=0.05,T=10, and t_1=2,t_2=4 and t-3=7 the times that the asset must be checked.Also consider the S_0=100,K=125 and the barrier b=60.

My attempt is the following :

```<code># Initialise parameters
S0 = 100      # initial stock price
K = 125       # strike price
T = 10        # time to maturity in years
b = 60        # up-and-out barrier price/value
r = 0.05      # annual risk-free rate
N = 4         # number of time steps
u = 1.1       # up-factor in binomial models
d = 0.9       # ensure recombining tree
opttype = 'C' # Option Type 'C' or 'P'

def barrier_binomial(K,T,S0,b,r,N,u,d,opttype='C'):
    #precompute values
    dt = T/N
    q = (1+r - d)/(u-d)
    disc = np.exp(-r*dt)

    # initialise asset prices at maturity
    S = S0 * d**(np.arange(N,-1,-1)) * u**(np.arange(0,N+1,1))

    # option payoff
    if opttype == 'C':
        C = np.maximum( S - K, 0 )
    else:
        C = np.maximum( K - S, 0 )

    # check terminal condition payoff
    C[S >= b] = 0

    # backward recursion through the tree
    for i in np.arange(N-1,-1,-1):
        S = S0 * d**(np.arange(i,-1,-1)) * u**(np.arange(0,i+1,1))
        C[:i+1] = disc * ( q * C[1:i+2] + (1-q) * C[0:i+1] )
        C = C[:-1]
        C[S >= H] = 0
    return C[0]

barrier_binomial(K,T,S0,b,r,N,u,d,opttype='C')

</code>```

I receive nothing because something is wrong and I don’t know what

But is it a simulation ?

Any help from someone ?

答: In your loop you are using C[S >= H] = 0, but your barrier param is defined as b. Also you are filling the array C with 0s only, so check the payoff condition. In general, I find it much easier looping through matrices when working with tree models.

Title: Barrier Option Pricing in Python

Body:
We have a barrier call option of European type with strike price  K>0 and a barrier value

0 < b< S0 ,

where S_0 is the starting price.According to the contract, the times  0<t_1<...<t_k<T  the price must be checked S(t_k)>b  for every k.

Assuming the S(t) is described with the binomial option model with u=1.1  and  d = 0.9,r=0.05,T=10, and t_1=2,t_2=4 and t-3=7 the times that the asset must be checked.Also consider the S_0=100,K=125 and the barrier b=60.

My attempt is the following :

# Initialise parameters
S0 = 100      # initial stock price
K = 125       # strike price
T = 10        # time to maturity in years
b = 60        # up-and-out barrier price/value
r = 0.05      # annual risk-free rate
N = 4         # number of time steps
u = 1.1       # up-factor in binomial models
d = 0.9       # ensure recombining tree
opttype = 'C' # Option Type 'C' or 'P'

def barrier_binomial(K,T,S0,b,r,N,u,d,opttype='C'):
    #precompute values
    dt = T/N
    q = (1+r - d)/(u-d)
    disc = np.exp(-r*dt)

    # initialise asset prices at maturity
    S = S0 * d**(np.arange(N,-1,-1)) * u**(np.arange(0,N+1,1))

    # option payoff
    if opttype == 'C':
        C = np.maximum( S - K, 0 )
    else:
        C = np.maximum( K - S, 0 )

    # check terminal condition payoff
    C[S >= b] = 0

    # backward recursion through the tree
    for i in np.arange(N-1,-1,-1):
        S = S0 * d**(np.arange(i,-1,-1)) * u**(np.arange(0,i+1,1))
        C[:i+1] = disc * ( q * C[1:i+2] + (1-q) * C[0:i+1] )
        C = C[:-1]
        C[S >= H] = 0
    return C[0]

barrier_binomial(K,T,S0,b,r,N,u,d,opttype='C')

I receive nothing because something is wrong and I don’t know what

But is it a simulation ?

Any help from someone ?


问:
Symfony 5 form sanitise user text input by stripping chars
I have a form in symfony 5:

```<code>$builder
            ->add('name',TextType::class,[
                'label'=>'Character Name',
                'constraints'=>[
                    new Regex('/[\w\s]+/')
                ],
                'required'=>false,
                'attr'=>[
                    'class'=>'form-control'
                ],
                'label_attr'=>[
                    'class'=>'form-label'
                ]
            ])->add('gender',ChoiceType::class,[
                'label'=>'Gender',
                'required'=>false,
                'choices'=>[
                    'Any'=>'',
                    'Male'=>'Male',
                    'Female'=>'Female',
                    'Genderless'=>'Genderless',
                    'Unknown'=>'Unknown'
                ],
                'attr'=>[
                    'class'=>'form-control'
                ],
                'label_attr'=>[
                    'class'=>'form-label'
                ]
            ])->add('status',ChoiceType::class,[
                'label'=>'Status',
                'required'=>false,
                'choices'=>[
                    'Any'=>'',
                    'Alive'=>'Alive',
                    'Dead'=>'Dead',
                    'Unknown'=>'unknown'
                ],
                'attr'=>[
                    'class'=>'form-control'
                ],
                'label_attr'=>[
                    'class'=>'form-label'
                ]
            ])->add('species',ChoiceType::class,[
                'label'=>'Species',
                'required'=>false,
                'choices'=>[
                    'Any'=>'',
                    'Human'=>'Human',
                    'Alien'=>'Alien'
                ],
                'attr'=>[
                    'class'=>'form-control'
                ],
                'label_attr'=>[
                    'class'=>'form-label'
                ]
            ])->add('submit',SubmitType::class,[
                'label'=>'Filter Results',
                'attr'=>[
                    'class'=>'btn btn-primary'
                ]
            ]);
</code>```

What i want to do if possible is use regex to strip special characters from the "name" field after it's submitted so the resulting field value only contains alphanumeric and spaces, so i want to run this on it:

```<code>preg_replace('/[^\w\s]/','',$name);
</code>```

The closest thing i can find to do this is a model transformer but that doesn't really suit this situation as it's just a one way action.

答:
You could use an EventSubscriber, just like Symfony does internally to trim the value in their TextType field (see  https://github.com/symfony/symfony/blob/9045ad4bf2837e302e7cdbe41c38f1af33cbe854/src/Symfony/Component/Form/Extension/Core/EventListener/TrimListener.php ):

```<code><?php

namespace App\Form\EventListener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;

class SanitizeListener implements EventSubscriberInterface
{
    public function preSubmit(FormEvent $event)
    {
        $data = $event->getData();

        if (!\is_string($data)) {
            return;
        }

        $event->setData(preg_replace('/[^\w\s]/','',$data));
    }

    public static function getSubscribedEvents(): array
    {
        return [FormEvents::PRE_SUBMIT => 'preSubmit'];
    }
}
</code>```

Attach the listener to your name field like this:

```<code>$builder->get('name')->addEventSubscriber(new SanitizeListener());
</code>```

Body:
I have a form in symfony 5:

$builder
            ->add('name',TextType::class,[
                'label'=>'Character Name',
                'constraints'=>[
                    new Regex('/[\w\s]+/')
                ],
                'required'=>false,
                'attr'=>[
                    'class'=>'form-control'
                ],
                'label_attr'=>[
                    'class'=>'form-label'
                ]
            ])->add('gender',ChoiceType::class,[
                'label'=>'Gender',
                'required'=>false,
                'choices'=>[
                    'Any'=>'',
                    'Male'=>'Male',
                    'Female'=>'Female',
                    'Genderless'=>'Genderless',
                    'Unknown'=>'Unknown'
                ],
                'attr'=>[
                    'class'=>'form-control'
                ],
                'label_attr'=>[
                    'class'=>'form-label'
                ]
            ])->add('status',ChoiceType::class,[
                'label'=>'Status',
                'required'=>false,
                'choices'=>[
                    'Any'=>'',
                    'Alive'=>'Alive',
                    'Dead'=>'Dead',
                    'Unknown'=>'unknown'
                ],
                'attr'=>[
                    'class'=>'form-control'
                ],
                'label_attr'=>[
                    'class'=>'form-label'
                ]
            ])->add('species',ChoiceType::class,[
                'label'=>'Species',
                'required'=>false,
                'choices'=>[
                    'Any'=>'',
                    'Human'=>'Human',
                    'Alien'=>'Alien'
                ],
                'attr'=>[
                    'class'=>'form-control'
                ],
                'label_attr'=>[
                    'class'=>'form-label'
                ]
            ])->add('submit',SubmitType::class,[
                'label'=>'Filter Results',
                'attr'=>[
                    'class'=>'btn btn-primary'
                ]
            ]);

What i want to do if possible is use regex to strip special characters from the "name" field after it's submitted so the resulting field value only contains alphanumeric and spaces, so i want to run this on it:

preg_replace('/[^\w\s]/','',$name);

The closest thing i can find to do this is a model transformer but that doesn't really suit this situation as it's just a one way action.

Body:
You could use an EventSubscriber, just like Symfony does internally to trim the value in their TextType field (see  https://github.com/symfony/symfony/blob/9045ad4bf2837e302e7cdbe41c38f1af33cbe854/src/Symfony/Component/Form/Extension/Core/EventListener/TrimListener.php ):

<?php

namespace App\Form\EventListener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;

class SanitizeListener implements EventSubscriberInterface
{
    public function preSubmit(FormEvent $event)
    {
        $data = $event->getData();

        if (!\is_string($data)) {
            return;
        }

        $event->setData(preg_replace('/[^\w\s]/','',$data));
    }

    public static function getSubscribedEvents(): array
    {
        return [FormEvents::PRE_SUBMIT => 'preSubmit'];
    }
}

Attach the listener to your name field like this:

$builder->get('name')->addEventSubscriber(new SanitizeListener());


问:
MySQL matching 2 out of 5 fields
In MySQL I'm trying to select any row that matches at least 2 fields of the provided data

Eg. I have been given firstName, lastName, dob, website, email and I want any rows that match firstName and lastName, or firstName and email, or website and email etc.

I know I could write a very long winded statement along the lines of
(this=this AND this=this) OR (this=this etc
but this query could potentially get really large, especially if we decide we want to match on more than 5 fields.

We will also need to rank the matching rows, so if some rows match 3 instead of only the minimum 2 fields then they should show up higher in the returned results.

I could process this afterwards with PHP, or do multiple SQL queries, I'm just wondering if anyone knows an easier/cleaner way to match this data?

I appreciate any help!
Jo

答:
You could count up the matching expressions. MySQL returns 1 for true and 0 for false.

```<code>WHERE (FirstName = ?) + (LastName = ?) + (... = ?) > 2
</code>```

You can also order using this as well. You will want to sort descending to ensure that the higher matches appear first.

```<code>ORDER BY ((FirstName = ?) + (LastName = ?) + (... = ?)) DESC
</code>```

ContentLicense: CC BY-SA 3.0

Title: MySQL matching 2 out of 5 fields

Body:
You could count up the matching expressions. MySQL returns 1 for true and 0 for false.

WHERE (FirstName = ?) + (LastName = ?) + (... = ?) > 2

You can also order using this as well. You will want to sort descending to ensure that the higher matches appear first.

ORDER BY ((FirstName = ?) + (LastName = ?) + (... = ?)) DESC


问:
How To Populate objects inside array through aggregation
i got order document with array contains objects, each one contains product id and quantity and also options related to product,
what i would to achieve is to join this collection with product collection through aggregation to get certain product data like name, price, image

this is the order document i would like to aggregate

```<code>{
_id:ObjectId('61c45d25bdf9c1389879db9f'),
orderItems: [
    {
        options:[
            {
                _id:ObjectId('61fd914d4a236b94f816c27d'),
                question: 'lorem ipsum dolor set amet',
                answer: 'lorem'
            }, {
                _id: ObjectId('61fd914d4a236b94f816c27d'),
                question: 'lorem ipsum dolor set amet',
                answer: 'lorem'
            }, {
                _id: ObjectId('61fd914d4a236b94f816c27d'),
                question: 'lorem ipsum dolor set amet',
                answer: 'lorem'
            }, {
                _id: ObjectId('61fd914d4a236b94f816c27d'),
                question: 'lorem ipsum dolor set amet',
                answer: 'lorem'
            },
        ],
        quantity:4,
        product:ObjectId('61c5e1e7c2ec39450cdf41b7')
    }, {
        options:[
            {
                _id: ObjectId('61fd914d4a236b94f816c27d'),
                question: 'lorem ipsum dolor set amet',
                answer:'lorem'
            }, {
                _id: ObjectId('61fd914d4a236b94f816c27d'),
                question: 'lorem ipsum dolor set amet',
                answer: 'lorem'
            },
            {
                _id: ObjectId('61fd914d4a236b94f816c27d'),
                question: 'lorem ipsum dolor set amet',
                answer: 'lorem'
            }, {
                _id: ObjectId('61fd914d4a236b94f816c27d'),
                question: 'lorem ipsum dolor set amet',
                answer:'lorem'
            },
        ],
        quantity:3,
        product:ObjectId('61c5e1e7c2ec39450cdf41b7')
    }
]}
</code>```

this is final query I'd like to achieve

```<code>{
    _id:ObjectId('61c45d25bdf9c1389879db9f'),
    orderItems: [
        {
            options:[
                {
                    _id: ObjectId('61fd914d4a236b94f816c27d'),
                    question: 'lorem ipsum dolor set amet',
                    answer:'lorem'
                },
                {
                    _id: ObjectId('61fd914d4a236b94f816c27d'),
                    question: 'lorem ipsum dolor set amet',
                    answer:'lorem'
                }, {
                    _id: ObjectId('61fd914d4a236b94f816c27d'),
                    question: 'lorem ipsum dolor set amet',
                    answer: 'lorem'
                }, {
                    _id: ObjectId('61fd914d4a236b94f816c27d'),
                    question: 'lorem ipsum dolor set amet',
                    answer: 'lorem'
            },
        ],
        quantity:2,
        product: {
            name:'lorem ipsum dolor set',
            image:'1452877_product.png',
            type:'immo file',
            price:20
        }
    }, {
        options:[
            {
                _id: ObjectId('61fd914d4a236b94f816c27d'),
                question: 'lorem ipsum dolor set amet',
                answer: 'lorem'
            },
            {
                _id: ObjectId('61fd914d4a236b94f816c27d'),
                question: 'lorem ipsum dolor set amet',
                answer:'lorem'
            }, {
                _id: ObjectId('61fd914d4a236b94f816c27d'),
                question: 'lorem ipsum dolor set amet',
                answer: 'lorem'
            },
            {
                _id: ObjectId('61fd914d4a236b94f816c27d'),
                question: 'lorem ipsum dolor set amet',
                answer: 'lorem'
            },
        ],
        quantity: 3,
        product: {
            name: 'lorem ipsum dolor set',
            image: '1452877_product.png',
            type: 'immo file',
            price: 20
        }
    }
]}
</code>```

答:
The Solution that worked for me is to unwind the orderItems first then join the products collection using lookup and then use group at last

the code as follow

```<code>const orders = await Order.aggregate([
     {
            $unwind:'$orderItems'
        },
        {
            $lookup: {
                from:'products',
                let:{productId:"$orderItems.product"},
                pipeline:[
                    {
                        $match: {
                            $expr:{
                                $eq:["$_id", "$$productId"]
                            }
                        }
                    },
                    {
                        $project:{
                            name:1,
                            price:1,
                            type:1,
                            image:1
                        }
                    }
                ],
                as:"product"
            }
        },
        {
            $set:{"orderItems.product":"$product"}
        },
        {
            $unwind:"$orderItems.product"
        },
        {
            $group:{
                _id:"$_id",
                orderItems:{$push:"$orderItems"}
            }
        }
])
</code>```

Body:
i got order document with array contains objects, each one contains product id and quantity and also options related to product,
what i would to achieve is to join this collection with product collection through aggregation to get certain product data like name, price, image

this is the order document i would like to aggregate

{
_id:ObjectId('61c45d25bdf9c1389879db9f'),
orderItems: [
    {
        options:[
            {
                _id:ObjectId('61fd914d4a236b94f816c27d'),
                question: 'lorem ipsum dolor set amet',
                answer: 'lorem'
            }, {
                _id: ObjectId('61fd914d4a236b94f816c27d'),
                question: 'lorem ipsum dolor set amet',
                answer: 'lorem'
            }, {
                _id: ObjectId('61fd914d4a236b94f816c27d'),
                question: 'lorem ipsum dolor set amet',
                answer: 'lorem'
            }, {
                _id: ObjectId('61fd914d4a236b94f816c27d'),
                question: 'lorem ipsum dolor set amet',
                answer: 'lorem'
            },
        ],
        quantity:4,
        product:ObjectId('61c5e1e7c2ec39450cdf41b7')
    }, {
        options:[
            {
                _id: ObjectId('61fd914d4a236b94f816c27d'),
                question: 'lorem ipsum dolor set amet',
                answer:'lorem'
            }, {
                _id: ObjectId('61fd914d4a236b94f816c27d'),
                question: 'lorem ipsum dolor set amet',
                answer: 'lorem'
            },
            {
                _id: ObjectId('61fd914d4a236b94f816c27d'),
                question: 'lorem ipsum dolor set amet',
                answer: 'lorem'
            }, {
                _id: ObjectId('61fd914d4a236b94f816c27d'),
                question: 'lorem ipsum dolor set amet',
                answer:'lorem'
            },
        ],
        quantity:3,
        product:ObjectId('61c5e1e7c2ec39450cdf41b7')
    }
]}

this is final query I'd like to achieve

{
    _id:ObjectId('61c45d25bdf9c1389879db9f'),
    orderItems: [
        {
            options:[
                {
                    _id: ObjectId('61fd914d4a236b94f816c27d'),
                    question: 'lorem ipsum dolor set amet',
                    answer:'lorem'
                },
                {
                    _id: ObjectId('61fd914d4a236b94f816c27d'),
                    question: 'lorem ipsum dolor set amet',
                    answer:'lorem'
                }, {
                    _id: ObjectId('61fd914d4a236b94f816c27d'),
                    question: 'lorem ipsum dolor set amet',
                    answer: 'lorem'
                }, {
                    _id: ObjectId('61fd914d4a236b94f816c27d'),
                    question: 'lorem ipsum dolor set amet',
                    answer: 'lorem'
            },
        ],
        quantity:2,
        product: {
            name:'lorem ipsum dolor set',
            image:'1452877_product.png',
            type:'immo file',
            price:20
        }
    }, {
        options:[
            {
                _id: ObjectId('61fd914d4a236b94f816c27d'),
                question: 'lorem ipsum dolor set amet',
                answer: 'lorem'
            },
            {
                _id: ObjectId('61fd914d4a236b94f816c27d'),
                question: 'lorem ipsum dolor set amet',
                answer:'lorem'
            }, {
                _id: ObjectId('61fd914d4a236b94f816c27d'),
                question: 'lorem ipsum dolor set amet',
                answer: 'lorem'
            },
            {
                _id: ObjectId('61fd914d4a236b94f816c27d'),
                question: 'lorem ipsum dolor set amet',
                answer: 'lorem'
            },
        ],
        quantity: 3,
        product: {
            name: 'lorem ipsum dolor set',
            image: '1452877_product.png',
            type: 'immo file',
            price: 20
        }
    }
]}

Body:
The Solution that worked for me is to unwind the orderItems first then join the products collection using lookup and then use group at last

the code as follow

const orders = await Order.aggregate([
     {
            $unwind:'$orderItems'
        },
        {
            $lookup: {
                from:'products',
                let:{productId:"$orderItems.product"},
                pipeline:[
                    {
                        $match: {
                            $expr:{
                                $eq:["$_id", "$$productId"]
                            }
                        }
                    },
                    {
                        $project:{
                            name:1,
                            price:1,
                            type:1,
                            image:1
                        }
                    }
                ],
                as:"product"
            }
        },
        {
            $set:{"orderItems.product":"$product"}
        },
        {
            $unwind:"$orderItems.product"
        },
        {
            $group:{
                _id:"$_id",
                orderItems:{$push:"$orderItems"}
            }
        }
])


问:
Why doesn't this code raise a StopIteration exception?
In this code I have class name Iter that contains Two dunder methods __iter__ and __next__. In __iter__method I set self.current equal to zero and return self. In next method I increase
self.current += 1. When it reaches 10 I want it to raise a StopIteration exception.

```<code>class Iter:
    def __iter__(self):
        self.current = 0
        return self

    def __next__(self):
        self.current += 1
        if self.current == 10:
            raise StopIteration

        return self.current

it = Iter()
for i in it:
    print(i)
</code>```

答:
Your iterator already raises StopIteration, which is caught by the for loop in order to stop the iteration.  This is just how for loops work normally.

You can see this easily in your iterator if you add a print:

```<code>    def __next__(self):
        self.current += 1
        if self.current == 10:
            print("raising StopIteration")
            raise StopIteration
</code>```
```<code>1
2
3
4
5
6
7
8
9
raising StopIteration
</code>```

If you want to re-raise StopIteration after your iterator is exhausted, one option is just to raise one manually after the for loop:

```<code>it = Iter()
for i in it:
    print(i)
raise StopIteration
</code>```
```<code>1
2
3
4
5
6
7
8
9
Traceback (most recent call last):
  File "test.py", line 16, in <module>
    raise StopIteration
StopIteration
</code>```

Another is to change the way you do the iteration so that the StopIteration isn't caught:

```<code>it = iter(Iter())
while True:
    print(next(it))
</code>```
```<code>1
2
3
4
5
6
7
8
9
Traceback (most recent call last):
  File "test.py", line 15, in <module>
    print(next(it))
  File "test.py", line 9, in __next__
    raise StopIteration
StopIteration
</code>```

Body:
In this code I have class name Iter that contains Two dunder methods __iter__ and __next__. In __iter__method I set self.current equal to zero and return self. In next method I increase
self.current += 1. When it reaches 10 I want it to raise a StopIteration exception.

class Iter:
    def __iter__(self):
        self.current = 0
        return self

    def __next__(self):
        self.current += 1
        if self.current == 10:
            raise StopIteration

        return self.current

it = Iter()
for i in it:
    print(i)

Body:
Your iterator already raises StopIteration, which is caught by the for loop in order to stop the iteration.  This is just how for loops work normally.

You can see this easily in your iterator if you add a print:

    def __next__(self):
        self.current += 1
        if self.current == 10:
            print("raising StopIteration")
            raise StopIteration

1
2
3
4
5
6
7
8
9
raising StopIteration

If you want to re-raise StopIteration after your iterator is exhausted, one option is just to raise one manually after the for loop:

it = Iter()
for i in it:
    print(i)
raise StopIteration

1
2
3
4
5
6
7
8
9
Traceback (most recent call last):
  File "test.py", line 16, in <module>
    raise StopIteration
StopIteration

Another is to change the way you do the iteration so that the StopIteration isn't caught:

it = iter(Iter())
while True:
    print(next(it))

1
2
3
4
5
6
7
8
9
Traceback (most recent call last):
  File "test.py", line 15, in <module>
    print(next(it))
  File "test.py", line 9, in __next__
    raise StopIteration
StopIteration


问:
EasyPHP doesn't show README.md in indexes
I'm using EasyPHP Devserver 17 and have cloned a GitHub repo to a directory in my eds-www folder. When I navigate to the directory index of localhost/path/to/repo/ in my browser, I can see all the files, except README.md. EasyPHP will list other markdown files in the index, too.

I tried the steps at https://stackoverflow.com/a/11991421/5025767, but when I access my http.conf file, there is no indexignore option for README*.

How do I make EasyPHP display README.md?

答:
EasyPHP's setting to show README files is located in C:\<path to server root>\conf\extra\httpd-autoindex.conf.

Editing this file, removing README* from the IndexIgnore directive, and then restarting the server, shows README files in the directory listing.


问:
Cartesian product of list of templates and list of types to instantiate them with
Not sure if title is descriptive, but what I would like is this:

input:

list of templates(in my case containers) taking 1 (required, can be more optional) type arguments

list of types

output:

"cartesian product" where each template in first set is instantiated with every type in second set.

example:

```<code>template_list<std::vector, std::set> x type_list<int, double> =>
type_list<std::vector<int>, std::vector<double>, std::set<int>, std::set<double>>
</code>```

I found this question, but that is about a case when elements of both sets are types.

How to create the Cartesian product of a type list?

I presume that what I want is impossible without macros, but it may be possible that I am missing something.

答:
As in my answer on he linked question, with Boost.Mp11, this is a short one-liner (as always):

using templates = mp_list<mp_quote<std::vector>, mp_quote<std::set>>;
using types = mp_list<int, double>;

using result = mp_product<
    mp_invoke_q,
    templates, types>;

static_assert(std::same_as<
    result,
    mp_list<std::vector<int>,
            std::vector<double>,
            std::set<int>,
            std::set<double>
            >>);
```

Demo.

Note that you need templates as mp_list<mp_quote<C1>, mp_quote<C2>> instead of template_list<C1, C2>, since metaprogramming is lot easier if everything is a type. But that's not a huge burden.

Body:
Not sure if title is descriptive, but what I would like is this:

input:

list of templates(in my case containers) taking 1 (required, can be more optional) type arguments

list of types

output:

"cartesian product" where each template in first set is instantiated with every type in second set.

example:

template_list<std::vector, std::set> x type_list<int, double> =>
type_list<std::vector<int>, std::vector<double>, std::set<int>, std::set<double>>

I found this question, but that is about a case when elements of both sets are types.

How to create the Cartesian product of a type list?

I presume that what I want is impossible without macros, but it may be possible that I am missing something.

Body:
As in my answer on he linked question, with Boost.Mp11, this is a short one-liner (as always):

using templates = mp_list<mp_quote<std::vector>, mp_quote<std::set>>;
using types = mp_list<int, double>;

using result = mp_product<
    mp_invoke_q,
    templates, types>;

static_assert(std::same_as<
    result,
    mp_list<std::vector<int>,
            std::vector<double>,
            std::set<int>,
            std::set<double>
            >>);

Demo.

Note that you need templates as mp_list<mp_quote<C1>, mp_quote<C2>> instead of template_list<C1, C2>, since metaprogramming is lot easier if everything is a type. But that's not a huge burden.


问:
Get all Shots (table) related to a SessionId (table) where a third table named Results connects them through Result Id. using Linq
I want to use the sessionId to get all the Shots related to that specific Session. In the database the Shots table has a foreign key to a table named Results. Results has a foreign key to the table Session and it's primary key is the sessionId.
The code below returns 0 and I have tried multiple Include etc but nothing works.

Anyone know how to solve this and return a list of Shots related to a specific Session?

```<code>public List<Shots> GetShotListFromSession(string sessionId)
        {
            List<Shots> shotslist = new List<Shots>();
            shotslist = _db.Shots.Where(x => x.Results.Session.Id == sessionId).ToList();

            return shotslist;

        }

    ```
[Picture of the relations in database[1]

  [1]: https://i.stack.imgur.com/LfQcW.png
```

答:
You can first select the desired Results and then use .SelectMany() to retrieve and combine all associated Shots.

List<Shots> shotslist = _db.Results
    .Where(r => r.Session.Id == sessionId)
    .SelectMany(r => r.Shots)
    .ToList();
```

Body:
I want to use the sessionId to get all the Shots related to that specific Session. In the database the Shots table has a foreign key to a table named Results. Results has a foreign key to the table Session and it's primary key is the sessionId.
The code below returns 0 and I have tried multiple Include etc but nothing works.

Anyone know how to solve this and return a list of Shots related to a specific Session?

public List<Shots> GetShotListFromSession(string sessionId)
        {
            List<Shots> shotslist = new List<Shots>();
            shotslist = _db.Shots.Where(x => x.Results.Session.Id == sessionId).ToList();

            return shotslist;

        }

    ```
[Picture of the relations in database[1]

  [1]: https://i.stack.imgur.com/LfQcW.png


问:
"User is not set" IncompleteDsnException after migrating to Laravel 9
I was using Laravel 8.64, and my emails were working fine both on prod and dev servers. However, after upgrading to 9.0.2, I have an issue with sending emails. Of course, I followed all instructions, but still, I get errors when I try to send an email.

User is not set. {"exception":"[object]
(Symfony\Component\Mailer\Exception\IncompleteDsnException(code:
0): User is not set.

After some reasearch in vendor folder i found class AbstractTransportFactory that contains getUser method.

```<code>protected function getUser(Dsn $dsn): string
{
    $user = $dsn->getUser();
    if (null === $user) {
        throw new IncompleteDsnException('User is not set.');
    }

    return $user;
}
</code>```

When I return ''; in this if statement, everything is working fine instead of throwing an exception. Does anyone know the solution for this and why this is happening

答:
I had the same issue.

Make sure that your .env file contains:
MAILGUN_DOMAIN=your.domain.com
MAILGUN_SECRET=your.mailgun.secret

This would be reflected as the username/password for the DSN.

Cheers

Body:
I was using Laravel 8.64, and my emails were working fine both on prod and dev servers. However, after upgrading to 9.0.2, I have an issue with sending emails. Of course, I followed all instructions, but still, I get errors when I try to send an email.

User is not set. {"exception":"[object]
(Symfony\Component\Mailer\Exception\IncompleteDsnException(code:
0): User is not set.

After some reasearch in vendor folder i found class AbstractTransportFactory that contains getUser method.

protected function getUser(Dsn $dsn): string
{
    $user = $dsn->getUser();
    if (null === $user) {
        throw new IncompleteDsnException('User is not set.');
    }

    return $user;
}

When I return ''; in this if statement, everything is working fine instead of throwing an exception. Does anyone know the solution for this and why this is happening


问:
Remove unwanted characters from Dataframe values in Pandas
I have the following Dataframe full of locus/gen names from a multiple genome alignment.

However, I am trying to get only a full list of the locus/name without the coordinates.

```<code>    Tuberculosis_locus  Smagmatis_locus             H37RA_locus             Bovis_locus
0   0:Rv0001:1-1524     1:MSMEG_RS33460:6986600-6988114 2:MRA_RS00005:1-1524    3:BQ2027_RS00005:1-1524
1   0:Rv0002:2052-3260  1:MSMEG_RS00005:499-1692    2:MRA_RS00010:2052-3260 3:BQ2027_RS00010:2052-3260
2   0:Rv0003:3280-4437  1:MSMEG_RS00015:2624-3778   2:MRA_RS00015:3280-4437 3:BQ2027_RS00015:3280-4437
</code>```

To avoid issues with empty cells, I am filling cells with 'N/A' and then striping the unwanted characters. But it's giving the same exact result, nothing seems to be happening.

```<code>for value in orthologs['Tuberculosis_locus']:
    orthologs['Tuberculosis_locus'] = orthologs['Tuberculosis_locus'].fillna("N/A")
    orthologs['Tuberculosis_locus'] = orthologs['Tuberculosis_locus'].map(lambda x: x.lstrip('\d:').rstrip(':\d+'))
</code>```

Any idea on what I am doing wrong? I'd like the following output:

```<code>Tuberculosis_locus  Smagmatis_locus  H37RA_locus  Bovis_locus
    0   Rv0001  MSMEG_RS33460   MRA_RS00005 BQ2027_RS00005
    1   Rv0002  MSMEG_RS00005   MRA_RS00010 BQ2027_RS00010
    2   Rv0003  MSMEG_RS00015   MRA_RS00015 BQ2027_RS00015
</code>```

答:
Split by : with a maximum split of two and then take the 2nd elements, eg:

```<code>df.applymap(lambda v: v.split(':', 2)[1])
</code>```

Body:
I have the following Dataframe full of locus/gen names from a multiple genome alignment.

However, I am trying to get only a full list of the locus/name without the coordinates.

    Tuberculosis_locus  Smagmatis_locus             H37RA_locus             Bovis_locus
0   0:Rv0001:1-1524     1:MSMEG_RS33460:6986600-6988114 2:MRA_RS00005:1-1524    3:BQ2027_RS00005:1-1524
1   0:Rv0002:2052-3260  1:MSMEG_RS00005:499-1692    2:MRA_RS00010:2052-3260 3:BQ2027_RS00010:2052-3260
2   0:Rv0003:3280-4437  1:MSMEG_RS00015:2624-3778   2:MRA_RS00015:3280-4437 3:BQ2027_RS00015:3280-4437

To avoid issues with empty cells, I am filling cells with 'N/A' and then striping the unwanted characters. But it's giving the same exact result, nothing seems to be happening.

for value in orthologs['Tuberculosis_locus']:
    orthologs['Tuberculosis_locus'] = orthologs['Tuberculosis_locus'].fillna("N/A")
    orthologs['Tuberculosis_locus'] = orthologs['Tuberculosis_locus'].map(lambda x: x.lstrip('\d:').rstrip(':\d+'))

Any idea on what I am doing wrong? I'd like the following output:

Tuberculosis_locus  Smagmatis_locus  H37RA_locus  Bovis_locus
    0   Rv0001  MSMEG_RS33460   MRA_RS00005 BQ2027_RS00005
    1   Rv0002  MSMEG_RS00005   MRA_RS00010 BQ2027_RS00010
    2   Rv0003  MSMEG_RS00015   MRA_RS00015 BQ2027_RS00015

Body:
Split by : with a maximum split of two and then take the 2nd elements, eg:

df.applymap(lambda v: v.split(':', 2)[1])


问:
Skript - Get the body of the code component
I'm working on an extension for vs code that adds support for Skript syntax.

I'm stuck on that I can't select the body of the code block. In total, there are several of them in the Skript syntax (commands, functions, events, and a few more). Each block starts with a zero indent (it's indent sensitive). I have provided an example Skript syntax below.

```<code>on join:
    set the player's gamemode to spectator
    join_player(player)

command /join [<player>]:
    trigger:
        if arg-1 is not set:
            join_player(player)
        else:
            player has permission "op"
            join_player(arg-1)

function reset_arena():
    set all blocks within {loc1} and {loc2} to snow block
</code>```

The original author of this extension used this construction. But it doesn't work with an odd number (\r\n|\r|\n). Also defines the last line of the document as not related to the last component.

```<code>if (search = component.match(/^(?<component>(command\s?(?<head>[^\:]*))\:?(.*)(?<body>((\r\n|\r|\n)([^a-zA-Z][^\r\n]*)?)*))/i)?.groups) {
    return this._createCommand(skDocument, range, search.component, search.head, search.body);
}
</code>```

Please tell me how to correctly make a regex so that the body of the component is selected. Thanks a lot

答:
I believe you need something like this:

```<code>(?<component>^\w+ +(?<head>.*)\n(?<body>(?:[\s\S](?!\n\w))*))
</code>```

It will provide 3 groups for each match:

component

head

body

You can have a better idea of how it works and make any modifications you may need in the following link: https://regex101.com/r/0VaKhR/2

Body:
I'm working on an extension for vs code that adds support for Skript syntax.

I'm stuck on that I can't select the body of the code block. In total, there are several of them in the Skript syntax (commands, functions, events, and a few more). Each block starts with a zero indent (it's indent sensitive). I have provided an example Skript syntax below.

on join:
    set the player's gamemode to spectator
    join_player(player)

command /join [<player>]:
    trigger:
        if arg-1 is not set:
            join_player(player)
        else:
            player has permission "op"
            join_player(arg-1)

function reset_arena():
    set all blocks within {loc1} and {loc2} to snow block

The original author of this extension used this construction. But it doesn't work with an odd number (\r\n|\r|\n). Also defines the last line of the document as not related to the last component.

if (search = component.match(/^(?<component>(command\s?(?[^\:]*))\:?(.*)(?((\r\n|\r|\n)([^a-zA-Z][^\r\n]*)?)*))/i)?.groups) {
    return this._createCommand(skDocument, range, search.component, search.head, search.body);
}

Please tell me how to correctly make a regex so that the body of the component is selected. Thanks a lot

Body:
I believe you need something like this:

(?<component>^\w+ +(?<head>.*)\n(?<body>(?:[\s\S](?!\n\w))*))

It will provide 3 groups for each match:

component

head

body

You can have a better idea of how it works and make any modifications you may need in the following link: https://regex101.com/r/0VaKhR/2


问:
React Router v6 not showing nested route - what am I missing?
I have in my index the following routes:

```<code>    <BrowserRouter>
        <Routes>
            <Route path="/" element={<App />} />
            <Route path="admin" element={<AdminDashboard /> } />
        </Routes>
    </BrowserRouter>
</code>```

I can access / and admin, and the components render correctly.

Inside AdminDashboard, I have two other routes:

```<code>        <Routes>
            <Route path="/" element={<AdminCards />} />
            <Route path="news-sources" element={<NewsSourcesAdmin /> } />
        </Routes>
</code>```

If I access http://localhost/ and http://localhost/admin, I get things to render correctly.

However, if I attempt to go to http://localhost/admin/news-sources, then the NewsSourcesAdmin component does not render. I get an empty page instead.

Shouldn't the AdminDashboard component render given I'm under the admin route, and then the NewsSourcesAdmin component render inside of it given I am under the /admin/news-sources route?

I am on React 17, React Router v6.

What am I missing?

答:
v6 routes are exact by default.
Use trailing * to match everything:

```<code><Route path="admin/*" element={<AdminDashboard /> } />
</code>```

Body:
I have in my index the following routes:

    <BrowserRouter>
        <Routes>
            <Route path="/" element={<App />} />
            <Route path="admin" element={<AdminDashboard /> } />
        </Routes>
    </BrowserRouter>

I can access / and admin, and the components render correctly.

Inside AdminDashboard, I have two other routes:

        <Routes>
            <Route path="/" element={<AdminCards />} />
            <Route path="news-sources" element={<NewsSourcesAdmin /> } />
        </Routes>

If I access http://localhost/ and http://localhost/admin, I get things to render correctly.

However, if I attempt to go to http://localhost/admin/news-sources, then the NewsSourcesAdmin component does not render. I get an empty page instead.

Shouldn't the AdminDashboard component render given I'm under the admin route, and then the NewsSourcesAdmin component render inside of it given I am under the /admin/news-sources route?

I am on React 17, React Router v6.

What am I missing?

Body:
v6 routes are exact by default.
Use trailing * to match everything:

<Route path="admin/*" element={<AdminDashboard /> } />


问:
VS code CSS class selector not found with angular and bootstrap 5 beta
I'm using bootstrap 5 with angular and I add style and script to angular.json but the problem in VS Code it does not recognize the bootstrap classes.

答:
Now, using bootstrap 5 and angular 13.2.2, the HTML CSS support extension doesn't work.

However, IntelliSense for CSS class names in HTML works for me


问:
What are the arguments against the use of the "<?="?

Possible Duplicate:

  Are PHP short tags acceptable to use?

The <?= is one of the very few elegant things about PHP, IMO. Yet, there are people that deliberately avoid it (in favor of the much longer <?php echo). Why would they do that?

答:
Because by default servers aren't set up with php short-tag support, its something that needs to be toggled. if for some reason the server does not have short-tag support turned on, your code will error out. better to just add a couple characters, and aviod potential problems.

EDIT

search before posting: Are PHP short tags acceptable to use?


问:
Pandas: how to index dataframe for certain value or string without knowing the column name
Although it seems very detrimental, I am having a hard time getting the index of a dataframe for a certain string or value at a random position in the dataframe.

I made an example dataframe:

```<code>fruits = {
    'column1':["Apples","Pears","Bananas","Oranges","Strawberries"],
    'column2':[1,2,3,4,5],
    'column3':["Kiwis","Mangos","Pineapples","Grapes","Melons"]
          }

df = pd.DataFrame(fruits)

        column1  column2     column3
0        Apples        1       Kiwis
1         Pears        2      Mangos
2       Bananas        3  Pineapples
3       Oranges        4      Grapes
4  Strawberries        5      Melons
</code>```

Now I want to get the position index of Mangos, without having the knowledge in which column or row it exists. So far I succeeded in getting the row index:

```<code>print(df.loc[df.isin(["Mangos"]).any(axis=1)].index)
</code>```

Which results in:

```<code>Int64Index([1], dtype='int64')
</code>```

But now I would also like to retrieve the column index or column name.

This thread is a very simplified version of Get column name where value is something in pandas dataframe, but I could not figure out the code using the other thread.

答:
Stack the dataframe to reshape into multiindex series, then use boolean indexing to get the index

```<code>s = df.stack()
s[s == 'Mangos'].index
</code>```

```<code>MultiIndex([(1, 'column3')])
</code>```

Body:
Although it seems very detrimental, I am having a hard time getting the index of a dataframe for a certain string or value at a random position in the dataframe.

I made an example dataframe:

fruits = {
    'column1':["Apples","Pears","Bananas","Oranges","Strawberries"],
    'column2':[1,2,3,4,5],
    'column3':["Kiwis","Mangos","Pineapples","Grapes","Melons"]
          }

df = pd.DataFrame(fruits)

        column1  column2     column3
0        Apples        1       Kiwis
1         Pears        2      Mangos
2       Bananas        3  Pineapples
3       Oranges        4      Grapes
4  Strawberries        5      Melons

Now I want to get the position index of Mangos, without having the knowledge in which column or row it exists. So far I succeeded in getting the row index:

print(df.loc[df.isin(["Mangos"]).any(axis=1)].index)

Which results in:

Int64Index([1], dtype='int64')

But now I would also like to retrieve the column index or column name.

This thread is a very simplified version of Get column name where value is something in pandas dataframe, but I could not figure out the code using the other thread.

Body:
Stack the dataframe to reshape into multiindex series, then use boolean indexing to get the index

s = df.stack()
s[s == 'Mangos'].index

MultiIndex([(1, 'column3')])


问:
merging multiple .txt files into one .xlsx having different column names
I've been following this answer : How do I extract data from multiple text files to Excel for merging multiple .txt files to one .xlsx spreadsheet, but this answer is giving me the data in multiple worksheets with no distinct column names.

What I'm trying to do is to extract the data of 3 .txt files(each file contains data in one column without a column name) into one spreadsheet and each column should have a distinct column name('col1', 'col2' and 'col3') respectively.

data1.txt:

```<code>ACC_NT/mc_pf_qer
ACC_NT/gsd
ACC_NT/hcv_efg_tdc
ACC_NT/ids_gc
ISQ_BX/oic_lkv
ISQ_BX/pfg_8c
</code>```

data2.txt:

```<code>79.2%
53.9%
100.0%
50.0%
44.2%
0.0%
</code>```

data3.txt:

```<code>ACC_NT/ACC_NT_mc_pf_qer.html
ACC_NT/ACC_NT_gsd.html
ACC_NT/ACC_NT_hcv_efg_tdc.html
ACC_NT/ACC_NT_ids_gc.html
ISQ_BX/ISQ_BX_oic_lkv.html
ISQ_BX/ISQ_BX_pfg_8c.html
</code>```

Any help or guidance is appreciated, thanks!

答:
IIUC:

```<code>data = {}
for i, filename in enumerate(['data1.txt', 'data2.txt', 'data3.txt'], 1):
    data[f"col{i}"] = pd.read_csv(filename, squeeze=True, header=None)
pd.concat(data, axis=1).to_excel('output.xlsx')
</code>```

Update

I realized that the col2 data contains the percentage details and in the output.xlsx

```<code>data = {}
for i, filename in enumerate(['data1.txt', 'data2.txt', 'data3.txt'], 1):
    data[f"col{i}"] = pd.read_csv(filename, squeeze=True, header=None)
df = pd.concat(data, axis=1)
df['col2'] = df['col2'].str.strip('%').astype(float)
df.to_excel('output.xlsx', index=False)
</code>```

Body:
I've been following this answer : How do I extract data from multiple text files to Excel for merging multiple .txt files to one .xlsx spreadsheet, but this answer is giving me the data in multiple worksheets with no distinct column names.

What I'm trying to do is to extract the data of 3 .txt files(each file contains data in one column without a column name) into one spreadsheet and each column should have a distinct column name('col1', 'col2' and 'col3') respectively.

data1.txt:

ACC_NT/mc_pf_qer
ACC_NT/gsd
ACC_NT/hcv_efg_tdc
ACC_NT/ids_gc
ISQ_BX/oic_lkv
ISQ_BX/pfg_8c

data2.txt:

79.2%
53.9%
100.0%
50.0%
44.2%
0.0%

data3.txt:

ACC_NT/ACC_NT_mc_pf_qer.html
ACC_NT/ACC_NT_gsd.html
ACC_NT/ACC_NT_hcv_efg_tdc.html
ACC_NT/ACC_NT_ids_gc.html
ISQ_BX/ISQ_BX_oic_lkv.html
ISQ_BX/ISQ_BX_pfg_8c.html

Any help or guidance is appreciated, thanks!

Body:
IIUC:

data = {}
for i, filename in enumerate(['data1.txt', 'data2.txt', 'data3.txt'], 1):
    data[f"col{i}"] = pd.read_csv(filename, squeeze=True, header=None)
pd.concat(data, axis=1).to_excel('output.xlsx')

Update

I realized that the col2 data contains the percentage details and in the output.xlsx

data = {}
for i, filename in enumerate(['data1.txt', 'data2.txt', 'data3.txt'], 1):
    data[f"col{i}"] = pd.read_csv(filename, squeeze=True, header=None)
df = pd.concat(data, axis=1)
df['col2'] = df['col2'].str.strip('%').astype(float)
df.to_excel('output.xlsx', index=False)


问:
Pycord mute command doesn't throw error but doesn't add role
I am using pycord for this so I can use slash commands.

Here is my code:

```<code>import discord, os
from dotenv import load_dotenv
from discord.ext import commands

load_dotenv(f'{os.getcwd()}/token.env')

bot = commands.Bot()

token = str(os.getenv('TOKEN'))
@bot.slash_command(description = 'mutes member of choice')
@commands.has_permissions(administrator = True)
async def mute(ctx, member: discord.Member):
    guild = ctx.guild
    mutedRole = discord.utils.get(guild.roles, name="Muted")

    if not mutedRole:
        mutedRole = await guild.create_role(name="Muted")

        for channel in guild.channels:
            await channel.set_permissions(mutedRole, speak=False, send_messages=False, read_message_history=True, read_messages=False)

    await member.add_roles(mutedRole)
    await ctx.send(f"Muted {member.mention}")

@mute.error
async def permserror(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        ctx.respond('Sorry! You dont have permission.')

@bot.event
async def on_ready():
    print(f'Client ready as {bot.user}')

bot.run(token)
</code>```

This isn't my full code, but the other commands don't seem necessary for my problem.

Anyway, when I try to use this command, it doesn't throw an error in the console, but the application doesn't respond and it doesn't add the role.

I put a print statement between each line of code, and it seems to stop just before it adds the role.

How can I fix this?

Update: My previous code did not run so I have updated it.

答: This doesn't actually have to do with the code of the program. All you have to do is move the bot role to the top and it'll work. The error is 403 Forbidden (error code: 50013): Missing Permissions. Also, you have to reinvite the bot and add applications.commands if you haven't already.

Body:
I am using pycord for this so I can use slash commands.

Here is my code:

import discord, os
from dotenv import load_dotenv
from discord.ext import commands

load_dotenv(f'{os.getcwd()}/token.env')

bot = commands.Bot()

token = str(os.getenv('TOKEN'))
@bot.slash_command(description = 'mutes member of choice')
@commands.has_permissions(administrator = True)
async def mute(ctx, member: discord.Member):
    guild = ctx.guild
    mutedRole = discord.utils.get(guild.roles, name="Muted")

    if not mutedRole:
        mutedRole = await guild.create_role(name="Muted")

        for channel in guild.channels:
            await channel.set_permissions(mutedRole, speak=False, send_messages=False, read_message_history=True, read_messages=False)

    await member.add_roles(mutedRole)
    await ctx.send(f"Muted {member.mention}")

@mute.error
async def permserror(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        ctx.respond('Sorry! You dont have permission.')

@bot.event
async def on_ready():
    print(f'Client ready as {bot.user}')

bot.run(token)

This isn't my full code, but the other commands don't seem necessary for my problem.

Anyway, when I try to use this command, it doesn't throw an error in the console, but the application doesn't respond and it doesn't add the role.

I put a print statement between each line of code, and it seems to stop just before it adds the role.

How can I fix this?

Update: My previous code did not run so I have updated it.


问:
How to change just one parameter using Redux?
I try to update my global state using Redux, but I try to update just one paramter of five, not all.

My store code looks like:

```<code>const initialState = {
    loggedIn: false,
    thisUser: {}
}

export function usersReducer(state = initialState, action) {
    switch (action.type) {
        case 'users/loggedIn':
            return { ...state, loggedIn: action.payload }
        case 'users/addUser':
            return { ...state, thisUser: action.payload }
        default:
            return state
    }
}
</code>```

I tried to write a new case like, but doesn't work:

```<code>case 'users/setActivated':
            return { ...state, thisUser.activated: action.payload }
</code>```

VS Code doesn't let me write that ".activated"

My dispatch look like:

```<code>dispatch({ type: 'users/setActivated', payload: 1 })
</code>```

What is  wrong?

答:
Well, your syntax is wrong, that's what. :)

```<code>case 'users/setActivated':
    return { ...state, thisUser: {...state.thisUser, activated: action.payload} }
</code>```

is what you need to shallow-merge state with a shallow-merged nested object.

Note that it quickly gets very old to dig into objects like that, and you might want to look at e.g. immer.

Body:
I try to update my global state using Redux, but I try to update just one paramter of five, not all.

My store code looks like:

const initialState = {
    loggedIn: false,
    thisUser: {}
}

export function usersReducer(state = initialState, action) {
    switch (action.type) {
        case 'users/loggedIn':
            return { ...state, loggedIn: action.payload }
        case 'users/addUser':
            return { ...state, thisUser: action.payload }
        default:
            return state
    }
}

I tried to write a new case like, but doesn't work:

case 'users/setActivated':
            return { ...state, thisUser.activated: action.payload }

VS Code doesn't let me write that ".activated"

My dispatch look like:

dispatch({ type: 'users/setActivated', payload: 1 })

What is  wrong?

Body:
Well, your syntax is wrong, that's what. :)

case 'users/setActivated':
    return { ...state, thisUser: {...state.thisUser, activated: action.payload} }

is what you need to shallow-merge state with a shallow-merged nested object.

Note that it quickly gets very old to dig into objects like that, and you might want to look at e.g. immer.