问:
FLUTTER Error: Method 'copyWith' cannot be called on 'TextStyle?' because it is potentially null
Wow I have a whole lot of these:

Error: Method 'copyWith' cannot be called on 'TextStyle?' because it
is potentially null.

'TextStyle' is from 'package:flutter/src/painting/text_style.dart' ('../flutter/packages/flutter/lib/src/painting/text_style.dart'). Try
calling using ?. instead.

I don't understand the instruction, I've tried naively appending ? marks in various places, tried changing 'copyWith' to 'apply'.

This is the errourous code:

```<code>                    style: Theme.of(context)
                        .textTheme
                        .bodyText2
                        .copyWith(fontWeight: FontWeight.bold)
</code>```

Uh, I don't get it. Major project changes for this null thing, and a fair amount of the time I feel I'm guessing.  My dart files are now littered with !, which seems surprisingly verbose.

Anyway, my project won't compile without this, and I have a good few so help is appreciated.

答:
You have to mark your bodyText2 value as not null with !, but be sure that the bodyText2 value returned is not null, otherwise you will get another error. To read more about null safety: null safety

Theme.of(context).textTheme.bodyText2!.copyWith(fontWeight: FontWeight.bold);
```

Body:
Wow I have a whole lot of these:

Error: Method 'copyWith' cannot be called on 'TextStyle?' because it
is potentially null.

'TextStyle' is from 'package:flutter/src/painting/text_style.dart' ('../flutter/packages/flutter/lib/src/painting/text_style.dart'). Try
calling using ?. instead.

I don't understand the instruction, I've tried naively appending ? marks in various places, tried changing 'copyWith' to 'apply'.

This is the errourous code:

                    style: Theme.of(context)
                        .textTheme
                        .bodyText2
                        .copyWith(fontWeight: FontWeight.bold)

Uh, I don't get it. Major project changes for this null thing, and a fair amount of the time I feel I'm guessing.  My dart files are now littered with !, which seems surprisingly verbose.

Anyway, my project won't compile without this, and I have a good few so help is appreciated.


来源: stackexchange

问:
Automate clear browsing data Safari
Is there any way to automate clearing cache, cookies and history in Safari? I can run Swift, Python, JavaScript and AppleScript.

This is the AppleScript I have right now, but it is slow, interruptible and basically activates user interface buttons. What I want is something that works in the background and still gets the job done.

```<code>--Clear history (also clears cache and cookies)
tell application "System Events" to keystroke "t" using {command down}
tell application "System Events"
    click menu item "Clear History…" of menu 1 of menu bar item "History" of menu bar 1 of process "Safari"
    try
        click button "Clear History" of sheet 1 of window 1 of process "Safari"
    end try
end tell
tell application "System Events" to keystroke "w" using {command down}
</code>```

答:
I found the files where the browsing data is saved. These scripts delete the files with the same effect as clearing Safari history manually. Also clears cache and cookies for all applications in /User/Library.

AppleScript

```<code>--  Get path of files to delete and folders to empty
set base to "Macintosh HD:Users:User:Library:"
set docs to {"Safari:History.db", "Safari:History.db-lock", "Safari:History.db-shm", "Safari:History.db-wal", "Safari:CloudTabs.db", "Safari:CloudTabs.db-shm", "Safari:CloudTabs.db-wal", "Safari:PerSitePreferences.db", "Safari:PerSitePreferences.db-shm", "Safari:PerSitePreferences.db-wal", "Safari:Downloads.plist", "Safari:RecentlyClosedTabs.plist", "Safari:SearchDescriptions.plist"}
set docs1 to {"Safari:LocalStorage", "Safari:Favicon Cache", "Safari:Touch Icons Cache", "Caches:com.apple.Safari", "Caches", "Cookies"}
--  Delete history files
tell application "Finder"
    repeat with i from 1 to length of docs
        set doc to item i of docs
        set doc to base & doc
        try
            delete file doc
        end try
    end repeat
end tell

--  Empty cache folders
tell application "Finder"
    repeat with i from 1 to length of docs1
        set doc to item i of docs1
        set doc to base & doc
        try
            delete (every item of folder doc)
        end try
    end repeat
end tell
</code>```

Python 3.10

```<code>import os
import shutil

# Declare file & folder directories
library = "/Users/User/Library"
files = [
    "/Safari/History.db",
    "/Safari/History.db-lock",
    "/Safari/History.db-shm",
    "/Safari/History.db-wal",
    "/Safari/CloudTabs.db",
    "/Safari/CloudTabs.db-shm",
    "/Safari/CloudTabs.db-wal",
    "/Safari/PerSitePreferences.db",
    "/Safari/PerSitePreferences.db-shm",
    "/Safari/PerSitePreferences.db-wal",
    "/Safari/Downloads.plist",
    "/Safari/RecentlyClosedTabs.plist",
    "/Safari/SearchDescriptions.plist",
    "/Containers/com.apple.Safari/Data/Library/Safari/SafariTabs.db",
    "/Containers/com.apple.Safari/Data/Library/Safari/SafariTabs.db-shm",
    "/Containers/com.apple.Safari/Data/Library/Safari/SafariTabs.db-wal"
]
folders = [
    "/Safari/Databases",
    "/Safari/LocalStorage",
    "/Safari/Favicon Cache",
    "/Safari/Template Icons",
    "/Safari/Touch Icons Cache",
    "/Containers/com.apple.Safari/Data/Library/Caches",
    "/Containers/com.apple.Safari/Data/Library/Saved Application State"
]
sensitive = [
    "/Caches",
    "/Cookies",
]

# Delete Safari history files
for file in files:
    if os.path.exists(library + file):
        os.remove(library + file)
for folder in folders:
    if os.path.exists(library + folder):
        shutil.rmtree(library + folder)

# Delete caches and cookies
for folder in sensitive:
    for file in os.listdir(library + folder):
        os.system("rm -r " + library + folder + "/" + file)
</code>```

Python 3.10 multiprocessing

```<code>import os
import shutil
import multiprocessing

#MARK: - Declare file & folder directories
library = "/Users/User/Library"
files = (
    "/Safari/History.db",
    "/Safari/History.db-lock",
    "/Safari/History.db-shm",
    "/Safari/History.db-wal",
    "/Safari/CloudTabs.db",
    "/Safari/CloudTabs.db-shm",
    "/Safari/CloudTabs.db-wal",
    "/Safari/PerSitePreferences.db"
    "/Safari/PerSitePreferences.db-shm",
    "/Safari/PerSitePreferences.db-wal",
    "/Safari/Downloads.plist",
    "/Safari/RecentlyClosedTabs.plist",
    "/Safari/SearchDescriptions.plist",
    "/Containers/com.apple.Safari/Data/Library/Safari/SafariTabs.db",
    "/Containers/com.apple.Safari/Data/Library/Safari/SafariTabs.db-shm",
    "/Containers/com.apple.Safari/Data/Library/Safari/SafariTabs.db-wal"
)
folders = (
    ("/Safari/Databases",
    "/Safari/LocalStorage",
    "/Safari/Favicon Cache",
     "/Safari/Template Icons"),
    ("/Safari/Touch Icons Cache",
    "/Containers/com.apple.Safari/Data/tmp",
     "/Containers/com.apple.Safari/Data/CloudKit",
     "/Containers/com.apple.Safari/Data/Library/Caches"),
    ("/Containers/com.apple.Safari/Data/Library/Logs",
    "/Containers/com.apple.Safari/Data/Library/HTTPStorages",
    "/Containers/com.apple.Safari/Data/Library/WebKit/MediaKeys",
    "/Containers/com.apple.Safari/Data/Library/WebKit/WebsiteData",
    "/Containers/com.apple.Safari/Data/Library/Saved Application State")
)
sensitive_folders = (
    "/Caches",
    "/Cookies"
)

#MARK - Delete Safari history files as well as caches and cookies
#  Optimized for 3 GHz 6-Core Intel Core i5 CPU

def delete_files():
    #  Delete Safari history files
    for file in files:
        if os.path.exists(library + file): os.remove(library + file)
def delete_folders(segment):
    #  Delete folders in segment and all files inside folders
    for folder in folders[segment]:
        if os.path.exists(library + folder): shutil.rmtree(library + folder)
def delete_sensitive_folders():
    #  Delete caches and cookies folders and contents located in /User/Library folder
    for folder in sensitive_folders:
        if os.path.exists(library + folder): shutil.rmtree(library + folder)

if __name__ == "__main__":
    #  Create and start process to delete Safari history files
    file_delete_process = multiprocessing.Process(target = delete_files)
    file_delete_process.start()

    #  Create and start process to delete caches and cookies
    sensitive_folders_delete_process = multiprocessing.Process(target = delete_sensitive_folders)
    sensitive_folders_delete_process.start()

    #  Create and start processes to delete folders
    for i in range(0, 3):
        folder_delete_process = multiprocessing.Process(target = delete_folders, args = (i,))
        folder_delete_process.start()
</code>```

C++ 20

```<code>#include <string>
#include <iostream>
#include <filesystem>

using namespace std;
namespace fs = filesystem;

int main() {
    const string library = "/Users/User/Library";
    const string files[16] = {
        "/Safari/History.db",
        "/Safari/History.db-lock",
        "/Safari/History.db-shm",
        "/Safari/History.db-wal",
        "/Safari/CloudTabs.db",
        "/Safari/CloudTabs.db-shm",
        "/Safari/CloudTabs.db-wal",
        "/Safari/PerSitePreferences.db",
        "/Safari/PerSitePreferences.db-shm",
        "/Safari/PerSitePreferences.db-wal",
        "/Safari/Downloads.plist",
        "/Safari/RecentlyClosedTabs.plist",
        "/Safari/SearchDescriptions.plist",
        "/Containers/com.apple.Safari/Data/Library/Safari/SafariTabs.db",
        "/Containers/com.apple.Safari/Data/Library/Safari/SafariTabs.db-shm",
        "/Containers/com.apple.Safari/Data/Library/Safari/SafariTabs.db-wal"
    };
    const string folders[13] = {
        "/Safari/Databases",
        "/Safari/LocalStorage",
        "/Safari/Favicon Cache",
        "/Safari/Template Icons",
        "/Safari/Touch Icons Cache",
        "/Containers/com.apple.Safari/Data/tmp",
        "/Containers/com.apple.Safari/Data/CloudKit",
        "/Containers/com.apple.Safari/Data/Library/Caches",
        "/Containers/com.apple.Safari/Data/Library/Logs",
        "/Containers/com.apple.Safari/Data/Library/HTTPStorages",
        "/Containers/com.apple.Safari/Data/Library/WebKit/MediaKeys",
        "/Containers/com.apple.Safari/Data/Library/WebKit/WebsiteData",
        "/Containers/com.apple.Safari/Data/Library/Saved Application State"
    };
    const string sensitiveFolders[2] = {
        "/Caches",
        "/Cookies"
    };

    for(const string &i: files) { fs::remove_all(library + i);};
    for(const string &i: folders) { fs::remove_all(library + i);};
    for(const string &i: sensitiveFolders) { fs::remove_all(library + i);};
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Automate clear browsing data Safari

Body:
Is there any way to automate clearing cache, cookies and history in Safari? I can run Swift, Python, JavaScript and AppleScript.

This is the AppleScript I have right now, but it is slow, interruptible and basically activates user interface buttons. What I want is something that works in the background and still gets the job done.

--Clear history (also clears cache and cookies)
tell application "System Events" to keystroke "t" using {command down}
tell application "System Events"
    click menu item "Clear History…" of menu 1 of menu bar item "History" of menu bar 1 of process "Safari"
    try
        click button "Clear History" of sheet 1 of window 1 of process "Safari"
    end try
end tell
tell application "System Events" to keystroke "w" using {command down}

Body:
I found the files where the browsing data is saved. These scripts delete the files with the same effect as clearing Safari history manually. Also clears cache and cookies for all applications in /User/Library.

AppleScript

--  Get path of files to delete and folders to empty
set base to "Macintosh HD:Users:User:Library:"
set docs to {"Safari:History.db", "Safari:History.db-lock", "Safari:History.db-shm", "Safari:History.db-wal", "Safari:CloudTabs.db", "Safari:CloudTabs.db-shm", "Safari:CloudTabs.db-wal", "Safari:PerSitePreferences.db", "Safari:PerSitePreferences.db-shm", "Safari:PerSitePreferences.db-wal", "Safari:Downloads.plist", "Safari:RecentlyClosedTabs.plist", "Safari:SearchDescriptions.plist"}
set docs1 to {"Safari:LocalStorage", "Safari:Favicon Cache", "Safari:Touch Icons Cache", "Caches:com.apple.Safari", "Caches", "Cookies"}
--  Delete history files
tell application "Finder"
    repeat with i from 1 to length of docs
        set doc to item i of docs
        set doc to base & doc
        try
            delete file doc
        end try
    end repeat
end tell

--  Empty cache folders
tell application "Finder"
    repeat with i from 1 to length of docs1
        set doc to item i of docs1
        set doc to base & doc
        try
            delete (every item of folder doc)
        end try
    end repeat
end tell

Python 3.10

import os
import shutil

# Declare file & folder directories
library = "/Users/User/Library"
files = [
    "/Safari/History.db",
    "/Safari/History.db-lock",
    "/Safari/History.db-shm",
    "/Safari/History.db-wal",
    "/Safari/CloudTabs.db",
    "/Safari/CloudTabs.db-shm",
    "/Safari/CloudTabs.db-wal",
    "/Safari/PerSitePreferences.db",
    "/Safari/PerSitePreferences.db-shm",
    "/Safari/PerSitePreferences.db-wal",
    "/Safari/Downloads.plist",
    "/Safari/RecentlyClosedTabs.plist",
    "/Safari/SearchDescriptions.plist",
    "/Containers/com.apple.Safari/Data/Library/Safari/SafariTabs.db",
    "/Containers/com.apple.Safari/Data/Library/Safari/SafariTabs.db-shm",
    "/Containers/com.apple.Safari/Data/Library/Safari/SafariTabs.db-wal"
]
folders = [
    "/Safari/Databases",
    "/Safari/LocalStorage",
    "/Safari/Favicon Cache",
    "/Safari/Template Icons",
    "/Safari/Touch Icons Cache",
    "/Containers/com.apple.Safari/Data/Library/Caches",
    "/Containers/com.apple.Safari/Data/Library/Saved Application State"
]
sensitive = [
    "/Caches",
    "/Cookies",
]

# Delete Safari history files
for file in files:
    if os.path.exists(library + file):
        os.remove(library + file)
for folder in folders:
    if os.path.exists(library + folder):
        shutil.rmtree(library + folder)

# Delete caches and cookies
for folder in sensitive:
    for file in os.listdir(library + folder):
        os.system("rm -r " + library + folder + "/" + file)

Python 3.10 multiprocessing

import os
import shutil
import multiprocessing

#MARK: - Declare file & folder directories
library = "/Users/User/Library"
files = (
    "/Safari/History.db",
    "/Safari/History.db-lock",
    "/Safari/History.db-shm",
    "/Safari/History.db-wal",
    "/Safari/CloudTabs.db",
    "/Safari/CloudTabs.db-shm",
    "/Safari/CloudTabs.db-wal",
    "/Safari/PerSitePreferences.db"
    "/Safari/PerSitePreferences.db-shm",
    "/Safari/PerSitePreferences.db-wal",
    "/Safari/Downloads.plist",
    "/Safari/RecentlyClosedTabs.plist",
    "/Safari/SearchDescriptions.plist",
    "/Containers/com.apple.Safari/Data/Library/Safari/SafariTabs.db",
    "/Containers/com.apple.Safari/Data/Library/Safari/SafariTabs.db-shm",
    "/Containers/com.apple.Safari/Data/Library/Safari/SafariTabs.db-wal"
)
folders = (
    ("/Safari/Databases",
    "/Safari/LocalStorage",
    "/Safari/Favicon Cache",
     "/Safari/Template Icons"),
    ("/Safari/Touch Icons Cache",
    "/Containers/com.apple.Safari/Data/tmp",
     "/Containers/com.apple.Safari/Data/CloudKit",
     "/Containers/com.apple.Safari/Data/Library/Caches"),
    ("/Containers/com.apple.Safari/Data/Library/Logs",
    "/Containers/com.apple.Safari/Data/Library/HTTPStorages",
    "/Containers/com.apple.Safari/Data/Library/WebKit/MediaKeys",
    "/Containers/com.apple.Safari/Data/Library/WebKit/WebsiteData",
    "/Containers/com.apple.Safari/Data/Library/Saved Application State")
)
sensitive_folders = (
    "/Caches",
    "/Cookies"
)

#MARK - Delete Safari history files as well as caches and cookies
#  Optimized for 3 GHz 6-Core Intel Core i5 CPU

def delete_files():
    #  Delete Safari history files
    for file in files:
        if os.path.exists(library + file): os.remove(library + file)
def delete_folders(segment):
    #  Delete folders in segment and all files inside folders
    for folder in folders[segment]:
        if os.path.exists(library + folder): shutil.rmtree(library + folder)
def delete_sensitive_folders():
    #  Delete caches and cookies folders and contents located in /User/Library folder
    for folder in sensitive_folders:
        if os.path.exists(library + folder): shutil.rmtree(library + folder)

if __name__ == "__main__":
    #  Create and start process to delete Safari history files
    file_delete_process = multiprocessing.Process(target = delete_files)
    file_delete_process.start()

    #  Create and start process to delete caches and cookies
    sensitive_folders_delete_process = multiprocessing.Process(target = delete_sensitive_folders)
    sensitive_folders_delete_process.start()

    #  Create and start processes to delete folders
    for i in range(0, 3):
        folder_delete_process = multiprocessing.Process(target = delete_folders, args = (i,))
        folder_delete_process.start()

C++ 20

#include <string>
#include <iostream>
#include <filesystem>

using namespace std;
namespace fs = filesystem;

int main() {
    const string library = "/Users/User/Library";
    const string files[16] = {
        "/Safari/History.db",
        "/Safari/History.db-lock",
        "/Safari/History.db-shm",
        "/Safari/History.db-wal",
        "/Safari/CloudTabs.db",
        "/Safari/CloudTabs.db-shm",
        "/Safari/CloudTabs.db-wal",
        "/Safari/PerSitePreferences.db",
        "/Safari/PerSitePreferences.db-shm",
        "/Safari/PerSitePreferences.db-wal",
        "/Safari/Downloads.plist",
        "/Safari/RecentlyClosedTabs.plist",
        "/Safari/SearchDescriptions.plist",
        "/Containers/com.apple.Safari/Data/Library/Safari/SafariTabs.db",
        "/Containers/com.apple.Safari/Data/Library/Safari/SafariTabs.db-shm",
        "/Containers/com.apple.Safari/Data/Library/Safari/SafariTabs.db-wal"
    };
    const string folders[13] = {
        "/Safari/Databases",
        "/Safari/LocalStorage",
        "/Safari/Favicon Cache",
        "/Safari/Template Icons",
        "/Safari/Touch Icons Cache",
        "/Containers/com.apple.Safari/Data/tmp",
        "/Containers/com.apple.Safari/Data/CloudKit",
        "/Containers/com.apple.Safari/Data/Library/Caches",
        "/Containers/com.apple.Safari/Data/Library/Logs",
        "/Containers/com.apple.Safari/Data/Library/HTTPStorages",
        "/Containers/com.apple.Safari/Data/Library/WebKit/MediaKeys",
        "/Containers/com.apple.Safari/Data/Library/WebKit/WebsiteData",
        "/Containers/com.apple.Safari/Data/Library/Saved Application State"
    };
    const string sensitiveFolders[2] = {
        "/Caches",
        "/Cookies"
    };

    for(const string &i: files) { fs::remove_all(library + i);};
    for(const string &i: folders) { fs::remove_all(library + i);};
    for(const string &i: sensitiveFolders) { fs::remove_all(library + i);};
}


问:
syntax explanation for copying object array and add new property
Can someone explain to me why this is the only version I've tried that works for copying state with es6 and adding another field, out of the other ways tried that are listed below? :

```<code>const values = [{key: "1", val: "one"}, {key: "2", val: "two"}];

var works = values.map(v => {
    return {
       ...v,
       extra: "stuff"
   }
})
</code>```

And all of these produce these errors:

```<code>//Unexpected token '...'
var notWorks1 = values.map(v => ...v, extra: "stuff");

// Rest parameter must be last formal parameter
var notWorks2 = values.map(v => {...v, extra: "stuff"})

// Rest parameter must be last formal parameter
var notWorks3 = values.map(v => {
  {
   ...v,
   extra: "stuff"
  }
})

// unexpected token 'return'
var notWorks4 = values.map(v =>
   return {
    ...v,
    extra: "stuff"
   }
)
// unexpected 'return'
var notWorks5 = values.map(v => return ...v, extra: "stuff");
</code>```

I thought the arrow was implicit return (see first 3 attempts).

Is that first way the only syntax that can be used? If there are any others, I'd like to know as I'm trying to practice and learn multiple options.. and I want the most terse, smallest option (one line).

答:
spread syntax is used in an array or object. So you have to put it between {} or [].

{} are compiled as if they belong to the arrow function, not an object.

When you put your code in {}, you need to return the result.

In order to use return in arrow function, you need the put it between {}

The same as 4.

Body:
Can someone explain to me why this is the only version I've tried that works for copying state with es6 and adding another field, out of the other ways tried that are listed below? :

const values = [{key: "1", val: "one"}, {key: "2", val: "two"}];

var works = values.map(v => {
    return {
       ...v,
       extra: "stuff"
   }
})

And all of these produce these errors:

//Unexpected token '...'
var notWorks1 = values.map(v => ...v, extra: "stuff");

// Rest parameter must be last formal parameter
var notWorks2 = values.map(v => {...v, extra: "stuff"})

// Rest parameter must be last formal parameter
var notWorks3 = values.map(v => {
  {
   ...v,
   extra: "stuff"
  }
})

// unexpected token 'return'
var notWorks4 = values.map(v =>
   return {
    ...v,
    extra: "stuff"
   }
)
// unexpected 'return'
var notWorks5 = values.map(v => return ...v, extra: "stuff");

I thought the arrow was implicit return (see first 3 attempts).

Is that first way the only syntax that can be used? If there are any others, I'd like to know as I'm trying to practice and learn multiple options.. and I want the most terse, smallest option (one line).


问:
How to access WEB API on .NET Core from the outside network?
I want to access my API from the outside ?

On the local machine I access my API like this:

```<code>https://localhost:44377/api/stations
</code>```

So my IP address for example is: 186.143.119.43

What do I need to change to see it through external networks?

This is my launchSettings.json file:

```<code>    {
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:51429",
      "sslPort": 44377
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "weatherforecast",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "WebAPI": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "weatherforecast",
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}
</code>```

How to access this API from outside network ?

答: You need to configure your ports and your IP in the rooter Idk how to do it but I early do it for a server for one of my game or you can use NGROK (I use it for temporary servers)</p>

Body:
I want to access my API from the outside ?

On the local machine I access my API like this:

https://localhost:44377/api/stations

So my IP address for example is: 186.143.119.43

What do I need to change to see it through external networks?

This is my launchSettings.json file:

    {
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:51429",
      "sslPort": 44377
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "weatherforecast",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "WebAPI": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "weatherforecast",
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

How to access this API from outside network ?


问:
ioredis connection keeps resetting when connecting to local redis cluster from docker container
I have a docker compose containerized client/server node app that is failing to create a stable connection to a redis cluster I have running on my local environment. The redis cluster has 6 nodes (3 master, 3 replica configuration) running on my local machine. Every time I start my app and attempt to connect to redis, the connect event is spammed and I get the following error on my client:

```<code>Proxy error: Could not proxy request /check-login from localhost:3000 to http://server.
See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNRESET)
</code>```

I have made sure to configure the redis cluster to have the settings protected-mode to no and bind to 0.0.0.0 to allow remote access to the cluster. I have confirmed that I can access the cluster locally by pinging one of the cluster nodes redis-cli -h 127.0.0.1 -p 30001:

```<code>127.0.0.1:30001> ping
PONG
127.0.0.1:30001> exit
</code>```

I am setting my REDIS_HOSTS environment to be "host.docker.internal:30001,host.docker.internal:30005,host.docker.internal:30006". This should allow me to connect to my redis cluster running at 127.0.0.1 on my host machine. My node application code:

```<code>const Redis = require("ioredis");

const hosts = process.env.REDIS_HOSTS.split(",").map((connection) => {
  const [host, port] = connection.split(":");

  return {
    host,
    port,
  };
});

const client = new Redis.Cluster(hosts, {
  enableAutoPipelining: true,
  slotsRefreshTimeout: 100000,
});

client.on("error", (error) => {
  console.log("redis connection failed: ", error);
});

client.on("connect", () => {
  console.log("redis connection established");
});

module.exports = client;
</code>```

My ioredis logs:

```<code>2022-02-11T23:52:09.970Z ioredis:cluster status: [empty] -> connecting
info: Listening on port 80
2022-02-11T23:52:15.449Z ioredis:cluster resolved hostname host.docker.internal to IP 192.168.65.2
2022-02-11T23:52:15.476Z ioredis:cluster:connectionPool Reset with [
  { host: '192.168.65.2', port: 30001 },
  { host: '192.168.65.2', port: 30002 },
  { host: '192.168.65.2', port: 30003 }
]
2022-02-11T23:52:15.482Z ioredis:cluster:connectionPool Connecting to 192.168.65.2:30001 as master
2022-02-11T23:52:15.504Z ioredis:redis status[192.168.65.2:30001]: [empty] -> wait
2022-02-11T23:52:15.511Z ioredis:cluster:connectionPool Connecting to 192.168.65.2:30002 as master
2022-02-11T23:52:15.517Z ioredis:redis status[192.168.65.2:30002]: [empty] -> wait
2022-02-11T23:52:15.519Z ioredis:cluster:connectionPool Connecting to 192.168.65.2:30003 as master
2022-02-11T23:52:15.521Z ioredis:redis status[192.168.65.2:30003]: [empty] -> wait
2022-02-11T23:52:15.530Z ioredis:cluster getting slot cache from 192.168.65.2:30002
2022-02-11T23:52:15.541Z ioredis:redis status[192.168.65.2:30002 (ioredis-cluster(refresher))]: [empty] -> wait
2022-02-11T23:52:15.590Z ioredis:redis status[192.168.65.2:30002 (ioredis-cluster(refresher))]: wait -> connecting
2022-02-11T23:52:15.603Z ioredis:redis queue command[192.168.65.2:30002 (ioredis-cluster(refresher))]: 0 -> cluster([ 'slots' ])
2022-02-11T23:52:15.614Z ioredis:cluster:subscriber selected a subscriber 192.168.65.2:30001
2022-02-11T23:52:15.621Z ioredis:redis status[192.168.65.2:30001 (ioredis-cluster(subscriber))]: [empty] -> wait
2022-02-11T23:52:15.622Z ioredis:cluster:subscriber started
2022-02-11T23:52:15.734Z ioredis:redis status[192.168.65.2:30002 (ioredis-cluster(refresher))]: connecting -> connect
2022-02-11T23:52:15.737Z ioredis:redis status[192.168.65.2:30002 (ioredis-cluster(refresher))]: connect -> ready
2022-02-11T23:52:15.739Z ioredis:connection set the connection name [ioredis-cluster(refresher)]
2022-02-11T23:52:15.742Z ioredis:redis write command[192.168.65.2:30002 (ioredis-cluster(refresher))]: 0 -> client([ 'setname', 'ioredis-cluster(refresher)' ])
2022-02-11T23:52:15.749Z ioredis:connection send 1 commands in offline queue
2022-02-11T23:52:15.750Z ioredis:redis write command[192.168.65.2:30002 (ioredis-cluster(refresher))]: 0 -> cluster([ 'slots' ])
2022-02-11T23:52:15.781Z ioredis:cluster cluster slots result count: 3
2022-02-11T23:52:15.783Z ioredis:cluster cluster slots result [0]: slots 0~5460 served by [ '127.0.0.1:30001', '127.0.0.1:30004' ]
2022-02-11T23:52:15.788Z ioredis:cluster cluster slots result [1]: slots 5461~10922 served by [ '127.0.0.1:30002', '127.0.0.1:30005' ]
2022-02-11T23:52:15.792Z ioredis:cluster cluster slots result [2]: slots 10923~16383 served by [ '127.0.0.1:30003', '127.0.0.1:30006' ]
2022-02-11T23:52:15.849Z ioredis:cluster:connectionPool Reset with [
  { host: '127.0.0.1', port: 30001, readOnly: false },
  { host: '127.0.0.1', port: 30004, readOnly: true },
  { host: '127.0.0.1', port: 30002, readOnly: false },
  { host: '127.0.0.1', port: 30005, readOnly: true },
  { host: '127.0.0.1', port: 30003, readOnly: false },
  { host: '127.0.0.1', port: 30006, readOnly: true }
]
2022-02-11T23:52:15.850Z ioredis:cluster:connectionPool Disconnect 192.168.65.2:30001 because the node does not hold any slot
2022-02-11T23:52:15.851Z ioredis:redis status[192.168.65.2:30001]: wait -> close
2022-02-11T23:52:15.851Z ioredis:connection skip reconnecting since the connection is manually closed.
2022-02-11T23:52:15.852Z ioredis:redis status[192.168.65.2:30001]: close -> end
2022-02-11T23:52:15.857Z ioredis:cluster:connectionPool Remove 192.168.65.2:30001 from the pool
2022-02-11T23:52:15.858Z ioredis:cluster:connectionPool Disconnect 192.168.65.2:30002 because the node does not hold any slot
2022-02-11T23:52:15.858Z ioredis:redis status[192.168.65.2:30002]: wait -> close
2022-02-11T23:52:15.859Z ioredis:connection skip reconnecting since the connection is manually closed.
2022-02-11T23:52:15.859Z ioredis:redis status[192.168.65.2:30002]: close -> end
2022-02-11T23:52:15.861Z ioredis:cluster:connectionPool Remove 192.168.65.2:30002 from the pool
2022-02-11T23:52:15.861Z ioredis:cluster:connectionPool Disconnect 192.168.65.2:30003 because the node does not hold any slot
2022-02-11T23:52:15.861Z ioredis:redis status[192.168.65.2:30003]: wait -> close
2022-02-11T23:52:15.865Z ioredis:connection skip reconnecting since the connection is manually closed.
2022-02-11T23:52:15.866Z ioredis:redis status[192.168.65.2:30003]: close -> end
2022-02-11T23:52:15.866Z ioredis:cluster:connectionPool Remove 192.168.65.2:30003 from the pool
2022-02-11T23:52:15.867Z ioredis:cluster:connectionPool Connecting to 127.0.0.1:30001 as master
2022-02-11T23:52:15.869Z ioredis:redis status[127.0.0.1:30001]: [empty] -> wait
2022-02-11T23:52:15.871Z ioredis:cluster:connectionPool Connecting to 127.0.0.1:30004 as slave
2022-02-11T23:52:15.873Z ioredis:redis status[127.0.0.1:30004]: [empty] -> wait
2022-02-11T23:52:15.874Z ioredis:cluster:connectionPool Connecting to 127.0.0.1:30002 as master
2022-02-11T23:52:15.877Z ioredis:redis status[127.0.0.1:30002]: [empty] -> wait
2022-02-11T23:52:15.877Z ioredis:cluster:connectionPool Connecting to 127.0.0.1:30005 as slave
2022-02-11T23:52:15.882Z ioredis:redis status[127.0.0.1:30005]: [empty] -> wait
2022-02-11T23:52:15.883Z ioredis:cluster:connectionPool Connecting to 127.0.0.1:30003 as master
2022-02-11T23:52:15.885Z ioredis:redis status[127.0.0.1:30003]: [empty] -> wait
2022-02-11T23:52:15.886Z ioredis:cluster:connectionPool Connecting to 127.0.0.1:30006 as slave
2022-02-11T23:52:15.887Z ioredis:redis status[127.0.0.1:30006]: [empty] -> wait
2022-02-11T23:52:15.893Z ioredis:cluster status: connecting -> connect
2022-02-11T23:52:15.904Z ioredis:redis status[127.0.0.1:30002]: wait -> connecting
2022-02-11T23:52:15.906Z ioredis:redis queue command[127.0.0.1:30002]: 0 -> cluster([ 'info' ])
2022-02-11T23:52:15.916Z ioredis:cluster:subscriber subscriber has left, selecting a new one...
2022-02-11T23:52:15.917Z ioredis:redis status[192.168.65.2:30001 (ioredis-cluster(subscriber))]: wait -> close
2022-02-11T23:52:15.918Z ioredis:connection skip reconnecting since the connection is manually closed.
2022-02-11T23:52:15.918Z ioredis:redis status[192.168.65.2:30001 (ioredis-cluster(subscriber))]: close -> end
2022-02-11T23:52:15.919Z ioredis:cluster:subscriber selected a subscriber 127.0.0.1:30004
2022-02-11T23:52:15.921Z ioredis:redis status[127.0.0.1:30004 (ioredis-cluster(subscriber))]: [empty] -> wait
2022-02-11T23:52:16.000Z ioredis:connection error: { Error: connect ECONNREFUSED 127.0.0.1:30002
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1148:16)
  errno: -111,
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 30002 }
2022-02-11T23:52:16.030Z ioredis:redis status[127.0.0.1:30002]: connecting -> close
2022-02-11T23:52:16.031Z ioredis:connection skip reconnecting because `retryStrategy` is not a function
2022-02-11T23:52:16.032Z ioredis:redis status[127.0.0.1:30002]: close -> end
2022-02-11T23:52:16.034Z ioredis:cluster:connectionPool Remove 127.0.0.1:30002 from the pool
2022-02-11T23:52:16.036Z ioredis:cluster Ready check failed (Error: Connection is closed.
    at close (/usr/src/app/node_modules/ioredis/built/redis/event_handler.js:184:25)
    at Socket.<anonymous> (/usr/src/app/node_modules/ioredis/built/redis/event_handler.js:155:20)
    at Object.onceWrapper (events.js:520:26)
    at Socket.emit (events.js:400:28)
    at Socket.emit (domain.js:470:12)
    at TCP.<anonymous> (net.js:675:12)). Reconnecting...
2022-02-11T23:52:16.042Z ioredis:cluster status: connect -> disconnecting
...
</code>```

答:
The clue to the solution was found in the following log snippet:

```<code>2022-02-11T23:52:15.750Z ioredis:redis write command[192.168.65.2:30002 (ioredis-cluster(refresher))]: 0 -> cluster([ 'slots' ])
2022-02-11T23:52:15.781Z ioredis:cluster cluster slots result count: 3
2022-02-11T23:52:15.783Z ioredis:cluster cluster slots result [0]: slots 0~5460 served by [ '127.0.0.1:30001', '127.0.0.1:30004' ]
2022-02-11T23:52:15.788Z ioredis:cluster cluster slots result [1]: slots 5461~10922 served by [ '127.0.0.1:30002', '127.0.0.1:30005' ]
2022-02-11T23:52:15.792Z ioredis:cluster cluster slots result [2]: slots 10923~16383 served by [ '127.0.0.1:30003', '127.0.0.1:30006' ]
</code>```

The internal redis cluster network was still communicating between nodes on network address 127.0.0.1, creating the connect ECONNREFUSED errors when the ioredis client attempted to use those network mappings to establish the cluster connection.

I had to use the natMap option in the ioredis client to remap the internal cluster network connections to the network address of the docker container:

```<code>let natMap = {};
const localHost = "127.0.0.1";

const hosts = process.env.REDIS_HOSTS.split(",").map((connection) => {
  const [host, port] = connection.split(":");

  // assign nat host address mappings
  // when accessing local redis cluster from containerized network
  natMap[`${localHost}:${port}`] = { host, port };

  return {
    host,
    port,
  };
});

// natMap output
// {
//   "127.0.0.1:30001": { host: "docker.internal.network", port: 30001 },
//   "127.0.0.1:30002": { host: "docker.internal.network", port: 30002 },
//   "127.0.0.1:30003": { host: "docker.internal.network", port: 30003 },
// }

// create redis cluster client
const client = new Redis.Cluster(hosts, {
  enableAutoPipelining: true,
  slotsRefreshTimeout: 100000,
  natMap,
});
</code>```

Body:
I have a docker compose containerized client/server node app that is failing to create a stable connection to a redis cluster I have running on my local environment. The redis cluster has 6 nodes (3 master, 3 replica configuration) running on my local machine. Every time I start my app and attempt to connect to redis, the connect event is spammed and I get the following error on my client:

Proxy error: Could not proxy request /check-login from localhost:3000 to http://server.
See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNRESET)

I have made sure to configure the redis cluster to have the settings protected-mode to no and bind to 0.0.0.0 to allow remote access to the cluster. I have confirmed that I can access the cluster locally by pinging one of the cluster nodes redis-cli -h 127.0.0.1 -p 30001:

127.0.0.1:30001> ping
PONG
127.0.0.1:30001> exit

I am setting my REDIS_HOSTS environment to be "host.docker.internal:30001,host.docker.internal:30005,host.docker.internal:30006". This should allow me to connect to my redis cluster running at 127.0.0.1 on my host machine. My node application code:

const Redis = require("ioredis");

const hosts = process.env.REDIS_HOSTS.split(",").map((connection) => {
  const [host, port] = connection.split(":");

  return {
    host,
    port,
  };
});

const client = new Redis.Cluster(hosts, {
  enableAutoPipelining: true,
  slotsRefreshTimeout: 100000,
});

client.on("error", (error) => {
  console.log("redis connection failed: ", error);
});

client.on("connect", () => {
  console.log("redis connection established");
});

module.exports = client;

My ioredis logs:

2022-02-11T23:52:09.970Z ioredis:cluster status: [empty] -> connecting
info: Listening on port 80
2022-02-11T23:52:15.449Z ioredis:cluster resolved hostname host.docker.internal to IP 192.168.65.2
2022-02-11T23:52:15.476Z ioredis:cluster:connectionPool Reset with [
  { host: '192.168.65.2', port: 30001 },
  { host: '192.168.65.2', port: 30002 },
  { host: '192.168.65.2', port: 30003 }
]
2022-02-11T23:52:15.482Z ioredis:cluster:connectionPool Connecting to 192.168.65.2:30001 as master
2022-02-11T23:52:15.504Z ioredis:redis status[192.168.65.2:30001]: [empty] -> wait
2022-02-11T23:52:15.511Z ioredis:cluster:connectionPool Connecting to 192.168.65.2:30002 as master
2022-02-11T23:52:15.517Z ioredis:redis status[192.168.65.2:30002]: [empty] -> wait
2022-02-11T23:52:15.519Z ioredis:cluster:connectionPool Connecting to 192.168.65.2:30003 as master
2022-02-11T23:52:15.521Z ioredis:redis status[192.168.65.2:30003]: [empty] -> wait
2022-02-11T23:52:15.530Z ioredis:cluster getting slot cache from 192.168.65.2:30002
2022-02-11T23:52:15.541Z ioredis:redis status[192.168.65.2:30002 (ioredis-cluster(refresher))]: [empty] -> wait
2022-02-11T23:52:15.590Z ioredis:redis status[192.168.65.2:30002 (ioredis-cluster(refresher))]: wait -> connecting
2022-02-11T23:52:15.603Z ioredis:redis queue command[192.168.65.2:30002 (ioredis-cluster(refresher))]: 0 -> cluster([ 'slots' ])
2022-02-11T23:52:15.614Z ioredis:cluster:subscriber selected a subscriber 192.168.65.2:30001
2022-02-11T23:52:15.621Z ioredis:redis status[192.168.65.2:30001 (ioredis-cluster(subscriber))]: [empty] -> wait
2022-02-11T23:52:15.622Z ioredis:cluster:subscriber started
2022-02-11T23:52:15.734Z ioredis:redis status[192.168.65.2:30002 (ioredis-cluster(refresher))]: connecting -> connect
2022-02-11T23:52:15.737Z ioredis:redis status[192.168.65.2:30002 (ioredis-cluster(refresher))]: connect -> ready
2022-02-11T23:52:15.739Z ioredis:connection set the connection name [ioredis-cluster(refresher)]
2022-02-11T23:52:15.742Z ioredis:redis write command[192.168.65.2:30002 (ioredis-cluster(refresher))]: 0 -> client([ 'setname', 'ioredis-cluster(refresher)' ])
2022-02-11T23:52:15.749Z ioredis:connection send 1 commands in offline queue
2022-02-11T23:52:15.750Z ioredis:redis write command[192.168.65.2:30002 (ioredis-cluster(refresher))]: 0 -> cluster([ 'slots' ])
2022-02-11T23:52:15.781Z ioredis:cluster cluster slots result count: 3
2022-02-11T23:52:15.783Z ioredis:cluster cluster slots result [0]: slots 0~5460 served by [ '127.0.0.1:30001', '127.0.0.1:30004' ]
2022-02-11T23:52:15.788Z ioredis:cluster cluster slots result [1]: slots 5461~10922 served by [ '127.0.0.1:30002', '127.0.0.1:30005' ]
2022-02-11T23:52:15.792Z ioredis:cluster cluster slots result [2]: slots 10923~16383 served by [ '127.0.0.1:30003', '127.0.0.1:30006' ]
2022-02-11T23:52:15.849Z ioredis:cluster:connectionPool Reset with [
  { host: '127.0.0.1', port: 30001, readOnly: false },
  { host: '127.0.0.1', port: 30004, readOnly: true },
  { host: '127.0.0.1', port: 30002, readOnly: false },
  { host: '127.0.0.1', port: 30005, readOnly: true },
  { host: '127.0.0.1', port: 30003, readOnly: false },
  { host: '127.0.0.1', port: 30006, readOnly: true }
]
2022-02-11T23:52:15.850Z ioredis:cluster:connectionPool Disconnect 192.168.65.2:30001 because the node does not hold any slot
2022-02-11T23:52:15.851Z ioredis:redis status[192.168.65.2:30001]: wait -> close
2022-02-11T23:52:15.851Z ioredis:connection skip reconnecting since the connection is manually closed.
2022-02-11T23:52:15.852Z ioredis:redis status[192.168.65.2:30001]: close -> end
2022-02-11T23:52:15.857Z ioredis:cluster:connectionPool Remove 192.168.65.2:30001 from the pool
2022-02-11T23:52:15.858Z ioredis:cluster:connectionPool Disconnect 192.168.65.2:30002 because the node does not hold any slot
2022-02-11T23:52:15.858Z ioredis:redis status[192.168.65.2:30002]: wait -> close
2022-02-11T23:52:15.859Z ioredis:connection skip reconnecting since the connection is manually closed.
2022-02-11T23:52:15.859Z ioredis:redis status[192.168.65.2:30002]: close -> end
2022-02-11T23:52:15.861Z ioredis:cluster:connectionPool Remove 192.168.65.2:30002 from the pool
2022-02-11T23:52:15.861Z ioredis:cluster:connectionPool Disconnect 192.168.65.2:30003 because the node does not hold any slot
2022-02-11T23:52:15.861Z ioredis:redis status[192.168.65.2:30003]: wait -> close
2022-02-11T23:52:15.865Z ioredis:connection skip reconnecting since the connection is manually closed.
2022-02-11T23:52:15.866Z ioredis:redis status[192.168.65.2:30003]: close -> end
2022-02-11T23:52:15.866Z ioredis:cluster:connectionPool Remove 192.168.65.2:30003 from the pool
2022-02-11T23:52:15.867Z ioredis:cluster:connectionPool Connecting to 127.0.0.1:30001 as master
2022-02-11T23:52:15.869Z ioredis:redis status[127.0.0.1:30001]: [empty] -> wait
2022-02-11T23:52:15.871Z ioredis:cluster:connectionPool Connecting to 127.0.0.1:30004 as slave
2022-02-11T23:52:15.873Z ioredis:redis status[127.0.0.1:30004]: [empty] -> wait
2022-02-11T23:52:15.874Z ioredis:cluster:connectionPool Connecting to 127.0.0.1:30002 as master
2022-02-11T23:52:15.877Z ioredis:redis status[127.0.0.1:30002]: [empty] -> wait
2022-02-11T23:52:15.877Z ioredis:cluster:connectionPool Connecting to 127.0.0.1:30005 as slave
2022-02-11T23:52:15.882Z ioredis:redis status[127.0.0.1:30005]: [empty] -> wait
2022-02-11T23:52:15.883Z ioredis:cluster:connectionPool Connecting to 127.0.0.1:30003 as master
2022-02-11T23:52:15.885Z ioredis:redis status[127.0.0.1:30003]: [empty] -> wait
2022-02-11T23:52:15.886Z ioredis:cluster:connectionPool Connecting to 127.0.0.1:30006 as slave
2022-02-11T23:52:15.887Z ioredis:redis status[127.0.0.1:30006]: [empty] -> wait
2022-02-11T23:52:15.893Z ioredis:cluster status: connecting -> connect
2022-02-11T23:52:15.904Z ioredis:redis status[127.0.0.1:30002]: wait -> connecting
2022-02-11T23:52:15.906Z ioredis:redis queue command[127.0.0.1:30002]: 0 -> cluster([ 'info' ])
2022-02-11T23:52:15.916Z ioredis:cluster:subscriber subscriber has left, selecting a new one...
2022-02-11T23:52:15.917Z ioredis:redis status[192.168.65.2:30001 (ioredis-cluster(subscriber))]: wait -> close
2022-02-11T23:52:15.918Z ioredis:connection skip reconnecting since the connection is manually closed.
2022-02-11T23:52:15.918Z ioredis:redis status[192.168.65.2:30001 (ioredis-cluster(subscriber))]: close -> end
2022-02-11T23:52:15.919Z ioredis:cluster:subscriber selected a subscriber 127.0.0.1:30004
2022-02-11T23:52:15.921Z ioredis:redis status[127.0.0.1:30004 (ioredis-cluster(subscriber))]: [empty] -> wait
2022-02-11T23:52:16.000Z ioredis:connection error: { Error: connect ECONNREFUSED 127.0.0.1:30002
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1148:16)
  errno: -111,
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 30002 }
2022-02-11T23:52:16.030Z ioredis:redis status[127.0.0.1:30002]: connecting -> close
2022-02-11T23:52:16.031Z ioredis:connection skip reconnecting because `retryStrategy` is not a function
2022-02-11T23:52:16.032Z ioredis:redis status[127.0.0.1:30002]: close -> end
2022-02-11T23:52:16.034Z ioredis:cluster:connectionPool Remove 127.0.0.1:30002 from the pool
2022-02-11T23:52:16.036Z ioredis:cluster Ready check failed (Error: Connection is closed.
    at close (/usr/src/app/node_modules/ioredis/built/redis/event_handler.js:184:25)
    at Socket.<anonymous> (/usr/src/app/node_modules/ioredis/built/redis/event_handler.js:155:20)
    at Object.onceWrapper (events.js:520:26)
    at Socket.emit (events.js:400:28)
    at Socket.emit (domain.js:470:12)
    at TCP.<anonymous> (net.js:675:12)). Reconnecting...
2022-02-11T23:52:16.042Z ioredis:cluster status: connect -> disconnecting
...

Body:
The clue to the solution was found in the following log snippet:

2022-02-11T23:52:15.750Z ioredis:redis write command[192.168.65.2:30002 (ioredis-cluster(refresher))]: 0 -> cluster([ 'slots' ])
2022-02-11T23:52:15.781Z ioredis:cluster cluster slots result count: 3
2022-02-11T23:52:15.783Z ioredis:cluster cluster slots result [0]: slots 0~5460 served by [ '127.0.0.1:30001', '127.0.0.1:30004' ]
2022-02-11T23:52:15.788Z ioredis:cluster cluster slots result [1]: slots 5461~10922 served by [ '127.0.0.1:30002', '127.0.0.1:30005' ]
2022-02-11T23:52:15.792Z ioredis:cluster cluster slots result [2]: slots 10923~16383 served by [ '127.0.0.1:30003', '127.0.0.1:30006' ]

The internal redis cluster network was still communicating between nodes on network address 127.0.0.1, creating the connect ECONNREFUSED errors when the ioredis client attempted to use those network mappings to establish the cluster connection.

I had to use the natMap option in the ioredis client to remap the internal cluster network connections to the network address of the docker container:

let natMap = {};
const localHost = "127.0.0.1";

const hosts = process.env.REDIS_HOSTS.split(",").map((connection) => {
  const [host, port] = connection.split(":");

  // assign nat host address mappings
  // when accessing local redis cluster from containerized network
  natMap[`${localHost}:${port}`] = { host, port };

  return {
    host,
    port,
  };
});

// natMap output
// {
//   "127.0.0.1:30001": { host: "docker.internal.network", port: 30001 },
//   "127.0.0.1:30002": { host: "docker.internal.network", port: 30002 },
//   "127.0.0.1:30003": { host: "docker.internal.network", port: 30003 },
// }

// create redis cluster client
const client = new Redis.Cluster(hosts, {
  enableAutoPipelining: true,
  slotsRefreshTimeout: 100000,
  natMap,
});


问:
javascript;storing values in array
I am trying to store values in array using javascript..but i get strange error in javascript.below is my code

```<code>var a = 1;
for(i=0;i<4;i++)
{

var all = new Array();
all[i]=a;
a++;
}

alert(all[1]);
alert(all[2]);
alert(all[3]);
</code>```

please check the code here : http://jsfiddle.net/D8Suq/

for all[1] and all[2] i am getting undefined error..but all[3] is working fine,,,am confused.some one please help me

答:
```<code> var all = [];
    for (i = 0; i <= 4; i++) {
      let element = i;
      all.push(element);
    }
    alert(all[1]);
    alert(all[2]);
    alert(all[3]);
    alert(all[4]);
</code>```

ContentLicense: CC BY-SA 3.0

Title: javascript;storing values in array

Body:
I am trying to store values in array using javascript..but i get strange error in javascript.below is my code

var a = 1;
for(i=0;i<4;i++)
{

var all = new Array();
all[i]=a;
a++;
}

alert(all[1]);
alert(all[2]);
alert(all[3]);

please check the code here : http://jsfiddle.net/D8Suq/

for all[1] and all[2] i am getting undefined error..but all[3] is working fine,,,am confused.some one please help me


问:
EF Core multiple OneToMany relations
I'm creating my database in SQL Server and it's mapping. I would like to allow multiple tables (for example Purchase and Provider) to have entries in the table Documents:

```<code>public class Document
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public Guid OwnerId { get; set; }
    public string? Note { get; set; }
}

public class Provider
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public ICollection<Document> Documents { get; set; }
}

public class Purchase
{
    public Guid Id { get; set; }
    public DateTime Date { get; set; }
    public ICollection<Document> Documents { get; set; }
}
</code>```

I created the mappings for the two classes:

```<code>public class ProviderMapping : IEntityTypeConfiguration<Provider>
{
    public void Configure(EntityTypeBuilder<Provider> builder)
    {
        builder
            .HasKey(e => e.Id);

        builder
            .Property(e => e.Name)
            .HasMaxLength(50);

        builder
            .HasMany(x => x.Documents)
            .WithOne()
            .OnDelete(DeleteBehavior.Cascade)
            .HasForeignKey(x => x.OwnerId);
}

public class PurchaseMapping : IEntityTypeConfiguration<Purchase>
{
    public void Configure(EntityTypeBuilder<Purchase> builder)
    {
        builder
             .HasKey(x => x.Id);

        builder
            .HasMany(x => x.Documents)
            .WithOne()
            .OnDelete(DeleteBehavior.Cascade)
            .HasForeignKey(x => x.OwnerId);
    }
}
</code>```

But the SQL Server database doesn't let me create a foreign key on the same column.

Is there a method how to make this possible? I had this before when creating database tables manually if I call correct (was a few years ago), but can't get it running with Entity Framework Core.

Thanks in advance

答:
you have to fix document by adding purcharse Id</p>
```<code>public class Document
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string? Note { get; set; }

    public Guid ProviderId { get; set; }
    public virtual Provider Provider { get; set; }

    public Guid PurchaseId { get; set; }
    public virtual Purchase Purchase { get; set; }
}
</code>```

Title: EF Core multiple OneToMany relations

Body:
I'm creating my database in SQL Server and it's mapping. I would like to allow multiple tables (for example Purchase and Provider) to have entries in the table Documents:

public class Document
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public Guid OwnerId { get; set; }
    public string? Note { get; set; }
}

public class Provider
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public ICollection<Document> Documents { get; set; }
}

public class Purchase
{
    public Guid Id { get; set; }
    public DateTime Date { get; set; }
    public ICollection<Document> Documents { get; set; }
}

I created the mappings for the two classes:

public class ProviderMapping : IEntityTypeConfiguration<Provider>
{
    public void Configure(EntityTypeBuilder<Provider> builder)
    {
        builder
            .HasKey(e => e.Id);

        builder
            .Property(e => e.Name)
            .HasMaxLength(50);

        builder
            .HasMany(x => x.Documents)
            .WithOne()
            .OnDelete(DeleteBehavior.Cascade)
            .HasForeignKey(x => x.OwnerId);
}

public class PurchaseMapping : IEntityTypeConfiguration<Purchase>
{
    public void Configure(EntityTypeBuilder<Purchase> builder)
    {
        builder
             .HasKey(x => x.Id);

        builder
            .HasMany(x => x.Documents)
            .WithOne()
            .OnDelete(DeleteBehavior.Cascade)
            .HasForeignKey(x => x.OwnerId);
    }
}

But the SQL Server database doesn't let me create a foreign key on the same column.

Is there a method how to make this possible? I had this before when creating database tables manually if I call correct (was a few years ago), but can't get it running with Entity Framework Core.

Thanks in advance

Body:
you have to fix document by adding purcharse Id

public class Document
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string? Note { get; set; }

    public Guid ProviderId { get; set; }
    public virtual Provider Provider { get; set; }

    public Guid PurchaseId { get; set; }
    public virtual Purchase Purchase { get; set; }
}


问:
During installation of lightgbm it says that you should install cmake first, while I have installed it
I want to install the GPU version of lightgbm on Ubuntu, based on the following command:

```<code>pip install lightgbm --install-option=--gpu
</code>```

During installation, an error is occurred saying "Please install CMake first". After installing CMake, I get the same error again. To be sure that CMake is installed, I run the following command and get the correct version of the installed CMake:

```<code>/opt/cmake/bin/cmake -version
</code>```

What is the possible reason of this error?

答: I had same issue too, on my M1 MacBook Air. I solve this problem by using brew. Firstly, I ran brew install gcc then brew install CMake because of dependicies. After that, I ran brew install lightgbm on my IDE's terminal. Finally, run pip install lightgbm command on my IDE's terminal and I can succesfully import lightgbm.

Body:
I want to install the GPU version of lightgbm on Ubuntu, based on the following command:

pip install lightgbm --install-option=--gpu

During installation, an error is occurred saying "Please install CMake first". After installing CMake, I get the same error again. To be sure that CMake is installed, I run the following command and get the correct version of the installed CMake:

/opt/cmake/bin/cmake -version

What is the possible reason of this error?


问:
A StringToken Parser which gives Google Search style "Did you mean:" Suggestions

Seeking a method to:

Take whitespace separated tokens in a String; return a suggested Word

ie:

Google Search can take "fonetic wrd nterpreterr",

and atop of the result page it shows "Did you mean: phonetic word interpreter"

A solution in any of the C* languages or Java would be preferred.

Are there any existing Open Libraries which perform such functionality?

Or is there a way to Utilise a Google API to request a suggested word?

答:
Since no one has yet mentioned it, I'll give one more phrase to search for: "edit distance" (for example, link text).
That can be used to find closest matches, assuming it's typos where letters are transposed, missing or added.

But usually this is also coupled with some sort of relevancy information; either by simple popularity (to assume most commonly used close-enough match is most likely correct word), or by contextual likelihood (words that follow preceding correct word, or come before one). This gets into information retrieval; one way to start is to look at bigram and trigrams (sequences of words seen together). Google has very extensive freely available data sets for these.

For simple initial solution though a dictionary couple with Levenshtein-based matchers works surprisingly well.

OwnerDisplayName: Ande Turner

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: StaxMan


问:
Pandas df: retrieving the records that have cell value == float not working. What am I doing wrong?
I have this code and I can't figure out what to do to retrieve the row that I want.

I am trying to retrieve the row that has device_id=16384035. I tried both float and integer and also string there (since it tells me the column is object) but none worked

```<code>print(s_devices['Device ID'])
print(s_devices.columns)
print(s_devices.iloc[0,1])
print(type(s_devices.iloc[0,1]))
print(s_devices[['Device ID']==float(16384035)])
</code>```

The above prints the below

```<code>0      16384035.0
1      17177488.0
2      16384036.0
3      17177489.0
4               0
          ...
534    17746358.0
535    17746359.0
536    17746360.0
537    17746361.0
538    17746362.0
Name: Device ID, Length: 539, dtype: object
Index(['Serial Number', 'Device ID', 'Device Name'.....some keys removed from here],
      dtype='object')
16384035.0
<class 'float'>
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
~/.local/lib/python3.9/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   3360             try:
-> 3361                 return self._engine.get_loc(casted_key)
   3362             except KeyError as err:

~/.local/lib/python3.9/site-packages/pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

~/.local/lib/python3.9/site-packages/pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: False

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
/tmp/ipykernel_540/2993650396.py in <module>
      3 print(s_devices.iloc[0,1])
      4 print(type(s_devices.iloc[0,1]))
----> 5 print(s_devices[['Device ID']==float(16384035)])

~/.local/lib/python3.9/site-packages/pandas/core/frame.py in __getitem__(self, key)
   3453             if self.columns.nlevels > 1:
   3454                 return self._getitem_multilevel(key)
-> 3455             indexer = self.columns.get_loc(key)
   3456             if is_integer(indexer):
   3457                 indexer = [indexer]

~/.local/lib/python3.9/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   3361                 return self._engine.get_loc(casted_key)
   3362             except KeyError as err:
-> 3363                 raise KeyError(key) from err
   3364
   3365         if is_scalar(key) and isna(key) and not self.hasnans:

KeyError: False
</code>```

答:
You're indexing it wrong:

```<code>s_devices[['Device ID']==float(16384035)]
</code>```

You create a boolean Series with the equality and index the DataFrame with it:

```<code>msk = s_devices['Device ID']==float(16384035)
out = s_devices[msk]
</code>```

or as a one-liner:

```<code>out = s_devices[s_devices['Device ID']==float(16384035)]
</code>```

Note that ['Device ID']==float(16384035) evaluates to False. So what you're trying to do is: s_devices[False] which raises the KeyError since there's no column named False.

Body:
I have this code and I can't figure out what to do to retrieve the row that I want.

I am trying to retrieve the row that has device_id=16384035. I tried both float and integer and also string there (since it tells me the column is object) but none worked

print(s_devices['Device ID'])
print(s_devices.columns)
print(s_devices.iloc[0,1])
print(type(s_devices.iloc[0,1]))
print(s_devices[['Device ID']==float(16384035)])

The above prints the below

0      16384035.0
1      17177488.0
2      16384036.0
3      17177489.0
4               0
          ...
534    17746358.0
535    17746359.0
536    17746360.0
537    17746361.0
538    17746362.0
Name: Device ID, Length: 539, dtype: object
Index(['Serial Number', 'Device ID', 'Device Name'.....some keys removed from here],
      dtype='object')
16384035.0
<class 'float'>
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
~/.local/lib/python3.9/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   3360             try:
-> 3361                 return self._engine.get_loc(casted_key)
   3362             except KeyError as err:

~/.local/lib/python3.9/site-packages/pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

~/.local/lib/python3.9/site-packages/pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: False

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
/tmp/ipykernel_540/2993650396.py in <module>
      3 print(s_devices.iloc[0,1])
      4 print(type(s_devices.iloc[0,1]))
----> 5 print(s_devices[['Device ID']==float(16384035)])

~/.local/lib/python3.9/site-packages/pandas/core/frame.py in __getitem__(self, key)
   3453             if self.columns.nlevels > 1:
   3454                 return self._getitem_multilevel(key)
-> 3455             indexer = self.columns.get_loc(key)
   3456             if is_integer(indexer):
   3457                 indexer = [indexer]

~/.local/lib/python3.9/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   3361                 return self._engine.get_loc(casted_key)
   3362             except KeyError as err:
-> 3363                 raise KeyError(key) from err
   3364
   3365         if is_scalar(key) and isna(key) and not self.hasnans:

KeyError: False

Body:
You're indexing it wrong:

s_devices[['Device ID']==float(16384035)]

You create a boolean Series with the equality and index the DataFrame with it:

msk = s_devices['Device ID']==float(16384035)
out = s_devices[msk]

or as a one-liner:

out = s_devices[s_devices['Device ID']==float(16384035)]

Note that ['Device ID']==float(16384035) evaluates to False. So what you're trying to do is: s_devices[False] which raises the KeyError since there's no column named False.


问:
How to disable an Entry on tkinter when a Checkbutton is unchecked using for loop and dictionary
I'm working on a Windows application for my work and my knowledge on Python is very limited, so I didn't know how to figure this out :

I want to make each entry widget inside the frame disabled when its checkbutton is unchecked and enabled when its checkbutton is checked and make them all checked by default.
I tried this code that I took part of it from this tutorial but it didn't work as expected.

```<code>from tkinter import *

class Principal():
    def __init__(self):
        self.root= Tk()
        self.root.geometry('800x800')

        self.prixArticlesFrame = LabelFrame(self.root, text="Prix des articles", width=2000)
        self.prixArticlesFrame.place(relx = 0.75, rely = 0.15,anchor = N)

        self.DefautArticlesCheckButton={
            "Deblai" : IntVar(),
            "Remblai" : IntVar(),
            "Blocage" : IntVar(),
            "Beton de propreté": IntVar(),
            "Beton armé": IntVar(),
            "Acier à haute adherence": IntVar(),
            "Joint de dilatation": IntVar(),

        }
        for index, (key, value) in enumerate(self.DefautArticlesCheckButton.items()):
            self.cur_check = Checkbutton(self.prixArticlesFrame,
            text=key,variable=self.DefautArticlesCheckButton[key], onvalue=1,
            offvalue=0,command=self.ArticlesEntryState)
            self.cur_check.grid(row=index, column=0, padx=10, pady=10, sticky="W")

        self.DefautArticlesEntries={
            "Deblai" : StringVar(),
            "Remblai" : StringVar(),
            "Blocage" : StringVar(),
            "Beton de propreté": StringVar(),
            "Beton armé": StringVar(),
            "Acier à haute adherence": StringVar(),
            "Joint de dilatation": StringVar(),

        }

        for index, (key, value) in enumerate(self.DefautArticlesEntries.items()):
            self.cur_entry = 'DefautArticlesEntries' +key

            self.cur_entry=Entry(self.prixArticlesFrame,width=10,
                          textvariable=self.DefautArticlesEntries[key])
            self.cur_entry.grid(row=index,column=2,padx=10)
            self.cur_entry.config(state=NORMAL)
        self.root.mainloop()

    def ArticlesEntryState(self):
        for index, (key, value) in enumerate(self.DefautArticlesCheckButton.items()):

            if self.DefautArticlesCheckButton[key].get() == 1:
                self.cur_entry.grid(row=index,column=2,padx=10)
                self.cur_entry.config(state=NORMAL)

            elif self.DefautArticlesCheckButton[key].get() == 0:
                self.cur_entry.config(state=DISABLED)

app = Principal()
</code>```

here is what I got in gif image

What I have done wrong?
Thanks

答:
Update:

As @acw1668 said, I used self.cur_entry to change the entry's state when checkbutton is checked or unchecked and this only change the last entry's state.
I created instead a list and appended the entries created to it :

```<code>from tkinter import *

class Principal():

    def __init__(self):

        self.root= Tk()

        self.root.geometry('800x800')

        self.AjouterArticleFrame = LabelFrame(self.root, text="Ajouter un article", width=2000)
        self.AjouterArticleFrame.place_forget()

        self.DefautArticlesCheckButton={
            "Deblai" : IntVar(value=1),
            "Remblai" : IntVar(value=1),
            "Blocage" : IntVar(value=1),
            "Beton de propreté": IntVar(value=1),
            "Beton armé": IntVar(value=1),
            "Acier à haute adherence": IntVar(value=1),
            "Joint de dilatation": IntVar(value=1),
            }

        self.variablesList=[]
        for index, (key, value) in enumerate(self.DefautArticlesCheckButton.items()):
            checkbutton_=Checkbutton(self.prixArticlesFrame, text=key,variable=self.DefautArticlesCheckButton[key], onvalue=1, offvalue=0,command=self.DefaultArticlesEntryState)
            checkbutton_.grid(row=index, column=0, padx=10, pady=10, sticky="W")
            self.variablesList.append(self.DefautArticlesCheckButton[key])

        self.DefautArticlesPrix=[
            "Deblai" ,
            "Remblai" ,
            "Blocage" ,
            "Beton de propreté" ,
            "Beton armé" ,
            "Acier à haute adherence" ,
            "Joint de dilatation",
        ]
        self.DefautArticlesPrixEntriesWidgets=[]

        for i in self.DefautArticlesPrix:
            entry_prix=Entry(self.prixArticlesFrame,width=10)
            entry_prix.grid(row=self.DefautArticlesPrix.index(i),column=2,padx=10)
            self.DefautArticlesPrixEntriesWidgets.append(entry_prix)

    def DefaultArticlesEntryState(self):
        for i in range(len(self.variablesList)):
            if int(self.variablesList[i].get()) == 1:
                self.DefautArticlesPrixEntriesWidgets[i].grid(row=i,column=2,padx=10)
                self.DefautArticlesPrixEntriesWidgets[i].config(state=NORMAL)

            elif int(self.variablesList[i].get()) == 0:
                self.DefautArticlesPrixEntriesWidgets[i].config(state=DISABLED)

app = Principal()

</code>```

Body:
I'm working on a Windows application for my work and my knowledge on Python is very limited, so I didn't know how to figure this out :

I want to make each entry widget inside the frame disabled when its checkbutton is unchecked and enabled when its checkbutton is checked and make them all checked by default.
I tried this code that I took part of it from this tutorial but it didn't work as expected.

from tkinter import *

class Principal():
    def __init__(self):
        self.root= Tk()
        self.root.geometry('800x800')

        self.prixArticlesFrame = LabelFrame(self.root, text="Prix des articles", width=2000)
        self.prixArticlesFrame.place(relx = 0.75, rely = 0.15,anchor = N)

        self.DefautArticlesCheckButton={
            "Deblai" : IntVar(),
            "Remblai" : IntVar(),
            "Blocage" : IntVar(),
            "Beton de propreté": IntVar(),
            "Beton armé": IntVar(),
            "Acier à haute adherence": IntVar(),
            "Joint de dilatation": IntVar(),

        }
        for index, (key, value) in enumerate(self.DefautArticlesCheckButton.items()):
            self.cur_check = Checkbutton(self.prixArticlesFrame,
            text=key,variable=self.DefautArticlesCheckButton[key], onvalue=1,
            offvalue=0,command=self.ArticlesEntryState)
            self.cur_check.grid(row=index, column=0, padx=10, pady=10, sticky="W")

        self.DefautArticlesEntries={
            "Deblai" : StringVar(),
            "Remblai" : StringVar(),
            "Blocage" : StringVar(),
            "Beton de propreté": StringVar(),
            "Beton armé": StringVar(),
            "Acier à haute adherence": StringVar(),
            "Joint de dilatation": StringVar(),

        }

        for index, (key, value) in enumerate(self.DefautArticlesEntries.items()):
            self.cur_entry = 'DefautArticlesEntries' +key

            self.cur_entry=Entry(self.prixArticlesFrame,width=10,
                          textvariable=self.DefautArticlesEntries[key])
            self.cur_entry.grid(row=index,column=2,padx=10)
            self.cur_entry.config(state=NORMAL)
        self.root.mainloop()

    def ArticlesEntryState(self):
        for index, (key, value) in enumerate(self.DefautArticlesCheckButton.items()):

            if self.DefautArticlesCheckButton[key].get() == 1:
                self.cur_entry.grid(row=index,column=2,padx=10)
                self.cur_entry.config(state=NORMAL)

            elif self.DefautArticlesCheckButton[key].get() == 0:
                self.cur_entry.config(state=DISABLED)

app = Principal()

here is what I got in gif image

What I have done wrong?
Thanks

Body:
Update:

As @acw1668 said, I used self.cur_entry to change the entry's state when checkbutton is checked or unchecked and this only change the last entry's state.
I created instead a list and appended the entries created to it :

from tkinter import *

class Principal():

    def __init__(self):

        self.root= Tk()

        self.root.geometry('800x800')

        self.AjouterArticleFrame = LabelFrame(self.root, text="Ajouter un article", width=2000)
        self.AjouterArticleFrame.place_forget()

        self.DefautArticlesCheckButton={
            "Deblai" : IntVar(value=1),
            "Remblai" : IntVar(value=1),
            "Blocage" : IntVar(value=1),
            "Beton de propreté": IntVar(value=1),
            "Beton armé": IntVar(value=1),
            "Acier à haute adherence": IntVar(value=1),
            "Joint de dilatation": IntVar(value=1),
            }

        self.variablesList=[]
        for index, (key, value) in enumerate(self.DefautArticlesCheckButton.items()):
            checkbutton_=Checkbutton(self.prixArticlesFrame, text=key,variable=self.DefautArticlesCheckButton[key], onvalue=1, offvalue=0,command=self.DefaultArticlesEntryState)
            checkbutton_.grid(row=index, column=0, padx=10, pady=10, sticky="W")
            self.variablesList.append(self.DefautArticlesCheckButton[key])

        self.DefautArticlesPrix=[
            "Deblai" ,
            "Remblai" ,
            "Blocage" ,
            "Beton de propreté" ,
            "Beton armé" ,
            "Acier à haute adherence" ,
            "Joint de dilatation",
        ]
        self.DefautArticlesPrixEntriesWidgets=[]

        for i in self.DefautArticlesPrix:
            entry_prix=Entry(self.prixArticlesFrame,width=10)
            entry_prix.grid(row=self.DefautArticlesPrix.index(i),column=2,padx=10)
            self.DefautArticlesPrixEntriesWidgets.append(entry_prix)

    def DefaultArticlesEntryState(self):
        for i in range(len(self.variablesList)):
            if int(self.variablesList[i].get()) == 1:
                self.DefautArticlesPrixEntriesWidgets[i].grid(row=i,column=2,padx=10)
                self.DefautArticlesPrixEntriesWidgets[i].config(state=NORMAL)

            elif int(self.variablesList[i].get()) == 0:
                self.DefautArticlesPrixEntriesWidgets[i].config(state=DISABLED)

app = Principal()


问:
Regex splitting on newline outside of quotes in VBA Macros
I have a file which contains pipe separated string, I want to split that string on new lines that are outside double quotes using Split function of VBA if possible.
File date looks like this.
fileStr =  abc|hbd|hss
abd|"shs
hshs"|jdjd
hddn|hddd|sdjdd

desired ouput should be like below
Row 1 -> abc|hbd|hss
Row 2 -> abd|"shs
hshs"|jdjd
Row 3 -> hddn|hddd|sdjdd

I have tried Split(strData, vbNewLine)  but its not working.

Can you please give the code snippet which I can directly use in my VBA Code.

Note: Need this in VBA Macros not in other languages

答:
I suggest you match, rather than split, using the following regular expression (with re.Global = True).

```<code>(?=.)[^"\r\n]*(?:"(?:[^"]*")+)?[^"\r\n]*
</code>```

Demo

The expression can be broken down as follows.

```<code>(?=.)      # positive lookahead asserts that a character follows
[^"\r\n]*  # match >= 0 characters other than double-quotes
           # and line terminators
(?:        # begin a non-capture group
  "        # match a double-quote
  (?:      # begin a non-capture group
    [^"]*  # match >= 0 characters other than double-quotes
    "      # match a double-quote
  )+       # end inner non-capture group and execute >= 1 times
)?         # end outer non-capture group and make it optional
[^"\r\n]*  # match >= 0 characters other than double-quotes
</code>```

The purpose of the positive lookahead at the beginning is to avoid matching empty strings.

Body:
I suggest you match, rather than split, using the following regular expression (with re.Global = True).

(?=.)[^"\r\n]*(?:"(?:[^"]*")+)?[^"\r\n]*

Demo

The expression can be broken down as follows.

(?=.)      # positive lookahead asserts that a character follows
[^"\r\n]*  # match >= 0 characters other than double-quotes
           # and line terminators
(?:        # begin a non-capture group
  "        # match a double-quote
  (?:      # begin a non-capture group
    [^"]*  # match >= 0 characters other than double-quotes
    "      # match a double-quote
  )+       # end inner non-capture group and execute >= 1 times
)?         # end outer non-capture group and make it optional
[^"\r\n]*  # match >= 0 characters other than double-quotes

The purpose of the positive lookahead at the beginning is to avoid matching empty strings.


问:
align div horizontally after screen resize using css
I'm trying to align div horizontally as the browser resizes, currently, I have 3 divs. As per the requirement, I can add an additional div. My problem is as soon I increase the window size above 2500, the right side of the screen becomes empty & all the divs are floating to left. As I cannot set the div width to 30-33% as per the requirement. Below is my code. kindly help.

div.box-container {
  mc-grid-row: true;
  margin-left: auto;
  margin-right: auto;
  float: left;
  display: flex;
  width: 100%
}

div.box {
  float: left;
  background-color: #ffffff;
  position: relative;
  padding: 10px;
  box-sizing: border-box;
  height: 326px;
  margin-left: 20px;
  margin-bottom: 0;
  top: 55px;
  border-top-right-radius: 0px;
  width: 30%;
  border: 1px solid #cccccc;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box-container">

  <div class="box">
    <p>jfn,mnfngf,mn,mgfnbgnkjdkjgkdg</p>
  </div>
  <div class="box">
    <p>jfn,mnfngf,mn,mgfnbgnkjdkjgkdg</p>
  </div>
  <div class="box">
    <p>jfn,mnfngf,mn,mgfnbgnkjdkjgkdg</p>
  </div>
</div></code>```

答:
Remove float and only use flex:

* {
  box-sizing: border-box;
}

body,
html {
  margin: auto;
}

div.box-container {
  mc-grid-row: true;
  margin-left: auto;
  margin-right: auto;
  display: flex;
  width: 100%;
}

div.box {
  background-color: #ffffff;
  padding: 10px;
  height: 326px;
  margin-left: 20px;
  margin-bottom: 0;
  top: 55px;
  border-top-right-radius: 0px;
  width: calc(100vw / 3);
  /*calc(100vw / number of div)*/
  border: 1px solid #cccccc;
  word-break: break-word;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box-container">
  <div class="box">
    <p>jfn,mnfngf,mn,mgfnbgnkjdkjgkdg</p>
  </div>
  <div class="box">
    <p>jfn,mnfngf,mn,mgfnbgnkjdkjgkdg</p>
  </div>
  <div class="box">
    <p>jfn,mnfngf,mn,mgfnbgnkjdkjgkdg</p>
  </div>
</div></code>```

Body:
I'm trying to align div horizontally as the browser resizes, currently, I have 3 divs. As per the requirement, I can add an additional div. My problem is as soon I increase the window size above 2500, the right side of the screen becomes empty & all the divs are floating to left. As I cannot set the div width to 30-33% as per the requirement. Below is my code. kindly help.

div.box-container {
  mc-grid-row: true;
  margin-left: auto;
  margin-right: auto;
  float: left;
  display: flex;
  width: 100%
}

div.box {
  float: left;
  background-color: #ffffff;
  position: relative;
  padding: 10px;
  box-sizing: border-box;
  height: 326px;
  margin-left: 20px;
  margin-bottom: 0;
  top: 55px;
  border-top-right-radius: 0px;
  width: 30%;
  border: 1px solid #cccccc;
}

jfn,mnfngf,mn,mgfnbgnkjdkjgkdg

jfn,mnfngf,mn,mgfnbgnkjdkjgkdg

jfn,mnfngf,mn,mgfnbgnkjdkjgkdg

Body:
Remove float and only use flex:

* {
  box-sizing: border-box;
}

body,
html {
  margin: auto;
}

div.box-container {
  mc-grid-row: true;
  margin-left: auto;
  margin-right: auto;
  display: flex;
  width: 100%;
}

div.box {
  background-color: #ffffff;
  padding: 10px;
  height: 326px;
  margin-left: 20px;
  margin-bottom: 0;
  top: 55px;
  border-top-right-radius: 0px;
  width: calc(100vw / 3);
  /*calc(100vw / number of div)*/
  border: 1px solid #cccccc;
  word-break: break-word;
}

<div class="box-container">
  <div class="box">
    <p>jfn,mnfngf,mn,mgfnbgnkjdkjgkdg</p>
  </div>
  <div class="box">
    <p>jfn,mnfngf,mn,mgfnbgnkjdkjgkdg</p>
  </div>
  <div class="box">
    <p>jfn,mnfngf,mn,mgfnbgnkjdkjgkdg</p>
  </div>
</div>


问:
Counting unique values in a column in pandas dataframe like in Qlik?
If I have a table like this:

```<code>df = pd.DataFrame({
         'hID': [101, 102, 103, 101, 102, 104, 105, 101],
         'dID': [10, 11, 12, 10, 11, 10, 12, 10],
         'uID': ['James', 'Henry', 'Abe', 'James', 'Henry', 'Brian', 'Claude', 'James'],
         'mID': ['A', 'B', 'A', 'B', 'A', 'A', 'A', 'C']
})
</code>```

I can do count(distinct hID) in Qlik to come up with count of 5 for unique hID.  How do I do that in python using a pandas dataframe?  Or maybe a numpy array?  Similarly, if were to do count(hID) I will get 8 in Qlik.  What is the equivalent way to do it in pandas?

答:
For unique count of your rows without duplications

df['hID'].nunique()

To know the number of each unique row content duplicated

df['hID'].value_counts()

Body:
If I have a table like this:

df = pd.DataFrame({
         'hID': [101, 102, 103, 101, 102, 104, 105, 101],
         'dID': [10, 11, 12, 10, 11, 10, 12, 10],
         'uID': ['James', 'Henry', 'Abe', 'James', 'Henry', 'Brian', 'Claude', 'James'],
         'mID': ['A', 'B', 'A', 'B', 'A', 'A', 'A', 'C']
})

I can do count(distinct hID) in Qlik to come up with count of 5 for unique hID.  How do I do that in python using a pandas dataframe?  Or maybe a numpy array?  Similarly, if were to do count(hID) I will get 8 in Qlik.  What is the equivalent way to do it in pandas?


问:
How to change a connection to GitHub from SSH to HTTPS?
I created my first repository in GitHub yesterday. When making the connection I used SSH instead of HTTPS, so I went through a little painful SSH key creation and connection process. At some point I got stuck and the connection failed. I wondered at that moment how I could revert the process I started and begin with a HTTPS connection instead. Happily, today I got the connection working through SSH but I'm wondering about the value of being able to change the type of connection (SSH vs HTTPS) and if there is a way to do it.</p>

答:
So guys I struggled with this problem for a while but finally got how to solve it.
First make sure you have updated your git to the latest version using:

C:\> git update-git-for-windows

Afterwards run the command:

C:\>git config --global url."https://github.com/".insteadOf git@github.com:

Then:

C:\>git config --global url."https://".insteadOf git://

If you still get the Permission denied (publickey) error you can do the process manually as follows:

Navigate to your .gitconfig file.

You can check for its location using:

git config --list --show-origin

Open the file using notepad.

Delete this section:

```<code>[url "git://"]
    insteadOf = https://
[url "insteadOf = git@github.com:"]
    insteadOf = https://github.com/

</code>```

Replace with:

```<code>[url "https://"]
    insteadOf = git://
[url "https://github.com/"]
    insteadOf = git@github.com:
</code>```

After this you should be able to log in using your Personal Access token successfully.

Body:
So guys I struggled with this problem for a while but finally got how to solve it.
First make sure you have updated your git to the latest version using:

C:\> git update-git-for-windows

Afterwards run the command:

C:\>git config --global url."https://github.com/".insteadOf git@github.com:

Then:

C:\>git config --global url."https://".insteadOf git://

If you still get the Permission denied (publickey) error you can do the process manually as follows:

Navigate to your .gitconfig file.

You can check for its location using:

git config --list --show-origin

Open the file using notepad.

Delete this section:

[url "git://"]
    insteadOf = https://
[url "insteadOf = git@github.com:"]
    insteadOf = https://github.com/

Replace with:

[url "https://"]
    insteadOf = git://
[url "https://github.com/"]
    insteadOf = git@github.com:

After this you should be able to log in using your Personal Access token successfully.


问:
AJAX - Update div content - Going backwards?
A current web based tool is template driven, rendering HTML and serving it a page at a time. I've been experimenting with using more modern tools such as ajax to load page contents, purely what changes between pages.

One problem I've discovered in testing is that if I a 'back' link (which calls JavaScript:history.go(-1); ) as with out current tool it doesn't work. In our previous system such links take you to the previous page (where one existed).

In the test system I'm updating div content using jQuerys ajax.

Does anyone have a strategy for working around this with dynamic content, providing a link which takes you back one step in a hierarchy?

答:
I've struggled with this problem many times, there are all sorts of solutions that recommend manipulating browser history and intercepting back clicks from the browser etc.

The short of it is that you use page parameters to control the content rendered on a page, however changing the address bar values will reload the page, so how does this work? Simple, you can change any value after a # and the browser will not reload the page. Then your javascript simply reads the value after the # to determine the content of the page.
Here is a good article on it..

I wondered how gmail did it and analyzing their page it seems that they use a lot of iframes. The advantage of iframes is that they can give your site an ajax look and feel without really being as such and I believe hitting back on a browser simply hits back on the iframe. It's been a while since I did something like this so can't be 100% sure.

I hope this helps. No one person here will be able to give you a 100% working solution (to the best of my knowledge) the nature of ajax applications is such that the solution has to be custom as well.


问:
Toggle element data for element that I click on, not all elements
I want to toggle data for specific element I click on. Whenever I try to display element data then all items are toggling which I do not want. How can I only toggle the item I click on?

export default function App() {
  const [post, setPosts] = useState([]);
  const [name, setName ] = useState('');
  const [displayId, setDisplayId] = useState(false);
  const getPosts = () => {
    fetch("https://jsonplaceholder.typicode.com/posts")
      .then((res) => res.json())
      .then((res) => {
        setPosts(res);
      });
  };

  useEffect(() => {
    getPosts();
  }, []);

  useEffect(() => {
    console.log(name);
  }, [name]);

  return (

Hello CodeSandbox

      <input type="text" value={name} onChange={(e) => setName(e.target.value)} />
      {post.map((item) => (

{item.title}

        <button onClick={() => setDisplayId(el => el = !el)}>Show ID</button>
        { displayId &&

{item.id}

        }

      ))}

Start editing to see some magic happezn!

  );
}
```

答:
You want to be able to show or hide each item of the array separately, so your state should reflect that - it should contain a value for each element of the array, instead of having just a single displayId boolean.

```<code>const [displayToggles, setDisplayToggles] = useState([]);
const getPosts = () => {
  fetch("https://jsonplaceholder.typicode.com/posts")
    .then((res) => res.json())
    .then((res) => {
      setPosts(res);
      setDisplayToggles(res.map(() => false));
    });
};

// ...
{post.map((item, i) => (
    <div key={item.id}>
    <p>{item.title}</p>
    <button
        onClick={() => setDisplayToggles(displayToggles.map((bool, j) => j === i ? !bool : bool))}
    >Show ID</button>
    { displayToggles[i] &&
</code>```

Also

```<code>useEffect(() => {
  getPosts();
}, []);
</code>```

simplifies to

```<code>useEffect(getPosts, []);
</code>```

function App() {
  const [post, setPosts] = React.useState([]);
  const [name, setName ] = React.useState('');
const [displayToggles, setDisplayToggles] = React.useState([]);
React.useEffect(() => {
  fetch("https://jsonplaceholder.typicode.com/posts")
    .then((res) => res.json())
    .then((res) => {
      setPosts(res);
      setDisplayToggles(res.map(() => false));
    });
}, []);

  return post.map((item, i) => (

{item.title}

    <button
        onClick={() => setDisplayToggles(displayToggles.map((bool, j) => j === i ? !bool : bool))}
    >Show ID</button>
    { displayToggles[i] &&

{item.id}

        }

        ));
}

ReactDOM.render(<App />, document.querySelector('.react'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div></code>```

Body:
You want to be able to show or hide each item of the array separately, so your state should reflect that - it should contain a value for each element of the array, instead of having just a single displayId boolean.

const [displayToggles, setDisplayToggles] = useState([]);
const getPosts = () => {
  fetch("https://jsonplaceholder.typicode.com/posts")
    .then((res) => res.json())
    .then((res) => {
      setPosts(res);
      setDisplayToggles(res.map(() => false));
    });
};

// ...
{post.map((item, i) => (
    <div key={item.id}>
    <p>{item.title}</p>
    <button
        onClick={() => setDisplayToggles(displayToggles.map((bool, j) => j === i ? !bool : bool))}
    >Show ID</button>
    { displayToggles[i] &&

Also

useEffect(() => {
  getPosts();
}, []);

simplifies to

useEffect(getPosts, []);

function App() {
  const [post, setPosts] = React.useState([]);
  const [name, setName ] = React.useState('');
const [displayToggles, setDisplayToggles] = React.useState([]);
React.useEffect(() => {
  fetch("https://jsonplaceholder.typicode.com/posts")
    .then((res) => res.json())
    .then((res) => {
      setPosts(res);
      setDisplayToggles(res.map(() => false));
    });
}, []);

  return post.map((item, i) => (
        <div key={item.id}>
        <p>{item.title}</p>
    <button
        onClick={() => setDisplayToggles(displayToggles.map((bool, j) => j === i ? !bool : bool))}
    >Show ID</button>
    { displayToggles[i] &&
          <p>{item.id}</p>
        }
        </div>
        ));
}

ReactDOM.render(<App />, document.querySelector('.react'));

<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>


问:
how to migrate clustered rds(postgres) to different account?
I am migrating from AccountA(source) to AccountB(Target), same region.
I ran templates so AccountB already has a RDS cluster but with no data. The db instance id is exactly same as what I have on the sourcing account.

**My goal is to have the same endpoint as before since we're retiring AccountA completely and I don't want to change codes side for the updated endpoint. **

I took a snapshot of the cluster(writer instance) then copy snapshot with a KMS key, shared it with AccountB. All good.  Now, from the AccountB(target), copied snapshot and attempted to restore. I thought I could restore directly into the RDS cluster but I see that's not doable with restore as it always creates a new instance.

Then, I renamed the existing empty RDS cluster to something else to free up the DB instance ID, then renamed the temp cluster to the same name. It worked but this seems not efficient.

What's is the best practice for the RDS data migration ?

Clustered RDS ( writer - reader ) and Cross Account

I didn't create a snapshot for Reader. Will it be synced from the writer automatically once I restore?

答:
Your experience is correct -- RDS Snapshots are restored as a new RDS instance (rather than loading data into an existing instance).

By "endpoint", if you are referring to the DNS Name used to connect to the database, then the new database will not have the same endpoint. If you want to preserve an endpoint, then you can create a DNS Name with a CNAME record that resolves to the DNS Name of the database. That way, you can change the CNAME record to point to a different endpoint without needing to change the code. (However, you probably haven't done this, so you'll need to change the code to point to the new DNS Name anyway, so it's the same amount of work.)

You are correct that you do not need to snapshot/copy the Readers -- you can simply create them from the new database. You will need to 'create' the Readers on the new database after the restore, since the Snapshot simply contains data for the main database.