问:
Getting the first class from multiple classes with the same name with BeautifulSoup
I am trying to extract information from this page which has it's HTML as below.

I am trying to extract the text in the first class="currentServers" (example: I get 745,807 from this line 745,807

The problem is that in the row there are two spans with class name class="currentServers". I want to get the value in the first column of the row.

HTML:

```<code><tr class="player_count_row" style="">
                            <td align="right">
                                <span class="currentServers">745,807</span>
                            </td>
                            <td align="right">
                                <span class="currentServers">836,540</span>
                            </td>
                            <td width="20"> </td>
                            <td>
                                <a class="gameLink" onmouseover="GameHover( this, event, 'global_hover', {"type":"app","id":570,"v6":1} );" onmouseout="HideGameHover( this, event, 'global_hover' )" href="http://store.steampowered.com/app/570/">Dota 2</a>
                            </td>
                        </tr>
</code>```

I feel that I am close but I can't figure it out.

This is what I tried:

```<code>def GetTopGamesByPlayers():
    response = requests.get(url)
    html = response.content

    soup = BeautifulSoup(html)

    r = []

    final_link = soup.p.a
    final_link.decompose()

    links = soup.findAll("a", { "class" : "gameLink" })
    currentPlayers = soup.findAll("span", {"class" : "currentServers"})

    players = ""
    i = 0

    for player in currentPlayers :
        for link in links:
            players = currentPlayers[0].text
            try:
                appid = link.get('onmouseover')
                appid = findAppIdFromStats(appid,'"id":' , ',"public":1')
                linkg = link.get('href')
            except AttributeError:
                r.append(["N/A","N/A","N/A"])
            r.append([appid,linkg,players])

    c = ["N/A","N/A", "N/A"]
    while c in r:
        r.remove(c)
    return r

def findAppIdFromStats( s, first, last ):
      try:
        start = s.index( first ) + len( first )
        end = s.index( last, start )
        return s[start:end]
      except ValueError:
            return "first: " + first + "last: " + last
</code>```

The below is the output :

```<code>[u'346110', u'http://store.steampowered.com/app/346110/', u'745,807']
[u'230410', u'http://store.steampowered.com/app/230410/', u'745,807']
[u'252950', u'http://store.steampowered.com/app/252950/', u'745,807']
[u'482730', u'http://store.steampowered.com/app/482730/', u'745,807']
[u'252490', u'http://store.steampowered.com/app/252490/', u'745,807']
[u'4000', u'http://store.steampowered.com/app/4000/', u'745,807']
[u'444090', u'http://store.steampowered.com/app/444090/', u'745,807']
[u'359550', u'http://store.steampowered.com/app/359550/', u'745,807']
[u'588430', u'http://store.steampowered.com/app/588430/', u'745,807']
[u'374320', u'http://store.steampowered.com/app/374320/', u'745,807']
[u'8930', u'http://store.steampowered.com/app/8930/', u'745,807']
[u'107410', u'http://store.steampowered.com/app/107410/', u'745,807']
[u'238960', u'http://store.steampowered.com/app/238960/', u'745,807']
[u'304930', u'http://store.steampowered.com/app/304930/', u'745,807']
[u'10', u'http://store.steampowered.com/app/10/', u'745,807']
[u'72850', u'http://store.steampowered.com/app/72850/', u'745,807']
[u'289070', u'http://store.steampowered.com/app/289070/', u'745,807']
[u'105600', u'http://store.steampowered.com/app/105600/', u'745,807']
[u'377160', u'http://store.steampowered.com/app/377160/', u'745,807']
[u'236390', u'http://store.steampowered.com/app/236390/', u'745,807']
[u'292030', u'http://store.steampowered.com/app/292030/', u'745,807']
[u'227300', u'http://store.steampowered.com/app/227300/', u'745,807']
[u'386360', u'http://store.steampowered.com/app/386360/', u'745,807']
[u'236850', u'http://store.steampowered.com/app/236850/', u'745,807']
[u'364360', u'http://store.steampowered.com/app/364360/', u'745,807']
[u'381210', u'http://store.steampowered.com/app/381210/', u'745,807']
[u'363970', u'http://store.steampowered.com/app/363970/', u'745,807']
[u'453480', u'http://store.steampowered.com/app/453480/', u'745,807'

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

I want to extract the value that has the red ellipse around it:

(appid, Current Players, Game Name) - I can succesfully get the appid and game name for each game but not the Current Players in sequence

答:
I would try grabbing each of the rows and then grabbing the first instance of .currentServers like this.

```<code>rows = soup.find_all(class_='player_count_row')
for row in rows:
    print row.find(class_='currentServers').text
</code>```

Body:
I am trying to extract information from this page which has it's HTML as below.

I am trying to extract the text in the first class="currentServers" (example: I get 745,807 from this line 745,807

The problem is that in the row there are two spans with class name class="currentServers". I want to get the value in the first column of the row.

HTML:

                                745,807

                                836,540

                                Dota 2

I feel that I am close but I can't figure it out.

This is what I tried:

def GetTopGamesByPlayers():
    response = requests.get(url)
    html = response.content

    soup = BeautifulSoup(html)

    r = []

    final_link = soup.p.a
    final_link.decompose()

    links = soup.findAll("a", { "class" : "gameLink" })
    currentPlayers = soup.findAll("span", {"class" : "currentServers"})

    players = ""
    i = 0

    for player in currentPlayers :
        for link in links:
            players = currentPlayers[0].text
            try:
                appid = link.get('onmouseover')
                appid = findAppIdFromStats(appid,'"id":' , ',"public":1')
                linkg = link.get('href')
            except AttributeError:
                r.append(["N/A","N/A","N/A"])
            r.append([appid,linkg,players])

    c = ["N/A","N/A", "N/A"]
    while c in r:
        r.remove(c)
    return r

def findAppIdFromStats( s, first, last ):
      try:
        start = s.index( first ) + len( first )
        end = s.index( last, start )
        return s[start:end]
      except ValueError:
            return "first: " + first + "last: " + last

The below is the output :

[u'346110', u'http://store.steampowered.com/app/346110/', u'745,807']
[u'230410', u'http://store.steampowered.com/app/230410/', u'745,807']
[u'252950', u'http://store.steampowered.com/app/252950/', u'745,807']
[u'482730', u'http://store.steampowered.com/app/482730/', u'745,807']
[u'252490', u'http://store.steampowered.com/app/252490/', u'745,807']
[u'4000', u'http://store.steampowered.com/app/4000/', u'745,807']
[u'444090', u'http://store.steampowered.com/app/444090/', u'745,807']
[u'359550', u'http://store.steampowered.com/app/359550/', u'745,807']
[u'588430', u'http://store.steampowered.com/app/588430/', u'745,807']
[u'374320', u'http://store.steampowered.com/app/374320/', u'745,807']
[u'8930', u'http://store.steampowered.com/app/8930/', u'745,807']
[u'107410', u'http://store.steampowered.com/app/107410/', u'745,807']
[u'238960', u'http://store.steampowered.com/app/238960/', u'745,807']
[u'304930', u'http://store.steampowered.com/app/304930/', u'745,807']
[u'10', u'http://store.steampowered.com/app/10/', u'745,807']
[u'72850', u'http://store.steampowered.com/app/72850/', u'745,807']
[u'289070', u'http://store.steampowered.com/app/289070/', u'745,807']
[u'105600', u'http://store.steampowered.com/app/105600/', u'745,807']
[u'377160', u'http://store.steampowered.com/app/377160/', u'745,807']
[u'236390', u'http://store.steampowered.com/app/236390/', u'745,807']
[u'292030', u'http://store.steampowered.com/app/292030/', u'745,807']
[u'227300', u'http://store.steampowered.com/app/227300/', u'745,807']
[u'386360', u'http://store.steampowered.com/app/386360/', u'745,807']
[u'236850', u'http://store.steampowered.com/app/236850/', u'745,807']
[u'364360', u'http://store.steampowered.com/app/364360/', u'745,807']
[u'381210', u'http://store.steampowered.com/app/381210/', u'745,807']
[u'363970', u'http://store.steampowered.com/app/363970/', u'745,807']
[u'453480', u'http://store.steampowered.com/app/453480/', u'745,807'

... ... ...

I want to extract the value that has the red ellipse around it:

(appid, Current Players, Game Name) - I can succesfully get the appid and game name for each game but not the Current Players in sequence

Body:
I would try grabbing each of the rows and then grabbing the first instance of .currentServers like this.

rows = soup.find_all(class_='player_count_row')
for row in rows:
    print row.find(class_='currentServers').text


来源: stackexchange

问:
How to rename column before unpivot? SQL Server
Help I want to rename a column before using the unpivot method

My table is like this:

List item

```<code>id| value| ENE| FEB| MAR| ABR| MAY
1 | dsads|2000|2334|2344|2344|2344
</code>```

after unpivot I get something like this

```<code>id| value| month| amount
1 |  dads| ENE  | 2000
2 |  sadf| FEB  | 2334
</code>```

but I want something like this

```<code>id| value| month| amount
1 |  dads| 01   | 2000
2 |  sadf| 02   | 2334
</code>```

This is my query

```<code>select
    [año], [Empresa], [Region], [Suc], [CC], [Cuenta],
    [Subcuenta], [Descripcion], Periodo, Importe
from
    (select * from [dbo].['P Cargado$']) S
unpivot
    (Importe for Periodo in
        ([ENE], [FEB], [MAR], [ABR], [MAY], [JUN], [JUL], [AGO], [SEP],[OCT], [NOV], [DIC])
    ) AS unpvt;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Help I want to rename a column before using the unpivot method

My table is like this:

List item

id| value| ENE| FEB| MAR| ABR| MAY
1 | dsads|2000|2334|2344|2344|2344

after unpivot I get something like this

id| value| month| amount
1 |  dads| ENE  | 2000
2 |  sadf| FEB  | 2334

but I want something like this

id| value| month| amount
1 |  dads| 01   | 2000
2 |  sadf| 02   | 2334

This is my query

select
    [año], [Empresa], [Region], [Suc], [CC], [Cuenta],
    [Subcuenta], [Descripcion], Periodo, Importe
from
    (select * from [dbo].['P Cargado$']) S
unpivot
    (Importe for Periodo in
        ([ENE], [FEB], [MAR], [ABR], [MAY], [JUN], [JUL], [AGO], [SEP],[OCT], [NOV], [DIC])
    ) AS unpvt;

Body:
If you use cross apply(values ..) to unpivot, you could do so like this:

select t.id, t.value, x.*
from t
cross apply (values (1,ene),(2,feb),(3,mar),(4,abr),(5,may)) x (Mnth,Amount)

rextester demo: http://rextester.com/SZDP50356

returns:

+----+-------+------+--------+
| id | value | Mnth | Amount |
+----+-------+------+--------+
|  1 | dsads |    1 |   2000 |
|  1 | dsads |    2 |   2334 |
|  1 | dsads |    3 |   2344 |
|  1 | dsads |    4 |   2344 |
|  1 | dsads |    5 |   2344 |
+----+-------+------+--------+


问:
Excel VBA to insert rows based on cell value and copy columns down based on that number
I know there are several questions and answers about using Excel VBA to copy and insert rows based on a cell value but I have an additional requirement that makes it difficult to find a solution. I'm stuck at this point and need help.

I have a spreadsheet along the lines of the following:

```<code>Name    Unit    Count   Req1    Req2    Req3    Req4    ...  ...    Req25
Apple   304     5       Apple1  Apple2  Apple3  Apple4  ... Apple5
Pear    562     2       Pear1   Pear2
Kiwi    471     4       Kiwi1   Kiwi2   Kiwi3   Kiwi4
</code>```

The spreadsheet has columns for "Req1" through "Req25." If the"count" is 5, then "Req1" through "Req5" columns will have data. The "count" will vary per row leaving the reminder of the columns to "Req25" blank. I need to insert rows based on "count" -1, copy down all columns up to "count" column, and then move "Req2," "Req3," etc. down to the corresponding inserted row in the "Req1" column. I'm probably not explaining it very well.

I need the end result to look like:

```<code>Name    Unit    Count   Req1
Apple   304     5       Apple1
Apple   304     5       Apple2
Apple   304     5       Apple3
Apple   304     5       Apple4
Apple   304     5       Apple5
Pear    562     2       Pear1
Pear    562     2       Pear2
Kiwi    471     4       Kiwi1
Kiwi    471     4       Kiwi2
Kiwi    471     4       Kiwi3
Kiwi    471     4       Kiwi4
</code>```

I am able to insert the correct number of rows but I'm stuck on looping through the columns and moving them down into the "Req1" column.

Any help is GREATLY appreciated!! Thanks in advance!

答:
you could work with arrays and slice them with Application.Index()

```<code>Sub main()
    Dim data1 As Variant, data2 As Variant
    Dim i As Long

    With Range("A2", Cells(Rows.Count, "A").End(xlUp))
        data1 = .Resize(, 3).Value
        data2 = .Offset(, 3).Resize(, 25).Value
        .Resize(, 28).ClearContents
    End With
    For i = LBound(data1) To UBound(data1)
        With Cells(Rows.Count, 1).End(xlUp).Offset(1)
            .Resize(data1(i, 3), 3) = Application.Index(data1, i, 0)
            .Offset(, 3).Resize(data1(i, 3), 1) = Application.Transpose(Application.Index(data2, i, 0))
        End With
    Next
End Sub
</code>```

Body:
I know there are several questions and answers about using Excel VBA to copy and insert rows based on a cell value but I have an additional requirement that makes it difficult to find a solution. I'm stuck at this point and need help.

I have a spreadsheet along the lines of the following:

Name    Unit    Count   Req1    Req2    Req3    Req4    ...  ...    Req25
Apple   304     5       Apple1  Apple2  Apple3  Apple4  ... Apple5
Pear    562     2       Pear1   Pear2
Kiwi    471     4       Kiwi1   Kiwi2   Kiwi3   Kiwi4

The spreadsheet has columns for "Req1" through "Req25." If the"count" is 5, then "Req1" through "Req5" columns will have data. The "count" will vary per row leaving the reminder of the columns to "Req25" blank. I need to insert rows based on "count" -1, copy down all columns up to "count" column, and then move "Req2," "Req3," etc. down to the corresponding inserted row in the "Req1" column. I'm probably not explaining it very well.

I need the end result to look like:

Name    Unit    Count   Req1
Apple   304     5       Apple1
Apple   304     5       Apple2
Apple   304     5       Apple3
Apple   304     5       Apple4
Apple   304     5       Apple5
Pear    562     2       Pear1
Pear    562     2       Pear2
Kiwi    471     4       Kiwi1
Kiwi    471     4       Kiwi2
Kiwi    471     4       Kiwi3
Kiwi    471     4       Kiwi4

I am able to insert the correct number of rows but I'm stuck on looping through the columns and moving them down into the "Req1" column.

Any help is GREATLY appreciated!! Thanks in advance!

Body:
you could work with arrays and slice them with Application.Index()

Sub main()
    Dim data1 As Variant, data2 As Variant
    Dim i As Long

    With Range("A2", Cells(Rows.Count, "A").End(xlUp))
        data1 = .Resize(, 3).Value
        data2 = .Offset(, 3).Resize(, 25).Value
        .Resize(, 28).ClearContents
    End With
    For i = LBound(data1) To UBound(data1)
        With Cells(Rows.Count, 1).End(xlUp).Offset(1)
            .Resize(data1(i, 3), 3) = Application.Index(data1, i, 0)
            .Offset(, 3).Resize(data1(i, 3), 1) = Application.Transpose(Application.Index(data2, i, 0))
        End With
    Next
End Sub


问:
Send parameters to a URL and get output from that page
I have 2 pages say abc.php and def.php. When abc.php sends 2 values [id and name] to def.php, it shows a message "Value received". Now how can I send those 2 values to def.php without using form in abc.php and get the "Value received" message from def.php? I can't use form because when user frequently visits the abc.php file, the script should automatically work and get the message "Value received" from def.php. Please see my example code:

abc.php:

```<code> <?php
  $id="123";
  $name="blahblah";
   //need to send the value to def.php & get value from that page
  // echo $value=Print the "Value received" msg from def.php;
 ?>
</code>```

def.php:

```<code> <?php
  $id=$_GET['id'];
  $name=$_GET['name'];
  if(!is_null($id)&&!is_null($name))
  {  echo "Value received";}
  else{echo "Not ok";}
 ?>
</code>```

Is there any kind heart who can help me solve the issue?

答:
You can try without cURL (I havent tried though):

Copy pasted from : POSTing data without cURL extension

```<code>// Your POST data
$data = http_build_query(array(
    'param1' => 'data1',
    'param2' => 'data2'
));

// Create HTTP stream context
$context = stream_context_create(array(
    'http' => array(
        'method' => 'POST',
        'header' => 'Content-Type: application/x-www-form-urlencoded',
        'content' => $data
    )
));

// Make POST request
$response = file_get_contents('http://example.com', false, $context);
</code>```

Body:
I have 2 pages say abc.php and def.php. When abc.php sends 2 values [id and name] to def.php, it shows a message "Value received". Now how can I send those 2 values to def.php without using form in abc.php and get the "Value received" message from def.php? I can't use form because when user frequently visits the abc.php file, the script should automatically work and get the message "Value received" from def.php. Please see my example code:

abc.php:

 <?php
  $id="123";
  $name="blahblah";
   //need to send the value to def.php & get value from that page
  // echo $value=Print the "Value received" msg from def.php;
 ?>

def.php:

 <?php
  $id=$_GET['id'];
  $name=$_GET['name'];
  if(!is_null($id)&&!is_null($name))
  {  echo "Value received";}
  else{echo "Not ok";}
 ?>

Is there any kind heart who can help me solve the issue?

Body:
You can try without cURL (I havent tried though):

Copy pasted from : POSTing data without cURL extension

// Your POST data
$data = http_build_query(array(
    'param1' => 'data1',
    'param2' => 'data2'
));

// Create HTTP stream context
$context = stream_context_create(array(
    'http' => array(
        'method' => 'POST',
        'header' => 'Content-Type: application/x-www-form-urlencoded',
        'content' => $data
    )
));

// Make POST request
$response = file_get_contents('http://example.com', false, $context);

ContentLicense: CC BY-SA 2.5


问:
Design simple code first movies database (many to many) EF
I'm doing some tutorial on ASP MVC and the guy in the video only uses 1 genre per movie, but I'm interested in knowing on how to make a movie have multiple genres. Example, how do I make this code:

public class Movie
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<Genre> Genre { get; set; }
}

public class Genre
{
    public int Id { get; set; }
    public string Name { get; set; }
}
```

generate some tables like this:

Movie

Id (Primary Key)

Name

Genre

Id (Primary Key)

Name

MovieGenresRelation

Id (Primary Key)

MovieId (References Movie.Id)

GenreId (References Genre.Id)

I tried adding the MovieGenresRelation class but then how do add reference properties to the Movie class?
Anyway I think that's not how I should go about to do this so please point me to the right direction.

答:
You are on the right track (you describe a many-to-many relationship).

You can actually do it with an ICollection on both sides of the relationship in EF6, but in EFCore you have to make the intermediate table yourself. In EF6, you could add this to Genre:

```<code>public virtual ICollection<Movie> Movies {get; set;}
</code>```

As far as reference properties in the intermediate go, just add them the way you would expect:

```<code>public virtual Movie Movie {get; set;}
public virtual Genre Genre {get; set;}
</code>```

The primary difference is that the properties in Movie and Genre would point to MovieGenreRelation instead of each other.

Body:
I'm doing some tutorial on ASP MVC and the guy in the video only uses 1 genre per movie, but I'm interested in knowing on how to make a movie have multiple genres. Example, how do I make this code:

public class Movie
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<Genre> Genre { get; set; }
}

public class Genre
{
    public int Id { get; set; }
    public string Name { get; set; }
}

generate some tables like this:

Movie

Id (Primary Key)

Name

Genre

Id (Primary Key)

Name

MovieGenresRelation

Id (Primary Key)

MovieId (References Movie.Id)

GenreId (References Genre.Id)

I tried adding the MovieGenresRelation class but then how do add reference properties to the Movie class?
Anyway I think that's not how I should go about to do this so please point me to the right direction.

Body:
You are on the right track (you describe a many-to-many relationship).

You can actually do it with an ICollection on both sides of the relationship in EF6, but in EFCore you have to make the intermediate table yourself. In EF6, you could add this to Genre:

public virtual ICollection<Movie> Movies {get; set;}

As far as reference properties in the intermediate go, just add them the way you would expect:

public virtual Movie Movie {get; set;}
public virtual Genre Genre {get; set;}

The primary difference is that the properties in Movie and Genre would point to MovieGenreRelation instead of each other.


问:
Can't access enum within struct
I have the following struct defined

Header File:

```<code>struct SDK {
   enum {
       HEADER0 = 0,
       HEADER1,
       LINGO,
       COMMAND,
       LENGTH,
       ACK_CMD,
       ACK_STATUS
   }commandFormat;
}mySDK;
</code>```

and I want to use it like this:

main.c

```<code>switch (rxData[mySDK.commandFormat.LINGO]) {
   default:
      break;
}
</code>```

I am getting the error: request for member 'LINGO' in something not a structure or union

I know I'm probably doing something stupid, but I can't figure out what exactly. Thank you.

答:
Just write

```<code>switch (rxData[mySDK.commandFormat]) {
</code>```

provided that the data member commandFormat of the object mySDK was initialized in particularly with LINGO.

Or write

```<code>switch (rxData[INGO]) {
</code>```

Title: Can't access enum within struct

Body:
I have the following struct defined

Header File:

struct SDK {
   enum {
       HEADER0 = 0,
       HEADER1,
       LINGO,
       COMMAND,
       LENGTH,
       ACK_CMD,
       ACK_STATUS
   }commandFormat;
}mySDK;

and I want to use it like this:

main.c

switch (rxData[mySDK.commandFormat.LINGO]) {
   default:
      break;
}

I am getting the error: request for member 'LINGO' in something not a structure or union

I know I'm probably doing something stupid, but I can't figure out what exactly. Thank you.

Body:
Just write

switch (rxData[mySDK.commandFormat]) {

provided that the data member commandFormat of the object mySDK was initialized in particularly with LINGO.

Or write

switch (rxData[INGO]) {


问:
How to get two <div> floating below each other
I want to ask how can I move floated  below another so both of them are floating on the same side but they're below each other. Thanks.</p>

答: Thanks, but I solved it so, that i put both s to another  which I floated on that side.</p>

ContentLicense: CC BY-SA 4.0


问:
How to send the requests in batches using Jmeter
I've a scenario where I need to send the requests in batches of user defined number (for example 1K,5K,10K etc) with a specified interval between each batch.

Assume Interval between batch is 30 Seconds, I've to send 'N' number of request per batch, for example 1K. Sending 1K request got finished within 10 Seconds, so for next 20 Seconds no request should go. Once the interval gets over another batch of 1K should be sent.

Input : Data is flowing from a CSV, for the 2nd batch it should ideally start from 1001.

Options tried : Constant Throughput Timer. With this I'm restricting the speed of the request, which I do not want to do.

Can someone help me with other option which i can try with?

答:
Add JSR223 Samplers before and after your requests. Your test plan should look like this:

JSR223 Sampler 1

You requests

JSR223 Sampler 2

Add this code to your first JSR223 Sampler:

```<code>interval = 30000     //Specify the desired interval here
startTime = System.currentTimeMillis()
vars.put("startTime", startTime.toString())
vars.put("interval", Long.toString(interval))
</code>```

Add this code to your second JSR223 Sampler:

```<code>startTime = Long.parseLong(vars.get("startTime"))
interval = Long.parseLong(vars.get("interval"))
endTime = System.currentTimeMillis()
duration = endTime - startTime
if (duration < interval) {
    sleepTime = interval - duration
    log.info("Sleeping for ${sleepTime} ms")
    Thread.sleep(sleepTime)
}
</code>```

This will make your threads sleep until the interval is over (if they've already completed their work).

If you need more precision you can  modify this solution to make all of your threads respect the same time interval.

Body:
Add JSR223 Samplers before and after your requests. Your test plan should look like this:

JSR223 Sampler 1

You requests

JSR223 Sampler 2

Add this code to your first JSR223 Sampler:

interval = 30000     //Specify the desired interval here
startTime = System.currentTimeMillis()
vars.put("startTime", startTime.toString())
vars.put("interval", Long.toString(interval))

Add this code to your second JSR223 Sampler:

startTime = Long.parseLong(vars.get("startTime"))
interval = Long.parseLong(vars.get("interval"))
endTime = System.currentTimeMillis()
duration = endTime - startTime
if (duration < interval) {
    sleepTime = interval - duration
    log.info("Sleeping for ${sleepTime} ms")
    Thread.sleep(sleepTime)
}

This will make your threads sleep until the interval is over (if they've already completed their work).

If you need more precision you can  modify this solution to make all of your threads respect the same time interval.


问:
How to play mp3 file in swift3?
I have started to learn ios development and am stuck in one place. My code to play mp3 file is

```<code>var bombSoundEffect: AVAudioPlayer!
let path = Bundle.main.path(forResource: "faded", ofType:"mp3")!
let url = NSURL(fileURLWithPath: path)

 do {
        let sound = try AVAudioPlayer(contentsOf: (url as NSURL) as URL)
        bombSoundEffect.play()

    } catch {
        print("couldn't load file :(")
    }
    if bombSoundEffect != nil {
        bombSoundEffect.stop()
        bombSoundEffect = nil
        }
</code>```

However, when I click on the button, my file doesn't play. The song is playing perfectly normally.

答:
Try with the follow code: </p>

```<code>var bombSoundEffect: AVAudioPlayer?

func playAudio() {
    let url = Bundle.main.url(forResource: "faded", withExtension: "mp3")!

    do {
        bombSoundEffect = try AVAudioPlayer(contentsOf: url)
        guard let bombSound = bombSoundEffect else { return }

        bombSound.prepareToPlay()
        bombSound.play()
    } catch let error {
        print(error.localizedDescription)
    }
}
</code>```

Title: How to play mp3 file in swift3?

Body:
I have started to learn ios development and am stuck in one place. My code to play mp3 file is

var bombSoundEffect: AVAudioPlayer!
let path = Bundle.main.path(forResource: "faded", ofType:"mp3")!
let url = NSURL(fileURLWithPath: path)

 do {
        let sound = try AVAudioPlayer(contentsOf: (url as NSURL) as URL)
        bombSoundEffect.play()

    } catch {
        print("couldn't load file :(")
    }
    if bombSoundEffect != nil {
        bombSoundEffect.stop()
        bombSoundEffect = nil
        }

However, when I click on the button, my file doesn't play. The song is playing perfectly normally.

Body:
Try with the follow code:

var bombSoundEffect: AVAudioPlayer?

func playAudio() {
    let url = Bundle.main.url(forResource: "faded", withExtension: "mp3")!

    do {
        bombSoundEffect = try AVAudioPlayer(contentsOf: url)
        guard let bombSound = bombSoundEffect else { return }

        bombSound.prepareToPlay()
        bombSound.play()
    } catch let error {
        print(error.localizedDescription)
    }
}


问:
Selecting a random value from a subsection of an enum
Given a Swift enum as such:

```<code>enum PerformerPosition: Int {

    case String_Violin1
    case String_Violin2
    case String_Viola
    case String_Cello
    case String_CB

    case Wind_Oboe
    case Wind_Clarinet
    case Wind_Flute
    ...

}
</code>```

(For the needs of the project, I am not able to have a nested enum.) I would like to randomly select an enum value with the String_ prefix, only.

The only way I know so far is to do a random enum value from all the available cases, as such:

```<code>private static let _count: PerformerPosition.RawValue = {
    // find the maximum enum value
    var maxValue: Int = 0
    while let _ = PerformerPosition(rawValue: maxValue) {
        maxValue += 1
    }
    return maxValue
}()

static func randomPerformer() -> PerformerPosition {
    // pick and return a new value
    let rand = arc4random_uniform(UInt32(count))
    return PlayerPosition(rawValue: Int(rand))!
}
</code>```

How could I make it so I am able to pick a random value based on the String_ prefix only without having to resort to hard-coding an upper value (for example, new String_ prefix positions may be added)? Thanks

答:
So you don't want to change any of the code even if a new position is added. Right?

To do that, you need to get all the enum cases dynamically, instead of hardcoding them. According to this answer, you can use this method to get all the cases:

```<code>protocol EnumCollection : Hashable {}
extension EnumCollection {
    static func cases() -> AnySequence<Self> {
        typealias S = Self
        return AnySequence { () -> AnyIterator<S> in
            var raw = 0
            return AnyIterator {
                let current : Self = withUnsafePointer(to: &raw) { $0.withMemoryRebound(to: S.self, capacity: 1) { $0.pointee } }
                guard current.hashValue == raw else { return nil }
                raw += 1
                return current
            }
        }
    }
}
</code>```

After you got this cases method, you can easily get what you want by:

```<code>let startingWithString = Array(PerformerPosition.cases().filter { "\($0)".hasPrefix("String_") })
let rand = arc4random_uniform(UInt32(startingWithString.count))
let randomPosition = startingWithString[Int(rand)]
</code>```

Body:
Given a Swift enum as such:

enum PerformerPosition: Int {

    case String_Violin1
    case String_Violin2
    case String_Viola
    case String_Cello
    case String_CB

    case Wind_Oboe
    case Wind_Clarinet
    case Wind_Flute
    ...

}

(For the needs of the project, I am not able to have a nested enum.) I would like to randomly select an enum value with the String_ prefix, only.

The only way I know so far is to do a random enum value from all the available cases, as such:

private static let _count: PerformerPosition.RawValue = {
    // find the maximum enum value
    var maxValue: Int = 0
    while let _ = PerformerPosition(rawValue: maxValue) {
        maxValue += 1
    }
    return maxValue
}()

static func randomPerformer() -> PerformerPosition {
    // pick and return a new value
    let rand = arc4random_uniform(UInt32(count))
    return PlayerPosition(rawValue: Int(rand))!
}

How could I make it so I am able to pick a random value based on the String_ prefix only without having to resort to hard-coding an upper value (for example, new String_ prefix positions may be added)? Thanks

Body:
So you don't want to change any of the code even if a new position is added. Right?

To do that, you need to get all the enum cases dynamically, instead of hardcoding them. According to this answer, you can use this method to get all the cases:

protocol EnumCollection : Hashable {}
extension EnumCollection {
    static func cases() -> AnySequence<Self> {
        typealias S = Self
        return AnySequence { () -> AnyIterator<S> in
            var raw = 0
            return AnyIterator {
                let current : Self = withUnsafePointer(to: &raw) { $0.withMemoryRebound(to: S.self, capacity: 1) { $0.pointee } }
                guard current.hashValue == raw else { return nil }
                raw += 1
                return current
            }
        }
    }
}

After you got this cases method, you can easily get what you want by:

let startingWithString = Array(PerformerPosition.cases().filter { "\($0)".hasPrefix("String_") })
let rand = arc4random_uniform(UInt32(startingWithString.count))
let randomPosition = startingWithString[Int(rand)]


问:
ExcelNewbie: Matching cell information across worksheets
Please forgive me if this is simple...I am not an Excel expert and this is causing my nose to bleed(!)

Firstly I am using Excel 365.

I am working on a Bonus Calculator Sheet and the system is VERY complex, but I have reduced it to a two column table.

Column A is the company success "number" and column B is the % bonus it draws. This is all on worksheet B.
Worksheet A contains salary stuff and the company success number sits at the top and is not changed. What I need to do in pseudocode is:

Take value from Sheet A Cell A1
Find match in Sheet B Column A.
Return value next to it in Column B to Sheet A somewhere.

My life is mainly spent in the world of Python and this looks SO simple - but any help you experts could offer would just make my day rosier...if anyone can help I will give my two dogs a biscuit to show the love(!)

Thanks.

答:
Seems pretty simple.</p>

```<code>=VLOOKUP(A2,SheetB!A:B,2,FALSE)
</code>```

Body:
Seems pretty simple.

=VLOOKUP(A2,SheetB!A:B,2,FALSE)


问:
Keras-ImportError: cannot import name ctc_ops
I have Anaconda 4.3.1 installed in my laptop after the commands cd /home/username/anaconda3and source bin/activate ~/anaconda3 my package starts .
And I installed keras using pip3 conda install keras inside my anaconda. package.and made a document named keras.json inside my keras folder.
When I start my Python in anaconda3 and import keras this happens

```<code>>>> import keras'
Using TensorFlow backend.

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/tushar/.local/lib/python3.5/site-packages/keras/__init__.py", line 3, in <module>
    from . import activations
  File "/home/tushar/.local/lib/python3.5/site-packages/keras/activations.py", line 3, in <module>
    from . import backend as K
  File "/home/tushar/.local/lib/python3.5/site-packages/keras/backend/__init__.py", line 64, in <module>
    from .tensorflow_backend import *
  File "/home/tushar/.local/lib/python3.5/site-packages/keras/backend/tensorflow_backend.py", line 6, in <module>
    from tensorflow.python.ops import ctc_ops as ctc
ImportError: cannot import name 'ctc_ops'
</code>```

After following this I could not get any solution. I would appreciate any help.

答:
I had this same exact issue (I was using pip instead of conda to install keras / tensorflow, however). Make sure you have the most up-to-date version of tensorflow (tensorflow-1.0.1 as of March 31st, 2017).

```<code>sudo pip install tensorflow --upgrade
</code>```

fixed the problem for me (I was running tensorflow-0.9.0rc0 before and was getting the same ImportError: cannot import name ctc_ops error as you)

Body:
I have Anaconda 4.3.1 installed in my laptop after the commands cd /home/username/anaconda3and source bin/activate ~/anaconda3 my package starts .
And I installed keras using pip3 conda install keras inside my anaconda. package.and made a document named keras.json inside my keras folder.
When I start my Python in anaconda3 and import keras this happens

>>> import keras'
Using TensorFlow backend.

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/tushar/.local/lib/python3.5/site-packages/keras/__init__.py", line 3, in <module>
    from . import activations
  File "/home/tushar/.local/lib/python3.5/site-packages/keras/activations.py", line 3, in <module>
    from . import backend as K
  File "/home/tushar/.local/lib/python3.5/site-packages/keras/backend/__init__.py", line 64, in <module>
    from .tensorflow_backend import *
  File "/home/tushar/.local/lib/python3.5/site-packages/keras/backend/tensorflow_backend.py", line 6, in <module>
    from tensorflow.python.ops import ctc_ops as ctc
ImportError: cannot import name 'ctc_ops'

After following this I could not get any solution. I would appreciate any help.

Body:
I had this same exact issue (I was using pip instead of conda to install keras / tensorflow, however). Make sure you have the most up-to-date version of tensorflow (tensorflow-1.0.1 as of March 31st, 2017).

sudo pip install tensorflow --upgrade

fixed the problem for me (I was running tensorflow-0.9.0rc0 before and was getting the same ImportError: cannot import name ctc_ops error as you)


问:
Mongoose Schema for User profile, that has one to many properties
I used to use MySQL and now new to Mongodb. In phase of learning, I am trying to create a User Profile like LinkedIn. I am confused to choose the proper way of creating one-to-many relationship in mongodb schemas.

Context: A user can have multiple education qualification and same with experience. Here are two ways, that i tried to create the schema as:

Example 1:

```<code>var userSchema = new mongoose.Schema({
  name: {
    first: String,
    middle: String,
    last: String,
  },
  gender: { type: Number, max: 3, min: 0, default: GENDERS.Unspecified },
  age: Number,
  education: [{type: Schema.Types.ObjectId, ref:'Education'}],
  experience: [{type: Schema.Types.ObjectId, ref:'Experience'}],
  email: String
});
</code>```

Example 2:

```<code>var userSchema = new mongoose.Schema({
  name: {
    first: String,
    middle: String,
    last: String,
  },
  gender: { type: Number, max: 3, min: 0, default: GENDERS.Unspecified },
  age: Number,
  education: [{type: String, detail: {
    major: String,
    degree: String,
    grade: String,
    startdate: Date,
    enddate: Date,
    remarks: String
  }}],
  experience: [{type: String, detail: {
    position: String,
    company: String,
    dateofjoin: String,
    dateofretire: String,
    location: String,
    responsibilities: [{type:String}],
    description: String,
  }}],
  email: String
});
</code>```

I haven't tested the second option.

Which one is better and easier during writing querying to fetch or add data? Is there a better way to write schema for scenarios like that?

答:
For this particular example I would suggest embedding the documents vs storing as reference, and here is why.

Usually my first step in mongodb schema design is to consider how I will be querying the data?

Will I want to know the educational background of a user, or will I want to know all users who have a particular educational background?  Having answers to these types of questions will determine how you want to setup your database.

If you already know your user, having the embedded educational background within that document is quick and easy to access.  No separate queries are needed, and the schema still isn't overly complex and difficult to comprehend.  This is how I would expect you would want to access the data.

Now, if you want to find all users with a particular educational background, there are obviously large drawbacks to the embedded document schema.  In that case you would need to first look at each user, then loop through the education array to see all the various educations.

So the answer will be dependent on the expected queries you will be making to the data, but in this case (unless you are doing reporting on all users) then embedded is probably the way to go.

You may also find this discussion helpful:

MongoDB relationships: embed or reference?

Body:
I used to use MySQL and now new to Mongodb. In phase of learning, I am trying to create a User Profile like LinkedIn. I am confused to choose the proper way of creating one-to-many relationship in mongodb schemas.

Context: A user can have multiple education qualification and same with experience. Here are two ways, that i tried to create the schema as:

Example 1:

var userSchema = new mongoose.Schema({
  name: {
    first: String,
    middle: String,
    last: String,
  },
  gender: { type: Number, max: 3, min: 0, default: GENDERS.Unspecified },
  age: Number,
  education: [{type: Schema.Types.ObjectId, ref:'Education'}],
  experience: [{type: Schema.Types.ObjectId, ref:'Experience'}],
  email: String
});

Example 2:

var userSchema = new mongoose.Schema({
  name: {
    first: String,
    middle: String,
    last: String,
  },
  gender: { type: Number, max: 3, min: 0, default: GENDERS.Unspecified },
  age: Number,
  education: [{type: String, detail: {
    major: String,
    degree: String,
    grade: String,
    startdate: Date,
    enddate: Date,
    remarks: String
  }}],
  experience: [{type: String, detail: {
    position: String,
    company: String,
    dateofjoin: String,
    dateofretire: String,
    location: String,
    responsibilities: [{type:String}],
    description: String,
  }}],
  email: String
});

I haven't tested the second option.

Which one is better and easier during writing querying to fetch or add data? Is there a better way to write schema for scenarios like that?


问:
Add right-click context menu only in desktop
I know how to implement a context menu over a file or folder

Integrating into Windows Explorer context menu

How add context menu item to Windows Explorer for folders

but I want to know how to put a command in the context menu in the desktop right-click without right-clicking on a file or folder

答:
Have a look at https://msdn.microsoft.com/en-us/library/windows/desktop/cc144110.aspx

I think the registry path for the desktop background is HKEY_CLASSES_ROOT/DesktopBackground, but looking through my registry I can see some of the handlers I see on my dekstop under /Directory/Background as well.


问:
MYSQL delete all records except first and last for a given date
This gives me all the records for a particular switch and port. I would like to delete all except the first and last one for each day.</p>

```<code>/mysql -sN --user=root --password=notmypassword -e
"SELECT * FROM collector.fibre
WHERE fabric_switch_name = 'switch-1'
  AND port = '0'
  AND datatype = 'TxElements'
  AND (time > '2016-05-31 00:00:00' AND time < '2016-05-31 23:59:59') "
</code>```

答:
I don't know how much time will it take to delete all this records but i think
minutes of works just wait for it :</p>

```<code>delete fb from collector.fibre fb
INNER JOIN
(
SELECT
  distinct
  f.id -- extract only the ids
FROM
  collector.fibre  f
  INNER JOIN (
    -- create a special table   day   min_time  max_time
    select
      date(time) as 'day',
      min(time) as 'min_time',
      max(time) as 'max_time'
    from
      collector.fibre
     Where
        -- must be the same set of records
        -- because we look for a dates of this switch
       fabric_switch_name = 'switch-1'
       AND port = '0'
       AND datatype = 'TxElements'
    group by date(time)
  )  fd on date(f.time) = fd.day  -- join the two table to have a special table see example down
WHERE
  fabric_switch_name = 'switch-1'
  AND port = '0'
  AND datatype = 'TxElements'
  -- extract record witch the time is not
  -- the min or the max of that date
  AND (f.time <> fd.min_time and f.time <> fd.max_time)
) recs on fb.id = recs.id -- join the table and the result of query by the id now you will remove the records that exist in the result of the query
</code>```

Body:
This gives me all the records for a particular switch and port. I would like to delete all except the first and last one for each day.

/mysql -sN --user=root --password=notmypassword -e
"SELECT * FROM collector.fibre
WHERE fabric_switch_name = 'switch-1'
  AND port = '0'
  AND datatype = 'TxElements'
  AND (time > '2016-05-31 00:00:00' AND time < '2016-05-31 23:59:59') "

Body:
I don't know how much time will it take to delete all this records but i think
minutes of works just wait for it :

delete fb from collector.fibre fb
INNER JOIN
(
SELECT
  distinct
  f.id -- extract only the ids
FROM
  collector.fibre  f
  INNER JOIN (
    -- create a special table   day   min_time  max_time
    select
      date(time) as 'day',
      min(time) as 'min_time',
      max(time) as 'max_time'
    from
      collector.fibre
     Where
        -- must be the same set of records
        -- because we look for a dates of this switch
       fabric_switch_name = 'switch-1'
       AND port = '0'
       AND datatype = 'TxElements'
    group by date(time)
  )  fd on date(f.time) = fd.day  -- join the two table to have a special table see example down
WHERE
  fabric_switch_name = 'switch-1'
  AND port = '0'
  AND datatype = 'TxElements'
  -- extract record witch the time is not
  -- the min or the max of that date
  AND (f.time <> fd.min_time and f.time <> fd.max_time)
) recs on fb.id = recs.id -- join the table and the result of query by the id now you will remove the records that exist in the result of the query


问:
unsure why state is changing
I have a button in a child component for debugging purposes that prints the current state in its parent component. When it prints, that is how I want the state to be. When I hit another button in the same child component, the state changes in the parent, by removing a few properties.

Notice how the Id and SEO_CSEO_Survey_Questions__r properties are now missing.

Child Component

```<code>import React, { Component } from 'react';
import { Link } from 'react-router';

class Index extends Component {

  constructor(props){
    super(props)

    this.state = {
      selected: 'created'
    }

    this.updatePreview = this.updatePreview.bind(this);
    this.renderEditArea = this.renderEditArea.bind(this);
  }

  isActive(value) {
      return 'slds-tabs--default__item '+((value===this.state.selected) ?'slds-active':'');
  }

  updatePreview(e){
    const updatedPreview = {
      ...this.props.selectedPreview,
      [e.target.name]: e.target.value
    };
    this.props.update(updatedPreview)
  }

  // determines which type of edit area should display
  // survey settings or question
  renderEditArea() {
    let selected = this.props.selectedPreview;
    let hasNameKey = "Name" in selected;
    if(hasNameKey){
      return (
        <div>
          <input
            onChange={(e) => this.updatePreview(e)}
            name="Name"
            type="text"
            className="slds-input"
            value={selected.Name ? selected.Name : ''}
          />
          <input
            onChange={(e) => this.updatePreview(e)}
            name="SEO__Welcome_Text__c"
            type="text"
            className="slds-input"
            value={selected.SEO__Welcome_Text__c ? selected.SEO__Welcome_Text__c : ''}
          />
        </div>
      )
    }else {
      return (
        <input
          onChange={(e) => this.updatePreview(e)}
          name="SEO__Question__c"
          type="text"
          className="slds-input"
          value={selected.SEO__Question__c ? selected.SEO__Question__c : ''}
        />
      )
    }
  }

  render() {
    return (
      <div className="slds-size--1-of-1 slds-medium-size--4-of-5 slds-large-size--4-of-5">
        <div className="slds-tabs--default">
          <h2 className="slds-text-heading--small slds-p-top--x-small" style={{position: "absolute"}}>
            <button onClick={this.props.addQuestion} className="slds-button slds-button--icon slds-p-left--xx-small" title="add sur">
              <svg className="slds-button__icon slds-button__icon--medium" aria-hidden="true">
                <use xlinkHref={addIcon}></use>
              </svg>
              <span className="slds-assistive-text">Add Question</span>
            </button>
          </h2>
          <ul className="slds-tabs--default__nav" style={{justifyContent: "flex-end"}}>
            <Link to="/"className="slds-button slds-button--neutral">Back</Link>
            <button onClick={this.props.save} className="slds-button slds-button--brand">Save</button>
            <button onClick={this.props.currentState} className="slds-button slds-button--brand">Current State</button>
          </ul>
        </div>
        <div className="slds-grid slds-wrap slds-grid--pull-padded">
          {this.renderEditArea()}
        </div>
      </div>
    );
  }
}

export default Index;
</code>```

Parent

```<code>import React, { Component } from 'react';
import { getQuestions, addQuestion, deleteQuestion, newSurveyQuestions, updateSurveyQuestions, EMPTY_SURVEY } from './helpers';

import SideBar from './survey/SideBar';
import MainArea from './survey/Index';

class Survey extends Component {

  constructor(props) {
    super(props)

    this.state = {
      survey: [],
      selectedPreview: []
    }

    this.componentWillMount = this.componentWillMount.bind(this);
    this.save = this.save.bind(this);
    this.setSelectedPreview = this.setSelectedPreview.bind(this);
    this.currentState = this.currentState.bind(this);
  }

  // if the url is `/survey/new`, create an empty survey
  // to save for later.
  // else if there is an id in the url, load the survey and questions
  componentWillMount(){
    if(this.props.pathname === "/survey/new") {
      this.setState({
        survey: EMPTY_SURVEY,
        selectedPreview: EMPTY_SURVEY[0]
      })
    } else if (this.props.params.surveyId){
      getQuestions(this.props.params.surveyId).then(survey => {
        // 'survey' contains all the questions
        this.setState({
          survey,
          selectedPreview: survey[0]
        });
      });
    }
  }

  currentState() {
    console.log('clicking Current State');
    console.log(this.state.survey[0]);
  }

  // saves a new survey with associated newly created questions
  // or saves an existing survey with associated questions
  save() {
    console.log('clicking Save');
    console.log(this.state.survey[0]);
    // if the url is set to survey/new
    // save new survey with associated newly created questions
    if(this.props.pathname === "/survey/new") {
      newSurveyQuestions(this.state.survey).then( id => {
        this.context.router.transitionTo(`/survey/id/${id}`);
      })

    // else update survey and questions
    } else {
      updateSurveyQuestions(this.state.survey);
    }
  }

  // sets selectedPreview for the entire component and
  // its children
  setSelectedPreview(selectedPreview) {
    this.setState({selectedPreview});
  }

  render() {
    return (
      <div className="slds-grid slds-wrap slds-grid--pull-padded">
        <SideBar
          survey={this.state.survey}
          setSelectedPreview={this.setSelectedPreview}
          deleteQuestion={this.deleteQuestion}

        />
        <MainArea
          addQuestion={this.addQuestion}
          selectedPreview={this.state.selectedPreview}
          update={this.update}
          save={this.save}
          currentState={this.currentState}
        />
      </div>
    );
  }
}

Survey.contextTypes = {
  router: React.PropTypes.object
}

export default Survey;
</code>```

help function

```<code>export function updateSurveyQuestions(survey) {
  // create proper url for update request
  const requestURL = `${URL + survey[0].attributes.url}`;

  // save questions for later update requests
  const questions = survey[0].SEO__CSEO_Survey_Questions__r.records;

  let s = [...survey];

  // remove properties for proper body format
  delete s[0].Id;
  delete s[0].SEO__CSEO_Survey_Questions__r;
  delete s[0].attributes;

  axios.patch(requestURL, s[0], API_TOKEN);

  questions.forEach( question => {
    // save request url for later
    let requestURL = `${URL + question.attributes.url }`;

    // remove properites for proper body format
    delete question.attributes;
    delete question.Id;

    axios.patch(requestURL, question, API_TOKEN);
  })
}
</code>```

When I removed all the code in save(), except for the console.log's, it prints as expected.

答:
tl;dr: Your code is working fine. What you are seeing is a consequence of how objects and the console work. Do

```<code>console.log(this.state.survey[0].Id);
</code>```

instead to see that the property does actually exist.

See also Is Chrome's JavaScript console lazy about evaluating arrays?

When I removed all the code in save(), except for the console.log's, it prints as expected.

That seems to suggest that that code is changing the object. E.g. updateSurveyQuestions or newSurveyQuestions might remove these properties.

You have to keep in mind that the output you see in the console is computed at the moment you expand the properties, not at the moment console.log is called. In fact, the little i icon next to Object tells you that. When you hover over it says:

Value below was evaluated just now

Here is a simplified example of what you are experiencing: Expand the object and notice that it is empty even though we removed it after calling console.dir (open your browser's console):

var obj = {foo: 42};
console.dir(obj);
delete obj.foo;```
</div>
</div>
</p>

<hr>

<p>Ideally <code>updateSurveyQuestions</code> or <code>newSurveyQuestions</code> would not mutate the object directly, but rather clone it, make the necessary changes to the clone and then update the components state (if desired). E.g. a simple way to clone the object is via <code>Object.assign</code>:</p>

```var copy = Object.assign({}, this.state.survey[0]);
```

Title: unsure why state is changing

Body:
I have a button in a child component for debugging purposes that prints the current state in its parent component. When it prints, that is how I want the state to be. When I hit another button in the same child component, the state changes in the parent, by removing a few properties.

Notice how the Id and SEO_CSEO_Survey_Questions__r properties are now missing.

Child Component

import React, { Component } from 'react';
import { Link } from 'react-router';

class Index extends Component {

  constructor(props){
    super(props)

    this.state = {
      selected: 'created'
    }

    this.updatePreview = this.updatePreview.bind(this);
    this.renderEditArea = this.renderEditArea.bind(this);
  }

  isActive(value) {
      return 'slds-tabs--default__item '+((value===this.state.selected) ?'slds-active':'');
  }

  updatePreview(e){
    const updatedPreview = {
      ...this.props.selectedPreview,
      [e.target.name]: e.target.value
    };
    this.props.update(updatedPreview)
  }

  // determines which type of edit area should display
  // survey settings or question
  renderEditArea() {
    let selected = this.props.selectedPreview;
    let hasNameKey = "Name" in selected;
    if(hasNameKey){
      return (

          <input
            onChange={(e) => this.updatePreview(e)}
            name="Name"
            type="text"
            className="slds-input"
            value={selected.Name ? selected.Name : ''}
          />
          <input
            onChange={(e) => this.updatePreview(e)}
            name="SEO__Welcome_Text__c"
            type="text"
            className="slds-input"
            value={selected.SEO__Welcome_Text__c ? selected.SEO__Welcome_Text__c : ''}
          />

      )
    }else {
      return (
        <input
          onChange={(e) => this.updatePreview(e)}
          name="SEO__Question__c"
          type="text"
          className="slds-input"
          value={selected.SEO__Question__c ? selected.SEO__Question__c : ''}
        />
      )
    }
  }

  render() {
    return (

            <button onClick={this.props.addQuestion} className="slds-button slds-button--icon slds-p-left--xx-small" title="add sur">
              <svg className="slds-button__icon slds-button__icon--medium" aria-hidden="true">
                <use xlinkHref={addIcon}></use>
              </svg>
              Add Question
            </button>

            <Link to="/"className="slds-button slds-button--neutral">Back</Link>
            <button onClick={this.props.save} className="slds-button slds-button--brand">Save</button>
            <button onClick={this.props.currentState} className="slds-button slds-button--brand">Current State</button>

          {this.renderEditArea()}

    );
  }
}

export default Index;

Parent

import React, { Component } from 'react';
import { getQuestions, addQuestion, deleteQuestion, newSurveyQuestions, updateSurveyQuestions, EMPTY_SURVEY } from './helpers';

import SideBar from './survey/SideBar';
import MainArea from './survey/Index';

class Survey extends Component {

  constructor(props) {
    super(props)

    this.state = {
      survey: [],
      selectedPreview: []
    }

    this.componentWillMount = this.componentWillMount.bind(this);
    this.save = this.save.bind(this);
    this.setSelectedPreview = this.setSelectedPreview.bind(this);
    this.currentState = this.currentState.bind(this);
  }

  // if the url is `/survey/new`, create an empty survey
  // to save for later.
  // else if there is an id in the url, load the survey and questions
  componentWillMount(){
    if(this.props.pathname === "/survey/new") {
      this.setState({
        survey: EMPTY_SURVEY,
        selectedPreview: EMPTY_SURVEY[0]
      })
    } else if (this.props.params.surveyId){
      getQuestions(this.props.params.surveyId).then(survey => {
        // 'survey' contains all the questions
        this.setState({
          survey,
          selectedPreview: survey[0]
        });
      });
    }
  }

  currentState() {
    console.log('clicking Current State');
    console.log(this.state.survey[0]);
  }

  // saves a new survey with associated newly created questions
  // or saves an existing survey with associated questions
  save() {
    console.log('clicking Save');
    console.log(this.state.survey[0]);
    // if the url is set to survey/new
    // save new survey with associated newly created questions
    if(this.props.pathname === "/survey/new") {
      newSurveyQuestions(this.state.survey).then( id => {
        this.context.router.transitionTo(`/survey/id/${id}`);
      })

    // else update survey and questions
    } else {
      updateSurveyQuestions(this.state.survey);
    }
  }

  // sets selectedPreview for the entire component and
  // its children
  setSelectedPreview(selectedPreview) {
    this.setState({selectedPreview});
  }

  render() {
    return (

        <SideBar
          survey={this.state.survey}
          setSelectedPreview={this.setSelectedPreview}
          deleteQuestion={this.deleteQuestion}

        />
        <MainArea
          addQuestion={this.addQuestion}
          selectedPreview={this.state.selectedPreview}
          update={this.update}
          save={this.save}
          currentState={this.currentState}
        />

    );
  }
}

Survey.contextTypes = {
  router: React.PropTypes.object
}

export default Survey;

help function

export function updateSurveyQuestions(survey) {
  // create proper url for update request
  const requestURL = `${URL + survey[0].attributes.url}`;

  // save questions for later update requests
  const questions = survey[0].SEO__CSEO_Survey_Questions__r.records;

  let s = [...survey];

  // remove properties for proper body format
  delete s[0].Id;
  delete s[0].SEO__CSEO_Survey_Questions__r;
  delete s[0].attributes;

  axios.patch(requestURL, s[0], API_TOKEN);

  questions.forEach( question => {
    // save request url for later
    let requestURL = `${URL + question.attributes.url }`;

    // remove properites for proper body format
    delete question.attributes;
    delete question.Id;

    axios.patch(requestURL, question, API_TOKEN);
  })
}

When I removed all the code in save(), except for the console.log's, it prints as expected.

Body:
tl;dr: Your code is working fine. What you are seeing is a consequence of how objects and the console work. Do

console.log(this.state.survey[0].Id);

instead to see that the property does actually exist.

See also Is Chrome's JavaScript console lazy about evaluating arrays?

When I removed all the code in save(), except for the console.log's, it prints as expected.

That seems to suggest that that code is changing the object. E.g. updateSurveyQuestions or newSurveyQuestions might remove these properties.

You have to keep in mind that the output you see in the console is computed at the moment you expand the properties, not at the moment console.log is called. In fact, the little i icon next to Object tells you that. When you hover over it says:

Value below was evaluated just now

Here is a simplified example of what you are experiencing: Expand the object and notice that it is empty even though we removed it after calling console.dir (open your browser's console):

var obj = {foo: 42};
console.dir(obj);
delete obj.foo;

Ideally updateSurveyQuestions or newSurveyQuestions would not mutate the object directly, but rather clone it, make the necessary changes to the clone and then update the components state (if desired). E.g. a simple way to clone the object is via Object.assign:

var copy = Object.assign({}, this.state.survey[0]);


问:
For loop for finding index in string
I'm wondering why my function does not call the index of the character in the string. I used a for loop for this, and for some reason it's just listing all of the possible indices of the string. I made a specific if statement, but I don't get why it's not following the instructions.</p>

```<code>def where_is(char,string):
  c=0
  for char in string:
    if char==(string[c]):
      print (c)
      c+=1
    else:
      print ("")
where_is('p','apple')
</code>```

答:
The problem is that the given code iterated over everything stored in the string and as it matched everytime the value of 'c' increased and got printed.
I think your code should be:

```<code>def where_is(char, string):
    for i in range(len(string)):
        if char == (string[i]):
            print(i)

where_is('p', 'apple')
</code>```

This prints the index of all the 'p's in 'apple'.

Title: For loop for finding index in string

Body:
I'm wondering why my function does not call the index of the character in the string. I used a for loop for this, and for some reason it's just listing all of the possible indices of the string. I made a specific if statement, but I don't get why it's not following the instructions.

def where_is(char,string):
  c=0
  for char in string:
    if char==(string[c]):
      print (c)
      c+=1
    else:
      print ("")
where_is('p','apple')

Body:
The problem is that the given code iterated over everything stored in the string and as it matched everytime the value of 'c' increased and got printed.
I think your code should be:

def where_is(char, string):
    for i in range(len(string)):
        if char == (string[i]):
            print(i)

where_is('p', 'apple')

This prints the index of all the 'p's in 'apple'.


问:
@ViewChildren(TemplateRef) is undefined for <template> elements
How can I get a collection of all templates (TemplateRef) inside a component? It works fine with ViewChild but ViewChildren is undefined...

I use a solution from this question. Plunker with the full example.

```<code>  @Component({
    selector: 'my-app',
    template: `
            <div>
              <template #model>...</template>
              <template #color>...</template>
            </div>`
  })
  export class App {
  @ViewChild('model') model;
  @ViewChild('color') color;
  @ViewChildren(TemplateRef) templates: QueryList<TemplateRef>;

  ngAfterContentInit() {
    console.log(this.templates); // undefined
    console.log(this.model); // TemplateRef_ {...}
  }
}
</code>```

I need templates for a grid component where it's possible to define templates for columns. Unfortunately ng-content doesn't support dynamic projection, so I'm trying to achieve it with templates.

答:
If you move console.log('child', this.templates); to ngAfterViewInit() then it works.

```<code>ngAfterViewInit() {
  console.log('child', this.templates);
}
</code>```

I had expected it to work in ngAfterContentInit() as well. It seems in this Angular version ngAfterContentInit() runs before ngAfterViewInit(). I was sure this was the other way around earlier.

Plunker example

Body:
How can I get a collection of all templates (TemplateRef) inside a component? It works fine with ViewChild but ViewChildren is undefined...

I use a solution from this question. Plunker with the full example.

  @Component({
    selector: 'my-app',
    template: `

              <template #model>...</template>
              <template #color>...</template>

`
  })
  export class App {
  @ViewChild('model') model;
  @ViewChild('color') color;
  @ViewChildren(TemplateRef) templates: QueryList<TemplateRef>;

  ngAfterContentInit() {
    console.log(this.templates); // undefined
    console.log(this.model); // TemplateRef_ {...}
  }
}

I need templates for a grid component where it's possible to define templates for columns. Unfortunately ng-content doesn't support dynamic projection, so I'm trying to achieve it with templates.

Body:
If you move console.log('child', this.templates); to ngAfterViewInit() then it works.

ngAfterViewInit() {
  console.log('child', this.templates);
}

I had expected it to work in ngAfterContentInit() as well. It seems in this Angular version ngAfterContentInit() runs before ngAfterViewInit(). I was sure this was the other way around earlier.

Plunker example


答:
Firstly, the index you used is not being increased in the else part and secondly, I generally prefer a while loop to a for loop when it comes to iterating through strings. Making slight modifications to your code, have a look at this :

```<code>def where_is(char,string):
  i=0
  while i<len(string):
    if char==(string[i]):
      print (i)
    else:
      print ("")
    i+=1
where_is('p','apple')
</code>```

Input : where_is('p','apple')

Output: 1 2

Check it out here

Title: For loop for finding index in string

Body:
Firstly, the index you used is not being increased in the else part and secondly, I generally prefer a while loop to a for loop when it comes to iterating through strings. Making slight modifications to your code, have a look at this :

def where_is(char,string):
  i=0
  while i<len(string):
    if char==(string[i]):
      print (i)
    else:
      print ("")
    i+=1
where_is('p','apple')

Input : where_is('p','apple')

Output: 1 2

Check it out here


问:
How can I get videos based on user genre?
As you can see in my definition below. User can have one or many videos. A user can have one genre.

How can I list videos based on a specific genre?

```<code>class User
  include Mongoid::Document
  include Mongoid::Timestamps

  references_many :videos
  referenced_in :genre

  ....
end

class Video
  include Mongoid::Document
  include Mongoid::Timestamps

  referenced_in :user
  ....
end

class Genre
  include Mongoid::Document

  references_one :user
  ....
end
</code>```

答:
You need to do several requests.</p>

```<code>list_your_want = Genre.all.inject({}) do |result, genre|
  result[genre.name] = genre.user.videos
  result
end
</code>```

Body:
As you can see in my definition below. User can have one or many videos. A user can have one genre.

How can I list videos based on a specific genre?

class User
  include Mongoid::Document
  include Mongoid::Timestamps

  references_many :videos
  referenced_in :genre

  ....
end

class Video
  include Mongoid::Document
  include Mongoid::Timestamps

  referenced_in :user
  ....
end

class Genre
  include Mongoid::Document

  references_one :user
  ....
end

Body:
You need to do several requests.

list_your_want = Genre.all.inject({}) do |result, genre|
  result[genre.name] = genre.user.videos
  result
end


问:
Copy command - deep or shallow copy?
When I am copying the object with copy command in iOS (swift / objective c), Will that be a shallow copy or a deep copy ?

```<code>var str = "Hello, playground"
var copyStr = str.copy()
</code>```

and

```<code>var originalArray = [1, 2, 3, 4] as NSArray
var copyArray = originalArray.copy()

withUnsafePointer(to: &originalArray) {
    print(" originall address: \($0)")
}

withUnsafePointer(to: &copyArray) {
    print(" copy address: \($0)")
}
</code>```

Help me with the lines above , is this a deep copy or a shallow copy ?

The issue is , this behaviour in objective c is showing me the same
  address with both string and array which is shallow copy and in swift3
  it is showing me different address which is deep copy

答:
String in Swift are Value Types. For all Value Types, a new copy of the existing String value is created.

From Apple Document.

Swift’s copy-by-default String behavior ensures that when a function
  or method passes you a String value, it is clear that you own that
  exact String value, regardless of where it came from. You can be
  confident that the string you are passed will not be modified unless
  you modify it yourself.

Hope this helps

Title: Copy command - deep or shallow copy?

Body:
When I am copying the object with copy command in iOS (swift / objective c), Will that be a shallow copy or a deep copy ?

var str = "Hello, playground"
var copyStr = str.copy()

and

var originalArray = [1, 2, 3, 4] as NSArray
var copyArray = originalArray.copy()

withUnsafePointer(to: &originalArray) {
    print(" originall address: \($0)")
}

withUnsafePointer(to: &copyArray) {
    print(" copy address: \($0)")
}

Help me with the lines above , is this a deep copy or a shallow copy ?

The issue is , this behaviour in objective c is showing me the same
  address with both string and array which is shallow copy and in swift3
  it is showing me different address which is deep copy


问:
How to remove or customize the pagination button in Bootstrap carousel
I'd like to remove the default button (or white dot) in Bootstrap carousel.
Is it possible to customize them?

答:
Just remove indicators part from carousel declaration:

```

Body:
Just remove indicators part from carousel declaration:

<!-- Indicators -->
<ol class="carousel-indicators">
  <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
  <li data-target="#myCarousel" data-slide-to="1"></li>
  <li data-target="#myCarousel" data-slide-to="2"></li>
  <li data-target="#myCarousel" data-slide-to="3"></li>
</ol>


问:
Get number before a specified string
Given the string

```<code>RAM Statistics: 5954 / 8174 743=InUse 746=Peak
</code>```

I need a RegEx (or three) to extract the 743, the 746, and ideally the 5954 / 8174 so each can be assigned to a specific variable.

I THINK this is what LookBehind is used for, but I am having a hell of a time actually getting a RegEx to "Get the numbers between a Space and =Peak", for example.

I have tried

```<code>$string = 'RAM Statistics:     5954 /     8174       743=InUse      746=Peak'
$regexPeak = '(?<= )(.#)(?=\=Peak)'
$string -match $regexPeak > $null
$peak = $matches[0]
Write-Host "$peak"
</code>```

But that's returning nothing.

UPDATE:
Per Joshua I have tried

```<code>$string = 'RAM Statistics:     5954 /     8174       743=InUse      746=Peak'
$regexPeak = '(\d+) / (\d+) (\d+)=\D+(\d+)=peak/gi'
$string -match $regexPeak
$peak = $matches[0]
Write-Host "$peak!"
</code>```

And both $matches[0] and [1] return everything before the =Peak. So

```<code>Statistics:     5954 /     8174       743=InUse      746!
</code>```

Title: Get number before a specified string

Body:
Given the string

RAM Statistics: 5954 / 8174 743=InUse 746=Peak

I need a RegEx (or three) to extract the 743, the 746, and ideally the 5954 / 8174 so each can be assigned to a specific variable.

I THINK this is what LookBehind is used for, but I am having a hell of a time actually getting a RegEx to "Get the numbers between a Space and =Peak", for example.

I have tried

$string = 'RAM Statistics:     5954 /     8174       743=InUse      746=Peak'
$regexPeak = '(?<= )(.#)(?=\=Peak)'
$string -match $regexPeak > $null
$peak = $matches[0]
Write-Host "$peak"

But that's returning nothing.

UPDATE:
Per Joshua I have tried

$string = 'RAM Statistics:     5954 /     8174       743=InUse      746=Peak'
$regexPeak = '(\d+) / (\d+) (\d+)=\D+(\d+)=peak/gi'
$string -match $regexPeak
$peak = $matches[0]
Write-Host "$peak!"

And both $matches[0] and [1] return everything before the =Peak. So

Statistics:     5954 /     8174       743=InUse      746!

Body:
Updated Regex:

/(\d+) \/ (\d+) (\d+)=\D+(\d+)=peak/gi


问:
UWP application not working in VS 2017
I am unable to open my UWP application in VS 2017. According to this site it should work.

The UpgradeLog.htm file says: The application which this project type is based on was not found.

Visual Studio shows the project as incompatible and states: This project is incompatible with the current edition of Visual Studio.

I do have UWP installed per the VS 2017 installation dialog. I am using the professional edition if this matters. This application only targets tablets and desktops.

答:
I created a new UWP project using VS 2017. I compared the csproj files to see what might be the difference. I noticed that the ProjectTypeGuids each contained two guids. The first guid was different between the two however the second was the same.

So, I changed the first guid: {BC8A1FFA-BEE3-4634-8014-F334798102B3} became {A5A43C5B-DE2A-4C0C-9213-0A381AF9435A}.

I still received errors including version string portion was too short or too long. For this I changed the MinimumVisualStudioVersion to 14, updated the Project ToolsVersion to 15, and added the TargetPlatformIdentifier with a value of UAP. All these changes were needed as it didn't work until I had done all of these.

After this I could load the project however I see errors loading runtime libraries. This is still an issue however the project loads now which was the original scope of my question. I'll work on the remaining errors separately.

Title: UWP application not working in VS 2017


问:
form.$valid is working for "required" but it's not working for ngPattern and maxlength.
If zipcode is empty then form is invalid so button is disabled but if zipcode is 2 digits error message is showing but form is showing as valid in controller. If zipcode is empty then I need to disable button but I'm checking form valid or not but dont worry about ng-disabled. I just need solution for showing the "div" if and only if form is valid.

 function submitUserDetail (formValid) {
      if(formValid) {
      $scope.showDiv = true;
      }
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>            <div class="">
                <div class="">
                    <label required>
                        Zip code required
                    </label>
                    <label pattern>
                        Invalid Zip code
                    </label>
                </div>
                <div class="">
                    <input type="tel" maxlength="5" class="" name="zip5"
                           ng-model="userDetail.zipCode" required=""
                           pattern="^\d{5}$"
                           data-validate-on-blur="true" value=""
                           size="5">
                    <span class="" title="Reset" onclick="jQuery(this).prev('input').val('').trigger('change');"></span>
                </div>
            </div>

        <div class="">
            <div class="">
                <div class="">
                    <span class=""></span>
                    <button class="" href="#" id="button" ng-click="submitUserDetail(form.$valid)" ng-disabled="form.$invalid">See section</button>
                    <span class=""></span>
                </div>
            </div>
        </div>

        <div ng-if="showDiv">
        .......
        </div></code>```

Thanks in advance.

答:
I assume that you have a <form> wrapping the HTML provided.

If so, you should make sure your <form> tag has novalidate applied so you're using AngularJS form validation and not HTML5 form validation:

```<code> <form name="form" ng-submit="submitUserDetail(form.$valid)" novalidate>
</code>```

Also, it looks like you're mixing HTML5 validation attributes with AngularJS validation attributes. You should be using ng-required and ng-pattern instead of required and pattern.

Body:
If zipcode is empty then form is invalid so button is disabled but if zipcode is 2 digits error message is showing but form is showing as valid in controller. If zipcode is empty then I need to disable button but I'm checking form valid or not but dont worry about ng-disabled. I just need solution for showing the "div" if and only if form is valid.

 function submitUserDetail (formValid) {
      if(formValid) {
      $scope.showDiv = true;
      }
    }

                        Zip code required

                        Invalid Zip code

                    <input type="tel" maxlength="5" class="" name="zip5"
                           ng-model="userDetail.zipCode" required=""
                           pattern="^\d{5}$"
                           data-validate-on-blur="true" value=""
                           size="5">

                    <button class="" href="#" id="button" ng-click="submitUserDetail(form.$valid)" ng-disabled="form.$invalid">See section</button>

        .......

Thanks in advance.

Body:
I assume that you have a <form> wrapping the HTML provided.

If so, you should make sure your <form> tag has novalidate applied so you're using AngularJS form validation and not HTML5 form validation:

 <form name="form" ng-submit="submitUserDetail(form.$valid)" novalidate>

Also, it looks like you're mixing HTML5 validation attributes with AngularJS validation attributes. You should be using ng-required and ng-pattern instead of required and pattern.


问:
Brute force password VBA
I'm trying to workout how one could cycle through all possibilities of a string but i doesn't seem to be going very well.

I have so far put a set of characters into an array but I cant for the life of me get my head around how I can make it work. I have got this far but my brain cannot seem to get round it.

Can any one shed any light of the proper way to do this and possibly pseudo code so I can create my own.

```<code>Function passwordGenerator(length As Integer)
    Dim characters() As String
    Dim x As Integer
    Dim y As Integer
    Dim p As Integer
    Dim t As Integer

    Dim oldpassword As String
    Dim newcharacter As String

    ReDim Preserve characters(1)

    For x = 48 To 90
        ReDim Preserve characters(UBound(characters) + 1)
        characters(UBound(characters) - 1) = VBA.Chr(x)
    Next x
    y = 1

        Do

            For x = 1 To length
            oldpassword = generateBlank(x)
            p = 1
                For t = 1 To p
                newpassword = WorksheetFunction.Replace(oldpassword, t, 1, characters(y))
                    For y = 1 To UBound(characters)
                        newpassword = WorksheetFunction.Replace(oldpassword, p, 1, characters(y))
                        Debug.Print newpassword
                        p = p + 1
                    Next y
                Next t
            Next x

        Loop

    End Function

Function generateBlank(length As Integer)

Dim x As Integer

For x = 1 To length
    generateBlank = generateBlank & "A"
Next x

End Function
</code>```

EDIT:::

I have edited my code but this way i have to know the length and that does not create an effective algorithm? Any help?

```<code>Function passwordGenerator()
Dim characters() As String
Dim x As Integer
Dim y As Integer
Dim p As Integer
Dim t As Integer
Dim w As Integer
Dim e As Integer
Dim r As Integer
Dim u As Integer

Dim oldpassword As String
Dim newcharacter As String

ReDim Preserve characters(1)

For x = 48 To 90
    ReDim Preserve characters(UBound(characters) + 1)
    characters(UBound(characters) - 1) = VBA.Chr(x)
Next x
y = 1

oldpassword = generateBlank(3)
        For x = 1 To UBound(characters)
            oldpassword = WorksheetFunction.Replace(oldpassword, 1, 1, characters(x))
            For t = 1 To UBound(characters)
                oldpassword = WorksheetFunction.Replace(oldpassword, 2, 1, characters(t))
                For y = 1 To UBound(characters)
                    oldpassword = WorksheetFunction.Replace(oldpassword, 3, 1, characters(y))
                    For q = 1 To UBound(characters)
                        oldpassword = WorksheetFunction.Replace(oldpassword, 4, 1, characters(q))
                        For w = 1 To UBound(characters)
                            oldpassword = WorksheetFunction.Replace(oldpassword, 5, 1, characters(w))
                            Debug.Print oldpassword
                            DoEvents
                        Next w
                    Next q
                Next y
            Next t
        Next x
End Function
</code>```

答:
I have edited the code in JA72's answer to provide a more comprehensive technique for brute forcing the "Restrict Editing" password.  I removed the array and ReDim portions, and combined it all into one sub.  The problem with JA's method is, while it works for the character set of ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 for 4-character passwords ([26+26+10]^4 = 14,776,336 possibilities), it does not work with a 5-character password ([26+26+10]^5 = 916,132,832 possibilities). The array functions in the original code cause a 32-bit Office application to immediately run out of memory when trying 5-character passwords or beyond.  I also noticed memory usage climbing as it iterated through 14 million possibilities with the original code, whereas memory usage stays flat with the code below.

This example specifically targets Word's ActiveDocument.Unprotect method.  It's simple enough to change the section that attempts to use the password to whatever Office object model suits your needs.

This code worked for me after several hours and about 400 million password attempts.  I feel it was likely a hash collision versus the actual password, but I'll take what works.

If you want to see the output work before you commit to several hours of CPU to this, there are a few things included for convenience.  This is explained in code comments as well.

Set the number of iterations by editing the n variable.

Change the first loop For i = 1 to m to For i = 1 to n to loop only so many times instead of all possible times.

Turn on the output by uncommenting the line If i Mod showEvery = 0 Then Debug.Print i, pw line.

If you want to see every password: leave showEvery set to 1, otherwise choose a different number to see every nth password.

Comment the section that actually tries the password against ActiveDocument.Unprotect and checks for errors.  It's marked in the code with comments.

```<code>Sub GetPassword()

Dim s As Integer, totalChars As Integer, j As Long  'GeneratePassword loop vars
Dim gpi As Long           'GeneratePassword index
Dim characters As String  'characters that can be part of the password.
Dim pw As String          'password attempt string

characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
totalChars = Len(characters)

Dim i As Double           'count integer
Dim n As Double           'number of interations to complete (if active)
Dim pwLen As Integer      'length of password
Dim m As Double           'number of permutations
Dim showEvery As Integer  'show multiples of this in debug log

pwLen = 5                 'password length
m = totalChars ^ pwLen    'number of potential combinations of characters for the length
n = 1000                  'number of loop iterations if you don't want all of them.
showEvery = 1             'use 1 here to show every password.  10000 shows every 10,000th password, etc...

On Error Resume Next      'no need to invoke an error handler, just check the Err.Number
For i = 1 To m  'use "1 to n" if you want to test a certain number or "1 to m" if you want try all combinations.
    pw = vbNullString
    gpi = i     'assign GeneratePassword loop integer our loop integer
    'GeneratePassword loop
    For s = 1 To pwLen
        j = ((gpi - 1) Mod totalChars) + 1
        pw = Mid(characters, j, 1) & pw
        gpi = (gpi - j) \ totalChars + 1
    Next s

    'writes out if uncommented and it's the right i. comment out once you're sure of the output.
    'If i Mod showEvery = 0 Then Debug.Print i, pw

    'try the password to unprotect the document, comment if just testing passwords in Immediate window
    ActiveDocument.Unprotect password:=pw
    If Err.Number <> 5485 Then
        MsgBox "Unexpected Error Code: " & Err.Number & vbCrLf & Err.Description & vbCrLf & pw
    End If
    If ActiveDocument.ProtectionType = wdNoProtection Then
        MsgBox "Unprotected with password: " & vbCrLf & pw
        Debug.Print "Unprotect Password:  " & pw
        Exit Sub
    End If
    'end trying the password.

Next i

End Sub
</code>```

Title: Brute force password VBA

Body:
I'm trying to workout how one could cycle through all possibilities of a string but i doesn't seem to be going very well.

I have so far put a set of characters into an array but I cant for the life of me get my head around how I can make it work. I have got this far but my brain cannot seem to get round it.

Can any one shed any light of the proper way to do this and possibly pseudo code so I can create my own.

Function passwordGenerator(length As Integer)
    Dim characters() As String
    Dim x As Integer
    Dim y As Integer
    Dim p As Integer
    Dim t As Integer

    Dim oldpassword As String
    Dim newcharacter As String

    ReDim Preserve characters(1)

    For x = 48 To 90
        ReDim Preserve characters(UBound(characters) + 1)
        characters(UBound(characters) - 1) = VBA.Chr(x)
    Next x
    y = 1

        Do

            For x = 1 To length
            oldpassword = generateBlank(x)
            p = 1
                For t = 1 To p
                newpassword = WorksheetFunction.Replace(oldpassword, t, 1, characters(y))
                    For y = 1 To UBound(characters)
                        newpassword = WorksheetFunction.Replace(oldpassword, p, 1, characters(y))
                        Debug.Print newpassword
                        p = p + 1
                    Next y
                Next t
            Next x

        Loop

    End Function

Function generateBlank(length As Integer)

Dim x As Integer

For x = 1 To length
    generateBlank = generateBlank & "A"
Next x

End Function

EDIT:::

I have edited my code but this way i have to know the length and that does not create an effective algorithm? Any help?

Function passwordGenerator()
Dim characters() As String
Dim x As Integer
Dim y As Integer
Dim p As Integer
Dim t As Integer
Dim w As Integer
Dim e As Integer
Dim r As Integer
Dim u As Integer

Dim oldpassword As String
Dim newcharacter As String

ReDim Preserve characters(1)

For x = 48 To 90
    ReDim Preserve characters(UBound(characters) + 1)
    characters(UBound(characters) - 1) = VBA.Chr(x)
Next x
y = 1

oldpassword = generateBlank(3)
        For x = 1 To UBound(characters)
            oldpassword = WorksheetFunction.Replace(oldpassword, 1, 1, characters(x))
            For t = 1 To UBound(characters)
                oldpassword = WorksheetFunction.Replace(oldpassword, 2, 1, characters(t))
                For y = 1 To UBound(characters)
                    oldpassword = WorksheetFunction.Replace(oldpassword, 3, 1, characters(y))
                    For q = 1 To UBound(characters)
                        oldpassword = WorksheetFunction.Replace(oldpassword, 4, 1, characters(q))
                        For w = 1 To UBound(characters)
                            oldpassword = WorksheetFunction.Replace(oldpassword, 5, 1, characters(w))
                            Debug.Print oldpassword
                            DoEvents
                        Next w
                    Next q
                Next y
            Next t
        Next x
End Function

Body:
I have edited the code in JA72's answer to provide a more comprehensive technique for brute forcing the "Restrict Editing" password.  I removed the array and ReDim portions, and combined it all into one sub.  The problem with JA's method is, while it works for the character set of ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 for 4-character passwords ([26+26+10]^4 = 14,776,336 possibilities), it does not work with a 5-character password ([26+26+10]^5 = 916,132,832 possibilities). The array functions in the original code cause a 32-bit Office application to immediately run out of memory when trying 5-character passwords or beyond.  I also noticed memory usage climbing as it iterated through 14 million possibilities with the original code, whereas memory usage stays flat with the code below.

This example specifically targets Word's ActiveDocument.Unprotect method.  It's simple enough to change the section that attempts to use the password to whatever Office object model suits your needs.

This code worked for me after several hours and about 400 million password attempts.  I feel it was likely a hash collision versus the actual password, but I'll take what works.

If you want to see the output work before you commit to several hours of CPU to this, there are a few things included for convenience.  This is explained in code comments as well.

Set the number of iterations by editing the n variable.

Change the first loop For i = 1 to m to For i = 1 to n to loop only so many times instead of all possible times.

Turn on the output by uncommenting the line If i Mod showEvery = 0 Then Debug.Print i, pw line.

If you want to see every password: leave showEvery set to 1, otherwise choose a different number to see every nth password.

Comment the section that actually tries the password against ActiveDocument.Unprotect and checks for errors.  It's marked in the code with comments.

Sub GetPassword()

Dim s As Integer, totalChars As Integer, j As Long  'GeneratePassword loop vars
Dim gpi As Long           'GeneratePassword index
Dim characters As String  'characters that can be part of the password.
Dim pw As String          'password attempt string

characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
totalChars = Len(characters)

Dim i As Double           'count integer
Dim n As Double           'number of interations to complete (if active)
Dim pwLen As Integer      'length of password
Dim m As Double           'number of permutations
Dim showEvery As Integer  'show multiples of this in debug log

pwLen = 5                 'password length
m = totalChars ^ pwLen    'number of potential combinations of characters for the length
n = 1000                  'number of loop iterations if you don't want all of them.
showEvery = 1             'use 1 here to show every password.  10000 shows every 10,000th password, etc...

On Error Resume Next      'no need to invoke an error handler, just check the Err.Number
For i = 1 To m  'use "1 to n" if you want to test a certain number or "1 to m" if you want try all combinations.
    pw = vbNullString
    gpi = i     'assign GeneratePassword loop integer our loop integer
    'GeneratePassword loop
    For s = 1 To pwLen
        j = ((gpi - 1) Mod totalChars) + 1
        pw = Mid(characters, j, 1) & pw
        gpi = (gpi - j) \ totalChars + 1
    Next s

    'writes out if uncommented and it's the right i. comment out once you're sure of the output.
    'If i Mod showEvery = 0 Then Debug.Print i, pw

    'try the password to unprotect the document, comment if just testing passwords in Immediate window
    ActiveDocument.Unprotect password:=pw
    If Err.Number <> 5485 Then
        MsgBox "Unexpected Error Code: " & Err.Number & vbCrLf & Err.Description & vbCrLf & pw
    End If
    If ActiveDocument.ProtectionType = wdNoProtection Then
        MsgBox "Unprotected with password: " & vbCrLf & pw
        Debug.Print "Unprotect Password:  " & pw
        Exit Sub
    End If
    'end trying the password.

Next i

End Sub


问:
Symfony JWT token: exception when token is expired
I am using JWT Token Bundle for user authentication. When the token is expired I get 500 server error. Instead of this how can I return JsonResponse with error code and message?

Here is my authenticator class:

```<code> class JwtTokenAuthentication extends AbstractGuardAuthenticator
{
/**
 * @var JWTEncoderInterface
 */
private $jwtEncoder;

/**
 * @var EntityManager
 */
private $em;

public function __construct(JWTEncoderInterface $jwtEncoder, EntityManager $em)
{
    $this->jwtEncoder = $jwtEncoder;
    $this->em = $em;
}

public function getCredentials(Request $request)
{
    $extractor = new AuthorizationHeaderTokenExtractor(
        'Bearer',
        'Authorization'
    );
    $token = $extractor->extract($request);
    if (!$token) {
        return null;
    }

    return $token;
}

public function getUser($credentials, UserProviderInterface $userProvider)
{
    $data = $this->jwtEncoder->decode($credentials);
    if(!$data){
      return null;
    }
    $user = $this->em->getRepository("AlumnetCoreBundle:User")->find($data["email"]);
    return $user;
}

public function checkCredentials($credentials, UserInterface $user)
{
    return true;
}

public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
    //todo
}

public function start(Request $request, AuthenticationException $authException = null)
{
    return new JsonResponse([
        'errorMessage' => 'auth required'
    ], Response::HTTP_UNAUTHORIZED);
}
}
</code>```

答:
You can decode the token in a try-catch:

```<code>try {
    $data = $this->jwtEncoder->decode($credentials);
} catch (\Exception $e) {
    throw new \Symfony\Component\Security\Core\Exception\BadCredentialsException($e->getMessage(), 0, $e);
}
</code>```

But you might have to implement the missing onAuthenticationFailure since throwing this exception will make it called. Something like:

```<code>public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
    return new JsonResponse([
        'errorMessage' => $exception->getMessage(),
    ], Response::HTTP_UNAUTHORIZED);
}
</code>```

Btw, LexikJWTAuthenticationBundle comes with a built-in JWTTokenAuthenticator since its 2.0 version. I suggest you to try using it before implementing your own authenticator, or at least extend it.

Body:
I am using JWT Token Bundle for user authentication. When the token is expired I get 500 server error. Instead of this how can I return JsonResponse with error code and message?

Here is my authenticator class:

 class JwtTokenAuthentication extends AbstractGuardAuthenticator
{
/**
 * @var JWTEncoderInterface
 */
private $jwtEncoder;

/**
 * @var EntityManager
 */
private $em;

public function __construct(JWTEncoderInterface $jwtEncoder, EntityManager $em)
{
    $this->jwtEncoder = $jwtEncoder;
    $this->em = $em;
}

public function getCredentials(Request $request)
{
    $extractor = new AuthorizationHeaderTokenExtractor(
        'Bearer',
        'Authorization'
    );
    $token = $extractor->extract($request);
    if (!$token) {
        return null;
    }

    return $token;
}

public function getUser($credentials, UserProviderInterface $userProvider)
{
    $data = $this->jwtEncoder->decode($credentials);
    if(!$data){
      return null;
    }
    $user = $this->em->getRepository("AlumnetCoreBundle:User")->find($data["email"]);
    return $user;
}

public function checkCredentials($credentials, UserInterface $user)
{
    return true;
}

public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
    //todo
}

public function start(Request $request, AuthenticationException $authException = null)
{
    return new JsonResponse([
        'errorMessage' => 'auth required'
    ], Response::HTTP_UNAUTHORIZED);
}
}

Body:
You can decode the token in a try-catch:

try {
    $data = $this->jwtEncoder->decode($credentials);
} catch (\Exception $e) {
    throw new \Symfony\Component\Security\Core\Exception\BadCredentialsException($e->getMessage(), 0, $e);
}

But you might have to implement the missing onAuthenticationFailure since throwing this exception will make it called. Something like:

public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
    return new JsonResponse([
        'errorMessage' => $exception->getMessage(),
    ], Response::HTTP_UNAUTHORIZED);
}

Btw, LexikJWTAuthenticationBundle comes with a built-in JWTTokenAuthenticator since its 2.0 version. I suggest you to try using it before implementing your own authenticator, or at least extend it.