问:
How to create a streak (or run of form) in R based on date, team and competition?
I have a quite specific problem I believe that I have been struggling to answer and thought I would open it out to the wonderful community.

I have a madeup dataset shown below (which is paet of a subset of over 30,000 rows - so want to make this solution as reproducible as possible):

```<code>*Date,Home Team,Away Team,League,Home Goals,Away Goals
43389,Everton,Wolves,League,1,3
43364,Man C,Arsenal,League,3,1
43414,Everton,Man C,League,0,2
43385,Liverpool,Bournemouth,League,3,0
43397,Man C,Chelsea,League,6,0
43390,Liverpool,Watford,League,5,0
43381,Man C,West Ham,League,1,0
43392,Man C,Arsenal,League,3,1
43369,Everton,Man C,League,0,2
43375,Liverpool,Bournemouth,League,3,0
43382,Man C,Chelsea,League,6,0
43396,Liverpool,Watford,League,5,0
43373,Man C,West Ham,League,1,0*
</code>```

In R, what I would like to have appended to each of the rows is a streak to say how many games have each team won in a row (within each competition) based on the date, I.e. how many games have the won in a row in chronolgical order? Ideally their would be four columns -> Home team streak at Home, Away Team Streak away, Home team overall streak (Home and Away combined) and Away team overall streak (Home and Away combined). Although I am sure that once one solution has been found the others will be able to be recreated using a similar code. I feel that I could do this in Excel with a Count or Sumif, however, I am not sure how to reproduce this in R and would like this to be as efficient as possible.

Thanks in advance for your help!!

```<code>> dput(Data)
structure(list(Date = structure(c(3L, 10L, 12L, 2L, 7L, 13L,
4L, 8L, 9L, 4L, 11L, 1L, 5L, 6L), .Label = c("03/10/2018", "04/10/2018",
"04/11/2018", "09/10/2018", "10/11/2018", "13/09/2018", "16/09/2018",
"16/10/2018", "20/09/2018", "21/10/2018", "22/10/2018", "28/09/2018",
"30/09/2018"), class = "factor"), Home.Team = structure(c(1L,
3L, 1L, 2L, 3L, 2L, 3L, 1L, 3L, 1L, 2L, 3L, 2L, 3L), .Label = c("Everton",
"Liverpool", "Man C"), class = "factor"), Away.Team = structure(c(7L,
1L, 4L, 2L, 3L, 5L, 6L, 7L, 1L, 4L, 2L, 3L, 5L, 6L), .Label = c("Arsenal",
"Bournemouth", "Chelsea", "Man C", "Watford", "West Ham", "Wolves"
), class = "factor"), Competition = structure(c(2L, 2L, 2L, 2L,
2L, 2L, 1L, 1L, 2L, 2L, 2L, 1L, 2L, 2L), .Label = c("Cup", "League"
), class = "factor"), Home.Goals = c(1L, 3L, 0L, 3L, 6L, 5L,
1L, 1L, 3L, 0L, 3L, 6L, 5L, 1L), Away.Goals = c(3L, 1L, 2L, 0L,
0L, 0L, 0L, 3L, 1L, 2L, 0L, 0L, 0L, 0L)), .Names = c("Date",
"Home.Team", "Away.Team", "Competition", "Home.Goals", "Away.Goals"
), class = "data.frame", row.names = c(NA, -14L))
</code>```

答:
I hope the following helps. The data sample has only teams always winning or always losing, but running it on the entire dataset should work as well.</p>

```<code>library(dplyr)
library(data.table)

df <- df %>%
    mutate_if(is.factor, as.character) # turn factors into characters

#          Date Home.Team   Away.Team Competition Home.Goals Away.Goals
# 1  04/11/2018   Everton      Wolves      League          1          3
# 2  21/10/2018     Man C     Arsenal      League          3          1
# 3  28/09/2018   Everton       Man C      League          0          2
# 4  04/10/2018 Liverpool Bournemouth      League          3          0
# 5  16/09/2018     Man C     Chelsea      League          6          0
# 6  30/09/2018 Liverpool     Watford      League          5          0
# 7  09/10/2018     Man C    West Ham         Cup          1          0
# 8  16/10/2018   Everton      Wolves         Cup          1          3
# 9  20/09/2018     Man C     Arsenal      League          3          1
# 10 09/10/2018   Everton       Man C      League          0          2
# 11 22/10/2018 Liverpool Bournemouth      League          3          0
# 12 03/10/2018     Man C     Chelsea         Cup          6          0
# 13 10/11/2018 Liverpool     Watford      League          5          0
# 14 13/09/2018     Man C    West Ham      League          1          0

# now we stack the dataframe twice on top of each other...
df <- df %>% # first...
    rename(Home.Team = Away.Team # ...with switched home and away columns
           , Away.Team = Home.Team
           , Home.Goals = Away.Goals
           , Away.Goals = Home.Goals) %>%
    bind_rows(df) # and second in the original form

#          Date   Away.Team   Home.Team Competition Away.Goals Home.Goals
# 1  04/11/2018     Everton      Wolves      League          1          3
# 2  21/10/2018       Man C     Arsenal      League          3          1
# 3  28/09/2018     Everton       Man C      League          0          2
# 4  04/10/2018   Liverpool Bournemouth      League          3          0
# 5  16/09/2018       Man C     Chelsea      League          6          0
# 6  30/09/2018   Liverpool     Watford      League          5          0
# 7  09/10/2018       Man C    West Ham         Cup          1          0
# 8  16/10/2018     Everton      Wolves         Cup          1          3
# 9  20/09/2018       Man C     Arsenal      League          3          1
# 10 09/10/2018     Everton       Man C      League          0          2
# 11 22/10/2018   Liverpool Bournemouth      League          3          0
# 12 03/10/2018       Man C     Chelsea         Cup          6          0
# 13 10/11/2018   Liverpool     Watford      League          5          0
# 14 13/09/2018       Man C    West Ham      League          1          0
# 15 04/11/2018      Wolves     Everton      League          3          1
# 16 21/10/2018     Arsenal       Man C      League          1          3
# 17 28/09/2018       Man C     Everton      League          2          0
# 18 04/10/2018 Bournemouth   Liverpool      League          0          3
# 19 16/09/2018     Chelsea       Man C      League          0          6
# 20 30/09/2018     Watford   Liverpool      League          0          5
# 21 09/10/2018    West Ham       Man C         Cup          0          1
# 22 16/10/2018      Wolves     Everton         Cup          3          1
# 23 20/09/2018     Arsenal       Man C      League          1          3
# 24 09/10/2018       Man C     Everton      League          2          0
# 25 22/10/2018 Bournemouth   Liverpool      League          0          3
# 26 03/10/2018     Chelsea       Man C         Cup          0          6
# 27 10/11/2018     Watford   Liverpool      League          0          5
# 28 13/09/2018    West Ham       Man C      League          0          1

df %>%
    mutate(won = Home.Goals < Away.Goals) %>% # now we calculate whether the match was won
    arrange(Home.Team, Date) %>% # sort by home.team and then date
    group_by(Home.Team) %>% # and for every home.team...
    mutate(streakGroup = rleid(won)) %>% # ...we calculate an ID for all the streaks
    group_by(Home.Team, streakGroup) %>% # and then for every home.team AND streak
    mutate(gamesWonInStreak = cumsum(won)) # we calculate the cumulative sum (number of games won in a roll)

#    Date       Away.Team Home.Team   Competition Away.Goals Home.Goals won   streakGroup gamesWonInStreak
#    <chr>      <chr>     <chr>       <chr>            <int>      <int> <lgl>       <int>            <int>
# 1  20/09/2018 Man C     Arsenal     League               3          1 TRUE            1                1
# 2  21/10/2018 Man C     Arsenal     League               3          1 TRUE            1                2
# 3  04/10/2018 Liverpool Bournemouth League               3          0 TRUE            1                1
# 4  22/10/2018 Liverpool Bournemouth League               3          0 TRUE            1                2
# 5  03/10/2018 Man C     Chelsea     Cup                  6          0 TRUE            1                1
# 6  16/09/2018 Man C     Chelsea     League               6          0 TRUE            1                2
# 7  04/11/2018 Wolves    Everton     League               3          1 TRUE            1                1
# 8  09/10/2018 Man C     Everton     League               2          0 TRUE            1                2
# 9  16/10/2018 Wolves    Everton     Cup                  3          1 TRUE            1                3
# 10 28/09/2018 Man C     Everton     League               2          0 TRUE            1                4
# # ... with 18 more rows
</code>```

Body:
I have a quite specific problem I believe that I have been struggling to answer and thought I would open it out to the wonderful community.

I have a madeup dataset shown below (which is paet of a subset of over 30,000 rows - so want to make this solution as reproducible as possible):

*Date,Home Team,Away Team,League,Home Goals,Away Goals
43389,Everton,Wolves,League,1,3
43364,Man C,Arsenal,League,3,1
43414,Everton,Man C,League,0,2
43385,Liverpool,Bournemouth,League,3,0
43397,Man C,Chelsea,League,6,0
43390,Liverpool,Watford,League,5,0
43381,Man C,West Ham,League,1,0
43392,Man C,Arsenal,League,3,1
43369,Everton,Man C,League,0,2
43375,Liverpool,Bournemouth,League,3,0
43382,Man C,Chelsea,League,6,0
43396,Liverpool,Watford,League,5,0
43373,Man C,West Ham,League,1,0*

In R, what I would like to have appended to each of the rows is a streak to say how many games have each team won in a row (within each competition) based on the date, I.e. how many games have the won in a row in chronolgical order? Ideally their would be four columns -> Home team streak at Home, Away Team Streak away, Home team overall streak (Home and Away combined) and Away team overall streak (Home and Away combined). Although I am sure that once one solution has been found the others will be able to be recreated using a similar code. I feel that I could do this in Excel with a Count or Sumif, however, I am not sure how to reproduce this in R and would like this to be as efficient as possible.

Thanks in advance for your help!!

> dput(Data)
structure(list(Date = structure(c(3L, 10L, 12L, 2L, 7L, 13L,
4L, 8L, 9L, 4L, 11L, 1L, 5L, 6L), .Label = c("03/10/2018", "04/10/2018",
"04/11/2018", "09/10/2018", "10/11/2018", "13/09/2018", "16/09/2018",
"16/10/2018", "20/09/2018", "21/10/2018", "22/10/2018", "28/09/2018",
"30/09/2018"), class = "factor"), Home.Team = structure(c(1L,
3L, 1L, 2L, 3L, 2L, 3L, 1L, 3L, 1L, 2L, 3L, 2L, 3L), .Label = c("Everton",
"Liverpool", "Man C"), class = "factor"), Away.Team = structure(c(7L,
1L, 4L, 2L, 3L, 5L, 6L, 7L, 1L, 4L, 2L, 3L, 5L, 6L), .Label = c("Arsenal",
"Bournemouth", "Chelsea", "Man C", "Watford", "West Ham", "Wolves"
), class = "factor"), Competition = structure(c(2L, 2L, 2L, 2L,
2L, 2L, 1L, 1L, 2L, 2L, 2L, 1L, 2L, 2L), .Label = c("Cup", "League"
), class = "factor"), Home.Goals = c(1L, 3L, 0L, 3L, 6L, 5L,
1L, 1L, 3L, 0L, 3L, 6L, 5L, 1L), Away.Goals = c(3L, 1L, 2L, 0L,
0L, 0L, 0L, 3L, 1L, 2L, 0L, 0L, 0L, 0L)), .Names = c("Date",
"Home.Team", "Away.Team", "Competition", "Home.Goals", "Away.Goals"
), class = "data.frame", row.names = c(NA, -14L))

Body:
I hope the following helps. The data sample has only teams always winning or always losing, but running it on the entire dataset should work as well.

library(dplyr)
library(data.table)

df <- df %>%
    mutate_if(is.factor, as.character) # turn factors into characters

#          Date Home.Team   Away.Team Competition Home.Goals Away.Goals
# 1  04/11/2018   Everton      Wolves      League          1          3
# 2  21/10/2018     Man C     Arsenal      League          3          1
# 3  28/09/2018   Everton       Man C      League          0          2
# 4  04/10/2018 Liverpool Bournemouth      League          3          0
# 5  16/09/2018     Man C     Chelsea      League          6          0
# 6  30/09/2018 Liverpool     Watford      League          5          0
# 7  09/10/2018     Man C    West Ham         Cup          1          0
# 8  16/10/2018   Everton      Wolves         Cup          1          3
# 9  20/09/2018     Man C     Arsenal      League          3          1
# 10 09/10/2018   Everton       Man C      League          0          2
# 11 22/10/2018 Liverpool Bournemouth      League          3          0
# 12 03/10/2018     Man C     Chelsea         Cup          6          0
# 13 10/11/2018 Liverpool     Watford      League          5          0
# 14 13/09/2018     Man C    West Ham      League          1          0

# now we stack the dataframe twice on top of each other...
df <- df %>% # first...
    rename(Home.Team = Away.Team # ...with switched home and away columns
           , Away.Team = Home.Team
           , Home.Goals = Away.Goals
           , Away.Goals = Home.Goals) %>%
    bind_rows(df) # and second in the original form

#          Date   Away.Team   Home.Team Competition Away.Goals Home.Goals
# 1  04/11/2018     Everton      Wolves      League          1          3
# 2  21/10/2018       Man C     Arsenal      League          3          1
# 3  28/09/2018     Everton       Man C      League          0          2
# 4  04/10/2018   Liverpool Bournemouth      League          3          0
# 5  16/09/2018       Man C     Chelsea      League          6          0
# 6  30/09/2018   Liverpool     Watford      League          5          0
# 7  09/10/2018       Man C    West Ham         Cup          1          0
# 8  16/10/2018     Everton      Wolves         Cup          1          3
# 9  20/09/2018       Man C     Arsenal      League          3          1
# 10 09/10/2018     Everton       Man C      League          0          2
# 11 22/10/2018   Liverpool Bournemouth      League          3          0
# 12 03/10/2018       Man C     Chelsea         Cup          6          0
# 13 10/11/2018   Liverpool     Watford      League          5          0
# 14 13/09/2018       Man C    West Ham      League          1          0
# 15 04/11/2018      Wolves     Everton      League          3          1
# 16 21/10/2018     Arsenal       Man C      League          1          3
# 17 28/09/2018       Man C     Everton      League          2          0
# 18 04/10/2018 Bournemouth   Liverpool      League          0          3
# 19 16/09/2018     Chelsea       Man C      League          0          6
# 20 30/09/2018     Watford   Liverpool      League          0          5
# 21 09/10/2018    West Ham       Man C         Cup          0          1
# 22 16/10/2018      Wolves     Everton         Cup          3          1
# 23 20/09/2018     Arsenal       Man C      League          1          3
# 24 09/10/2018       Man C     Everton      League          2          0
# 25 22/10/2018 Bournemouth   Liverpool      League          0          3
# 26 03/10/2018     Chelsea       Man C         Cup          0          6
# 27 10/11/2018     Watford   Liverpool      League          0          5
# 28 13/09/2018    West Ham       Man C      League          0          1

df %>%
    mutate(won = Home.Goals < Away.Goals) %>% # now we calculate whether the match was won
    arrange(Home.Team, Date) %>% # sort by home.team and then date
    group_by(Home.Team) %>% # and for every home.team...
    mutate(streakGroup = rleid(won)) %>% # ...we calculate an ID for all the streaks
    group_by(Home.Team, streakGroup) %>% # and then for every home.team AND streak
    mutate(gamesWonInStreak = cumsum(won)) # we calculate the cumulative sum (number of games won in a roll)

#    Date       Away.Team Home.Team   Competition Away.Goals Home.Goals won   streakGroup gamesWonInStreak
#    <chr>      <chr>     <chr>       <chr>            <int>      <int> <lgl>       <int>            <int>
# 1  20/09/2018 Man C     Arsenal     League               3          1 TRUE            1                1
# 2  21/10/2018 Man C     Arsenal     League               3          1 TRUE            1                2
# 3  04/10/2018 Liverpool Bournemouth League               3          0 TRUE            1                1
# 4  22/10/2018 Liverpool Bournemouth League               3          0 TRUE            1                2
# 5  03/10/2018 Man C     Chelsea     Cup                  6          0 TRUE            1                1
# 6  16/09/2018 Man C     Chelsea     League               6          0 TRUE            1                2
# 7  04/11/2018 Wolves    Everton     League               3          1 TRUE            1                1
# 8  09/10/2018 Man C     Everton     League               2          0 TRUE            1                2
# 9  16/10/2018 Wolves    Everton     Cup                  3          1 TRUE            1                3
# 10 28/09/2018 Man C     Everton     League               2          0 TRUE            1                4
# # ... with 18 more rows


来源: stackexchange

问:
How can i center a Audio Player?
how can i center the audio player?

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        #playlist{
            list-style: none;
        }
        #playlist li a{
            color:white;
            text-decoration: none;
        }
        #playlist .current-song a{
            color:blue;
        }
        body {background-color: black;}
        h1 {color: white;}
        p {color: white;}
    </style>
    <link rel="shortcut icon" type="image/ico" href="/img/favicon.ico">
</head>
<body>
    <audio src="" controls autoplay id="audioPlayer">
        Sorry, your Browser doesn't Support HTML5!
    </audio>
    <ul id="playlist">
        <li class="current-song"><a href="/music/song1.mp3"></a></li>
        <li><a href="/music/song2.mp3"></a></li>
    </ul>
    <!-- <p>Back to <a href="https://URL/">URL</a></p> -->
    <script src="https://code.jquery.com/tt.js"></script>
    <script src="audioPlayer.js"></script>
    <script>
        audioPlayer();
    </script>
</body>
</html>
</code>```

This is what i have so far: https://prnt.sc/r4o3nh
And this is what i want: https://prnt.sc/r4o3en

What i tried:
style="display: block; margin: 0 auto;
style="position:absolute;top:0;left:0;width:100%;height:100%;" width="1400" height="900"

答:
Are you looking for something like this?

.audioWrapper {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

#playlist {
  list-style: none;
}

#playlist li a {
  color: white;
  text-decoration: none;
}

#playlist .current-song a {
  color: blue;
}

body {
  background-color: black;
}

h1 {
  color: white;
}

p {
  color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="audioWrapper">
  <audio src="" controls autoplay id="audioPlayer">
        Sorry, your Browser doesn't Support HTML5!
    </audio>
  <ul id="playlist">
    <li class="current-song">

    </li>
    <li>

    </li>
  </ul>
</div></code>```

ContentLicense: CC BY-SA 4.0

Title: How can i center a Audio Player?

Body:
how can i center the audio player?

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title></title>

    <link rel="shortcut icon" type="image/ico" href="/img/favicon.ico">

    <audio src="" controls autoplay id="audioPlayer">
        Sorry, your Browser doesn't Support HTML5!
    </audio>

This is what i have so far: https://prnt.sc/r4o3nh
And this is what i want: https://prnt.sc/r4o3en

What i tried:
style="display: block; margin: 0 auto;
style="position:absolute;top:0;left:0;width:100%;height:100%;" width="1400" height="900"

Body:
Are you looking for something like this?

.audioWrapper {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

#playlist {
  list-style: none;
}

#playlist li a {
  color: white;
  text-decoration: none;
}

#playlist .current-song a {
  color: blue;
}

body {
  background-color: black;
}

h1 {
  color: white;
}

p {
  color: white;
}

<div class="audioWrapper">
  <audio src="" controls autoplay id="audioPlayer">
        Sorry, your Browser doesn't Support HTML5!
    </audio>
  <ul id="playlist">
    <li class="current-song">
      <a href="/music/song1.mp3"></a>
    </li>
    <li>
      <a href="/music/song2.mp3"></a>
    </li>
  </ul>
</div>


问:
Spring boot mocked object returning null on call
I am using @RunWith(SpringRunner.class) to writing unit test case to mock the object. I am trying to mock the repository instance which is accepting request object and returning response, but in unit test case implementation I have mocked the repository using @MockBean annotation and register the it's method call using Mockito.when(respository.post(request)).thenReturn(response). But this call is returning null.

答:
I had the same issue here, vsk.rahul's comment helped me a lot.

I was trying to to use a method to return a mock interaction, but not succeeded, turning it into a static method gave me the expected behavior.

Problem:

The method bar.foo() was returning null for any interaction

```<code>public void test1() {
    doReturn(mockReturn()).when(bar).foo();
}

private String mockReturn() {
    return "abc";
}
</code>```

Solution:

The method bar.foo() is returning abc String for any interaction

```<code>public void test1() {
    doReturn(mockReturn()).when(bar).foo();
}

private static String mockReturn() {
    return "abc";
}
</code>```

Body:
I had the same issue here, vsk.rahul's comment helped me a lot.

I was trying to to use a method to return a mock interaction, but not succeeded, turning it into a static method gave me the expected behavior.

Problem:

The method bar.foo() was returning null for any interaction

public void test1() {
    doReturn(mockReturn()).when(bar).foo();
}

private String mockReturn() {
    return "abc";
}

Solution:

The method bar.foo() is returning abc String for any interaction

public void test1() {
    doReturn(mockReturn()).when(bar).foo();
}

private static String mockReturn() {
    return "abc";
}


问:
Android BluetoothHeadset getConnectedDevices() list is empty
In my app, I want to get certain details about the connected bluetooth headset.
First, I thought of getting the connected devices whose profile is headset.

```<code> val result =  BluetoothAdapter.getDefaultAdapter()
        .getProfileProxy(context, mProfileListener, BluetoothProfile.HEADSET)
</code>```

The listener snippet is as follows :

```<code>private var mBluetoothHeadset: BluetoothHeadset? = null
private val mProfileListener = object : BluetoothProfile.ServiceListener {
    override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) {
        if (profile == BluetoothProfile.HEADSET) {
            mBluetoothHeadset = proxy as BluetoothHeadset
            val devices = mBluetoothHeadset?.connectedDevices
            devices?.forEach {
                println(it.name)
            }
        }
    }

    override fun onServiceDisconnected(profile: Int) {
        if (profile == BluetoothProfile.HEADSET) {
            mBluetoothHeadset = null
        }
    }
}
</code>```

I have declared the necessary permissions in the manifest

```<code> <uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
</code>```

But mBluetoothHeadset?.connectedDevices is always returning an empty list. But in my tablet, the device is already connected to a bluetooth headset. Am I missing anything here?

答:
It looks like we can get the list of connected devices by filtering it based on the various connection states. The following snippet worked for me</p>

```<code> private val states = intArrayOf(
    BluetoothProfile.STATE_DISCONNECTING,
    BluetoothProfile.STATE_DISCONNECTED,
    BluetoothProfile.STATE_CONNECTED,
    BluetoothProfile.STATE_CONNECTING
)
private val mProfileListener = object : BluetoothProfile.ServiceListener {
    override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) {
        if (profile == BluetoothProfile.HEADSET) {
            mBluetoothHeadset = proxy as BluetoothHeadset
            val devices = mBluetoothHeadset?.getDevicesMatchingConnectionStates(states)
            devices?.forEach {
                println("${it.name} ${it.bondState}")
            }
        }
    }
</code>```

Body:
In my app, I want to get certain details about the connected bluetooth headset.
First, I thought of getting the connected devices whose profile is headset.

 val result =  BluetoothAdapter.getDefaultAdapter()
        .getProfileProxy(context, mProfileListener, BluetoothProfile.HEADSET)

The listener snippet is as follows :

private var mBluetoothHeadset: BluetoothHeadset? = null
private val mProfileListener = object : BluetoothProfile.ServiceListener {
    override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) {
        if (profile == BluetoothProfile.HEADSET) {
            mBluetoothHeadset = proxy as BluetoothHeadset
            val devices = mBluetoothHeadset?.connectedDevices
            devices?.forEach {
                println(it.name)
            }
        }
    }

    override fun onServiceDisconnected(profile: Int) {
        if (profile == BluetoothProfile.HEADSET) {
            mBluetoothHeadset = null
        }
    }
}

I have declared the necessary permissions in the manifest

 <uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

But mBluetoothHeadset?.connectedDevices is always returning an empty list. But in my tablet, the device is already connected to a bluetooth headset. Am I missing anything here?

Body:
It looks like we can get the list of connected devices by filtering it based on the various connection states. The following snippet worked for me

 private val states = intArrayOf(
    BluetoothProfile.STATE_DISCONNECTING,
    BluetoothProfile.STATE_DISCONNECTED,
    BluetoothProfile.STATE_CONNECTED,
    BluetoothProfile.STATE_CONNECTING
)
private val mProfileListener = object : BluetoothProfile.ServiceListener {
    override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) {
        if (profile == BluetoothProfile.HEADSET) {
            mBluetoothHeadset = proxy as BluetoothHeadset
            val devices = mBluetoothHeadset?.getDevicesMatchingConnectionStates(states)
            devices?.forEach {
                println("${it.name} ${it.bondState}")
            }
        }
    }


问:
Compare boost::any contents
I am using a container to hold a list of pointers to anything:

```<code>struct Example {
    std::vector<boost::any> elements;
}
</code>```

To insert elements in this container, I had written a couple of helper functions (members of the struct Example):

```<code>void add_any(boost::any& a) {
    elements.push_back(a);
}

template<typename T>
void add_to_list(T& a) {
    boost::any bany = &a;
    add_any(bany);
}
</code>```

Now, I would like to insert elements only when they are not present in this container. To do this, I thought that I would only need to call search over elements with an appropriate comparator function. However, I do not know how to compare the boost::any instances.

My question:
Knowing that my boost::any instances always contain a pointer to something; is it possible to compare two boost::any values?

update

I thank you for your answers. I have also managed to do this in a probably unsafe way: using boost::unsafe_any_cast to obtain a void** and comparing the underlying pointer.

For the moment, this is working fine. I would, however, appreciate your comments: maybe this is a big mistake!

```<code>#include <boost/any.hpp>
#include <iostream>
#include <vector>
#include <string>
using namespace std;

bool any_compare(const boost::any& a1, const boost::any& a2) {
    cout << "compare " << *boost::unsafe_any_cast<void*>(&a1)
         << " with:  " << *boost::unsafe_any_cast<void*>(&a2);
    return (*boost::unsafe_any_cast<void*>(&a1)) ==
        (*boost::unsafe_any_cast<void*>(&a2));
}

struct A {};

class Example {
public:
    Example() : elements(0),
                m_1(3.14),
                m_2(42),
                m_3("hello"),
                m_4() {};
    virtual ~Example() {};

    void test_insert() {
        add_to_list(m_1);
        add_to_list(m_2);
        add_to_list(m_3);
        add_to_list(m_4);
        add_to_list(m_1); // should not insert
        add_to_list(m_2); // should not insert
        add_to_list(m_3); // should not insert
        add_to_list(m_4); // should not insert
    };

    template <typename T>
    void add_to_list(T& a) {
        boost::any bany = &a;
        add_any(bany);
    }

private:
    vector<boost::any> elements;
    double m_1;
    int    m_2;
    string m_3;
    A      m_4;

    void add_any(const boost::any& a) {
        cout << "Trying to insert " << (*boost::unsafe_any_cast<void*>(&a)) << endl;
        vector<boost::any>::const_iterator it;
        for (it =  elements.begin();
             it != elements.end();
             ++it) {
            if ( any_compare(a,*it) ) {
                cout << " : not inserting, already in list" << endl;
                return;
            }
            cout << endl;
        }
        cout << "Inserting " << (*boost::unsafe_any_cast<void*>(&a)) << endl;
        elements.push_back(a);
    };

};

int main(int argc, char *argv[]) {

    Example ex;
    ex.test_insert();
    unsigned char c;
    ex.add_to_list(c);
    ex.add_to_list(c); // should not insert

    return 0;
}
</code>```

答:
You cannot directly provide it, but you can actually use any as the underlying type... though for pointers it's pointless (ah!)

```<code>struct any {
  std::type_info const& _info;
  void* _address;
};
</code>```

And a templated constructor:

```<code>template <typename T>
any::any(T* t):
   _info(typeid(*t)),
   _address(dynamic_cast<void*>(t))
{
}
</code>```

This is, basically, boost::any.

Now we need to "augment" it with our comparison mechanism.

In order to do so, we'll "capture" the implementation of std::less.

```<code>typedef bool (*Comparer)(void*,void*);

template <typename T>
bool compare(void* lhs, void* rhs) const {
  return std::less<T>()(*reinterpret_cast<T*>(lhs), *reinterpret_cast<T*>(rhs));
}

template <typename T>
Comparer make_comparer(T*) { return compare<T>; }
</code>```

And augment the constructor of any.

```<code>struct any {
  std::type_info const& _info;
  void* _address;
  Comparer _comparer;
};

template <typename T>
any::any(T* t):
  _info(typeid(*t)),
  _address(dynamic_cast<void*>(t)),
  _comparer(make_comparer(t))
{
}
</code>```

Then, we provided a specialization of less (or operator<)

```<code>bool operator<(any const& lhs, any const& rhs) {
  if (lhs._info.before(rhs._info)) { return true; }
  if (rhs._info.before(lhs._info)) { return false; }
  return (*lhs._comparer)(lhs._address, rhs._address);
}
</code>```

Note: encapsulation, etc... are left as an exercise to the reader

ContentLicense: CC BY-SA 3.0

Title: Compare boost::any contents

Body:
I am using a container to hold a list of pointers to anything:

struct Example {
    std::vector<boost::any> elements;
}

To insert elements in this container, I had written a couple of helper functions (members of the struct Example):

void add_any(boost::any& a) {
    elements.push_back(a);
}

template<typename T>
void add_to_list(T& a) {
    boost::any bany = &a;
    add_any(bany);
}

Now, I would like to insert elements only when they are not present in this container. To do this, I thought that I would only need to call search over elements with an appropriate comparator function. However, I do not know how to compare the boost::any instances.

My question:
Knowing that my boost::any instances always contain a pointer to something; is it possible to compare two boost::any values?

update

I thank you for your answers. I have also managed to do this in a probably unsafe way: using boost::unsafe_any_cast to obtain a void** and comparing the underlying pointer.

For the moment, this is working fine. I would, however, appreciate your comments: maybe this is a big mistake!

#include <boost/any.hpp>
#include <iostream>
#include <vector>
#include <string>
using namespace std;

bool any_compare(const boost::any& a1, const boost::any& a2) {
    cout << "compare " << *boost::unsafe_any_cast<void*>(&a1)
         << " with:  " << *boost::unsafe_any_cast<void*>(&a2);
    return (*boost::unsafe_any_cast<void*>(&a1)) ==
        (*boost::unsafe_any_cast<void*>(&a2));
}

struct A {};

class Example {
public:
    Example() : elements(0),
                m_1(3.14),
                m_2(42),
                m_3("hello"),
                m_4() {};
    virtual ~Example() {};

    void test_insert() {
        add_to_list(m_1);
        add_to_list(m_2);
        add_to_list(m_3);
        add_to_list(m_4);
        add_to_list(m_1); // should not insert
        add_to_list(m_2); // should not insert
        add_to_list(m_3); // should not insert
        add_to_list(m_4); // should not insert
    };

    template <typename T>
    void add_to_list(T& a) {
        boost::any bany = &a;
        add_any(bany);
    }

private:
    vector<boost::any> elements;
    double m_1;
    int    m_2;
    string m_3;
    A      m_4;

    void add_any(const boost::any& a) {
        cout << "Trying to insert " << (*boost::unsafe_any_cast<void*>(&a)) << endl;
        vector<boost::any>::const_iterator it;
        for (it =  elements.begin();
             it != elements.end();
             ++it) {
            if ( any_compare(a,*it) ) {
                cout << " : not inserting, already in list" << endl;
                return;
            }
            cout << endl;
        }
        cout << "Inserting " << (*boost::unsafe_any_cast<void*>(&a)) << endl;
        elements.push_back(a);
    };

};

int main(int argc, char *argv[]) {

    Example ex;
    ex.test_insert();
    unsigned char c;
    ex.add_to_list(c);
    ex.add_to_list(c); // should not insert

    return 0;
}

Body:
You cannot directly provide it, but you can actually use any as the underlying type... though for pointers it's pointless (ah!)

struct any {
  std::type_info const& _info;
  void* _address;
};

And a templated constructor:

template <typename T>
any::any(T* t):
   _info(typeid(*t)),
   _address(dynamic_cast<void*>(t))
{
}

This is, basically, boost::any.

Now we need to "augment" it with our comparison mechanism.

In order to do so, we'll "capture" the implementation of std::less.

typedef bool (*Comparer)(void*,void*);

template <typename T>
bool compare(void* lhs, void* rhs) const {
  return std::less<T>()(*reinterpret_cast<T*>(lhs), *reinterpret_cast<T*>(rhs));
}

template <typename T>
Comparer make_comparer(T*) { return compare<T>; }

And augment the constructor of any.

struct any {
  std::type_info const& _info;
  void* _address;
  Comparer _comparer;
};

template <typename T>
any::any(T* t):
  _info(typeid(*t)),
  _address(dynamic_cast<void*>(t)),
  _comparer(make_comparer(t))
{
}

Then, we provided a specialization of less (or operator<)

bool operator<(any const& lhs, any const& rhs) {
  if (lhs._info.before(rhs._info)) { return true; }
  if (rhs._info.before(lhs._info)) { return false; }
  return (*lhs._comparer)(lhs._address, rhs._address);
}

Note: encapsulation, etc... are left as an exercise to the reader


问:
Prepopulate HTML form based on previous field
I currently have a very simple HTML form that looks something like this:

```<code><form>
   <label for="faccountNumber">Account Number</label>
   <input type="number" class="form-control" id="faccountNumber"><br><br>
   <label for="ffirstName">First Name</label>
   <input type="text" class="form-control" id="ffirstName"><br><br>
   <label for="fsurname">Surname</label>
   <input type="text" class="form-control" id="fsurname"><br><br>
</form>
</code>```

I would like to prepopulate some values dependent on the account number entered. This is just for a mockup & so I just want to hardcode in a few examples.

For example, if the account number 1789was entered I would like to automatically prepopulate the first name as John & the surname as Smith. How can I do this?

答:
You can do this with some javascript, this is rough solution using jquery:

```<code>$("#faccountNumber").bind('keyup mouseup', function () {
    let accountNum = $(this).val();
    if (accountNum == 1789) {
        $('#ffirstName').val("John");
        $('#fsurname').val("Smith");
    }
});
</code>```

If you want to make it more dynamic, you can fetch the data with ajax, but like CD001 said in the comments, you should avoid doing stuff like this for any sensitive data.

Body:
I currently have a very simple HTML form that looks something like this:

<form>
   Account Number
   <input type="number" class="form-control" id="faccountNumber">

   First Name
   <input type="text" class="form-control" id="ffirstName">

   Surname
   <input type="text" class="form-control" id="fsurname">

</form>

I would like to prepopulate some values dependent on the account number entered. This is just for a mockup & so I just want to hardcode in a few examples.

For example, if the account number 1789was entered I would like to automatically prepopulate the first name as John & the surname as Smith. How can I do this?

Body:
You can do this with some javascript, this is rough solution using jquery:

$("#faccountNumber").bind('keyup mouseup', function () {
    let accountNum = $(this).val();
    if (accountNum == 1789) {
        $('#ffirstName').val("John");
        $('#fsurname').val("Smith");
    }
});

If you want to make it more dynamic, you can fetch the data with ajax, but like CD001 said in the comments, you should avoid doing stuff like this for any sensitive data.


问:
Python looping when there is only one item in the list
Hello i need to loop over a few accounts but sometimes there is only one account. What is the best way to do that please?

Here is what i tried but this fails when there is only one account in the list.

```<code>accounts = ('X123456','Y325252')
for account in accounts:
    do stuff
</code>```

Sorry about the beginners question.

答:
A Python for loop will iterate over each item in a tuple or each character in a string. A string in parentheses is just a string. Python doesn't realize it's a tuple unless there is a comma within the parentheses.

Example:

```<code>In : tuple1 = ('this', 'that')
In : tuple2 = ('this')
In : tuple3 = ('this',)

In : tuple1[0]
Out: 'this'

In : tuple2[0]
Out: 't'

In : tuple3[0]
Out: 'this'

In : for item in tuple2:
...:     print(item)
...:
t
h
i
s

In : for item in tuple3:
...:     print(item)
...:
this
</code>```

Body:
Hello i need to loop over a few accounts but sometimes there is only one account. What is the best way to do that please?

Here is what i tried but this fails when there is only one account in the list.

accounts = ('X123456','Y325252')
for account in accounts:
    do stuff

Sorry about the beginners question.

Body:
A Python for loop will iterate over each item in a tuple or each character in a string. A string in parentheses is just a string. Python doesn't realize it's a tuple unless there is a comma within the parentheses.

Example:

In : tuple1 = ('this', 'that')
In : tuple2 = ('this')
In : tuple3 = ('this',)

In : tuple1[0]
Out: 'this'

In : tuple2[0]
Out: 't'

In : tuple3[0]
Out: 'this'

In : for item in tuple2:
...:     print(item)
...:
t
h
i
s

In : for item in tuple3:
...:     print(item)
...:
this


问:
Asp.Net - Scheduled Task using IHostedService
I'm working on an ASP.NET web application written in C# and hosted in an Azure virtual machine using IIS 10 as a web server. I have to schedule a background task to run once a day. To achieve this I created the following DailyTask class:

```<code>public class DailyTask : IHostedService {

    public Task StartAsync(CancellationToken cancellationToken) {
        Debug.WriteLine("start");
        Task.Run(TaskRoutine, cancellationToken);
        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken) {
        Debug.WriteLine("stop");
        return null;
    }

    public Task TaskRoutine() {
        while (true) {
            try {
                /* ... */

                DateTime nextStop = DateTime.Now.AddDays(1);
                var timeToWait = nextStop - DateTime.Now;
                var millisToWait = timeToWait.TotalMilliseconds;
                Thread.Sleep((int)millisToWait);
            }

            catch (Exception e) {
                Debug.WriteLine(e);
            }
        }
    }
}
</code>```

To start this task I added the following statement in my Startup class:

```<code>public class Startup {
    public void ConfigureServices(IServiceCollection services) {
        /* ... */
        services.AddSingleton<Microsoft.Extensions.Hosting.IHostedService, HiddenUserCleaner>();
        /* ... */
    }
}
</code>```

After a deploy on my test server, I observed that this solution works fine. But is it reliable? Can there be problems if used in production?

答:
It's not safe. Take a look at the guide here: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-3.1&tabs=visual-studio

If the app shuts down unexpectedly (for example, the app's process fails), StopAsync might not be called. Therefore, any methods called or operations conducted in StopAsync might not occur.

It's not the case exactly, but it assumes that the application can be restarted. Same thing goes with application pool which restarts occasionally.

Overall, this will not assure that it will run daily. If the application restarts frequently for whatever reason, it could be that it never runs.

The same is true with libraries like hangfire.

Other solutions could be web jobs, or you could check if it has executed today by using some kind of persistence like a database that stores the last execution time and the IHostingService will check every some time and on startup whether or not it should execute the background job and act accordingly.

Body:
I'm working on an ASP.NET web application written in C# and hosted in an Azure virtual machine using IIS 10 as a web server. I have to schedule a background task to run once a day. To achieve this I created the following DailyTask class:

public class DailyTask : IHostedService {

    public Task StartAsync(CancellationToken cancellationToken) {
        Debug.WriteLine("start");
        Task.Run(TaskRoutine, cancellationToken);
        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken) {
        Debug.WriteLine("stop");
        return null;
    }

    public Task TaskRoutine() {
        while (true) {
            try {
                /* ... */

                DateTime nextStop = DateTime.Now.AddDays(1);
                var timeToWait = nextStop - DateTime.Now;
                var millisToWait = timeToWait.TotalMilliseconds;
                Thread.Sleep((int)millisToWait);
            }

            catch (Exception e) {
                Debug.WriteLine(e);
            }
        }
    }
}

To start this task I added the following statement in my Startup class:

public class Startup {
    public void ConfigureServices(IServiceCollection services) {
        /* ... */
        services.AddSingleton<Microsoft.Extensions.Hosting.IHostedService, HiddenUserCleaner>();
        /* ... */
    }
}

After a deploy on my test server, I observed that this solution works fine. But is it reliable? Can there be problems if used in production?


问:
Sending a raw XML request to a SOAP service with Zeep (trying to duplicate an argument)
I am able to send a simple SOAP request with Zeep.

```<code>    with client.settings(strict=False):
        resp = client.service.demandeFicheProduit(
            demandeur=self.xxx, motDePasse=self.yyy,
            ean13s="foo",
            multiple=False)
</code>```

However, I need to give multiple times the ean13s argument, which is not possible in a Python function call, so I figured I need to build the XML myself.

With Zeep's debug on, I see that the XML sent is this:

```<code><?xml version='1.0' encoding='utf-8'?>
<soap-env:Envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/">
  <soap-env:Body>
    <ns0:demandeFicheProduit xmlns:ns0="http://fel.ws.accelya.com/">
      <demandeur>xxx
      </demandeur>
      <motDePasse>yyy
      </motDePasse>
      <ean13s>foo
      </ean13s>
      <multiple>false
      </multiple>
    </ns0:demandeFicheProduit>
  </soap-env:Body>
</soap-env:Envelope>
</code>```

So I only need to replicate the

```<code>      <ean13s>foo
      </ean13s>
</code>```

part.

Looking into Zeep, I see a Transport.post_xml method: https://github.com/mvantellingen/python-zeep/blob/da8a88b9f5/src/zeep/transports.py#L86 which takes an lxml tree as parameter. (doc)

```<code>def post_xml(self, address, envelope, headers):
        """Post the envelope xml element to the given address with the headers.
        This method is intended to be overriden if you want to customize the
        serialization of the xml element. By default the body is formatted
        and encoded as utf-8. See ``zeep.wsdl.utils.etree_to_string``.
        """
        message = etree_to_string(envelope)
        return self.post(address, message, headers)
</code>```

I tried a post_raw_xml method, without etree_to_string:

```<code>    def post_raw_xml(self, address, raw_envelope, headers):
        return self.post(address, raw_envelope, headers)
</code>```

I call it with the above XML

```<code>transport = zeep.Transport()
transport.post_raw_xml("adress", my_xml, {})  # {}: headers?
</code>```

and the response status is OK (200), however the service answers it is an invalid request.

Are there XML / SOAP intricacies I didn't pay attention to? Encoding? Headers? (here {})

edit: after spying a bit more the Zeep internals, the headers it sends are

```<code>{'SOAPAction': '""', 'Content-Type': 'text/xml; charset=utf-8'}
</code>```

So I thought I could simply use requests.post, to no avail yet. To use requests, see Sending SOAP request using Python Requests

How to otherwise build an XML manually?

Any more idea on how I can duplicate the eans13 argument?

Thank you.

答:
I solved my problem without Zeep.

I send a raw XML string with requests, I don't construct an XML manually with lxml or xsd.

What helped me was print-debugging the internals of Zeep's transport.py/post method (so the headers are {'SOAPAction': '""', 'Content-Type': 'text/xml; charset=utf-8'}
),

this other question: Sending SOAP request using Python Requests to send a post request:

```<code>requests.post(url, data=xml, headers=headers)
</code>```

and being careful on the XML string (yes there is a newline character after the closing <?xml> tag).

The downside is to parse the XML back.

Body:
I am able to send a simple SOAP request with Zeep.

    with client.settings(strict=False):
        resp = client.service.demandeFicheProduit(
            demandeur=self.xxx, motDePasse=self.yyy,
            ean13s="foo",
            multiple=False)

However, I need to give multiple times the ean13s argument, which is not possible in a Python function call, so I figured I need to build the XML myself.

With Zeep's debug on, I see that the XML sent is this:

<?xml version='1.0' encoding='utf-8'?>
<soap-env:Envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/">
  <soap-env:Body>
    <ns0:demandeFicheProduit xmlns:ns0="http://fel.ws.accelya.com/">
      <demandeur>xxx
      </demandeur>
      <motDePasse>yyy
      </motDePasse>
      <ean13s>foo
      </ean13s>
      <multiple>false
      </multiple>
    </ns0:demandeFicheProduit>
  </soap-env:Body>
</soap-env:Envelope>

So I only need to replicate the

      <ean13s>foo
      </ean13s>

part.

Looking into Zeep, I see a Transport.post_xml method: https://github.com/mvantellingen/python-zeep/blob/da8a88b9f5/src/zeep/transports.py#L86 which takes an lxml tree as parameter. (doc)

def post_xml(self, address, envelope, headers):
        """Post the envelope xml element to the given address with the headers.
        This method is intended to be overriden if you want to customize the
        serialization of the xml element. By default the body is formatted
        and encoded as utf-8. See ``zeep.wsdl.utils.etree_to_string``.
        """
        message = etree_to_string(envelope)
        return self.post(address, message, headers)

I tried a post_raw_xml method, without etree_to_string:

    def post_raw_xml(self, address, raw_envelope, headers):
        return self.post(address, raw_envelope, headers)

I call it with the above XML

transport = zeep.Transport()
transport.post_raw_xml("adress", my_xml, {})  # {}: headers?

and the response status is OK (200), however the service answers it is an invalid request.

Are there XML / SOAP intricacies I didn't pay attention to? Encoding? Headers? (here {})

edit: after spying a bit more the Zeep internals, the headers it sends are

{'SOAPAction': '""', 'Content-Type': 'text/xml; charset=utf-8'}

So I thought I could simply use requests.post, to no avail yet. To use requests, see Sending SOAP request using Python Requests

How to otherwise build an XML manually?

Any more idea on how I can duplicate the eans13 argument?

Thank you.

Body:
I solved my problem without Zeep.

I send a raw XML string with requests, I don't construct an XML manually with lxml or xsd.

What helped me was print-debugging the internals of Zeep's transport.py/post method (so the headers are {'SOAPAction': '""', 'Content-Type': 'text/xml; charset=utf-8'}
),

this other question: Sending SOAP request using Python Requests to send a post request:

requests.post(url, data=xml, headers=headers)

and being careful on the XML string (yes there is a newline character after the closing <?xml> tag).

The downside is to parse the XML back.


问:
Jupyter Notebook Kernel busy all the time
I have instaled anaconda and python works fine in Sypder , IPython etc . However I am not able to run python notebook.

Kernel gets created , it also connects but it shows the dark circle busy symbol throughout . There is no problem with the firewall or antivirus .
I have tried by disabling both .

I am also not able to open python terminal from notebook there is some powershell error.

Can anyone suggest something ?

Edit 1 : Added the snapshot and the log

Log Anaconda Prompt :

```
(base) C:\Users\Project>jupyter notebook
[I 13:11:26.561 NotebookApp] JupyterLab extension loaded from C:\Users\Project\A
naconda3\lib\site-packages\jupyterlab
[I 13:11:26.561 NotebookApp] JupyterLab application directory is C:\Users\Projec
t\Anaconda3\share\jupyter\lab
[I 13:11:26.569 NotebookApp] Serving notebooks from local directory: C:\Users\Pr
oject
[I 13:11:26.570 NotebookApp] The Jupyter Notebook is running at:
[I 13:11:26.570 NotebookApp] http://localhost:8888/?token=28e7406ee648d631648f9b
8c53e1f3027f5eb30516ccf15f
[I 13:11:26.571 NotebookApp] Use Control-C to stop this server and shut down all
 kernels (twice to skip confirmation).
[C 13:11:26.768 NotebookApp]

    To access the notebook, open this file in a browser:
        file:///C:/Users/Project/AppData/Roaming/jupyter/runtime/nbserver-3064-o
pen.html
    Or copy and paste one of these URLs:
        http://localhost:8888/?token=28e7406ee648d631648f9b8c53e1f3027f5eb30516c
cf15f
[I 13:11:56.237 NotebookApp] Creating new notebook in
[I 13:12:02.401 NotebookApp] Kernel started: 55d8fb5e-2fe7-4d4b-a1d3-a11b0b7e7e7
d
[I 13:12:05.242 NotebookApp] Adapting to protocol v5.1 for kernel 55d8fb5e-2fe7-
4d4b-a1d3-a11b0b7e7e7d
```

And the image where kernel is always busy

kernel busy

答:
I was also getting the same issue, I tried a lot of different stuff but nothing seemed to help me out. Ultimately, a Kernel Restart instead of Kernel Interrupt helped me out! The kernel restarted and I was able to run the kernels as usual.

I think this is just a workaround if someone finds the real solution please do let us know!

Body:
I have instaled anaconda and python works fine in Sypder , IPython etc . However I am not able to run python notebook.

Kernel gets created , it also connects but it shows the dark circle busy symbol throughout . There is no problem with the firewall or antivirus .
I have tried by disabling both .

I am also not able to open python terminal from notebook there is some powershell error.

Can anyone suggest something ?

Edit 1 : Added the snapshot and the log

Log Anaconda Prompt :

(base) C:\Users\Project>jupyter notebook
[I 13:11:26.561 NotebookApp] JupyterLab extension loaded from C:\Users\Project\A
naconda3\lib\site-packages\jupyterlab
[I 13:11:26.561 NotebookApp] JupyterLab application directory is C:\Users\Projec
t\Anaconda3\share\jupyter\lab
[I 13:11:26.569 NotebookApp] Serving notebooks from local directory: C:\Users\Pr
oject
[I 13:11:26.570 NotebookApp] The Jupyter Notebook is running at:
[I 13:11:26.570 NotebookApp] http://localhost:8888/?token=28e7406ee648d631648f9b
8c53e1f3027f5eb30516ccf15f
[I 13:11:26.571 NotebookApp] Use Control-C to stop this server and shut down all
 kernels (twice to skip confirmation).
[C 13:11:26.768 NotebookApp]

    To access the notebook, open this file in a browser:
        file:///C:/Users/Project/AppData/Roaming/jupyter/runtime/nbserver-3064-o
pen.html
    Or copy and paste one of these URLs:
        http://localhost:8888/?token=28e7406ee648d631648f9b8c53e1f3027f5eb30516c
cf15f
[I 13:11:56.237 NotebookApp] Creating new notebook in
[I 13:12:02.401 NotebookApp] Kernel started: 55d8fb5e-2fe7-4d4b-a1d3-a11b0b7e7e7
d
[I 13:12:05.242 NotebookApp] Adapting to protocol v5.1 for kernel 55d8fb5e-2fe7-
4d4b-a1d3-a11b0b7e7e7d

And the image where kernel is always busy

kernel busy


问:
Find length of a string in SQL using LIKE operator
Example:

Suppose there are following rows:

1- Animal is innocent
 2- Dog is Animal

select length(columnname like %animal%) from tablename

```<code>o/p - 1-17
      2-13
</code>```

答:
Yes it is possible. You just need to alter your query a little. The value given to the LENGTH function should the column upon which you wish to calculate the length. The LIKE operator should be used along with a WHERE statement. See code below.</p>

```<code>SELECT LENGTH(columnname) from tablename WHERE columname LIKE "%animal%"
</code>```

Body:
Example:

Suppose there are following rows:

1- Animal is innocent
 2- Dog is Animal

select length(columnname like %animal%) from tablename

o/p - 1-17
      2-13

Body:
Yes it is possible. You just need to alter your query a little. The value given to the LENGTH function should the column upon which you wish to calculate the length. The LIKE operator should be used along with a WHERE statement. See code below.

SELECT LENGTH(columnname) from tablename WHERE columname LIKE "%animal%"


问:
How to use table valued functions in SQL Server
I've a stored procedure here

```<code>ALTER PROCEDURE [dbo].[SortedReport]
(
    @ClientID INT,
    @RecordLimit,
    @FromDate DATETIME,
    @ToDate DATETIME,
    @OrderBy NVARCHAR(MAX)
)
AS
BEGIN
SELECT TOP (@RecordLimit)
        sv.ClientID,
        sv.VendorID,
        sv.ProductID,
        sv.TransactionTime,
        sv.ClientName,
        sv.VendorName,
        sv.ProductName,
        sv.ProductCode,
        sv.VendorCode,
        StockCount = dbo.GetStockCount(sv.ProductID, sv.VendorID, @ClientID, @FromDate, @ToDate),
        TransactionCount = dbo.GetTransCount(sv.ProductID, sv.VendorID, @FromDate, @ToDate),
        ProductCount     = dbo.GetProductCount(sv.ProductID, sv.VendorID),
FROM SortedReportiew AS sv
WHERE (sv.ClientID = @ClientID)
    AND (sv.TransactionTime >= @FromDate)
    AND (sv.TransactionTime < @Date)
</code>```

The function calls in the SELECT part is highly inefficient when I have large data. There function calls for 100 rows will mean a lot of reads.

I need to remove the calls from there and have bulk read in a table valued function and to pass most report parameters to these functions

```<code>SELECT
    sd.StockCount,
    sd.TransactionCount
    pd.ProductCount,
    TransactionTime,
    ClientName,
    VendorName,
    ProductName,
    ProductCode,
    VendorCode
FROM
(
    SELECT TOP (@RecordLimit)
        sv.ClientID,
        sv.VendorID,
        sv.ProductID,
        sv.TransactionTime,
        sv.ClientName,
        sv.VendorName,
        sv.ProductName,
        sv.ProductCode,
        sv.VendorCode
    FROM SortedReportiew AS sv
        --Begin Where {
    WHERE
        (ClientID = @ClientID)
        AND TransactionTime >= @FromDate
        AND TransactionTime < @ToDate
        --End Where }
) AS mainQuery
FULL JOIN GetStockDetails(
     @ClientID,
     @FromDate,
     @ToDate,
     ) AS sd
ON mainQuery.ClientID = sd.ClientID
LEFT OUTER JOIN GetProductDetails(
     @ProductID
     @FromDate,
     @ToDate,
     ) AS pd
ON mainQuery.ClientID = pd.ClientID
</code>```

I've n't tried table valued function before. What I h've written so far is

```<code>ALTER FUNCTION [dbo].[GetStockDetails]
(
   @ClientID INT
   @FromDate DATETIME,
   @ToDate DATETIME,
)
RETURNS @tblStockDetails TABLE (
  -- Columns returned by the function
        StockCount INT,
        TransactionCount  INT
)
AS

BEGIN

INSERT INTO @tblStockDetails

SELECT
    StockCount,
    TransactionCount
FROM
(
SELECT
    StockCount = (SELECT COUNT(*)... //  My Query here
    ....
RETURN

END
</code>```

Can somebody advice on the format of the table valued function for this requirement.

答:
Answer to the comment above.

Well, you should make the temp table so big that you have all entries (rows) that isnt constants. And limit the table with the constants i.e. @fromDate and @toDate

For instance:

```<code>dbo.GetStockCount(sv.ProductID, sv.VendorID, @ClientID, @FromDate, @ToDate)
</code>```

This should be done something like this:

```<code>INSERT INTO #tempTable
SELECT  theValuePreviouslyFetchedFromFunction
        ,ProductID
        ,VendorID
FROM    yourTable
WHERE   clientIDValue = @ClientID
    AND dateValue <= @fromDate
    AND dateValue > @toDate
</code>```

And you define the temp table with primary key on productID and vendorID.

Then you can join this table with the initial one on these two columns and have the result in the select.

Without any more example code it is hard to help you group all functions to one query.

Hope this helps.

Body:
I've a stored procedure here

ALTER PROCEDURE [dbo].[SortedReport]
(
    @ClientID INT,
    @RecordLimit,
    @FromDate DATETIME,
    @ToDate DATETIME,
    @OrderBy NVARCHAR(MAX)
)
AS
BEGIN
SELECT TOP (@RecordLimit)
        sv.ClientID,
        sv.VendorID,
        sv.ProductID,
        sv.TransactionTime,
        sv.ClientName,
        sv.VendorName,
        sv.ProductName,
        sv.ProductCode,
        sv.VendorCode,
        StockCount = dbo.GetStockCount(sv.ProductID, sv.VendorID, @ClientID, @FromDate, @ToDate),
        TransactionCount = dbo.GetTransCount(sv.ProductID, sv.VendorID, @FromDate, @ToDate),
        ProductCount     = dbo.GetProductCount(sv.ProductID, sv.VendorID),
FROM SortedReportiew AS sv
WHERE (sv.ClientID = @ClientID)
    AND (sv.TransactionTime >= @FromDate)
    AND (sv.TransactionTime < @Date)

The function calls in the SELECT part is highly inefficient when I have large data. There function calls for 100 rows will mean a lot of reads.

I need to remove the calls from there and have bulk read in a table valued function and to pass most report parameters to these functions

SELECT
    sd.StockCount,
    sd.TransactionCount
    pd.ProductCount,
    TransactionTime,
    ClientName,
    VendorName,
    ProductName,
    ProductCode,
    VendorCode
FROM
(
    SELECT TOP (@RecordLimit)
        sv.ClientID,
        sv.VendorID,
        sv.ProductID,
        sv.TransactionTime,
        sv.ClientName,
        sv.VendorName,
        sv.ProductName,
        sv.ProductCode,
        sv.VendorCode
    FROM SortedReportiew AS sv
        --Begin Where {
    WHERE
        (ClientID = @ClientID)
        AND TransactionTime >= @FromDate
        AND TransactionTime < @ToDate
        --End Where }
) AS mainQuery
FULL JOIN GetStockDetails(
     @ClientID,
     @FromDate,
     @ToDate,
     ) AS sd
ON mainQuery.ClientID = sd.ClientID
LEFT OUTER JOIN GetProductDetails(
     @ProductID
     @FromDate,
     @ToDate,
     ) AS pd
ON mainQuery.ClientID = pd.ClientID

I've n't tried table valued function before. What I h've written so far is

ALTER FUNCTION [dbo].[GetStockDetails]
(
   @ClientID INT
   @FromDate DATETIME,
   @ToDate DATETIME,
)
RETURNS @tblStockDetails TABLE (
  -- Columns returned by the function
        StockCount INT,
        TransactionCount  INT
)
AS

BEGIN

INSERT INTO @tblStockDetails

SELECT
    StockCount,
    TransactionCount
FROM
(
SELECT
    StockCount = (SELECT COUNT(*)... //  My Query here
    ....
RETURN

END

Can somebody advice on the format of the table valued function for this requirement.

Body:
Answer to the comment above.

Well, you should make the temp table so big that you have all entries (rows) that isnt constants. And limit the table with the constants i.e. @fromDate and @toDate

For instance:

dbo.GetStockCount(sv.ProductID, sv.VendorID, @ClientID, @FromDate, @ToDate)

This should be done something like this:

INSERT INTO #tempTable
SELECT  theValuePreviouslyFetchedFromFunction
        ,ProductID
        ,VendorID
FROM    yourTable
WHERE   clientIDValue = @ClientID
    AND dateValue <= @fromDate
    AND dateValue > @toDate

And you define the temp table with primary key on productID and vendorID.

Then you can join this table with the initial one on these two columns and have the result in the select.

Without any more example code it is hard to help you group all functions to one query.

Hope this helps.


问:
pytest assert for pyspark dataframe comparison
I have 2 pyspark dataframe as shown in file attached. expected_df and actual_df

In my unit test I am trying to check if both are equal or not.

for which my code is

```<code>expected = map(lambda row: row.asDict(), expected_df.collect())
actual = map(lambda row: row.asDict(), actaual_df.collect())
assert expected = actual
</code>```

Since both dfs are same but row order is different so assert fails here.
What is best way to compare such dfs.

答:
try to have "==" instead of "=".
assert expected == actual</p>

Body:
I have 2 pyspark dataframe as shown in file attached. expected_df and actual_df

In my unit test I am trying to check if both are equal or not.

for which my code is

expected = map(lambda row: row.asDict(), expected_df.collect())
actual = map(lambda row: row.asDict(), actaual_df.collect())
assert expected = actual

Since both dfs are same but row order is different so assert fails here.
What is best way to compare such dfs.


问:
top n in DolphinDB SQL statements
The following SQL statement in DolphinDB database

```<code>n=10000
x = select top n * from bn_1m_spot
</code>```

returns the following error message:

```<code>Syntax Error: [line #2] integer constant expected after keyword top
</code>```

Is there a way to use a variable after keyword top in DolphinDB SQL?

答:
Yes, top clause must be used with a constant integer. If you do need to specify n dynamically, please use function sql to construct a sql statement.

sql(select=sqlCol("*"), from=bn_1m_spot, limit=n).eval()

Title: top n in DolphinDB SQL statements

Body:
The following SQL statement in DolphinDB database

n=10000
x = select top n * from bn_1m_spot

returns the following error message:

Syntax Error: [line #2] integer constant expected after keyword top

Is there a way to use a variable after keyword top in DolphinDB SQL?


问:
I'm not getting proper output for checking a string to be palindrome or not
I am not getting expected output while running the program

```<code>print('----------palindrome or not---------')
line=input('enter a line:-')
length=len(line)
a=0
if(length%2==0):
    length1=length/2
else:
    length1=(length+1)/2
for i in range (0,length-1):
    if(line[i]==line[length-2]):
        a+=1
if(a==length1):
    print("entered line is palindrome")
else:
    print("entered line is not palindrome")
</code>```

OUTPUT:

答:
Perhaps try:</p>

```<code>#!/usr/local/cpython-3.8/bin/python3

print('----------palindrome or not---------')

line = input('enter a line:-')
length = len(line)
half_length = length // 2

for i in range(0, half_length):
    if line[i] != line[length - i - 1]:
        print("entered line is not palindrome")
        break
else:
    print("entered line is palindrome")
</code>```

Body:
I am not getting expected output while running the program

print('----------palindrome or not---------')
line=input('enter a line:-')
length=len(line)
a=0
if(length%2==0):
    length1=length/2
else:
    length1=(length+1)/2
for i in range (0,length-1):
    if(line[i]==line[length-2]):
        a+=1
if(a==length1):
    print("entered line is palindrome")
else:
    print("entered line is not palindrome")

OUTPUT:

Body:
Perhaps try:

#!/usr/local/cpython-3.8/bin/python3

print('----------palindrome or not---------')

line = input('enter a line:-')
length = len(line)
half_length = length // 2

for i in range(0, half_length):
    if line[i] != line[length - i - 1]:
        print("entered line is not palindrome")
        break
else:
    print("entered line is palindrome")


问:
Duck-typing user-defined classes
So Python's core language and built-ins use a lot of duck typing. But for our own code, say I want to create my own class with a method that deals with "certain types" of objects, is it more idiomatic to use duck typing:

class MerkleTree:

    def method(self, document):
        try:
            hash_ = document.sha256_hash()
        except AttributeError:
            raise TypeError()
        do_smth_with_hash(hash_)
```

<p>or is it more idiomatic to just use a normal type check:</p>

<pre class="lang-py prettyprint-override"><code>class MerkleTree:

    def method(self, document):
        if isinstance(document, SHA256Hashable):
            raise TypeError()
        hash_ = document.sha256_hash()
        do_smth_with_hash(hash_)
</code>```

答:
From a pure typing perspective, MerkleTree.method will accept an argument of any type; Python has no way of restricting it.

From a duck-typing perspective, you promise that

```<code>def method(self, document):
    hash_ = document.sha256_hash()
    do_smth_with_hash(hash_)
</code>```

will work as long as document.sha256_hash is a callable whose return value is suitable for use by do_smth_with_hash, but method doesn't do any enforcement. Your documentation states a precondition for calling method, but it is up to the caller to meet that precondition and any consequences for violating it are the caller's problem, not method's.

You can provide a type hint (using the Protocol class) that more formally documents this precondition in a way that static type-checking tools like mypy can verify.

```<code>class ShaHashable(typing.Protocol):
    def sha256_hash(self):
        pass

class MerkleTree:

    def method(self, document: ShaHashable):
        hash_ = document.sha256_hash()
        do_smth_with_hash(hash_)
</code>```

Normally, you don't go so far as to catch one exception simply to raise one of a different type. The user knows from reading the documentation that method could raise an AttributeError if document doesn't have the appropriate method, and mypy can help catch that error without having to run the code.

Title: Duck-typing user-defined classes

Body:
So Python's core language and built-ins use a lot of duck typing. But for our own code, say I want to create my own class with a method that deals with "certain types" of objects, is it more idiomatic to use duck typing:

class MerkleTree:

    def method(self, document):
        try:
            hash_ = document.sha256_hash()
        except AttributeError:
            raise TypeError()
        do_smth_with_hash(hash_)

or is it more idiomatic to just use a normal type check:

class MerkleTree:

    def method(self, document):
        if isinstance(document, SHA256Hashable):
            raise TypeError()
        hash_ = document.sha256_hash()
        do_smth_with_hash(hash_)

Body:
From a pure typing perspective, MerkleTree.method will accept an argument of any type; Python has no way of restricting it.

From a duck-typing perspective, you promise that

def method(self, document):
    hash_ = document.sha256_hash()
    do_smth_with_hash(hash_)

will work as long as document.sha256_hash is a callable whose return value is suitable for use by do_smth_with_hash, but method doesn't do any enforcement. Your documentation states a precondition for calling method, but it is up to the caller to meet that precondition and any consequences for violating it are the caller's problem, not method's.

You can provide a type hint (using the Protocol class) that more formally documents this precondition in a way that static type-checking tools like mypy can verify.

class ShaHashable(typing.Protocol):
    def sha256_hash(self):
        pass

class MerkleTree:

    def method(self, document: ShaHashable):
        hash_ = document.sha256_hash()
        do_smth_with_hash(hash_)

Normally, you don't go so far as to catch one exception simply to raise one of a different type. The user knows from reading the documentation that method could raise an AttributeError if document doesn't have the appropriate method, and mypy can help catch that error without having to run the code.


问:
Images flowing out of a tablet layout inside a constraint layout
I'm facing troubles with a TableLayout here. My goal would be to make two columns with equal width, each one with one image that should adjust it's width so it fits inside the cell's available space, but it seems the images keep overflowing outside the available space in the cell/row. I have tested some properties without luck so far, so I could use some help here.

This is the current outcome in the design view:

I'd have expected the teddy bear to occupy only 50% of the row width at the left, and then the other image (which is an umbrella) to fit into the remaining 50% at the right of the bear. But you see that's not what's happening.

This is the layout code:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rootLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".view.DebugFragment">

    <TableLayout
        android:id="@+id/tableImages"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:stretchColumns="*"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TableRow
            android:layout_width="0dp"
            android:layout_height="wrap_content">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="16dp"
                app:srcCompat="@drawable/teddy_bear" />

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="16dp"
                tools:srcCompat="@drawable/umbrella" />

        </TableRow>
    </TableLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

UPDATE: Following Jakob F advice of replacing stretchColumns with shrinkColumns solves the issue with the image overflowing the layout boundaries, but breaks the requirement of both columns being of same width. See image:

UPDATE: Keeping the stretchColumns="*" and setting the layout_width of each image to 0dp does the trick of keeping them inside the layout boundaries AND make both columns the same with. Now I just have to figure out how to keep them at the same height, but that's a different issue I think.

UPDATE: Adding android:scaleType="fitStart" to both images aligns both of them to the top as desired, but it keeps adding space under the images for no reason (I have changed the background color so the limits of the images are more obvious).

答:
OK, I managed to solve all the issues by myself. Can't help but complain on how difficult such an obvious task can become sometimes in Android. I had to go over a lot of trial and error with a number of different attributes which functionality seem anything but obvious in most cases. Anyway, this is the solution:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rootLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#99ffff"
    tools:context=".view.DebugFragment">

    <TableLayout
        android:id="@+id/tableImages"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:stretchColumns="*"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="top">

            <ImageView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:adjustViewBounds="true"
                android:padding="16dp"
                app:srcCompat="@drawable/teddy_bear" />

            <ImageView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:adjustViewBounds="true"
                android:padding="16dp"
                app:srcCompat="@drawable/umbrella" />

        </TableRow>
    </TableLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

The result:

Body:
I'm facing troubles with a TableLayout here. My goal would be to make two columns with equal width, each one with one image that should adjust it's width so it fits inside the cell's available space, but it seems the images keep overflowing outside the available space in the cell/row. I have tested some properties without luck so far, so I could use some help here.

This is the current outcome in the design view:

I'd have expected the teddy bear to occupy only 50% of the row width at the left, and then the other image (which is an umbrella) to fit into the remaining 50% at the right of the bear. But you see that's not what's happening.

This is the layout code:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rootLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".view.DebugFragment">

    <TableLayout
        android:id="@+id/tableImages"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:stretchColumns="*"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TableRow
            android:layout_width="0dp"
            android:layout_height="wrap_content">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="16dp"
                app:srcCompat="@drawable/teddy_bear" />

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="16dp"
                tools:srcCompat="@drawable/umbrella" />

        </TableRow>
    </TableLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

UPDATE: Following Jakob F advice of replacing stretchColumns with shrinkColumns solves the issue with the image overflowing the layout boundaries, but breaks the requirement of both columns being of same width. See image:

UPDATE: Keeping the stretchColumns="*" and setting the layout_width of each image to 0dp does the trick of keeping them inside the layout boundaries AND make both columns the same with. Now I just have to figure out how to keep them at the same height, but that's a different issue I think.

UPDATE: Adding android:scaleType="fitStart" to both images aligns both of them to the top as desired, but it keeps adding space under the images for no reason (I have changed the background color so the limits of the images are more obvious).

Body:
OK, I managed to solve all the issues by myself. Can't help but complain on how difficult such an obvious task can become sometimes in Android. I had to go over a lot of trial and error with a number of different attributes which functionality seem anything but obvious in most cases. Anyway, this is the solution:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rootLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#99ffff"
    tools:context=".view.DebugFragment">

    <TableLayout
        android:id="@+id/tableImages"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:stretchColumns="*"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="top">

            <ImageView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:adjustViewBounds="true"
                android:padding="16dp"
                app:srcCompat="@drawable/teddy_bear" />

            <ImageView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:adjustViewBounds="true"
                android:padding="16dp"
                app:srcCompat="@drawable/umbrella" />

        </TableRow>
    </TableLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

The result:


问:
Chrome failed to start in docker container using Selenium after upgrading to ChromeDriver v80 and Chrome v80
I have E2E tests running in a docker container. After Friday's update of selenium/node-chrome it would not work anymore. I have tried to use older versions of selenium/node-chrome but it won't work. I have very little experience with docker containers etc.

Google Chrome 80.0.3987.106 <- Info gotten running command
  google-chrome --version chromedriver-80.0.3987.106 <- Info gotten from
  /opt/selenium/ folder.

Here`s how my Dockerfile looks like:

```<code>FROM selenium/node-chrome:3.141.59
ENV NODE_VERSION 12.14.1

USER root

RUN apt-get -qqy update \
 && apt-get -qqy --no-install-recommends install xz-utils \
 && apt-get -qqy autoremove \
 && apt-get -qqy clean \
 && rm -rf /var/lib/apt/lists/* /var/cache/apt/* \
 && ARCH= \
 && dpkgArch="$(dpkg --print-architecture)" \
 && case "${dpkgArch##*-}" in \
    amd64) ARCH='x64';; \
    ppc64el) ARCH='ppc64le';; \
    s390x) ARCH='s390x';; \
    arm64) ARCH='arm64';; \
    armhf) ARCH='armv7l';; \
    i386) ARCH='x86';; \
    *) echo "unsupported architecture"; exit 1 ;; \
  esac \
  # gpg keys listed at https://github.com/nodejs/node#release-keys
  && set -ex \
  && for key in \
    94AE36675C464D64BAFA68DD7434390BDBE9B9C5 \
    FD3A5288F042B6850C66B31F09FE44734EB7990E \
    71DCFD284A79C3B38668286BC97EC7A07EDE3FC1 \
    DD8F2338BAE7501E3DD5AC78C273792F7D83545D \
    C4F0DFFF4E8C1A8236409D08E73BC641CC11F4C8 \
    B9AE9905FFD7803F25714661B63B535A4C206CA9 \
    77984A986EBC2AA786BC0F66B01FBB92821C587A \
    8FCCA13FEF1D0C2E91008E09770F7A9A5AE15600 \
    4ED778F539E3634C779C87C6D7062848A1AB005C \
    A48C2BEE680E841632CD4E44F07496B3EB3C1762 \
    B9E2F5981AA6E0CD28160D9FF13993A75599653C \
  ; do \
    gpg --batch --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys "$key" || \
    gpg --batch --keyserver hkp://ipv4.pool.sks-keyservers.net --recv-keys "$key" || \
    gpg --batch --keyserver hkp://pgp.mit.edu:80 --recv-keys "$key" ; \
  done \
  && curl -fsSLO --compressed "https://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-$ARCH.tar.xz" \
  && curl -fsSLO --compressed "https://nodejs.org/dist/v$NODE_VERSION/SHASUMS256.txt.asc" \
  && gpg --batch --decrypt --output SHASUMS256.txt SHASUMS256.txt.asc \
  && grep " node-v$NODE_VERSION-linux-$ARCH.tar.xz\$" SHASUMS256.txt | sha256sum -c - \
  && tar -xJf "node-v$NODE_VERSION-linux-$ARCH.tar.xz" -C /usr/local --strip-components=1 --no-same-owner \
  && rm "node-v$NODE_VERSION-linux-$ARCH.tar.xz" SHASUMS256.txt.asc SHASUMS256.txt \
  && ln -s /usr/local/bin/node /usr/local/bin/nodejs \
  && mkdir /src \
  && chown seluser /src

USER seluser

WORKDIR /src

COPY ./package-lock.json ./package.json ./
RUN npm install && \
  npm run wd:update

COPY . ./

CMD ["npm", "test"]
</code>```

Build seems to go fine without any problems, but when trying to run tests I get the following error message:

```<code>    > protractor protractor.conf.js

[13:51:33] I/launcher - Running 1 instances of WebDriver
[13:51:33] I/local - Starting selenium standalone server...
[13:51:35] I/local - Selenium standalone server started at http://XXX.XX.X.X:51473/wd/hub
[13:51:36] E/launcher - unknown error: Chrome failed to start: crashed.
  (unknown error: DevToolsActivePort file doesn't exist)
  (The process started from chrome location /opt/google/chrome/chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'
System info: host: '8bc3b606ae46', ip: 'XXX.XX.X.X', os.name: 'Linux', os.arch: 'amd64', os.version: '4.19.76-linuxkit', java.version: '1.8.0_242'
Driver info: driver.version: unknown
remote stacktrace: #0 0x5584b6f867a9 <unknown>

[13:51:36] E/launcher - WebDriverError: unknown error: Chrome failed to start: crashed.
  (unknown error: DevToolsActivePort file doesn't exist)
  (The process started from chrome location /opt/google/chrome/chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'
System info: host: '8bc3b606ae46', ip: 'XXX.XX.X.X', os.name: 'Linux', os.arch: 'amd64', os.version: '4.19.76-linuxkit', java.version: '1.8.0_242'
Driver info: driver.version: unknown
remote stacktrace: #0 0x5584b6f867a9 <unknown>

    at Object.checkLegacyResponse (/src/node_modules/selenium-webdriver/lib/error.js:546:15)
    at parseHttpResponse (/src/node_modules/selenium-webdriver/lib/http.js:509:13)
    at /src/node_modules/selenium-webdriver/lib/http.js:441:30
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
From: Task: WebDriver.createSession()
    at Function.createSession (/src/node_modules/selenium-webdriver/lib/webdriver.js:769:24)
    at Function.createSession (/src/node_modules/selenium-webdriver/chrome.js:761:15)
    at createDriver (/src/node_modules/selenium-webdriver/index.js:170:33)
    at Builder.build (/src/node_modules/selenium-webdriver/index.js:626:16)
    at Local.getNewDriver (/src/node_modules/protractor/built/driverProviders/driverProvider.js:53:33)
    at Runner.createBrowser (/src/node_modules/protractor/built/runner.js:195:43)
    at /src/node_modules/protractor/built/runner.js:339:29
    at _fulfilled (/src/node_modules/q/q.js:834:54)
    at /src/node_modules/q/q.js:863:30
    at Promise.promise.promiseDispatch (/src/node_modules/q/q.js:796:13)
[13:51:36] E/launcher - Process exited with error code 199
npm ERR! Test failed.  See above for more details.
</code>```

答:
This error message...

```<code>[13:51:36] E/launcher - unknown error: Chrome failed to start: crashed.
  (unknown error: DevToolsActivePort file doesn't exist)
  (The process started from chrome location /opt/google/chrome/chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'
System info: host: '8bc3b606ae46', ip: 'XXX.XX.X.X', os.name: 'Linux', os.arch: 'amd64', os.version: '4.19.76-linuxkit', java.version: '1.8.0_242'
Driver info: driver.version: unknown
remote stacktrace: #0 0x5584b6f867a9 <unknown>
</code>```

...implies that the ChromeDriver v80.0 was unable to initiate/spawn a new Browsing Context with in Docker image for Chrome (80.0).

As per the discussion WebDriver 80.0.3987.16 can't open Chrome on Linux @triciac mentioned that, the implementation of ChromeDriver v80.0 looks for Chrome in the following order:

locations->push_back(base::FilePath("/usr/local/sbin"));

locations->push_back(base::FilePath("/usr/local/bin"));

locations->push_back(base::FilePath("/usr/sbin"));

locations->push_back(base::FilePath("/usr/bin"));

locations->push_back(base::FilePath("/sbin"));

locations->push_back(base::FilePath("/bin"));

locations->push_back(base::FilePath("/opt/google/chrome")); // last try with the default installation location.

@johnchen confirmed that, the binary search order on Linux was accidentally changed by r708243, which was intended to make it easier to configure the name of the Chrome binary, but accidentally changed the search order as well.

ChromeDriver team have updated ChromeDriver to fix this issue through this revision / commit.

Solution

The above mentioned solution is available with:

ChromeDriver v80.0.3987.106

ChromeDriver v81.0.4044.20

Interim solution

An interim solution would be using the binary_location attribute and you can find a detailed discussion in Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed

Body:
I have E2E tests running in a docker container. After Friday's update of selenium/node-chrome it would not work anymore. I have tried to use older versions of selenium/node-chrome but it won't work. I have very little experience with docker containers etc.

Google Chrome 80.0.3987.106 <- Info gotten running command
  google-chrome --version chromedriver-80.0.3987.106 <- Info gotten from
  /opt/selenium/ folder.

Here`s how my Dockerfile looks like:

FROM selenium/node-chrome:3.141.59
ENV NODE_VERSION 12.14.1

USER root

RUN apt-get -qqy update \
 && apt-get -qqy --no-install-recommends install xz-utils \
 && apt-get -qqy autoremove \
 && apt-get -qqy clean \
 && rm -rf /var/lib/apt/lists/* /var/cache/apt/* \
 && ARCH= \
 && dpkgArch="$(dpkg --print-architecture)" \
 && case "${dpkgArch##*-}" in \
    amd64) ARCH='x64';; \
    ppc64el) ARCH='ppc64le';; \
    s390x) ARCH='s390x';; \
    arm64) ARCH='arm64';; \
    armhf) ARCH='armv7l';; \
    i386) ARCH='x86';; \
    *) echo "unsupported architecture"; exit 1 ;; \
  esac \
  # gpg keys listed at https://github.com/nodejs/node#release-keys
  && set -ex \
  && for key in \
    94AE36675C464D64BAFA68DD7434390BDBE9B9C5 \
    FD3A5288F042B6850C66B31F09FE44734EB7990E \
    71DCFD284A79C3B38668286BC97EC7A07EDE3FC1 \
    DD8F2338BAE7501E3DD5AC78C273792F7D83545D \
    C4F0DFFF4E8C1A8236409D08E73BC641CC11F4C8 \
    B9AE9905FFD7803F25714661B63B535A4C206CA9 \
    77984A986EBC2AA786BC0F66B01FBB92821C587A \
    8FCCA13FEF1D0C2E91008E09770F7A9A5AE15600 \
    4ED778F539E3634C779C87C6D7062848A1AB005C \
    A48C2BEE680E841632CD4E44F07496B3EB3C1762 \
    B9E2F5981AA6E0CD28160D9FF13993A75599653C \
  ; do \
    gpg --batch --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys "$key" || \
    gpg --batch --keyserver hkp://ipv4.pool.sks-keyservers.net --recv-keys "$key" || \
    gpg --batch --keyserver hkp://pgp.mit.edu:80 --recv-keys "$key" ; \
  done \
  && curl -fsSLO --compressed "https://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-$ARCH.tar.xz" \
  && curl -fsSLO --compressed "https://nodejs.org/dist/v$NODE_VERSION/SHASUMS256.txt.asc" \
  && gpg --batch --decrypt --output SHASUMS256.txt SHASUMS256.txt.asc \
  && grep " node-v$NODE_VERSION-linux-$ARCH.tar.xz\$" SHASUMS256.txt | sha256sum -c - \
  && tar -xJf "node-v$NODE_VERSION-linux-$ARCH.tar.xz" -C /usr/local --strip-components=1 --no-same-owner \
  && rm "node-v$NODE_VERSION-linux-$ARCH.tar.xz" SHASUMS256.txt.asc SHASUMS256.txt \
  && ln -s /usr/local/bin/node /usr/local/bin/nodejs \
  && mkdir /src \
  && chown seluser /src

USER seluser

WORKDIR /src

COPY ./package-lock.json ./package.json ./
RUN npm install && \
  npm run wd:update

COPY . ./

CMD ["npm", "test"]

Build seems to go fine without any problems, but when trying to run tests I get the following error message:

    > protractor protractor.conf.js

[13:51:33] I/launcher - Running 1 instances of WebDriver
[13:51:33] I/local - Starting selenium standalone server...
[13:51:35] I/local - Selenium standalone server started at http://XXX.XX.X.X:51473/wd/hub
[13:51:36] E/launcher - unknown error: Chrome failed to start: crashed.
  (unknown error: DevToolsActivePort file doesn't exist)
  (The process started from chrome location /opt/google/chrome/chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'
System info: host: '8bc3b606ae46', ip: 'XXX.XX.X.X', os.name: 'Linux', os.arch: 'amd64', os.version: '4.19.76-linuxkit', java.version: '1.8.0_242'
Driver info: driver.version: unknown
remote stacktrace: #0 0x5584b6f867a9 <unknown>

[13:51:36] E/launcher - WebDriverError: unknown error: Chrome failed to start: crashed.
  (unknown error: DevToolsActivePort file doesn't exist)
  (The process started from chrome location /opt/google/chrome/chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'
System info: host: '8bc3b606ae46', ip: 'XXX.XX.X.X', os.name: 'Linux', os.arch: 'amd64', os.version: '4.19.76-linuxkit', java.version: '1.8.0_242'
Driver info: driver.version: unknown
remote stacktrace: #0 0x5584b6f867a9 <unknown>

    at Object.checkLegacyResponse (/src/node_modules/selenium-webdriver/lib/error.js:546:15)
    at parseHttpResponse (/src/node_modules/selenium-webdriver/lib/http.js:509:13)
    at /src/node_modules/selenium-webdriver/lib/http.js:441:30
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
From: Task: WebDriver.createSession()
    at Function.createSession (/src/node_modules/selenium-webdriver/lib/webdriver.js:769:24)
    at Function.createSession (/src/node_modules/selenium-webdriver/chrome.js:761:15)
    at createDriver (/src/node_modules/selenium-webdriver/index.js:170:33)
    at Builder.build (/src/node_modules/selenium-webdriver/index.js:626:16)
    at Local.getNewDriver (/src/node_modules/protractor/built/driverProviders/driverProvider.js:53:33)
    at Runner.createBrowser (/src/node_modules/protractor/built/runner.js:195:43)
    at /src/node_modules/protractor/built/runner.js:339:29
    at _fulfilled (/src/node_modules/q/q.js:834:54)
    at /src/node_modules/q/q.js:863:30
    at Promise.promise.promiseDispatch (/src/node_modules/q/q.js:796:13)
[13:51:36] E/launcher - Process exited with error code 199
npm ERR! Test failed.  See above for more details.

Body:
This error message...

[13:51:36] E/launcher - unknown error: Chrome failed to start: crashed.
  (unknown error: DevToolsActivePort file doesn't exist)
  (The process started from chrome location /opt/google/chrome/chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'
System info: host: '8bc3b606ae46', ip: 'XXX.XX.X.X', os.name: 'Linux', os.arch: 'amd64', os.version: '4.19.76-linuxkit', java.version: '1.8.0_242'
Driver info: driver.version: unknown
remote stacktrace: #0 0x5584b6f867a9 <unknown>

...implies that the ChromeDriver v80.0 was unable to initiate/spawn a new Browsing Context with in Docker image for Chrome (80.0).

As per the discussion WebDriver 80.0.3987.16 can't open Chrome on Linux @triciac mentioned that, the implementation of ChromeDriver v80.0 looks for Chrome in the following order:

locations->push_back(base::FilePath("/usr/local/sbin"));

locations->push_back(base::FilePath("/usr/local/bin"));

locations->push_back(base::FilePath("/usr/sbin"));

locations->push_back(base::FilePath("/usr/bin"));

locations->push_back(base::FilePath("/sbin"));

locations->push_back(base::FilePath("/bin"));

locations->push_back(base::FilePath("/opt/google/chrome")); // last try with the default installation location.

@johnchen confirmed that, the binary search order on Linux was accidentally changed by r708243, which was intended to make it easier to configure the name of the Chrome binary, but accidentally changed the search order as well.

ChromeDriver team have updated ChromeDriver to fix this issue through this revision / commit.

Solution

The above mentioned solution is available with:

ChromeDriver v80.0.3987.106

ChromeDriver v81.0.4044.20

Interim solution

An interim solution would be using the binary_location attribute and you can find a detailed discussion in Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed


问:
If True result based on a query output of 2 results
In column F I have the below formula which references the status of sheet 2 column G. The query formula produces 2 results populating cells F2 & F3. I want an "if" formula that if my query produces 2 cells containing yes, yes then say true but if it produces yes, no then produce false or no, no produce false.

This is the link to the sheet for reference. https://docs.google.com/spreadsheets/d/1C5xWlw9vMZMNhXprSCBZsNp0T9qMxvuooIP8I6JoI2Y/edit#gid=0

答:
I was able to come up with an answer with collaboration of some awesome people. The way I solved it, for now, is changing the where clause to focus on the "False" response only and wrapping it in an if and iferror to give me the True response

=iferror(ifna(if(query(IMPORTRANGE("https:/...","range"),"select Col8 where Col1 = '"&A7&"' and '"&E7&"' = Col2 and Col8 = 'No'",0)="No",FALSE,TRUE),TRUE),FALSE)


问:
[[ -e $file ]] command in unix
I'm relatively new to unix command line and I do not really understand what this command does:

```<code>[[ ! -e "$text_file" ]] || { echo "Error: I cannot overwrite '$text_file'." >&2;}
</code>```

Does anyone have an idea?

答:
First of all, it checks 2 conditions with logical OR || operator.

-e FILE - True if the FILE exists and is a file,
so the condition is negating the result of this check.

and then if this is false then it goes and prints the message and send that to stderr (>&2). If the first condition is true then second condition won't be evaluated (of course this default logical OR way of working)

In Unix-world, stdout is generally used when everything is working correctly and stderr is generally used to print messages when something goes wrong.

By default, stdout and stderr both print to your screen. The main difference is that the > and | operators catch stdout by default, but not stderr.

You can also check other things like below:

-r FILE - True if the FILE exists and is readable.

-w FILE - True if the FILE exists and is writable.

-x FILE - True if the FILE exists and is executable.

-d FILE - True if the FILE exists and is a directory.

-e FILE - True if the FILE exists and is a file, regardless of type (node, directory, socket, etc.).

-f FILE - True if the FILE exists and is a regular file (not a directory or device)

Title: [[ -e $file ]] command in unix

Body:
I'm relatively new to unix command line and I do not really understand what this command does:

[[ ! -e "$text_file" ]] || { echo "Error: I cannot overwrite '$text_file'." >&2;}

Does anyone have an idea?