问:
Delete last 3 characters if they are equal to something
(without affecting the char level formatting in the cell)

I've already posted a similar question, but I unfortunately I realized I couldn't use any of the solutions because all of them removed all the formatting in the cells :(

I have a code that replaces various text strings. It looks like this (+ some more IFs):

```<code>Sub Fix()
  Dim X As Long, Cell As Range
  For Each Cell In Selection
    For X = Len(Cell.Text) To 1 Step -1
      If Cell.Characters(X, 3).Text = ", ," Then Cell.Characters(X, 3).Text = ","
      If Cell.Characters(X, 3).Text = ", (" Then Cell.Characters(X, 3).Text = " ("
      If Cell.Characters(X, 3).Text = ", [" Then Cell.Characters(X, 3).Text = " ["
      If Cell.Characters(X, 3).Text = ", -" Then Cell.Characters(X, 3).Text = " -"
      If Cell.Characters(1, 3).Text = "abc" Then Cell.Characters(1, 3).Text = ""
    Next
  Next
End Sub
</code>```

The last line of my code deletes abc if this is contained at the beginning of the selected cell(s).

I am looking to find out how to delete abc when this is contained at the end of the selected cell(s).

But it's really important for me to preserve all the original formatting in the cells (text size, colors, bold/italic/underline letters etc).

Please bear in mind that I am a complete beginner and I don't know anything about programming. I've copied the code above from the internet and just changed the values.

Thank you in advance for your help.

答:
Something like this would probably work:

```<code>Sub FixData()
Dim X As Long, Y As Long, Cell As Range, FindChars As Variant, ReplaceChars As Variant, StartRemove As Variant, EndRemove As Variant
FindChars = Array(", ,", ", (", ", [", ", -") 'must have at least 2 elements, if you only have one then just put something it will never have like "zzzzzzzzzz"
ReplaceChars = Array(",", " (", " [", " -") 'must have at least 2 elements, if you only have one then just put something it will never have like "zzzzzzzzzz"
StartRemove = Array("something1", "somthingelse1") 'must have at least 2 elements, if you only have one then just put something it will never have like "zzzzzzzzzz"
EndRemove = Array("something2", "somthingelse2") 'must have at least 2 elements, if you only have one then just put something it will never have like "zzzzzzzzzz"
For Each Cell In Selection
    For Y = LBound(FindChars) To UBound(FindChars)
        If InStr(1, Cell.Text, FindChars(Y)) > 0 Then Cell.Characters(InStr(1, Cell.Text, FindChars(Y)), Len(FindChars(Y))).Delete
    Next
    For Y = LBound(StartRemove) To UBound(StartRemove)
        If Left(Cell.Text, Len(StartRemove(Y))) = StartRemove Then Cell.Characters(1, Len(StartRemove(Y))).Delete
    Next
    For Y = LBound(EndRemove) To UBound(EndRemove)
        If Right(Cell.Text, Len(EndRemove(Y))) = EndRemove Then Cell.Characters(Len(Cell) - Len(EndRemove(Y)) + 1, Len(EndRemove(Y))).Delete
    Next
Next
End Sub
</code>```

Edit based on conversations since and updates to reflect these conversations.

This code has 4 arrays, it rips through the find and replace arrays first to find and replace any instance. Then it goes through the start array to find only things at the start then lastly it loops the end array to find anything at the end of the string.

Using cell.characters().delete will remove those chars without altering the individual character formatting around it.

Body:
(without affecting the char level formatting in the cell)

I've already posted a similar question, but I unfortunately I realized I couldn't use any of the solutions because all of them removed all the formatting in the cells :(

I have a code that replaces various text strings. It looks like this (+ some more IFs):

Sub Fix()
  Dim X As Long, Cell As Range
  For Each Cell In Selection
    For X = Len(Cell.Text) To 1 Step -1
      If Cell.Characters(X, 3).Text = ", ," Then Cell.Characters(X, 3).Text = ","
      If Cell.Characters(X, 3).Text = ", (" Then Cell.Characters(X, 3).Text = " ("
      If Cell.Characters(X, 3).Text = ", [" Then Cell.Characters(X, 3).Text = " ["
      If Cell.Characters(X, 3).Text = ", -" Then Cell.Characters(X, 3).Text = " -"
      If Cell.Characters(1, 3).Text = "abc" Then Cell.Characters(1, 3).Text = ""
    Next
  Next
End Sub

The last line of my code deletes abc if this is contained at the beginning of the selected cell(s).

I am looking to find out how to delete abc when this is contained at the end of the selected cell(s).

But it's really important for me to preserve all the original formatting in the cells (text size, colors, bold/italic/underline letters etc).

Please bear in mind that I am a complete beginner and I don't know anything about programming. I've copied the code above from the internet and just changed the values.

Thank you in advance for your help.

Body:
Something like this would probably work:

Sub FixData()
Dim X As Long, Y As Long, Cell As Range, FindChars As Variant, ReplaceChars As Variant, StartRemove As Variant, EndRemove As Variant
FindChars = Array(", ,", ", (", ", [", ", -") 'must have at least 2 elements, if you only have one then just put something it will never have like "zzzzzzzzzz"
ReplaceChars = Array(",", " (", " [", " -") 'must have at least 2 elements, if you only have one then just put something it will never have like "zzzzzzzzzz"
StartRemove = Array("something1", "somthingelse1") 'must have at least 2 elements, if you only have one then just put something it will never have like "zzzzzzzzzz"
EndRemove = Array("something2", "somthingelse2") 'must have at least 2 elements, if you only have one then just put something it will never have like "zzzzzzzzzz"
For Each Cell In Selection
    For Y = LBound(FindChars) To UBound(FindChars)
        If InStr(1, Cell.Text, FindChars(Y)) > 0 Then Cell.Characters(InStr(1, Cell.Text, FindChars(Y)), Len(FindChars(Y))).Delete
    Next
    For Y = LBound(StartRemove) To UBound(StartRemove)
        If Left(Cell.Text, Len(StartRemove(Y))) = StartRemove Then Cell.Characters(1, Len(StartRemove(Y))).Delete
    Next
    For Y = LBound(EndRemove) To UBound(EndRemove)
        If Right(Cell.Text, Len(EndRemove(Y))) = EndRemove Then Cell.Characters(Len(Cell) - Len(EndRemove(Y)) + 1, Len(EndRemove(Y))).Delete
    Next
Next
End Sub

Edit based on conversations since and updates to reflect these conversations.

This code has 4 arrays, it rips through the find and replace arrays first to find and replace any instance. Then it goes through the start array to find only things at the start then lastly it loops the end array to find anything at the end of the string.

Using cell.characters().delete will remove those chars without altering the individual character formatting around it.


来源: stackexchange

问:
MySQL DELETE query issue with Select
The following query:

```<code>DELETE FROM CO05IN.ININVPRC WHERE IPPART IN (SELECT IPPART FROM CO05IN.ININVPRC left join CO05IN.ININVMST on IPPART = IMPART where IMPART is null);
</code>```

Creates this on the log: You can't specify target table 'ININVPRC' for update in FROM clause.

What is causing this?

Note using MySQL version 5.1

答:
Try in this way.</p>

```<code>DELETE FROM CO05IN.ININVPRC WHERE IPPART IN (select * from (SELECT IPPART FROM CO05IN.ININVPRC left join CO05IN.ININVMST on IPPART = IMPART where IMPART is null) as t);
</code>```

ContentLicense: CC BY-SA 3.0

Title: MySQL DELETE query issue with Select

Body:
The following query:

DELETE FROM CO05IN.ININVPRC WHERE IPPART IN (SELECT IPPART FROM CO05IN.ININVPRC left join CO05IN.ININVMST on IPPART = IMPART where IMPART is null);

Creates this on the log: You can't specify target table 'ININVPRC' for update in FROM clause.

What is causing this?

Note using MySQL version 5.1

Body:
Try in this way.

DELETE FROM CO05IN.ININVPRC WHERE IPPART IN (select * from (SELECT IPPART FROM CO05IN.ININVPRC left join CO05IN.ININVMST on IPPART = IMPART where IMPART is null) as t);


问:
Maven - Failsafe plugin is not running cucumber tests in parallel
I am trying to setup serenity cucumber tests to run in parallel

I have added all the necessary configuration that have been mentioned but for some reason tests are executed in a single thread. I tried various combinations with forkCount, threadCount, parallel, useUnlimitedThreadCounts etc nothing seems to work.

Also tried having a dependency for JUnit 4 and 5 which didnt work as well.

Pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <properties>
        <serenity.version>2.2.5</serenity.version>
        <serenity.maven.version>2.2.5</serenity.maven.version>
        <serenity.cucumber5.version>2.2.2</serenity.cucumber5.version>
        <cucumber.version>5.6.0</cucumber.version>
        <selenium.version>3.141.59</selenium.version>
    </properties>

    <dependencies>
        <!-- Cucumber -->
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-core</artifactId>
            <version>${cucumber.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>${cucumber.version}</version>
            <scope>test</scope>
        </dependency>

        <!-- Serenity -->
        <dependency>
            <groupId>net.serenity-bdd</groupId>
            <artifactId>serenity-core</artifactId>
            <version>${serenity.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>io.cucumber</groupId>
                    <artifactId>cucumber-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>net.serenity-bdd</groupId>
            <artifactId>serenity-cucumber5</artifactId>
            <version>${serenity.cucumber5.version}</version>
        </dependency>

        <!-- Selenium -->
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>${selenium.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>3.0.0-M4</version>
                <dependencies>
                    <dependency>
                        <groupId>org.apache.maven.surefire</groupId>
                        <artifactId>surefire-junit47</artifactId>
                        <version>3.0.0-M4</version>
                    </dependency>
                </dependencies>
                <configuration>
                    <parallel>classes</parallel>
                    <threadCount>2</threadCount>
                    <forkCount>2C</forkCount>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

</code>```

The maven debug logs for verify indicates parallelMavenExecution is set to false for some reason.

```<code>[DEBUG] Configuring mojo org.apache.maven.plugins:maven-failsafe-plugin:3.0.0-M4:integration-test from plugin realm ClassRealm[plugin>org.apache.maven.plugins:maven-failsafe-plugin:3.0.0-M4, parent: jdk.internal.loader.ClassLoaders$AppClassLoader@4f8e5cde]
[DEBUG] Configuring mojo 'org.apache.maven.plugins:maven-failsafe-plugin:3.0.0-M4:integration-test' with basic configurator -->
[DEBUG]   (s) additionalClasspathElements = []
[DEBUG]   (s) basedir = /Users/vinothraj/IdeaProjects/hiscox-usa-portal-testsuite
[DEBUG]   (s) childDelegation = false
[DEBUG]   (s) classpathDependencyExcludes = []
[DEBUG]   (s) defaultClassesDirectory = /target/classes
[DEBUG]   (s) dependenciesToScan = []
[DEBUG]   (s) disableXmlReport = false
[DEBUG]   (s) enableAssertions = true
[DEBUG]   (f) excludedEnvironmentVariables = []
[DEBUG]   (f) forkCount = 2C
[DEBUG]   (s) forkMode = once
[DEBUG]   (s) forkedProcessExitTimeoutInSeconds = 30
[DEBUG]   (s) junitArtifactName = junit:junit
[DEBUG]   (s) localRepository =       id: local
      url: file:///.m2/repository/
   layout: default
snapshots: [enabled => true, update => always]
 releases: [enabled => true, update => always]

[DEBUG]   (s) parallel = classes
[DEBUG]   (f) parallelMavenExecution = false
[DEBUG]   (s) parallelOptimized = true
[DEBUG]   (s) perCoreThreadCount = true
</code>```

Thanks in advance.

答:
You're using the wrong value for parallel. You have to set it to methods or both. Otherwise Surefire will run all tests of your runner class serially.

https://github.com/cucumber/cucumber-jvm/tree/main/cucumber-junit

Cucumber JUnit supports parallel execution of feature files across multiple threads. To enable this with maven set the parallel property to either methods or both.

```<code><build>
    <plugins>
        <plugin>
            <artifactId>maven-surefire-plugin</artifactId>
            <!-- Use 2.22.1 or higher -->
            <version>${maven-surefire-plugin.version}</version>
            <configuration>
                <parallel>both</parallel>
                <threadCount>4</threadCount>
            </configuration>
        </plugin>
    </plugins>
</build>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to setup serenity cucumber tests to run in parallel

I have added all the necessary configuration that have been mentioned but for some reason tests are executed in a single thread. I tried various combinations with forkCount, threadCount, parallel, useUnlimitedThreadCounts etc nothing seems to work.

Also tried having a dependency for JUnit 4 and 5 which didnt work as well.

Pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <properties>
        <serenity.version>2.2.5</serenity.version>
        <serenity.maven.version>2.2.5</serenity.maven.version>
        <serenity.cucumber5.version>2.2.2</serenity.cucumber5.version>
        <cucumber.version>5.6.0</cucumber.version>
        <selenium.version>3.141.59</selenium.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-core</artifactId>
            <version>${cucumber.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>${cucumber.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>net.serenity-bdd</groupId>
            <artifactId>serenity-core</artifactId>
            <version>${serenity.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>io.cucumber</groupId>
                    <artifactId>cucumber-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>net.serenity-bdd</groupId>
            <artifactId>serenity-cucumber5</artifactId>
            <version>${serenity.cucumber5.version}</version>
        </dependency>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>${selenium.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>3.0.0-M4</version>
                <dependencies>
                    <dependency>
                        <groupId>org.apache.maven.surefire</groupId>
                        <artifactId>surefire-junit47</artifactId>
                        <version>3.0.0-M4</version>
                    </dependency>
                </dependencies>
                <configuration>
                    <parallel>classes</parallel>
                    <threadCount>2</threadCount>
                    <forkCount>2C</forkCount>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

The maven debug logs for verify indicates parallelMavenExecution is set to false for some reason.

[DEBUG] Configuring mojo org.apache.maven.plugins:maven-failsafe-plugin:3.0.0-M4:integration-test from plugin realm ClassRealm[plugin>org.apache.maven.plugins:maven-failsafe-plugin:3.0.0-M4, parent: jdk.internal.loader.ClassLoaders$AppClassLoader@4f8e5cde]
[DEBUG] Configuring mojo 'org.apache.maven.plugins:maven-failsafe-plugin:3.0.0-M4:integration-test' with basic configurator -->
[DEBUG]   (s) additionalClasspathElements = []
[DEBUG]   (s) basedir = /Users/vinothraj/IdeaProjects/hiscox-usa-portal-testsuite
[DEBUG]   (s) childDelegation = false
[DEBUG]   (s) classpathDependencyExcludes = []
[DEBUG]   (s) defaultClassesDirectory = /target/classes
[DEBUG]   (s) dependenciesToScan = []
[DEBUG]   (s) disableXmlReport = false
[DEBUG]   (s) enableAssertions = true
[DEBUG]   (f) excludedEnvironmentVariables = []
[DEBUG]   (f) forkCount = 2C
[DEBUG]   (s) forkMode = once
[DEBUG]   (s) forkedProcessExitTimeoutInSeconds = 30
[DEBUG]   (s) junitArtifactName = junit:junit
[DEBUG]   (s) localRepository =       id: local
      url: file:///.m2/repository/
   layout: default
snapshots: [enabled => true, update => always]
 releases: [enabled => true, update => always]

[DEBUG]   (s) parallel = classes
[DEBUG]   (f) parallelMavenExecution = false
[DEBUG]   (s) parallelOptimized = true
[DEBUG]   (s) perCoreThreadCount = true

Thanks in advance.

Body:
You're using the wrong value for parallel. You have to set it to methods or both. Otherwise Surefire will run all tests of your runner class serially.

https://github.com/cucumber/cucumber-jvm/tree/main/cucumber-junit

Cucumber JUnit supports parallel execution of feature files across multiple threads. To enable this with maven set the parallel property to either methods or both.

<build>
    <plugins>
        <plugin>
            <artifactId>maven-surefire-plugin</artifactId>
            <!-- Use 2.22.1 or higher -->
            <version>${maven-surefire-plugin.version}</version>
            <configuration>
                <parallel>both</parallel>
                <threadCount>4</threadCount>
            </configuration>
        </plugin>
    </plugins>
</build>


问:
How to find seg fault which doesn't occur when using tools
I ask this because the seg fault doesn't occur in my C++ program if I run it with Valgrind or GDB. But it's easily reproducible once I run it stand-alone as it will seg fault without fail. I have commented out sections of code to the point of making it run, but I have still been unable to find the exact cause. I fear it's happening earlier on and just showing up late.

Update:
   To clarify, this is C++ 17 on Linux.

答:
Make sure you're not disabling core dumps (ulimit -c unlimited, though there are other config options that are relevant), then when your program crashes, you should get a core dump file.

Run gdb program core to analyze the core dump -- gdb will look like you've used it to run your program and it hit the signal that stopped it.  You can do a backtrace to see the stack, examine variables and memory, etc.


问:
C# Sorting a DataTableCollection by a common column in each table
I'm having some troubles figuring out how to sort a DataTableCollection.  The scenario is that each table in the collection would have the same schema and have a column called "JobNumber" which I want to sort on.  The data in these tables would need to be processed in that order.

Any suggestions?

答: Well it's easy to iterate throught the tables in the collection, but as for sorting each one, you may want to see:   http://msdn.microsoft.com/en-us/library/zk13kdh0(v=vs.71).aspx</p>


问:
Using scaler in Sklearn PIpeline and Cross validation
I previously saw a post with code like this:

```<code>scalar = StandardScaler()
clf = svm.LinearSVC()

pipeline = Pipeline([('transformer', scalar), ('estimator', clf)])

cv = KFold(n_splits=4)
scores = cross_val_score(pipeline, X, y, cv = cv)
</code>```

My understanding is that: when we apply scaler, we should use 3 out of the 4 folds to calculate mean and standard deviation, then we apply the mean and standard deviation to all 4 folds.

In the above code, how can I know that Sklearn is following the same strategy? On the other hand, if sklearn is not following the same strategy, which means sklearn would calculate the mean/std from all 4 folds. Would that mean I should not use the above codes?

I do like the above codes because it saves tons of time.

答:
In the example you gave, I would add an additional step using sklearn.model_selection.train_test_split:

```<code>folds = 4

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=(1/folds), random_state=0, stratify=y)

scalar = StandardScaler()
clf = svm.LinearSVC()

pipeline = Pipeline([('transformer', scalar), ('estimator', clf)])

cv = KFold(n_splits=(folds - 1))
scores = cross_val_score(pipeline, X_train, y_train, cv = cv)
</code>```

I think best practice is to only use the training data set (i.e., X_train, y_train) when tuning the hyperparameters of your model, and the test data set (i.e., X_test, y_test) should be used as a final check, to make sure your model isn't biased towards the validation folds. At that point you would apply the same scaler that you fit on your training data set to your testing data set.

Body:
I previously saw a post with code like this:

scalar = StandardScaler()
clf = svm.LinearSVC()

pipeline = Pipeline([('transformer', scalar), ('estimator', clf)])

cv = KFold(n_splits=4)
scores = cross_val_score(pipeline, X, y, cv = cv)

My understanding is that: when we apply scaler, we should use 3 out of the 4 folds to calculate mean and standard deviation, then we apply the mean and standard deviation to all 4 folds.

In the above code, how can I know that Sklearn is following the same strategy? On the other hand, if sklearn is not following the same strategy, which means sklearn would calculate the mean/std from all 4 folds. Would that mean I should not use the above codes?

I do like the above codes because it saves tons of time.

Body:
In the example you gave, I would add an additional step using sklearn.model_selection.train_test_split:

folds = 4

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=(1/folds), random_state=0, stratify=y)

scalar = StandardScaler()
clf = svm.LinearSVC()

pipeline = Pipeline([('transformer', scalar), ('estimator', clf)])

cv = KFold(n_splits=(folds - 1))
scores = cross_val_score(pipeline, X_train, y_train, cv = cv)

I think best practice is to only use the training data set (i.e., X_train, y_train) when tuning the hyperparameters of your model, and the test data set (i.e., X_test, y_test) should be used as a final check, to make sure your model isn't biased towards the validation folds. At that point you would apply the same scaler that you fit on your training data set to your testing data set.


Title: How to organzie data from a raw txt file with PHP

Body:
I have a raw data into a .txt file which i want to use to build a character stats out of it. Now sure if it will parse well below but i have into a textarea on my website (will leave a link below) where it is structured better than what it looks like here. Any ideas how can i put it to use with PHP? I want to use this data on a "character calculator" where people will choose a level and i want to dispaly the HP, Def, Str, Dex and all the other stats based on the level chosen. They are on the same row as the level so i was thinking either to read the level and see what's on the row next or maybe a whole different approach. I am open to ideas

https://www.diablo-2.net/articles/mercenaries#act-1-rogues

Lvl HP  Def Str Dex AR  MinD    MaxD    Res
1   40  10  32  41  205 1   2   0
2   40  17  33  43  215 1   2   0
3   45  26  35  45  235 1   3   0
4   54  34  36  47  257 1   3   2
5   63  43  37  49  279 1   3   4
6   72  51  38  51  301 1   3   6
7   81  60  40  53  323 2   4   8
8   90  68  41  55  345 2   4   10
9   99  77  42  57  367 2   4   12
10  108 85  43  59  389 2   4   14
11  117 94  45  61  411 3   5   16
12  126 102 46  63  433 3   5   18
13  135 111 47  65  455 3   5   20
14  144 119 48  67  477 3   5   22
15  153 128 50  69  499 4   6   24
16  162 136 51  71  521 4   6   26
17  171 145 52  73  543 4   6   28
18  180 153 53  75  565 4   6   30
19  189 162 55  77  587 5   7   32
20  198 170 56  79  609 5   7   34
21  207 179 57  81  631 5   7   36
22  216 187 58  83  653 5   7   38
23  225 196 60  85  675 6   8   40
24  234 204 61  87  697 6   8   42
25  243 213 62  89  719 6   8   44
26  252 221 63  91  741 6   8   46
27  261 230 65  93  763 7   9   48
28  270 238 66  95  785 7   9   50
29  279 247 67  97  807 7   9   52
30  288 255 68  99  829 7   9   54
31  297 264 70  101 851 8   10  56
32  306 272 71  103 873 8   10  58
33  315 281 72  105 895 8   10  60
34  324 289 73  107 917 8   10  62
35  333 298 75  109 939 9   11  64
36  342 306 77  111 961 9   11  66
37  360 322 78  113 995 9   11  67
38  378 337 79  115 1029    10  12  69
39  396 353 80  117 1063    10  12  71
40  414 368 82  119 1097    11  13  73
41  432 384 83  121 1131    11  13  74
42  450 399 84  123 1165    12  14  76
43  468 415 85  125 1199    12  14  78
44  486 430 87  127 1233    13  15  80
45  504 446 88  129 1267    13  15  81
46  522 461 89  131 1301    14  16  83
47  540 477 90  133 1335    14  16  85
48  558 492 92  135 1369    15  17  87
49  576 508 93  137 1403    15  17  88
50  594 523 94  139 1437    16  18  90
51  612 539 95  141 1471    16  18  92
52  630 554 97  143 1505    17  19  94
53  648 570 98  145 1539    17  19  95
54  666 585 99  147 1573    18  20  97
55  684 601 100 149 1607    18  20  99
56  702 616 102 151 1641    19  21  101
57  720 632 103 153 1675    19  21  102
58  738 647 104 155 1709    20  22  104
59  756 663 105 157 1743    20  22  106
60  774 678 107 159 1777    21  23  108
61  792 694 108 161 1811    21  23  109
62  810 709 109 163 1845    22  24  111
63  828 725 110 165 1879    22  24  113
64  846 740 112 167 1913    23  25  115
65  864 756 113 169 1947    23  25  116
66  882 771 114 171 1981    24  26  118
67  900 787 116 173 2015    25  27  121
68  930 809 117 175 2061    25  27  122
69  960 832 118 177 2107    26  28  123
70  990 854 119 179 2153    27  29  124
71  1020    877 121 181 2199    28  30  126
72  1050    899 122 183 2245    28  30  127
73  1080    922 123 185 2291    29  31  128
74  1110    944 124 187 2337    30  32  129
75  1140    967 126 189 2383    31  33  131
76  1170    989 127 191 2429    31  33  132
77  1200    1012    128 193 2475    32  34  133
78  1230    1034    129 195 2521    33  35  134
79  1260    1057    131 197 2567    34  36  136
80  1290    1079    132 199 2613    34  36  137
81  1320    1102    133 201 2659    35  37  138
82  1350    1124    134 203 2705    36  38  139
83  1380    1147    136 205 2751    37  39  141
84  1410    1169    137 207 2797    37  39  142
85  1440    1192    138 209 2843    38  40  143
86  1470    1214    139 211 2889    39  41  144
87  1500    1237    141 213 2935    40  42  146
88  1530    1259    142 215 2981    40  42  147
89  1560    1282    143 217 3027    41  43  148
90  1590    1304    144 219 3073    42  44  149
91  1620    1327    146 221 3119    43  45  151
92  1650    1349    147 223 3165    43  45  152
93  1680    1372    148 225 3211    44  46  153
94  1710    1394    149 227 3257    45  47  154
95  1740    1417    151 229 3303    46  48  155
96  1770    1439    152 231 3349    46  48  157
97  1800    1462    153 233 3395    47  49  158
98  1830    1484    154 235 3441    48  50  159
Lvl HP  Def Str Dex AR  MinD    MaxD    Res

Edit: I checked the suggested idea by E. Safa Tok and I did some tests using this:

$level = 98;
echo "
";
echo "
";
foreach ($line as $key=>$value) {
    echo "
";
    echo "" . $key . "	";
    echo "" . $result[$level][$key] . "	";
    echo "
";
}
echo "
";

It works!!!! Thanks a lot.

Body:
I wrote a piece of code to split your input to array. After that process, also you can generate JSON formatted array with json_decode function.

<?php

$input = <<<EOT
Lvl HP  Def Str Dex AR  MinD    MaxD    Res
1   40  10  32  41  205 1   2   0
2   40  17  33  43  215 1   2   0
3   45  26  35  45  235 1   3   0
4   54  34  36  47  257 1   3   2
5   63  43  37  49  279 1   3   4
6   72  51  38  51  301 1   3   6
7   81  60  40  53  323 2   4   8
8   90  68  41  55  345 2   4   10
9   99  77  42  57  367 2   4   12
10  108 85  43  59  389 2   4   14
11  117 94  45  61  411 3   5   16
12  126 102 46  63  433 3   5   18
13  135 111 47  65  455 3   5   20
14  144 119 48  67  477 3   5   22
15  153 128 50  69  499 4   6   24
16  162 136 51  71  521 4   6   26
17  171 145 52  73  543 4   6   28
18  180 153 53  75  565 4   6   30
19  189 162 55  77  587 5   7   32
20  198 170 56  79  609 5   7   34
21  207 179 57  81  631 5   7   36
22  216 187 58  83  653 5   7   38
23  225 196 60  85  675 6   8   40
24  234 204 61  87  697 6   8   42
25  243 213 62  89  719 6   8   44
26  252 221 63  91  741 6   8   46
27  261 230 65  93  763 7   9   48
28  270 238 66  95  785 7   9   50
29  279 247 67  97  807 7   9   52
30  288 255 68  99  829 7   9   54
31  297 264 70  101 851 8   10  56
32  306 272 71  103 873 8   10  58
33  315 281 72  105 895 8   10  60
34  324 289 73  107 917 8   10  62
35  333 298 75  109 939 9   11  64
36  342 306 77  111 961 9   11  66
37  360 322 78  113 995 9   11  67
38  378 337 79  115 1029    10  12  69
39  396 353 80  117 1063    10  12  71
40  414 368 82  119 1097    11  13  73
41  432 384 83  121 1131    11  13  74
42  450 399 84  123 1165    12  14  76
43  468 415 85  125 1199    12  14  78
44  486 430 87  127 1233    13  15  80
45  504 446 88  129 1267    13  15  81
46  522 461 89  131 1301    14  16  83
47  540 477 90  133 1335    14  16  85
48  558 492 92  135 1369    15  17  87
49  576 508 93  137 1403    15  17  88
50  594 523 94  139 1437    16  18  90
51  612 539 95  141 1471    16  18  92
52  630 554 97  143 1505    17  19  94
53  648 570 98  145 1539    17  19  95
54  666 585 99  147 1573    18  20  97
55  684 601 100 149 1607    18  20  99
56  702 616 102 151 1641    19  21  101
57  720 632 103 153 1675    19  21  102
58  738 647 104 155 1709    20  22  104
59  756 663 105 157 1743    20  22  106
60  774 678 107 159 1777    21  23  108
61  792 694 108 161 1811    21  23  109
62  810 709 109 163 1845    22  24  111
63  828 725 110 165 1879    22  24  113
64  846 740 112 167 1913    23  25  115
65  864 756 113 169 1947    23  25  116
66  882 771 114 171 1981    24  26  118
67  900 787 116 173 2015    25  27  121
68  930 809 117 175 2061    25  27  122
69  960 832 118 177 2107    26  28  123
70  990 854 119 179 2153    27  29  124
71  1020    877 121 181 2199    28  30  126
72  1050    899 122 183 2245    28  30  127
73  1080    922 123 185 2291    29  31  128
74  1110    944 124 187 2337    30  32  129
75  1140    967 126 189 2383    31  33  131
76  1170    989 127 191 2429    31  33  132
77  1200    1012    128 193 2475    32  34  133
78  1230    1034    129 195 2521    33  35  134
79  1260    1057    131 197 2567    34  36  136
80  1290    1079    132 199 2613    34  36  137
81  1320    1102    133 201 2659    35  37  138
82  1350    1124    134 203 2705    36  38  139
83  1380    1147    136 205 2751    37  39  141
84  1410    1169    137 207 2797    37  39  142
85  1440    1192    138 209 2843    38  40  143
86  1470    1214    139 211 2889    39  41  144
87  1500    1237    141 213 2935    40  42  146
88  1530    1259    142 215 2981    40  42  147
89  1560    1282    143 217 3027    41  43  148
90  1590    1304    144 219 3073    42  44  149
91  1620    1327    146 221 3119    43  45  151
92  1650    1349    147 223 3165    43  45  152
93  1680    1372    148 225 3211    44  46  153
94  1710    1394    149 227 3257    45  47  154
95  1740    1417    151 229 3303    46  48  155
96  1770    1439    152 231 3349    46  48  157
97  1800    1462    153 233 3395    47  49  158
98  1830    1484    154 235 3441    48  50  159
Lvl HP  Def Str Dex AR  MinD    MaxD    Res
EOT;

// Split to lines
$lines = explode("\n", $input);
$result = array();

// for each line
foreach ($lines as $line) {
    // parse with space char
    $parsed_line = explode(" ", $line);

    $index = 0;
    foreach ($parsed_line as $i) {
        if($i == " " or strlen($i)==0){
            array_splice($parsed_line, $index, 1);
            // if item popped, reduce index
            $index -= 1;
        }
        $index += 1;
    }
    // create array of line to add result array.
    $line = array(
        "Lvl" => $parsed_line[0],
        "HP" => $parsed_line[1],
        "Def"   => $parsed_line[2],
        "Str"  => $parsed_line[3],
        "Dex" => $parsed_line[4],
        "AR" => $parsed_line[5],
        "MinD" => $parsed_line[6],
        "MaxD" => $parsed_line[7],
        "Res" => $parsed_line[8],
    );
    array_push($result, $line);
}
// can view whole array with:
//var_dump($result);

// Example of usage of item selection method 9 -> Lvl. Def -> parameter.
echo $result[9]['Def'];
?>


问:
How to combine two composed applicative functors?
I have two composed applicative functors Maybe [Integer] and want to combine them with <$>/<*> but I am stuck with applying the applicative operation. The following does not typecheck:

```<code>(<*>) (<*>) ((<$>) ((+) <$>) $ Just [1,2,3]) $ Just [4,5,6]
</code>```

Expected result:

```<code>Just [5,6,7,6,7,8,7,8,9]
</code>```

The functor part works, i.e. the intermediate value passed to <*> as the first argument is Just [Integer -> Integer]. I am used to S-expressions so I have a hard time with the Haskell syntax. I know of Compose but I am interested in the mere composition wihtout abstraction.

答:
The composition of two Applicatives is always an Applicative (unlike the case for Monad).

We can use this to our advantage here with the Compose newtype from Data.Functor.Compose:

```<code>newtype Compose f g a = Compose { getCompose :: f (g a) }
</code>```

It requires a bit of wrapping, but this kind of solution could be useful under the right circumstances:

```<code>example :: Maybe [Int]
example =
  getCompose ((+) <$> Compose (Just [1,2,3]) <*> Compose (Just [4,5,6]))
</code>```

Body:
I have two composed applicative functors Maybe [Integer] and want to combine them with <$>/<*> but I am stuck with applying the applicative operation. The following does not typecheck:

(<*>) (<*>) ((<$>) ((+) <$>) $ Just [1,2,3]) $ Just [4,5,6]

Expected result:

Just [5,6,7,6,7,8,7,8,9]

The functor part works, i.e. the intermediate value passed to <*> as the first argument is Just [Integer -> Integer]. I am used to S-expressions so I have a hard time with the Haskell syntax. I know of Compose but I am interested in the mere composition wihtout abstraction.

Body:
The composition of two Applicatives is always an Applicative (unlike the case for Monad).

We can use this to our advantage here with the Compose newtype from Data.Functor.Compose:

newtype Compose f g a = Compose { getCompose :: f (g a) }

It requires a bit of wrapping, but this kind of solution could be useful under the right circumstances:

example :: Maybe [Int]
example =
  getCompose ((+) <$> Compose (Just [1,2,3]) <*> Compose (Just [4,5,6]))


答:
Good bad old printf debugging :). Make your program drop breadcrumbs (in the form of console output, or writing to the log) in the general vicinity of the crash point. As you get a better idea of where the crash point is, make breadcrumbs tighter. Assuming your crash is reasonably deterministic, this will converge on the crash point eventually.

Another technique, install a signal handler for SIGSEGV. Once the signal fires, dump the crash point registers, then use something like addr2line to translate the IP address to the source line. You'd need the starting address of the module.

Title: How to find seg fault which doesn't occur when using tools

Body:
I ask this because the seg fault doesn't occur in my C++ program if I run it with Valgrind or GDB. But it's easily reproducible once I run it stand-alone as it will seg fault without fail. I have commented out sections of code to the point of making it run, but I have still been unable to find the exact cause. I fear it's happening earlier on and just showing up late.

Update:
   To clarify, this is C++ 17 on Linux.


问:
Android onTouchListeners for seperate views
I am trying to drag and drop views around on my screen.  I have an array of views and id like to set an on click listener for each one so that I know which piece the user is trying to interact with.  For some reason the listener will only set to whichever piece is placed last, and from there behaves like i want it too.  How do I make it so that each view has its own individual on click handler.

Here is the code:

```<code>class MainActivity : AppCompatActivity() {

val touch = TouchListener()
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    val mainScreen = findViewById<RelativeLayout>(R.id.rellayout)

    for ( i in 0 .. 4)
    {
        for (j in 0 .. 4)
        {
            val testSquare = Square(this, (1+2*i)*54f , (1+2*j)*54f, (PI/4).toFloat())

            testSquare.setOnTouchListener(touch)
            mainScreen.addView(testSquare)
        }
    }

}
}
</code>```

答:
you can implements onTochListener then switch in different view like this.

```<code>class Activity : AppCompatActivity(), View.OnTouchListener {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_)
    val mainScreen = findViewById<RelativeLayout>(R.id.rellayout)

    for ( i in 0 .. 4)
    {
        for (j in 0 .. 4)
        {
            val testSquare = Square(this, (1+2*i)*54f , (1+2*j)*54f, (PI/4).toFloat())

            testSquare.setOnTouchListener(this)
            mainScreen.addView(testSquare)
        }
    }
}

override fun onTouch(view: View, motionEvent: MotionEvent): Boolean {
    when (view.id) {
        R.id.death // these are example ids
        -> {
        }
        R.id.daimajia_indicator_wrapper -> {
        }
        R.id.Accordion -> {
        }
    }//do code
    //do code
    //do code
    return false
}
</code>```

}

Body:
I am trying to drag and drop views around on my screen.  I have an array of views and id like to set an on click listener for each one so that I know which piece the user is trying to interact with.  For some reason the listener will only set to whichever piece is placed last, and from there behaves like i want it too.  How do I make it so that each view has its own individual on click handler.

Here is the code:

class MainActivity : AppCompatActivity() {

val touch = TouchListener()
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    val mainScreen = findViewById<RelativeLayout>(R.id.rellayout)

    for ( i in 0 .. 4)
    {
        for (j in 0 .. 4)
        {
            val testSquare = Square(this, (1+2*i)*54f , (1+2*j)*54f, (PI/4).toFloat())

            testSquare.setOnTouchListener(touch)
            mainScreen.addView(testSquare)
        }
    }

}
}

Body:
you can implements onTochListener then switch in different view like this.

class Activity : AppCompatActivity(), View.OnTouchListener {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_)
    val mainScreen = findViewById<RelativeLayout>(R.id.rellayout)

    for ( i in 0 .. 4)
    {
        for (j in 0 .. 4)
        {
            val testSquare = Square(this, (1+2*i)*54f , (1+2*j)*54f, (PI/4).toFloat())

            testSquare.setOnTouchListener(this)
            mainScreen.addView(testSquare)
        }
    }
}

override fun onTouch(view: View, motionEvent: MotionEvent): Boolean {
    when (view.id) {
        R.id.death // these are example ids
        -> {
        }
        R.id.daimajia_indicator_wrapper -> {
        }
        R.id.Accordion -> {
        }
    }//do code
    //do code
    //do code
    return false
}

}


问:
angular - how to display array as multiple lines in a table cell
Sorry I am new to angular and trying to learning some basics while making some app myself.

I have the following that that outputs an array in the table cell
TEST1,TEST2,TEST3

My goal is to make it to display as

TEST1

TEST2

TEST3

getStatus(element.message) returns an array that is constructed by

array.push(match[0]) in a for loop

```<code>    <ng-container matColumnDef="ticketStatus">
      <th mat-header-cell *matHeaderCellDef class="text-center w-6">
        Status
      </th>
      <td mat-cell *matCellDef="let element">{{ getStatus(element.message) }}</td>
    </ng-container>
</code>```

答:
I noticed that you are using Angular material. What you could do is populating your cells using a foreach on displayedColumns?

```<code><table cdk-table [dataSource]="dataSource">

  <ng-container *ngFor="let col of displayedColumns" cdkColumnDef="{{ col }}">
     <th cdk-header-cell *cdkHeaderCellDef>{{ col }}</th>
     <td cdk-cell *cdkCellDef="let row; let i = index"> {{ getFieldValue(i, col) }}   </td>
   </ng-container>

   <tr cdk-header-row *cdkHeaderRowDef="displayedColumns"></tr>
   <tr cdk-row *cdkRowDef="let row; columns: displayedColumns;"></tr>
</table>
</code>```

Please note: the example is a CDK-table, but it is almost similar to Angular Material Table since it is derived from CdkTable.

I created a Stackblitz. Maybe you can get some inspiration:

https://stackblitz.com/edit/angular-ivy-bes8zf

Body:
Sorry I am new to angular and trying to learning some basics while making some app myself.

I have the following that that outputs an array in the table cell
TEST1,TEST2,TEST3

My goal is to make it to display as

TEST1

TEST2

TEST3

getStatus(element.message) returns an array that is constructed by

array.push(match[0]) in a for loop

    <ng-container matColumnDef="ticketStatus">

        Status

      {{ getStatus(element.message) }}
    </ng-container>

Body:
I noticed that you are using Angular material. What you could do is populating your cells using a foreach on displayedColumns?

<table cdk-table [dataSource]="dataSource">

  <ng-container *ngFor="let col of displayedColumns" cdkColumnDef="{{ col }}">
     <th cdk-header-cell *cdkHeaderCellDef>{{ col }}</th>
     <td cdk-cell *cdkCellDef="let row; let i = index"> {{ getFieldValue(i, col) }}   </td>
   </ng-container>

   <tr cdk-header-row *cdkHeaderRowDef="displayedColumns"></tr>
   <tr cdk-row *cdkRowDef="let row; columns: displayedColumns;"></tr>
</table>

Please note: the example is a CDK-table, but it is almost similar to Angular Material Table since it is derived from CdkTable.

I created a Stackblitz. Maybe you can get some inspiration:

https://stackblitz.com/edit/angular-ivy-bes8zf


问:
AWS Elastic BeanStalk + Wordpress URL rewrite Issue
Hey Guys i deployed wordpress with Elastic Bean Stalk ( i have nginx + RDS ) but only wordpress home page working fine but URL rewrite not working. ( wordpress home page working fine & wordpress from NON google friedly URL works fine ) problem is with URL rewrite anyone has any idea how we can solve this OR how we can install APACHE on AWS EBS ( i am using EBS +  RDS + Code Pipeline )</p>

答:
The AWS provides official whitepapers and guides on how to properly setup and run Wordpress on Beanstalk. I put the links to them, since from your question it is not clear if you followed any of them and why they don't work, nor why they are not suited for your use case:

Build a WordPress Website Deploy and host a production-ready WordPress website on AWS

Deploying a high-availability WordPress website with an external Amazon RDS database to Elastic Beanstalk

Deploying WordPress with AWS Elastic Beanstalk

WordPress: Best Practices on AWS

If your needs are different, updating the question with more details and explanations would be useful to provide more detailed answer.


问:
How to covert simple date-string to ISO-date format in python?
I'm able to convert ISO-date format to simple date format as below.

```<code>from dateutil.parser import parse
date_string = '2018-03-12T10:12:45Z'
dt = parse(date_string)
print(dt.date())    #prints 2018-03-12
print(dt.time())    #prints 10:12:45
print(dt.tzinfo)    #prints tzutc()
</code>```

How to convert it other way ? examples shown below

```<code>If input is `2018-03-12` , then output should be `2018-03-12T00:00:00Z`
If input is `2018-03-12-10-12-45` , then output should be `2018-03-12T10:12:45Z`
</code>```

I am accepting two inputs (format : yyyy-mm-dd) and trying to form date-range between from-date and to-date in iso-format. How can I do that (as below) ?

```<code>input1 : `2018-03-12` , output1 : `2018-03-12T00:00:000Z` (12AM, 24-hr format)
input2 : `2018-03-15` , output2 : `2018-03-15T23:59:000Z` (11:59PM, 24-hr format)
</code>```

Solution:

```<code>import dateutil.parser
from datetime import datetime
import time
input1="2018-03-12"
input2="2018-03-15"+" 01:02:03.004"
output1=dateutil.parser.parse(input1)
output2=dateutil.parser.parse(input2)
output1 = "%s:%06.3f%s" % (output1.strftime('%Y-%m-%dT%H:%M'),float("%06.3f" % (output1.second+output1.microsecond / 1e6)),output1.strftime('Z'))
output2 = "%s:%06.3f%s" % (output2.strftime('%Y-%m-%dT%H:%M'),float("%06.3f" % (output2.second+output2.microsecond / 1e6)),output2.strftime('Z'))
print(output1)
print(output2)
</code>```

Output:

```<code>2018-03-12T00:00:00.000Z
2018-03-15T01:02:03.004Z
</code>```

答:
you can use datetime module (if there is only 2 expected patterns, you can simply do try-except)

```<code>str_date = '2018-03-12'

def convert(x):
    try:
        return datetime.strptime(x, '%Y-%m-%d-%H-%M-%S')
    except ValueError:
        return datetime.strptime(x, '%Y-%m-%d')

convert(str_date)
</code>```

Body:
I'm able to convert ISO-date format to simple date format as below.

from dateutil.parser import parse
date_string = '2018-03-12T10:12:45Z'
dt = parse(date_string)
print(dt.date())    #prints 2018-03-12
print(dt.time())    #prints 10:12:45
print(dt.tzinfo)    #prints tzutc()

How to convert it other way ? examples shown below

If input is `2018-03-12` , then output should be `2018-03-12T00:00:00Z`
If input is `2018-03-12-10-12-45` , then output should be `2018-03-12T10:12:45Z`

I am accepting two inputs (format : yyyy-mm-dd) and trying to form date-range between from-date and to-date in iso-format. How can I do that (as below) ?

input1 : `2018-03-12` , output1 : `2018-03-12T00:00:000Z` (12AM, 24-hr format)
input2 : `2018-03-15` , output2 : `2018-03-15T23:59:000Z` (11:59PM, 24-hr format)

Solution:

import dateutil.parser
from datetime import datetime
import time
input1="2018-03-12"
input2="2018-03-15"+" 01:02:03.004"
output1=dateutil.parser.parse(input1)
output2=dateutil.parser.parse(input2)
output1 = "%s:%06.3f%s" % (output1.strftime('%Y-%m-%dT%H:%M'),float("%06.3f" % (output1.second+output1.microsecond / 1e6)),output1.strftime('Z'))
output2 = "%s:%06.3f%s" % (output2.strftime('%Y-%m-%dT%H:%M'),float("%06.3f" % (output2.second+output2.microsecond / 1e6)),output2.strftime('Z'))
print(output1)
print(output2)

Output:

2018-03-12T00:00:00.000Z
2018-03-15T01:02:03.004Z

Body:
you can use datetime module (if there is only 2 expected patterns, you can simply do try-except)

str_date = '2018-03-12'

def convert(x):
    try:
        return datetime.strptime(x, '%Y-%m-%d-%H-%M-%S')
    except ValueError:
        return datetime.strptime(x, '%Y-%m-%d')

convert(str_date)


问:
JSX element type 'string' is not a constructor function for JSX elements. Typescript
So i have been working on a reusable icon element that I can call in any class and just pass a string <Icon name="chat" /> that contain the specific colour of the icon .. This error is the result of the previous question I raised .. you can find the link below

I raised a question early before this:

icon.ts file

```<code>const iconsList = {
    heart: '',
    star: '',
    like: '',
    dislike: '',
    flash: '',
    marker: '',
    filter: '',
    user: '',
    circle: '',
    hashtag: '',
    calendar: '',
    chevronLeft: '',
    optionsV: '',
    optionsH: '',
    chat: '',
    explore: ''
};

interface Props{
    name: keyof typeof iconsList;
}

const Icon = ({name }: Props) => {
    let icon = iconsList[name];
    icon = icon.substr(3);
    icon = String.fromCharCode(parseInt(icon, 16));

    return icon;
 };

export default Icon;
</code>```

profile.tsx

```<code>import React from 'react';
import styles from '../assets/styles';

import {
  ScrollView,
  View,
  Text,
  ImageBackground,
  TouchableOpacity
} from 'react-native';
import Icon from '../components/Icon';
const Profile = () => {
return (

<TouchableOpacity>
  <Text style={styles.topIconLeft}>
    <Icon name="chevronLeft" />
  </Text>
</TouchableOpacity>

);
}
</code>```

This line of <Icon name="chevronLeft" />complains with an error of "JSX element type 'string' is not a constructor function for JSX elements.ts(2605)

Screenshot :

答:
string is not a valid return value for a react component. A react component always has to return a ReactDOM element or a Fragment, that implements the render method. You can try

```<code>const Icon : React.SFC<Props> = ({name }: Props) => {
    let icon = iconsList[name];
    icon = icon.substr(3);
    icon = String.fromCharCode(parseInt(icon, 16));

    return <>{icon}</>;
 };
</code>```

And actually it won't hurt if you renamed icon.ts to icon.tsx. Depending on your compiler settings the <>{icon}</> part might not get recognized correctly as JSX markup.

Body:
So i have been working on a reusable icon element that I can call in any class and just pass a string <Icon name="chat" /> that contain the specific colour of the icon .. This error is the result of the previous question I raised .. you can find the link below

I raised a question early before this:

icon.ts file

const iconsList = {
    heart: '',
    star: '',
    like: '',
    dislike: '',
    flash: '',
    marker: '',
    filter: '',
    user: '',
    circle: '',
    hashtag: '',
    calendar: '',
    chevronLeft: '',
    optionsV: '',
    optionsH: '',
    chat: '',
    explore: ''
};

interface Props{
    name: keyof typeof iconsList;
}

const Icon = ({name }: Props) => {
    let icon = iconsList[name];
    icon = icon.substr(3);
    icon = String.fromCharCode(parseInt(icon, 16));

    return icon;
 };

export default Icon;

profile.tsx

import React from 'react';
import styles from '../assets/styles';

import {
  ScrollView,
  View,
  Text,
  ImageBackground,
  TouchableOpacity
} from 'react-native';
import Icon from '../components/Icon';
const Profile = () => {
return (

<TouchableOpacity>
  <Text style={styles.topIconLeft}>
    <Icon name="chevronLeft" />
  </Text>
</TouchableOpacity>

);
}

This line of <Icon name="chevronLeft" />complains with an error of "JSX element type 'string' is not a constructor function for JSX elements.ts(2605)

Screenshot :

Body:
string is not a valid return value for a react component. A react component always has to return a ReactDOM element or a Fragment, that implements the render method. You can try

const Icon : React.SFC<Props> = ({name }: Props) => {
    let icon = iconsList[name];
    icon = icon.substr(3);
    icon = String.fromCharCode(parseInt(icon, 16));

    return <>{icon}</>;
 };

And actually it won't hurt if you renamed icon.ts to icon.tsx. Depending on your compiler settings the <>{icon}</> part might not get recognized correctly as JSX markup.


问:
How to filter the Eclipse Outline View to show only Functions
I want to have the 'Outline view' in Eclipse in the CDT (so for a C project) show me only function names. So no enums, include files, macros, etc...

There are some options in the 'Filters...' menu, but none that make it possible to only show functions.

Can anybody help me?

答: You can click on 'Hide Fields' (third option in picture) to display just the functions (Eclipse Version: 2019-03 (4.11))


问:
GAE: managing dev and production versions of my app
There are a lot of things I need to do before uploading my production app to GAE. Its becoming very tedious and error-prone, and I would like to know some best-practice how to handle following requirements, and if some tools already exist for doing this:

Dev and test environment on my local machine: want to use debug versions of my javascript files, Production: want to minify the files and also concatenate them into 1. E.g.: given this code in mytemplate.html

```<code><script src="script1.js"></script>
<script src="script2.js"></script>
<script src="script3.js"></script>
<script src="script4.js"></script>
<script src="script5.js"></script>
</code>```

Wanted: some process to automatically minify the files, concatenate them into 1, and edit the code above so that it becomes:

```<code><script src="mytemplate.js"></script>
</code>```

Dev and test: use a settings.dev.py

Production: use settings.py

Some way to automatically switch to settings.py when pushing to production. i.e., I don't to manually edit all the py files and change all references to settings.dev.py to settings.py. Is a config file the recommended way to do this? I change a setting in my config.py file before pushing to production, and then the rest of the code picks up the right settings.py? Also, in python is the config file a .py file, or is it something else usually - i.e., what is the norm? (in .net we usually use xml for storing configurations)

答:
So you can detect whether your app is running in dev or production as follows:

```<code>import os
DEV = os.environ['SERVER_SOFTWARE'].startswith('Development')
</code>```

Pass this bool along to your Django templates, and write conditionals when you want behavior to vary:

```<code>{% if DEV %}
  <script src="script1.js"></script>
  <script src="script2.js"></script>
  <script src="script3.js"></script>
  <script src="script4.js"></script>
  <script src="script5.js"></script>
{% else %}
  <script src="mytemplate.js"></script>
{% endif %}
</code>```

To handle minification at the last minute, write a custom deployment script that runs any pre-deployment tasks first and then calls appcfg.py update. When you want to deploy, run your deployment wrapper instead of calling appcfg.py directly.

You can handle your settings.py in a few different ways. Use one settings file with per-environment conditionals, import different settings files depending on the environment, or swap in the production file as part of your deployment wrapper.

Body:
There are a lot of things I need to do before uploading my production app to GAE. Its becoming very tedious and error-prone, and I would like to know some best-practice how to handle following requirements, and if some tools already exist for doing this:

Dev and test environment on my local machine: want to use debug versions of my javascript files, Production: want to minify the files and also concatenate them into 1. E.g.: given this code in mytemplate.html

Wanted: some process to automatically minify the files, concatenate them into 1, and edit the code above so that it becomes:

Dev and test: use a settings.dev.py

Production: use settings.py

Some way to automatically switch to settings.py when pushing to production. i.e., I don't to manually edit all the py files and change all references to settings.dev.py to settings.py. Is a config file the recommended way to do this? I change a setting in my config.py file before pushing to production, and then the rest of the code picks up the right settings.py? Also, in python is the config file a .py file, or is it something else usually - i.e., what is the norm? (in .net we usually use xml for storing configurations)

Body:
So you can detect whether your app is running in dev or production as follows:

import os
DEV = os.environ['SERVER_SOFTWARE'].startswith('Development')

Pass this bool along to your Django templates, and write conditionals when you want behavior to vary:

{% if DEV %}
  <script src="script1.js"></script>
  <script src="script2.js"></script>
  <script src="script3.js"></script>
  <script src="script4.js"></script>
  <script src="script5.js"></script>
{% else %}
  <script src="mytemplate.js"></script>
{% endif %}

To handle minification at the last minute, write a custom deployment script that runs any pre-deployment tasks first and then calls appcfg.py update. When you want to deploy, run your deployment wrapper instead of calling appcfg.py directly.

You can handle your settings.py in a few different ways. Use one settings file with per-environment conditionals, import different settings files depending on the environment, or swap in the production file as part of your deployment wrapper.


问:
Program not reading '?' after separation of strings by '?' as well as '.'
I have an original text file that is one very long string. I separated this file / string using '?' and full stop '.' in order to be able to go through it sentence by sentence, and I saved these sentences / strings into a list called sentences_list.

I'm reading the strings in that list, in order to count the number of '?' symbols but it's not picking up the '?' symbol at all. How can this be?
Here is the code for the function that looks for the '?' :

```<code>def count_question_symbols(list):
    count = 0
    for item in list:
        if "?" in item:
            count += 1
    print("Questions asked", count, "times")

count_question_symbols(sentences_list)
</code>```

And here is the code where the 'sentences_list' is created:

```<code>file = open("classic_cars.txt", "r")
sentences_list = []
for line in file:
    sentences_list.extend(re.split(r"[?\.]\s*", line))
</code>```

答:
re.split is mostly an over complication of the goal.
In python, files can be converted to strings rather easily.
The count method is great when testing if a substring is contained within a string.

```<code>if __name__ == "__main__":
    with open("file.txt", "r") as f:
        count = f.read().count("?")
        print("Num question marks: " + str(count))
        # or in 3.6+
        print(f"Num question marks: {count}")
</code>```

Note that a happy accident of the function provided is that it works on most sizes of strings. (not just whole lines from files)

Body:
I have an original text file that is one very long string. I separated this file / string using '?' and full stop '.' in order to be able to go through it sentence by sentence, and I saved these sentences / strings into a list called sentences_list.

I'm reading the strings in that list, in order to count the number of '?' symbols but it's not picking up the '?' symbol at all. How can this be?
Here is the code for the function that looks for the '?' :

def count_question_symbols(list):
    count = 0
    for item in list:
        if "?" in item:
            count += 1
    print("Questions asked", count, "times")

count_question_symbols(sentences_list)

And here is the code where the 'sentences_list' is created:

file = open("classic_cars.txt", "r")
sentences_list = []
for line in file:
    sentences_list.extend(re.split(r"[?\.]\s*", line))

Body:
re.split is mostly an over complication of the goal.
In python, files can be converted to strings rather easily.
The count method is great when testing if a substring is contained within a string.

if __name__ == "__main__":
    with open("file.txt", "r") as f:
        count = f.read().count("?")
        print("Num question marks: " + str(count))
        # or in 3.6+
        print(f"Num question marks: {count}")

Note that a happy accident of the function provided is that it works on most sizes of strings. (not just whole lines from files)


问:
Nuxt App Output Error when trying to Create
I want to initialize a Nuxt Project using the command

yarn create nuxt-app <project-name>

i get this error:

```<code>C:\Users\AbdulAzeez\AppData\Local\Yarn\Data\global\node_modules\sao\lib\installPackages.js:108
        throw new SAOError(`Failed to install ${packageName} in ${cwd}`)
        ^

SAOError: Failed to install packages in C:\Users\AbdulAzeez\Desktop\vue-sax-demo
    at ChildProcess.<anonymous> (C:\Users\AbdulAzeez\AppData\Local\Yarn\Data\global\node_modules\sao\lib\installPackages.js:108:15)
    at ChildProcess.emit (events.js:315:20)
    at ChildProcess.cp.emit (C:\Users\AbdulAzeez\AppData\Local\Yarn\Data\global\node_modules\sao\node_modules\cross-spawn\lib\enoent.js:34:29)
    at maybeClose (internal/child_process.js:1051:16)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:287:5) {
  __sao: true
}
error Command failed.
Exit code: 1
Command: C:\Users\AbdulAzeez\AppData\Roaming\npm\bin\create-nuxt-app
Arguments: vue-sax-demo
Directory: C:\Users\AbdulAzeez\Desktop
Output:
</code>```

This is not the first time, i'm creating a nuxt-project, I'm just getting this Error recently!

I even tried using npx, the same Error

答:
Try to use the LTS version of node.js, the v14 is not stable. The current LTS version is 12.17.0 or see this link for the official LTS version if you are seen this in the future ( https://nodejs.org/en/download/)

after that run >>>

```<code>npx create-nuxt-app <project-name>
</code>```

Body:
I want to initialize a Nuxt Project using the command

yarn create nuxt-app <project-name>

i get this error:

C:\Users\AbdulAzeez\AppData\Local\Yarn\Data\global\node_modules\sao\lib\installPackages.js:108
        throw new SAOError(`Failed to install ${packageName} in ${cwd}`)
        ^

SAOError: Failed to install packages in C:\Users\AbdulAzeez\Desktop\vue-sax-demo
    at ChildProcess.<anonymous> (C:\Users\AbdulAzeez\AppData\Local\Yarn\Data\global\node_modules\sao\lib\installPackages.js:108:15)
    at ChildProcess.emit (events.js:315:20)
    at ChildProcess.cp.emit (C:\Users\AbdulAzeez\AppData\Local\Yarn\Data\global\node_modules\sao\node_modules\cross-spawn\lib\enoent.js:34:29)
    at maybeClose (internal/child_process.js:1051:16)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:287:5) {
  __sao: true
}
error Command failed.
Exit code: 1
Command: C:\Users\AbdulAzeez\AppData\Roaming\npm\bin\create-nuxt-app
Arguments: vue-sax-demo
Directory: C:\Users\AbdulAzeez\Desktop
Output:

This is not the first time, i'm creating a nuxt-project, I'm just getting this Error recently!

I even tried using npx, the same Error

Body:
Try to use the LTS version of node.js, the v14 is not stable. The current LTS version is 12.17.0 or see this link for the official LTS version if you are seen this in the future ( https://nodejs.org/en/download/)

after that run >>>

npx create-nuxt-app <project-name>


问:
ASP.NET Core and SAML authentication
I should implement authentication by ADFS on my ASP.NET Core 3 application. This application should use SAML2 for it. I found nice example of Sustainsys.Saml2.AspNetCore2 usages at this repository, but if I correctly understand SamlController generates JWT-token by it self.

Can anybody explain me, how to get token from ADFS?

答:
You need a SAML client side stack.

Sustainsys is one option. Use the stack to send an AuthnRequest. You then authenticate on ADFS and ADFS will return a SAML XML token (not a JWT).

Use the stack to decode it and get the assertions (claims).

Title: ASP.NET Core and SAML authentication


问:
List multiplication in NetLogo
I'm modeling the distribution of hoverflies in an aphid-infested crop field with flower margins. I have a couple of lists which are setup as patch variables as follows:

```<code>set nl n-values 20 [0];; number of larvae per age (in days)
set il n-values 20 [0.0001];; individual larvae growth per age (in days)
set il_growth n-values 20 [0];; growth of larvae per age (in days)
</code>```

I gave the value 0.0001 instead of 0 because previously I got errors regarding the 0.

Every timestap the following happens:

```<code>to time
  set nl fput item 3 peggs nl ;every day the amount of 4 days old eggs are added to the number of larvae
  set il fput ((item dtl peggs) * weight_hatch) il ;the weight of the larvae that just hatched are calculated by multiplying nl by the weight they have when they hatch
  set il_growth (il * e ^ (g * (aphids)*(1 - (il / weight_max))));;growth individual predator larvae in every age class
  set larvae nl * il_growth; the total biomass of al larvae in a patch
end
</code>```

The for il_growth comes from the literature and I know that parameters/variables like e, g, aphids and weight_max aren't the problem because this formula work fine before I introduced il.

I'm not sure yet if the approach for biomass is the best way (because of the error of il that I'll describe below), but I figured that the multiplication is possible since nl and il are both lists of the same length.

When I syntax check the code it doesn't give any errors. But when I run it, it says the following: * expected input to be a number but got the list [0 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4] instead.
The * it points at is the first one in the il_growth formula.

I thought that this could be caused because the code needs il to be a number and not a list. Then I found on google that this could be fixed by the functions 'foreach' or 'map'.

With foreach I tried this:

```<code>set il_growth foreach il (il * e ^ (g * (aphids)*(1 - (il / weight_max))))
</code>```

This gave the error 'set expected 2 inputs'. I also tried many other configurations with foreach, but none worked.

With map I tried this:

```<code>set il_growth map report_il il

to-report report_il
  report (il * e ^ (g * (aphids)*(1 - (il / weight_max))))
end
</code>```

This gave me the same error as before: * expected input to be a number but got the list [0 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4] instead.

答:
We don't need to know everything you have tried if the attempt didn't help, just enough to understand the code that you are trying to fix and a description of the problem. You definitely can't simply multiply lists the way you have, even if they are the same length. This is a complete model that will generate the same error message:

```<code>to testme1
  let list1 [1 2 3]
  let list2 [4 5 6]
  print list1 * list2
end
</code>```

If what you are trying to do is multiply the two lists on an item by item basis, then you need map. Here is the equivalent model:

```<code>to testme2
  let list1 [1 2 3]
  let list2 [4 5 6]
  print (map * list1 list2)
end
</code>```

So, if I have understood your question, replace set larvae nl * il with set larvae (map nl * il). If that doesn't fix your problem, please edit your question to more clearly identify what you are trying to resolve.

UPDATE: for comment

Okay, from your comment, the line set il_growth (il * e ^ (g * (aphids)*(1 - (il / weight_max)))) is throwing the error. Just like the map is necessary for multiplying lists, it is necessary for more complicated arithmetic. You are multiplying the list il by something with a bunch of values (e, g, aphids, weight_max) and operators and the list il again.

Try replacing with this (untested):

```<code>set il_growth map [ thisval -> thisval * e ^ (g * (aphids)*(1 - (thisval / weight_max)))) ] il
</code>```

What this (sort of) does is run through the list il, giving the current item to the temporary variable named 'thisval', and does the calculations on the individual value rather than the list. But it applies to the whole list.

Title: List multiplication in NetLogo

Body:
I'm modeling the distribution of hoverflies in an aphid-infested crop field with flower margins. I have a couple of lists which are setup as patch variables as follows:

set nl n-values 20 [0];; number of larvae per age (in days)
set il n-values 20 [0.0001];; individual larvae growth per age (in days)
set il_growth n-values 20 [0];; growth of larvae per age (in days)

I gave the value 0.0001 instead of 0 because previously I got errors regarding the 0.

Every timestap the following happens:

to time
  set nl fput item 3 peggs nl ;every day the amount of 4 days old eggs are added to the number of larvae
  set il fput ((item dtl peggs) * weight_hatch) il ;the weight of the larvae that just hatched are calculated by multiplying nl by the weight they have when they hatch
  set il_growth (il * e ^ (g * (aphids)*(1 - (il / weight_max))));;growth individual predator larvae in every age class
  set larvae nl * il_growth; the total biomass of al larvae in a patch
end

The for il_growth comes from the literature and I know that parameters/variables like e, g, aphids and weight_max aren't the problem because this formula work fine before I introduced il.

I'm not sure yet if the approach for biomass is the best way (because of the error of il that I'll describe below), but I figured that the multiplication is possible since nl and il are both lists of the same length.

When I syntax check the code it doesn't give any errors. But when I run it, it says the following: * expected input to be a number but got the list [0 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4] instead.
The * it points at is the first one in the il_growth formula.

I thought that this could be caused because the code needs il to be a number and not a list. Then I found on google that this could be fixed by the functions 'foreach' or 'map'.

With foreach I tried this:

set il_growth foreach il (il * e ^ (g * (aphids)*(1 - (il / weight_max))))

This gave the error 'set expected 2 inputs'. I also tried many other configurations with foreach, but none worked.

With map I tried this:

set il_growth map report_il il

to-report report_il
  report (il * e ^ (g * (aphids)*(1 - (il / weight_max))))
end

This gave me the same error as before: * expected input to be a number but got the list [0 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4 1.0E-4] instead.

Body:
We don't need to know everything you have tried if the attempt didn't help, just enough to understand the code that you are trying to fix and a description of the problem. You definitely can't simply multiply lists the way you have, even if they are the same length. This is a complete model that will generate the same error message:

to testme1
  let list1 [1 2 3]
  let list2 [4 5 6]
  print list1 * list2
end

If what you are trying to do is multiply the two lists on an item by item basis, then you need map. Here is the equivalent model:

to testme2
  let list1 [1 2 3]
  let list2 [4 5 6]
  print (map * list1 list2)
end

So, if I have understood your question, replace set larvae nl * il with set larvae (map nl * il). If that doesn't fix your problem, please edit your question to more clearly identify what you are trying to resolve.

UPDATE: for comment

Okay, from your comment, the line set il_growth (il * e ^ (g * (aphids)*(1 - (il / weight_max)))) is throwing the error. Just like the map is necessary for multiplying lists, it is necessary for more complicated arithmetic. You are multiplying the list il by something with a bunch of values (e, g, aphids, weight_max) and operators and the list il again.

Try replacing with this (untested):

set il_growth map [ thisval -> thisval * e ^ (g * (aphids)*(1 - (thisval / weight_max)))) ] il

What this (sort of) does is run through the list il, giving the current item to the temporary variable named 'thisval', and does the calculations on the individual value rather than the list. But it applies to the whole list.


问:
Console log json value
I'm working with Testcafe and I would like to ask how to display on the console a json value.
For example, I have this link "https://jsonplaceholder.typicode.com/users"
I want to console the first username or all usernames for example.
Best regards!</p>

答:
I'm a little confused with how your JSON object is setup in the link that you presented. If all of your objects that are shown in that link are held in an array (most likely) then you'll want to do something like this</p>

```<code>yourJson.forEach(object => {console.log(object.username)})
</code>```

Title: Console log json value

Body:
I'm a little confused with how your JSON object is setup in the link that you presented. If all of your objects that are shown in that link are held in an array (most likely) then you'll want to do something like this

yourJson.forEach(object => {console.log(object.username)})


问:
How do you force Perl to re-compile a regex compiled with "/o" on demand?
Technical question:

Given a regex:

```<code>my $regEx = qr{whatever$myVar}oxi; # Notice /o for "compile-once"
</code>```

What is the most effective way to force it to recompile on demand? (e.g. when I know from the program logic that $myVar value changed) without dropping /o and depending on Perl's internal smarts to auto-recompile?

NOTE: The regex is used in a substitution, which may affect re-compilation rules sans /o:

```<code>$string2 =~ s/$regEx//;
</code>```

The context is:

I have a regular expression that is built by slurping in a fairly long (>1k long) string from a config file.

That file is re-read once every 60 minutes.

If the string read from the file changes (as defined by changing file timestamp), I want to re-compile the regex using the re-slurped string value in $myVar.

The regex is used repeatedly and frequently in the Perl module running under mod_perl.

This means that (coupled with the string being >1-2k long) I must use "/o" modifier to force compile-once on the regex, to avoid performance hit of Perl repeatedly checking if the variable value changed (this heuristic is from perlop qr//, since the regex is used as part  of s/// as shown above and not by itself as a match).

That in turn means that, when I know that the variable changed after re-slurping it in 1 hour, I need to force the regex to re-compile despite the /o modifier.

UPDATE: Here's an illustration of why I need /o - without it, the regex is recompiled (and thus necessarily checked) every loop iteration; with it it is NOT:

```<code>$ perl -e '{for (my $i=0; $i<3; $i++) {
                 my $re = qr{$i}oix; $s="123"; $s =~ s/$re//;
                 print "i=$i; s=$s\n"; }}'
i=0; s=123
i=1; s=123
i=2; s=123

$ perl -e '{ for (my $i=0; $i<3; $i++) {
                  my $re = qr{$i}ix; $s="123"; $s =~ s/$re//;
                  print "i=$i; s=$s\n"; }}'
i=0; s=123
i=1; s=23
i=2; s=13
</code>```

答:
According to perlop

The effect the 'o' modifier has is not
  propagated, being restricted to those
  patterns explicitly using it.

So if you write

```<code>my $str = 'x';
my $re  = qr/$str/o;
...
if (s/$re//) {
    ...
}
</code>```

Perl will still check to see whether or not $re has changed when executing the s///. The /o acts as a promise that the value of $str used in the compilation of $re won't change so if you re-executed the qr// you'd get the same result even if $str has changed. You can see this in effect with use re 'debug':

```<code>use strict;
use warnings;
use re 'debug';

foreach my $i (0 .. 2) {
    my $s  = '123';

    print STDERR "Setting \$re\n";
    my $re = qr/$i/o;

    print STDERR "Performing s///\n";
    $s =~ s/$re//;
}
</code>```

With the /o modifier, you'll only see "Compiling REx..." after "Setting $re" the first time through the loop. Without it you'll see it each iteration.

The take-away is that if you want to change the pattern during runtime you shouldn't use /o. It won't affect the s/// and it will prevent you from being able to re-compile $re when you need to.

Body:
Technical question:

Given a regex:

my $regEx = qr{whatever$myVar}oxi; # Notice /o for "compile-once"

What is the most effective way to force it to recompile on demand? (e.g. when I know from the program logic that $myVar value changed) without dropping /o and depending on Perl's internal smarts to auto-recompile?

NOTE: The regex is used in a substitution, which may affect re-compilation rules sans /o:

$string2 =~ s/$regEx//;

The context is:

I have a regular expression that is built by slurping in a fairly long (>1k long) string from a config file.

That file is re-read once every 60 minutes.

If the string read from the file changes (as defined by changing file timestamp), I want to re-compile the regex using the re-slurped string value in $myVar.

The regex is used repeatedly and frequently in the Perl module running under mod_perl.

This means that (coupled with the string being >1-2k long) I must use "/o" modifier to force compile-once on the regex, to avoid performance hit of Perl repeatedly checking if the variable value changed (this heuristic is from perlop qr//, since the regex is used as part  of s/// as shown above and not by itself as a match).

That in turn means that, when I know that the variable changed after re-slurping it in 1 hour, I need to force the regex to re-compile despite the /o modifier.

UPDATE: Here's an illustration of why I need /o - without it, the regex is recompiled (and thus necessarily checked) every loop iteration; with it it is NOT:

$ perl -e '{for (my $i=0; $i<3; $i++) {
                 my $re = qr{$i}oix; $s="123"; $s =~ s/$re//;
                 print "i=$i; s=$s\n"; }}'
i=0; s=123
i=1; s=123
i=2; s=123

$ perl -e '{ for (my $i=0; $i<3; $i++) {
                  my $re = qr{$i}ix; $s="123"; $s =~ s/$re//;
                  print "i=$i; s=$s\n"; }}'
i=0; s=123
i=1; s=23
i=2; s=13

Body:
According to perlop

The effect the 'o' modifier has is not
  propagated, being restricted to those
  patterns explicitly using it.

So if you write

my $str = 'x';
my $re  = qr/$str/o;
...
if (s/$re//) {
    ...
}

Perl will still check to see whether or not $re has changed when executing the s///. The /o acts as a promise that the value of $str used in the compilation of $re won't change so if you re-executed the qr// you'd get the same result even if $str has changed. You can see this in effect with use re 'debug':

use strict;
use warnings;
use re 'debug';

foreach my $i (0 .. 2) {
    my $s  = '123';

    print STDERR "Setting \$re\n";
    my $re = qr/$i/o;

    print STDERR "Performing s///\n";
    $s =~ s/$re//;
}

With the /o modifier, you'll only see "Compiling REx..." after "Setting $re" the first time through the loop. Without it you'll see it each iteration.

The take-away is that if you want to change the pattern during runtime you shouldn't use /o. It won't affect the s/// and it will prevent you from being able to re-compile $re when you need to.


问:
Change an object value inside a loop in JavaScript
I have an array of objects like this:

```<code>const data = [{
  _id:"49847444033",
  name:"yoko"
},{
  _id:"49847433333",
  name:"doira"
}]
</code>```

I have to change each item name property to something like this :

```<code>...
{
  _id:"49847433333",
  name:{
      en:"John"
    }
}
</code>```

My attempt is to loop object like following :

```<code>data.forEach((item) => {
   item.name = {en:"john"}
   console.log(item)
})
</code>```

But this always console the original item and the name property value is not modified.

答:
```<code>const newData = data.map(user => ({ _id: user._id, name: { en: user.name } }))
</code>```

Body:
I have an array of objects like this:

const data = [{
  _id:"49847444033",
  name:"yoko"
},{
  _id:"49847433333",
  name:"doira"
}]

I have to change each item name property to something like this :

...
{
  _id:"49847433333",
  name:{
      en:"John"
    }
}

My attempt is to loop object like following :

data.forEach((item) => {
   item.name = {en:"john"}
   console.log(item)
})

But this always console the original item and the name property value is not modified.


问:
how to fix property does not exit in Angular
so I'm working on existing code base and I'm trying make the mat-form filed to get TextData that written in mam-chart.model.ts file but some reason I'm getting this error " ERROR TypeError: Cannot read property 'text' of undefined' ". I

Any suggestion or help will be really apppreciated

design.ts

```<code>import { Chart, TextData, ChartData} from 'src/app/mam-chart/models';
export class ChartDesignComponent implements OnInit {
 chart: Chart;
 chartData: ChartData;
}
</code>```

design.html

```<code>            <mat-form-field appearance="fill">
                <mat-label>Text</mat-label>
                <input matInput  [(ngModel)]="chartData.textData.text" />
            </mat-form-field >

            <mat-form-field appearance="fill">
                <mat-label>Color(# + hex color code)</mat-label>
                <input matInput [(ngModel)]="chartData.textData.color"/>
            </mat-form-field >
</code>```

mam-chart.model.ts

```<code>export class Chart {
    id: number;
    chartType: ChartType = ChartType.chart;
    version: number = 2;
    dataType: ChartDataType = ChartDataType.static;
    template: ChartTemplate;

    .........

}
export class TextCard extends Chart {
    public chartData: CardDataChart;

    constructor(json?: any) {
        super(json)
        if (json == null) {
            return;
        }
        this.chartData = new ChartData(json.chartData);
    }
}

export class TextData {
    public text:  string;
    public color:  string;
    public size: string;
    public sizePx: number;

    constructor(json?: any) {
        if (json == null) {
            this.text = "";
            this.color = "";
            this.size = "";
            this.sizePx = 20;
            return;
        }
       ......

export class ChartData {
    filteredData: FilteredData[];
    figures: Figure[];
    textData: TextData;
}
</code>```

答:
your class Chart hasn't property chartData and textData too...
try so [(ngModel)]="chartData.textData.color"

Body:
so I'm working on existing code base and I'm trying make the mat-form filed to get TextData that written in mam-chart.model.ts file but some reason I'm getting this error " ERROR TypeError: Cannot read property 'text' of undefined' ". I

Any suggestion or help will be really apppreciated

design.ts

import { Chart, TextData, ChartData} from 'src/app/mam-chart/models';
export class ChartDesignComponent implements OnInit {
 chart: Chart;
 chartData: ChartData;
}

design.html

            <mat-form-field appearance="fill">
                <mat-label>Text</mat-label>
                <input matInput  [(ngModel)]="chartData.textData.text" />
            </mat-form-field >

            <mat-form-field appearance="fill">
                <mat-label>Color(# + hex color code)</mat-label>
                <input matInput [(ngModel)]="chartData.textData.color"/>
            </mat-form-field >

mam-chart.model.ts

export class Chart {
    id: number;
    chartType: ChartType = ChartType.chart;
    version: number = 2;
    dataType: ChartDataType = ChartDataType.static;
    template: ChartTemplate;

    .........

}
export class TextCard extends Chart {
    public chartData: CardDataChart;

    constructor(json?: any) {
        super(json)
        if (json == null) {
            return;
        }
        this.chartData = new ChartData(json.chartData);
    }
}

export class TextData {
    public text:  string;
    public color:  string;
    public size: string;
    public sizePx: number;

    constructor(json?: any) {
        if (json == null) {
            this.text = "";
            this.color = "";
            this.size = "";
            this.sizePx = 20;
            return;
        }
       ......

export class ChartData {
    filteredData: FilteredData[];
    figures: Figure[];
    textData: TextData;
}


问:
Complex layout in react app : CSS or Bootstrap, or both?
I'm working on a react app, in which I use react-bootstrap to get some useful components. I'm fairly new to javascript and react and web development in general.

So I wanted to create a layout that appears to be rather complex to achieve with the Bootstrap Container, Row and Col elements alone: I needed a sidebar, and it looks that you cannot do this with raw Bootstrap, and you need to write custom css.

Managing both Bootstrap layout and CSS tends to overload my brain... I can see 3 ways of getting it done:

try to do it all with Boostrap components, no extra CSS (seems unrealistic to me)

use boostrap elements for layout, and tweak them with custom CSS

use only CSS  for layout (Grid or Flexbox for instance - no Bootstrap components)

After googling around a lot, the last option seems the most manageable to me. Which way do you think is the most realistic for a newbie, and allows me to get what I want? Is there another solution I didn't think of?

答:
As a newbie, I would say 100% to start with CSS and doing it custom yourself. You will have full control over the layout and what it is doing behind the scenes of bootstrap and if you want to update it, you know exactly how. When I started Web dev only 3 years ago, the first thing I learned in CSS (except the basics) was Flex and it has saved me.
IMO, Work on learning CSS Flex and Grid and you will master them both together which will help you greatly working on the front end.</p>


问:
How to resolve branches when git diff .. returns nothing but git diff ... returns changes?
I think my master and release branches somehow diverged and I'm wondering what the best way to bring them back in sync is.

I have a master branch which is supposed to be used for development, but then I'll merge this master branch into a release branch to create final builds that can be deployed. It was working fine, but as of a week ago, whenever I try to create a pull request merging from master into release, I get a list of commits that should've already been in release. I'll merge the PR, but this keeps happening with every new PR trying to merge from master to release.

I tried looking at changes to make sure both branches are identical

git diff upstream/master..upstream/release gives me no diffs.

git diff upstream/release..upstream/master also gives me no diffs.

However git diff upstream/master...upstream/release gives me the changes from all the commits since the one that probably diverged my two branches.

I think what might be happening is that my two branches are identical in raw code, but they have different commits? I'm still taking classes on git and how to use it more effectively so any help would be greatly appreciated!

答:
I think what might be happening is that my two branches are identical in raw code, but they have different commits?

Yes, that is the correct diagnosis, although you can confirm this with:

```<code>git log --left-right --boundary --decorate --oneline --graph
    upstream/master...upstream/release
</code>```

(all as one one, broken up into several for posting purposes).

Remember, Git is about commits.  Branch names like master and release, and remote-tracking names like upstream/master and upstream/release, identify some particular commit.  We say that these names point to those commits.

Commits also point to other commits: in particular, each commit points to its immediate parent.

When you have a simple linear sequence of such commits, each with its own hash ID, ending in some final hash ID we can call H, we can draw that like this:

```<code>... <-F <-G <-H   <-- master
</code>```

The name master holds the right hash ID: it lets you (or Git, at least) easily find the correct hash H for the last commit in the chain.  In other words, master points to H.  Commit H itself contains the snapshot—all of your files, frozen in time—and also the raw hash ID of previous ("parent") commit G, so H points to G.  The hash lets Git find G.  Commit G contains a snapshot and another parent-hash, F, which lets Git find F, and so on.

In this case, you have a situation like this:

```<code>          I--J   <-- upstream/master
         /
...--G--H
         \
          K--L   <-- upstream/release
</code>```

For whatever reason,1 the snapshots in J and L match, so comparing upstream/master (commit J) to upstream/release (commit L) shows no difference, regardless of which direction you use for the comparison.

Here, it's helpful to know that:

```<code>git diff A..B
</code>```

just means:

```<code>git diff A B
</code>```

That is, Git finds the two hash IDs in question, extracts the two frozen snapshots, and compares (diffs) them.  You see information telling you what is needed to change the snapshot that is in A into the snapshot in B,

But:

```<code>git diff A...B
</code>```

does not mean compare A to B, but rather find a merge base between A and B, and compare that merge base snapshot to B.  In this case, given the drawing I made—which probably does not quite match the actual set of commits you have—the merge base of upstream/master and upstream/release is commit H, which as you can see, is in both histories: you will find commit H if you start at J and work backwards, and you will also find commit H if you start at L and work backwards.

So here, this would diff the snapshot in H against the snapshot in whichever commit is pointed-to by the name you put on the right.  Since the snapshots in J and L match, you'll see the same diff regardless of which way you run it:

git diff upstream/master...upstream/release

compares H vs L, while:

```<code>git diff upstream/release...upstream/master
</code>```

compares H vs J, but they both produce the same diff.

If you want the histories to match up—the history is the set of commits found by starting at the name, then working backwards—you must:

move upstream/release, or

move upstream/master, or

add a new merge commit and move both, as illustrated by:

```<code>          I--J
         /    \
...--G--H      M   <-- upstream/release, upstream/master
         \    /
          K--L
</code>```

for instance.  But all of this is complicated by the fact that these two names are remote-tracking names.  They are not branch names.

These remote-tracking names are yours, so you can move them—but your Git automatically moves them, to match the hash IDs stored in some other Git repository's branch names.  That other Git repository is the one your Git calls upstream, and it has branch names master and release.  You run:

```<code>git fetch upstream
</code>```

and your Git calls up their Git, finds any new commits they have that you don't (that you'll need), gets those commits, and then updates your upstream/* remote-tracking names to store the same hash IDs that their branch names hold.

Hence, to get your remote-tracking names updated, the right way to do that is to convince them to get their branch names updated.  Then you just run git fetch upstream to update yours to match.

1The most likely reason to have these commits matching like this, without a merge commit in place, is for someone to have used git merge --squash, or perhaps a clicky GitHub web page button labeled "squash and merge".

Body:
I think what might be happening is that my two branches are identical in raw code, but they have different commits?

Yes, that is the correct diagnosis, although you can confirm this with:

git log --left-right --boundary --decorate --oneline --graph
    upstream/master...upstream/release

(all as one one, broken up into several for posting purposes).

Remember, Git is about commits.  Branch names like master and release, and remote-tracking names like upstream/master and upstream/release, identify some particular commit.  We say that these names point to those commits.

Commits also point to other commits: in particular, each commit points to its immediate parent.

When you have a simple linear sequence of such commits, each with its own hash ID, ending in some final hash ID we can call H, we can draw that like this:

... <-F <-G <-H   <-- master

The name master holds the right hash ID: it lets you (or Git, at least) easily find the correct hash H for the last commit in the chain.  In other words, master points to H.  Commit H itself contains the snapshot—all of your files, frozen in time—and also the raw hash ID of previous ("parent") commit G, so H points to G.  The hash lets Git find G.  Commit G contains a snapshot and another parent-hash, F, which lets Git find F, and so on.

In this case, you have a situation like this:

          I--J   <-- upstream/master
         /
...--G--H
         \
          K--L   <-- upstream/release

For whatever reason,1 the snapshots in J and L match, so comparing upstream/master (commit J) to upstream/release (commit L) shows no difference, regardless of which direction you use for the comparison.

Here, it's helpful to know that:

git diff A..B

just means:

git diff A B

That is, Git finds the two hash IDs in question, extracts the two frozen snapshots, and compares (diffs) them.  You see information telling you what is needed to change the snapshot that is in A into the snapshot in B,

But:

git diff A...B

does not mean compare A to B, but rather find a merge base between A and B, and compare that merge base snapshot to B.  In this case, given the drawing I made—which probably does not quite match the actual set of commits you have—the merge base of upstream/master and upstream/release is commit H, which as you can see, is in both histories: you will find commit H if you start at J and work backwards, and you will also find commit H if you start at L and work backwards.

So here, this would diff the snapshot in H against the snapshot in whichever commit is pointed-to by the name you put on the right.  Since the snapshots in J and L match, you'll see the same diff regardless of which way you run it:

git diff upstream/master...upstream/release

compares H vs L, while:

git diff upstream/release...upstream/master

compares H vs J, but they both produce the same diff.

If you want the histories to match up—the history is the set of commits found by starting at the name, then working backwards—you must:

move upstream/release, or

move upstream/master, or

add a new merge commit and move both, as illustrated by:

          I--J
         /    \
...--G--H      M   <-- upstream/release, upstream/master
         \    /
          K--L

for instance.  But all of this is complicated by the fact that these two names are remote-tracking names.  They are not branch names.

These remote-tracking names are yours, so you can move them—but your Git automatically moves them, to match the hash IDs stored in some other Git repository's branch names.  That other Git repository is the one your Git calls upstream, and it has branch names master and release.  You run:

git fetch upstream

and your Git calls up their Git, finds any new commits they have that you don't (that you'll need), gets those commits, and then updates your upstream/* remote-tracking names to store the same hash IDs that their branch names hold.

Hence, to get your remote-tracking names updated, the right way to do that is to convince them to get their branch names updated.  Then you just run git fetch upstream to update yours to match.

1The most likely reason to have these commits matching like this, without a merge commit in place, is for someone to have used git merge --squash, or perhaps a clicky GitHub web page button labeled "squash and merge".