问:
How can I insert a '-' in my string?
I have a string that can look like this: 12345, this 123456 or this: 1234567.

I'd like to make each string look like this: 123-45, this: 1234-56 or this: 12345-67.

How can I do this in C#?

答:
```<code>string myString = "1234567";
if(myString.Length > 1)
   string dashed = myString.Insert(myString.Length - 2, "-");
</code>```

EDIT: Added check based on comment, but depends on how such strings should be handled. (e.g. dashed even if length = 2?)

Title: How can I insert a '-' in my string?

Body:
string myString = "1234567";
if(myString.Length > 1)
   string dashed = myString.Insert(myString.Length - 2, "-");

EDIT: Added check based on comment, but depends on how such strings should be handled. (e.g. dashed even if length = 2?)


来源: stackexchange

问:
Fastest component that works with NSAttributedString?
Looks like NSTextField is too slow for work with large attributed texts.

1000 rows with 18 symbols each are slow on M1 processor;

3000 rows slow on macbook pro 2015

Is there exist some component that works fast enough with NSAttributedString?

I need component that will be:

Fast

Ability to select/copy text

Works with NSAttributedString

PS: SwiftUI's Text with AttributedString is much slower than NSTextField with NSAttributedString

Application for testing performance of NSTextField

```<code>@main
struct TestAppApp: App {
    var body: some Scene {
        WindowGroup {
            AttrTest()
        }
    }
}

struct AttrTest: View {
    @State var nsString: NSAttributedString = generateText(rows: 1000)
    var body: some View{
        VStack {
            HStack{
                Button("1000") {
                    nsString = generateText(rows: 1000)
                }
                Button("2000") {
                    nsString = generateText(rows: 2000)
                }
                Button("5000") {
                    nsString = generateText(rows: 5000)
                }
                Button("7000") {
                    nsString = generateText(rows: 7000)
                }
                Button("9000") {
                    nsString = generateText(rows: 9000)
                }
            }
            TabView {
                VStack{
                    AttributedText(attributedString: $nsString, selectable: false)
                }
                .tabItem {
                    Text("NSTextField")
                }
                AttributedText(attributedString: $nsString, selectable: false)
                    .padding(.leading, 80)
                    .background(Color.green)
                    .tabItem {
                        Text("Other")
                    }
            }
        }
    }
}

func generateText(rows: Int) -> NSMutableAttributedString {
    let attrs: [[NSAttributedString.Key : Any]] = [
        [.foregroundColor: NSColor.red],
        [.backgroundColor: NSColor.blue],
        [.strokeColor: NSColor.blue],
        [.strokeColor: NSColor.green],
        [.underlineColor: NSColor.green],
        [.underlineColor: NSColor.yellow],
        [.underlineColor: NSColor.gray],
        [.backgroundColor: NSColor.yellow],
        [.backgroundColor: NSColor.green],
        [.backgroundColor: NSColor.magenta]
    ]
    let str = NSMutableAttributedString(string: "")
    for _ in 0...rows {
        let strNew = NSMutableAttributedString(string: "fox jumps over the lazy dog\n")
        strNew.setAttributes(attrs.randomElement(), range: NSRange(location: 0, length: strNew.length) )
        str.append(strNew)
    }
    return str
}

@available(OSX 11.0, *)
public struct AttributedText: NSViewRepresentable {
    @Binding var text: NSAttributedString
    private let selectable: Bool
    public init(attributedString: Binding<NSAttributedString>, selectable: Bool = true) {
        _text = attributedString
        self.selectable = selectable
    }
    public func makeNSView(context: Context) -> NSTextField {
        let textField = NSTextField(labelWithAttributedString: text)
        textField.preferredMaxLayoutWidth = textField.frame.width
        textField.allowsEditingTextAttributes = true // Fix of clear of styles on click
        textField.isSelectable = selectable
        return textField
    }
    public func updateNSView(_ textField: NSTextField, context: Context) {
        textField.attributedStringValue = $text.wrappedValue
    }
}
</code>```

答: Typically large text is stored in an NSTextView, not an NSTextField. But for specialized uses, it's quite common to build your own solutions in Core Text.</p>

ContentLicense: CC BY-SA 4.0

Body:
Looks like NSTextField is too slow for work with large attributed texts.

1000 rows with 18 symbols each are slow on M1 processor;

3000 rows slow on macbook pro 2015

Is there exist some component that works fast enough with NSAttributedString?

I need component that will be:

Fast

Ability to select/copy text

Works with NSAttributedString

PS: SwiftUI's Text with AttributedString is much slower than NSTextField with NSAttributedString

Application for testing performance of NSTextField

@main
struct TestAppApp: App {
    var body: some Scene {
        WindowGroup {
            AttrTest()
        }
    }
}

struct AttrTest: View {
    @State var nsString: NSAttributedString = generateText(rows: 1000)
    var body: some View{
        VStack {
            HStack{
                Button("1000") {
                    nsString = generateText(rows: 1000)
                }
                Button("2000") {
                    nsString = generateText(rows: 2000)
                }
                Button("5000") {
                    nsString = generateText(rows: 5000)
                }
                Button("7000") {
                    nsString = generateText(rows: 7000)
                }
                Button("9000") {
                    nsString = generateText(rows: 9000)
                }
            }
            TabView {
                VStack{
                    AttributedText(attributedString: $nsString, selectable: false)
                }
                .tabItem {
                    Text("NSTextField")
                }
                AttributedText(attributedString: $nsString, selectable: false)
                    .padding(.leading, 80)
                    .background(Color.green)
                    .tabItem {
                        Text("Other")
                    }
            }
        }
    }
}

func generateText(rows: Int) -> NSMutableAttributedString {
    let attrs: [[NSAttributedString.Key : Any]] = [
        [.foregroundColor: NSColor.red],
        [.backgroundColor: NSColor.blue],
        [.strokeColor: NSColor.blue],
        [.strokeColor: NSColor.green],
        [.underlineColor: NSColor.green],
        [.underlineColor: NSColor.yellow],
        [.underlineColor: NSColor.gray],
        [.backgroundColor: NSColor.yellow],
        [.backgroundColor: NSColor.green],
        [.backgroundColor: NSColor.magenta]
    ]
    let str = NSMutableAttributedString(string: "")
    for _ in 0...rows {
        let strNew = NSMutableAttributedString(string: "fox jumps over the lazy dog\n")
        strNew.setAttributes(attrs.randomElement(), range: NSRange(location: 0, length: strNew.length) )
        str.append(strNew)
    }
    return str
}

@available(OSX 11.0, *)
public struct AttributedText: NSViewRepresentable {
    @Binding var text: NSAttributedString
    private let selectable: Bool
    public init(attributedString: Binding<NSAttributedString>, selectable: Bool = true) {
        _text = attributedString
        self.selectable = selectable
    }
    public func makeNSView(context: Context) -> NSTextField {
        let textField = NSTextField(labelWithAttributedString: text)
        textField.preferredMaxLayoutWidth = textField.frame.width
        textField.allowsEditingTextAttributes = true // Fix of clear of styles on click
        textField.isSelectable = selectable
        return textField
    }
    public func updateNSView(_ textField: NSTextField, context: Context) {
        textField.attributedStringValue = $text.wrappedValue
    }
}


问:
How to reload a page using puppeteer(if page doesn't load only)
Most of the time I launch my automated bot it stucks at the beginning due to network issues,so when I reload it,It works.I want my bot to do this if the page doesn't load</p>

答:
Your page request isn't responded or the response isn't success with status 200 OK.

So maybe you want to get the page requested again if the response isn't OK.

These below lines will try to reload the page until it's status is 200 OK.

```<code>const gotoHome = async () => {
    try {
        let response
        do {
            response = await page.goto('https://www.google.com', {
                timeout: 0,
                waitUntil: 'load'
            })
        } while (response.status() !== 200)
    } catch (error) {
        (async () => await bot.gotoHome())()
    }
}

</code>```

Please accept my answer as right if this help you.

Body:
Your page request isn't responded or the response isn't success with status 200 OK.

So maybe you want to get the page requested again if the response isn't OK.

These below lines will try to reload the page until it's status is 200 OK.

const gotoHome = async () => {
    try {
        let response
        do {
            response = await page.goto('https://www.google.com', {
                timeout: 0,
                waitUntil: 'load'
            })
        } while (response.status() !== 200)
    } catch (error) {
        (async () => await bot.gotoHome())()
    }
}

Please accept my answer as right if this help you.


问:
Cannot group data by a column in R
I want to get a count of how many times each Player's name appears in my data frame ph1. My code is showing how many times each name is in the dataset, but I cannot group it by nso I can see how many times each Player's name is in the dataset.

I would prefer a dplyr solution but am open to others.

For example:

```<code>n Number_Players
1  21
2  2
</code>```

Code

```<code>ph1 %>%
     filter(!is.na(Player)) %>%
     group_by(Player) %>%
     mutate(n= n()) %>%
     relocate(n, .after=Player)
</code>```

Sample of how my output is appearing

```<code>Player              n   Year    PA  AB
Peavy, Jake         1   2008    58  49
Gallardo, Yovani    1   2014    59  53
Stratton, Chris     1   2018    50  43
Cashner, Andrew     1   2015    61  60
Anderson, Chase     1   2016    52  45
Burnes, Corbin      1   2021    59  52
Wolf, Randy         1   2009    80  67
Davies, Zach        2   2016    61  53
Senzatela, Antonio  1   2021    51  39
Syndergaard, Noah   2   2015    50  43
</code>```

Sample data

```<code>structure(list(Player = c("Peavy, Jake", "Gallardo, Yovani",
"Stratton, Chris", "Cashner, Andrew", "Anderson, Chase", "Burnes, Corbin",
"Wolf, Randy", "Davies, Zach", "Senzatela, Antonio", "Syndergaard, Noah",
"Syndergaard, Noah", "Davies, Zach", "Sánchez, Aníbal", "Hudson, Dakota",
"Leake, Mike", "De La Rosa, Jorge", "Cueto, Johnny", "González, Gio",
"Peralta, Wily", "Vólquez, Edinson", "Ryu, Hyun Jin", "Dempster, Ryan",
"Holland, Derek", "Wheeler, Zack", "Sabathia, CC"), Year = c(2008,
2014, 2018, 2015, 2016, 2021, 2009, 2016, 2021, 2015, 2016, 2019,
2019, 2019, 2016, 2015, 2008, 2015, 2014, 2014, 2014, 2009, 2018,
2014, 2008), PA = c(58, 59, 50, 61, 52, 59, 80, 61, 51, 50, 67,
54, 56, 59, 55, 50, 56, 56, 68, 64, 56, 75, 56, 62, 50), AB = c(49,
53, 43, 60, 45, 52, 67, 53, 39, 43, 58, 51, 52, 51, 49, 48, 45,
43, 57, 53, 47, 64, 53, 50, 48)), row.names = c(NA, -25L), class = c("tbl_df",
"tbl", "data.frame"))
</code>```

I checked the existing stackoverflow solutions, but did not see one that matches my need. If one exists, I would appreciate it if you could provide its link.

答:
Here is another dplyr way:

First we use add_count to add the count as a new column,
then we have to consider the duplets with distinct
and finally we can apply count on n (that was generated by add_count)

```<code>ph1 %>%
  add_count(Player) %>%
  distinct(Player, .keep_all = TRUE) %>%
  count(n, name= "Number_Players")
</code>```
```<code>      n Number_Players
  <int>          <int>
1     1             21
2     2              2
</code>```

Title: Cannot group data by a column in R

Body:
I want to get a count of how many times each Player's name appears in my data frame ph1. My code is showing how many times each name is in the dataset, but I cannot group it by nso I can see how many times each Player's name is in the dataset.

I would prefer a dplyr solution but am open to others.

For example:

n Number_Players
1  21
2  2

Code

ph1 %>%
     filter(!is.na(Player)) %>%
     group_by(Player) %>%
     mutate(n= n()) %>%
     relocate(n, .after=Player)

Sample of how my output is appearing

Player              n   Year    PA  AB
Peavy, Jake         1   2008    58  49
Gallardo, Yovani    1   2014    59  53
Stratton, Chris     1   2018    50  43
Cashner, Andrew     1   2015    61  60
Anderson, Chase     1   2016    52  45
Burnes, Corbin      1   2021    59  52
Wolf, Randy         1   2009    80  67
Davies, Zach        2   2016    61  53
Senzatela, Antonio  1   2021    51  39
Syndergaard, Noah   2   2015    50  43

Sample data

structure(list(Player = c("Peavy, Jake", "Gallardo, Yovani",
"Stratton, Chris", "Cashner, Andrew", "Anderson, Chase", "Burnes, Corbin",
"Wolf, Randy", "Davies, Zach", "Senzatela, Antonio", "Syndergaard, Noah",
"Syndergaard, Noah", "Davies, Zach", "Sánchez, Aníbal", "Hudson, Dakota",
"Leake, Mike", "De La Rosa, Jorge", "Cueto, Johnny", "González, Gio",
"Peralta, Wily", "Vólquez, Edinson", "Ryu, Hyun Jin", "Dempster, Ryan",
"Holland, Derek", "Wheeler, Zack", "Sabathia, CC"), Year = c(2008,
2014, 2018, 2015, 2016, 2021, 2009, 2016, 2021, 2015, 2016, 2019,
2019, 2019, 2016, 2015, 2008, 2015, 2014, 2014, 2014, 2009, 2018,
2014, 2008), PA = c(58, 59, 50, 61, 52, 59, 80, 61, 51, 50, 67,
54, 56, 59, 55, 50, 56, 56, 68, 64, 56, 75, 56, 62, 50), AB = c(49,
53, 43, 60, 45, 52, 67, 53, 39, 43, 58, 51, 52, 51, 49, 48, 45,
43, 57, 53, 47, 64, 53, 50, 48)), row.names = c(NA, -25L), class = c("tbl_df",
"tbl", "data.frame"))

I checked the existing stackoverflow solutions, but did not see one that matches my need. If one exists, I would appreciate it if you could provide its link.

Body:
Here is another dplyr way:

First we use add_count to add the count as a new column,
then we have to consider the duplets with distinct
and finally we can apply count on n (that was generated by add_count)

ph1 %>%
  add_count(Player) %>%
  distinct(Player, .keep_all = TRUE) %>%
  count(n, name= "Number_Players")

      n Number_Players
  <int>          <int>
1     1             21
2     2              2


问:
How do get SIM slot index of inbox SMS in android by ContentProvider?
I am developing an app which dials some USSD and waits for SMS related to them. It uses both SIM slots in a dual-SIM phone. I need to identify which SIM (e.g. slot index) received a particular SMS. I can get it when received SMS using BroadcastReceiver. But in case I miss some broadcasts (e.g. user uninstalled the app -> SMS received -> app re-installed. In this scenario I must recheck messages after every start-up of my application process.

I am reading SMS using ContentProvider:

```<code>val cursor = resolver.query(Uri.parse("content://sms/inbox"), null, null, null, null)
</code>```

In android docs, there is a column named sub_id (i.e. Telephony.TextBasedSmsColumns.SUBSCRIPTION_ID). But I cannot obtain that column from my testing device Xiaomi Redmi 5 Plus, MIUI Global 11.0.2, Android 8.1.0. It throws exception when I try to get that column using cursor.getString(c.getColumnIndexOrThrow(Telephony.TextBasedSmsColumns.SUBSCRIPTION_ID)) saying that only available columns are: [_id, thread_id, address, person, date, date_sent, protocol, read, status, type, reply_path_present, subject, body, service_center, locked, error_code, seen, timed, deleted, sync_state, marker, source, bind_id, mx_status, mx_id, mx_id_v2, out_time, account, sim_id, block_type, advanced_seen, b2c_ttl, b2c_numbers, fake_cell_type, url_risky_type, creator, favorite_date].

EDIT: Note that sim_id gives me larger values like 11, 13, 14 etc. I cannot map them to sim slots anyway.

答:
I got it finally, sim_id is equivalent to the documented sub_id column. Therefore, we need to be careful when using android Telephony API.

```<code>fun findSlotFromSubId(sm: SubscriptionManager, subId: Int): Int {
    try {
        for (s in sm.activeSubscriptionInfoList) {
            if (s.subscriptionId == subId) {
                return s.simSlotIndex
            }
        }
    } catch (e: SecurityException) {
        e.printStackTrace()
    }
    return -1
}
</code>```

Body:
I am developing an app which dials some USSD and waits for SMS related to them. It uses both SIM slots in a dual-SIM phone. I need to identify which SIM (e.g. slot index) received a particular SMS. I can get it when received SMS using BroadcastReceiver. But in case I miss some broadcasts (e.g. user uninstalled the app -> SMS received -> app re-installed. In this scenario I must recheck messages after every start-up of my application process.

I am reading SMS using ContentProvider:

val cursor = resolver.query(Uri.parse("content://sms/inbox"), null, null, null, null)

In android docs, there is a column named sub_id (i.e. Telephony.TextBasedSmsColumns.SUBSCRIPTION_ID). But I cannot obtain that column from my testing device Xiaomi Redmi 5 Plus, MIUI Global 11.0.2, Android 8.1.0. It throws exception when I try to get that column using cursor.getString(c.getColumnIndexOrThrow(Telephony.TextBasedSmsColumns.SUBSCRIPTION_ID)) saying that only available columns are: [_id, thread_id, address, person, date, date_sent, protocol, read, status, type, reply_path_present, subject, body, service_center, locked, error_code, seen, timed, deleted, sync_state, marker, source, bind_id, mx_status, mx_id, mx_id_v2, out_time, account, sim_id, block_type, advanced_seen, b2c_ttl, b2c_numbers, fake_cell_type, url_risky_type, creator, favorite_date].

EDIT: Note that sim_id gives me larger values like 11, 13, 14 etc. I cannot map them to sim slots anyway.

Body:
I got it finally, sim_id is equivalent to the documented sub_id column. Therefore, we need to be careful when using android Telephony API.

fun findSlotFromSubId(sm: SubscriptionManager, subId: Int): Int {
    try {
        for (s in sm.activeSubscriptionInfoList) {
            if (s.subscriptionId == subId) {
                return s.simSlotIndex
            }
        }
    } catch (e: SecurityException) {
        e.printStackTrace()
    }
    return -1
}


问:
Extract specific columns and rows from an R dataset creating a new excell file
I'm writing the thesis for my master's degree I should create time series from the covid data of my country, Italy. The data is taken from here:
dataset italy
'https://raw.githubusercontent.com/pcm-dpc/COVID-19/master/dati-regioni/dpc-covid19-ita-regioni.csv" from this dataset I would like to have a new excel file that contains only the columns with the date, the denomination of the region, and the total number of deaths. From here I then go on to create the time series for every single Italian region. I hope I explained myself well, thank you very much for your help.
the program used R studio</p>

答:
How about something like this?</p>
```<code>#Import file
csv <- read.csv("dpc-covid19-ita-regioni.csv")

#Subset for three columns of interest and save to new object
csv2 <- csv[,c("data", "denominazione_regione", "deceduti")]

#Save to new Excel file
library(openxlsx)
write.xlsx(csv2, 'name-of-your-excel-file.xlsx')
</code>```

Body:
How about something like this?

#Import file
csv <- read.csv("dpc-covid19-ita-regioni.csv")

#Subset for three columns of interest and save to new object
csv2 <- csv[,c("data", "denominazione_regione", "deceduti")]

#Save to new Excel file
library(openxlsx)
write.xlsx(csv2, 'name-of-your-excel-file.xlsx')


问:
What is the most elegant way to encode/decode an Object to Dictionary
The object in question consists of key/value pairs aka @property. Is there an elegant way to encode/decode this object to a dictionary? It seems brute force to manually pull out each attribute and create the dictionary by hand. </p>

答:
Objective-C's "object as dictionary" support comes through Key-Value Coding:</p>

```<code>NSArray *myAttributes; // Assume this exists
NSDictionary *dictRepresentation = [object dictionaryWithValuesForKeys:myAttributes];
</code>```

OwnerDisplayName: Keith Fitzgerald

ContentLicense: CC BY-SA 2.5

Body:
Objective-C's "object as dictionary" support comes through Key-Value Coding:

NSArray *myAttributes; // Assume this exists
NSDictionary *dictRepresentation = [object dictionaryWithValuesForKeys:myAttributes];

OwnerDisplayName: Chuck


问:
React-sortable-hoc transition doesnt work
I made a sortable list using react-sortable-hoc. My problem is that there is no transition. I tried to use transitionDuration, but it still doesnt work. Here is sandbox with problem:
https://codesandbox.io/s/stoic-hill-lulln?file=/src/App.js</p>

答:
try wrapping your SortableItem in List</p>
```<code>    const SortableItem = sortableElement(({ value, index }) => (
    <li style={{"listStyleType":'none'}}>
    << YOUR CODE HERE>>
    </li>
  ));
</code>```

Body:
try wrapping your SortableItem in List

    const SortableItem = sortableElement(({ value, index }) => (
    <li style={{"listStyleType":'none'}}>
    << YOUR CODE HERE>>
    </li>
  ));


问:
Debug Manim community in PyCharm
Is there any way to debug a Manim community python script within PyCharm?

I found this discussion for Manim 3b1b version but it doesn't apply to Manim community and I prefer to use the community version as it seems to be better documented.

答:
Whenever I am debugging the library, I avoid using the CLI and render scenes directly from the file. Just add a snippet like this:

```<code>with tempconfig({"quality": "medium_quality"}):
    scene = YourSceneClass()
    scene.render()
</code>```

And then the script can be run with the default Python debugger in PyCharm (at least that's how it is for me in VS Code).

Title: Debug Manim community in PyCharm

Body:
Whenever I am debugging the library, I avoid using the CLI and render scenes directly from the file. Just add a snippet like this:

with tempconfig({"quality": "medium_quality"}):
    scene = YourSceneClass()
    scene.render()

And then the script can be run with the default Python debugger in PyCharm (at least that's how it is for me in VS Code).


问:
QThread crash when show QMessageBox PyQt5 Python
I'm trying to show MessageBox in QThread, but the program always crash after close the MessageBox. I tried to find answer about "create QThread" and "create QMessageBox in another thread", but none of these solved my problem, and some answers are for PyQt4.

The whole code is from a simple tutorial : https://realpython.com/python-pyqt-qthread/

I only insert some code under function reportProgress to raise an error and show a messagebox.

Please teach me how to code the messagebox part, I already tried to solve this for days, really appreciate.

```<code># Code from: https://realpython.com/python-pyqt-qthread/
import sys
from time import sleep
from PyQt5.QtCore import QObject, QThread, pyqtSignal
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (
    QApplication,
    QLabel,
    QMainWindow,
    QPushButton,
    QVBoxLayout,
    QWidget,
    QMessageBox,
)

# Step 1: Create a worker class
class Worker(QObject):
    finished = pyqtSignal()
    progress = pyqtSignal(int)

    def run(self):
        """Long-running task."""
        for i in range(5):
            sleep(1)
            self.progress.emit(i + 1)
        self.finished.emit()

class Window(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.clicksCount = 0
        self.setupUi()

    def setupUi(self):
        self.setWindowTitle("Freezing GUI")
        self.resize(300, 150)
        self.centralWidget = QWidget()
        self.setCentralWidget(self.centralWidget)
        # Create and connect widgets
        self.clicksLabel = QLabel("Counting: 0 clicks", self)
        self.clicksLabel.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        self.stepLabel = QLabel("Long-Running Step: 0")
        self.stepLabel.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        self.countBtn = QPushButton("Click me!", self)
        self.countBtn.clicked.connect(self.countClicks)
        self.longRunningBtn = QPushButton("Long-Running Task!", self)
        self.longRunningBtn.clicked.connect(self.runLongTask)
        # Set the layout
        layout = QVBoxLayout()
        layout.addWidget(self.clicksLabel)
        layout.addWidget(self.countBtn)
        layout.addStretch()
        layout.addWidget(self.stepLabel)
        layout.addWidget(self.longRunningBtn)
        self.centralWidget.setLayout(layout)

    def countClicks(self):
        self.clicksCount += 1
        self.clicksLabel.setText(f"Counting: {self.clicksCount} clicks")

    def reportProgress(self, n):
        self.stepLabel.setText(f"Long-Running Step: {n}")
        # I insert this, trying to show a messagebox when error occurs
        if n == 3:
            try:
                print(int('aaa'))
            except:
                QMessageBox.information(self, 'Warning', 'Success', QMessageBox.Ok)

    def runLongTask(self):
        # Step 2: Create a QThread object
        self.thread = QThread()
        # Step 3: Create a worker object
        self.worker = Worker()
        # Step 4: Move worker to the thread
        self.worker.moveToThread(self.thread)
        # Step 5: Connect signals and slots
        self.thread.started.connect(self.worker.run)
        self.worker.finished.connect(self.thread.quit)
        self.worker.finished.connect(self.worker.deleteLater)
        self.thread.finished.connect(self.thread.deleteLater)

        self.worker.progress.connect(self.reportProgress)
        # Step 6: Start the thread
        self.thread.start()

        # Final resets
        self.longRunningBtn.setEnabled(False)
        self.thread.finished.connect(
            lambda: self.longRunningBtn.setEnabled(True)
        )
        self.thread.finished.connect(
            lambda: self.stepLabel.setText("Long-Running Step: 0")
        )

app = QApplication(sys.argv)
win = Window()
win.show()
sys.exit(app.exec_())
</code>```

答: The code works as-is for me, no crashing. It could be a problem with the version of python you are running or the version of PyQt5 you have installed - I suggest updating everything.</p>

Body:
I'm trying to show MessageBox in QThread, but the program always crash after close the MessageBox. I tried to find answer about "create QThread" and "create QMessageBox in another thread", but none of these solved my problem, and some answers are for PyQt4.

The whole code is from a simple tutorial : https://realpython.com/python-pyqt-qthread/

I only insert some code under function reportProgress to raise an error and show a messagebox.

Please teach me how to code the messagebox part, I already tried to solve this for days, really appreciate.

# Code from: https://realpython.com/python-pyqt-qthread/
import sys
from time import sleep
from PyQt5.QtCore import QObject, QThread, pyqtSignal
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (
    QApplication,
    QLabel,
    QMainWindow,
    QPushButton,
    QVBoxLayout,
    QWidget,
    QMessageBox,
)

# Step 1: Create a worker class
class Worker(QObject):
    finished = pyqtSignal()
    progress = pyqtSignal(int)

    def run(self):
        """Long-running task."""
        for i in range(5):
            sleep(1)
            self.progress.emit(i + 1)
        self.finished.emit()

class Window(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.clicksCount = 0
        self.setupUi()

    def setupUi(self):
        self.setWindowTitle("Freezing GUI")
        self.resize(300, 150)
        self.centralWidget = QWidget()
        self.setCentralWidget(self.centralWidget)
        # Create and connect widgets
        self.clicksLabel = QLabel("Counting: 0 clicks", self)
        self.clicksLabel.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        self.stepLabel = QLabel("Long-Running Step: 0")
        self.stepLabel.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        self.countBtn = QPushButton("Click me!", self)
        self.countBtn.clicked.connect(self.countClicks)
        self.longRunningBtn = QPushButton("Long-Running Task!", self)
        self.longRunningBtn.clicked.connect(self.runLongTask)
        # Set the layout
        layout = QVBoxLayout()
        layout.addWidget(self.clicksLabel)
        layout.addWidget(self.countBtn)
        layout.addStretch()
        layout.addWidget(self.stepLabel)
        layout.addWidget(self.longRunningBtn)
        self.centralWidget.setLayout(layout)

    def countClicks(self):
        self.clicksCount += 1
        self.clicksLabel.setText(f"Counting: {self.clicksCount} clicks")

    def reportProgress(self, n):
        self.stepLabel.setText(f"Long-Running Step: {n}")
        # I insert this, trying to show a messagebox when error occurs
        if n == 3:
            try:
                print(int('aaa'))
            except:
                QMessageBox.information(self, 'Warning', 'Success', QMessageBox.Ok)

    def runLongTask(self):
        # Step 2: Create a QThread object
        self.thread = QThread()
        # Step 3: Create a worker object
        self.worker = Worker()
        # Step 4: Move worker to the thread
        self.worker.moveToThread(self.thread)
        # Step 5: Connect signals and slots
        self.thread.started.connect(self.worker.run)
        self.worker.finished.connect(self.thread.quit)
        self.worker.finished.connect(self.worker.deleteLater)
        self.thread.finished.connect(self.thread.deleteLater)

        self.worker.progress.connect(self.reportProgress)
        # Step 6: Start the thread
        self.thread.start()

        # Final resets
        self.longRunningBtn.setEnabled(False)
        self.thread.finished.connect(
            lambda: self.longRunningBtn.setEnabled(True)
        )
        self.thread.finished.connect(
            lambda: self.stepLabel.setText("Long-Running Step: 0")
        )

app = QApplication(sys.argv)
win = Window()
win.show()
sys.exit(app.exec_())


问:
Labeling stack local variables (asm)
In an ASM function, one can use the stack to create a local workspace for variables.

What I am wondering is, can you create labels to reference them vs using an explicit numeric offset from the stack pointer?

Ex: one wants to ldr r0, sp+4 but use a symbol name instead? What is the correct way to do this? I can't imagine people remembering numeric offsets for everything.

答:
I can't imagine people remembering numeric offsets for everything.

All assemblers allow using labels for global variables, and in part for this reason, global variables are commonly used in assembly coursework programming where named local variables would have been used in high-level languages.

Also because global variables are allocated and initialized using relatively simple data declarations, whereas using stack storage for local variables requires dynamic allocation, initialization and deallocation, and then of course, offsets relative to the stack pointer rather than absolute addressing via named labels.  While we tend to frown on global variables in general programming, many toy/assignment programs have only a main and few or no functions, so global storage is actually reasonable there.

Many local variables and parameters get mapped to registers on most modern machines.  It is necessary to identify registers to use for variables, temps, and parameter passing, and using some kind of #define or equate often makes that harder rather than easier.  Many programmers prefer to describe variables and their mappings in comments instead of using macros or equates.

Memory is the last resort for mappings of scalar variables, as registers are preferred.  These days, we do the smallest necessary amount in assembly (sometimes none at all).  And as already noted, we can substitute global variables for local variables when writing toy programs.  Among these reasons, using offsets doesn't really hurt as much as you'd think.

There's also reasons that the mappings for a given local variable changes during the progression the function it is in, so have to be adjusted for the situation (e.g. sometimes a parameter moves to another register for reasons of the calling convention; other times from memory to a register for performance; if we don't want the overhead of a frame pointer, then a push will change offsets of things already on the stack).  Assembly language is so low level we often don't want to obscure detail.

Title: Labeling stack local variables (asm)


问:
Node async await function execution not in order
I'm confused. I'm new to async so I know I'm missing something fundamental but I'm scratching my head. From the examples I've seen, I thought I had this right but...

The below code works fine when mocked. However, when I fetch the real dashboard object from mongo I can see execution is not in order. Therefore the code that relies on there being a dashboard object fails due to it being 'undefined'.

Relevant code

```<code>router.get('/:id?', (req, res) => {
  getDashboardData(req)
})

async function getDashboardData(req) {
  const dashboardId = await getDashboardId(req)
  const dashboard = await loadDashboard(dashboardId)
  const results = await showResults(dashboardId, dashboard)
}

async function getDashboardId(req) {
  dashboardId = req.params.id.trim()
  // Some other things happen here but ultimately we return a UUID
  return(dashboardId)
}

async function loadDashboardFromId (dashboardId) {
  Dashboard.findOne({dashboardId: dashboardId}).then((dashboard) => {
    if (dashboard == null || dashboard.dashboardId == null) {
      throw new Error('No dashboard matched in loadDashboardFromId for dashbardId: ' + dashboardId)
    } else {
      console.log('dashboard within loadDashboardFromId: ' + dashboard)
      return dashboard
    }
  })
}

async function showResults(dashboardId, dashboard) {
  console.log("dashboardId: " + dashboardId)
  console.log("dashboard within showResults: " + dashboard)
}
</code>```

Console output below. You can see showResults() executes before loadDashboard() returns:

```<code>connected to mongo server.
open connection to mongo server.
dashboardId: dbc7e954-c6a7-490f-8d9b-4dd11f11d262
dashboard within showResults: undefined
dashboard within loadDashboardFromId: {
  _id: new ObjectId("6208f552a442468c65987e62"),
  dashboardId: 'dbc7e954-c6a7-490f-8d9b-4dd11f11d262',
  createdDate: 2022-02-13T00:00:00.000Z,
  surveyId: 'b55a58d6-63f1-473e-9a3c-34f5d63af499',
  participantId: '9b274cfe-68ea-4206-9f3c-f2ee309ec4de',
  personalityTotal: new Decimal128("69"),
 // etc }```
```

答:
You can use Promise ...
For More Documentation
https://www.newline.co/fullstack-react/30-days-of-react/day-15/

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve

```<code>  async function getDashboardData(req) {
    var dashboardId;
    var dashboard;
    var promise = new Promise(async function(resolve, reject) {
      dashboardId = await getDashboardId(req)
      dashboard = await loadDashboard(dashboardId)
      if(dashboardId && dashboard){
         resolve(true);
       }
      })
    const results = await showResults(dashboardId, dashboard)
   }
</code>```

Body:
I'm confused. I'm new to async so I know I'm missing something fundamental but I'm scratching my head. From the examples I've seen, I thought I had this right but...

The below code works fine when mocked. However, when I fetch the real dashboard object from mongo I can see execution is not in order. Therefore the code that relies on there being a dashboard object fails due to it being 'undefined'.

Relevant code

router.get('/:id?', (req, res) => {
  getDashboardData(req)
})

async function getDashboardData(req) {
  const dashboardId = await getDashboardId(req)
  const dashboard = await loadDashboard(dashboardId)
  const results = await showResults(dashboardId, dashboard)
}

async function getDashboardId(req) {
  dashboardId = req.params.id.trim()
  // Some other things happen here but ultimately we return a UUID
  return(dashboardId)
}

async function loadDashboardFromId (dashboardId) {
  Dashboard.findOne({dashboardId: dashboardId}).then((dashboard) => {
    if (dashboard == null || dashboard.dashboardId == null) {
      throw new Error('No dashboard matched in loadDashboardFromId for dashbardId: ' + dashboardId)
    } else {
      console.log('dashboard within loadDashboardFromId: ' + dashboard)
      return dashboard
    }
  })
}

async function showResults(dashboardId, dashboard) {
  console.log("dashboardId: " + dashboardId)
  console.log("dashboard within showResults: " + dashboard)
}

Console output below. You can see showResults() executes before loadDashboard() returns:

connected to mongo server.
open connection to mongo server.
dashboardId: dbc7e954-c6a7-490f-8d9b-4dd11f11d262
dashboard within showResults: undefined
dashboard within loadDashboardFromId: {
  _id: new ObjectId("6208f552a442468c65987e62"),
  dashboardId: 'dbc7e954-c6a7-490f-8d9b-4dd11f11d262',
  createdDate: 2022-02-13T00:00:00.000Z,
  surveyId: 'b55a58d6-63f1-473e-9a3c-34f5d63af499',
  participantId: '9b274cfe-68ea-4206-9f3c-f2ee309ec4de',
  personalityTotal: new Decimal128("69"),
 // etc }```

Body:
You can use Promise ...
For More Documentation
https://www.newline.co/fullstack-react/30-days-of-react/day-15/

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve

  async function getDashboardData(req) {
    var dashboardId;
    var dashboard;
    var promise = new Promise(async function(resolve, reject) {
      dashboardId = await getDashboardId(req)
      dashboard = await loadDashboard(dashboardId)
      if(dashboardId && dashboard){
         resolve(true);
       }
      })
    const results = await showResults(dashboardId, dashboard)
   }


问:
Find index of word in string
I want to write a function which will find index of word in string.
For example if string is

This is word.

my function for string "word" should return number 3.

Note: functions from string.h library and auxiliary strings are not allowed.

How could I do this in C?

答:
Here are steps to follow:

you must specify precisely what is a word in the string.

measure the length len of the word to search

define an int index = 1

in a loop, using a pointer p starting at the beginning of the string:

advance p past all word delimiters (spaces, punctuation or non letters?)

if p is at end of string return 0 (not found).

measure the length len1 of the current word in the string

if len1 == len and all bytes are identical to those of the word, return index

otherwise skip the word by advancing p by len1, increment index and continue the loop.

Here is an implementation:

```<code>#include <stddef.h>

int isletter(char c) {
    /* assuming ASCII */
    return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
}

int word_index(const char *str, const char *word) {
    const char *p = str;
    size_t len, len1, i;
    int index = 1;
    for (len = 0; word[len]; len++)
        continue;
    for (;;) {
        while (!is_letter(*p))
            p++;
        if (*p == '\0')
            return 0;
        for (len1 = 0; is_letter(p[len1]); len1++)
            continue;
        if (len1 == len) {
            for (i = 0; i < len && p[i] == word[i]; i++)
                continue;
            if (i == len)
                return index;
        }
        p += len1;
        index++;
    }
}
</code>```

Title: Find index of word in string

Body:
Here are steps to follow:

you must specify precisely what is a word in the string.

measure the length len of the word to search

define an int index = 1

in a loop, using a pointer p starting at the beginning of the string:

advance p past all word delimiters (spaces, punctuation or non letters?)

if p is at end of string return 0 (not found).

measure the length len1 of the current word in the string

if len1 == len and all bytes are identical to those of the word, return index

otherwise skip the word by advancing p by len1, increment index and continue the loop.

Here is an implementation:

#include <stddef.h>

int isletter(char c) {
    /* assuming ASCII */
    return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
}

int word_index(const char *str, const char *word) {
    const char *p = str;
    size_t len, len1, i;
    int index = 1;
    for (len = 0; word[len]; len++)
        continue;
    for (;;) {
        while (!is_letter(*p))
            p++;
        if (*p == '\0')
            return 0;
        for (len1 = 0; is_letter(p[len1]); len1++)
            continue;
        if (len1 == len) {
            for (i = 0; i < len && p[i] == word[i]; i++)
                continue;
            if (i == len)
                return index;
        }
        p += len1;
        index++;
    }
}


问:
how to coerce a data.frame into a sparse matrix in R
I am trying to follow the example here: cui2vecWorkflow by creating a matrix similar to the one here term_cooccurrence_matrix.rda that has the following properties:

```<code>> cooc<-get(load('~/development/cui2vec/vignettes/term_cooccurrence_matrix.rda'))
> str(cooc)
Formal class 'dsCMatrix' [package "Matrix"] with 7 slots
  ..@ i       : int [1:2366] 0 1 2 0 1 2 3 4 3 5 ...
  ..@ p       : int [1:101] 0 1 2 3 7 8 10 17 19 27 ...
  ..@ Dim     : int [1:2] 100 100
  ..@ Dimnames:List of 2
  .. ..$ : chr [1:100] "C0016875" "C0162770" "C0024730" "C0038689" ...
  .. ..$ : chr [1:100] "C0016875" "C0162770" "C0024730" "C0038689" ...
  ..@ x       : num [1:2366] 412 6286 8280 118 110 ...
  ..@ uplo    : chr "U"
  ..@ factors : list()
</code>```

The dataframe I have looks like:

```<code>> test
        CUI1     CUI2 Count
1   C0000699 C3894683     2
2   C0000699 C0101725     1
3   C0000699 C1882413     3
4   C0000699 C0245531     3
5   C0000699 C0068475     2
6   C0000699 C0538927     3
7   C0000699 C0724693     1
8   C0000699 C0216784     2
9   C0000699 C2248020     1
10  C0000699 C0069449     3
...
</code>```

but when I read it in and convert to a matrix it obviously won't be the same structure, as per

```<code>> mat <- as.matrix(test)
> str(mat)
 chr [1:1000000, 1:3] "C0000699" "C0000699" "C0000699" "C0000699" "C0000699" "C0000699" "C0000699" "C0000699" ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr [1:3] "CUI1" "CUI2" "Count"
</code>```

I then take the next step and coerce the matrix mat to a sparse matrix:

```<code>> mat <- as(mat,  "sparseMatrix")
> str(mat)
Formal class 'dgCMatrix' [package "Matrix"] with 6 slots
  ..@ i       : int [1:3000000] 0 1 2 3 4 5 6 7 8 9 ...
  ..@ p       : int [1:4] 0 1000000 2000000 3000000
  ..@ Dim     : int [1:2] 1000000 3
  ..@ Dimnames:List of 2
  .. ..$ : NULL
  .. ..$ : chr [1:3] "CUI1" "CUI2" "Count"
  ..@ x       : num [1:3000000] NA NA NA NA NA NA NA NA NA NA ...
  ..@ factors : list()
</code>```

but the structure looks wrong.

Trying this, I get an error:

```<code>> mat <- as(mat,  "dsCMatrix")
Error in asMethod(object) :
  not a symmetric matrix; consider forceSymmetric() or symmpart()
In addition: Warning message:
In storage.mode(from) <- "double" : NAs introduced by coercion
</code>```

So I try this:

```<code>> mat <- as(forceSymmetric(mat),  "dsCMatrix")
Error in forceSymmetric(mat) :
  invalid class 'NA' to dup_mMatrix_as_geMatrix
</code>```

(I haven't been able to find any examples for how to construct a matrix of the class structure("dsCMatrix", package = "Matrix") from a data.frame, so I am just winging it).

It looks like the Dim and Dimnames aren't defined properly, along with the value of x.

答:
Following user20650's comment, first coerce the CUI* columns to factor with the same levels, then use xtabs to create a sparse matrix, then add its transpose.

txt <- '
        CUI1     CUI2 Count
1   C0000699 C3894683     2
2   C0000699 C0101725     1
3   C0000699 C1882413     3
4   C0000699 C0245531     3
5   C0000699 C0068475     2
6   C0000699 C0538927     3
7   C0000699 C0724693     1
8   C0000699 C0216784     2
9   C0000699 C2248020     1
10  C0000699 C0069449     3
'
test <- read.table(textConnection(txt), header = TRUE)

library(Matrix)

levls <- Reduce(union, test[1:2])
test[1:2] <- lapply(test[1:2], factor, levels = levls)
res <- xtabs(Count ~ CUI1 + CUI2, data = test, sparse = TRUE)
res <- forceSymmetric(res)
class(res)
#> [1] "dsCMatrix"
#> attr(,"package")
#> [1] "Matrix"
```

Created on 2022-02-13 by the reprex package (v2.0.1)

Body:
I am trying to follow the example here: cui2vecWorkflow by creating a matrix similar to the one here term_cooccurrence_matrix.rda that has the following properties:

> cooc<-get(load('~/development/cui2vec/vignettes/term_cooccurrence_matrix.rda'))
> str(cooc)
Formal class 'dsCMatrix' [package "Matrix"] with 7 slots
  ..@ i       : int [1:2366] 0 1 2 0 1 2 3 4 3 5 ...
  ..@ p       : int [1:101] 0 1 2 3 7 8 10 17 19 27 ...
  ..@ Dim     : int [1:2] 100 100
  ..@ Dimnames:List of 2
  .. ..$ : chr [1:100] "C0016875" "C0162770" "C0024730" "C0038689" ...
  .. ..$ : chr [1:100] "C0016875" "C0162770" "C0024730" "C0038689" ...
  ..@ x       : num [1:2366] 412 6286 8280 118 110 ...
  ..@ uplo    : chr "U"
  ..@ factors : list()

The dataframe I have looks like:

> test
        CUI1     CUI2 Count
1   C0000699 C3894683     2
2   C0000699 C0101725     1
3   C0000699 C1882413     3
4   C0000699 C0245531     3
5   C0000699 C0068475     2
6   C0000699 C0538927     3
7   C0000699 C0724693     1
8   C0000699 C0216784     2
9   C0000699 C2248020     1
10  C0000699 C0069449     3
...

but when I read it in and convert to a matrix it obviously won't be the same structure, as per

> mat <- as.matrix(test)
> str(mat)
 chr [1:1000000, 1:3] "C0000699" "C0000699" "C0000699" "C0000699" "C0000699" "C0000699" "C0000699" "C0000699" ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr [1:3] "CUI1" "CUI2" "Count"

I then take the next step and coerce the matrix mat to a sparse matrix:

> mat <- as(mat,  "sparseMatrix")
> str(mat)
Formal class 'dgCMatrix' [package "Matrix"] with 6 slots
  ..@ i       : int [1:3000000] 0 1 2 3 4 5 6 7 8 9 ...
  ..@ p       : int [1:4] 0 1000000 2000000 3000000
  ..@ Dim     : int [1:2] 1000000 3
  ..@ Dimnames:List of 2
  .. ..$ : NULL
  .. ..$ : chr [1:3] "CUI1" "CUI2" "Count"
  ..@ x       : num [1:3000000] NA NA NA NA NA NA NA NA NA NA ...
  ..@ factors : list()

but the structure looks wrong.

Trying this, I get an error:

> mat <- as(mat,  "dsCMatrix")
Error in asMethod(object) :
  not a symmetric matrix; consider forceSymmetric() or symmpart()
In addition: Warning message:
In storage.mode(from) <- "double" : NAs introduced by coercion

So I try this:

> mat <- as(forceSymmetric(mat),  "dsCMatrix")
Error in forceSymmetric(mat) :
  invalid class 'NA' to dup_mMatrix_as_geMatrix

(I haven't been able to find any examples for how to construct a matrix of the class structure("dsCMatrix", package = "Matrix") from a data.frame, so I am just winging it).

It looks like the Dim and Dimnames aren't defined properly, along with the value of x.

Body:
Following user20650's comment, first coerce the CUI* columns to factor with the same levels, then use xtabs to create a sparse matrix, then add its transpose.

txt <- '
        CUI1     CUI2 Count
1   C0000699 C3894683     2
2   C0000699 C0101725     1
3   C0000699 C1882413     3
4   C0000699 C0245531     3
5   C0000699 C0068475     2
6   C0000699 C0538927     3
7   C0000699 C0724693     1
8   C0000699 C0216784     2
9   C0000699 C2248020     1
10  C0000699 C0069449     3
'
test <- read.table(textConnection(txt), header = TRUE)

library(Matrix)

levls <- Reduce(union, test[1:2])
test[1:2] <- lapply(test[1:2], factor, levels = levls)
res <- xtabs(Count ~ CUI1 + CUI2, data = test, sparse = TRUE)
res <- forceSymmetric(res)
class(res)
#> [1] "dsCMatrix"
#> attr(,"package")
#> [1] "Matrix"

Created on 2022-02-13 by the reprex package (v2.0.1)


问:
Clicking on part of an image
I'm sorry if this has been asked before, I tried to search and didn't find anything.

I am creating a C# WPF application.

I have an image, for example of a man.

Is there a way to detect which part of the man's body the mouse has clicked? for example if the mouse clicks his hand we get a message box : "You have clicked the hand"?

I would like to divide the into random shapes not just rectangles, so the mouse click have to be precise.

Thanks a lot for any help

答: If I were you, I'd create multiple polys over the top of the image and get it to the correct position/shape, then make them transparent and handle click events for each poly.</p>

ContentLicense: CC BY-SA 3.0

Title: Clicking on part of an image


问:
`Building wheel for opencv-python (PEP 517) ... -` runs forever
When I run

```<code>!pip install imgaug==0.4.0
</code>```

the following is the output

```<code>Collecting imgaug==0.4.0
  Using cached https://files.pythonhosted.org/packages/66/b1/af3142c4a85cba6da9f4ebb5ff4e21e2616309552caca5e8acefe9840622/imgaug-0.4.0-py2.py3-none-any.whl
Requirement already satisfied: Pillow in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from imgaug==0.4.0) (5.4.1)
Requirement already satisfied: numpy>=1.15 in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from imgaug==0.4.0) (1.15.4)
Collecting Shapely (from imgaug==0.4.0)
  Using cached https://files.pythonhosted.org/packages/9d/18/557d4f55453fe00f59807b111cc7b39ce53594e13ada88e16738fb4ff7fb/Shapely-1.7.1-cp36-cp36m-manylinux1_x86_64.whl
Requirement already satisfied: six in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from imgaug==0.4.0) (1.12.0)
Requirement already satisfied: matplotlib in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from imgaug==0.4.0) (3.0.2)
Collecting scikit-image>=0.14.2 (from imgaug==0.4.0)
  Using cached https://files.pythonhosted.org/packages/0e/ba/53e1bfbdfd0f94514d71502e3acea494a8b4b57c457adbc333ef386485da/scikit_image-0.17.2-cp36-cp36m-manylinux1_x86_64.whl
Requirement already satisfied: imageio in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from imgaug==0.4.0) (2.4.1)
Collecting opencv-python (from imgaug==0.4.0)
  Using cached https://files.pythonhosted.org/packages/77/f5/49f034f8d109efcf9b7e98fbc051878b83b2f02a1c73f92bbd37f317288e/opencv-python-4.4.0.42.tar.gz
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
    Preparing wheel metadata ... done
Requirement already satisfied: scipy in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from imgaug==0.4.0) (1.2.0)
Requirement already satisfied: cycler>=0.10 in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from matplotlib->imgaug==0.4.0) (0.10.0)
Requirement already satisfied: kiwisolver>=1.0.1 in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from matplotlib->imgaug==0.4.0) (1.0.1)
Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from matplotlib->imgaug==0.4.0) (2.3.1)
Requirement already satisfied: python-dateutil>=2.1 in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from matplotlib->imgaug==0.4.0) (2.7.5)
Collecting tifffile>=2019.7.26 (from scikit-image>=0.14.2->imgaug==0.4.0)
  Using cached https://files.pythonhosted.org/packages/3c/13/4f873f6b167c2e77288ce8db1c9f742d1e0e1463644e2df4e3bd3c40a422/tifffile-2020.8.25-py3-none-any.whl
Requirement already satisfied: networkx>=2.0 in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from scikit-image>=0.14.2->imgaug==0.4.0) (2.2)
Collecting PyWavelets>=1.1.1 (from scikit-image>=0.14.2->imgaug==0.4.0)
  Using cached https://files.pythonhosted.org/packages/59/bb/d2b85265ec9fa3c1922210c9393d4cdf7075cc87cce6fe671d7455f80fbc/PyWavelets-1.1.1-cp36-cp36m-manylinux1_x86_64.whl
Requirement already satisfied: setuptools in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from kiwisolver>=1.0.1->matplotlib->imgaug==0.4.0) (40.8.0)
Requirement already satisfied: decorator>=4.3.0 in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from networkx>=2.0->scikit-image>=0.14.2->imgaug==0.4.0) (4.3.2)
Building wheels for collected packages: opencv-python
  Building wheel for opencv-python (PEP 517) ... -
</code>```

But the Building wheel for opencv-python (PEP 517) ... - runs forever, how to resolve this problem?

答: If you are using Raspberry pi then use command pip install opencv-python==4.5.3.56 then update numpy using pip install -U numpy and then install package you need to install which has OpenCV dependency.

Body:
When I run

!pip install imgaug==0.4.0

the following is the output

Collecting imgaug==0.4.0
  Using cached https://files.pythonhosted.org/packages/66/b1/af3142c4a85cba6da9f4ebb5ff4e21e2616309552caca5e8acefe9840622/imgaug-0.4.0-py2.py3-none-any.whl
Requirement already satisfied: Pillow in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from imgaug==0.4.0) (5.4.1)
Requirement already satisfied: numpy>=1.15 in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from imgaug==0.4.0) (1.15.4)
Collecting Shapely (from imgaug==0.4.0)
  Using cached https://files.pythonhosted.org/packages/9d/18/557d4f55453fe00f59807b111cc7b39ce53594e13ada88e16738fb4ff7fb/Shapely-1.7.1-cp36-cp36m-manylinux1_x86_64.whl
Requirement already satisfied: six in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from imgaug==0.4.0) (1.12.0)
Requirement already satisfied: matplotlib in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from imgaug==0.4.0) (3.0.2)
Collecting scikit-image>=0.14.2 (from imgaug==0.4.0)
  Using cached https://files.pythonhosted.org/packages/0e/ba/53e1bfbdfd0f94514d71502e3acea494a8b4b57c457adbc333ef386485da/scikit_image-0.17.2-cp36-cp36m-manylinux1_x86_64.whl
Requirement already satisfied: imageio in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from imgaug==0.4.0) (2.4.1)
Collecting opencv-python (from imgaug==0.4.0)
  Using cached https://files.pythonhosted.org/packages/77/f5/49f034f8d109efcf9b7e98fbc051878b83b2f02a1c73f92bbd37f317288e/opencv-python-4.4.0.42.tar.gz
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
    Preparing wheel metadata ... done
Requirement already satisfied: scipy in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from imgaug==0.4.0) (1.2.0)
Requirement already satisfied: cycler>=0.10 in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from matplotlib->imgaug==0.4.0) (0.10.0)
Requirement already satisfied: kiwisolver>=1.0.1 in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from matplotlib->imgaug==0.4.0) (1.0.1)
Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from matplotlib->imgaug==0.4.0) (2.3.1)
Requirement already satisfied: python-dateutil>=2.1 in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from matplotlib->imgaug==0.4.0) (2.7.5)
Collecting tifffile>=2019.7.26 (from scikit-image>=0.14.2->imgaug==0.4.0)
  Using cached https://files.pythonhosted.org/packages/3c/13/4f873f6b167c2e77288ce8db1c9f742d1e0e1463644e2df4e3bd3c40a422/tifffile-2020.8.25-py3-none-any.whl
Requirement already satisfied: networkx>=2.0 in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from scikit-image>=0.14.2->imgaug==0.4.0) (2.2)
Collecting PyWavelets>=1.1.1 (from scikit-image>=0.14.2->imgaug==0.4.0)
  Using cached https://files.pythonhosted.org/packages/59/bb/d2b85265ec9fa3c1922210c9393d4cdf7075cc87cce6fe671d7455f80fbc/PyWavelets-1.1.1-cp36-cp36m-manylinux1_x86_64.whl
Requirement already satisfied: setuptools in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from kiwisolver>=1.0.1->matplotlib->imgaug==0.4.0) (40.8.0)
Requirement already satisfied: decorator>=4.3.0 in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from networkx>=2.0->scikit-image>=0.14.2->imgaug==0.4.0) (4.3.2)
Building wheels for collected packages: opencv-python
  Building wheel for opencv-python (PEP 517) ... -

But the Building wheel for opencv-python (PEP 517) ... - runs forever, how to resolve this problem?


问:
Anybody who succeeded in adding "Email Composer" Cordova plugin to Ionic 5 project (for Android12)?
I have created a simple Ionic 5 app and would like to add the functionality that would allow sending emails (including those scheduled).
I have tried the https://ionicframework.com/docs/native/email-composer but found myself stuck with this supporting Android 12. Is there anybody who succeeded?</p>

答: I am use Appery.io to do that, they are based on Cordova and I have no issues with their Ionic 5 app working on Android 12 devices.They offer https://docs.appery.io/docs/ionic-5-mailgun-email-sample-app-with-server-code-plugin, https://docs.appery.io/docs/ionic-5-sendgrid-email-sample-app-with-server-code-plugin.  They also offer to try bulk mailing using their SendGridEmail plugin: https://docs.appery.io/docs/using-sendgrid-plugin-for-bulk-mailing.</p>


问:
graphviz: change color of some nodes
I am using NetworkX to parse a graph and graphviz to represent that same graph as an svg file. I am trying to color each node of my graph based on the name of the node such as:

```<code>if node.name == 'abc':
  node.color = 'blue'
else:
  node.color = 'pink'
</code>```

I was able to color every node of my graph with the same color and I am not able to set conditions to have different node colors based on my previous algorithm.

Based on this StackOverflow post, Graphviz dot: How to change the colour of one record in multi-record shape, it is probably not possible. But it I look at the .dot output file, each node as a color attribute so it should be possible to change it?

graph.dot:

```<code>digraph "" {
    graph [bb="0,0,61610,509.51",
        edge_default="{}",
        edges="{'arrowsize': '4.0'}",
        node_default="{}",
        rankdir=TD
    ];
    node [fillcolor=red,
        label="\N",
        shape=rectangle,
        style=filled
    ];
    "gold_adhoc_demand_review.countries"    [color=red,
        height=0.5,
        kind=adhoc,
        pos="1010,234",
        table=countries,
        use_case=demand_review,
        width=3.1389,
        zone=gold];
    "gold_core.location"    [color=blue,
        height=0.5,
        kind=core,
        pos="868,306",
        table=location,
        width=1.6389,
        zone=gold];
    "gold_core.location" -> "gold_adhoc_demand_review.countries"    [pos="e,975.13,252.19 902.74,287.88 921.82,278.47 945.68,266.71 966.05,256.67"];
    "gold_adhoc_product_priorities.distribution_network"    [color=red,
        height=0.5,
        kind=adhoc,
        pos="150,234",
        table=distribution_network,
        use_case=product_priorities,
        width=4.1667,
        zone=gold];
    "gold_core.location" -> "gold_adhoc_product_priorities.distribution_network"    [pos="e,300.22,251.11 808.82,299.62 708.56,290.46 498.65,271.06 310.31,252.13"];
    "gold_adhoc_global_supply_review.country"   [color=red,
        height=0.5,
        kind=adhoc,
        pos="1267,234",
        table=country,
        use_case=global_supply_review,
        width=3.4861,
        zone=gold];
...
</code>```

draw.py

```<code>def draw_graph(networkx_graph):
    networkx_graph.graph['graph'] = {'rankdir': PYGRAPHIZ_RANKDIR}
    networkx_graph.graph['node'] = {'shape': PYGRAPHIZ_SHAPE_TYPE, 'fillcolor': 'red', 'style':'filled'}
    networkx_graph.graph['edges']={'arrowsize': PYGRAPHIZ_ARROW_SIZE}
    pygraphviz_graph = to_agraph(networkx_graph)
    pygraphviz_graph.layout("svg")
    pygraphviz_graph.draw("result.svg")
    print(pygraphviz_graph.graph_attr)
</code>```

答:
The property you want to update is fillcolor, not color. color controls the border of a node.

(See the documentation at https://graphviz.org/docs/attrs/fillcolor/)

Your logic would look like this to customize the fill color of individual nodes:

```<code>if node.name == 'abc':
  node.fillcolor = 'gold'
else:
  node.fillcolor = 'pink'
</code>```

Note: you can use RGB color codes rather than names to give you more options, e.g.: fillcolor = "#ffd700"

Title: graphviz: change color of some nodes

Body:
I am using NetworkX to parse a graph and graphviz to represent that same graph as an svg file. I am trying to color each node of my graph based on the name of the node such as:

if node.name == 'abc':
  node.color = 'blue'
else:
  node.color = 'pink'

I was able to color every node of my graph with the same color and I am not able to set conditions to have different node colors based on my previous algorithm.

Based on this StackOverflow post, Graphviz dot: How to change the colour of one record in multi-record shape, it is probably not possible. But it I look at the .dot output file, each node as a color attribute so it should be possible to change it?

graph.dot:

digraph "" {
    graph [bb="0,0,61610,509.51",
        edge_default="{}",
        edges="{'arrowsize': '4.0'}",
        node_default="{}",
        rankdir=TD
    ];
    node [fillcolor=red,
        label="\N",
        shape=rectangle,
        style=filled
    ];
    "gold_adhoc_demand_review.countries"    [color=red,
        height=0.5,
        kind=adhoc,
        pos="1010,234",
        table=countries,
        use_case=demand_review,
        width=3.1389,
        zone=gold];
    "gold_core.location"    [color=blue,
        height=0.5,
        kind=core,
        pos="868,306",
        table=location,
        width=1.6389,
        zone=gold];
    "gold_core.location" -> "gold_adhoc_demand_review.countries"    [pos="e,975.13,252.19 902.74,287.88 921.82,278.47 945.68,266.71 966.05,256.67"];
    "gold_adhoc_product_priorities.distribution_network"    [color=red,
        height=0.5,
        kind=adhoc,
        pos="150,234",
        table=distribution_network,
        use_case=product_priorities,
        width=4.1667,
        zone=gold];
    "gold_core.location" -> "gold_adhoc_product_priorities.distribution_network"    [pos="e,300.22,251.11 808.82,299.62 708.56,290.46 498.65,271.06 310.31,252.13"];
    "gold_adhoc_global_supply_review.country"   [color=red,
        height=0.5,
        kind=adhoc,
        pos="1267,234",
        table=country,
        use_case=global_supply_review,
        width=3.4861,
        zone=gold];
...

draw.py

def draw_graph(networkx_graph):
    networkx_graph.graph['graph'] = {'rankdir': PYGRAPHIZ_RANKDIR}
    networkx_graph.graph['node'] = {'shape': PYGRAPHIZ_SHAPE_TYPE, 'fillcolor': 'red', 'style':'filled'}
    networkx_graph.graph['edges']={'arrowsize': PYGRAPHIZ_ARROW_SIZE}
    pygraphviz_graph = to_agraph(networkx_graph)
    pygraphviz_graph.layout("svg")
    pygraphviz_graph.draw("result.svg")
    print(pygraphviz_graph.graph_attr)

Body:
The property you want to update is fillcolor, not color. color controls the border of a node.

(See the documentation at https://graphviz.org/docs/attrs/fillcolor/)

Your logic would look like this to customize the fill color of individual nodes:

if node.name == 'abc':
  node.fillcolor = 'gold'
else:
  node.fillcolor = 'pink'

Note: you can use RGB color codes rather than names to give you more options, e.g.: fillcolor = "#ffd700"


答:
I can't think of a solution better than this (though there might be better ones).</p>
```<code>#include <stdio.h>

int main() {
    char word[] = "This is a word";
    int flag = 0, space = 0, pos = -1;
    for (int i = 0; word[i] != '\0'; i++) {
        if (flag == 1) {
                break;
            }
        for (int j = 0; word[j] != '\0'; j++) {
            if (flag == 1) {
                break;
            }
            else if (word[j+1] == '\0' || word[j+2] == '\0' || word[j+3] == '\0') {
                break;
            }
            else {
                if (word[j] == 'w' && word[j+1] == 'o' && word[j+2] == 'r' && word[j+3] == 'd') {
                    flag = 1;
                    pos = j;
                }
            }
        }
    }

    for (int i = 0; word[i] != '\0'; i++) {
        if (word[i] == ' ' || word[i] == '!' || word[i] == '@') {// And many more symbols
            fchars++;
        }
        else {
            break;
        }
    }

    if (flag == 1 && pos-1 > 0 && word[pos-1] == ' ') {
        for (int i = 0; i < pos; i++) {
            if (word[i] == ' ') {
                space++;
            }
        }
        printf("Found at position = %i\n", space+1-fchars);
    }
    else {
       printf("Not found!\n");
    }

}
</code>```

Title: Find index of word in string

Body:
I want to write a function which will find index of word in string.
For example if string is

This is word.

my function for string "word" should return number 3.

Note: functions from string.h library and auxiliary strings are not allowed.

How could I do this in C?

Body:
I can't think of a solution better than this (though there might be better ones).

#include <stdio.h>

int main() {
    char word[] = "This is a word";
    int flag = 0, space = 0, pos = -1;
    for (int i = 0; word[i] != '\0'; i++) {
        if (flag == 1) {
                break;
            }
        for (int j = 0; word[j] != '\0'; j++) {
            if (flag == 1) {
                break;
            }
            else if (word[j+1] == '\0' || word[j+2] == '\0' || word[j+3] == '\0') {
                break;
            }
            else {
                if (word[j] == 'w' && word[j+1] == 'o' && word[j+2] == 'r' && word[j+3] == 'd') {
                    flag = 1;
                    pos = j;
                }
            }
        }
    }

    for (int i = 0; word[i] != '\0'; i++) {
        if (word[i] == ' ' || word[i] == '!' || word[i] == '@') {// And many more symbols
            fchars++;
        }
        else {
            break;
        }
    }

    if (flag == 1 && pos-1 > 0 && word[pos-1] == ' ') {
        for (int i = 0; i < pos; i++) {
            if (word[i] == ' ') {
                space++;
            }
        }
        printf("Found at position = %i\n", space+1-fchars);
    }
    else {
       printf("Not found!\n");
    }

}


答:
You can split the sentence by space to get the words and then match each word in the sentence with the word you want to match
Please check this modified code:

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

int main()
{
    char word[] = "word";
    char string[100];
    gets(string);
    int curWordStart = -1;
    int curWordEnd = -1;
    int wordCount = 0;
    int i = 0;
    for (i = 0; string[i] != '\0'; i++)
    {
        if (string[i] == ' ')
        {
            int curWordLength = curWordEnd - curWordStart + 1;
            if (curWordStart != -1 && curWordLength > 0)
            {
                wordCount++;
                int foundMatch = 1;
                int j;
                int k = 0;
                for (j = curWordStart; j <= curWordEnd; j++) {
                    if (word[k] == '\0') {
                        foundMatch = 0;
                        break;
                    }
                    if (word[k] != string[j])
                    {
                        foundMatch = 0;
                        break;
                    }
                    k++;
                }
                if (word[k] != '\0')
                {
                    foundMatch = 0;
                }

                if (foundMatch == 1)
                {
                    printf("%d\n", wordCount);
                }
            }
            curWordStart = -1;
            curWordEnd = -1;
        }
        else if ((string[i] >= 'a' && string[i] <= 'z') || (string[i] >= 'A' && string[i] <= 'Z'))
        {
            if (curWordStart == -1) {
                curWordStart = i;
            }
            curWordEnd = i;
        }
    }
    int curWordLength = curWordEnd - curWordStart + 1;
    if (curWordStart != -1 && curWordLength > 0)
    {
        wordCount++;
        int foundMatch = 1;
        int j;
        int k = 0;
        for (j = curWordStart; j <= curWordEnd; j++) {
            if (word[k] == '\0') {
                foundMatch = 0;
                break;
            }
            if (word[k] != string[j])
            {
                foundMatch = 0;
                break;
            }
            k++;
        }
        if (word[k] != '\0')
        {
            foundMatch = 0;
        }

        if (foundMatch == 1)
        {
            printf("%d\n", wordCount);
        }
    }
    return 0;
}
</code>```

It will print each position of the searched word in the sentence. If you want to just print the first one, you can easily modify it.

Title: Find index of word in string

Body:
You can split the sentence by space to get the words and then match each word in the sentence with the word you want to match
Please check this modified code:

#include<stdio.h>

int main()
{
    char word[] = "word";
    char string[100];
    gets(string);
    int curWordStart = -1;
    int curWordEnd = -1;
    int wordCount = 0;
    int i = 0;
    for (i = 0; string[i] != '\0'; i++)
    {
        if (string[i] == ' ')
        {
            int curWordLength = curWordEnd - curWordStart + 1;
            if (curWordStart != -1 && curWordLength > 0)
            {
                wordCount++;
                int foundMatch = 1;
                int j;
                int k = 0;
                for (j = curWordStart; j <= curWordEnd; j++) {
                    if (word[k] == '\0') {
                        foundMatch = 0;
                        break;
                    }
                    if (word[k] != string[j])
                    {
                        foundMatch = 0;
                        break;
                    }
                    k++;
                }
                if (word[k] != '\0')
                {
                    foundMatch = 0;
                }

                if (foundMatch == 1)
                {
                    printf("%d\n", wordCount);
                }
            }
            curWordStart = -1;
            curWordEnd = -1;
        }
        else if ((string[i] >= 'a' && string[i] <= 'z') || (string[i] >= 'A' && string[i] <= 'Z'))
        {
            if (curWordStart == -1) {
                curWordStart = i;
            }
            curWordEnd = i;
        }
    }
    int curWordLength = curWordEnd - curWordStart + 1;
    if (curWordStart != -1 && curWordLength > 0)
    {
        wordCount++;
        int foundMatch = 1;
        int j;
        int k = 0;
        for (j = curWordStart; j <= curWordEnd; j++) {
            if (word[k] == '\0') {
                foundMatch = 0;
                break;
            }
            if (word[k] != string[j])
            {
                foundMatch = 0;
                break;
            }
            k++;
        }
        if (word[k] != '\0')
        {
            foundMatch = 0;
        }

        if (foundMatch == 1)
        {
            printf("%d\n", wordCount);
        }
    }
    return 0;
}

It will print each position of the searched word in the sentence. If you want to just print the first one, you can easily modify it.


问:
Multiple dispatch funcs causing one rerender only. Why?
I'm using Redux to handle my app state. As I understand, every time I change the state, Redux will force my component to rerender (in simple terms). The code looks like this:

```<code>const SideMenu = props => {

   console.log(`Render`);

   const { isLoading, error, sections, activeSectionId } = useSelector(state => state.sections);
   const dispatch = useDispatch();

   useEffect(() => {
      console.log(`useEffect`);

      if (!sections.length) {
         dispatch(getSections());
      }

      if (sections.length && !activeSectionId) {
         dispatch(setActiveSection(sections[0].id));   // <-- console.log inside
      }
   }, [dispatch, sections, activeSectionId]);

   if (isLoading) {
      return (
         <div>Side menu is loading...</div>
      )
   }

   if (error) {
      return (
         <div>Side menu error: {error}</div>
      )
   }

   return (
      <ul>
         Menu here...
      </ul>
   )
}
</code>```

In this example every function inside dispatch is a fake (just to test render logic) and synchronous. I put console.log() inside action creators with functions names to see what's going on. Notice that in getSections I have two inner dispatch. Code of getSections action:

```<code>export const getSections = () => {
   // this is not async func
   return (dispatch, getState) => {
      try {
         dispatch(setSections([{}]));    // <-- console.log inside
      } catch (error) {
         dispatch(setSectionsError(error.message));
      }
      dispatch(isSectionsLoading(false));   // <-- console.log inside
   }
}
</code>```

So after run this code I see log sequence like this:

```<code>Render
useEffect
setSections
isSectionsLoading
Render
useEffect
setActiveSection
Render
useEffect
</code>```

I see 3 Renders, but it has to be 4 because I dispatched 3 times (setSections, isSectionsLoading, setActiveSection). Why it renders only 3 times?

答:
React will batch multiple queued state updates into a single render, depending on when those state updates were queued.

In this case, it looks like you're dispatching twice synchronously from within a single useEffect hook.  So yes, I would expect those two updates to be batched together.

See my extensive post A (Mostly) Complete Guide to React Rendering Behavior for more details on how React rendering works.

Body:
I'm using Redux to handle my app state. As I understand, every time I change the state, Redux will force my component to rerender (in simple terms). The code looks like this:

const SideMenu = props => {

   console.log(`Render`);

   const { isLoading, error, sections, activeSectionId } = useSelector(state => state.sections);
   const dispatch = useDispatch();

   useEffect(() => {
      console.log(`useEffect`);

      if (!sections.length) {
         dispatch(getSections());
      }

      if (sections.length && !activeSectionId) {
         dispatch(setActiveSection(sections[0].id));   // <-- console.log inside
      }
   }, [dispatch, sections, activeSectionId]);

   if (isLoading) {
      return (

Side menu is loading...

      )
   }

   if (error) {
      return (

Side menu error: {error}

      )
   }

   return (

         Menu here...

   )
}

In this example every function inside dispatch is a fake (just to test render logic) and synchronous. I put console.log() inside action creators with functions names to see what's going on. Notice that in getSections I have two inner dispatch. Code of getSections action:

export const getSections = () => {
   // this is not async func
   return (dispatch, getState) => {
      try {
         dispatch(setSections([{}]));    // <-- console.log inside
      } catch (error) {
         dispatch(setSectionsError(error.message));
      }
      dispatch(isSectionsLoading(false));   // <-- console.log inside
   }
}

So after run this code I see log sequence like this:

Render
useEffect
setSections
isSectionsLoading
Render
useEffect
setActiveSection
Render
useEffect

I see 3 Renders, but it has to be 4 because I dispatched 3 times (setSections, isSectionsLoading, setActiveSection). Why it renders only 3 times?


问:
enable button after actual input entered
How  to enabled button, when the actual amount entered

lets say i have 100 minimum and 200 maximum

i want when user enters amount below 100 error comes actual amount needed and button reamins dsiabled

when user enters more than 200 do the same echo error

user has to enter 100 and above but not exceed maximum

```<code> <form method="post">
<input type="text" id="Textfield">
<button type="submit" class="disabledButton" disabled>Submit</button>
<p id="error"></p>
</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$('#Textfield').keyup(function(){
     var textBox = $('#Textfield').val();
     if((textBox >= 100) || (textBox <= 200) ){
       $('.disabledButton').prop("disabled", false);
     } else {
     $('#error').text('actual amount needed');
        return false;
    }
});
</script>
</code>```

答:
EDIT
Sorry, I guess I kinda just glossed over the question. Here's your working code))

<form>
    <input type="text" />
    <button type="submit" disabled>Submit</button>

</form>

```
</div>
</div>
</p>
<p>previous edit: Edited to add dynamic error message</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
    <input type="text" max="200" />
    <button type="submit" disabled>Submit</button>
    <p id="error" style="color: red"></p>
</form>

<script>
    const input = document.querySelector('input');
    const button = document.querySelector('button');
    const error = document.querySelector('#error');
    const minChars = 10;

    const setError = (length) => {
        const message = `Please enter ${minChars - length} more character(s).`;
        error.innerText = message;
        error.style.display = 'block';
    };

    const hideError = () => {
        error.style.display = 'none';
    };

    input.addEventListener('keyup', () => {
        const enteredLength = input.value.length;

        if (enteredLength >= minChars) {
            button.disabled = false;
            return hideError();
        }

        setError(enteredLength);
        button.disabled = true;
    });
</script></code>```

Body:
How  to enabled button, when the actual amount entered

lets say i have 100 minimum and 200 maximum

i want when user enters amount below 100 error comes actual amount needed and button reamins dsiabled

when user enters more than 200 do the same echo error

user has to enter 100 and above but not exceed maximum

 <form method="post">
<input type="text" id="Textfield">
<button type="submit" class="disabledButton" disabled>Submit</button>

</form>

Body:
EDIT
Sorry, I guess I kinda just glossed over the question. Here's your working code))

<form>
    <input type="text" />
    <button type="submit" disabled>Submit</button>
    <p id="error" style="color: red"></p>
</form>

<script>
    const input = document.querySelector('input');
    const button = document.querySelector('button');
    const error = document.querySelector('#error');
    const minVal = 100;
    const maxVal = 200;

    const setError = (current) => {
        const message = `Please enter between ${minVal} and ${maxVal}. You entered ${current}`;
        error.innerText = message;
        error.style.display = 'block';
    };

    const hideError = () => {
        error.style.display = 'none';
    };

    input.addEventListener('keyup', () => {
        const enteredValue = parseInt(input.value, 10);

        if (enteredValue >= minVal && enteredValue <= maxVal) {
            button.disabled = false;
            return hideError();
        }

        setError(enteredValue);
        button.disabled = true;
    });
</script>

previous edit: Edited to add dynamic error message

<form>
    <input type="text" max="200" />
    <button type="submit" disabled>Submit</button>
    <p id="error" style="color: red"></p>
</form>

<script>
    const input = document.querySelector('input');
    const button = document.querySelector('button');
    const error = document.querySelector('#error');
    const minChars = 10;

    const setError = (length) => {
        const message = `Please enter ${minChars - length} more character(s).`;
        error.innerText = message;
        error.style.display = 'block';
    };

    const hideError = () => {
        error.style.display = 'none';
    };

    input.addEventListener('keyup', () => {
        const enteredLength = input.value.length;

        if (enteredLength >= minChars) {
            button.disabled = false;
            return hideError();
        }

        setError(enteredLength);
        button.disabled = true;
    });
</script>


问:
How to write click event in inside of cellrenderer angular ag grid
enter code hereI am trying to create edit and delete buttons in same column for every row using angular ag grid. To display the edit and delete buttons, I am using icons. I am able to display the remove and edit icons for every row in ag grid, but i am failing to click those icons.
Below are the respective images of that. I tried to click event inside of button but it was not worked, I tried to write click event in icon tag also but it is also not worked.
Below is my code which i am using

```<code>

</code>```

答:
You can follow this approach to create a click event in cell renderer.

First : Create Button Cell

create button cell renderer as an Angular component that implements the ICellRendererAngularComp interface as follows :

```<code>@Component({
  selector: 'btn-cell-renderer',
  template: `
    <button (click)="handleClickEvent($event)">Click me</button>
  `,
})
export class BtnCellRenderer implements ICellRendererAngularComp
{
  private params: any;

  agInit(params: any): void {
    this.params = params;
  }

  handleClickEvent() {
    this.params.clicked(this.params.value);
  }

}
</code>```

The params object is accessed through the agInit hook.

Second:  Register the BtnRenderer in the app module

// app/app.modules.ts

```<code>@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule,
    AgGridModule.withComponents([BtnCellRenderer]),
  ],
  declarations: [AppComponent, BtnCellRenderer],
  bootstrap: [AppComponent],
})
</code>```

Third:  Use the renderer
Use the renderer in your component as follows

```<code>// app/app.component.ts

this.columnDefs = [
      {
        field: 'action',
        cellRenderer: 'btnCellRenderer',
        cellRendererParams: {
          clicked: function(field: any) {
            alert(`${field} was clicked`);
          }
        },
        minWidth: 100,
      }

      ];

      this.frameworkComponents = {
      btnCellRenderer: BtnCellRenderer
    };
</code>```

Body:
You can follow this approach to create a click event in cell renderer.

First : Create Button Cell

create button cell renderer as an Angular component that implements the ICellRendererAngularComp interface as follows :

@Component({
  selector: 'btn-cell-renderer',
  template: `
    <button (click)="handleClickEvent($event)">Click me</button>
  `,
})
export class BtnCellRenderer implements ICellRendererAngularComp
{
  private params: any;

  agInit(params: any): void {
    this.params = params;
  }

  handleClickEvent() {
    this.params.clicked(this.params.value);
  }

}

The params object is accessed through the agInit hook.

Second:  Register the BtnRenderer in the app module

// app/app.modules.ts

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule,
    AgGridModule.withComponents([BtnCellRenderer]),
  ],
  declarations: [AppComponent, BtnCellRenderer],
  bootstrap: [AppComponent],
})

Third:  Use the renderer
Use the renderer in your component as follows

// app/app.component.ts

this.columnDefs = [
      {
        field: 'action',
        cellRenderer: 'btnCellRenderer',
        cellRendererParams: {
          clicked: function(field: any) {
            alert(`${field} was clicked`);
          }
        },
        minWidth: 100,
      }

      ];

      this.frameworkComponents = {
      btnCellRenderer: BtnCellRenderer
    };


问:
Django HTML template tag for date
I get date data from an API on the internet, but it comes as a string. How do I convert this to the following format using django HTML template tag?

Current date data format:
2022-02-13 00:00:00 UTC

My wish format:
13 February 2022 00:00

My wish another format:
13 February 2022

答:
Because in templates it's not that simple to use Python, we need to create custom Template Tag. Let's start with creating folder in your app, let's name it custom_tags.py. It should be created in YourProject/your_app/templatetags/ folder, so we have to also create templatetags folder in there.

custom_tags.py:

```<code>from django import template
import datetime

register = template.Library()

@register.filter(name='format_date')
def format_date(date_string):
    return datetime.datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S %Z')
</code>```

your_template.html:

```<code>{% load custom_tags %}

{{ datetime_from_API|format_date|date:'d F Y j:i' }}

# or if that does not work - I can't check it right now

{% with datetime_from_API|format_date as my_date %}
    {{ my_date|date:'d F Y j:i' }}
{% endwith %}
</code>```

If you can get datetime objects directly you can use date tag in templates.

usage:

```<code>with hour:
{{ some_model.datetime|date:'d F Y j:i' }}

date only:
{{ some_model.datetime|date:'d F Y' }}
</code>```

Read more in Django DOCS

Title: Django HTML template tag for date

Body:
Because in templates it's not that simple to use Python, we need to create custom Template Tag. Let's start with creating folder in your app, let's name it custom_tags.py. It should be created in YourProject/your_app/templatetags/ folder, so we have to also create templatetags folder in there.

custom_tags.py:

from django import template
import datetime

register = template.Library()

@register.filter(name='format_date')
def format_date(date_string):
    return datetime.datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S %Z')

your_template.html:

{% load custom_tags %}

{{ datetime_from_API|format_date|date:'d F Y j:i' }}

# or if that does not work - I can't check it right now

{% with datetime_from_API|format_date as my_date %}
    {{ my_date|date:'d F Y j:i' }}
{% endwith %}

If you can get datetime objects directly you can use date tag in templates.

usage:

with hour:
{{ some_model.datetime|date:'d F Y j:i' }}

date only:
{{ some_model.datetime|date:'d F Y' }}

Read more in Django DOCS


问:
Not able to hit any breakpoints on c# dll using VS 2019 or Rider
Trying to debug C# dll with VS 2019 and Rider 2021.1.3. Everything compiles and dll is copied to the right location as well as .pdb file. But none of the breakpoints get hit on either of IDEs.

On Rider got a notification: "Didn't find the associated module for the breakpoint..."

On Visual Studio the breakpoint simply doesn't get hit.

The code changes get propagated, so the code itself works fine and gets executed, but debugging doesn't work at all.

What I have done: pretty much everything what is described here: Debugging properties setup

Except for cleaning up AppData since there is no the directory for Temporary ASP.NET Files

Have reinstalled Rider in to the similar location on the same drive where the solution is.

Set the Debug options on VS as described in the link

Using Debug option of course.

Set the Symbols file path on Tools -> Options -> Debugging -> Symbols

Also, somewhat similar setup works for C++ project I have, but not for the C# one.

Also, when I attach to the process, then somehow the Window -> Modules doesn't show my dll in the list. Which is probably because it is a mono project. But it is 100% loaded as I've mentioned above as the code changes are picked up.

Rider setup for dll debug:

```<code>{
  "profiles": {
    "Assembly-CSharp": {
      "commandName": "Executable",
      "executablePath": "$(ProjectDir)..\\....exe",
      "remoteDebugEnabled": false
    }
  }
</code>```

Update: One of the problems potentially is that I have mono.dll in the Debug > Windows > Modules, but not the dll I am working with. So, in that case, how do I explicitly see my dll in the list of the loaded modules so that I can load .pdb file manually? Is it even possible (relevant) in this case?

Update1: Found this which might be relevant in this case.

Update2: Found configuration for Unity projects (managed dlls). From this, the only relevant part is at the end with selection of the appropriate target Framework. Trying to find out of how to be able to configure it.

答:
Fixed with debugging version of mono.dll as per this link here

Since the dll in question was managed dll from the Unity game built with Mono, thus apparently the debugging can be enabled with the debugging version of that dll.

Body:
Trying to debug C# dll with VS 2019 and Rider 2021.1.3. Everything compiles and dll is copied to the right location as well as .pdb file. But none of the breakpoints get hit on either of IDEs.

On Rider got a notification: "Didn't find the associated module for the breakpoint..."

On Visual Studio the breakpoint simply doesn't get hit.

The code changes get propagated, so the code itself works fine and gets executed, but debugging doesn't work at all.

What I have done: pretty much everything what is described here: Debugging properties setup

Except for cleaning up AppData since there is no the directory for Temporary ASP.NET Files

Have reinstalled Rider in to the similar location on the same drive where the solution is.

Set the Debug options on VS as described in the link

Using Debug option of course.

Set the Symbols file path on Tools -> Options -> Debugging -> Symbols

Also, somewhat similar setup works for C++ project I have, but not for the C# one.

Also, when I attach to the process, then somehow the Window -> Modules doesn't show my dll in the list. Which is probably because it is a mono project. But it is 100% loaded as I've mentioned above as the code changes are picked up.

Rider setup for dll debug:

{
  "profiles": {
    "Assembly-CSharp": {
      "commandName": "Executable",
      "executablePath": "$(ProjectDir)..\\....exe",
      "remoteDebugEnabled": false
    }
  }

Update: One of the problems potentially is that I have mono.dll in the Debug > Windows > Modules, but not the dll I am working with. So, in that case, how do I explicitly see my dll in the list of the loaded modules so that I can load .pdb file manually? Is it even possible (relevant) in this case?

Update1: Found this which might be relevant in this case.

Update2: Found configuration for Unity projects (managed dlls). From this, the only relevant part is at the end with selection of the appropriate target Framework. Trying to find out of how to be able to configure it.