问:
file i/o problem - lines not being written to file as they are being read
I have a text file of Things each with some associated parameters like so:

```<code>1   Thing 1
2   Attribute: X
3   Other1: foo
4   Other2: bar
5   Thing 2
6   Attribute: Y
7   Other1: foo
8   Thing 3
9   Attribute: a
10  Thing 4
11  Attribute: f
12  Thing 5
13  Attribute: m
14  EndText
</code>```

Where the Thing number indicates the attribute position in the following arrays:

```<code>Current Attribute Array: [X, Y, a, f, m]
Future Attribute Array: [X - 1, Y - 1, a - 1, f - 1, m - 1] ' (representing some mathematical operation based on conditions)
</code>```

(These arrays exist in the code already)

Lets say the above file is called Things.txt. I want to be able to go line-by-line through the file and change "Attribute" from the value in the current array to the operated upon attribute from the future array.

Note that the "OtherN" parameters are there to emphasize that the sections in the file for each "Thing" are not equal in row count.

I have set up a for loop to go from lbound(currentArray) to ubound(currentArray)

Lets say we're on loop iteration 3

I have previously set

```<code>rowThing = 8 (the row that Thing 3's section begins)
rowNextThing = 10 (the first row that no longer applies to Thing 3)
searchText = "Attribute: a" (a concatenation of "Attribute: " and the 3rd entry in the current attribute array)
Set fso = CreateObject("Scripting.FileSystemObject")
</code>```

```<code>Open filePath For Input As #1
Open tempFilePath For Append As #2

    Do While Not EOF(1)

        Line Input #1, textline

        rowCounter = rowCounter + 1

        ' check the current line to see if it contains the string we're looking
        ' for (must be in between rowThing and rowNextThing and equal to the
        ' search text. If so, change whats printed in the tempFile. If not,
        ' just read from file and write to tempFile
        If (InStr(textline, searchText) > 0 And rowCounter > rowThing And rowCounter < rowNextThing) Then

            Print #2, futureAttribute ' ("Attribute: a - 1", in this case)

        Else

            Print #2, textline

        End If

    Loop

Close #1
Close #2

' delete file, rename tempFile to file (saving the newly written tempFile)
fso.DeleteFile filePath
fso.MoveFile tempFilePath, filePath
</code>```

When I step through the code and reach "Close #2", what I expect to see is a tempFile that looks exactly like the file. Instead I see a tempFile that looks a lot like the beginning of the file, but stops early (only writes up to line 10, for example).

Note that the real file is 888 lines long with 27 different Things.

Any ideas?

EDIT: I was asked to provide a fuller accounting of my code, so here that is

```<code>Set fso = CreateObject("Scripting.FileSystemObject")

rowThing = 0
rowNextThing = 0

' set arrays
currentValueAttributes = Array(9.9, 8.7, 4.5, 4.6, 10.1)
newValueAttributes = Array(9.7, 7.2, 5, 3.5, 7.8)
arrayThings = Array("Thing 1", "Thing 2", "Thing 3", "Thing 4", "Thing 5")

For i = LBound(arrayThings) To UBound(arrayThings) ' this should equate to for i = 0 to 4

    searchTextAttribute = "Attribute: " & currentValueAttributes(i)
    replaceTextAttribute = "Attribute: " & newValueAttributes(i)
    searchTextThing = arrayThings(i)

    If i < UBound(arrayThings) Then

        searchTextNextThing = arrayThings(i + 1)

    Else

        searchTextNextThing = "EndText"

    End If

    Open filePath For Input As #1

        Do While Not EOF(1)

            Line Input #1, textline

            rowCounter = rowCounter + 1

            ' check the current line to see if it contains arrayThings(i)
            ' if it does, set rowThing as the current line number (saves the rownum of the current Thing)
            If textline Like searchTextThing Then

                rowThing = rowCounter

            End If

        Loop

    Close #1

    rowCounter = 0
    textline = ""

        Open filePath For Input As #1

            Do While Not EOF(1)

            Line Input #1, textline

            rowCounter = rowCounter + 1

            ' check the current line to see if it contains arrayThings(i + 1) or EndText
            ' if it does, set rowNextThing as the current line number (saves the rownum of the current NextThing)
            If textline Like searchTextNextThing Then

                rowNextThing = rowCounter

            End If

            Loop

        Close #1

        rowCounter = 0
        textline = ""

    Open filePath For Input As #1
    Open tempFilePath For Append As #2

        Do While Not EOF(1)

            Line Input #1, textline

            rowCounter = rowCounter + 1

            ' check the current line to see if it contains the string we're looking
            ' for (must be in between rowThing and rowNextThing and equal to the
            ' search text. If so, change whats printed in the tempFile. If not,
            ' just read from file and write to tempFile
            If (InStr(textline, searchTextAttribute) > 0 And rowCounter > rowThing And rowCounter < rowNextThing) Then

                Print #2, replaceTextAttribute

            Else

                Print #2, textline

            End If

        Loop

    Close #1
    Close #2

    ' delete file, rename tempFile to file (saving the newly written tempFile)
    fso.DeleteFile filePath
    fso.MoveFile tempFilePath, filePath

Next i
</code>```

答:
Seems like you only need to read your file once, if the aim is to replace the content according to your arrays of values.

I would suggest moving the configuration (thing names, current and new values) onto a worksheet range and using that to drive your code.

Eg: if your range looks like this -

Then your code can look something like this (untested):

```<code>Sub TESTER()

    Dim fso As Object
    Dim searchTextAttribute, replaceTextAttribute
    Dim ffI As Integer, ffO As Integer, inThing As Boolean
    Dim rngData As Range, m, filePath, tempFilePath, textline

    Set rngData = Sheet1.Range("A2:C12")

    filePath = "somePath"
    tempFilePath = "otherPath"

    ffI = FreeFile
    Open filePath For Input As #ffI
    ffO = FreeFile
    Open tempFilePath For Append As #ffO

    Do While Not EOF(1)
        Line Input #1, textline

        m = Application.Match(textline, rngData.Columns(1), 0) '<< is this a Thing?
        If Not IsError(m) Then
            'found a Thing, so read the current/new attributes
            searchTextAttribute = "Attribute: " & rngData.Cells(m, 2).Value
            replaceTextAttribute = "Attribute: " & rngData.Cells(m, 3).Value
            inThing = True
        Else
            If inThing And textline = searchTextAttribute Then
                textline = replaceTextAttribute
            End If
        End If
        Print #2, textline
    Loop

    Close #ffI
    Close #ffO

End Sub
</code>```

Body:
I have a text file of Things each with some associated parameters like so:

1   Thing 1
2   Attribute: X
3   Other1: foo
4   Other2: bar
5   Thing 2
6   Attribute: Y
7   Other1: foo
8   Thing 3
9   Attribute: a
10  Thing 4
11  Attribute: f
12  Thing 5
13  Attribute: m
14  EndText

Where the Thing number indicates the attribute position in the following arrays:

Current Attribute Array: [X, Y, a, f, m]
Future Attribute Array: [X - 1, Y - 1, a - 1, f - 1, m - 1] ' (representing some mathematical operation based on conditions)

(These arrays exist in the code already)

Lets say the above file is called Things.txt. I want to be able to go line-by-line through the file and change "Attribute" from the value in the current array to the operated upon attribute from the future array.

Note that the "OtherN" parameters are there to emphasize that the sections in the file for each "Thing" are not equal in row count.

I have set up a for loop to go from lbound(currentArray) to ubound(currentArray)

Lets say we're on loop iteration 3

I have previously set

rowThing = 8 (the row that Thing 3's section begins)
rowNextThing = 10 (the first row that no longer applies to Thing 3)
searchText = "Attribute: a" (a concatenation of "Attribute: " and the 3rd entry in the current attribute array)
Set fso = CreateObject("Scripting.FileSystemObject")

Open filePath For Input As #1
Open tempFilePath For Append As #2

    Do While Not EOF(1)

        Line Input #1, textline

        rowCounter = rowCounter + 1

        ' check the current line to see if it contains the string we're looking
        ' for (must be in between rowThing and rowNextThing and equal to the
        ' search text. If so, change whats printed in the tempFile. If not,
        ' just read from file and write to tempFile
        If (InStr(textline, searchText) > 0 And rowCounter > rowThing And rowCounter < rowNextThing) Then

            Print #2, futureAttribute ' ("Attribute: a - 1", in this case)

        Else

            Print #2, textline

        End If

    Loop

Close #1
Close #2

' delete file, rename tempFile to file (saving the newly written tempFile)
fso.DeleteFile filePath
fso.MoveFile tempFilePath, filePath

When I step through the code and reach "Close #2", what I expect to see is a tempFile that looks exactly like the file. Instead I see a tempFile that looks a lot like the beginning of the file, but stops early (only writes up to line 10, for example).

Note that the real file is 888 lines long with 27 different Things.

Any ideas?

EDIT: I was asked to provide a fuller accounting of my code, so here that is

Set fso = CreateObject("Scripting.FileSystemObject")

rowThing = 0
rowNextThing = 0

' set arrays
currentValueAttributes = Array(9.9, 8.7, 4.5, 4.6, 10.1)
newValueAttributes = Array(9.7, 7.2, 5, 3.5, 7.8)
arrayThings = Array("Thing 1", "Thing 2", "Thing 3", "Thing 4", "Thing 5")

For i = LBound(arrayThings) To UBound(arrayThings) ' this should equate to for i = 0 to 4

    searchTextAttribute = "Attribute: " & currentValueAttributes(i)
    replaceTextAttribute = "Attribute: " & newValueAttributes(i)
    searchTextThing = arrayThings(i)

    If i < UBound(arrayThings) Then

        searchTextNextThing = arrayThings(i + 1)

    Else

        searchTextNextThing = "EndText"

    End If

    Open filePath For Input As #1

        Do While Not EOF(1)

            Line Input #1, textline

            rowCounter = rowCounter + 1

            ' check the current line to see if it contains arrayThings(i)
            ' if it does, set rowThing as the current line number (saves the rownum of the current Thing)
            If textline Like searchTextThing Then

                rowThing = rowCounter

            End If

        Loop

    Close #1

    rowCounter = 0
    textline = ""

        Open filePath For Input As #1

            Do While Not EOF(1)

            Line Input #1, textline

            rowCounter = rowCounter + 1

            ' check the current line to see if it contains arrayThings(i + 1) or EndText
            ' if it does, set rowNextThing as the current line number (saves the rownum of the current NextThing)
            If textline Like searchTextNextThing Then

                rowNextThing = rowCounter

            End If

            Loop

        Close #1

        rowCounter = 0
        textline = ""

    Open filePath For Input As #1
    Open tempFilePath For Append As #2

        Do While Not EOF(1)

            Line Input #1, textline

            rowCounter = rowCounter + 1

            ' check the current line to see if it contains the string we're looking
            ' for (must be in between rowThing and rowNextThing and equal to the
            ' search text. If so, change whats printed in the tempFile. If not,
            ' just read from file and write to tempFile
            If (InStr(textline, searchTextAttribute) > 0 And rowCounter > rowThing And rowCounter < rowNextThing) Then

                Print #2, replaceTextAttribute

            Else

                Print #2, textline

            End If

        Loop

    Close #1
    Close #2

    ' delete file, rename tempFile to file (saving the newly written tempFile)
    fso.DeleteFile filePath
    fso.MoveFile tempFilePath, filePath

Next i

Body:
Seems like you only need to read your file once, if the aim is to replace the content according to your arrays of values.

I would suggest moving the configuration (thing names, current and new values) onto a worksheet range and using that to drive your code.

Eg: if your range looks like this -

Then your code can look something like this (untested):

Sub TESTER()

    Dim fso As Object
    Dim searchTextAttribute, replaceTextAttribute
    Dim ffI As Integer, ffO As Integer, inThing As Boolean
    Dim rngData As Range, m, filePath, tempFilePath, textline

    Set rngData = Sheet1.Range("A2:C12")

    filePath = "somePath"
    tempFilePath = "otherPath"

    ffI = FreeFile
    Open filePath For Input As #ffI
    ffO = FreeFile
    Open tempFilePath For Append As #ffO

    Do While Not EOF(1)
        Line Input #1, textline

        m = Application.Match(textline, rngData.Columns(1), 0) '<< is this a Thing?
        If Not IsError(m) Then
            'found a Thing, so read the current/new attributes
            searchTextAttribute = "Attribute: " & rngData.Cells(m, 2).Value
            replaceTextAttribute = "Attribute: " & rngData.Cells(m, 3).Value
            inThing = True
        Else
            If inThing And textline = searchTextAttribute Then
                textline = replaceTextAttribute
            End If
        End If
        Print #2, textline
    Loop

    Close #ffI
    Close #ffO

End Sub


来源: stackexchange

问:
how to remove new lines and returns from php string?
A php variable contains the following string:

```<code><p>text</p>
<p>text2</p>
<ul>
<li>item1</li>
<li>item2</li>
</ul>
</code>```

I want to remove all the new line characters in this string so the string will look like this:

```<code><p>text</p><p>text2><ul><li>item1</li><li>item2</li></ul>
</code>```

I've tried the following without success:

```<code>str_replace('\n', '', $str);
str_replace('\r', '', $str);
str_replace('\r\n\', '', $str);
</code>```

Anyone knows how to fix this?

答:
```<code>$str = "Hello World!\n\n";
echo chop($str);

output : Hello World!
</code>```

ContentLicense: CC BY-SA 2.5

Body:
A php variable contains the following string:

text

text2

item1

item2

I want to remove all the new line characters in this string so the string will look like this:

text

text2>

item1

item2

I've tried the following without success:

str_replace('\n', '', $str);
str_replace('\r', '', $str);
str_replace('\r\n\', '', $str);

Anyone knows how to fix this?

ContentLicense: CC BY-SA 4.0


问:
accessing the return value of function that was bound to an event (tkinter)
Basically, what I've done is bound a click event to a function.  For example:

```<code>self.button1.bind("<Button-1>",self.chooseDice)
</code>```

What I want now is to access the result of chooseDice() in another function.  What is the best way to go about doing that?

```<code>class GraphicsInterface:

    #we want to initialize the game board here, set up the dice and buttons
    def __init__(self):
        self.window = Tk()
        self.window.geometry("720x500")

        #buttons under each die
        self.clicked=[] #empty list to collect all the buttons that were clicked (see chooseDice function)
        self.button1 = Button(self.window, text="Dice 1", width=13) #create the button object
        self.button1.place(x=60, y=160)
        #bind button click event to a function (chooseDice())
        self.button1.bind("<Button-1>",self.chooseDice)

        self.button2 = Button(self.window, text="Dice 2", width=13)
        self.button2.place(x=185, y=160)
        self.button2.bind("<Button-1>",self.chooseDice)

    #using the event as an argument, append the text to the clicked list
    def chooseDice(self, event):
        self.clicked.append(event.widget.cget('text'))
        self.diceList=[] #create a new empty list
        for i in range(len(self.clicked)):
            self.diceList.append(int(self.clicked[i][5])) #get just the int value of the last character (i.e. the dice number)
        self.deactivate(event.widget)  #deactivate the button
        return self.diceList
</code>```

答:
You are already doing what you need to do. Your example code sets self.diceList to some value. Anywhere else in your code you can directly use self.diceList.

By the way -- you're writing code that is going to be hard to maintain over time. For example, what if you change the dice label to "Dice One" or simply "One" rather than "Dice 1"? Or, as your app progresses you might want graphical images instead of text on the buttons. You'll have to modify the code that parses the button name. You are essentially encoding information in a button label which is not a good idea.

A simple solution, that also makes your chooseDice method simpler and easier to understand, is to pass in the dice number in the callback. For example:

```<code>self.button1.configure(command=lambda btn=self.button1: self.chooseDice(btn, 1))
</code>```

The above passes two parameters to the chooseDice method: the button instance (so you can disable it) and the button number (so you don't have to parse the button name to get it)

This also allows you to create your dice in a loop rather than hard-coding multiple copies of the same block of code. Here's a complete working example:

```<code>from Tkinter import *

class GraphicsInterface:

    def __init__(self):
        self.window = Tk()
        self.window.geometry("720x500")
        self.clicked=[]
        self.buttons = []

        for n in range(1, 3):
            btn = Button(text="Button " + str(n))
            btn.configure(command=lambda btn=btn, n=n: self.chooseDice(btn, n))
            btn.pack()
            self.buttons.append(btn)

        btn = Button(text="Go!", command=self.go)
        btn.pack()
        self.window.mainloop()

    def go(self):
        print "buttons:", self.clicked
        self.reset()

    def reset(self):
        '''Reset all the buttons'''
        self.clicked = []
        for button in self.buttons:
            button.configure(state="normal")

    def chooseDice(self, widget, number):
        self.clicked.append(number)
        widget.configure(state="disabled")

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

Finally, some last bits of advice:

Don't use place, it makes your GUIs harder to create, and they won't react well to changes in window size, changes in font, changes in platform, etc. Use pack and grid instead. Also, don't create fixed-width buttons. Again, this is to better handle changes in fonts. There are times when you want fixed width buttons, but it doesn't look like your code has any reason to use them.

Finally, I don't know what you're actually trying to accomplish, but usually if you're using buttons to track state (is this thing pressed or not?) you want to use checkboxes (pick N of N) or radiobuttons (pick 1 of N).  You might want to consider switching to those instead of to buttons.

ContentLicense: CC BY-SA 3.0

Body:
Basically, what I've done is bound a click event to a function.  For example:

self.button1.bind("<Button-1>",self.chooseDice)

What I want now is to access the result of chooseDice() in another function.  What is the best way to go about doing that?

class GraphicsInterface:

    #we want to initialize the game board here, set up the dice and buttons
    def __init__(self):
        self.window = Tk()
        self.window.geometry("720x500")

        #buttons under each die
        self.clicked=[] #empty list to collect all the buttons that were clicked (see chooseDice function)
        self.button1 = Button(self.window, text="Dice 1", width=13) #create the button object
        self.button1.place(x=60, y=160)
        #bind button click event to a function (chooseDice())
        self.button1.bind("<Button-1>",self.chooseDice)

        self.button2 = Button(self.window, text="Dice 2", width=13)
        self.button2.place(x=185, y=160)
        self.button2.bind("<Button-1>",self.chooseDice)

    #using the event as an argument, append the text to the clicked list
    def chooseDice(self, event):
        self.clicked.append(event.widget.cget('text'))
        self.diceList=[] #create a new empty list
        for i in range(len(self.clicked)):
            self.diceList.append(int(self.clicked[i][5])) #get just the int value of the last character (i.e. the dice number)
        self.deactivate(event.widget)  #deactivate the button
        return self.diceList

Body:
You are already doing what you need to do. Your example code sets self.diceList to some value. Anywhere else in your code you can directly use self.diceList.

By the way -- you're writing code that is going to be hard to maintain over time. For example, what if you change the dice label to "Dice One" or simply "One" rather than "Dice 1"? Or, as your app progresses you might want graphical images instead of text on the buttons. You'll have to modify the code that parses the button name. You are essentially encoding information in a button label which is not a good idea.

A simple solution, that also makes your chooseDice method simpler and easier to understand, is to pass in the dice number in the callback. For example:

self.button1.configure(command=lambda btn=self.button1: self.chooseDice(btn, 1))

The above passes two parameters to the chooseDice method: the button instance (so you can disable it) and the button number (so you don't have to parse the button name to get it)

This also allows you to create your dice in a loop rather than hard-coding multiple copies of the same block of code. Here's a complete working example:

from Tkinter import *

class GraphicsInterface:

    def __init__(self):
        self.window = Tk()
        self.window.geometry("720x500")
        self.clicked=[]
        self.buttons = []

        for n in range(1, 3):
            btn = Button(text="Button " + str(n))
            btn.configure(command=lambda btn=btn, n=n: self.chooseDice(btn, n))
            btn.pack()
            self.buttons.append(btn)

        btn = Button(text="Go!", command=self.go)
        btn.pack()
        self.window.mainloop()

    def go(self):
        print "buttons:", self.clicked
        self.reset()

    def reset(self):
        '''Reset all the buttons'''
        self.clicked = []
        for button in self.buttons:
            button.configure(state="normal")

    def chooseDice(self, widget, number):
        self.clicked.append(number)
        widget.configure(state="disabled")

app = GraphicsInterface()

Finally, some last bits of advice:

Don't use place, it makes your GUIs harder to create, and they won't react well to changes in window size, changes in font, changes in platform, etc. Use pack and grid instead. Also, don't create fixed-width buttons. Again, this is to better handle changes in fonts. There are times when you want fixed width buttons, but it doesn't look like your code has any reason to use them.

Finally, I don't know what you're actually trying to accomplish, but usually if you're using buttons to track state (is this thing pressed or not?) you want to use checkboxes (pick N of N) or radiobuttons (pick 1 of N).  You might want to consider switching to those instead of to buttons.


问:
Yii2 - migration can't be applied
I wanted to apply migrations, but it won't let me do that.

cmd looks like this:

```<code>D:\web\website>yii migrate --migrationPath=@yii/rbac/migrations
Yii Migration Tool (based on Yii v2.0.35)

Total 5 new migrations to be applied:
        sjaakp\pluto\migrations\m000000_000000_init
        m140506_102106_rbac_init
        m170907_052038_rbac_add_index_on_auth_assignment_user_id
        m180523_151638_rbac_updates_indexes_without_prefix
        m200409_110543_rbac_update_mssql_trigger

Apply the above migrations? (yes|no) [no]:
D:\web\website>
</code>```

It won't let me type 'yes' to apply to the migrations.

Anyone an Idea what I can do?

Thanks.

答:
Ustmaestro gave a helpful answer:

I dont know wath is the problem with your terminal, but You can do it
  by applying yes default using with --interactive=0 in migration
  command like following: yii migrate --interactive=0
  --migrationPath=@yii/rbac/migrations

Title: Yii2 - migration can't be applied

Body:
I wanted to apply migrations, but it won't let me do that.

cmd looks like this:

D:\web\website>yii migrate --migrationPath=@yii/rbac/migrations
Yii Migration Tool (based on Yii v2.0.35)

Total 5 new migrations to be applied:
        sjaakp\pluto\migrations\m000000_000000_init
        m140506_102106_rbac_init
        m170907_052038_rbac_add_index_on_auth_assignment_user_id
        m180523_151638_rbac_updates_indexes_without_prefix
        m200409_110543_rbac_update_mssql_trigger

Apply the above migrations? (yes|no) [no]:
D:\web\website>

It won't let me type 'yes' to apply to the migrations.

Anyone an Idea what I can do?

Thanks.


问:
Convert character matrix into numeric matrix
I have a 7 by 31 character matrix called extra4 and its structure looks like this:

```<code>> str(extra4)
 chr [1:7, 1:31] "36.88  " " 45.48  " " 52.46  " " 111.31 " " 138.45 " " 121.09 " " 122.62" ...
 - attr(*, "dimnames")=List of 2
  ..$ : chr [1:7] "1990" "1991" "1992" "1993" ...
  ..$ : chr [1:31] "1" "2" "3" "4" ...
</code>```

After reading similar questions in SO I've tried the following but I've failed:

```<code>>matrix(as.numeric(unlist(extra4)),nrow=nrow(extra4))
Warning message:
In matrix(as.numeric(unlist(extra4)), nrow = nrow(extra4)) :
  NAs introduced by coercion
</code>```

and also I've tried

```<code>> class(extra4)<-"numeric"
Warning message:
In class(extra4) <- "numeric" : NAs introduced by coercion

> extra4<-apply(extra4, 1, as.numeric)
Warning messages:
1: In apply(extra4, 1, as.numeric) : NAs introduced by coercion
2: In apply(extra4, 1, as.numeric) : NAs introduced by coercion
3: In apply(extra4, 1, as.numeric) : NAs introduced by coercion
4: In apply(extra4, 1, as.numeric) : NAs introduced by coercion
5: In apply(extra4, 1, as.numeric) : NAs introduced by coercion
6: In apply(extra4, 1, as.numeric) : NAs introduced by coercion
7: In apply(extra4, 1, as.numeric) : NAs introduced by coercion

> extra4<-apply(extra4, 2, as.numeric)
There were 31 warnings (use warnings() to see them)
</code>```

I've also tried changing the matrix to data frame and then doing sapply(extra4, as.numeric) but this did not work either, and I've also tried writing the data as csv but somehow the output ends up including non-numeric characters.

It's strange because especially after doing the above, only some of the numbers are turned to numeric values. However, I'm sure that all elements are character, because when I compare those which are saved and those which are not, I get

```<code>> str(extra4[1,1])
 chr "36.88  "
> str(extra4[1,2])
 chr " 19.11  "
</code>```

I'm also adding the following to show my data in more detail:

```<code>extra4 <- matrix(
  c(
    "36.88  ", " 45.48  ", " 52.46  ", " 111.31 ", " 138.45 ",
    " 121.09 ", " 122.62", " 19.11  ", " 27.97  ", " 37.14  ", " 47.68  ",
    " 60.78  ", " 35.84  ", " 38.64", " 56.21  ", " 74.94  ", " 92.3   ",
    " 118.62 ", " 138.13 ", " 104.65 ", " 113.98", " 30.48  ", " 51.54  ",
    " 61.57  ", " 99.87  ", " 80.9   ", " 84.97  ", " 99.34", "20.16  ",
    " 24.76  ", " 27.76  ", " 37.53  ", " 50.53  ", " 28.8   ", " 25.06",
    " 87.73  ", " 98.68  ", " 119.95 ", " 150.74 ", " 214.35 ", " 118.5  ",
    " 129.19", " 32.36  ", " 36.52  ", " 42.67  ", " 56.55  ", " 89.22  ",
    " 49.97  ", " 50.62", "35.09  ", " 40.77  ", " 48.43  ", " 82.61  ",
    " 120.1  ", " 72.43  ", " 76.69", " 47.21  ", " 67.25  ", " 78.62  ",
    " 66.64  ", " 83.78  ", " 127.79 ", " 154.11", " 86.1   ", " 127.59 ",
    " 164.43 ", " 249.32 ", " 312.01 ", " 272.09 ", " 265.68", " 83.75  ",
    " 118.41 ", " 171.52 ", " 229.27 ", " 241.63 ", " 201    ", " 213.01",
    " 36.63  ", " 52.1   ", " 66.03  ", " 101.38 ", " 126.71 ", " 95.46  ",
    " 110.03", " 57.5   ", " 75.72  ", " 101.31 ", " 147.5  ", " 171.01 ",
    " 148.66 ", " 167.93", " 29.56  ", " 38.37  ", " 48.8   ", " 65.5   ",
    " 84.77  ", " 75.2   ", " 81.27", " 77.28  ", " 93.7   ", " 119.62 ",
    " 247    ", " 301.76 ", " 222.52 ", " 244.46", " 45.6   ", " 54.32  ",
    " 87.81  ", " 132.93 ", " 163.62 ", " 152.99 ", " 170.85", " 27.13  ",
    " 36.96  ", " 48.94  ", " 80.01  ", " 124.07 ", " 93.49  ", " 105.57",
    " 54.55  ", " 85.93  ", " 102.3  ", " 122.7  ", " 168.36 ", " 151.79 ",
    " 169.65", " 86.19  ", " 121.82 ", " 191.7  ", " 247.75 ", " 260.23 ",
    " 196.48 ", " 243.06", "47.35  ", " 60.63  ", " 76.4   ", " 93.04  ",
    " 102.13 ", " 98.29  ", " 86.27", " 10.93  ", " 13.33  ", " 16.82  ",
    " 18.2   ", " 23.48  ", " 16.52  ", " 16.19", "   NA   ", "  NA    ",
    "   NA   ", "  NA    ", " 69.46  ", " 54.22  ", " 60.16", " 60.93  ",
    " 89.86  ", " 141.85 ", " 207.9  ", " 182.79 ", " 159.1  ", " 159.46",
    " 15.37  ", " 18.48  ", " 24.33  ", " 38.37  ", " 45.87  ", " 34.86  ",
    " 31.96", " 34.05  ", " 40.1   ", " 55.02  ", " 58.31  ", " 86.89  ",
    " 65.68  ", " 65.68", "1.51   ", " 0.93   ", " 1      ", " 1.78   ",
    " 2.8    ", " 1.56   ", " 1.41", " 27.15  ", " 31.37  ", " 39.46  ",
    " 40.33  ", " 61.86  ", " 45.18  ", " 57.71", " 14.74  ", " 16.3   ",
    " 25.06  ", " 31.74  ", " 37.39  ", " 27.18  ", " 30.49", " 3.59   ",
    " 4.86   ", " 5.67   ", " 6.36   ", " 7.6    ", " 4.8    ", " 5.5",
    "4.73   ", " 5.68   ", " 7.3    ", " 8.53   ", " 11.03  ", " 8.44   ",
    " 9.84", "16.76  ", " 24.83  ", " 32.66  ", " 46.22  ", " 48.01  ",
    " 43.44  ", " 48.29"
  ),
  nrow = 7L,
  ncol = 31L,
  dimnames = list(
    c("1990", "1991", "1992", "1993", "1994", "1995", "1996"),
    c(
      "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
      "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23",
      "24", "25", "26", "27", "28", "29", "30", "31"
    )
  )
)
</code>```

sessionInfo() gave the following:

```<code>    > sessionInfo()
R version 3.0.0 (2013-04-03)
Platform: x86_64-apple-darwin10.8.0 (64-bit)

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] gdata_2.13.2

loaded via a namespace (and not attached):
[1] gtools_2.7.1 tools_3.0.0
</code>```

答:
I think you can just apply:

```<code>data.matrix(frame, rownames.force = NA)
</code>```

Here more info: https://stat.ethz.ch/R-manual/R-devel/library/base/html/data.matrix.html

Body:
I have a 7 by 31 character matrix called extra4 and its structure looks like this:

> str(extra4)
 chr [1:7, 1:31] "36.88  " " 45.48  " " 52.46  " " 111.31 " " 138.45 " " 121.09 " " 122.62" ...
 - attr(*, "dimnames")=List of 2
  ..$ : chr [1:7] "1990" "1991" "1992" "1993" ...
  ..$ : chr [1:31] "1" "2" "3" "4" ...

After reading similar questions in SO I've tried the following but I've failed:

>matrix(as.numeric(unlist(extra4)),nrow=nrow(extra4))
Warning message:
In matrix(as.numeric(unlist(extra4)), nrow = nrow(extra4)) :
  NAs introduced by coercion

and also I've tried

> class(extra4)<-"numeric"
Warning message:
In class(extra4) <- "numeric" : NAs introduced by coercion

> extra4<-apply(extra4, 1, as.numeric)
Warning messages:
1: In apply(extra4, 1, as.numeric) : NAs introduced by coercion
2: In apply(extra4, 1, as.numeric) : NAs introduced by coercion
3: In apply(extra4, 1, as.numeric) : NAs introduced by coercion
4: In apply(extra4, 1, as.numeric) : NAs introduced by coercion
5: In apply(extra4, 1, as.numeric) : NAs introduced by coercion
6: In apply(extra4, 1, as.numeric) : NAs introduced by coercion
7: In apply(extra4, 1, as.numeric) : NAs introduced by coercion

> extra4<-apply(extra4, 2, as.numeric)
There were 31 warnings (use warnings() to see them)

I've also tried changing the matrix to data frame and then doing sapply(extra4, as.numeric) but this did not work either, and I've also tried writing the data as csv but somehow the output ends up including non-numeric characters.

It's strange because especially after doing the above, only some of the numbers are turned to numeric values. However, I'm sure that all elements are character, because when I compare those which are saved and those which are not, I get

> str(extra4[1,1])
 chr "36.88  "
> str(extra4[1,2])
 chr " 19.11  "

I'm also adding the following to show my data in more detail:

extra4 <- matrix(
  c(
    "36.88  ", " 45.48  ", " 52.46  ", " 111.31 ", " 138.45 ",
    " 121.09 ", " 122.62", " 19.11  ", " 27.97  ", " 37.14  ", " 47.68  ",
    " 60.78  ", " 35.84  ", " 38.64", " 56.21  ", " 74.94  ", " 92.3   ",
    " 118.62 ", " 138.13 ", " 104.65 ", " 113.98", " 30.48  ", " 51.54  ",
    " 61.57  ", " 99.87  ", " 80.9   ", " 84.97  ", " 99.34", "20.16  ",
    " 24.76  ", " 27.76  ", " 37.53  ", " 50.53  ", " 28.8   ", " 25.06",
    " 87.73  ", " 98.68  ", " 119.95 ", " 150.74 ", " 214.35 ", " 118.5  ",
    " 129.19", " 32.36  ", " 36.52  ", " 42.67  ", " 56.55  ", " 89.22  ",
    " 49.97  ", " 50.62", "35.09  ", " 40.77  ", " 48.43  ", " 82.61  ",
    " 120.1  ", " 72.43  ", " 76.69", " 47.21  ", " 67.25  ", " 78.62  ",
    " 66.64  ", " 83.78  ", " 127.79 ", " 154.11", " 86.1   ", " 127.59 ",
    " 164.43 ", " 249.32 ", " 312.01 ", " 272.09 ", " 265.68", " 83.75  ",
    " 118.41 ", " 171.52 ", " 229.27 ", " 241.63 ", " 201    ", " 213.01",
    " 36.63  ", " 52.1   ", " 66.03  ", " 101.38 ", " 126.71 ", " 95.46  ",
    " 110.03", " 57.5   ", " 75.72  ", " 101.31 ", " 147.5  ", " 171.01 ",
    " 148.66 ", " 167.93", " 29.56  ", " 38.37  ", " 48.8   ", " 65.5   ",
    " 84.77  ", " 75.2   ", " 81.27", " 77.28  ", " 93.7   ", " 119.62 ",
    " 247    ", " 301.76 ", " 222.52 ", " 244.46", " 45.6   ", " 54.32  ",
    " 87.81  ", " 132.93 ", " 163.62 ", " 152.99 ", " 170.85", " 27.13  ",
    " 36.96  ", " 48.94  ", " 80.01  ", " 124.07 ", " 93.49  ", " 105.57",
    " 54.55  ", " 85.93  ", " 102.3  ", " 122.7  ", " 168.36 ", " 151.79 ",
    " 169.65", " 86.19  ", " 121.82 ", " 191.7  ", " 247.75 ", " 260.23 ",
    " 196.48 ", " 243.06", "47.35  ", " 60.63  ", " 76.4   ", " 93.04  ",
    " 102.13 ", " 98.29  ", " 86.27", " 10.93  ", " 13.33  ", " 16.82  ",
    " 18.2   ", " 23.48  ", " 16.52  ", " 16.19", "   NA   ", "  NA    ",
    "   NA   ", "  NA    ", " 69.46  ", " 54.22  ", " 60.16", " 60.93  ",
    " 89.86  ", " 141.85 ", " 207.9  ", " 182.79 ", " 159.1  ", " 159.46",
    " 15.37  ", " 18.48  ", " 24.33  ", " 38.37  ", " 45.87  ", " 34.86  ",
    " 31.96", " 34.05  ", " 40.1   ", " 55.02  ", " 58.31  ", " 86.89  ",
    " 65.68  ", " 65.68", "1.51   ", " 0.93   ", " 1      ", " 1.78   ",
    " 2.8    ", " 1.56   ", " 1.41", " 27.15  ", " 31.37  ", " 39.46  ",
    " 40.33  ", " 61.86  ", " 45.18  ", " 57.71", " 14.74  ", " 16.3   ",
    " 25.06  ", " 31.74  ", " 37.39  ", " 27.18  ", " 30.49", " 3.59   ",
    " 4.86   ", " 5.67   ", " 6.36   ", " 7.6    ", " 4.8    ", " 5.5",
    "4.73   ", " 5.68   ", " 7.3    ", " 8.53   ", " 11.03  ", " 8.44   ",
    " 9.84", "16.76  ", " 24.83  ", " 32.66  ", " 46.22  ", " 48.01  ",
    " 43.44  ", " 48.29"
  ),
  nrow = 7L,
  ncol = 31L,
  dimnames = list(
    c("1990", "1991", "1992", "1993", "1994", "1995", "1996"),
    c(
      "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
      "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23",
      "24", "25", "26", "27", "28", "29", "30", "31"
    )
  )
)

sessionInfo() gave the following:

    > sessionInfo()
R version 3.0.0 (2013-04-03)
Platform: x86_64-apple-darwin10.8.0 (64-bit)

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] gdata_2.13.2

loaded via a namespace (and not attached):
[1] gtools_2.7.1 tools_3.0.0

Body:
I think you can just apply:

data.matrix(frame, rownames.force = NA)

Here more info: https://stat.ethz.ch/R-manual/R-devel/library/base/html/data.matrix.html


问:
How to make a list of numbers from a txt file in python?
I have text file containing the numbers 52, 2,103,592,2090,34452,0,1, but arranged as one column (under each other). I want to import the numbers into python and create a list

```<code>L=[52,2,103,592,2090,34452,0,1]
</code>```

The best I have managed to do so far is:

```<code>txtfile=open('file.txt')

L=[]
for line in txtfile:
    L.append(line.rstrip())

print(L)
</code>```

which returns:

```<code>L=['52','2','103','592','2090','34452','0','1']

</code>```

but the ' around the numbers bother me.

Any help is appreciated.

答:
You can use int() to convert string to integer, but I'd also like to emphasize using with keyword for handling files.

```<code>L = []
with open('file.txt') as txtfile:
    for line in txtfile:
        L.append(int(line.rstrip()))
</code>```

Edit: You can also read without for loop, by using map and split like so:

```<code>with open('file.txt') as txtfile:
    L = list(map(int, txtfile.read().split('\n')))
</code>```

Body:
I have text file containing the numbers 52, 2,103,592,2090,34452,0,1, but arranged as one column (under each other). I want to import the numbers into python and create a list

L=[52,2,103,592,2090,34452,0,1]

The best I have managed to do so far is:

txtfile=open('file.txt')

L=[]
for line in txtfile:
    L.append(line.rstrip())

print(L)

which returns:

L=['52','2','103','592','2090','34452','0','1']

but the ' around the numbers bother me.

Any help is appreciated.

Body:
You can use int() to convert string to integer, but I'd also like to emphasize using with keyword for handling files.

L = []
with open('file.txt') as txtfile:
    for line in txtfile:
        L.append(int(line.rstrip()))

Edit: You can also read without for loop, by using map and split like so:

with open('file.txt') as txtfile:
    L = list(map(int, txtfile.read().split('\n')))


问:
Automate uploading users image to Active Directory using Powershell
I have a code that finds all AD users and compares them to our photo folder. If they arent a user the image is archived, if it is found then nothing happens. What I want to do is if the user exists and the thumbnail attribute is empty, then upload the image to the thumbnail. This has proven to be harder than expected. Any idea of how to mass upload images?
My code currently is</p>

```<code>$usersWithoutImage = Get-ADUser -Filter * -properties thumbnailPhoto | ? {(-not($_.thumbnailPhoto))}
| select Name
$repPics = (Get-childItem \\web01\rep-pics).basename

ForEach ($image in $usersWithoutImage){
    if ($usersWithoutImage -eq $repPics){
        $ADphoto = [byte[]](Get-Content $image -Encoding byte)
        Set-ADUser $repPics -Replace @{thumbnailPhoto=$ADphoto}

}
}
</code>```

答:
Step one is to add some logging so you know if and when certain branches of code are hit.

```<code>$repPics = (Get-childItem \\web01\rep-pics).basename
Write-host "Found $($usersWithoutImage.Count) users without a photo"
ForEach ($image in $usersWithoutImage){
    if ($usersWithoutImage -eq $repPics){
        Write-host "Users name [$image] is in the users photo directory, uploading..."
        $ADphoto = [byte[]](Get-Content $image -Encoding byte)
        Set-ADUser $repPics -Replace @{thumbnailPhoto=$ADphoto}
    }
    else{
        Write-Warning "Users name [$image] is NOT in the users photo directory, please update!!"
    }
}
</code>```

Doing some analysis of your code reveals this line...

```<code>    if ($usersWithoutImage -eq $repPics){

</code>```

Which will never evaluate to true because the comparison doesn't make sense.  You should check to see if the current user is -in the array of $repPics, not if it -equals, because that will never be the case.  I'd rewrite it like this:

```<code>ForEach ($user in $usersWithoutImage){
    if ($repPics -contains $user){
</code>```

So your completed code would look like this:

```<code>$repPics = (Get-childItem \\web01\rep-pics).basename
Write-host "Found $($usersWithoutImage.Count) users without a photo"
ForEach ($user in $usersWithoutImage){
    if ($repPics -contains $user){
        Write-host "Users name [$user] is in the users photo directory, uploading..."
        $imagePath = ".\$($user).png"
        $ADphoto = [byte[]](Get-Content $imagePath -Encoding byte)
        Set-ADUser $user -Replace @{thumbnailPhoto=$ADphoto}
    }
    else{
        Write-Warning "Users name [$user] is NOT in the users photo directory, please update!!"
    }
}
</code>```

One last thing is that you need to update line $imagePath =... to match your file path and file type.

Body:
I have a code that finds all AD users and compares them to our photo folder. If they arent a user the image is archived, if it is found then nothing happens. What I want to do is if the user exists and the thumbnail attribute is empty, then upload the image to the thumbnail. This has proven to be harder than expected. Any idea of how to mass upload images?
My code currently is

$usersWithoutImage = Get-ADUser -Filter * -properties thumbnailPhoto | ? {(-not($_.thumbnailPhoto))}
| select Name
$repPics = (Get-childItem \\web01\rep-pics).basename

ForEach ($image in $usersWithoutImage){
    if ($usersWithoutImage -eq $repPics){
        $ADphoto = [byte[]](Get-Content $image -Encoding byte)
        Set-ADUser $repPics -Replace @{thumbnailPhoto=$ADphoto}

}
}

Body:
Step one is to add some logging so you know if and when certain branches of code are hit.

$repPics = (Get-childItem \\web01\rep-pics).basename
Write-host "Found $($usersWithoutImage.Count) users without a photo"
ForEach ($image in $usersWithoutImage){
    if ($usersWithoutImage -eq $repPics){
        Write-host "Users name [$image] is in the users photo directory, uploading..."
        $ADphoto = [byte[]](Get-Content $image -Encoding byte)
        Set-ADUser $repPics -Replace @{thumbnailPhoto=$ADphoto}
    }
    else{
        Write-Warning "Users name [$image] is NOT in the users photo directory, please update!!"
    }
}

Doing some analysis of your code reveals this line...

    if ($usersWithoutImage -eq $repPics){

Which will never evaluate to true because the comparison doesn't make sense.  You should check to see if the current user is -in the array of $repPics, not if it -equals, because that will never be the case.  I'd rewrite it like this:

ForEach ($user in $usersWithoutImage){
    if ($repPics -contains $user){

So your completed code would look like this:

$repPics = (Get-childItem \\web01\rep-pics).basename
Write-host "Found $($usersWithoutImage.Count) users without a photo"
ForEach ($user in $usersWithoutImage){
    if ($repPics -contains $user){
        Write-host "Users name [$user] is in the users photo directory, uploading..."
        $imagePath = ".\$($user).png"
        $ADphoto = [byte[]](Get-Content $imagePath -Encoding byte)
        Set-ADUser $user -Replace @{thumbnailPhoto=$ADphoto}
    }
    else{
        Write-Warning "Users name [$user] is NOT in the users photo directory, please update!!"
    }
}

One last thing is that you need to update line $imagePath =... to match your file path and file type.


问:
Material-Table in React. Dynamically setting table options with state variables
Im new to this Material-Table table.  Im trying to set its options based upon what the user selects to do.

For example, I want to turn on/off filtering based upon if the user want to filter or not.

I have a button that sets a state variable true or false depending on when its selected.

```<code>    this.state = {
        filterStatus:false,
    }
</code>```

But my options property doesnt allow me to use the state variable.

```<code>     options={{
           filtering: {this.state.filterStatus}
             }}
</code>```

Is there a way to do this?

I want the user to be able to simplily have the option to turn off filtering with a push button.

To go from this,

enter image description here

to this

enter image description here

答:
You can use filtering under options in MaterialTable as below:

```<code><MaterialTable
            title="Basic Filtering Preview"
            columns={state.columns}
            data={state.data}
            options={{
                filtering: state.filtering
            }}
            icons={tableIcons}
        />
</code>```

In this example, I used a toggle button to trun off/on  filtering.

Here is the Code Sandbox

Body:
Im new to this Material-Table table.  Im trying to set its options based upon what the user selects to do.

For example, I want to turn on/off filtering based upon if the user want to filter or not.

I have a button that sets a state variable true or false depending on when its selected.

    this.state = {
        filterStatus:false,
    }

But my options property doesnt allow me to use the state variable.

     options={{
           filtering: {this.state.filterStatus}
             }}

Is there a way to do this?

I want the user to be able to simplily have the option to turn off filtering with a push button.

To go from this,

enter image description here

to this

enter image description here

Body:
You can use filtering under options in MaterialTable as below:

<MaterialTable
            title="Basic Filtering Preview"
            columns={state.columns}
            data={state.data}
            options={{
                filtering: state.filtering
            }}
            icons={tableIcons}
        />

In this example, I used a toggle button to trun off/on  filtering.

Here is the Code Sandbox


问:
Button function called twice after DatePicker change
If I manually enter a date into a sap.m.DatePicker (typing it not using the value help picker) and press a button straight away without losing focus on the field, the button doesn't do anything which is correct, but when I click it again the press function is called twice.

It seems like the change event is called when I click over the button, so the button isn't pressed, but when I then press the button again it fires twice.

https://jsfiddle.net/saznxrs6/

```<code>onDateChange: function(){
    alert("date changed");
},
onSubmit: function(){
    alert("Hello!");
}
</code>```

Enter a date into the picker manually i.e. 01/12/2017, then click the submit button without losing focus on the date field first. You should see an alert for the date changed. Click the button again, you should get two alerts for the button function.

Is this a UI5 bug or something I am doing wrong?

答:
The issue is reproducible only with alert() which ...

... is handled differently depending on the browser.

... UI5 apps shouldn't deal with in the production environment.

Replace alert with console.log and you can see that the handlers are executed as expected:

Press: "date changed", "hello"

Press: "hello"

Body:
If I manually enter a date into a sap.m.DatePicker (typing it not using the value help picker) and press a button straight away without losing focus on the field, the button doesn't do anything which is correct, but when I click it again the press function is called twice.

It seems like the change event is called when I click over the button, so the button isn't pressed, but when I then press the button again it fires twice.

https://jsfiddle.net/saznxrs6/

onDateChange: function(){
    alert("date changed");
},
onSubmit: function(){
    alert("Hello!");
}

Enter a date into the picker manually i.e. 01/12/2017, then click the submit button without losing focus on the date field first. You should see an alert for the date changed. Click the button again, you should get two alerts for the button function.

Is this a UI5 bug or something I am doing wrong?


问:
Multithread performance
I created very simple app to figure out how boost::thread works.
I found result of this test suprising.
4 threads of execution finish computation 2 times faster than 1 thread.
I expected 4x boost.
Another question is why 8 threads did not bring any performance boost?

I'm using boost 1.46.1 and VS2008. Full source code is below.
Program was run on Core i5 750 machine.

```<code>#include <iostream>
#include <vector>
#include <cmath>

#include <boost/thread.hpp>
#include <boost/timer.hpp>

typedef unsigned int uint;

struct Vector {
    float x, y, z;

    Vector() : x(0.f), y(0.f), z(0.f) {}

    float len() {
        return sqrtf(x*x + y*y + z*z);
    }

};

float norm(int a) {
    return float((a % 10) + 1) / 10.f;
}

void genVectors(std::vector<Vector>& examples) {
    srand(GetTickCount());

    for (uint i = 0; i < examples.size(); ++i) {
        examples[i].x = norm(rand());
        examples[i].y = norm(rand());
        examples[i].z = norm(rand());
    }

}

typedef std::vector<Vector> Data;
typedef Data::iterator DataIter;

typedef std::vector<float> Result;
typedef Result::iterator ResultIter;

struct Worker {
    Data   data;
    Result result;

    Worker(DataIter& dataStart,
           const DataIter& dataEnd,
           ResultIter& resultStart,
           const ResultIter& resultEnd) : data(dataStart, dataEnd), result(resultStart, resultEnd) {
        assert(data.size() == result.size());
    }

    void operator()() {
        DataIter di = data.begin();
        ResultIter ri = result.begin();

        const DataIter dend = data.end();

        for (; di != dend; ++di, ++ri) {
            *ri = di->len();
        }
    }
};

int main(int argc, char **argv) {
    const uint numThreads = 4;
    const uint seqLen = 13107200;

    std::vector<Vector> a;
    a.resize(seqLen);

    genVectors(a);

    std::vector<float> singleThreadResult(a.size());
    assert(a.size() == singleThreadResult.size());

    boost::timer singleThreadTimer;
    for (uint i = 0; i < a.size(); ++i) {
        singleThreadResult[i] = a[i].len();
    }
    double singleThreadTime = singleThreadTimer.elapsed();

    std::vector<float> multiThreadResult(a.size());

    Worker* workers[numThreads];
    for (uint i = 0; i < numThreads; ++i) {
        uint chunkSize = seqLen / numThreads;
        assert(numThreads * chunkSize == seqLen);

        workers[i] = new Worker(a.begin() + i*chunkSize,
                                a.begin() + (i+1)*chunkSize,
                                multiThreadResult.begin() + i*chunkSize,
                                multiThreadResult.begin() + (i+1)*chunkSize);
    }

    boost::timer multiThreadTimer;
    boost::thread_group threads;
    for (uint i = 0; i < numThreads; ++i) {
        threads.create_thread(boost::ref(*workers[i]));
    }
    threads.join_all();
    double multiThreadTime = multiThreadTimer.elapsed();

    using namespace std;
    cout << "Single thread time: " << singleThreadTime << endl;
    cout << numThreads << " threads time: " << multiThreadTime << endl;

    return 0;
}
</code>```

答: When you use system threading, there is no guarantee that every thread will be run on a separate core. You can't assign a core for a thread - that's the OS task. And given that you have 4 threads in your application, the OS can really run them on a single core depending on the overall CPU load and gazillion other factors.</p>

Title: Multithread performance

Body:
I created very simple app to figure out how boost::thread works.
I found result of this test suprising.
4 threads of execution finish computation 2 times faster than 1 thread.
I expected 4x boost.
Another question is why 8 threads did not bring any performance boost?

I'm using boost 1.46.1 and VS2008. Full source code is below.
Program was run on Core i5 750 machine.

#include <iostream>
#include <vector>
#include <cmath>

#include <boost/thread.hpp>
#include <boost/timer.hpp>

typedef unsigned int uint;

struct Vector {
    float x, y, z;

    Vector() : x(0.f), y(0.f), z(0.f) {}

    float len() {
        return sqrtf(x*x + y*y + z*z);
    }

};

float norm(int a) {
    return float((a % 10) + 1) / 10.f;
}

void genVectors(std::vector<Vector>& examples) {
    srand(GetTickCount());

    for (uint i = 0; i < examples.size(); ++i) {
        examples[i].x = norm(rand());
        examples[i].y = norm(rand());
        examples[i].z = norm(rand());
    }

}

typedef std::vector<Vector> Data;
typedef Data::iterator DataIter;

typedef std::vector<float> Result;
typedef Result::iterator ResultIter;

struct Worker {
    Data   data;
    Result result;

    Worker(DataIter& dataStart,
           const DataIter& dataEnd,
           ResultIter& resultStart,
           const ResultIter& resultEnd) : data(dataStart, dataEnd), result(resultStart, resultEnd) {
        assert(data.size() == result.size());
    }

    void operator()() {
        DataIter di = data.begin();
        ResultIter ri = result.begin();

        const DataIter dend = data.end();

        for (; di != dend; ++di, ++ri) {
            *ri = di->len();
        }
    }
};

int main(int argc, char **argv) {
    const uint numThreads = 4;
    const uint seqLen = 13107200;

    std::vector<Vector> a;
    a.resize(seqLen);

    genVectors(a);

    std::vector<float> singleThreadResult(a.size());
    assert(a.size() == singleThreadResult.size());

    boost::timer singleThreadTimer;
    for (uint i = 0; i < a.size(); ++i) {
        singleThreadResult[i] = a[i].len();
    }
    double singleThreadTime = singleThreadTimer.elapsed();

    std::vector<float> multiThreadResult(a.size());

    Worker* workers[numThreads];
    for (uint i = 0; i < numThreads; ++i) {
        uint chunkSize = seqLen / numThreads;
        assert(numThreads * chunkSize == seqLen);

        workers[i] = new Worker(a.begin() + i*chunkSize,
                                a.begin() + (i+1)*chunkSize,
                                multiThreadResult.begin() + i*chunkSize,
                                multiThreadResult.begin() + (i+1)*chunkSize);
    }

    boost::timer multiThreadTimer;
    boost::thread_group threads;
    for (uint i = 0; i < numThreads; ++i) {
        threads.create_thread(boost::ref(*workers[i]));
    }
    threads.join_all();
    double multiThreadTime = multiThreadTimer.elapsed();

    using namespace std;
    cout << "Single thread time: " << singleThreadTime << endl;
    cout << numThreads << " threads time: " << multiThreadTime << endl;

    return 0;
}


问:
how to get full path with os.walk function in python
i am using os.walk to find directories, but it does not show the full path

code:

```<code>for root, subdirs, files in os.walk(path):
    print(subdirs)
</code>```

I assign system/ value to path.

Expected output:
system/a/a

Output: a

Now i could use glob.glob, but that lists symlinks, and i do not want that

答:
```<code>for root, dirnames, fnames in os.walk(path):
    print("I am looking in", root)
    print("These are the subdirectories:")
    for dirname in dirnames:
        print(os.path.join(root, dirname))

    print("These are the filenames:")
    for fname in fnames:
        print(os.path.join(root, fname))
</code>```

Body:
i am using os.walk to find directories, but it does not show the full path

code:

for root, subdirs, files in os.walk(path):
    print(subdirs)

I assign system/ value to path.

Expected output:
system/a/a

Output: a

Now i could use glob.glob, but that lists symlinks, and i do not want that


问:
Issue with adding independent filters search to multiple parameters in SSRS
I have been trying to create a report with multiple parameters. My requirement is to keep those parameters separate from each other while searching the report. in this picture we have four input values but they are codependent which each other and the requirement says the client should be able to see the data with one filter input Can anyone can help me how to separate these individual searchers. </p>

答:
It depends on if your parameters are related or not. If they are then please edit your question and I will update the answer.

However as a general rule you should set all parameters to allow NULL

Then in your dataset query your query would look something like

```<code>SELECT *
    FROM myTable
    WHERE (
        (region IN (@region) or @region IS NULL)
        AND
        (cocode IN (@cocode) or @cocode IS NULL)
        AND
        (prodcode IN (@prodcode) or @prodcode IS NULL)
        AND
        (datetimestamp IN(@datetimestamp) or @datetimestamp IS NULL)
        )
</code>```

I've used IN here in case your parameters allow multiple values, if they don't this will still work but you could change each part of the where clause to read for example, (region = @region or @region IS NULL)

If this does not help, please post a sample of your data and a sample of each of your parameter values, including any relationships between them.

Body:
It depends on if your parameters are related or not. If they are then please edit your question and I will update the answer.

However as a general rule you should set all parameters to allow NULL

Then in your dataset query your query would look something like

SELECT *
    FROM myTable
    WHERE (
        (region IN (@region) or @region IS NULL)
        AND
        (cocode IN (@cocode) or @cocode IS NULL)
        AND
        (prodcode IN (@prodcode) or @prodcode IS NULL)
        AND
        (datetimestamp IN(@datetimestamp) or @datetimestamp IS NULL)
        )

I've used IN here in case your parameters allow multiple values, if they don't this will still work but you could change each part of the where clause to read for example, (region = @region or @region IS NULL)

If this does not help, please post a sample of your data and a sample of each of your parameter values, including any relationships between them.


问:
How do I print the index of the maximum and minimum values?
The following code prints the maximum and minimum value. How do I go about printing the index of those values rather than the values themselves?</p>

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

int main()
{
    int arr1[100];
    int i, mx, mn, n;

       printf("Input the number of elements to be stored in the array :");
       scanf("%d",&n);

       printf("Input %d elements in the array :\n",n);
       for(i=0;i<n;i++)
            {
          printf("element - %d : ",i);
          scanf("%d",&arr1[i]);
        }

    mx = arr1[0];
    mn = arr1[0];

    for(i=1; i<n; i++)
    {
        if(arr1[i]>mx)
        {
            mx = arr1[i];
        }

        if(arr1[i]<mn)
        {
            mn = arr1[i];
        }
    }
    printf("Maximum element is : %d\n", mx);
    printf("Minimum element is : %d\n\n", mn);

    return 0;
}
</code>```

答:
It is not difficult to change your code that to track the indices of minimum and maximum elements.

Just store in the variables mx and mn indices of correspondingly minimum and maximum elements instead of their values as for example.

```<code>mx = 0;
mn = 0;

for ( i = 1; i < n; i++ )
{
    if ( arr1[i] > arr1[mx] )
    {
        mx = i;
    }
    else if ( arr1[i] < mn )
    {
        mn = i;
    }
}
</code>```

But I would like to point out that try always to write a more general code.

You could write a separate function that returns a pair of indices of maximum and minimum elements.

Here you are.

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

struct Pair { size_t min; size_t max; }
minmax_element( const int a[], size_t n )
{
    struct Pair minmax = { .min = 0, .max = 0 };

    for ( size_t i = 1; i < n; i++ )
    {
        if ( a[i] < a[minmax.min] )
        {
            minmax.min = i;
        }
        else if ( a[minmax.max] < a[i] )
        {
            minmax.max = i;
        }
    }

    return minmax;
}

int main(void)
{
    size_t n = 1;

    printf( "Input the number of elements to be stored in the array: " );
    scanf( "%zu", &n );

    int a[n];

    srand( ( unsigned int )time( NULL ) );

    for ( size_t i = 0; i < n; i++ )
    {
        a[i] = rand() % ( int )n;
    }

    for ( size_t i = 0; i < n; i++ )
    {
        printf( "%d ", a[i] );
    }
    putchar( '\n' );

    struct Pair minmax = minmax_element( a, n );

    printf( "The minimum value is %d at position %zu\n", a[minmax.min], minmax.min );
    printf( "The maximum value is %d at position %zu\n", a[minmax.max], minmax.max );

    return 0;
}
</code>```

The program output might look for example like

```<code>Input the number of elements to be stored in the array: 10
7 1 7 3 1 7 8 5 0 3
The minimum value is 0 at position 8
The maximum value is 8 at position 6
</code>```

Alternatively the function can be defined with two additional parameters: pointer to the index of minimum element and pointer to the index of maximum element.

Here you are.

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

void minmax_element( const int a[], size_t n, size_t *min, size_t *max )
{
    *min = 0;
    *max = 0;

    for ( size_t i = 1; i < n; i++ )
    {
        if ( a[i] < a[*min] )
        {
            *min = i;
        }
        else if ( a[*max] < a[i] )
        {
            *max = i;
        }
    }
}

int main(void)
{
    size_t n = 1;

    printf( "Input the number of elements to be stored in the array: " );
    scanf( "%zu", &n );

    int a[n];

    srand( ( unsigned int )time( NULL ) );

    for ( size_t i = 0; i < n; i++ )
    {
        a[i] = rand() % ( int )n;
    }

    for ( size_t i = 0; i < n; i++ )
    {
        printf( "%d ", a[i] );
    }
    putchar( '\n' );

    size_t min, max;

    minmax_element( a, n, &min, &max );

    printf( "The minimum value is %d at position %zu\n", a[min], min );
    printf( "The maximum value is %d at position %zu\n", a[max], max );

    return 0;
}
</code>```

The program output might look like

```<code>Input the number of elements to be stored in the array: 10
2 0 4 2 4 3 0 9 1 0
The minimum value is 0 at position 1
The maximum value is 9 at position 7
</code>```

Body:
The following code prints the maximum and minimum value. How do I go about printing the index of those values rather than the values themselves?

#include <stdio.h>

int main()
{
    int arr1[100];
    int i, mx, mn, n;

       printf("Input the number of elements to be stored in the array :");
       scanf("%d",&n);

       printf("Input %d elements in the array :\n",n);
       for(i=0;i<n;i++)
            {
          printf("element - %d : ",i);
          scanf("%d",&arr1[i]);
        }

    mx = arr1[0];
    mn = arr1[0];

    for(i=1; i<n; i++)
    {
        if(arr1[i]>mx)
        {
            mx = arr1[i];
        }

        if(arr1[i]<mn)
        {
            mn = arr1[i];
        }
    }
    printf("Maximum element is : %d\n", mx);
    printf("Minimum element is : %d\n\n", mn);

    return 0;
}

Body:
It is not difficult to change your code that to track the indices of minimum and maximum elements.

Just store in the variables mx and mn indices of correspondingly minimum and maximum elements instead of their values as for example.

mx = 0;
mn = 0;

for ( i = 1; i < n; i++ )
{
    if ( arr1[i] > arr1[mx] )
    {
        mx = i;
    }
    else if ( arr1[i] < mn )
    {
        mn = i;
    }
}

But I would like to point out that try always to write a more general code.

You could write a separate function that returns a pair of indices of maximum and minimum elements.

Here you are.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

struct Pair { size_t min; size_t max; }
minmax_element( const int a[], size_t n )
{
    struct Pair minmax = { .min = 0, .max = 0 };

    for ( size_t i = 1; i < n; i++ )
    {
        if ( a[i] < a[minmax.min] )
        {
            minmax.min = i;
        }
        else if ( a[minmax.max] < a[i] )
        {
            minmax.max = i;
        }
    }

    return minmax;
}

int main(void)
{
    size_t n = 1;

    printf( "Input the number of elements to be stored in the array: " );
    scanf( "%zu", &n );

    int a[n];

    srand( ( unsigned int )time( NULL ) );

    for ( size_t i = 0; i < n; i++ )
    {
        a[i] = rand() % ( int )n;
    }

    for ( size_t i = 0; i < n; i++ )
    {
        printf( "%d ", a[i] );
    }
    putchar( '\n' );

    struct Pair minmax = minmax_element( a, n );

    printf( "The minimum value is %d at position %zu\n", a[minmax.min], minmax.min );
    printf( "The maximum value is %d at position %zu\n", a[minmax.max], minmax.max );

    return 0;
}

The program output might look for example like

Input the number of elements to be stored in the array: 10
7 1 7 3 1 7 8 5 0 3
The minimum value is 0 at position 8
The maximum value is 8 at position 6

Alternatively the function can be defined with two additional parameters: pointer to the index of minimum element and pointer to the index of maximum element.

Here you are.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void minmax_element( const int a[], size_t n, size_t *min, size_t *max )
{
    *min = 0;
    *max = 0;

    for ( size_t i = 1; i < n; i++ )
    {
        if ( a[i] < a[*min] )
        {
            *min = i;
        }
        else if ( a[*max] < a[i] )
        {
            *max = i;
        }
    }
}

int main(void)
{
    size_t n = 1;

    printf( "Input the number of elements to be stored in the array: " );
    scanf( "%zu", &n );

    int a[n];

    srand( ( unsigned int )time( NULL ) );

    for ( size_t i = 0; i < n; i++ )
    {
        a[i] = rand() % ( int )n;
    }

    for ( size_t i = 0; i < n; i++ )
    {
        printf( "%d ", a[i] );
    }
    putchar( '\n' );

    size_t min, max;

    minmax_element( a, n, &min, &max );

    printf( "The minimum value is %d at position %zu\n", a[min], min );
    printf( "The maximum value is %d at position %zu\n", a[max], max );

    return 0;
}

The program output might look like

Input the number of elements to be stored in the array: 10
2 0 4 2 4 3 0 9 1 0
The minimum value is 0 at position 1
The maximum value is 9 at position 7


问:
the first io.emit is never getting sent
```<code>io.on('connection',function(socket){
console.log('connected');
socket.on('disconnect',()=>{
    console.log('a user disconnected');
});
socket.on('sendMessage',function(data){
    const message = data.text;
    const cookieList = socket.handshake.headers.cookie;
    const parsedCookies = myModule.parseCookies(cookieList);
    if(parsedCookies.nickName!==undefined){
        socket.nickName = parsedCookies.nickName;
    }
    io.emit('showMessage',{
        'message':message,
        'nickName':socket.nickName
    });
});
});
</code>```

this is my server code

```<code>'use strict';
 let socket = io();
 window.addEventListener('load',function(){
const button = document.querySelector('.btn');
button.addEventListener('click',function(event){
    const inputText = document.getElementById('msg').value;
    try{
        event.preventDefault();
        if(inputText.length<2){
            throw "some error";
        }else{
            const errorMessage = document.querySelector('.row p');
            if(errorMessage){
                errorMessage.remove();
            }
            socket.emit('sendMessage',{
                'text':inputText
            });
            showMessage();
        }
    }catch(error){
        const div  = document.querySelector('.row');
        console.log('error');
        if(!div.querySelector('p')){
            const errorP = document.createElement('p');
            errorP.setAttribute('style','color:red;');
            const errorMessage = document.createTextNode(error);
            errorP.appendChild(errorMessage);
            div.appendChild(errorP);
        }
    }
});
});
function showMessage(){
socket.on('showMessage',function(data){
    console.log("nickname :"+data.nickName + " message :"+data.message);
});
}
</code>```

this is my client side code

Problem is the first message is never getting sent.
Tried it both on chrome and firefox

From second messages communication works fine.. I cannot understand why the first message is not working

答:
socket.on('showMessage',function(data) shouldn't be wrapped in a function or be called every time you send a message. Because of this, your socket never knows how to handle an incoming "showMessage" event until after it has already received one. Replace your client code with this and it should work:

'use strict';
let socket = io();
window.addEventListener('load', function () {
    const button = document.querySelector('.btn');

    socket.on('showMessage', function (data) {
        console.log("nickname :" + data.nickName + " message :" + data.message);
    });

    button.addEventListener('click', function (event) {
        const inputText = document.getElementById('msg').value;
        try {
            event.preventDefault();
            if (inputText.length < 2) {
                throw "some error";
            } else {
                const errorMessage = document.querySelector('.row p');
                if (errorMessage) {
                    errorMessage.remove();
                }
                socket.emit('sendMessage', {
                    'text': inputText
                });
            }
        } catch (error) {
            const div = document.querySelector('.row');
            console.log('error');
            if (!div.querySelector('p')) {
                const errorP = document.createElement('p');
                errorP.setAttribute('style', 'color:red;');
                const errorMessage = document.createTextNode(error);
                errorP.appendChild(errorMessage);
                div.appendChild(errorP);
            }
        }
    });
});

```

Title: the first io.emit is never getting sent

Body:
io.on('connection',function(socket){
console.log('connected');
socket.on('disconnect',()=>{
    console.log('a user disconnected');
});
socket.on('sendMessage',function(data){
    const message = data.text;
    const cookieList = socket.handshake.headers.cookie;
    const parsedCookies = myModule.parseCookies(cookieList);
    if(parsedCookies.nickName!==undefined){
        socket.nickName = parsedCookies.nickName;
    }
    io.emit('showMessage',{
        'message':message,
        'nickName':socket.nickName
    });
});
});

this is my server code

'use strict';
 let socket = io();
 window.addEventListener('load',function(){
const button = document.querySelector('.btn');
button.addEventListener('click',function(event){
    const inputText = document.getElementById('msg').value;
    try{
        event.preventDefault();
        if(inputText.length<2){
            throw "some error";
        }else{
            const errorMessage = document.querySelector('.row p');
            if(errorMessage){
                errorMessage.remove();
            }
            socket.emit('sendMessage',{
                'text':inputText
            });
            showMessage();
        }
    }catch(error){
        const div  = document.querySelector('.row');
        console.log('error');
        if(!div.querySelector('p')){
            const errorP = document.createElement('p');
            errorP.setAttribute('style','color:red;');
            const errorMessage = document.createTextNode(error);
            errorP.appendChild(errorMessage);
            div.appendChild(errorP);
        }
    }
});
});
function showMessage(){
socket.on('showMessage',function(data){
    console.log("nickname :"+data.nickName + " message :"+data.message);
});
}

this is my client side code

Problem is the first message is never getting sent.
Tried it both on chrome and firefox

From second messages communication works fine.. I cannot understand why the first message is not working


问:
Fill a vector with zero values
I have a named numeric vector like this:

```<code>c(`1` = 2, `5` = 3, `6` = 1, `7` = 2, `8` = 1, `9` = 1)
#1 5 6 7 8 9 (names)
#2 3 1 2 1 1 (values)
</code>```

I want to expand the vector so that the names form a sequence of integers and fill the values with 0.

Here is my expected output:

```<code>c(`1` = 2, `2` = 0, `3` = 0, `4` = 0, `5` = 3, `6` = 1, `7` = 2, `8` = 1, `9` = 1)
#1 2 3 4 5 6 7 8 9
#2 0 0 0 3 1 2 1 1
</code>```

Any help?
Thanks

答:
Here is my solution using name based indexing:</p>

```<code>vec = c("1" = 2, "5" = 3, "6" = 1, "7" = 2, "8" = 1, "9" = 1)

newvec = double(9);
names(newvec) = 1:9
newvec[names(vec)] = vec;

newvec

# 1 2 3 4 5 6 7 8 9
# 2 0 0 0 3 1 2 1 1
</code>```

Title: Fill a vector with zero values

Body:
I have a named numeric vector like this:

c(`1` = 2, `5` = 3, `6` = 1, `7` = 2, `8` = 1, `9` = 1)
#1 5 6 7 8 9 (names)
#2 3 1 2 1 1 (values)

I want to expand the vector so that the names form a sequence of integers and fill the values with 0.

Here is my expected output:

c(`1` = 2, `2` = 0, `3` = 0, `4` = 0, `5` = 3, `6` = 1, `7` = 2, `8` = 1, `9` = 1)
#1 2 3 4 5 6 7 8 9
#2 0 0 0 3 1 2 1 1

Any help?
Thanks

Body:
Here is my solution using name based indexing:

vec = c("1" = 2, "5" = 3, "6" = 1, "7" = 2, "8" = 1, "9" = 1)

newvec = double(9);
names(newvec) = 1:9
newvec[names(vec)] = vec;

newvec

# 1 2 3 4 5 6 7 8 9
# 2 0 0 0 3 1 2 1 1


问:
Django REST Framework: Specify data type of SerializerMethodField
It seems SerializerMethodField assumes the data type of the field is a string, even if it is an int.  For instance, I have this field:

```<code>num_sections = serializers.SerializerMethodField(help_text="The number of sections for this course")

def get_num_sections(self, obj) -> int:
    return obj.sections.count()
</code>```

However, in the auto-generated OpenAPI schema, this field shows up as a string field.  Is there any way to set the proper data type for a SerializerMethodField?

答:
It is a bit of a heavy-handed solution, but this works for me:

```<code>num_sections = type('SerializerMethodField', (serializers.SerializerMethodField, serializers.IntegerField), dict())(
        help_text="The number of sections for this course")

def get_num_sections(self, obj) -> int:
    return obj.sections.count()
</code>```

The 3 argument type function can be used as a shorthand for making a child of two classes.

Please let me know if anyone has any better solutions or comments on this.

Body:
It seems SerializerMethodField assumes the data type of the field is a string, even if it is an int.  For instance, I have this field:

num_sections = serializers.SerializerMethodField(help_text="The number of sections for this course")

def get_num_sections(self, obj) -> int:
    return obj.sections.count()

However, in the auto-generated OpenAPI schema, this field shows up as a string field.  Is there any way to set the proper data type for a SerializerMethodField?

Body:
It is a bit of a heavy-handed solution, but this works for me:

num_sections = type('SerializerMethodField', (serializers.SerializerMethodField, serializers.IntegerField), dict())(
        help_text="The number of sections for this course")

def get_num_sections(self, obj) -> int:
    return obj.sections.count()

The 3 argument type function can be used as a shorthand for making a child of two classes.

Please let me know if anyone has any better solutions or comments on this.


问:
Why is ONE basic arithmetic operation in for loop body executed SLOWER THAN TWO arithmetic operations?
While I experimented with measuring time of execution of arithmetic operations, I came across very strange behavior. A code block containing a for loop with one arithmetic operation in the loop body was always executed slower than an identical code block, but with two arithmetic operations in the for loop body. Here is the code I ended up testing:

```<code>#include <iostream>
#include <chrono>

#define NUM_ITERATIONS 100000000

int main()
{
    // Block 1: one operation in loop body
    {
        int64_t x = 0, y = 0;
        auto start = std::chrono::high_resolution_clock::now();

        for (long i = 0; i < NUM_ITERATIONS; i++) {x+=31;}

        auto end = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double> diff = end-start;
        std::cout << diff.count() << " seconds. x,y = " << x << "," << y << std::endl;
    }

    // Block 2: two operations in loop body
    {
        int64_t x = 0, y = 0;
        auto start = std::chrono::high_resolution_clock::now();

        for (long i = 0; i < NUM_ITERATIONS; i++) {x+=17; y-=37;}

        auto end = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double> diff = end-start;
        std::cout << diff.count() << " seconds. x,y = " << x << "," << y << std::endl;
    }

    return 0;
}
</code>```

I tested this with different levels of code optimization (-O0,-O1,-O2,-O3), with different online compilers (for example onlinegdb.com), on my work machine, on my hame PC and laptop, on RaspberryPi and on my colleague's computer. I rearranged these two code blocks, repeated them, changed constants, changed operations (+, -, <<, =, etc.), changed integer types. But I always got similar result: the block with one line in loop is SLOWER than block with two lines:

1.05681 seconds. x,y = 3100000000,0

  0.90414 seconds. x,y = 1700000000,-3700000000

I checked the assembly output on https://godbolt.org/ but everything looked like I expected: second block just had one more operation in assembly output.

Three operations always behaved as expected: they are slower than one and faster than four. So why two operations produce such an anomaly?

Edit:

Let me repeat: I have such behaviour on all of my Windows and Unix machines with code not optimized. I looked at assembly I execute (Visual Studio, Windows) and I see the instructions I want to test there. Anyway if the loop is optimized away, there is nothing I ask about in the code which left. I added that optimizations notice in the question to avoid "do not measure not optimized code" answers because optimizations is not what I ask about. The question is actually why my computers execute two operations faster than one, first of all in code where these operations are not optimized away. The difference in time of execution is 5-25% on my tests (quite noticeable).

答:
ETA:  This was a guess, and Peter Cordes has made a very good argument about why it's incorrect.  Go upvote Peter's answer.

I'm leaving my answer here because some found the information useful.  Though this doesn't correctly explain the behavior seen in the OP, it highlights some of the issues that make it infeasible (and meaningless) to try to measure the speed of a particular instruction on a modern processor.

Educated guess:

It's the combined effect of pipelining, powering down portions of a core, and dynamic frequency scaling.

Modern processors pipeline so that multiple instructions can be executing at the same time.  This is possible because the processor actually works on micro-ops rather than the assembly-level instructions we usually think of as machine language.  Processors "schedule" micro-ops by dispatching them to different portions of the chip while keeping track of the dependencies between the instructions.

Suppose the core running your code has two arithmetic/logic units (ALUs).  A single arithmetic instruction repeated over and over requires only one ALU.  Using two ALUs doesn't help because the next operation depends on completion of the current one, so the second ALU would just be waiting around.

But in your two-expression test, the expressions are independent.  To compute the next value of y, you do not have to wait for the current operation on x to complete.  Now, because of power-saving features, that second ALU may be powered down at first.  The core might run a few iterations before realizing that it could make use of the second ALU.  At that point, it can power up the second ALU and most of the two-expression loop will run as fast as the one-expression loop.  So you might expect the two examples to take approximately the same amount of time.

Finally, many modern processors use dynamic frequency scaling.  When the processor detects that it's not running hard, it actually slows its clock a little bit to save power.  But when it's used heavily (and the current temperature of the chip permits), it might increase the actual clock speed as high as its rated speed.

I assume this is done with heuristics.  In the case where the second ALU stays powered down, the heuristic may decide it's not worth boosting the clock.  In the case where two ALUs are powered up and running at top speed, it may decide to boost the clock.  Thus the two-expression case, which should already be just about as fast as the one-expression case, actually runs at a higher average clock frequency, enabling it to complete twice as much work in slightly less time.

Given your numbers, the difference is about 14%.  My Windows machine idles at about 3.75 GHz, and if I push it a little by building a solution in Visual Studio, the clock climbs to about 4.25GHz (eyeballing the Performance tab in Task Manager).  That's a 13% difference in clock speed, so we're in the right ballpark.

Body:
While I experimented with measuring time of execution of arithmetic operations, I came across very strange behavior. A code block containing a for loop with one arithmetic operation in the loop body was always executed slower than an identical code block, but with two arithmetic operations in the for loop body. Here is the code I ended up testing:

#include <iostream>
#include <chrono>

#define NUM_ITERATIONS 100000000

int main()
{
    // Block 1: one operation in loop body
    {
        int64_t x = 0, y = 0;
        auto start = std::chrono::high_resolution_clock::now();

        for (long i = 0; i < NUM_ITERATIONS; i++) {x+=31;}

        auto end = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double> diff = end-start;
        std::cout << diff.count() << " seconds. x,y = " << x << "," << y << std::endl;
    }

    // Block 2: two operations in loop body
    {
        int64_t x = 0, y = 0;
        auto start = std::chrono::high_resolution_clock::now();

        for (long i = 0; i < NUM_ITERATIONS; i++) {x+=17; y-=37;}

        auto end = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double> diff = end-start;
        std::cout << diff.count() << " seconds. x,y = " << x << "," << y << std::endl;
    }

    return 0;
}

I tested this with different levels of code optimization (-O0,-O1,-O2,-O3), with different online compilers (for example onlinegdb.com), on my work machine, on my hame PC and laptop, on RaspberryPi and on my colleague's computer. I rearranged these two code blocks, repeated them, changed constants, changed operations (+, -, <<, =, etc.), changed integer types. But I always got similar result: the block with one line in loop is SLOWER than block with two lines:

1.05681 seconds. x,y = 3100000000,0

  0.90414 seconds. x,y = 1700000000,-3700000000

I checked the assembly output on https://godbolt.org/ but everything looked like I expected: second block just had one more operation in assembly output.

Three operations always behaved as expected: they are slower than one and faster than four. So why two operations produce such an anomaly?

Edit:

Let me repeat: I have such behaviour on all of my Windows and Unix machines with code not optimized. I looked at assembly I execute (Visual Studio, Windows) and I see the instructions I want to test there. Anyway if the loop is optimized away, there is nothing I ask about in the code which left. I added that optimizations notice in the question to avoid "do not measure not optimized code" answers because optimizations is not what I ask about. The question is actually why my computers execute two operations faster than one, first of all in code where these operations are not optimized away. The difference in time of execution is 5-25% on my tests (quite noticeable).


问:
Safe area not working in custom TabBarController's ViewController
In the didFinishLaunchingWithOptions of my app's AppDelegate, after initializing my UIWindow property, I set the root controller to a subclass of UITabBarController, in which I set the view controllers (and some other custom behaviour).

```<code>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    self.window = UIWindow(frame: UIScreen.main.bounds)
    self.window?.rootViewController = TabBarController() // a subclass of UITabBarController
    self.window?.makeKeyAndVisible()

    return true
}
</code>```

The issue I have is that the safe areas in the TabBarController's view controllers does not seem to work properly.

eg: sticking a view to the bottom of a view controller's view, using it's safeAreaLayoutGuide, goes behind the tab bar.

```<code>self.bottomView.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor)
</code>```

The custom behaviour (such as set tint colors, set the viewControllers and their tab bar items, or set the tabBarController's delegate - nothing crazy here) setup is made in it's viewDidLoad.

NB: I work in code only, I do not use interface builder.

答:
The issue was the way I presented programmatically the tab bar controller.
What I did in the AppDelegate's didFinishLaunchingWithOptions was :

```<code>    self.window?.rootViewController = MyTabBarController()
    self.window?.makeKeyAndVisible()
</code>```

I fixed the issue buy putting the tabbar in in a NavigationController :

```<code>    let navigationController = UINavigationController(rootViewController: MyTabBarController())
    self.window?.rootViewController = navigationController
    self.window?.makeKeyAndVisible()
</code>```

Body:
In the didFinishLaunchingWithOptions of my app's AppDelegate, after initializing my UIWindow property, I set the root controller to a subclass of UITabBarController, in which I set the view controllers (and some other custom behaviour).

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    self.window = UIWindow(frame: UIScreen.main.bounds)
    self.window?.rootViewController = TabBarController() // a subclass of UITabBarController
    self.window?.makeKeyAndVisible()

    return true
}

The issue I have is that the safe areas in the TabBarController's view controllers does not seem to work properly.

eg: sticking a view to the bottom of a view controller's view, using it's safeAreaLayoutGuide, goes behind the tab bar.

self.bottomView.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor)

The custom behaviour (such as set tint colors, set the viewControllers and their tab bar items, or set the tabBarController's delegate - nothing crazy here) setup is made in it's viewDidLoad.

NB: I work in code only, I do not use interface builder.

Body:
The issue was the way I presented programmatically the tab bar controller.
What I did in the AppDelegate's didFinishLaunchingWithOptions was :

    self.window?.rootViewController = MyTabBarController()
    self.window?.makeKeyAndVisible()

I fixed the issue buy putting the tabbar in in a NavigationController :

    let navigationController = UINavigationController(rootViewController: MyTabBarController())
    self.window?.rootViewController = navigationController
    self.window?.makeKeyAndVisible()


问:
Recursive challenge in JS combining all possible array keys in true | false versions, I attach the input and output
I have found many solutions about all posible combinations between array values but I need something different, I hope you could support me. Basically is to create all posible objects that combine array keys with true|false values, something like this:

Input: (Should return an array of 32 objects, 2exp5, two posible values in 5 keys)

```<code>let properties = ['arm','lens','season','food','size'];
</code>```

Output:

```<code>let combinations = [
  {"arm": "false","lens": "false","season": "false","food": "false","size": "false"}
  {"arm": "false","lens": "false","season": "false","food": "false","size": "true"}
  {"arm": "false","lens": "false","season": "false","food": "true","size": "true"}
  {"arm": "false","lens": "false","season": "true","food": "true","size": "true"}
  {"arm": "false","lens": "true","season": "true","food": "true","size": "true"}
  {"arm": "true","lens": "true","season": "true","food": "true","size": "true"}
  {"arm": "true","lens": "true","season": "true","food": "false","size": "true"}
  {"arm": "true","lens": "true","season": "false","food": "false","size": "true"}
  and so on...
]
</code>```

Thank you so much!

答:
Start building from empty array and add the 2 possibilities for key (true/false).
Repeat the process by traversing all keys, for each key take the available results from previous.

let properties = ["arm", "lens", "season", "food", "size"];

const addTwo = (arr, key) => {
  const result = [];
  ["true", "false"].forEach((val) =>
    arr.forEach((item) => result.push({ ...item, [key]: val }))
  );
  return result;
};

const combinations = (arr) => {
  let output = [{}];
  arr.forEach((key) => (output = addTwo(output, key)));
  return output;
};

console.log(combinations(properties));```

Body:
I have found many solutions about all posible combinations between array values but I need something different, I hope you could support me. Basically is to create all posible objects that combine array keys with true|false values, something like this:

Input: (Should return an array of 32 objects, 2exp5, two posible values in 5 keys)

let properties = ['arm','lens','season','food','size'];

Output:

let combinations = [
  {"arm": "false","lens": "false","season": "false","food": "false","size": "false"}
  {"arm": "false","lens": "false","season": "false","food": "false","size": "true"}
  {"arm": "false","lens": "false","season": "false","food": "true","size": "true"}
  {"arm": "false","lens": "false","season": "true","food": "true","size": "true"}
  {"arm": "false","lens": "true","season": "true","food": "true","size": "true"}
  {"arm": "true","lens": "true","season": "true","food": "true","size": "true"}
  {"arm": "true","lens": "true","season": "true","food": "false","size": "true"}
  {"arm": "true","lens": "true","season": "false","food": "false","size": "true"}
  and so on...
]

Thank you so much!


问:
How to just update the timestamp in duplicate rows while storing the original time stamp?
I have a python script the scrapes a website and inserts values into a MySQL database.  The script continuously scrapes a constantly updating website on a sleep delayed loop.  Right now there are 5 columns of values for example (dog, cat, mouse, lizard, snake) that are scraped from the website and the 6 column is a timestamp that is added when the row is inserted into the database by the python script.  I do not want to insert duplicate rows but I would like to retain the original timestamp as well as the updated timestamp if there is a duplicate.  An important metric for the database users is when this row was first found as well as if it is still available on the website that is being scraped.

For example: lets say the script inserted (beagle, calico, white mouse, gecko, python) at 2:30PM.  When the loop runs again in a half-hour it finds the same row but at a new timestamp of 3:00PM.  What would be the best way to not insert a duplicate record but illustrate the time difference of 30 minutes between when the row was first found and when it was last found? I am fairly decent at Python but have very little MySQL experience so perhaps I need a little help here. Do you think I should put this functionality in at the script side or on the database side through a SQL query?  If so how can this be done?

Thanks!

答:
I would suggest:

having two different timestamp columns: on that stores the date when the record was created, the other to store the last modified date. This can be easily done in MySQL with default values, so you don’t need to manage these columns from your application code

creating a unique (or primary key) constraint on all other columns, so you can use the ON DUPLICATE KEY syntax when processing new data

Setup:

```<code>create table mytable (
    dog varchar(50),
    cat varchar(50),
    mouse varchar(50),
    lizard varchar(50),
    snake varchar(50),
    created_at timestamp
        default current_timestamp,
    modified_at timestamp
        default current_timestamp
        on update current_timestamp,
    primary key (dog, cat, mouse, lizard, snake)
);
</code>```

Sample insert/update statement:

```<code>insert into mytable
    (dog, cat, mouse, lizard, snake)
values(?, ?, ?, ?, ?)
on duplicate key update modified_at = current_timestamp
</code>```

Body:
I would suggest:

having two different timestamp columns: on that stores the date when the record was created, the other to store the last modified date. This can be easily done in MySQL with default values, so you don’t need to manage these columns from your application code

creating a unique (or primary key) constraint on all other columns, so you can use the ON DUPLICATE KEY syntax when processing new data

Setup:

create table mytable (
    dog varchar(50),
    cat varchar(50),
    mouse varchar(50),
    lizard varchar(50),
    snake varchar(50),
    created_at timestamp
        default current_timestamp,
    modified_at timestamp
        default current_timestamp
        on update current_timestamp,
    primary key (dog, cat, mouse, lizard, snake)
);

Sample insert/update statement:

insert into mytable
    (dog, cat, mouse, lizard, snake)
values(?, ?, ?, ?, ?)
on duplicate key update modified_at = current_timestamp


问:
"No such file or directory" or "No such host is known" when running migrations
I deleted the migrations table from a Laravel 5.4 database named laravel. When I run php artisan migrate:install, I get this error:

[Illuminate\Database\QueryException]
SQLSTATE[HY000] [2002] No such file or directory
(SQL: select * from information_schema.tables where table_schema = laravel
    and table_name = migrations)
```
<p>I deleted and recreated the database. I also ran <code>composer update</code>. No luck. I can run the command in phpMyAdmin and create the table manually.</p>
<p>This problem sometimes also manifests itself with similar 2002 errors:</p>
<pre class="lang-none prettyprint-override"><code>[Illuminate\Database\QueryException]
SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: No such host is known.
(SQL: select * from information_schema.tables where table_schema = laravel
    and table_name = migrations and table_type = 'BASE TABLE')
</code>```

[Illuminate\Database\QueryException]
SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known
(SQL: select * from information_schema.tables where table_schema = laravel
    and table_name = migrations and table_type = 'BASE TABLE')
```

答:
I fixed this issue by setting environment variables in .env file:

DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
```

Actually I just changed from DB_HOST=127.0.0.1 to DB_HOST=mysql.

Body:
I deleted the migrations table from a Laravel 5.4 database named laravel. When I run php artisan migrate:install, I get this error:

[Illuminate\Database\QueryException]
SQLSTATE[HY000] [2002] No such file or directory
(SQL: select * from information_schema.tables where table_schema = laravel
    and table_name = migrations)

I deleted and recreated the database. I also ran composer update. No luck. I can run the command in phpMyAdmin and create the table manually.

This problem sometimes also manifests itself with similar 2002 errors:

[Illuminate\Database\QueryException]
SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: No such host is known.
(SQL: select * from information_schema.tables where table_schema = laravel
    and table_name = migrations and table_type = 'BASE TABLE')

[Illuminate\Database\QueryException]
SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known
(SQL: select * from information_schema.tables where table_schema = laravel
    and table_name = migrations and table_type = 'BASE TABLE')

Body:
I fixed this issue by setting environment variables in .env file:

DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306

Actually I just changed from DB_HOST=127.0.0.1 to DB_HOST=mysql.


问:
Split each PDF page in two?
I have a large number of PDF files which have two slides to a page (for printing).

The format is A4 pages each with two slides setup like so:

```<code>-----------
| slide 1 |
-----------
| slide 2 |
-----------
</code>```

How can I generate a new PDF file with one slide per page?

Happy to use GUI, CLI, scripts or even interface with a language's PDF library; but I do need the text on the slides to still be selectable.

答:
Here is how I did it with pdfrw:

import sys, os, pdfrw
writer = pdfrw.PdfWriter()
for page in pdfrw.PdfReader('input.pdf').pages:
    for y in [0, 0.5]:
        newpage = pdfrw.PageMerge()
        newpage.add(page, viewrect=(0, y, 1, 0.5))
        writer.addpages([newpage.render()])
writer.write('output.pdf')
```
<p>Short and working!</p>
<p>If you want it rotated (example: input A4 portrait, output 2 A5 portrait and not landscape):</p>
<pre class="lang-py prettyprint-override"><code>import sys, os, pdfrw
writer = pdfrw.PdfWriter()
for page in pdfrw.PdfReader('input.pdf').pages:
    for y in [0, 0.5]:
        newpage = pdfrw.PageMerge()
        newpage.add(page, viewrect=(0, y, 1, 0.5))
        p = newpage.render()
        p.Rotate = 270
        writer.addpages([p])
writer.write('output.pdf')
</code>```

Title: Split each PDF page in two?

Body:
I have a large number of PDF files which have two slides to a page (for printing).

The format is A4 pages each with two slides setup like so:

-----------
| slide 1 |
-----------
| slide 2 |
-----------

How can I generate a new PDF file with one slide per page?

Happy to use GUI, CLI, scripts or even interface with a language's PDF library; but I do need the text on the slides to still be selectable.

Body:
Here is how I did it with pdfrw:

import sys, os, pdfrw
writer = pdfrw.PdfWriter()
for page in pdfrw.PdfReader('input.pdf').pages:
    for y in [0, 0.5]:
        newpage = pdfrw.PageMerge()
        newpage.add(page, viewrect=(0, y, 1, 0.5))
        writer.addpages([newpage.render()])
writer.write('output.pdf')

Short and working!

If you want it rotated (example: input A4 portrait, output 2 A5 portrait and not landscape):

import sys, os, pdfrw
writer = pdfrw.PdfWriter()
for page in pdfrw.PdfReader('input.pdf').pages:
    for y in [0, 0.5]:
        newpage = pdfrw.PageMerge()
        newpage.add(page, viewrect=(0, y, 1, 0.5))
        p = newpage.render()
        p.Rotate = 270
        writer.addpages([p])
writer.write('output.pdf')