问:
Complex(ish) Joins Question:
I have the following table in a mySQL database, (nb: these are summarised so they are relevant to this question, some columns have been omitted).

```<code>author (id, username, password etc.)
thread (id, title, content)
tag (id, name)
reply (id, content)
thread_replies (thread_id, reply_id)
author_replies (author_id, reply_id)
thread_tags (thread_id, tag_id)
author_threads (author_id, thread_id)
</code>```

Now to get threads by a certain Author, I normally do this:

```<code>SELECT thread.title, thread.id AS thread_id, thread.content, author.username, author.id AS author_id
FROM thread
JOIN author_threads ON thread.id = author_threads.thread_id
JOIN author ON author_threads.author_id = author.id
WHERE author.id = '12'
</code>```

This works fine, however when I try getting the tags associated with these threads:

```<code>SELECT thread.title, thread.id AS thread_id, thread.content, author.username, author.id AS author_id, GROUP_CONCAT( DISTINCT tag.name
ORDER BY tag.name DESC
SEPARATOR ',' ) AS tags
FROM thread
JOIN thread_tags ON thread.id = thread_tags.thread_id
JOIN tag ON thread_tags.tag_id = tag.id
JOIN author_threads ON thread.id = author_threads.thread_id
JOIN author ON author_threads.author_id = author.id
WHERE author.id = '12'
LIMIT 0 , 30
</code>```

It only shows the first thread, and all the tags associated with this author in one column.

What am I doing wrong here?

Also If I wanted to count the number of replies the author got for each thread how would this be done?

答:
Because you're using an aggregate in your query (GROUP_CONCAT), your query is being grouped. Since you have no group by clause, your group is the entire result set (hence seeing every tag the author has used). Because MySQL allows for using non-grouped columns in grouped statements, you aren't getting an error, but you aren't getting the query that you want.

In order to retrieve the proper results, you need to group your query on thread.id.

```<code>select
    thread.title,
    thread.id as thread_id,
    thread.content,
    author.username,
    author.id as author_id,
    group_concat(distinct tag.name order by tag.name desc separator ',') as tags

from thread

join thread_tags ON thread.id = thread_tags.thread_id
join tag ON thread_tags.tag_id = tag.id
join author_threads ON thread.id = author_threads.thread_id
join author ON author_threads.author_id = author.id

where author.id = '12'

group by thread.id

limit 0 , 30
</code>```

This should work in MySQL, though it's not ANSI-compliant SQL since you're using non-grouped columns in the select clause without any aggregation. You can leave this as-is, or you can write more compliant SQL and use something like max around all of the columns other than thread.id. This won't look as pretty, but it will be compliant.

```<code>SELECT
    max(thread.title) as title,
    thread.id as thread_id,
    max(thread.content) as content,
    max(author.username) as username,
    max(author.id) as author_id,
    group_concat(distinct tag.name order by tag.name desc separator ',') as tags

from thread

join thread_tags ON thread.id = thread_tags.thread_id
join tag ON thread_tags.tag_id = tag.id
join author_threads ON thread.id = author_threads.thread_id
join author ON author_threads.author_id = author.id

where author.id = '12'

group by thread.id

LIMIT 0 , 30
</code>```

Reply Count

The above query (along with your original queries) are suitable only for retrieving the tag list. You could write an equivalent query to retrieve the reply count (assuming that replies aren't nested, in which case you'll have to use whatever recursive querying capabilities that MySQL provides, which I'm not familiar with), but to retrieve both in a single query requires subqueries:

```<code>select
    thread.title,
    thread.id as thread_id,
    thread.content,
    author.username,
    author.id,
    (select group_concat(distinct tag.name order by tag.name separator ',')

    from thread_tags

    join tag on tag.id = thread_tags.tag_id

    where thread_tags.thread_id = thread.id) as tags,
    (select count(1) from thread_replies where thread_id = thread.id) as reply_count

from thread

join author_threads ON thread.id = author_threads.thread_id
join author ON author_threads.author_id = author.id

where author.id = '12'

LIMIT 0 , 30
</code>```

I've removed the group by from this query because our aggregate has been moved into a subselect, meaning that the outer query is no longer grouped.

Title: Complex(ish) Joins Question:

Body:
I have the following table in a mySQL database, (nb: these are summarised so they are relevant to this question, some columns have been omitted).

author (id, username, password etc.)
thread (id, title, content)
tag (id, name)
reply (id, content)
thread_replies (thread_id, reply_id)
author_replies (author_id, reply_id)
thread_tags (thread_id, tag_id)
author_threads (author_id, thread_id)

Now to get threads by a certain Author, I normally do this:

SELECT thread.title, thread.id AS thread_id, thread.content, author.username, author.id AS author_id
FROM thread
JOIN author_threads ON thread.id = author_threads.thread_id
JOIN author ON author_threads.author_id = author.id
WHERE author.id = '12'

This works fine, however when I try getting the tags associated with these threads:

SELECT thread.title, thread.id AS thread_id, thread.content, author.username, author.id AS author_id, GROUP_CONCAT( DISTINCT tag.name
ORDER BY tag.name DESC
SEPARATOR ',' ) AS tags
FROM thread
JOIN thread_tags ON thread.id = thread_tags.thread_id
JOIN tag ON thread_tags.tag_id = tag.id
JOIN author_threads ON thread.id = author_threads.thread_id
JOIN author ON author_threads.author_id = author.id
WHERE author.id = '12'
LIMIT 0 , 30

It only shows the first thread, and all the tags associated with this author in one column.

What am I doing wrong here?

Also If I wanted to count the number of replies the author got for each thread how would this be done?

Body:
Because you're using an aggregate in your query (GROUP_CONCAT), your query is being grouped. Since you have no group by clause, your group is the entire result set (hence seeing every tag the author has used). Because MySQL allows for using non-grouped columns in grouped statements, you aren't getting an error, but you aren't getting the query that you want.

In order to retrieve the proper results, you need to group your query on thread.id.

select
    thread.title,
    thread.id as thread_id,
    thread.content,
    author.username,
    author.id as author_id,
    group_concat(distinct tag.name order by tag.name desc separator ',') as tags

from thread

join thread_tags ON thread.id = thread_tags.thread_id
join tag ON thread_tags.tag_id = tag.id
join author_threads ON thread.id = author_threads.thread_id
join author ON author_threads.author_id = author.id

where author.id = '12'

group by thread.id

limit 0 , 30

This should work in MySQL, though it's not ANSI-compliant SQL since you're using non-grouped columns in the select clause without any aggregation. You can leave this as-is, or you can write more compliant SQL and use something like max around all of the columns other than thread.id. This won't look as pretty, but it will be compliant.

SELECT
    max(thread.title) as title,
    thread.id as thread_id,
    max(thread.content) as content,
    max(author.username) as username,
    max(author.id) as author_id,
    group_concat(distinct tag.name order by tag.name desc separator ',') as tags

from thread

join thread_tags ON thread.id = thread_tags.thread_id
join tag ON thread_tags.tag_id = tag.id
join author_threads ON thread.id = author_threads.thread_id
join author ON author_threads.author_id = author.id

where author.id = '12'

group by thread.id

LIMIT 0 , 30

Reply Count

The above query (along with your original queries) are suitable only for retrieving the tag list. You could write an equivalent query to retrieve the reply count (assuming that replies aren't nested, in which case you'll have to use whatever recursive querying capabilities that MySQL provides, which I'm not familiar with), but to retrieve both in a single query requires subqueries:

select
    thread.title,
    thread.id as thread_id,
    thread.content,
    author.username,
    author.id,
    (select group_concat(distinct tag.name order by tag.name separator ',')

    from thread_tags

    join tag on tag.id = thread_tags.tag_id

    where thread_tags.thread_id = thread.id) as tags,
    (select count(1) from thread_replies where thread_id = thread.id) as reply_count

from thread

join author_threads ON thread.id = author_threads.thread_id
join author ON author_threads.author_id = author.id

where author.id = '12'

LIMIT 0 , 30

I've removed the group by from this query because our aggregate has been moved into a subselect, meaning that the outer query is no longer grouped.


来源: stackexchange

问:
Unit test function that is opening and reading a file
I am working on learning go with a simple program that is doing some file reading and am working on adding unit testing to my program. I have ran into an issue/question while doing this. I want to unit test the function below and my question is that the function takes a name of the file which is then opened and processed. During testing I do not want to actually pass it a real file. I am wondering is this something I can somehow mock so that I can just pass it a "fake" file and have it process that instead? Thanks!    </p>

```<code>func openAndReadFile(fileName string) [][]string {
    file, err := os.Open(fileName)
    if err != nil {
        fmt.Printf("Failed to read file: %s", fileName)
    }
    r := csv.NewReader(file)
    lines, err := r.ReadAll()
    if err != nil {
        log.Fatal(err)
    }
    return lines
}
</code>```

答:
The function you have shown is dominated by interactions: Interactions with the file system and interactions with the csv reader.  To be sure that these interactions work nicely you will later anyway have to do some integration-testing against the file system and the csv reader.  Think about which bugs you are hoping to find, and you will see that bugs are more likely on the interaction level: Is the order of file,err correct, or should it be the other way around?  Is nil really the value indicating no error?  Do you have to give more arguments to Open?  etc.

Therefore, I would not concentrate on unit-testing this function.  However, this function is a good candidate to be mocked to make unit-testing the surrounding code easier.  Thus, mock openAndReadFile to unit-test the surrounding code, and test openAndReadFile using integration-testing.

ContentLicense: CC BY-SA 4.0

Body:
I am working on learning go with a simple program that is doing some file reading and am working on adding unit testing to my program. I have ran into an issue/question while doing this. I want to unit test the function below and my question is that the function takes a name of the file which is then opened and processed. During testing I do not want to actually pass it a real file. I am wondering is this something I can somehow mock so that I can just pass it a "fake" file and have it process that instead? Thanks!

func openAndReadFile(fileName string) [][]string {
    file, err := os.Open(fileName)
    if err != nil {
        fmt.Printf("Failed to read file: %s", fileName)
    }
    r := csv.NewReader(file)
    lines, err := r.ReadAll()
    if err != nil {
        log.Fatal(err)
    }
    return lines
}


问:
Iterating over matrixes in a list stopped in numpy
I would like to iterate over a matrix of matrixes (indeed, sounds weird),

```<code>import numpy as np

ar = np.array

A = ar([[[1,2,3],[4,5,6],[7,8,9]],[[11,12,13],[14,15,16],[17,18,19]], [[1,2,3],[4,5,6],[7,8,9]], [[20,21,22],[23,24,25],[26,27,28]]])

B = np.copy(A)
C = np.copy(A)

im = np.array([A,B,C])
</code>```

in order to receive the matrix which stores the values of (x,y) position in subsequent matrixes. For example, in [1, 2, 3], on the postion of 1, that means: A[0,0,0], there will appear only ones in the next matrixes. Thus I will receive an array in the new matrix (considering also A[0,0,1] and A[0,0,2]):

```<code>[[1  1  1] [2  2  2] [3  3  3]]
</code>```

Therefore for the first array of A:

```<code>[[[1  1  1] [2  2  2] [3  3  3]]
[[4  4  4] [5  5  5] [6  6  6]]
[[7  7  7] [8  8  8] [9  9  9]]]
</code>```

I have created this function:

```<code>def loop_ar(arr):
    matrix, v, c, s = arr.shape
    new = np.zeros((v,c,s,matrix)) #The columns in the last array of new represent the subsequent arrays
    for x in range(v):
        for y in range(c):
            for s in range(s):
                for ma in range(matrix):
                    new[x,y,s,ma] = arr[ma, x, y, s]
    return new
</code>```

However, the output indicates, that the matrix stops iterating after few turns:

```<code>[[[[1. 1. 1.]
   [2. 2. 2.]
   [3. 3. 3.]]

  [[4. 4. 4.]
   [5. 5. 5.]
   [0. 0. 0.]]

  [[7. 7. 7.]
   [0. 0. 0.]
   [0. 0. 0.]]]

 [[[0. 0. 0.]
   [0. 0. 0.]
   [0. 0. 0.]]

  [[0. 0. 0.]
   [0. 0. 0.]
   [0. 0. 0.]]

  [[0. 0. 0.]
   [0. 0. 0.]
   [0. 0. 0.]]]

   ...
</code>```

When I tested this function on the list of lists, it worked. What has happened in this case? How can I fix it? It os only a simple case to illustrate my expectations; however, I would like to know the solution to a more complex problem, when B and C are not the copies of A. How can I force then the loop to iterate?

The B and C in the more complex case should have the same shape as A, howeb=ver they will differ in the last array. As in A we have:

```<code>[1  2  3]
</code>```

in B we would have for example on the same position:

```<code>[23  34  56]
</code>```

and in C:

```<code>[54  43  32]
</code>```

Therefore the new matrix will include the array:

```<code>[[1  23  54]  [2  34  43]  [3  56  32]]
</code>```

I have completed this task (I hope so) with converting a list to an array, because loop_arr worked for lists. However, it is a roundabaout. I want the solution and the explanation of the interruption in looping.

Here I present random data for the more complex question:

```<code>A = ar([[[1,2,3],[4,5,6],[7,8,9]],[[11,12,13],[14,15,16],[17,18,19]],[[20,21,22],[23,24,25],[26,27,28]]])

B = ar([[[23,34,56], [56, 78, 90], [12, 34, 32]], [[74,75,65], [25,57,76], [90,24,35]]])

C = ar([[[13,31,53], [54,96,69], [78, 90, 99]], [[35,64,66], [13,35,53], [37,73,61]], [[62, 87,97], [80,35,62], [75,76,67]]]
</code>```

The new matrix would look like:

```<code>[[[[1  23  13]  [2  34  31]  [3  56  53]]
[[4  56  54]  [5  78  96] [6  90  69]]
[[7  12  78]  [8  34  90]  [9  32  99]]]
      ...so on, so on, so on...
                                     ]]]]
</code>```

答:
```<code>In [44]: A = np.array([[[1,2,3],[4,5,6],[7,8,9]],[[11,12,13],[14,15,16],[17,18,19]],
    ...: [[1,2,3],[4,5,6],[7,8,9]], [[20,21,22],[23,24,25],[26,27,28]]])
    ...:
In [45]: A.shape
Out[45]: (4, 3, 3)
In [46]: im = np.array([A,A+10,A+20])
In [47]: im.shape
Out[47]: (3, 4, 3, 3)
</code>```

Looks to me like your code just transposes the axes, putting matrix dimension last instead of first.  np.stack takes an axis parameter.  Alternatively we can use the transpose function/method:

```<code>In [48]: im1 = np.stack([A,A+10,A+20], axis=3)
In [49]: im1.shape
Out[49]: (4, 3, 3, 3)
In [50]: im2 = im.transpose(1,2,3,0)
In [51]: im2.shape
Out[51]: (4, 3, 3, 3)
In [52]: im2
Out[52]:
array([[[[ 1, 11, 21],
         [ 2, 12, 22],
         [ 3, 13, 23]],

        [[ 4, 14, 24],
         [ 5, 15, 25],
         [ 6, 16, 26]],

        [[ 7, 17, 27],
         [ 8, 18, 28],
         [ 9, 19, 29]]],

        ....
        [[26, 36, 46],
         [27, 37, 47],
         [28, 38, 48]]]])
In [53]: np.allclose(im1,im2)
Out[53]: True
</code>```

I can't test you more complex case because B has the wrong shape.  And C has the wrong terminating character.

===

To see what's wrong with your iteration, print s at the start of its loop.  Look at how it evolves.  Then change the iteration variable to k, and watch that.

Body:
I would like to iterate over a matrix of matrixes (indeed, sounds weird),

import numpy as np

ar = np.array

A = ar([[[1,2,3],[4,5,6],[7,8,9]],[[11,12,13],[14,15,16],[17,18,19]], [[1,2,3],[4,5,6],[7,8,9]], [[20,21,22],[23,24,25],[26,27,28]]])

B = np.copy(A)
C = np.copy(A)

im = np.array([A,B,C])

in order to receive the matrix which stores the values of (x,y) position in subsequent matrixes. For example, in [1, 2, 3], on the postion of 1, that means: A[0,0,0], there will appear only ones in the next matrixes. Thus I will receive an array in the new matrix (considering also A[0,0,1] and A[0,0,2]):

[[1  1  1] [2  2  2] [3  3  3]]

Therefore for the first array of A:

[[[1  1  1] [2  2  2] [3  3  3]]
[[4  4  4] [5  5  5] [6  6  6]]
[[7  7  7] [8  8  8] [9  9  9]]]

I have created this function:

def loop_ar(arr):
    matrix, v, c, s = arr.shape
    new = np.zeros((v,c,s,matrix)) #The columns in the last array of new represent the subsequent arrays
    for x in range(v):
        for y in range(c):
            for s in range(s):
                for ma in range(matrix):
                    new[x,y,s,ma] = arr[ma, x, y, s]
    return new

However, the output indicates, that the matrix stops iterating after few turns:

[[[[1. 1. 1.]
   [2. 2. 2.]
   [3. 3. 3.]]

  [[4. 4. 4.]
   [5. 5. 5.]
   [0. 0. 0.]]

  [[7. 7. 7.]
   [0. 0. 0.]
   [0. 0. 0.]]]

 [[[0. 0. 0.]
   [0. 0. 0.]
   [0. 0. 0.]]

  [[0. 0. 0.]
   [0. 0. 0.]
   [0. 0. 0.]]

  [[0. 0. 0.]
   [0. 0. 0.]
   [0. 0. 0.]]]

   ...

When I tested this function on the list of lists, it worked. What has happened in this case? How can I fix it? It os only a simple case to illustrate my expectations; however, I would like to know the solution to a more complex problem, when B and C are not the copies of A. How can I force then the loop to iterate?

The B and C in the more complex case should have the same shape as A, howeb=ver they will differ in the last array. As in A we have:

[1  2  3]

in B we would have for example on the same position:

[23  34  56]

and in C:

[54  43  32]

Therefore the new matrix will include the array:

[[1  23  54]  [2  34  43]  [3  56  32]]

I have completed this task (I hope so) with converting a list to an array, because loop_arr worked for lists. However, it is a roundabaout. I want the solution and the explanation of the interruption in looping.

Here I present random data for the more complex question:

A = ar([[[1,2,3],[4,5,6],[7,8,9]],[[11,12,13],[14,15,16],[17,18,19]],[[20,21,22],[23,24,25],[26,27,28]]])

B = ar([[[23,34,56], [56, 78, 90], [12, 34, 32]], [[74,75,65], [25,57,76], [90,24,35]]])

C = ar([[[13,31,53], [54,96,69], [78, 90, 99]], [[35,64,66], [13,35,53], [37,73,61]], [[62, 87,97], [80,35,62], [75,76,67]]]

The new matrix would look like:

[[[[1  23  13]  [2  34  31]  [3  56  53]]
[[4  56  54]  [5  78  96] [6  90  69]]
[[7  12  78]  [8  34  90]  [9  32  99]]]
      ...so on, so on, so on...
                                     ]]]]

Body:
In [44]: A = np.array([[[1,2,3],[4,5,6],[7,8,9]],[[11,12,13],[14,15,16],[17,18,19]],
    ...: [[1,2,3],[4,5,6],[7,8,9]], [[20,21,22],[23,24,25],[26,27,28]]])
    ...:
In [45]: A.shape
Out[45]: (4, 3, 3)
In [46]: im = np.array([A,A+10,A+20])
In [47]: im.shape
Out[47]: (3, 4, 3, 3)

Looks to me like your code just transposes the axes, putting matrix dimension last instead of first.  np.stack takes an axis parameter.  Alternatively we can use the transpose function/method:

In [48]: im1 = np.stack([A,A+10,A+20], axis=3)
In [49]: im1.shape
Out[49]: (4, 3, 3, 3)
In [50]: im2 = im.transpose(1,2,3,0)
In [51]: im2.shape
Out[51]: (4, 3, 3, 3)
In [52]: im2
Out[52]:
array([[[[ 1, 11, 21],
         [ 2, 12, 22],
         [ 3, 13, 23]],

        [[ 4, 14, 24],
         [ 5, 15, 25],
         [ 6, 16, 26]],

        [[ 7, 17, 27],
         [ 8, 18, 28],
         [ 9, 19, 29]]],

        ....
        [[26, 36, 46],
         [27, 37, 47],
         [28, 38, 48]]]])
In [53]: np.allclose(im1,im2)
Out[53]: True

I can't test you more complex case because B has the wrong shape.  And C has the wrong terminating character.

===

To see what's wrong with your iteration, print s at the start of its loop.  Look at how it evolves.  Then change the iteration variable to k, and watch that.


问:
Convert RTMP to RTSP & Stream
I am trying to stream the camera view from a React Native or Ionic app and then receive the output as an RTSP feed on my PC. I have been able to use Bambuser's SDK to stream to their servers, and from there I can output to RTMP. Unfortunately it doesn't seem to allow RTSP output.

Can anyone tell me the best way of receiving this RTMP stream & converting it to RTSP please? I can use the nginx RTMP module (https://hub.docker.com/r/tiangolo/nginx-rtmp/) but I am not sure how to convert to RTSP.

I've tried using Wowza for this instead which works great, but there is an error when trying to use their SDK on Vuzix Blade smart glasses which I am using so I am having to look for an alternative solution.

Thanks for any help.

答: I managed this by using MistServer in the end. It accepts a wide range of protocols including RTMP, and can output RTSP.</p>

Title: Convert RTMP to RTSP & Stream


问:
VBA Web Scraping using getElementsByClassName to names and addresses
I'm trying to extract the clinic name and corresponding address for all the clinics from the following web page: https://medimap.ca/Location/Calgary,%20AB,%20Canada

I'm having issues locating the exact area where I should be drilling down into.  All the clinic names have the same class name of "_1FLG5" and the addresses are all "_1-Gov" . However, when I run through the below code nothing happens - no errors just nothing.

I'm also unsure if the reference after .getElementsByClassName is correct, as I want the inner text from the same row as where the "_1FLG5" is I referenced (0) and since I wanted the text from two rows below  "_1-Gov" I referenced (2).

```<code>Option Explicit

Sub GetClinicData()

    Dim objIE As InternetExplorer
    Dim clinicEle As Object
    Dim clinicAdd As Object

    Dim clinicName As String
    Dim address As String
    Dim y As Integer
    Dim x As Integer

    Set objIE = New InternetExplorer
    objIE.Visible = False

    objIE.navigate "https://medimap.ca/Location/Calgary,%20AB,%20Canada"
    Do While objIE.Busy = True Or objIE.readyState <> 4: DoEvents: Loop

    y = 1

    For Each clinicEle In objIE.document.getElementsByClassName("_1FLG5")
        clinicName = clinicEle.getElementsByClassName("_1FLG5")(0).innerText
        Sheets("Sheet1").Range("A" & y).Value = clinicName
        y = y + 1
    Next

    x = 1

    For Each clinicAdd In objIE.document.getElementsByClassName("_1-Gov")
        clinicAdd = clinicAdd.getElementsByClassName("_1-Gov")(2).innerText
        Sheets("Sheet1").Range("B" & x).Value = clinicAdd
        x = x + 1
    Next

End Sub
</code>```

答:
Content is dynamically loaded so you need a wait condition to ensure content loaded - otherwise your collections end up being of length 0. I use querySelectorAll to apply the class names which return nodeList you For Loop over the .Length of. Ideally you should add a timeout condition to the loop. I show a timed loop here.

```<code>Option Explicit

'VBE > Tools > References: Microsoft Internet Controls
Public Sub GetData()
    Dim ie As Object
    Set ie = CreateObject("InternetExplorer.Application")
    With ie
        .Visible = True
        .Navigate2 "https://medimap.ca/Location/Calgary,%20AB,%20Canada"

        While .Busy Or .readyState < 4: DoEvents: Wend

        Dim clinics As Object, addresses As Object, i As Long
        With .document

            Do
                Set clinics = .querySelectorAll("._1FLG5")
                Set addresses = .querySelectorAll("._1-Gov")
            Loop While clinics.Length = 0

            For i = 0 To clinics.Length - 1
                With ThisWorkbook.Worksheets("Sheet1")
                    .Cells(i + 1, 1) = Trim$(clinics.item(i).innerText)
                    .Cells(i + 1, 2) = Trim$(addresses.item(i).innerText)
                End With
            Next
        End With
        .Quit
    End With
End Sub
</code>```

Body:
I'm trying to extract the clinic name and corresponding address for all the clinics from the following web page: https://medimap.ca/Location/Calgary,%20AB,%20Canada

I'm having issues locating the exact area where I should be drilling down into.  All the clinic names have the same class name of "_1FLG5" and the addresses are all "_1-Gov" . However, when I run through the below code nothing happens - no errors just nothing.

I'm also unsure if the reference after .getElementsByClassName is correct, as I want the inner text from the same row as where the "_1FLG5" is I referenced (0) and since I wanted the text from two rows below  "_1-Gov" I referenced (2).

Option Explicit

Sub GetClinicData()

    Dim objIE As InternetExplorer
    Dim clinicEle As Object
    Dim clinicAdd As Object

    Dim clinicName As String
    Dim address As String
    Dim y As Integer
    Dim x As Integer

    Set objIE = New InternetExplorer
    objIE.Visible = False

    objIE.navigate "https://medimap.ca/Location/Calgary,%20AB,%20Canada"
    Do While objIE.Busy = True Or objIE.readyState <> 4: DoEvents: Loop

    y = 1

    For Each clinicEle In objIE.document.getElementsByClassName("_1FLG5")
        clinicName = clinicEle.getElementsByClassName("_1FLG5")(0).innerText
        Sheets("Sheet1").Range("A" & y).Value = clinicName
        y = y + 1
    Next

    x = 1

    For Each clinicAdd In objIE.document.getElementsByClassName("_1-Gov")
        clinicAdd = clinicAdd.getElementsByClassName("_1-Gov")(2).innerText
        Sheets("Sheet1").Range("B" & x).Value = clinicAdd
        x = x + 1
    Next

End Sub

Body:
Content is dynamically loaded so you need a wait condition to ensure content loaded - otherwise your collections end up being of length 0. I use querySelectorAll to apply the class names which return nodeList you For Loop over the .Length of. Ideally you should add a timeout condition to the loop. I show a timed loop here.

Option Explicit

'VBE > Tools > References: Microsoft Internet Controls
Public Sub GetData()
    Dim ie As Object
    Set ie = CreateObject("InternetExplorer.Application")
    With ie
        .Visible = True
        .Navigate2 "https://medimap.ca/Location/Calgary,%20AB,%20Canada"

        While .Busy Or .readyState < 4: DoEvents: Wend

        Dim clinics As Object, addresses As Object, i As Long
        With .document

            Do
                Set clinics = .querySelectorAll("._1FLG5")
                Set addresses = .querySelectorAll("._1-Gov")
            Loop While clinics.Length = 0

            For i = 0 To clinics.Length - 1
                With ThisWorkbook.Worksheets("Sheet1")
                    .Cells(i + 1, 1) = Trim$(clinics.item(i).innerText)
                    .Cells(i + 1, 2) = Trim$(addresses.item(i).innerText)
                End With
            Next
        End With
        .Quit
    End With
End Sub


问:
When using open() as f: does f represent a new variable being created?
I am new(ish) to Python and I'm just trying to figure out how things work. When I use:

```<code>with open('C:\\Users\\KB\\Documents\\DataProcessing.txt', 'r') as f:
</code>```

is f a new variable being created? Could I use any variable in its place? I've seen 'file' used as-well so I'm just wondering if this is an arbitrary name being assigned to a newly created variable? Could it be named anything or does it have to be f?

答:
Yes, f is a new variable.
Yes, you may use any other name.  file is a bad choice, because that's already a built-in name.  I often use something like the below, where in_file is the name of my input file.

```<code>with open(in_file) as csv_file:
</code>```

Body:
I am new(ish) to Python and I'm just trying to figure out how things work. When I use:

with open('C:\\Users\\KB\\Documents\\DataProcessing.txt', 'r') as f:

is f a new variable being created? Could I use any variable in its place? I've seen 'file' used as-well so I'm just wondering if this is an arbitrary name being assigned to a newly created variable? Could it be named anything or does it have to be f?

Body:
Yes, f is a new variable.
Yes, you may use any other name.  file is a bad choice, because that's already a built-in name.  I often use something like the below, where in_file is the name of my input file.

with open(in_file) as csv_file:


问:
why do I have to reference the method instead of the @variable?
Learning about classes, methods, global, instance variables and class variables.

Making a very basic account class, and the withdraw method takes 2 variables: pin_number, amount. I don't understand why both of these don't return true.

in the withdraw method if I go:

```<code> if pin_number == pin
</code>```

calls pin method returns @pin and statement is true

```<code> if pin_number == @pin
</code>```

statement returns false

my first assumption was the private tag, but I removed it and still doesn't return true.

```<code>class Account
  attr_reader :name, :balance
  def initialize(name, balance=100)
    @name = name
    @balance = balance
  end

  public
    def withdraw(pin_number, amount)
      if pin_number == pin
        @balance -= amount
        puts "Withdrew #{amount}. New balance: $#{@balance}."
      else
        puts pin_error
      end
    end

    def display_balance(pin_number)
      if pin_number == pin
        puts "Balance: $#{@balance}."
      else
        puts pin_error
      end
    end

    def deposit(amt)
      @balance += amt
      puts @balance
    end
private
    def pin
    @pin = '1234'
  end

 def pin_error
    "Access denied: incorrect PIN."
  end
end

checking_account = Account.new('Jensen', 904)
checking_account.deposit(5)
checking_account.withdraw('1234',900)
</code>```

答:
The effect you are seeing is because you only assign the instance variable @pin inside the pin method.

That is, it wasn't until you called pin in your comparison, that it got set. When you tried to use @pin directly, it had not yet been initialized.

Assign the @pin variable in initialize and then things will work.

```<code>class Account
  attr_reader :name, :balance
  def initialize(name, balance=100)
    @name = name
    @balance = balance
    @pin = '1234'
  end

  public
    def withdraw(pin_number, amount)
      if pin_number == @pin
        @balance -= amount
        puts "Withdrew #{amount} from pin #{@pin}, new bal is #@balance"
      else
        puts pin_error
      end
    end

    def display_balance(pin_number)
      if pin_number == @pin
        puts "Balance: $#{@balance}."
      else
        puts pin_error
      end
    end

    def deposit(amt)
      @balance += amt
      puts "Deposited #{amt} to pin #@pin, new bal is #@balance"
    end

 def pin_error
    "Access denied: incorrect PIN."
  end
end

checking_account = Account.new('Jensen', 904)
checking_account.deposit(5)
checking_account.withdraw('1234',900)
</code>```

This produces

```<code>Deposited 5 to pin 1234, new bal is 909
Withdrew 900 from pin 1234, new bal is 9
</code>```

Body:
Learning about classes, methods, global, instance variables and class variables.

Making a very basic account class, and the withdraw method takes 2 variables: pin_number, amount. I don't understand why both of these don't return true.

in the withdraw method if I go:

 if pin_number == pin

calls pin method returns @pin and statement is true

 if pin_number == @pin

statement returns false

my first assumption was the private tag, but I removed it and still doesn't return true.

class Account
  attr_reader :name, :balance
  def initialize(name, balance=100)
    @name = name
    @balance = balance
  end

  public
    def withdraw(pin_number, amount)
      if pin_number == pin
        @balance -= amount
        puts "Withdrew #{amount}. New balance: $#{@balance}."
      else
        puts pin_error
      end
    end

    def display_balance(pin_number)
      if pin_number == pin
        puts "Balance: $#{@balance}."
      else
        puts pin_error
      end
    end

    def deposit(amt)
      @balance += amt
      puts @balance
    end
private
    def pin
    @pin = '1234'
  end

 def pin_error
    "Access denied: incorrect PIN."
  end
end

checking_account = Account.new('Jensen', 904)
checking_account.deposit(5)
checking_account.withdraw('1234',900)

Body:
The effect you are seeing is because you only assign the instance variable @pin inside the pin method.

That is, it wasn't until you called pin in your comparison, that it got set. When you tried to use @pin directly, it had not yet been initialized.

Assign the @pin variable in initialize and then things will work.

class Account
  attr_reader :name, :balance
  def initialize(name, balance=100)
    @name = name
    @balance = balance
    @pin = '1234'
  end

  public
    def withdraw(pin_number, amount)
      if pin_number == @pin
        @balance -= amount
        puts "Withdrew #{amount} from pin #{@pin}, new bal is #@balance"
      else
        puts pin_error
      end
    end

    def display_balance(pin_number)
      if pin_number == @pin
        puts "Balance: $#{@balance}."
      else
        puts pin_error
      end
    end

    def deposit(amt)
      @balance += amt
      puts "Deposited #{amt} to pin #@pin, new bal is #@balance"
    end

 def pin_error
    "Access denied: incorrect PIN."
  end
end

checking_account = Account.new('Jensen', 904)
checking_account.deposit(5)
checking_account.withdraw('1234',900)

This produces

Deposited 5 to pin 1234, new bal is 909
Withdrew 900 from pin 1234, new bal is 9


问:
Multiclassing QObject and QThread together
I'm trying to create a set of state machines to handle different tasks in my PyQt project, in the process of handling the way that graphics need to be handled on a single thread, I've created two types of state machines, a StateMachine which must inherit QObject and a ThreadedStateMachine which, to avoid duplicate code, I've had inherit from both StateMachine and QThread.

Here is my minimally complete code to replicate the problem:

from PyQt5.QtCore import QObject, QThread

class StateMachine(QObject):
    def __init__(self):
        super().__init__()

class ThreadedStateMachine(StateMachine, QThread):
    def __init__(self):
        super().__init__()

if __name__ == "__main__":
    t = ThreadedStateMachine()
```

<p>I expected this to work without fail, but instead I receive this exception</p>

```QObject::connect: No such signal ThreadedStateMachine::started()
Traceback (most recent call last):
  File "/snap/pycharm-community/132/helpers/pydev/pydevd.py", line 1758, in <module>
    main()
  File "/snap/pycharm-community/132/helpers/pydev/pydevd.py", line 1752, in main
    globals = debugger.run(setup['file'], None, None, is_module)
  File "/snap/pycharm-community/132/helpers/pydev/pydevd.py", line 1147, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "/snap/pycharm-community/132/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "/home/aaron/.PyCharmCE2019.1/config/scratches/emerson_pmd/new/scratch_7.py", line 15, in <module>
    t = ThreadedStateMachine()
  File "/home/aaron/.PyCharmCE2019.1/config/scratches/emerson_pmd/new/scratch_7.py", line 11, in __init__
    super().__init__()
  File "/home/aaron/.PyCharmCE2019.1/config/scratches/emerson_pmd/new/scratch_7.py", line 6, in __init__
    super().__init__()
  File "/snap/pycharm-community/132/helpers/pydev/_pydev_bundle/pydev_monkey_qt.py", line 181, in __init__
    self.started = StartedSignalWrapper(self, self.started)
  File "/snap/pycharm-community/132/helpers/pydev/_pydev_bundle/pydev_monkey_qt.py", line 151, in __init__
    self.original_started.connect(self._signal)
TypeError: connect() failed between started() and _signal()
```

<p>What's the correct way to combine the <code>QObject</code> and <code>QThread</code> classes into a single object?</p>

<h3>Note</h3>

<p>I am currently using <code>threading.Thread</code> as a workaround, but I'd like to be able to launch a <code>QMessageBox</code> from the other thread, which shows an error:</p>

```QObject::connect: Cannot queue arguments of type 'QItemSelection'
(Make sure 'QItemSelection' is registered using qRegisterMetaType().)
QBasicTimer::start: Timers cannot be started from another thread
```

I believe that using QThread would work here.

答:
Well you have a problem PyQt does not allow the double inheritance of 2 QObject, StateMachine is a QObject and QThread is also a QObject(see the docs).

I do not think the problem is caused by threading.Thread(), I suspect that this is caused because you are modifying some object that lives in a thread and is not thread-safe, the QObjects are not thread-safe so you must interact with those objects in the thread where they live, and the models are QObject.

Read:

https://doc.qt.io/qt-5/threads-reentrancy.html

https://doc.qt.io/qt-5/thread-basics.html

Body:
I'm trying to create a set of state machines to handle different tasks in my PyQt project, in the process of handling the way that graphics need to be handled on a single thread, I've created two types of state machines, a StateMachine which must inherit QObject and a ThreadedStateMachine which, to avoid duplicate code, I've had inherit from both StateMachine and QThread.

Here is my minimally complete code to replicate the problem:

from PyQt5.QtCore import QObject, QThread

class StateMachine(QObject):
    def __init__(self):
        super().__init__()

class ThreadedStateMachine(StateMachine, QThread):
    def __init__(self):
        super().__init__()

if __name__ == "__main__":
    t = ThreadedStateMachine()

I expected this to work without fail, but instead I receive this exception

QObject::connect: No such signal ThreadedStateMachine::started()
Traceback (most recent call last):
  File "/snap/pycharm-community/132/helpers/pydev/pydevd.py", line 1758, in <module>
    main()
  File "/snap/pycharm-community/132/helpers/pydev/pydevd.py", line 1752, in main
    globals = debugger.run(setup['file'], None, None, is_module)
  File "/snap/pycharm-community/132/helpers/pydev/pydevd.py", line 1147, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "/snap/pycharm-community/132/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "/home/aaron/.PyCharmCE2019.1/config/scratches/emerson_pmd/new/scratch_7.py", line 15, in <module>
    t = ThreadedStateMachine()
  File "/home/aaron/.PyCharmCE2019.1/config/scratches/emerson_pmd/new/scratch_7.py", line 11, in __init__
    super().__init__()
  File "/home/aaron/.PyCharmCE2019.1/config/scratches/emerson_pmd/new/scratch_7.py", line 6, in __init__
    super().__init__()
  File "/snap/pycharm-community/132/helpers/pydev/_pydev_bundle/pydev_monkey_qt.py", line 181, in __init__
    self.started = StartedSignalWrapper(self, self.started)
  File "/snap/pycharm-community/132/helpers/pydev/_pydev_bundle/pydev_monkey_qt.py", line 151, in __init__
    self.original_started.connect(self._signal)
TypeError: connect() failed between started() and _signal()

What's the correct way to combine the QObject and QThread classes into a single object?

Note

I am currently using threading.Thread as a workaround, but I'd like to be able to launch a QMessageBox from the other thread, which shows an error:

QObject::connect: Cannot queue arguments of type 'QItemSelection'
(Make sure 'QItemSelection' is registered using qRegisterMetaType().)
QBasicTimer::start: Timers cannot be started from another thread

I believe that using QThread would work here.


问:
Add Class to outside div with specific class
Hey I try to add a class to the div with "teaser-background item-1" class when I hover the div with "teaser-item item-1" class or when I hover "item-2" then add a class to the div with "teaser-item item-2".

#HTML

```<code><div class="teaser-home-container">
   <div class="teaser-home owl-carousel owl-theme">
      <div class="owl-item">
         <div class="teaser-item item-1"></div>
      </div>
      <div class="owl-item">
         <div class="teaser-item item-2"></div>
      </div>
   </div>
   <div class="teaser-home--background">
      <div class="teaser-background item-1"></div>
      <div class="teaser-background item-2"></div>
   </div>
</div>
</code>```

#Jquery

```<code>$thisClass = $(this).find("div[class^=item-]").attr('class');
$('.owl-item').hover(function(){
   $(this).parents('.teaser-home-container').find($thisClass).addClass('hover');
};
</code>```

答:
```<code>$('.teaser-item.item-1').hover(function() {
    $('.teaser-background.item-1').addClass('hover');
});
$('.teaser-item.item-2').hover(function() {
    $('.teaser-background.item-2').addClass('hover');
});
</code>```

Body:
Hey I try to add a class to the div with "teaser-background item-1" class when I hover the div with "teaser-item item-1" class or when I hover "item-2" then add a class to the div with "teaser-item item-2".

#HTML

#Jquery

$thisClass = $(this).find("div[class^=item-]").attr('class');
$('.owl-item').hover(function(){
   $(this).parents('.teaser-home-container').find($thisClass).addClass('hover');
};


问:
Why using a reference as an iterator
I was learning about the emplace() of std::vector and stumble upon this code:

```<code>// vector::emplace
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector = {10,20,30};

  auto it = myvector.emplace ( myvector.begin()+1, 100 );
  myvector.emplace ( it, 200 );
  myvector.emplace ( myvector.end(), 300 );

  std::cout << "myvector contains:";
  for (auto& x: myvector)
    std::cout << ' ' << x;
  std::cout << '\n';

  return 0;
}
</code>```

I am wondering why in the for loop they use a reference auto& x instead of a simple copy, I tried without the & and it worked the same, is this a security to avoid a copy or a a performance trick ?

答:
The other difference between auto and auto& in this context is that auto& will let you modify the value in the vector. This may be an undesirable bug just waiting to happen. Ideally, if you are going to take a reference only for reading, you should take a const reference: const auto &

The benefit of using the reference when the vector contains objects that are more than a fundamental numeric or pointer type is it won't copy the whole object to a temporary. If the object has any deep copy semantics, or is perhaps a shared_ptr then there may be significant overhead that is totally avoided.

For a fundamental type the copy is usually very fast, so a single copy is preferred, but you can expect the compiler optimiser to do the "right thing" if asked to reference a fundamental and then use that reference numerous times, so for template programming you should favour the const-ref over the copy to keep the code simple when you don't know the type.

Title: Why using a reference as an iterator

Body:
I was learning about the emplace() of std::vector and stumble upon this code:

// vector::emplace
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector = {10,20,30};

  auto it = myvector.emplace ( myvector.begin()+1, 100 );
  myvector.emplace ( it, 200 );
  myvector.emplace ( myvector.end(), 300 );

  std::cout << "myvector contains:";
  for (auto& x: myvector)
    std::cout << ' ' << x;
  std::cout << '\n';

  return 0;
}

I am wondering why in the for loop they use a reference auto& x instead of a simple copy, I tried without the & and it worked the same, is this a security to avoid a copy or a a performance trick ?


答:
This might do the job for you, just by identifying the divs by ID </p>

```<code><script type="text/javascript">
        $(document).ready(function(){
            $(".teaser-item").hover(function(){
                var id = this.id;
                $("#hover"+id).addClass("hover");

            });
        });
    </script>

        <div class="teaser-home-container">
           <div class="teaser-home owl-carousel owl-theme">
              <div class="owl-item">
                 <div class="teaser-item" id="item-1">Item1</div>
              </div>
              <div class="owl-item">
                 <div class="teaser-item" id="item-2">Item2</div>
              </div>
           </div>
           <div class="teaser-home--background">
              <div class="teaser-background" id="hoveritem-1">Hitem1</div>
              <div class="teaser-background" id="hoveritem-2">Hitem2</div>
           </div>
        </div>
</code>```

Title: Add Class to outside div with specific class

Body:
This might do the job for you, just by identifying the divs by ID

<script type="text/javascript">
        $(document).ready(function(){
            $(".teaser-item").hover(function(){
                var id = this.id;
                $("#hover"+id).addClass("hover");

            });
        });
    </script>

        <div class="teaser-home-container">
           <div class="teaser-home owl-carousel owl-theme">
              <div class="owl-item">
                 <div class="teaser-item" id="item-1">Item1</div>
              </div>
              <div class="owl-item">
                 <div class="teaser-item" id="item-2">Item2</div>
              </div>
           </div>
           <div class="teaser-home--background">
              <div class="teaser-background" id="hoveritem-1">Hitem1</div>
              <div class="teaser-background" id="hoveritem-2">Hitem2</div>
           </div>
        </div>


问:
Counting and adding distinct values that occur in certain dates using PostgreSQL
Using some SQL in the tables of some database, I get a result like this:

```<code>id  name    date            status
1   John    2018-05-03      PRESENT
2   Mary    2018-05-03      NOT PRESENT
3   Jane    2018-05-03      NOT PRESENT
2   Mary    2018-05-04      PRESENT
1   John    2018-05-04      PRESENT
1   John    2018-05-05      PRESENT
2   Mary    2018-05-05      NOT PRESENT
3   Jane    2018-05-04      PRESENT
3   Jane    2018-05-05      NOT PRESENT
1   John    2018-05-06      PRESENT
</code>```

I wanna use further SQL to get in a result like this one:

```<code>id  name    date      present   not present
1   John    2018-05       4           0
2   Mary    2018-05       1           2
3   Jane    2018-05       2           1
</code>```

In other words, I wanna extract how many classes a student attended in a given month, based on the status he/she received everyday. How can I achieve that?

答:
Use conditional aggregation :

```<code>select id, name, to_char(date,'YYYY-MM') as "Date",
       sum(case when status = 'PRESENT' then 1 else 0 end ) as present,
       sum(case when status = 'NOT PRESENT' then 1 else 0 end ) as not_present
  from tab
 group by id, name, "Date"
 order by id
</code>```

Demo

keeping else 0 is important to get 0 for null returning cases

column alias in the select list might be used in the group by list
for Postgres

due to the desired output, truncating date value to month by
to_char(date,'YYYY-MM') is needed

Body:
Using some SQL in the tables of some database, I get a result like this:

id  name    date            status
1   John    2018-05-03      PRESENT
2   Mary    2018-05-03      NOT PRESENT
3   Jane    2018-05-03      NOT PRESENT
2   Mary    2018-05-04      PRESENT
1   John    2018-05-04      PRESENT
1   John    2018-05-05      PRESENT
2   Mary    2018-05-05      NOT PRESENT
3   Jane    2018-05-04      PRESENT
3   Jane    2018-05-05      NOT PRESENT
1   John    2018-05-06      PRESENT

I wanna use further SQL to get in a result like this one:

id  name    date      present   not present
1   John    2018-05       4           0
2   Mary    2018-05       1           2
3   Jane    2018-05       2           1

In other words, I wanna extract how many classes a student attended in a given month, based on the status he/she received everyday. How can I achieve that?

Body:
Use conditional aggregation :

select id, name, to_char(date,'YYYY-MM') as "Date",
       sum(case when status = 'PRESENT' then 1 else 0 end ) as present,
       sum(case when status = 'NOT PRESENT' then 1 else 0 end ) as not_present
  from tab
 group by id, name, "Date"
 order by id

Demo

keeping else 0 is important to get 0 for null returning cases

column alias in the select list might be used in the group by list
for Postgres

due to the desired output, truncating date value to month by
to_char(date,'YYYY-MM') is needed


问:
How do I center my buttons on my website?
I'm having a problem with my code and can't figure it out. I'm writing my own website and can't get my buttons to go to the center of the page. I tried almost everything I think but it always goes to about 30% or 70% for some reason... The website is not fully responsive for now I will work on that later. What's wrong with my code? What can I do to fix it next time? Thanks for any ideas!

function showHide() {
    var navList = document.getElementById("nav-lists");

    if (navList.className == '_Menus') {
        navList.classList.add("_Menus-show");
    } else {
        navList.classList.remove("_Menus-show");
    }

    const body = document.querySelector('body')
    const twitter = document.querySelector('.twitter')

    twitter.addEventListener("mouseover", function () {
        body.classList.add('linked')
    },false)

    twitter.addEventListener("mouseout", function () {
        body.classList.remove('linked')
    }, false)

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@font-face {
    font-family: 'familiar_probold';
    src: url('fonts/FamiliarPro/familiar_pro-bold-webfont.woff2') format('woff2'),
    url('fonts/FamiliarPro/familiar_pro-bold-webfont.woff') format('woff');
    font-weight: normal;
    font-style: normal;

}
@font-face {
    font-family: 'uni_sansheavy_caps';
    src: url('fonts/UniSansHeavy/uni_sans_heavy-webfont.woff2') format('woff2'),
    url('fonts/UniSansHeavy/uni_sans_heavy-webfont.woff') format('woff');
    font-weight: normal;
    font-style: normal;

}
@font-face {
    font-family: 'source_sans_problack';
    src: url('fonts/SourceSans/sourcesanspro-black-webfont.woff2') format('woff2'),
    url('fonts/SourceSans/sourcesanspro-black-webfont.woff') format('woff');
    font-weight: normal;
    font-style: normal;

}
*{
    margin: 0;
    padding: 0;
}
*,
*::before,
*::after {
    box-sizing: border-box;
    -webkit-box-sizing: border-box;
}

body {
    padding: 0;
    margin: 0;
    background-color: #f7f7f7;
    font-family: sans-serif;
}
img {
    width: 100%;
    height: auto;
}
.navbar {
    width: 100%;
    background-color: #000;

}

.container {
    max-width: 1140px;
    margin: 0 auto;
    height: 60px;
    display: flex;
    flex-wrap: wrap;

}

._Logo {
    overflow: hidden;
    text-align: center;
    flex-basis: 230px;
}

._Logo img {
    height: 100% !important;
    width: 150px !important;
}

._Menus ul {
    display: flex;
    list-style: none;
    padding: 0;
    margin: 0;
    flex-wrap: wrap;
}
._Menus ul li a {
    display: block;
    padding: 0 10px;
    height: 60px;
    line-height: 60px;
    text-decoration: none;
    color: #FFF;
    outline: none;
    font-family: 'uni_sansheavy_caps';
}
._Menus ul li a:hover {
    background-color: #FFF;
    color: #000;
}

._Iconbar {
    display: none;
    background-color: #000;
}

.menu-bar {
    width: 45px;
    align-self: center;
    cursor: pointer;
}

.icon-bar {
    height: 3px;
    width: 100%;
    background: #FFF;
    margin: 7px 0;
    display: block;
    border-radius: 2px;
}
.toppadding{
    padding-top: 0;
}
.topbackround{
    width: 100%;
    height: auto;
    position: relative;
    text-align: center;
    color: white;
}
.sloganlefttextfirst{
    position: absolute;
    top: 20%;
    left: 5%;
    font-family: 'familiar_probold';
    font-size: 200%;
    color: grey;
}
.sloganlefttextsecond{
    position: absolute;
    top: 25%;
    left: 5%;
    font-family: 'uni_sansheavy_caps';
    font-size: 500%;
}
.sloganlefttextthird{
    position: absolute;
    top: 35%;
    left: 5%;
    font-family: 'uni_sansheavy_caps';
    font-size: 500%;
    color: #DCC98E;
    border-bottom: 6px solid #DCC98E;
    padding-bottom: 3px;
}
.howitworkslefttextfirst a{
    position: absolute;
    top: 51%;
    left: 5%;
    font-family: 'familiar_probold';
    font-size: 200%;
    color: #B9CDBE;
    border-bottom: 3px solid #B9CDBE;
    padding-bottom: 3px;
    text-decoration: none;
}
.howitworkslefttextsecond{
    position: absolute;
    top: 57%;
    left: 5%;
    font-family: 'Arial';
    font-size: 200%;
    color: white;
}
hr{
    color: black;
    background-color: black;
    height: 8px;
    border: none;
}
.midbackground{
    background-color: #1B1C1E;
    padding-bottom: 100px;
}
.tutorial{
    padding-top: 3%;
    padding-bottom: 3%;
    text-align: center;
    left: 50%;
    font-family: 'uni_sansheavy_caps';
    color: #DCC98E;
    font-size: 350%;
    width: 100%;
}
.tutorial p{
    padding-top: 20px;
    padding-bottom: 20px;
    text-align: center;
    left: 50%;
    font-family: 'Arial';
    color: white;
    font-size: 50%;
    width: 100%;
}
.circles{
    margin: 0 auto;
}
.circles > div {
    overflow: hidden;
    float: left;
    width: auto;
    height: auto;
    position: relative;
    border-radius: 50%;
    -moz-border-radius: 50%;
    -webkit-border-radius: 50%;
    background: #1B1C1E;
}

.circles > div > div {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    font-family: 'uni_sansheavy_caps';
    font-size: 400%;
    color: grey;
}
.circles > div > div > div {
    display: table;
    width: 100%;
    height: 100%;
}
.circles > div > div > div > div {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}
@media (max-width: 320px)
{
    .circles > div {padding: 50%;}
}

@media (min-width: 321px) and (max-width: 800px)
{
    .circles > div {padding: 25%;}
}

@media (min-width: 801px)
{
    .circles{width:800px}
    .circles > div {padding: 12.5%;}
}
.circlescontent{
    margin: 0 auto;
}
.circlescontent > div {
    overflow:hidden;
    float:left;
    width:auto;
    height:auto;
    position: relative;
    background: #1B1C1E;
}

.circlescontent > div > div {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    font-family: 'familiar_probold';
    font-size: 250%;
    color: grey;
}
.circlescontent > div > div > div {
    display: table;
    width: 100%;
    height: 100%;
}
.circlescontent > div > div > div > div {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}
@media (max-width: 320px)
{
    .circlescontent > div {padding: 50%;}
}

@media (min-width: 321px) and (max-width: 800px)
{
    .circlescontent > div {padding: 25%;}
}

@media (min-width: 801px)
{
    .circlescontent{width:800px}
    .circlescontent > div {padding: 12.5%;}
}
.statement{
    padding-top: 25%;
    padding-bottom: 3%;
    text-align: center;
    left: 50%;
    font-family: 'uni_sansheavy_caps';
    color: #DCC98E;
    font-size: 350%;
    width: 100%;
}
.statement p{
    padding-top: 20px;
    padding-bottom: 0;
    text-align: center;
    left: 50%;
    font-family: 'familiar_probold';
    color: white;
    font-size: 50%;
    width: 100%;
}
.statementfinal{
    padding-top: 0;
    padding-bottom: 3%;
    text-align: center;
    left: 50%;
    font-family: 'uni_sansheavy_caps';
    color: #DCC98E;
    font-size: 350%;
    width: 100%;
}  /*HERE*/
.buttonbkg{
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 90vh;
}
.button {
    width: 320px;
    max-width: 100%;
    overflow: hidden;
    position: relative;
    transform: translatez(0);
    text-decoration: none;
    box-sizing: border-box;
    font-size: 130%;
    font-weight: normal;
    font-family: 'familiar_probold';
    color: #B9CDBE;
    box-shadow: 0 9px 18px rgba(0,0,0,0.2);
    display: inline-block;
    left: 50%;
    margin: 3%;
    align-content: center;
}

.steam{
    text-align: center;
    border-radius: 50px;
    padding: 26px;
    color: white;
    background: #BD3381;
    transition: all 0.2s ease-out 0s;
    display: inline-block;
    align-content: center;
}

.gradient {
    position: absolute;
    top: 0;
    right: 0;
    width: 100%;
    height: 100%;
    bottom: auto;
    margin: auto;
    z-index: -1;
    background: radial-gradient(90px circle at top center, rgba(238,88,63,.8) 30%, rgba(255,255,255,0));
    transition: all 0s ease-out 0s;
    transform: translatex(-140px);
    animation: 18s linear 0s infinite move;
    display: inline-block;
    align-content: center;
}

@keyframes move {
    0% {
        transform: translatex(-140px);
    }
    25% {
        transform: translatex(140px);
        opacity: 0.3;
    }
    50% {
        transform: translatex(140px);
        opacity: 1;
        background: radial-gradient(90px circle at bottom center, rgba(238,88,63,.5) 30%, rgba(255,255,255,0));
    }
    75% {
        transform: translatex(-140px);
        opacity: 0.3;
    }
    100% {
        opacity: 1;
        transform: translatex(-140px);
        background: radial-gradient(90px circle at top center, rgba(238,88,63,.5) 30%, rgba(255,255,255,0));
    }
}
@media (max-width: 900px) {
    ._Logo {
        height: 60px;
    }

    ._Menus {
        flex: 100%;
        background: #333;
        height: 0;
        overflow: hidden;

    }

    ._Menus ul{
        flex-direction: column;
    }

    ._Menus ul li a {
        height: 40px;
        font-size: 14px;
        text-transform: uppercase;
        line-height: 40px;
    }

    ._Menus ul li a:hover {
        background-color: #81d742;
        color: #FFF;
    }

    .container {
        justify-content: space-between;
    }

    ._Iconbar {
        display: flex;
        margin-right: 10px;

    }

    ._Menus-show {
        height: auto;
    }
    .brandimage{
        display: none;
    }

@media (max-width: 600px) {
    ._Logo {
        height: 60px;
    }

    ._Menus {
        flex: 100%;
        background: #333;
        height: 0;
        overflow: hidden;

    }

    ._Menus ul{
        flex-direction: column;
    }

    ._Menus ul li a {
        height: 40px;
        font-size: 14px;
        text-transform: uppercase;
        line-height: 40px;
    }

    ._Menus ul li a:hover {
        background-color: #81d742;
        color: #FFF;
    }

    .container {
        justify-content: space-between;
    }

    ._Iconbar {
        display: flex;
        margin-right: 10px;

    }

    ._Menus-show {
        height: auto;
    }

    .brandimage{
        display: none;
    }
}}

/*
#0C0028
#1D5EC3
#181A1B
 */</code>```

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Reff Skins</title>
    <link rel="stylesheet" href="style.css">
    <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS responsive navigation menu</title>

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS responsive navigation menu</title>

ABOUT

HOW IT WORKS

FAQ

AVAILABLE SKINS

SIGN IN THROUGH STEAM

WEBSITE WITH TRULY FREE SKINS

LOW ON SKINS?

TIME TO GET NEW FREE!

HOW IS THIS WORKING?

check how it works page or visit our YouTube

HOW CAN I DO IT?
If you want your new skins complete the four easy steps.

                        1.

                        2.

                        3.

                        4.

                        SIGN IN WITH STEAM

                        DO THE REFERR PROCESS

                        SELECT WANTED SKINS

                        GET YOUR SKINS

IT'S THAT EASY
NO DEPOSITS, NO PAYMENT METHODS, NO RISKY GAMBLING, NO SKINS HOLDING

WE SAID NO TO CATCHES!

        SIGN IN WITH STEAM
        AVAILABLE SKINS
        HOW IT WORKS

```

答:
Seems like you've got it half using flex, here's an answer sticking to it.

Firstly, you spelt buttonbkg wrong. Add flex-direction: column to it. Then like others said you will want to get rid of the left: 50%. On your .steam add your flex, and center align/justify.

.buttonbkg{
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 90vh;
}

.button {
    width: 320px;
    max-width: 100%;
    overflow: hidden;
    position: relative;
    transform: translatez(0);
    text-decoration: none;
    box-sizing: border-box;
    font-size: 130%;
    font-weight: normal;
    font-family: 'familiar_probold';
    color: #B9CDBE;
    box-shadow: 0 9px 18px rgba(0,0,0,0.2);
    display: inline-block;
    margin: 3%;
    align-content: center;
}

.steam{
    text-align: center;
    border-radius: 50px;
    padding: 26px;
    color: white;
    background: #BD3381;
    transition: all 0.2s ease-out 0s;
    display: flex;
    justify-content: center;
    align-items: center;
}```

Body:
I'm having a problem with my code and can't figure it out. I'm writing my own website and can't get my buttons to go to the center of the page. I tried almost everything I think but it always goes to about 30% or 70% for some reason... The website is not fully responsive for now I will work on that later. What's wrong with my code? What can I do to fix it next time? Thanks for any ideas!

function showHide() {
    var navList = document.getElementById("nav-lists");

    if (navList.className == '_Menus') {
        navList.classList.add("_Menus-show");
    } else {
        navList.classList.remove("_Menus-show");
    }

    const body = document.querySelector('body')
    const twitter = document.querySelector('.twitter')

    twitter.addEventListener("mouseover", function () {
        body.classList.add('linked')
    },false)

    twitter.addEventListener("mouseout", function () {
        body.classList.remove('linked')
    }, false)

}

@font-face {
    font-family: 'familiar_probold';
    src: url('fonts/FamiliarPro/familiar_pro-bold-webfont.woff2') format('woff2'),
    url('fonts/FamiliarPro/familiar_pro-bold-webfont.woff') format('woff');
    font-weight: normal;
    font-style: normal;

}
@font-face {
    font-family: 'uni_sansheavy_caps';
    src: url('fonts/UniSansHeavy/uni_sans_heavy-webfont.woff2') format('woff2'),
    url('fonts/UniSansHeavy/uni_sans_heavy-webfont.woff') format('woff');
    font-weight: normal;
    font-style: normal;

}
@font-face {
    font-family: 'source_sans_problack';
    src: url('fonts/SourceSans/sourcesanspro-black-webfont.woff2') format('woff2'),
    url('fonts/SourceSans/sourcesanspro-black-webfont.woff') format('woff');
    font-weight: normal;
    font-style: normal;

}
*{
    margin: 0;
    padding: 0;
}
*,
*::before,
*::after {
    box-sizing: border-box;
    -webkit-box-sizing: border-box;
}

body {
    padding: 0;
    margin: 0;
    background-color: #f7f7f7;
    font-family: sans-serif;
}
img {
    width: 100%;
    height: auto;
}
.navbar {
    width: 100%;
    background-color: #000;

}

.container {
    max-width: 1140px;
    margin: 0 auto;
    height: 60px;
    display: flex;
    flex-wrap: wrap;

}

._Logo {
    overflow: hidden;
    text-align: center;
    flex-basis: 230px;
}

._Logo img {
    height: 100% !important;
    width: 150px !important;
}

._Menus ul {
    display: flex;
    list-style: none;
    padding: 0;
    margin: 0;
    flex-wrap: wrap;
}
._Menus ul li a {
    display: block;
    padding: 0 10px;
    height: 60px;
    line-height: 60px;
    text-decoration: none;
    color: #FFF;
    outline: none;
    font-family: 'uni_sansheavy_caps';
}
._Menus ul li a:hover {
    background-color: #FFF;
    color: #000;
}

._Iconbar {
    display: none;
    background-color: #000;
}

.menu-bar {
    width: 45px;
    align-self: center;
    cursor: pointer;
}

.icon-bar {
    height: 3px;
    width: 100%;
    background: #FFF;
    margin: 7px 0;
    display: block;
    border-radius: 2px;
}
.toppadding{
    padding-top: 0;
}
.topbackround{
    width: 100%;
    height: auto;
    position: relative;
    text-align: center;
    color: white;
}
.sloganlefttextfirst{
    position: absolute;
    top: 20%;
    left: 5%;
    font-family: 'familiar_probold';
    font-size: 200%;
    color: grey;
}
.sloganlefttextsecond{
    position: absolute;
    top: 25%;
    left: 5%;
    font-family: 'uni_sansheavy_caps';
    font-size: 500%;
}
.sloganlefttextthird{
    position: absolute;
    top: 35%;
    left: 5%;
    font-family: 'uni_sansheavy_caps';
    font-size: 500%;
    color: #DCC98E;
    border-bottom: 6px solid #DCC98E;
    padding-bottom: 3px;
}
.howitworkslefttextfirst a{
    position: absolute;
    top: 51%;
    left: 5%;
    font-family: 'familiar_probold';
    font-size: 200%;
    color: #B9CDBE;
    border-bottom: 3px solid #B9CDBE;
    padding-bottom: 3px;
    text-decoration: none;
}
.howitworkslefttextsecond{
    position: absolute;
    top: 57%;
    left: 5%;
    font-family: 'Arial';
    font-size: 200%;
    color: white;
}
hr{
    color: black;
    background-color: black;
    height: 8px;
    border: none;
}
.midbackground{
    background-color: #1B1C1E;
    padding-bottom: 100px;
}
.tutorial{
    padding-top: 3%;
    padding-bottom: 3%;
    text-align: center;
    left: 50%;
    font-family: 'uni_sansheavy_caps';
    color: #DCC98E;
    font-size: 350%;
    width: 100%;
}
.tutorial p{
    padding-top: 20px;
    padding-bottom: 20px;
    text-align: center;
    left: 50%;
    font-family: 'Arial';
    color: white;
    font-size: 50%;
    width: 100%;
}
.circles{
    margin: 0 auto;
}
.circles > div {
    overflow: hidden;
    float: left;
    width: auto;
    height: auto;
    position: relative;
    border-radius: 50%;
    -moz-border-radius: 50%;
    -webkit-border-radius: 50%;
    background: #1B1C1E;
}

.circles > div > div {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    font-family: 'uni_sansheavy_caps';
    font-size: 400%;
    color: grey;
}
.circles > div > div > div {
    display: table;
    width: 100%;
    height: 100%;
}
.circles > div > div > div > div {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}
@media (max-width: 320px)
{
    .circles > div {padding: 50%;}
}

@media (min-width: 321px) and (max-width: 800px)
{
    .circles > div {padding: 25%;}
}

@media (min-width: 801px)
{
    .circles{width:800px}
    .circles > div {padding: 12.5%;}
}
.circlescontent{
    margin: 0 auto;
}
.circlescontent > div {
    overflow:hidden;
    float:left;
    width:auto;
    height:auto;
    position: relative;
    background: #1B1C1E;
}

.circlescontent > div > div {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    font-family: 'familiar_probold';
    font-size: 250%;
    color: grey;
}
.circlescontent > div > div > div {
    display: table;
    width: 100%;
    height: 100%;
}
.circlescontent > div > div > div > div {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}
@media (max-width: 320px)
{
    .circlescontent > div {padding: 50%;}
}

@media (min-width: 321px) and (max-width: 800px)
{
    .circlescontent > div {padding: 25%;}
}

@media (min-width: 801px)
{
    .circlescontent{width:800px}
    .circlescontent > div {padding: 12.5%;}
}
.statement{
    padding-top: 25%;
    padding-bottom: 3%;
    text-align: center;
    left: 50%;
    font-family: 'uni_sansheavy_caps';
    color: #DCC98E;
    font-size: 350%;
    width: 100%;
}
.statement p{
    padding-top: 20px;
    padding-bottom: 0;
    text-align: center;
    left: 50%;
    font-family: 'familiar_probold';
    color: white;
    font-size: 50%;
    width: 100%;
}
.statementfinal{
    padding-top: 0;
    padding-bottom: 3%;
    text-align: center;
    left: 50%;
    font-family: 'uni_sansheavy_caps';
    color: #DCC98E;
    font-size: 350%;
    width: 100%;
}  /*HERE*/
.buttonbkg{
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 90vh;
}
.button {
    width: 320px;
    max-width: 100%;
    overflow: hidden;
    position: relative;
    transform: translatez(0);
    text-decoration: none;
    box-sizing: border-box;
    font-size: 130%;
    font-weight: normal;
    font-family: 'familiar_probold';
    color: #B9CDBE;
    box-shadow: 0 9px 18px rgba(0,0,0,0.2);
    display: inline-block;
    left: 50%;
    margin: 3%;
    align-content: center;
}

.steam{
    text-align: center;
    border-radius: 50px;
    padding: 26px;
    color: white;
    background: #BD3381;
    transition: all 0.2s ease-out 0s;
    display: inline-block;
    align-content: center;
}

.gradient {
    position: absolute;
    top: 0;
    right: 0;
    width: 100%;
    height: 100%;
    bottom: auto;
    margin: auto;
    z-index: -1;
    background: radial-gradient(90px circle at top center, rgba(238,88,63,.8) 30%, rgba(255,255,255,0));
    transition: all 0s ease-out 0s;
    transform: translatex(-140px);
    animation: 18s linear 0s infinite move;
    display: inline-block;
    align-content: center;
}

@keyframes move {
    0% {
        transform: translatex(-140px);
    }
    25% {
        transform: translatex(140px);
        opacity: 0.3;
    }
    50% {
        transform: translatex(140px);
        opacity: 1;
        background: radial-gradient(90px circle at bottom center, rgba(238,88,63,.5) 30%, rgba(255,255,255,0));
    }
    75% {
        transform: translatex(-140px);
        opacity: 0.3;
    }
    100% {
        opacity: 1;
        transform: translatex(-140px);
        background: radial-gradient(90px circle at top center, rgba(238,88,63,.5) 30%, rgba(255,255,255,0));
    }
}
@media (max-width: 900px) {
    ._Logo {
        height: 60px;
    }

    ._Menus {
        flex: 100%;
        background: #333;
        height: 0;
        overflow: hidden;

    }

    ._Menus ul{
        flex-direction: column;
    }

    ._Menus ul li a {
        height: 40px;
        font-size: 14px;
        text-transform: uppercase;
        line-height: 40px;
    }

    ._Menus ul li a:hover {
        background-color: #81d742;
        color: #FFF;
    }

    .container {
        justify-content: space-between;
    }

    ._Iconbar {
        display: flex;
        margin-right: 10px;

    }

    ._Menus-show {
        height: auto;
    }
    .brandimage{
        display: none;
    }

@media (max-width: 600px) {
    ._Logo {
        height: 60px;
    }

    ._Menus {
        flex: 100%;
        background: #333;
        height: 0;
        overflow: hidden;

    }

    ._Menus ul{
        flex-direction: column;
    }

    ._Menus ul li a {
        height: 40px;
        font-size: 14px;
        text-transform: uppercase;
        line-height: 40px;
    }

    ._Menus ul li a:hover {
        background-color: #81d742;
        color: #FFF;
    }

    .container {
        justify-content: space-between;
    }

    ._Iconbar {
        display: flex;
        margin-right: 10px;

    }

    ._Menus-show {
        height: auto;
    }

    .brandimage{
        display: none;
    }
}}

/*
#0C0028
#1D5EC3
#181A1B
 */

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Reff Skins</title>
    <link rel="stylesheet" href="style.css">
    <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS responsive navigation menu</title>

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS responsive navigation menu</title>

ABOUT

HOW IT WORKS

FAQ

AVAILABLE SKINS

SIGN IN THROUGH STEAM

WEBSITE WITH TRULY FREE SKINS

LOW ON SKINS?

TIME TO GET NEW FREE!

HOW IS THIS WORKING?

check how it works page or visit our YouTube

HOW CAN I DO IT?
If you want your new skins complete the four easy steps.

                        1.

                        2.

                        3.

                        4.

                        SIGN IN WITH STEAM

                        DO THE REFERR PROCESS

                        SELECT WANTED SKINS

                        GET YOUR SKINS

IT'S THAT EASY
NO DEPOSITS, NO PAYMENT METHODS, NO RISKY GAMBLING, NO SKINS HOLDING

WE SAID NO TO CATCHES!

        SIGN IN WITH STEAM
        AVAILABLE SKINS
        HOW IT WORKS


问:
Creating a file of max length characters, with a word inserted at random locations x amount of times
I am able to create the random data file but when trying to insert the word at random locations x amount of times, the length of the file becomes greater than the max length passed in.

I have tried creating a file with random characters - length of word*amount of times it needs to be inserted and then adding it to the random locations but that just led to it being appended to the end of the file.

def gen_file(word:str, frequency:int, maxlength:int):
    contents = ''
    i = 0

    while i < frequency:
        for x in range(0, maxlength):
            ran_num = random.randint(0, maxlength-1)
            if x == ran_num:
                contents = contents + word
                i = i+1
            else:
                contents = contents + random.choice(string.ascii_letters)

    file = open("new.txt","w")
    file.write(file_contents)
    file.close()
```

If I call the function as gen_file('hello', 3, 5000). I expect the output file to be 5000 characters long with 'hello' inserted at 3 random locations but I get an output file that ranges anywhere from 10,000 - 20,000 characters.

答:
Your problem is right at the top of your control flow:

```<code>while i < frequency:
    for x in range(0, maxlength):
</code>```

For each of the 3 insertions, you generate 5000 x characters.  Instead, you need to choose three random locations within one set of 5000.  I suggest that you do this by choosing the three random locations at the beginning.  Sort those in order.  Then write your file, keeping track of the index position.  Whenever you reach the next position in your random list, stop to insert "hello".

Does that get you going?

Body:
I am able to create the random data file but when trying to insert the word at random locations x amount of times, the length of the file becomes greater than the max length passed in.

I have tried creating a file with random characters - length of word*amount of times it needs to be inserted and then adding it to the random locations but that just led to it being appended to the end of the file.

def gen_file(word:str, frequency:int, maxlength:int):
    contents = ''
    i = 0

    while i < frequency:
        for x in range(0, maxlength):
            ran_num = random.randint(0, maxlength-1)
            if x == ran_num:
                contents = contents + word
                i = i+1
            else:
                contents = contents + random.choice(string.ascii_letters)

    file = open("new.txt","w")
    file.write(file_contents)
    file.close()

If I call the function as gen_file('hello', 3, 5000). I expect the output file to be 5000 characters long with 'hello' inserted at 3 random locations but I get an output file that ranges anywhere from 10,000 - 20,000 characters.

Body:
Your problem is right at the top of your control flow:

while i < frequency:
    for x in range(0, maxlength):

For each of the 3 insertions, you generate 5000 x characters.  Instead, you need to choose three random locations within one set of 5000.  I suggest that you do this by choosing the three random locations at the beginning.  Sort those in order.  Then write your file, keeping track of the index position.  Whenever you reach the next position in your random list, stop to insert "hello".

Does that get you going?


问:
Creating recursive function to find object with certain attribute value
I have a list of objects based on:

```<code>class foo:
    def __init__(self,name):
         self.name = name
         self.children = [] #other instances contained in this list
</code>```

I have created a function that will find the object when .name matches the search term and will search through all the children of these objects:

```<code>def find(lst,search_term):
    for obj in lst:
        if obj.name == search_term:
            return obj
        elif obj.children != []:
            try:
                if find(obj.children,search_term).name == search_term:
                    return find(obj.children,search_term)
            except AttributeError:
                pass
</code>```

Is there a more elegant way of doing this?

答:
It's often easier to divide these types of problems into two functions, one for finding in a list and one for finding in a node. The finding in a node function is trivial (either it's the correct node or try to find in the children):

```<code>def _find_node(node, search_term):
    if node.name == search_term:
        return node
    return _find_list(node.children, search_term)
</code>```

the finding in a list function then just calls _find_node on each item (and returns the node if it's found):

```<code>def _find_list(lst, search_term):
    for node in lst:
        found = _find_node(node, search_term)
        if found is not None:
            return found
    return None
</code>```

Note that None is explicitly returned when not found.

Body:
I have a list of objects based on:

class foo:
    def __init__(self,name):
         self.name = name
         self.children = [] #other instances contained in this list

I have created a function that will find the object when .name matches the search term and will search through all the children of these objects:

def find(lst,search_term):
    for obj in lst:
        if obj.name == search_term:
            return obj
        elif obj.children != []:
            try:
                if find(obj.children,search_term).name == search_term:
                    return find(obj.children,search_term)
            except AttributeError:
                pass

Is there a more elegant way of doing this?

Body:
It's often easier to divide these types of problems into two functions, one for finding in a list and one for finding in a node. The finding in a node function is trivial (either it's the correct node or try to find in the children):

def _find_node(node, search_term):
    if node.name == search_term:
        return node
    return _find_list(node.children, search_term)

the finding in a list function then just calls _find_node on each item (and returns the node if it's found):

def _find_list(lst, search_term):
    for node in lst:
        found = _find_node(node, search_term)
        if found is not None:
            return found
    return None

Note that None is explicitly returned when not found.


问:
what is wrong between two "multiple key pressed" code sample?
I was trying to get multiple key pressed at the same time functionality. I found some answer for that. I was following this one.

JavaScript multiple keydown

The problem is I got some of that code which work. But My version of that does not work. I am totally clueless whats going on.

Code from the answer

```<code>var keys;

document.getElementById('demo').addEventListener("keydown", function (e) {
    keys = (keys || []);
    keys[e.keyCode]=true;

    if (keys[65] && keys[66]){
        document.body.style.backgroundColor = "red";
    }
} , false);

document.getElementById('demo').addEventListener("keyup", function (e) {
    keys[e.keyCode]=false;
    document.body.style.backgroundColor = "green";
    stop();
}, false);
</code>```

My version of code is.

```<code>var keys;

document.getElementById('demo').addEventListener("keydown", function (e) {
keys = (keys || []);
    keys[e.keycode]=true;
    if (keys[65] && keys[66]){
    document.body.style.backgroundColor = "red";
}
} , false);
document.getElementById("demo").addEventListener("keyup", function (e) {
    keys[e.keycode]=false;
    document.body.style.backgroundColor = "green";
//stop();
} , false);
</code>```

In my version of code first part is not working. I can't figure out why?

答:
original

 keys[e.keyCode]=true;
stop(); ```
</div>
</div>
</p>

<p>VS.yours</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>keys[e.keycode]=true;
//stop();</code>```

Body:
I was trying to get multiple key pressed at the same time functionality. I found some answer for that. I was following this one.

JavaScript multiple keydown

The problem is I got some of that code which work. But My version of that does not work. I am totally clueless whats going on.

Code from the answer

var keys;

document.getElementById('demo').addEventListener("keydown", function (e) {
    keys = (keys || []);
    keys[e.keyCode]=true;

    if (keys[65] && keys[66]){
        document.body.style.backgroundColor = "red";
    }
} , false);

document.getElementById('demo').addEventListener("keyup", function (e) {
    keys[e.keyCode]=false;
    document.body.style.backgroundColor = "green";
    stop();
}, false);

My version of code is.

var keys;

document.getElementById('demo').addEventListener("keydown", function (e) {
keys = (keys || []);
    keys[e.keycode]=true;
    if (keys[65] && keys[66]){
    document.body.style.backgroundColor = "red";
}
} , false);
document.getElementById("demo").addEventListener("keyup", function (e) {
    keys[e.keycode]=false;
    document.body.style.backgroundColor = "green";
//stop();
} , false);

In my version of code first part is not working. I can't figure out why?

Body:
original

 keys[e.keyCode]=true;
stop();

VS.yours

keys[e.keycode]=true;
//stop();


问:
Why does using void keyword before synchronized throws an error in Java, but the reverse works fine?
```<code>import java.util.*;

public class Deadlock extends Thread{

    private String name;

    public static void main(String[] args) {

    }

    public class MyObject{
        public void synchronized foo(String name) { //throws error saying 'Syntax error on token "void", volatile expected'

        }
    }
}
</code>```

But if, public void synchronized is changed to
public synchronized void, everything is fine.

Why is that?

答:
Look at the Java Specification 8.4.3. Method modifiers which says:

```<code>MethodModifier:
    (one of)
    Annotation public protected private
    abstract static final synchronized native strictfp
</code>```

Those must precede the return type, which comes as the last. The modifiers order does really not matter since they respect the return type comes as the last. That's why public synchronized void is valid.

Body:
import java.util.*;

public class Deadlock extends Thread{

    private String name;

    public static void main(String[] args) {

    }

    public class MyObject{
        public void synchronized foo(String name) { //throws error saying 'Syntax error on token "void", volatile expected'

        }
    }
}

But if, public void synchronized is changed to
public synchronized void, everything is fine.

Why is that?

Body:
Look at the Java Specification 8.4.3. Method modifiers which says:

MethodModifier:
    (one of)
    Annotation public protected private
    abstract static final synchronized native strictfp

Those must precede the return type, which comes as the last. The modifiers order does really not matter since they respect the return type comes as the last. That's why public synchronized void is valid.


问:
How to mock a local object being created in method being tested using JMockit
I unable to mock an instance of a Class which is being created inside the method which I am trying to test. Below is an example to illustrate the issue.

Class and Method Being tested:

```<code>// class being used in the class to be tested
public class SomeOtherClass{

public ResponseObject addObject(Request dtoObject){
    /// Some business logic goes here

    return reponseObject;
  }
}

// Class to be tested
public class ClassToBeTested {

public ClassToBeTested() {}

public void myMethodToBeTested() {
    SomeOtherClass otherClassObject = new SomeOtherClass();

    // Here I want mock the otherClassObject and also addObject method
    // Eventhoug I mocked it seems to me that as otherClassObject is being created here locally
    // I am unable to mock it.
    ReponseObject reponseObject = otherClassObject.addObject(dtoObject);

    // do some other stuff using the reponseObject
  }
}
</code>```

Test Class:

```<code>public class TestClassToBeTested {
@Tested private ClassToBeTested classBeingTested;
@Injectable SomeOtherClass innerSomeOtherClass;

RequestObject myRequestObject = new RequestObject();
myRequestObject.setSomevalue1("1");
myRequestObject.setSomevalue2("2");

ResponseObject myMockResponseObject = new ResponseObject();
myMockResponseObject.setResultCode(SUCCESS);

@Test
public void shouldTestSomething() {
    new NonStrictExpectations(){{
        // Here I am returning the mocked response object.
        SomeOtherClass.addObject((SomeOtherClass)any);
        result =myMockResponseObject;
    }};

    classBeingTested.myMethodToBeTested();

    // ...
 }
}
</code>```

I mocked the SomeOtherClass and its method but no luck, not sure the proper way to mock it using JMockit.

SomeOtherClass & its method addObject

Even though I mocked it in the Test class, but it gets cleared in the method to be tested. I found similar question being asked HERE, but the solution uses some other unit test framework Mockito. I am struggling to find similar solution using JMokcit. Could any one help me to find the solution for this?

Below is my updated code sample

Class and Method Being tested:

```<code>// This is the class to be tested
public class MyMainClass {

public ResponseObject addItem(ProductList products) {

ResponseObject responseObject = new ResponseObject();

OtherService otherService = new OtherService();

List<Product> productList = new ArrayList<Product>();
productList = products.getProducts();

for (int i = 0; i < productList.size(); i++) {
  Product product = otherService.addProduct(productList.get(i));
  System.out.println("model.Product " + product.getName() + " added
  successfully");
}

responseObject.setResponseCode("1");
responseObject.setResponseMessage("Success");
return responseObject;
 }
}

// Some other service internally used by MyMainClass
public class OtherService implements IService{
 public Product addProduct(Product product){

  // Some business logic to process the product
  System.out.println("Adding product :"+product.getName());

  return product;
  }
}

// Interface implemented by OtherService
public interface IService {

 Product addProduct(Product product);

}

// Sample ResponseObject class
public class ResponseObject {

String responseCode;
String responseMessage;

public String getResponseMessage() {
   return responseMessage;
}

public void setResponseMessage(String responseMessage) {
   this.responseMessage = responseMessage;
}

public String getResponseCode() {
  return responseCode;
}

public void setResponseCode(String responseCode) {
  this.responseCode = responseCode;
}
}
</code>```

Test Class:

```<code>public class MyMainClassTest {

@Tested
MyMainClass myMainClass;

@Mocked
IService otherService;

private List<Product> myProducts = new ArrayList<Product>();

@Before
public void init(){

  Product product1 = new Product();
  product1.setName("Test1");
  product1.setPid(1);
  product1.setPrice(100.00);
  myProducts.add(product1);
  Product product2 = new Product();
  product2.setName("Test2");
  product2.setPid(2);
  product2.setPrice(200.00);
  myProducts.add(product2);
}

@Test
public void addItem_Test() throws  Exception{
 myMainClass = new MyMainClass();

 new NonStrictExpectations(){{
  otherService.addProduct((Product)any);
  returns(myProducts.get(0));
 }};

 ProductList productList = new ProductList();
 productList.setProducts(myProducts);
 ResponseObject responseObject = myMainClass.addItem(productList);

 Assert.assertEquals(responseObject.getResponseMessage(),"Success");
}
}
</code>```

After trying and analyzing the problem I found the what went wrong. I will update the solution in the answer section so that it would be helpful others also.

Thanks.

答: You simply use @Mockedfor that. Check the JMockit tutorial or the API documentation, there are plenty of examples.

Body:
I unable to mock an instance of a Class which is being created inside the method which I am trying to test. Below is an example to illustrate the issue.

Class and Method Being tested:

// class being used in the class to be tested
public class SomeOtherClass{

public ResponseObject addObject(Request dtoObject){
    /// Some business logic goes here

    return reponseObject;
  }
}

// Class to be tested
public class ClassToBeTested {

public ClassToBeTested() {}

public void myMethodToBeTested() {
    SomeOtherClass otherClassObject = new SomeOtherClass();

    // Here I want mock the otherClassObject and also addObject method
    // Eventhoug I mocked it seems to me that as otherClassObject is being created here locally
    // I am unable to mock it.
    ReponseObject reponseObject = otherClassObject.addObject(dtoObject);

    // do some other stuff using the reponseObject
  }
}

Test Class:

public class TestClassToBeTested {
@Tested private ClassToBeTested classBeingTested;
@Injectable SomeOtherClass innerSomeOtherClass;

RequestObject myRequestObject = new RequestObject();
myRequestObject.setSomevalue1("1");
myRequestObject.setSomevalue2("2");

ResponseObject myMockResponseObject = new ResponseObject();
myMockResponseObject.setResultCode(SUCCESS);

@Test
public void shouldTestSomething() {
    new NonStrictExpectations(){{
        // Here I am returning the mocked response object.
        SomeOtherClass.addObject((SomeOtherClass)any);
        result =myMockResponseObject;
    }};

    classBeingTested.myMethodToBeTested();

    // ...
 }
}

I mocked the SomeOtherClass and its method but no luck, not sure the proper way to mock it using JMockit.

SomeOtherClass & its method addObject

Even though I mocked it in the Test class, but it gets cleared in the method to be tested. I found similar question being asked HERE, but the solution uses some other unit test framework Mockito. I am struggling to find similar solution using JMokcit. Could any one help me to find the solution for this?

Below is my updated code sample

Class and Method Being tested:

// This is the class to be tested
public class MyMainClass {

public ResponseObject addItem(ProductList products) {

ResponseObject responseObject = new ResponseObject();

OtherService otherService = new OtherService();

List<Product> productList = new ArrayList<Product>();
productList = products.getProducts();

for (int i = 0; i < productList.size(); i++) {
  Product product = otherService.addProduct(productList.get(i));
  System.out.println("model.Product " + product.getName() + " added
  successfully");
}

responseObject.setResponseCode("1");
responseObject.setResponseMessage("Success");
return responseObject;
 }
}

// Some other service internally used by MyMainClass
public class OtherService implements IService{
 public Product addProduct(Product product){

  // Some business logic to process the product
  System.out.println("Adding product :"+product.getName());

  return product;
  }
}

// Interface implemented by OtherService
public interface IService {

 Product addProduct(Product product);

}

// Sample ResponseObject class
public class ResponseObject {

String responseCode;
String responseMessage;

public String getResponseMessage() {
   return responseMessage;
}

public void setResponseMessage(String responseMessage) {
   this.responseMessage = responseMessage;
}

public String getResponseCode() {
  return responseCode;
}

public void setResponseCode(String responseCode) {
  this.responseCode = responseCode;
}
}

Test Class:

public class MyMainClassTest {

@Tested
MyMainClass myMainClass;

@Mocked
IService otherService;

private List<Product> myProducts = new ArrayList<Product>();

@Before
public void init(){

  Product product1 = new Product();
  product1.setName("Test1");
  product1.setPid(1);
  product1.setPrice(100.00);
  myProducts.add(product1);
  Product product2 = new Product();
  product2.setName("Test2");
  product2.setPid(2);
  product2.setPrice(200.00);
  myProducts.add(product2);
}

@Test
public void addItem_Test() throws  Exception{
 myMainClass = new MyMainClass();

 new NonStrictExpectations(){{
  otherService.addProduct((Product)any);
  returns(myProducts.get(0));
 }};

 ProductList productList = new ProductList();
 productList.setProducts(myProducts);
 ResponseObject responseObject = myMainClass.addItem(productList);

 Assert.assertEquals(responseObject.getResponseMessage(),"Success");
}
}

After trying and analyzing the problem I found the what went wrong. I will update the solution in the answer section so that it would be helpful others also.

Thanks.


问:
c++ how to use select to see if a socket has closed
Can someone provide me an example of how to use select() to see if a client has closed the connection on a socket?

FYI. I'm using linux.

Thanks!

答: If you get a read notification and the read returns 0 bytes the client has exited cleanly. If not you will get an exception notification.</p>

ContentLicense: CC BY-SA 3.0


问:
DataBinding to a checkbox not working correctly
I have a problem using DataBinding to a checkbox in C#. Checkbox does not reflect the value of the object it is bind to.

I used checkBox1.DataBindings.Add("Checked", cb, "t", false, DataSourceUpdateMode.OnPropertyChanged) to bind a simple data source to an object, cb. The the bool property "t" in the object updates based on the checkbox checked state, but the checkbox check state does not reflect the object state (cb.t).

```<code>namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        test cb = new test();
        public Form1()
        {
            InitializeComponent();

            cb.t = false;

            checkBox1.DataBindings.Add("Checked", cb, "t", false, DataSourceUpdateMode.OnPropertyChanged);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            cb.t = true;
            //checkBox1.Refresh();
            //checkBox1.Invalidate();
        }
    }

    public class test
    {
        public bool t { set; get; }
    }
}
</code>```

if i click button1 the state of the checkbox does not change; however, the if i i set the cb.t =  true in the constructor when the form loads the checkbox checked state is the same as the value of cb.t.  thanks for the help.

答:
Your view is not being notified of updates when your property changes. See -
How To: INotifyPropertyChanged

Try making these changes -

```<code>using System.ComponentModel;
using System.Runtime.CompilerServices;

public class test : INotifyPropertyChanged
    {
        private bool _t;
        public bool t {
            get { return _t; }
            set
            {
                if (value != _t)
                {
                    _t = value;
                    NotifyPropertyChanged();
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        // This method is called by the Set accessor of each property.
        // The CallerMemberName attribute that is applied to the optional propertyName
        // parameter causes the property name of the caller to be substituted as an argument.
        private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
</code>```

Body:
I have a problem using DataBinding to a checkbox in C#. Checkbox does not reflect the value of the object it is bind to.

I used checkBox1.DataBindings.Add("Checked", cb, "t", false, DataSourceUpdateMode.OnPropertyChanged) to bind a simple data source to an object, cb. The the bool property "t" in the object updates based on the checkbox checked state, but the checkbox check state does not reflect the object state (cb.t).

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        test cb = new test();
        public Form1()
        {
            InitializeComponent();

            cb.t = false;

            checkBox1.DataBindings.Add("Checked", cb, "t", false, DataSourceUpdateMode.OnPropertyChanged);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            cb.t = true;
            //checkBox1.Refresh();
            //checkBox1.Invalidate();
        }
    }

    public class test
    {
        public bool t { set; get; }
    }
}

if i click button1 the state of the checkbox does not change; however, the if i i set the cb.t =  true in the constructor when the form loads the checkbox checked state is the same as the value of cb.t.  thanks for the help.

Body:
Your view is not being notified of updates when your property changes. See -
How To: INotifyPropertyChanged

Try making these changes -

using System.ComponentModel;
using System.Runtime.CompilerServices;

public class test : INotifyPropertyChanged
    {
        private bool _t;
        public bool t {
            get { return _t; }
            set
            {
                if (value != _t)
                {
                    _t = value;
                    NotifyPropertyChanged();
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        // This method is called by the Set accessor of each property.
        // The CallerMemberName attribute that is applied to the optional propertyName
        // parameter causes the property name of the caller to be substituted as an argument.
        private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }