问:
StringBuilder.Append Vs StringBuilder.AppendFormat
I was wondering about StringBuilder and I've got a question that I was hoping the community would be able to explain.

Let's just forget about code readability, which of these is faster and why?

StringBuilder.Append:

```<code>StringBuilder sb = new StringBuilder();
sb.Append(string1);
sb.Append("----");
sb.Append(string2);
</code>```

StringBuilder.AppendFormat:

```<code>StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0}----{1}",string1,string2);
</code>```

答: 1 should be faster becuase it's simply appending the strings whereas 2 has to create a string based on a format and then append the string. So there's an extra step in there.</p>

OwnerDisplayName: Sergio

ContentLicense: CC BY-SA 2.5

Body:
I was wondering about StringBuilder and I've got a question that I was hoping the community would be able to explain.

Let's just forget about code readability, which of these is faster and why?

StringBuilder.Append:

StringBuilder sb = new StringBuilder();
sb.Append(string1);
sb.Append("----");
sb.Append(string2);

StringBuilder.AppendFormat:

StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0}----{1}",string1,string2);

LastEditorDisplayName: Samuel

OwnerDisplayName: Micah


来源: stackexchange

问:
listen EACCES: permission denied in windows
Everything was worked fine before today evening after i uninstalled vscode and installed again I'm facing this issue while try to run npm run app i  have no clue how to fix this i tried to run vs code and command prompt or bash using run as administrator but no luck, i see lot of fixes out there for this issue but most of them are for mac they fixed it using sudo but i don't see any good fix for windows it would be appreciated much if anyone will help me fix this

```<code>//this issue this my server code
const express = require("express");
const app = express()
const port = process.env || 8080

app.get("/", (req, res) => {
  res.send("Hello");
});

app.listen(port,()=>{
  console.log("running on 8080")
})
</code>```

and this is the complete error

```<code>events.js:187
      throw er; // Unhandled 'error' event
      ^

Error: listen EACCES: permission denied C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;D:\BookStore\node_modules\.bin;C:\Users\Samarth's PC\bin;C:\Program Files\Git\mingw64\bin;C:\Program Files\Git\usr\local\bin;C:\Program Files\Git\usr\bin;C:\Program Files\Git\usr\bin;C:\Program Files\Git\mingw64\bin;C:\Program Files\Git\usr\bin;C:\Users\Samarth's PC\bin;C:\ProgramData\Miniconda3;C:\ProgramData\Miniconda3\Library\mingw-w64\bin;C:\ProgramData\Miniconda3\Library\usr\bin;C:\ProgramData\Miniconda3\Library\bin;C:\ProgramData\Miniconda3\Scripts;C:\Python27;C:\Python27\Scripts;C:\Users\Samarth's PC\AppData\Local\Programs\Python\Python38-32\python.exe;C:\Program Files\nodejs;C:\ProgramData\chocolatey\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0;C:\WINDOWS\System32\OpenSSH;C:\Program Files (x86)\Yarn\bin;C:\Users\Samarth's PC\AppData\Local\Microsoft\WindowsApps;C:\Program Files\MongoDB\Server\4.0\bin;C:\Program Files\heroku\bin;C:\nvm;C:\Program Files\nodejs;C:\Python 3.8;C:\Users\Samarth's PC\AppData\Roaming\npm;C:\Users\Samarth's PC\AppData\Local\Yarn\bin;C:\Users\Samarth's PC\AppData\Local\Programs\Microsoft VS Code\bin;C:\Program Files\Git\usr\bin\vendor_perl;C:\Program Files\Git\usr\bin\core_perl
    at Server.setupListenHandle [as _listen2] (net.js:1283:19)
    at listenInCluster (net.js:1348:12)
    at Server.listen (net.js:1447:5)
    at Function.listen (D:\BookStore\node_modules\express\lib\application.js:618:24)
    at Object.<anonymous> (D:\BookStore\app.js:11:5)
    at Module._compile (internal/modules/cjs/loader.js:956:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
    at Module.load (internal/modules/cjs/loader.js:812:32)
    at Function.Module._load (internal/modules/cjs/loader.js:724:14)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10)
Emitted 'error' event on Server instance at:
    at emitErrorNT (net.js:1327:8)
    at processTicksAndRejections (internal/process/task_queues.js:80:21) {
  code: 'EACCES',
  errno: 'EACCES',
  syscall: 'listen',
  address: "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\npm-lifecycle\\node-gyp-bin;D:\\BookStore\\node_modules\\.bin;C:\\Users\\Samarth's PC\\bin;C:\\Program Files\\Git\\mingw64\\bin;C:\\Program Files\\Git\\usr\\local\\bin;C:\\Program Files\\Git\\usr\\bin;C:\\Program Files\\Git\\usr\\bin;C:\\Program Files\\Git\\mingw64\\bin;C:\\Program Files\\Git\\usr\\bin;C:\\Users\\Samarth's PC\\bin;C:\\ProgramData\\Miniconda3;C:\\ProgramData\\Miniconda3\\Library\\mingw-w64\\bin;C:\\ProgramData\\Miniconda3\\Library\\usr\\bin;C:\\ProgramData\\Miniconda3\\Library\\bin;C:\\ProgramData\\Miniconda3\\Scripts;C:\\Python27;C:\\Python27\\Scripts;C:\\Users\\Samarth's PC\\AppData\\Local\\Programs\\Python\\Python38-32\\python.exe;C:\\Program Files\\nodejs;C:\\ProgramData\\chocolatey\\bin;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0;C:\\WINDOWS\\System32\\OpenSSH;C:\\Program Files (x86)\\Yarn\\bin;C:\\Users\\Samarth's PC\\AppData\\Local\\Microsoft\\WindowsApps;C:\\Program Files\\MongoDB\\Server\\4.0\\bin;C:\\Program Files\\heroku\\bin;C:\\nvm;C:\\Program Files\\nodejs;C:\\Python 3.8;C:\\Users\\Samarth's PC\\AppData\\Roaming\\npm;C:\\Users\\Samarth's PC\\AppData\\Local\\Yarn\\bin;C:\\Users\\Samarth's PC\\AppData\\Local\\Programs\\Microsoft VS Code\\bin;C:\\Program Files\\Git\\usr\\bin\\vendor_perl;C:\\Program Files\\Git\\usr\\bin\\core_perl",
  port: -1
}
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! bookstore@1.0.0 start: `node app.js "app"`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the bookstore@1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Samarth's PC\AppData\Roaming\npm-cache\_logs\2019-12-20T16_43_00_131Z-debug.log
</code>```

```<code>//Error log is here
0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli   'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'start',
1 verbose cli   'app'
1 verbose cli ]
2 info using npm@6.12.0
3 info using node@v12.13.0
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info lifecycle bookstore@1.0.0~prestart: bookstore@1.0.0
6 info lifecycle bookstore@1.0.0~start: bookstore@1.0.0
7 verbose lifecycle bookstore@1.0.0~start: unsafe-perm in lifecycle true
8 verbose lifecycle bookstore@1.0.0~start: PATH: C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;D:\BookStore\node_modules\.bin;C:\Users\Samarth's PC\bin;C:\Program Files\Git\mingw64\bin;C:\Program Files\Git\usr\local\bin;C:\Program Files\Git\usr\bin;C:\Program Files\Git\usr\bin;C:\Program Files\Git\mingw64\bin;C:\Program Files\Git\usr\bin;C:\Users\Samarth's PC\bin;C:\ProgramData\Miniconda3;C:\ProgramData\Miniconda3\Library\mingw-w64\bin;C:\ProgramData\Miniconda3\Library\usr\bin;C:\ProgramData\Miniconda3\Library\bin;C:\ProgramData\Miniconda3\Scripts;C:\Python27;C:\Python27\Scripts;C:\Users\Samarth's PC\AppData\Local\Programs\Python\Python38-32\python.exe;C:\Program Files\nodejs;C:\ProgramData\chocolatey\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0;C:\WINDOWS\System32\OpenSSH;C:\Program Files (x86)\Yarn\bin;C:\Users\Samarth's PC\AppData\Local\Microsoft\WindowsApps;C:\Program Files\MongoDB\Server\4.0\bin;C:\Program Files\heroku\bin;C:\nvm;C:\Program Files\nodejs;C:\Python 3.8;C:\Users\Samarth's PC\AppData\Roaming\npm;C:\Users\Samarth's PC\AppData\Local\Yarn\bin;C:\Users\Samarth's PC\AppData\Local\Programs\Microsoft VS Code\bin;C:\Program Files\Git\usr\bin\vendor_perl;C:\Program Files\Git\usr\bin\core_perl
9 verbose lifecycle bookstore@1.0.0~start: CWD: D:\BookStore
10 silly lifecycle bookstore@1.0.0~start: Args: [ '/d /s /c', 'node app.js "app"' ]
11 silly lifecycle bookstore@1.0.0~start: Returned: code: 1  signal: null
12 info lifecycle bookstore@1.0.0~start: Failed to exec start script
13 verbose stack Error: bookstore@1.0.0 start: `node app.js "app"`
13 verbose stack Exit status 1
13 verbose stack     at EventEmitter.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\index.js:332:16)
13 verbose stack     at EventEmitter.emit (events.js:210:5)
13 verbose stack     at ChildProcess.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:210:5)
13 verbose stack     at maybeClose (internal/child_process.js:1021:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:283:5)
14 verbose pkgid bookstore@1.0.0
15 verbose cwd D:\BookStore
16 verbose Windows_NT 10.0.18362
17 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "start" "app"
18 verbose node v12.13.0
19 verbose npm  v6.12.0
20 error code ELIFECYCLE
21 error errno 1
22 error bookstore@1.0.0 start: `node app.js "app"`
22 error Exit status 1
23 error Failed at the bookstore@1.0.0 start script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]

</code>```

答: In case it helps someone else, it was failing for me because I tried adding a port that was too small (999), try changing your port and see if it can be solved that way.</p>

ContentLicense: CC BY-SA 4.0

Body:
Everything was worked fine before today evening after i uninstalled vscode and installed again I'm facing this issue while try to run npm run app i  have no clue how to fix this i tried to run vs code and command prompt or bash using run as administrator but no luck, i see lot of fixes out there for this issue but most of them are for mac they fixed it using sudo but i don't see any good fix for windows it would be appreciated much if anyone will help me fix this

//this issue this my server code
const express = require("express");
const app = express()
const port = process.env || 8080

app.get("/", (req, res) => {
  res.send("Hello");
});

app.listen(port,()=>{
  console.log("running on 8080")
})

and this is the complete error

events.js:187
      throw er; // Unhandled 'error' event
      ^

Error: listen EACCES: permission denied C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;D:\BookStore\node_modules\.bin;C:\Users\Samarth's PC\bin;C:\Program Files\Git\mingw64\bin;C:\Program Files\Git\usr\local\bin;C:\Program Files\Git\usr\bin;C:\Program Files\Git\usr\bin;C:\Program Files\Git\mingw64\bin;C:\Program Files\Git\usr\bin;C:\Users\Samarth's PC\bin;C:\ProgramData\Miniconda3;C:\ProgramData\Miniconda3\Library\mingw-w64\bin;C:\ProgramData\Miniconda3\Library\usr\bin;C:\ProgramData\Miniconda3\Library\bin;C:\ProgramData\Miniconda3\Scripts;C:\Python27;C:\Python27\Scripts;C:\Users\Samarth's PC\AppData\Local\Programs\Python\Python38-32\python.exe;C:\Program Files\nodejs;C:\ProgramData\chocolatey\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0;C:\WINDOWS\System32\OpenSSH;C:\Program Files (x86)\Yarn\bin;C:\Users\Samarth's PC\AppData\Local\Microsoft\WindowsApps;C:\Program Files\MongoDB\Server\4.0\bin;C:\Program Files\heroku\bin;C:\nvm;C:\Program Files\nodejs;C:\Python 3.8;C:\Users\Samarth's PC\AppData\Roaming\npm;C:\Users\Samarth's PC\AppData\Local\Yarn\bin;C:\Users\Samarth's PC\AppData\Local\Programs\Microsoft VS Code\bin;C:\Program Files\Git\usr\bin\vendor_perl;C:\Program Files\Git\usr\bin\core_perl
    at Server.setupListenHandle [as _listen2] (net.js:1283:19)
    at listenInCluster (net.js:1348:12)
    at Server.listen (net.js:1447:5)
    at Function.listen (D:\BookStore\node_modules\express\lib\application.js:618:24)
    at Object.<anonymous> (D:\BookStore\app.js:11:5)
    at Module._compile (internal/modules/cjs/loader.js:956:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
    at Module.load (internal/modules/cjs/loader.js:812:32)
    at Function.Module._load (internal/modules/cjs/loader.js:724:14)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10)
Emitted 'error' event on Server instance at:
    at emitErrorNT (net.js:1327:8)
    at processTicksAndRejections (internal/process/task_queues.js:80:21) {
  code: 'EACCES',
  errno: 'EACCES',
  syscall: 'listen',
  address: "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\npm-lifecycle\\node-gyp-bin;D:\\BookStore\\node_modules\\.bin;C:\\Users\\Samarth's PC\\bin;C:\\Program Files\\Git\\mingw64\\bin;C:\\Program Files\\Git\\usr\\local\\bin;C:\\Program Files\\Git\\usr\\bin;C:\\Program Files\\Git\\usr\\bin;C:\\Program Files\\Git\\mingw64\\bin;C:\\Program Files\\Git\\usr\\bin;C:\\Users\\Samarth's PC\\bin;C:\\ProgramData\\Miniconda3;C:\\ProgramData\\Miniconda3\\Library\\mingw-w64\\bin;C:\\ProgramData\\Miniconda3\\Library\\usr\\bin;C:\\ProgramData\\Miniconda3\\Library\\bin;C:\\ProgramData\\Miniconda3\\Scripts;C:\\Python27;C:\\Python27\\Scripts;C:\\Users\\Samarth's PC\\AppData\\Local\\Programs\\Python\\Python38-32\\python.exe;C:\\Program Files\\nodejs;C:\\ProgramData\\chocolatey\\bin;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0;C:\\WINDOWS\\System32\\OpenSSH;C:\\Program Files (x86)\\Yarn\\bin;C:\\Users\\Samarth's PC\\AppData\\Local\\Microsoft\\WindowsApps;C:\\Program Files\\MongoDB\\Server\\4.0\\bin;C:\\Program Files\\heroku\\bin;C:\\nvm;C:\\Program Files\\nodejs;C:\\Python 3.8;C:\\Users\\Samarth's PC\\AppData\\Roaming\\npm;C:\\Users\\Samarth's PC\\AppData\\Local\\Yarn\\bin;C:\\Users\\Samarth's PC\\AppData\\Local\\Programs\\Microsoft VS Code\\bin;C:\\Program Files\\Git\\usr\\bin\\vendor_perl;C:\\Program Files\\Git\\usr\\bin\\core_perl",
  port: -1
}
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! bookstore@1.0.0 start: `node app.js "app"`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the bookstore@1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Samarth's PC\AppData\Roaming\npm-cache\_logs\2019-12-20T16_43_00_131Z-debug.log

//Error log is here
0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli   'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'start',
1 verbose cli   'app'
1 verbose cli ]
2 info using npm@6.12.0
3 info using node@v12.13.0
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info lifecycle bookstore@1.0.0~prestart: bookstore@1.0.0
6 info lifecycle bookstore@1.0.0~start: bookstore@1.0.0
7 verbose lifecycle bookstore@1.0.0~start: unsafe-perm in lifecycle true
8 verbose lifecycle bookstore@1.0.0~start: PATH: C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;D:\BookStore\node_modules\.bin;C:\Users\Samarth's PC\bin;C:\Program Files\Git\mingw64\bin;C:\Program Files\Git\usr\local\bin;C:\Program Files\Git\usr\bin;C:\Program Files\Git\usr\bin;C:\Program Files\Git\mingw64\bin;C:\Program Files\Git\usr\bin;C:\Users\Samarth's PC\bin;C:\ProgramData\Miniconda3;C:\ProgramData\Miniconda3\Library\mingw-w64\bin;C:\ProgramData\Miniconda3\Library\usr\bin;C:\ProgramData\Miniconda3\Library\bin;C:\ProgramData\Miniconda3\Scripts;C:\Python27;C:\Python27\Scripts;C:\Users\Samarth's PC\AppData\Local\Programs\Python\Python38-32\python.exe;C:\Program Files\nodejs;C:\ProgramData\chocolatey\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0;C:\WINDOWS\System32\OpenSSH;C:\Program Files (x86)\Yarn\bin;C:\Users\Samarth's PC\AppData\Local\Microsoft\WindowsApps;C:\Program Files\MongoDB\Server\4.0\bin;C:\Program Files\heroku\bin;C:\nvm;C:\Program Files\nodejs;C:\Python 3.8;C:\Users\Samarth's PC\AppData\Roaming\npm;C:\Users\Samarth's PC\AppData\Local\Yarn\bin;C:\Users\Samarth's PC\AppData\Local\Programs\Microsoft VS Code\bin;C:\Program Files\Git\usr\bin\vendor_perl;C:\Program Files\Git\usr\bin\core_perl
9 verbose lifecycle bookstore@1.0.0~start: CWD: D:\BookStore
10 silly lifecycle bookstore@1.0.0~start: Args: [ '/d /s /c', 'node app.js "app"' ]
11 silly lifecycle bookstore@1.0.0~start: Returned: code: 1  signal: null
12 info lifecycle bookstore@1.0.0~start: Failed to exec start script
13 verbose stack Error: bookstore@1.0.0 start: `node app.js "app"`
13 verbose stack Exit status 1
13 verbose stack     at EventEmitter.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\index.js:332:16)
13 verbose stack     at EventEmitter.emit (events.js:210:5)
13 verbose stack     at ChildProcess.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:210:5)
13 verbose stack     at maybeClose (internal/child_process.js:1021:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:283:5)
14 verbose pkgid bookstore@1.0.0
15 verbose cwd D:\BookStore
16 verbose Windows_NT 10.0.18362
17 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "start" "app"
18 verbose node v12.13.0
19 verbose npm  v6.12.0
20 error code ELIFECYCLE
21 error errno 1
22 error bookstore@1.0.0 start: `node app.js "app"`
22 error Exit status 1
23 error Failed at the bookstore@1.0.0 start script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]


问:
How to show current URL inside embed
<embed src="snippet.html"> - I need to insert the custom url(othersite.com/directory/something/) + "search part" of the current URL inside src attribute. I get that something like "console.log(window.location.search)" can help, but how could I connect/insert that to be inside src?

In short, my embed code output should looks like: <embed src="othersite.com/directory/something/astalavista"> , when the current URL looks like this mysite.com/info/astalavista

How should my HTML code look like?

I use Wordpress. Need HTML code. Thanks.

答:
Try this</p>
```<code>const loc = new URL(location.href);
const lastPath = loc.pathname.split('/').pop();
const embed = document.createElement('embed');
embed.src = `https://othersite.com/directory/something/${lastPath}`
document.body.appendChild(embed)
</code>```

Title: How to show current URL inside embed

Body:
Try this

const loc = new URL(location.href);
const lastPath = loc.pathname.split('/').pop();
const embed = document.createElement('embed');
embed.src = `https://othersite.com/directory/something/${lastPath}`
document.body.appendChild(embed)


问:
Posix Equivalent for InterlockedExchange
What is the Posix equivalent to the Windows InterlockedExchange?

I have found the equivalent for InterlockedCompareExchange (i.e. __sync_val_compare_and_swap) but not simple exchange. I found this answer that gave a solution in assembly, but I need a cross platform/architecture C solution.

答:
If you have access to C2011 stdatomic.h, then I believe atomic_exchange is what you are looking for.

I am not aware of any other standardized equivalent.  In particular, the current version of POSIX does not mandate the presence of stdatomic.h (which is optional in C2011), and no version of POSIX has defined its own atomic operations, only higher-level thread synchronization operations (pthread_mutex_* for instakce).


问:
Flutter / Firebase project - Is `Unhandled Exception: Null check operator used on a null value` causing a blank screen?
I'm working on a flutter project with firebase. I'm currently developing on a MacBook, using a simulated iPhone (just in case this is relevant). I am able to run my app, but when doing so it's just a white blank screen that never goes away, it may also be pertinent to know this happens on the Chrome, and simulated Android devices too. Looking in the run window, I can see I have an error showing the following:

```<code>Launching lib/main.dart on iPhone 13 in debug mode...
Running Xcode build...
Xcode build done.                                           28.4s
Debug service listening on ws://127.0.0.1:61474/fF4XR-ozS5s=/ws
Syncing files to device iPhone 13...
[VERBOSE-2:ui_dart_state.cc(209)] Unhandled Exception: Null check operator used on a null value
#0      MethodChannel.binaryMessenger (package:flutter/src/services/platform_channel.dart:121:86)
#1      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:146:36)
#2      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:329:12)
#3      MethodChannel.invokeListMethod (package:flutter/src/services/platform_channel.dart:342:41)
#4      MethodChannelFirebase._initializeCore (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:31:37)
#5      MethodChannelFirebase.initializeApp (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:73:13)
#6      Firebase.initializeApp (package:firebase_core/src/firebase.dart:42:47)
#7      main (package:we_rise/main.dart:8:18)
#8      _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:145:25)
#9      _rootRun (dart:async/zon<…>
</code>```

Since I'm still quite a novice, I can't quite decipher what has gone wrong, or what I'm looking at here. Please find below my main.dart file code:

import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'database_config.dart';
import 'launch_page.dart';

void main() async {
  await Firebase.initializeApp(
    options: FirebaseOptions(
        apiKey: "foo",//"apiKey",
        appId: "foo",//"appId",
        messagingSenderId: "foo",//"messagingSenderId",
        projectId: "foo"),//"projectId"),
  );
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    SystemChrome.setPreferredOrientations(
      [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown],
    );
    return MaterialApp(
      theme: ThemeData(
        brightness: Brightness.light,
        fontFamily: 'BookmanOldStyle',
      ),
      home: LaunchPage(),
    );
  }
}
```
<p>I hope this is useful. I truly do not understand why it's presenting me with a blank white screen when the app loads. I also read this answer, but I don't think I've used a null check operator in my code. Any help, advice, and criticism is appreciated.</p>
<p><em><strong>EDIT: ADDED FLUTTER DOCTOR OUTPUT</strong></em></p>
<p><code>flutter doctor</code> output:</p>
<pre class="lang-dart prettyprint-override"><code>Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 2.5.3, on macOS 12.0.1 21A559 darwin-arm, locale en-GB)
[✓] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
[✓] Xcode - develop for iOS and macOS
[✓] Chrome - develop for the web
[✓] Android Studio (version 2020.3)
[✓] Connected device (2 available)

• No issues found!
</code>```

flutter doctor -v output:

```<code>flutter doctor -v
[✓] Flutter (Channel stable, 2.5.3, on macOS 12.0.1 21A559 darwin-arm, locale en-GB)
    • Flutter version 2.5.3 at /Users/me/Documents/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 18116933e7 (3 months ago), 2021-10-15 10:46:35 -0700
    • Engine revision d3ea636dc5
    • Dart version 2.14.4

[✓] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
    • Android SDK at /Users/me/Library/Android/sdk
    • Platform android-31, build-tools 31.0.0
    • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7249189)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 13.2.1, Build version 13C100
    • CocoaPods version 1.11.2

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2020.3)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7249189)

[✓] Connected device (2 available)
    • iPhone 13 (mobile) • C0D4EC95-07AF-46AB-A35E-F2B9F4437875 • ios            • com.apple.CoreSimulator.SimRuntime.iOS-15-2 (simulator)
    • Chrome (web)       • chrome                               • web-javascript • Google Chrome 97.0.4692.71

• No issues found!
</code>```

答:
To all those who come across this issue, what worked for me was creating a new project on the Windows version (I'm using android studio) and remaking the program on there, you can even copy and paste for the most part.

It seems to me that the main issue was that I do not own an iPhone while developing on MacOS, and consequently, I was unable to run this while it's linked to my developer profile.

Body:
I'm working on a flutter project with firebase. I'm currently developing on a MacBook, using a simulated iPhone (just in case this is relevant). I am able to run my app, but when doing so it's just a white blank screen that never goes away, it may also be pertinent to know this happens on the Chrome, and simulated Android devices too. Looking in the run window, I can see I have an error showing the following:

Launching lib/main.dart on iPhone 13 in debug mode...
Running Xcode build...
Xcode build done.                                           28.4s
Debug service listening on ws://127.0.0.1:61474/fF4XR-ozS5s=/ws
Syncing files to device iPhone 13...
[VERBOSE-2:ui_dart_state.cc(209)] Unhandled Exception: Null check operator used on a null value
#0      MethodChannel.binaryMessenger (package:flutter/src/services/platform_channel.dart:121:86)
#1      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:146:36)
#2      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:329:12)
#3      MethodChannel.invokeListMethod (package:flutter/src/services/platform_channel.dart:342:41)
#4      MethodChannelFirebase._initializeCore (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:31:37)
#5      MethodChannelFirebase.initializeApp (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:73:13)
#6      Firebase.initializeApp (package:firebase_core/src/firebase.dart:42:47)
#7      main (package:we_rise/main.dart:8:18)
#8      _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:145:25)
#9      _rootRun (dart:async/zon<…>

Since I'm still quite a novice, I can't quite decipher what has gone wrong, or what I'm looking at here. Please find below my main.dart file code:

import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'database_config.dart';
import 'launch_page.dart';

void main() async {
  await Firebase.initializeApp(
    options: FirebaseOptions(
        apiKey: "foo",//"apiKey",
        appId: "foo",//"appId",
        messagingSenderId: "foo",//"messagingSenderId",
        projectId: "foo"),//"projectId"),
  );
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    SystemChrome.setPreferredOrientations(
      [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown],
    );
    return MaterialApp(
      theme: ThemeData(
        brightness: Brightness.light,
        fontFamily: 'BookmanOldStyle',
      ),
      home: LaunchPage(),
    );
  }
}

I hope this is useful. I truly do not understand why it's presenting me with a blank white screen when the app loads. I also read this answer, but I don't think I've used a null check operator in my code. Any help, advice, and criticism is appreciated.

EDIT: ADDED FLUTTER DOCTOR OUTPUT

flutter doctor output:

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 2.5.3, on macOS 12.0.1 21A559 darwin-arm, locale en-GB)
[✓] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
[✓] Xcode - develop for iOS and macOS
[✓] Chrome - develop for the web
[✓] Android Studio (version 2020.3)
[✓] Connected device (2 available)

• No issues found!

flutter doctor -v output:

flutter doctor -v
[✓] Flutter (Channel stable, 2.5.3, on macOS 12.0.1 21A559 darwin-arm, locale en-GB)
    • Flutter version 2.5.3 at /Users/me/Documents/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 18116933e7 (3 months ago), 2021-10-15 10:46:35 -0700
    • Engine revision d3ea636dc5
    • Dart version 2.14.4

[✓] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
    • Android SDK at /Users/me/Library/Android/sdk
    • Platform android-31, build-tools 31.0.0
    • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7249189)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 13.2.1, Build version 13C100
    • CocoaPods version 1.11.2

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2020.3)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7249189)

[✓] Connected device (2 available)
    • iPhone 13 (mobile) • C0D4EC95-07AF-46AB-A35E-F2B9F4437875 • ios            • com.apple.CoreSimulator.SimRuntime.iOS-15-2 (simulator)
    • Chrome (web)       • chrome                               • web-javascript • Google Chrome 97.0.4692.71

• No issues found!


问:
Can I make dataframe that summarises/aggregates data from a much larger one?
I've got a horrendously large dataframe (covering hundreds of days worth of data) that contains data of the following pattern:

```<code>df = data.frame(date = c('2021-01-09', '2021-01-09', '2021-01-09', '2021-01-09', '2021-01-09', '2021-01-09', '2021-01-09', '2021-01-09', '2021-01-09', '2021-01-09'),
                category = c(UKS, USD, UKS, UKS, USD, USD, UKS, USD, UKZ, UKY),
                time = c(07:59:53, 08:00:03, 08:00:03, 08:00:03, 08:00:03, 08:00:04, 08:00:08, 08:00:11, 08:00:14, 08:00:15)
                quantity = c(0.001, 0.003, 0.018, 0.010, 0.043, 0.005, 0.023, 0.005, 0.001, 0.008)
                cumvol = c(0.001, 0.004, 0.022, 0.032, 0.075, 0.080, 0.103, 0.108, 0.109, 0.117)
                type = c(TSV, OSN, TSS, TSV, TSS, TSS, OSN, TSV, OSN, TSS)
</code>```

This dataframe cannot be changed, however what I would like to do is create a 'summary' dataframe from this one that sums together the total quantity for each category and type per day, as well as providing a total quantity on that day.

So using the above example:

```<code>For 2021-01-09
Total Quantity = 0.117
Total UKS = 0.052
Total USD = 0.056
Total UKZ = 0.001
Total UKY = 0.008
</code>```

Does anyone have any advice on how to achieve this for all the days I have data for?

答:
Although your question title includes "datatable", your input is a data.frame. Therefore I'll contribute a tidyverse approach here.

```<code>library(tidyverse)

df %>% group_by(date, category) %>%
  summarize(Total_quantity = sum(quantity), .groups = "drop") %>%
  group_by(date) %>%
  mutate(Total_date = sum(Total_quantity))

# A tibble: 4 x 4
# Groups:   date [1]
  date       category Total_quantity Date_total
  <chr>      <chr>             <dbl>      <dbl>
1 2021-01-09 UKS               0.052      0.117
2 2021-01-09 UKY               0.008      0.117
3 2021-01-09 UKZ               0.001      0.117
4 2021-01-09 USD               0.056      0.117
</code>```

Body:
I've got a horrendously large dataframe (covering hundreds of days worth of data) that contains data of the following pattern:

df = data.frame(date = c('2021-01-09', '2021-01-09', '2021-01-09', '2021-01-09', '2021-01-09', '2021-01-09', '2021-01-09', '2021-01-09', '2021-01-09', '2021-01-09'),
                category = c(UKS, USD, UKS, UKS, USD, USD, UKS, USD, UKZ, UKY),
                time = c(07:59:53, 08:00:03, 08:00:03, 08:00:03, 08:00:03, 08:00:04, 08:00:08, 08:00:11, 08:00:14, 08:00:15)
                quantity = c(0.001, 0.003, 0.018, 0.010, 0.043, 0.005, 0.023, 0.005, 0.001, 0.008)
                cumvol = c(0.001, 0.004, 0.022, 0.032, 0.075, 0.080, 0.103, 0.108, 0.109, 0.117)
                type = c(TSV, OSN, TSS, TSV, TSS, TSS, OSN, TSV, OSN, TSS)

This dataframe cannot be changed, however what I would like to do is create a 'summary' dataframe from this one that sums together the total quantity for each category and type per day, as well as providing a total quantity on that day.

So using the above example:

For 2021-01-09
Total Quantity = 0.117
Total UKS = 0.052
Total USD = 0.056
Total UKZ = 0.001
Total UKY = 0.008

Does anyone have any advice on how to achieve this for all the days I have data for?

Body:
Although your question title includes "datatable", your input is a data.frame. Therefore I'll contribute a tidyverse approach here.

library(tidyverse)

df %>% group_by(date, category) %>%
  summarize(Total_quantity = sum(quantity), .groups = "drop") %>%
  group_by(date) %>%
  mutate(Total_date = sum(Total_quantity))

# A tibble: 4 x 4
# Groups:   date [1]
  date       category Total_quantity Date_total
  <chr>      <chr>             <dbl>      <dbl>
1 2021-01-09 UKS               0.052      0.117
2 2021-01-09 UKY               0.008      0.117
3 2021-01-09 UKZ               0.001      0.117
4 2021-01-09 USD               0.056      0.117


问:
Defining sagemaker pipeline resource in Terraform
I'm rewriting a CloudFormation template into terraform and there is a CF resource I don't know the equivalent in TF.

The CF resource is AWS::SageMaker::Pipeline

Below is the fragment of the template.yaml

```<code>  pipeline:
    Type: AWS::SageMaker::Pipeline
    Properties:
      PipelineName: !Ref pPipelineName
      PipelineDisplayName: !Ref pPipelineName
      PipelineDescription: !Ref pPipelineDescription
      PipelineDefinition:
          PipelineDefinitionBody: !Sub "{\"Version\":\"2020-12-01\",........}}]}"
      RoleArn: !Ref pPipelineRoleArn
      Tags:
            - Key: project
              Value: !Ref pProjectName
</code>```

Have someone defined this resource in Terraform?

答:
It has not been officially added to the Terraform aws provider. However, recently a provider that helps people test different new features has been added to Terraform, and it is called AWS Cloud Control provider, awscc. An example on how to use this provider is given in [1]. There are also tutorials on HashiCorp Learn [2]. The resource you are looking for is given in [3].

[1] https://registry.terraform.io/providers/hashicorp/awscc

[2] https://learn.hashicorp.com/tutorials/terraform/aws-cloud-control

[3] https://registry.terraform.io/providers/hashicorp/awscc/latest/docs/resources/sagemaker_pipeline

Body:
I'm rewriting a CloudFormation template into terraform and there is a CF resource I don't know the equivalent in TF.

The CF resource is AWS::SageMaker::Pipeline

Below is the fragment of the template.yaml

  pipeline:
    Type: AWS::SageMaker::Pipeline
    Properties:
      PipelineName: !Ref pPipelineName
      PipelineDisplayName: !Ref pPipelineName
      PipelineDescription: !Ref pPipelineDescription
      PipelineDefinition:
          PipelineDefinitionBody: !Sub "{\"Version\":\"2020-12-01\",........}}]}"
      RoleArn: !Ref pPipelineRoleArn
      Tags:
            - Key: project
              Value: !Ref pProjectName

Have someone defined this resource in Terraform?


问:
Python code to print out value in any variable
What are some good ways to "pretty print" values of any variable (and anything inside the variable), whether it is:

scalar

object

list of scalar or objects

dict of scalar or objects

tuple of scalar or objects

Thanks

答:
```<code>from pprint import pprint

pprint(var)
</code>```

And if you don't like pprint, try https://pypi.org/project/pprintpp/

Body:
from pprint import pprint

pprint(var)

And if you don't like pprint, try https://pypi.org/project/pprintpp/


问:
Spring parallel processing inside a transaction
I have lots of micro services that perform database custom logic on pretty big data volumes. Every instance of these microservices use the following query: select * from ENTITY_TABLE for update skip locked to organize parallel work on this data and prevent data sets intersections.

The thing is that on each entity fecthed (batch size is around 100) I need to perform 3 more db requests and this takes pretty much time and not effective in general.

What I'd like to do is to organize parallel processing of each entity inside one big transaction. The main problem is that spring doesn't allow this. My code is something like this:

```<code>public class Manager {
    private final Fetcher fetcher;
    private final Processor processor;
    private TransactionTemplate transactionTemplate;

    public void doWork(int batchSize) {
        transactionTemplate.executeWithoutResult(status -> {
            List<MyEntity> entities = fetcher.fetch(batchSize);
            List<CompletableFuture<Boolean>> resultList = new ArrayList<>();
            for(MyEntity me : entities) {
                resultList.add(processor.process(entity));
            }
            CompletableFuture.allOf(resultList.toArray(new CompletableFuture[0])).join();
        });
    }
}

public class Fetcher {
    private JdbcTemplate jdbcTemplate;

    public List<MyEntity> fetch(int batchSize) {
        jdbcTemplate.setFetchSize(batchSize);
        jdbcTemplate.setMaxRows(batchSize);
        return jdbcTemplate.query("select * from ENTITY_TABLE for update skip locked", new BeanPropertyRowMapper<>(MyEntity.class);
    }
}

public class Processor() {
    @Async // <- this messes up transaction and makes it impossible to perform this work in parallel fashion inside transaction opened in the Manager class
    public void CompletableFuture<Boolean> process(MyEntity me) {
        boolean exists = repository.existsRelatedEntity(me.getId());
        if (!exists) {
            repository.createRelatedEntity(new RelatedEntity(/*..*/));
        } else {
            repository.updateRelatedEntity(me);
        }
        repository.markProcessed(me);
    }
}

</code>```

And the question is: Do I have any options here to make this possible to parallel work on te process function? Do I have some possibility to point jdbcTemplate on the transaction it should use for its opertions?

Any help is greatly appreciated.

Disclaimer: I know that I can mark all of the selected entities with help of additional update query and then process them one by one in separate transactions but I would like to see if I have any options here cause I simplified the code and in reality it is much more complex and would require a big rework in case of logic changes.

答:
If Fetcher and Processor are in the same service it should work in the same transaction after adding @Transactional(isolation = Isolation.READ_UNCOMMITTED) annotation on public void doWork(int batchSize);
I tested this with spring repository instead of JdbcTemplate and it seems to be working.

If you have any errors, please add it to your post

Body:
I have lots of micro services that perform database custom logic on pretty big data volumes. Every instance of these microservices use the following query: select * from ENTITY_TABLE for update skip locked to organize parallel work on this data and prevent data sets intersections.

The thing is that on each entity fecthed (batch size is around 100) I need to perform 3 more db requests and this takes pretty much time and not effective in general.

What I'd like to do is to organize parallel processing of each entity inside one big transaction. The main problem is that spring doesn't allow this. My code is something like this:

public class Manager {
    private final Fetcher fetcher;
    private final Processor processor;
    private TransactionTemplate transactionTemplate;

    public void doWork(int batchSize) {
        transactionTemplate.executeWithoutResult(status -> {
            List<MyEntity> entities = fetcher.fetch(batchSize);
            List<CompletableFuture<Boolean>> resultList = new ArrayList<>();
            for(MyEntity me : entities) {
                resultList.add(processor.process(entity));
            }
            CompletableFuture.allOf(resultList.toArray(new CompletableFuture[0])).join();
        });
    }
}

public class Fetcher {
    private JdbcTemplate jdbcTemplate;

    public List<MyEntity> fetch(int batchSize) {
        jdbcTemplate.setFetchSize(batchSize);
        jdbcTemplate.setMaxRows(batchSize);
        return jdbcTemplate.query("select * from ENTITY_TABLE for update skip locked", new BeanPropertyRowMapper<>(MyEntity.class);
    }
}

public class Processor() {
    @Async // <- this messes up transaction and makes it impossible to perform this work in parallel fashion inside transaction opened in the Manager class
    public void CompletableFuture<Boolean> process(MyEntity me) {
        boolean exists = repository.existsRelatedEntity(me.getId());
        if (!exists) {
            repository.createRelatedEntity(new RelatedEntity(/*..*/));
        } else {
            repository.updateRelatedEntity(me);
        }
        repository.markProcessed(me);
    }
}

And the question is: Do I have any options here to make this possible to parallel work on te process function? Do I have some possibility to point jdbcTemplate on the transaction it should use for its opertions?

Any help is greatly appreciated.

Disclaimer: I know that I can mark all of the selected entities with help of additional update query and then process them one by one in separate transactions but I would like to see if I have any options here cause I simplified the code and in reality it is much more complex and would require a big rework in case of logic changes.


问:
Calling constructor of parent class in static method of child class
I got a problem with calling super inside of the child static method.

```<code>const _todos = [];

class Todo {
  constructor(title) {
    this.title = title;
    this.id = Math.round(Math.random() * 100);
    _todos.push({title, id: this.id});

    console.log(`Todo ID: ${this.id}. DONT FORGET IT!`);
  }

  static TodoerVersion = '1.8';

  static removeTodo(id) {
    const todoIndex = _todos.findIndex(t => t.id == id);
    _todos.splice(todoIndex, 1);
  }
}

class TodoV2 extends Todo {
  static addTodo(title) {
    super(title);
  }

  static addDescription(todo, description) {
    todo.description = description;
  }

  static TodoerVersion = '2.0';
};

new TodoV2("play guitar");
</code>```

Why does it not work?
But if i call super in normal method, it would works just fine.

答:
super is only callable within the constructor function of a class.

Two answers for you:

The question you actually asked.

What I think you should do instead. :-)

Answering the question you asked:

JavaScript is very special in this regard: this has meaning in static methods (as long as you call them correctly, e.g. TodoV2.addTodo("title")): it's the constructor function you called the static method on. And a subclass constructor function inherits from its superclass constructor function (yes, really). So you can access the constructor function for the parent class using Object.getPrototypeOf(this) in the static method:

```<code>// This is something unusual that JavaScript actually does support
static addTodo(title) {
    const ctor = Object.getPrototypeOf(this);
    return new ctor(title);
}
</code>```

To handle the case where the user may have called addTodo in a way that doesn't set this, you might do something like this to default to TodoV2 if this is undefined:

```<code>static addTodo(title) {
    const ctor = Object.getPrototypeOf(this ?? TodoV2);
    return new ctor(title);
}
</code>```

What I think you should do instead

You shouldn't be using a static method for this. Instead, define a constructor for TodoV2:

```<code>class TodoV2 extends Todo {
    constructor(title, description) {
        super(title);
        this.description = description ?? "";
    }

    static addTodo(title) { // Why no `description`?
        return new this(title); // Or `new TodoV2(title)`
    }
}
</code>```

You might also look into the Symbol.species pattern if you want subclasses to create instances of superclasses.

Body:
I got a problem with calling super inside of the child static method.

const _todos = [];

class Todo {
  constructor(title) {
    this.title = title;
    this.id = Math.round(Math.random() * 100);
    _todos.push({title, id: this.id});

    console.log(`Todo ID: ${this.id}. DONT FORGET IT!`);
  }

  static TodoerVersion = '1.8';

  static removeTodo(id) {
    const todoIndex = _todos.findIndex(t => t.id == id);
    _todos.splice(todoIndex, 1);
  }
}

class TodoV2 extends Todo {
  static addTodo(title) {
    super(title);
  }

  static addDescription(todo, description) {
    todo.description = description;
  }

  static TodoerVersion = '2.0';
};

new TodoV2("play guitar");

Why does it not work?
But if i call super in normal method, it would works just fine.

Body:
super is only callable within the constructor function of a class.

Two answers for you:

The question you actually asked.

What I think you should do instead. :-)

Answering the question you asked:

JavaScript is very special in this regard: this has meaning in static methods (as long as you call them correctly, e.g. TodoV2.addTodo("title")): it's the constructor function you called the static method on. And a subclass constructor function inherits from its superclass constructor function (yes, really). So you can access the constructor function for the parent class using Object.getPrototypeOf(this) in the static method:

// This is something unusual that JavaScript actually does support
static addTodo(title) {
    const ctor = Object.getPrototypeOf(this);
    return new ctor(title);
}

To handle the case where the user may have called addTodo in a way that doesn't set this, you might do something like this to default to TodoV2 if this is undefined:

static addTodo(title) {
    const ctor = Object.getPrototypeOf(this ?? TodoV2);
    return new ctor(title);
}

What I think you should do instead

You shouldn't be using a static method for this. Instead, define a constructor for TodoV2:

class TodoV2 extends Todo {
    constructor(title, description) {
        super(title);
        this.description = description ?? "";
    }

    static addTodo(title) { // Why no `description`?
        return new this(title); // Or `new TodoV2(title)`
    }
}

You might also look into the Symbol.species pattern if you want subclasses to create instances of superclasses.


问:
WITH queries with INSERT in MySQL
I'm trying to do something that I'm almost positive works in Postgresql:

```<code>WITH cte AS (SELECT something FROM something WHERE something.name='reference')
INSERT INTO somewhere (id, name)
SELECT cte.id, 'John'
UNION ALL
SELECT cte.id, 'Frank'
UNION ALL
SELECT cte.id, 'Thomas'
;
</code>```

In other words, I want to grab the "something" row to be used for a bunch of new rows in "somwhere". Each new entry should have a reference (like  foreign key value) back to the same "something" row in the cte, mostly just to avoid a mess. However, MySQL is giving me that "blank stare" syntax error mechanism. Does MySQL allow WITH ... INSERT ...;?

Here's the actual code; it's just setting up test data:

```<code>WITH
  pr AS (SELECT pr_id from property AS p WHERE p.pr_name = 'Royal Oaks Plaza'),
  u AS (SELECT pr.pr_id AS pr_id, utyp.utyp_name AS utyp_name, utyp.utyp_id AS utyp_id FROM unit_type AS utyp, pr)
    INSERT INTO unit (pr_id, unt_number, utyp_id, unt_size)
    SELECT pr_id, '100', utyp_id, FLOOR(500 + RAND() * 2000)
      FROM u WHERE utyp_name = 'BEAUTY'
    UNION ALL
    SELECT pr_id, '110', utyp_id, FLOOR(500 + RAND() * 2000)
      FROM u WHERE utyp_name = 'RESTAURANT'
;
</code>```

答:
You can try to use a subquery to do the UNION ALL because CTE only can be used in the first query.

```<code>WITH cte AS (SELECT something FROM something WHERE something.name='reference')
INSERT INTO somewhere (id, name)
SELECT id,name
FROM (
    SELECT cte.id, 'John' name
    UNION ALL
    SELECT cte.id, 'Frank'
    UNION ALL
    SELECT cte.id, 'Thomas'
) t1;
</code>```

so you can do that in your query

```<code>WITH
  pr AS (SELECT pr_id from property AS p WHERE p.pr_name = 'Royal Oaks Plaza'),
  u AS (SELECT pr.pr_id AS pr_id, utyp.utyp_name AS utyp_name, utyp.utyp_id AS utyp_id FROM unit_type AS utyp, pr)
    INSERT INTO unit (pr_id, unt_number, utyp_id, unt_size)
    SELECT pr_id,utyp_id,num
    FROM (
        SELECT pr_id, '100', utyp_id, FLOOR(500 + RAND() * 2000)
        FROM u WHERE utyp_name = 'BEAUTY'
        UNION ALL
        SELECT pr_id, '110', utyp_id, FLOOR(500 + RAND() * 2000) num
        FROM u WHERE utyp_name = 'RESTAURANT'
    ) t1
;
</code>```

from your query I would rewrite by IN instead of UNION ALL

```<code>WITH
  pr AS (SELECT pr_id from property AS p WHERE p.pr_name = 'Royal Oaks Plaza'),
  u AS (SELECT pr.pr_id AS pr_id, utyp.utyp_name AS utyp_name, utyp.utyp_id AS utyp_id FROM unit_type AS utyp, pr)
    INSERT INTO unit (pr_id, unt_number, utyp_id, unt_size)
    SELECT pr_id, '110', utyp_id, FLOOR(500 + RAND() * 2000) num
    FROM u
    WHERE utyp_name IN ('RESTAURANT','BEAUTY')

;
</code>```

Title: WITH queries with INSERT in MySQL

Body:
I'm trying to do something that I'm almost positive works in Postgresql:

WITH cte AS (SELECT something FROM something WHERE something.name='reference')
INSERT INTO somewhere (id, name)
SELECT cte.id, 'John'
UNION ALL
SELECT cte.id, 'Frank'
UNION ALL
SELECT cte.id, 'Thomas'
;

In other words, I want to grab the "something" row to be used for a bunch of new rows in "somwhere". Each new entry should have a reference (like  foreign key value) back to the same "something" row in the cte, mostly just to avoid a mess. However, MySQL is giving me that "blank stare" syntax error mechanism. Does MySQL allow WITH ... INSERT ...;?

Here's the actual code; it's just setting up test data:

WITH
  pr AS (SELECT pr_id from property AS p WHERE p.pr_name = 'Royal Oaks Plaza'),
  u AS (SELECT pr.pr_id AS pr_id, utyp.utyp_name AS utyp_name, utyp.utyp_id AS utyp_id FROM unit_type AS utyp, pr)
    INSERT INTO unit (pr_id, unt_number, utyp_id, unt_size)
    SELECT pr_id, '100', utyp_id, FLOOR(500 + RAND() * 2000)
      FROM u WHERE utyp_name = 'BEAUTY'
    UNION ALL
    SELECT pr_id, '110', utyp_id, FLOOR(500 + RAND() * 2000)
      FROM u WHERE utyp_name = 'RESTAURANT'
;

Body:
You can try to use a subquery to do the UNION ALL because CTE only can be used in the first query.

WITH cte AS (SELECT something FROM something WHERE something.name='reference')
INSERT INTO somewhere (id, name)
SELECT id,name
FROM (
    SELECT cte.id, 'John' name
    UNION ALL
    SELECT cte.id, 'Frank'
    UNION ALL
    SELECT cte.id, 'Thomas'
) t1;

so you can do that in your query

WITH
  pr AS (SELECT pr_id from property AS p WHERE p.pr_name = 'Royal Oaks Plaza'),
  u AS (SELECT pr.pr_id AS pr_id, utyp.utyp_name AS utyp_name, utyp.utyp_id AS utyp_id FROM unit_type AS utyp, pr)
    INSERT INTO unit (pr_id, unt_number, utyp_id, unt_size)
    SELECT pr_id,utyp_id,num
    FROM (
        SELECT pr_id, '100', utyp_id, FLOOR(500 + RAND() * 2000)
        FROM u WHERE utyp_name = 'BEAUTY'
        UNION ALL
        SELECT pr_id, '110', utyp_id, FLOOR(500 + RAND() * 2000) num
        FROM u WHERE utyp_name = 'RESTAURANT'
    ) t1
;

from your query I would rewrite by IN instead of UNION ALL

WITH
  pr AS (SELECT pr_id from property AS p WHERE p.pr_name = 'Royal Oaks Plaza'),
  u AS (SELECT pr.pr_id AS pr_id, utyp.utyp_name AS utyp_name, utyp.utyp_id AS utyp_id FROM unit_type AS utyp, pr)
    INSERT INTO unit (pr_id, unt_number, utyp_id, unt_size)
    SELECT pr_id, '110', utyp_id, FLOOR(500 + RAND() * 2000) num
    FROM u
    WHERE utyp_name IN ('RESTAURANT','BEAUTY')

;


问:
PHP Re-create Wordpress the_loop
I'm currently working on a basic, but bespoke CMS that we will be using across several of our sites. Before anyone flames me, I am well aware of other alternatives, however nothing we have tried is really flexible enough for our data.

With that out of the way, I shall begin.

One of the features I do like from Wordpress is the known as The Loop.

```<code>while(have_posts()) : the_content();
    the_content();
endwhile;
</code>```

I've studied the code and come up with a similar class, which you can see here.

From looking at the code, I've figured out that, has_posts() seems to be returning a boolean if there are still posts in an array.

the_article is saying that we're still in the loop, so set a variable for the articles(posts) with the data we need.

I've kind of got this working, however I only seem to be able to get one piece of information from the array:

```<code>while (have_articles()): the_article();
    echo "<h1 class='title'>" . the_title() . "</h1>";
endwhile;
</code>```

Where the_title is:

```<code>function the_title() {
    global $AC;

    return $AC->p_title;
}
</code>```

Thanks for the help!

答:
I changed current_article to a public and not a static value, which helped. It also turned out that my function, the_title was accessing the wrong field name.

This problem is solved.

@Everyone who answered; your opinions are valued, and I agree, the loop is with its problems and stuff, but it also provides an easy (when you're in control) way of causing content to how you want it, easily. See Wordpress Themes.

ContentLicense: CC BY-SA 3.0

Title: PHP Re-create Wordpress the_loop

Body:
I'm currently working on a basic, but bespoke CMS that we will be using across several of our sites. Before anyone flames me, I am well aware of other alternatives, however nothing we have tried is really flexible enough for our data.

With that out of the way, I shall begin.

One of the features I do like from Wordpress is the known as The Loop.

while(have_posts()) : the_content();
    the_content();
endwhile;

I've studied the code and come up with a similar class, which you can see here.

From looking at the code, I've figured out that, has_posts() seems to be returning a boolean if there are still posts in an array.

the_article is saying that we're still in the loop, so set a variable for the articles(posts) with the data we need.

I've kind of got this working, however I only seem to be able to get one piece of information from the array:

while (have_articles()): the_article();
    echo "
" . the_title() . "
";
endwhile;

Where the_title is:

function the_title() {
    global $AC;

    return $AC->p_title;
}

Thanks for the help!


问:
How to get each letter of word list python
```<code>l = ['hello', 'world', 'monday']
        for i in range(n):
            word = input()
            l.append(word)
        for j in l[0]:
            print(j)
    Output : h e l l o
</code>```

I would like to do it for every word in l.

I want to keep my list intact because i would need to get len() of each word and i won't know the number of word that i could possibly get.
I don't know if i'm clear enough, if you need more informations let me know, thanks !

答:
```<code>def split_into_letters(word):
    return ' '.join(word)
lst = ['hello', 'world', 'monday']
lst_2 = list(map(split_into_letters, lst))
print(lst_2)
</code>```

You can map each word to a function that splits it into letters

Body:
l = ['hello', 'world', 'monday']
        for i in range(n):
            word = input()
            l.append(word)
        for j in l[0]:
            print(j)
    Output : h e l l o

I would like to do it for every word in l.

I want to keep my list intact because i would need to get len() of each word and i won't know the number of word that i could possibly get.
I don't know if i'm clear enough, if you need more informations let me know, thanks !

Body:
def split_into_letters(word):
    return ' '.join(word)
lst = ['hello', 'world', 'monday']
lst_2 = list(map(split_into_letters, lst))
print(lst_2)

You can map each word to a function that splits it into letters


问:
Turning date into integers in R
I have a data frame in R and I have a month column and a day column containing characters like "jan", "feb", or "mar" for months or "mon", "tue" or "wed" for days. I would like to find a way to convert both columns into integers ranging from 1 to 12 for months and 1 to 7 for days. I have tried built-in functions like month.abb but when I try using match with the column for months it just returns a list of NA. Thank you very much for your help !</p>

答:
Use match:

match(c("jan", "feb", "may"), tolower(month.abb))
match(c("mon", "tue", "thur"), c("mon", "tue", "wed", "thur", "fri", "sat", "sun"))
```

Title: Turning date into integers in R


问:
dataframe importing column's first value as column name while reading a CSV file
Whenever I read a csv file using pd.read_csv('file_name.csv') that has no column names, the first value is converted to the Column's name. What can be done ( if it can be done ) to rectify the situation by using Python only. Please don't suggest to open file manually and then place column names in it.

答:
It depends on what your needs are:

If you already know or want to specify your column names, there is no need to use header = None parameter in pd.read_csv(). Here is a demo example :

df = pd.read_csv(file_path, names=['name1', 'name2'])

else just use:

df = pd.read_csv(file_path, header=None)


问:
Djnago : AttributeError: module 'django.views.generic' has no attribute 'Detail'
where can I import the detail attribute from?

views.py:

```<code>from django.shortcuts import render
from django.views import generic

from . import models

class Index(generic.TemplateView):

   template_name='catalog/index.html'

   def get_context_data(self, **kwargs):
       context = super().get_context_data(**kwargs)
       context['num_books'] = models.Book.objects.all().count()
       context['num_instances'] = models.BookInstance.objects.all().count()
       context['num_instances_available'] = models.BookInstance.objects.filter(status__exact='a').count()
       context['num_authors'] = models.Author.objects.count()

       return context

class BookListView(generic.ListView):

   model = models.Book
   template_name = 'catalog/book_list.html'

class BookDetialView(generic.Detail.View):

   model= models.Book
   template_name = 'catalog/book_detail.html'
</code>```

urls.py

```<code>from django.urls import include, path, re_path
from . import views
from django.views.generic import TemplateView

app_name='catalog'
urlpatterns = [
   path(r'', views.Index.as_view(), name='index'),
   re_path(r'^$', views.Index.as_view(), name='index')
]

urlpatterns = [
   path(r'^$', views.index, name='index'),
   path(r'^books/$', views.BookListView.as_view(), name='books'),
   path(r'^book/(?P<pk>\d+)$', views.BookDetailView.as_view(), name='book-detail'),
]
</code>```

but the result:

class BookDetialView(generic.Detail.View):

AttributeError: module 'django.views.generic' has no attribute 'Detail'

答: Should be generic.DetailViewinstead of generic.Detail.View

Body:
where can I import the detail attribute from?

views.py:

from django.shortcuts import render
from django.views import generic

from . import models

class Index(generic.TemplateView):

   template_name='catalog/index.html'

   def get_context_data(self, **kwargs):
       context = super().get_context_data(**kwargs)
       context['num_books'] = models.Book.objects.all().count()
       context['num_instances'] = models.BookInstance.objects.all().count()
       context['num_instances_available'] = models.BookInstance.objects.filter(status__exact='a').count()
       context['num_authors'] = models.Author.objects.count()

       return context

class BookListView(generic.ListView):

   model = models.Book
   template_name = 'catalog/book_list.html'

class BookDetialView(generic.Detail.View):

   model= models.Book
   template_name = 'catalog/book_detail.html'

urls.py

from django.urls import include, path, re_path
from . import views
from django.views.generic import TemplateView

app_name='catalog'
urlpatterns = [
   path(r'', views.Index.as_view(), name='index'),
   re_path(r'^$', views.Index.as_view(), name='index')
]

urlpatterns = [
   path(r'^$', views.index, name='index'),
   path(r'^books/$', views.BookListView.as_view(), name='books'),
   path(r'^book/(?P<pk>\d+)$', views.BookDetailView.as_view(), name='book-detail'),
]

but the result:

class BookDetialView(generic.Detail.View):

AttributeError: module 'django.views.generic' has no attribute 'Detail'


问:
Request Data returned with JSON response
Hey

When sending a request to our Laravel API via POST method the request JSON data is sometimes returned in the JSON response, which results in an invalid response. See below for an example. The strange thing is if we restart the docker container the expected response is given for a bit, and then after a while, it goes back to adding the request data to the response.

I've spent a bit trying to find solutions but nothing I find works. So I'm hoping that someone here can help. From what I've found it seems like it's a nginx issue, and I've tried to disable cache and proxy request buffering but the issue still comes back.

Nginx Location Config

```<code>location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass php:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        proxy_cache off;
        proxy_no_cache 1;
        proxy_cache_bypass 1;
        if_modified_since off;
        expires off;
        etag off;
        proxy_request_buffering off;
    }
</code>```

Our setup

```<code>PHP Image: php:8.1.0-fpm-alpine3.15
Nginx Image: nginx:stable-alpine
Laravel Version: 8.78.1
</code>```

Request

```<code>{
    "first_name": "John",
    "last_name": "Doe"
}
</code>```

Controller

```<code>public function store(SomeRequest $request)
{
    $createdModel = SomeModel::create($request->validated());

    return response()->json([
        'model' => $createdModel
    ]);
}
</code>```

Response

```<code>{
    "first_name": "John",
    "last_name": "Doe"
}
{
    "model" => {
        "id" : 1,
        "first_name": "John",
        "last_name": "Doe"
    }
}
</code>```

答:
This issue was fixed by disallowing external connections to PHP-FPM (Port 9000).

We tracked down the issue and found that after a while PHP changed allow_url_include from Off to On. By blocking the port, it stopped changing the value by itself.

Body:
Hey

When sending a request to our Laravel API via POST method the request JSON data is sometimes returned in the JSON response, which results in an invalid response. See below for an example. The strange thing is if we restart the docker container the expected response is given for a bit, and then after a while, it goes back to adding the request data to the response.

I've spent a bit trying to find solutions but nothing I find works. So I'm hoping that someone here can help. From what I've found it seems like it's a nginx issue, and I've tried to disable cache and proxy request buffering but the issue still comes back.

Nginx Location Config

location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass php:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        proxy_cache off;
        proxy_no_cache 1;
        proxy_cache_bypass 1;
        if_modified_since off;
        expires off;
        etag off;
        proxy_request_buffering off;
    }

Our setup

PHP Image: php:8.1.0-fpm-alpine3.15
Nginx Image: nginx:stable-alpine
Laravel Version: 8.78.1

Request

{
    "first_name": "John",
    "last_name": "Doe"
}

Controller

public function store(SomeRequest $request)
{
    $createdModel = SomeModel::create($request->validated());

    return response()->json([
        'model' => $createdModel
    ]);
}

Response

{
    "first_name": "John",
    "last_name": "Doe"
}
{
    "model" => {
        "id" : 1,
        "first_name": "John",
        "last_name": "Doe"
    }
}


问:
Access database Connection string error in asp
I have created an asp feedback web page this page connect with the access database
when I run this page every thing is ok until I click to submit button
When I click submit button it gives error like

and here is my asp code

```<code><%
DIM objConn
Set objConn = Server.CreateObject("ADODB.Connection")
objConn.ConnectionString =Provider=Microsoft.Jet.OLEDB.4.0;
 Data Source="Server.MapPath("/MyData.mdb")

objConn.Open
%>
<%
DIM objRS
Set objRS = Server.CreateObject("ADODB.Recordset")
objRS.Open "tblContact",objConn,adLockOptimistic,adCmdTable
objRS.AddNew
objRS("Email") = Request.Form("Email")
objRS("FirstName") = Request.Form("FirstName")
objRS("LastName") = Request.Form("LastName")
objRS("Comments") = Request.Form("Comments")
objRS("DateContacted") = Date()
objRS.Update
%>

<%
DIM strFirstName
strFirstName = Request.Form("FirstName")
%>

<%
objRS.Close
Set objRS = Nothing
objCONN.Close
Set objCONN = Nothing
%>
</code>```

答:
Update

```<code>objConn.ConnectionString =Provider=Microsoft.Jet.OLEDB.4.0;
 Data Source="Server.MapPath("/MyData.mdb")
</code>```

with

```<code>objConn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath("/MyData.mdb")
</code>```

Body:
I have created an asp feedback web page this page connect with the access database
when I run this page every thing is ok until I click to submit button
When I click submit button it gives error like

and here is my asp code

<%
DIM objConn
Set objConn = Server.CreateObject("ADODB.Connection")
objConn.ConnectionString =Provider=Microsoft.Jet.OLEDB.4.0;
 Data Source="Server.MapPath("/MyData.mdb")

objConn.Open
%>
<%
DIM objRS
Set objRS = Server.CreateObject("ADODB.Recordset")
objRS.Open "tblContact",objConn,adLockOptimistic,adCmdTable
objRS.AddNew
objRS("Email") = Request.Form("Email")
objRS("FirstName") = Request.Form("FirstName")
objRS("LastName") = Request.Form("LastName")
objRS("Comments") = Request.Form("Comments")
objRS("DateContacted") = Date()
objRS.Update
%>

<%
DIM strFirstName
strFirstName = Request.Form("FirstName")
%>

<%
objRS.Close
Set objRS = Nothing
objCONN.Close
Set objCONN = Nothing
%>

Body:
Update

objConn.ConnectionString =Provider=Microsoft.Jet.OLEDB.4.0;
 Data Source="Server.MapPath("/MyData.mdb")

with

objConn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath("/MyData.mdb")


问:
React-Native: cannot update a component while rendering a different component
I've got this simple component Login:

```<code>function Login() {
  const [isFormValidState, setIsFormValidState] = React.useState(false);
  const [credentialState, setCredentialState] = React.useState();

  function getFormErrors(errors: any, dirty: boolean) {
    setIsFormValidState(!Object.keys(errors).length && dirty);
  }

  function getFormValues(values: any) {
    setCredentialState(values);
  }

  function doAction() {
    //credentialState rest call...
  }

  return (
    <View>
      <Text>Login</Text>
      <UserCredentialForm getFormValues={getFormValues} getFormErrors={getFormErrors}/>
      <Button title='Entra' disabled={!isFormValidState} onPress={doAction}/>
    </View>
  );
}
</code>```

Which calls UserCredentialForm:

```<code>export default function UserCredentialForm({ getFormValues, getFormErrors }) {
[...]
  return (
    <Formik innerRef={formRef} validationSchema={formSchema} initialValues={state.form} onSubmit={() => { }}>
      {({ handleChange, values, touched, errors, dirty }) => {
        getFormValues(values);
        getFormErrors(errors, dirty);
        return <React.Fragment>
          // <TextInput/>....
        </React.Fragment>
      }}
    </Formik>
  );

[...]
}
</code>```

While navigating in my app I've got this error:

react native cannot update a component Login while rendering a
different component Formik.

Then it points me to the error in the setCredentialState inside getFormValues handler in Login component.
I've resolved this using a ref instead of a state, but the problem itself is unsolved to me.

What if I need to update my parent component view after a child event?

答:
Simple example can be like

UserCredentialForm:

```<code> // Formik x React Native example
 import React from 'react';
 import { Button, TextInput, View } from 'react-native';
 import { Formik } from 'formik';

 export const MyReactNativeForm = ({onSubmit}) => (
   <Formik
     initialValues={{ email: '' }}
     onSubmit={values => onSubmit(values)}
   >
     {({ handleChange, handleBlur, handleSubmit, values }) => (
       <View>
         <TextInput
           onChangeText={handleChange('email')}
           onBlur={handleBlur('email')}
           value={values.email}
         />
         <Button onPress={handleSubmit} title="Submit" />
       </View>
     )}
   </Formik>
 );
</code>```

Usage like

```<code>function Login() {

  function doAction(values) {
    console.log(values);
    //credentialState rest call...
  }

  return (
    <View>
      ....
      <UserCredentialForm onSubmit={doAction} />
      ....
    </View>
  );
}
</code>```

Body:
I've got this simple component Login:

function Login() {
  const [isFormValidState, setIsFormValidState] = React.useState(false);
  const [credentialState, setCredentialState] = React.useState();

  function getFormErrors(errors: any, dirty: boolean) {
    setIsFormValidState(!Object.keys(errors).length && dirty);
  }

  function getFormValues(values: any) {
    setCredentialState(values);
  }

  function doAction() {
    //credentialState rest call...
  }

  return (
    <View>
      <Text>Login</Text>
      <UserCredentialForm getFormValues={getFormValues} getFormErrors={getFormErrors}/>
      <Button title='Entra' disabled={!isFormValidState} onPress={doAction}/>
    </View>
  );
}

Which calls UserCredentialForm:

export default function UserCredentialForm({ getFormValues, getFormErrors }) {
[...]
  return (
    <Formik innerRef={formRef} validationSchema={formSchema} initialValues={state.form} onSubmit={() => { }}>
      {({ handleChange, values, touched, errors, dirty }) => {
        getFormValues(values);
        getFormErrors(errors, dirty);
        return <React.Fragment>
          // <TextInput/>....
        </React.Fragment>
      }}
    </Formik>
  );

[...]
}

While navigating in my app I've got this error:

react native cannot update a component Login while rendering a
different component Formik.

Then it points me to the error in the setCredentialState inside getFormValues handler in Login component.
I've resolved this using a ref instead of a state, but the problem itself is unsolved to me.

What if I need to update my parent component view after a child event?

Body:
Simple example can be like

UserCredentialForm:

 // Formik x React Native example
 import React from 'react';
 import { Button, TextInput, View } from 'react-native';
 import { Formik } from 'formik';

 export const MyReactNativeForm = ({onSubmit}) => (
   <Formik
     initialValues={{ email: '' }}
     onSubmit={values => onSubmit(values)}
   >
     {({ handleChange, handleBlur, handleSubmit, values }) => (
       <View>
         <TextInput
           onChangeText={handleChange('email')}
           onBlur={handleBlur('email')}
           value={values.email}
         />
         <Button onPress={handleSubmit} title="Submit" />
       </View>
     )}
   </Formik>
 );

Usage like

function Login() {

  function doAction(values) {
    console.log(values);
    //credentialState rest call...
  }

  return (
    <View>
      ....
      <UserCredentialForm onSubmit={doAction} />
      ....
    </View>
  );
}


问:
*(*ptr)[4] and ++(*ptr)[2] functionality in this program
```<code>#include <iostream>
using namespace std;
int main()
{
    int i;
    const char *arr[] = {"C", "C++", "Java", "VBA"};
    const char *(*ptr)[4] = &arr;
    cout << ++(*ptr)[2];
    return 0;
}
</code>```

Output is "ava"

I am not able to understand why code is giving this output.
I tried to breakdown the code line by line to understand, but I am not that good in pointers so I am not able to understand what *(*ptr)[4] and ++(*ptr) is doing?
So I want to know their functionality in this code

答:
Lets look at different statements in your program.

Case 1

Here we consider the statement:

```<code> const char *arr[] = {"C", "C++", "Java", "VBA"};
</code>```

The above statement creates an array named arr that contains elements of type const char*. The size of this array is 4.

Case 2

Here we consider the statement:

```<code>const char *(*ptr)[4] = &arr;
</code>```

The above statement creates a pointer named ptr that points to an array of size 4 that contains elements of type const char*. Moreover, this pointer ptr is initialized with &arr. This means, the pointer ptr is pointing to the array arr.

Since arr is of type const char* [4] therefore , &arr gives us a const char* (*)[4].

Case 3

Here we consider the statement:

```<code>cout << ++(*ptr)[2];
</code>```

In the above statement, (*ptr) dereferences the pointer named ptr. This gives us the object to which ptr was pointing. But we know that(from case 2) ptr is pointing to the array arr. So the result of (*ptr) is nothing but the array named arr.

Now, the operator [] has higher precedence than operator ++. This means that the array arr that we got as a result of dereferencing, is subscripted for the value 2. That is we now get the 3rd element(which is at index 2) of the array arr. This means we now have a pointer that is pointing to the first element/character of the string literal "Java".

Finally, that pointer value is incremented. This is because of the ++. This mean now after incrementing, the pointer is pointing to the next character(which is 'a') in the string literal "Java".

So when you use cout on this pointer you get ava as the output because the pointer was pointing to the character 'a' and not 'J'.

Body:
#include <iostream>
using namespace std;
int main()
{
    int i;
    const char *arr[] = {"C", "C++", "Java", "VBA"};
    const char *(*ptr)[4] = &arr;
    cout << ++(*ptr)[2];
    return 0;
}

Output is "ava"

I am not able to understand why code is giving this output.
I tried to breakdown the code line by line to understand, but I am not that good in pointers so I am not able to understand what *(*ptr)[4] and ++(*ptr) is doing?
So I want to know their functionality in this code

Body:
Lets look at different statements in your program.

Case 1

Here we consider the statement:

 const char *arr[] = {"C", "C++", "Java", "VBA"};

The above statement creates an array named arr that contains elements of type const char*. The size of this array is 4.

Case 2

Here we consider the statement:

const char *(*ptr)[4] = &arr;

The above statement creates a pointer named ptr that points to an array of size 4 that contains elements of type const char*. Moreover, this pointer ptr is initialized with &arr. This means, the pointer ptr is pointing to the array arr.

Since arr is of type const char* [4] therefore , &arr gives us a const char* (*)[4].

Case 3

Here we consider the statement:

cout << ++(*ptr)[2];

In the above statement, (*ptr) dereferences the pointer named ptr. This gives us the object to which ptr was pointing. But we know that(from case 2) ptr is pointing to the array arr. So the result of (*ptr) is nothing but the array named arr.

Now, the operator [] has higher precedence than operator ++. This means that the array arr that we got as a result of dereferencing, is subscripted for the value 2. That is we now get the 3rd element(which is at index 2) of the array arr. This means we now have a pointer that is pointing to the first element/character of the string literal "Java".

Finally, that pointer value is incremented. This is because of the ++. This mean now after incrementing, the pointer is pointing to the next character(which is 'a') in the string literal "Java".

So when you use cout on this pointer you get ava as the output because the pointer was pointing to the character 'a' and not 'J'.


问:
Why does flutter doctor gives android tollchain error
when i type flutter doctor i recieve this one

Android toolchain - develop for Android devices
X Unable to locate Android SDK.
Install Android Studio from: https://developer.android.com/studio/index.html
On first launch it will assist you in installing the Android SDK components.
(or visit https://flutter.dev/docs/get-started/install/windows#android-setup for detailed instructions).
If the Android SDK has been installed to a custom location, please use
flutter config --android-sdk to update to that location.

For any help - thanks =)

答:
You need to

install android-studio in order to develop flutter apps.

install cmd-line-tools from android-studio -> sdk-manager -> appearence and behaviour -> system settings -> android sdk -> Android SDK command line tools

If you installed android-studio in any other location then add a system variable ANDROID-HOME with the path where your android sdk is located


问:
Simple Palindrome in c++
Would someone be kind enough to route me in the right direction regarding how to get the correct out with this palindrome checker</p>

```<code>#include <iostream>
using namespace std;

bool isPal(string number){
    for (int i = 0, j = number.length(); i < number.length(), j > 0; i++, j--)
        if (i == j){
            return true;
        }
        else
            return false;
    }

int main(){
    cout << isPal("helleh") << "\n";
        cout << isPal("9009") << "\n";
    system("pause");
    return 0;
}
</code>```

答:
```<code>#include <iostream>

#include <string.h>

using namespace std;

bool isPolindrome(string str) {

    long n = str.length();

    for (long i=0; i<n/2; i++) {

        if(str[i] != str[n-1-i]) return false;

    }

    return true;
}

int main() {

    string s;

    cin >> s;

    cout << boolalpha << isPolindrome(s) << endl;

    return 0;

}
</code>```

Title: Simple Palindrome in c++

Body:
Would someone be kind enough to route me in the right direction regarding how to get the correct out with this palindrome checker

#include <iostream>
using namespace std;

bool isPal(string number){
    for (int i = 0, j = number.length(); i < number.length(), j > 0; i++, j--)
        if (i == j){
            return true;
        }
        else
            return false;
    }

int main(){
    cout << isPal("helleh") << "\n";
        cout << isPal("9009") << "\n";
    system("pause");
    return 0;
}


问:
Python mysql.connector cursor.execute() and connection.commit() not working in a loop
Trying to automate working process with the tables in MySQL using for-loop

```<code>from mysql.connector import connect, Error

def main():
    try:
        with connect(host="host", user="user",password="password") as connection:
            connection.autocommit = True
            no_pk_tables_query = """
            select tab.table_schema as database_name,
                tab.table_name
            from information_schema.tables tab
            left join information_schema.table_constraints tco
                on tab.table_schema = tco.table_schema
                and tab.table_name = tco.table_name
                and tco.constraint_type = 'PRIMARY KEY'
            where tco.constraint_type is null
                and tab.table_schema not in('mysql', 'information_schema',
                                  'performance_schema', 'sys')
                and tab.table_type = 'BASE TABLE'
                order by tab.table_schema,
            tab.table_name;
            """
            tables_to_cure = []
            with connection.cursor() as cursor:
                cursor.execute(no_pk_tables_query)
                for table in cursor:
                    tables_to_cure.append(table[1])
                    print(table[1])

                for s_table in tables_to_cure:
                        cure = """
                                USE mission_impossible;
                                ALTER TABLE `{}` MODIFY `ID` int(18) NOT NULL auto_increment PRIMARY KEY;
                            """.format(s_table)
                        cursor.execute(cure)
                        print("Cured {}".format(s_table))
    except Error as e:
        print(e)
    finally:
        print("End")

main()
</code>```

And I get:

quote 2014 (HY000): Commands out of sync; you can't run this command now

If I add connection.commit() inside the for-loop after cursor.execute() I'll get:

_mysql_connector.MySQLInterfaceError: Commands out of sync; you can't run this command now

Does this mean that I'll have to use new connections inside loop instead of cursor?
I've looked it up and found some methods like fetchall() and nextset() but they seem to do other things than simply refreshing current cursor data.
Using connection.autocommit = True seem not to work either as the same error occurs.
Using something like sleep() also doesn't help.
What am I doing wrong here?

Edit

Getting rid of try/except didn't help:

```<code>  File "/usr/local/lib/python3.8/dist-packages/mysql/connector/connection_cext.py", line 523, in cmd_query
    self._cmysql.query(query,
_mysql_connector.MySQLInterfaceError: Commands out of sync; you can't run this command now

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "db.py", line 40, in <module>
    main()
  File "db.py", line 36, in main
    cursor.execute(cure)
  File "/usr/local/lib/python3.8/dist-packages/mysql/connector/cursor_cext.py", line 269, in execute
    result = self._cnx.cmd_query(stmt, raw=self._raw,
  File "/usr/local/lib/python3.8/dist-packages/mysql/connector/connection_cext.py", line 528, in cmd_query
    raise errors.get_mysql_exception(exc.errno, msg=exc.msg,
mysql.connector.errors.DatabaseError: 2014 (HY000): Commands out of sync; you can't run this command now
</code>```

Fixed:

Seems like I've finally figured it out, it's needed to get results from the cursor using fetchall() instead of directly addressing the cursor as an iterator.

            with connection.cursor() as cursor:
                cursor.execute(no_pk_tables_query)
                rows = cursor.fetchall()
            with connection.cursor() as cursor:
                for table in rows:
                    try:
                        print(table[1])
                        cure = """
                            ALTER TABLE `{}` MODIFY `ID` int(18) NOT NULL auto_increment PRIMARY KEY;
                        """.format(table[1])
                        cursor.execute(cure)
                        res = cursor.fetchall()
                        print(res)
                    except Error as e:
                        print(e)
```

Thx everybody

答:
Here's some sample code that shows how the "Commands out of sync" error can occur:

```<code>from mysql.connector import connect, Error
# replace asterisks in the CONFIG dictionary with your data
CONFIG = {
    'user': '*',
    'password': '*',
    'host': '*',
    'database': '*',
    'autocommit': False
}
try:
    with connect(**CONFIG) as conn:
        try:
            with conn.cursor() as cursor:
                cursor.execute('select * from ips')
                # cursor.fetchall()
        finally:
            conn.commit()
except Error as e:
    print(e)
</code>```

Explanation:

The code selects all rows from a table called "ips" the contents of which are irrelevant here.

Now, note that we do not attempt to get a rowset (fetchall is commented out). We then try to commit the transaction (even though no changes were made to the table).

This will induce the "Commands out of sync" error.

However, if we take out the comment line and fetch the rowset (fetchall) this problem does not arise.

Explicitly fetching the rowset is equivalent to iterating over the cursor.

If we change the autocommit parameter to True and remove the explicit commit(), we get another error:- "Unread result found".

In other words, it seems that MySQL requires you to get the rowset (or iterate over the cursor) whenever you select anything!

Note that even if autocommit is enabled (True) explicit calls to commit() are permitted

Solutions:

Either ensure that the client application iterates over the entire cursor after SELECT or in the CONFIG dictionary add: 'consume_results': True

Body:
Trying to automate working process with the tables in MySQL using for-loop

from mysql.connector import connect, Error

def main():
    try:
        with connect(host="host", user="user",password="password") as connection:
            connection.autocommit = True
            no_pk_tables_query = """
            select tab.table_schema as database_name,
                tab.table_name
            from information_schema.tables tab
            left join information_schema.table_constraints tco
                on tab.table_schema = tco.table_schema
                and tab.table_name = tco.table_name
                and tco.constraint_type = 'PRIMARY KEY'
            where tco.constraint_type is null
                and tab.table_schema not in('mysql', 'information_schema',
                                  'performance_schema', 'sys')
                and tab.table_type = 'BASE TABLE'
                order by tab.table_schema,
            tab.table_name;
            """
            tables_to_cure = []
            with connection.cursor() as cursor:
                cursor.execute(no_pk_tables_query)
                for table in cursor:
                    tables_to_cure.append(table[1])
                    print(table[1])

                for s_table in tables_to_cure:
                        cure = """
                                USE mission_impossible;
                                ALTER TABLE `{}` MODIFY `ID` int(18) NOT NULL auto_increment PRIMARY KEY;
                            """.format(s_table)
                        cursor.execute(cure)
                        print("Cured {}".format(s_table))
    except Error as e:
        print(e)
    finally:
        print("End")

main()

And I get:

quote 2014 (HY000): Commands out of sync; you can't run this command now

If I add connection.commit() inside the for-loop after cursor.execute() I'll get:

_mysql_connector.MySQLInterfaceError: Commands out of sync; you can't run this command now

Does this mean that I'll have to use new connections inside loop instead of cursor?
I've looked it up and found some methods like fetchall() and nextset() but they seem to do other things than simply refreshing current cursor data.
Using connection.autocommit = True seem not to work either as the same error occurs.
Using something like sleep() also doesn't help.
What am I doing wrong here?

Edit

Getting rid of try/except didn't help:

  File "/usr/local/lib/python3.8/dist-packages/mysql/connector/connection_cext.py", line 523, in cmd_query
    self._cmysql.query(query,
_mysql_connector.MySQLInterfaceError: Commands out of sync; you can't run this command now

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "db.py", line 40, in <module>
    main()
  File "db.py", line 36, in main
    cursor.execute(cure)
  File "/usr/local/lib/python3.8/dist-packages/mysql/connector/cursor_cext.py", line 269, in execute
    result = self._cnx.cmd_query(stmt, raw=self._raw,
  File "/usr/local/lib/python3.8/dist-packages/mysql/connector/connection_cext.py", line 528, in cmd_query
    raise errors.get_mysql_exception(exc.errno, msg=exc.msg,
mysql.connector.errors.DatabaseError: 2014 (HY000): Commands out of sync; you can't run this command now

Fixed:

Seems like I've finally figured it out, it's needed to get results from the cursor using fetchall() instead of directly addressing the cursor as an iterator.

            with connection.cursor() as cursor:
                cursor.execute(no_pk_tables_query)
                rows = cursor.fetchall()
            with connection.cursor() as cursor:
                for table in rows:
                    try:
                        print(table[1])
                        cure = """
                            ALTER TABLE `{}` MODIFY `ID` int(18) NOT NULL auto_increment PRIMARY KEY;
                        """.format(table[1])
                        cursor.execute(cure)
                        res = cursor.fetchall()
                        print(res)
                    except Error as e:
                        print(e)

Thx everybody

Body:
Here's some sample code that shows how the "Commands out of sync" error can occur:

from mysql.connector import connect, Error
# replace asterisks in the CONFIG dictionary with your data
CONFIG = {
    'user': '*',
    'password': '*',
    'host': '*',
    'database': '*',
    'autocommit': False
}
try:
    with connect(**CONFIG) as conn:
        try:
            with conn.cursor() as cursor:
                cursor.execute('select * from ips')
                # cursor.fetchall()
        finally:
            conn.commit()
except Error as e:
    print(e)

Explanation:

The code selects all rows from a table called "ips" the contents of which are irrelevant here.

Now, note that we do not attempt to get a rowset (fetchall is commented out). We then try to commit the transaction (even though no changes were made to the table).

This will induce the "Commands out of sync" error.

However, if we take out the comment line and fetch the rowset (fetchall) this problem does not arise.

Explicitly fetching the rowset is equivalent to iterating over the cursor.

If we change the autocommit parameter to True and remove the explicit commit(), we get another error:- "Unread result found".

In other words, it seems that MySQL requires you to get the rowset (or iterate over the cursor) whenever you select anything!

Note that even if autocommit is enabled (True) explicit calls to commit() are permitted

Solutions:

Either ensure that the client application iterates over the entire cursor after SELECT or in the CONFIG dictionary add: 'consume_results': True


问:
loading .so file react-native
I'm trying to load a .so file with my react-native project using the Native Modules.
I'm loading the library with the LoadLibrary func and i am not able to envoke the funtions inside.
However, i have opened a regular java project in android studio and i was able to load the library perfectly.

Any ideas?

答:
I had the same problem and what worked for me was adding this two files where is the MainActivity.java class. You have to change the package name of both classes to  com.solo_test

1- https://github.com/CassieLuoli/react-native-smartconnection/blob/master/android/src/main/java/com/luoli/smartconnection/SmartConfigHelper.java

2- https://github.com/CassieLuoli/react-native-smartconnection/blob/master/android/src/main/java/com/mediatek/demo/smartconnection/JniLoader.java
don't forget to change de name of the library on JniLoader.java class

Finally you need to invoke  SmartConfigHelper.init(); in MainActivity for load the library

Title: loading .so file react-native


Title: How to get each letter of word list python

Body:
l = ['hello', 'world', 'monday']
list(map(list, l))
#output
[['h', 'e', 'l', 'l', 'o'],
 ['w', 'o', 'r', 'l', 'd'],
 ['m', 'o', 'n', 'd', 'a', 'y']]


问:
Are there alternatives to CGPDFContext?
I am aiming to combine multiple PDF files each with identical dimensions into one file.

I've seen how it is done with CGPDFContext. I am just curious if there are (better?) alternatives to this method on the Mac.

Let's say I have the option to use PDFs, TIFF, PNG or JPEG files as input. Would using a different input file type mean anything significant for the process, or it would be easier to go with PDF input?

答: I have use PDFDocument API and it is programmatically easier to use. It may need PDF files as input though.</p>

Title: Are there alternatives to CGPDFContext?


问:
Cygwin error: "child_info_fork::abort: Loaded to different address:"
I am trying to build my software using cygwin-x86(32 bit version) on Windows-7.

Cygwin-x64(64 bit) works perfectly fine on the same machine. I want to build 32-bit executable.

Whenever I try cygwin-x86, I get the following errors:

[main] make 7780 child_info_fork::abort:
  C:\cygwin\bin\cygiconv-2.dll: Loaded to different address:
  parent(0x440000) != child(0x5F0000)
make: fork: Resource temporarily
  unavailable

I have checked this thread Cygwin Error

I have already tried everything mentioned in there, but I still continue to face the same issue.

Whenever i try /usr/bin/rebaseall -v or cd /usr/bin && ./rebaseall -v as mentioned in the step 7 of the accepted answer in the above mentioned thread, I get this error:

/usr/x86_64-pc-cygwin/sys-root/usr/bin/cygvtv_stubs-0.dll: skipped
  because wrong  machine type.
  /usr/x86_64-pc-cygwin/sys-root/usr/bin/cygz.dll: skipped because wrong
  machine type.
Segmentation fault (core dumped)

I get this wrong machine type error for a lot of other .dll's as well.

As mentioned earlier I have cygwin-64 installed on my machine & working as expected. But while running rebaseall it is somehow looking for x86-64-pc-cygwin instead of 32 bit version.

答:
For me, the solution was to remove the .new file extention of the libs from c:\cygwin64\bin\

I had the same problem using git. various dlls depending on the git command used where included in the error message stating that it was loaded to "different adress".

In fact a corporate antivirus or a loaded program had probably prevent un update during the rebase phase while installing a new program (git-svn in my case)
some required libraries where not installed but cleverly left in the target with the .new file extention.

I just had to remove the .new extention (and rename the original lib to .old) to solve the problem.

In my case the list of lib involved was:

```<code>cygcrypto-1.1.dll
cyggcc_s-seh-1.dll
cygintl-8.dll
cygwin1.dll
</code>```

Body:
For me, the solution was to remove the .new file extention of the libs from c:\cygwin64\bin\

I had the same problem using git. various dlls depending on the git command used where included in the error message stating that it was loaded to "different adress".

In fact a corporate antivirus or a loaded program had probably prevent un update during the rebase phase while installing a new program (git-svn in my case)
some required libraries where not installed but cleverly left in the target with the .new file extention.

I just had to remove the .new extention (and rename the original lib to .old) to solve the problem.

In my case the list of lib involved was:

cygcrypto-1.1.dll
cyggcc_s-seh-1.dll
cygintl-8.dll
cygwin1.dll