答:
Difference between two time points is std::chrono::duration, and these types you can sum. So just take difference to the first element, averagize, and add the average to the first element. You'll get average timepoint.

Just make sure the durations you get don't get overflown after summing up. Consider casting to std::chrono::duration<double> but it might be over cautious.

Instead of taking difference vs first element you can also use time_since_epoch() but I don't recommend.

Title: How do I average std::chrono::time_point?

Body:
Given a vector of std::chrono::time_point<Rep, Period>, how do I find the average time_point?

The usual algorithm to find an average (add all values with std::accumulate, divide by the vector size) does not work because  you can't add two std::chrono::time_point values, nor can you divide a std::chrono::time_point<Rep, Period> by vec.size()


来源: stackexchange

问:
how to make a regular grid base on some irregular points in python
I have a numpy array of x and y coordinates and want to make it regular. The array is sorted based on its x values (first column):

```<code>import numpy as np
Irregular_points = np.array([[1.1,5.], [0.85,7.1], [0.9,9], [1.1,11], [1.,13.1],
                   [1.9,5.2], [2.,6.9], [1.95,9], [2.1,11.1], [2.,13.1],
                   [3.0,5.1], [3.1,7.0], [3.,9], [3.0,11.], [3.1,12.8]])
</code>```

I want to firtly find out which points have almost the same x values: it will be the first five rows, middle five rows and last five rows. One signal for finding these points is that y value decreases when I go to the next group. Then, I want to replace the x values of each group with the average value. For example in the fisrt five rows x values are 1.1, 0.85, 0.9, 1.1 and 1. and the average is 0.98. I want to do the same for next two parts.

For y values I again want to find similar ones which fall into five groups and then replace them with average of each group. y values of the first group are 5., 5.2 and 5.1 and average is 5.1. Finally, my points should be like the following array:

```<code>Regular_points = np.array([[0.98,5.1], [0.98,7.0], [0.98,9.0], [0.98,11.03], [0.98,13.0],
                   [1.98,5.1], [1.98,7.0], [1.98,9.0], [1.98,11.03], [1.98,13.0],
                   [3.04,5.1], [3.04,7.0], [3.04,9.0], [3.04,11.03], [3.04,13.0]])
</code>```

I tried to round numbers but it did not work for real cases and I need to make these averages. I very much appreciate any help. The figure clearly shows what I want. Red dots are irregular points but by replacing averages, blue dots can be resulted.

ContentLicense: CC BY-SA 4.0

Body:
I have a numpy array of x and y coordinates and want to make it regular. The array is sorted based on its x values (first column):

import numpy as np
Irregular_points = np.array([[1.1,5.], [0.85,7.1], [0.9,9], [1.1,11], [1.,13.1],
                   [1.9,5.2], [2.,6.9], [1.95,9], [2.1,11.1], [2.,13.1],
                   [3.0,5.1], [3.1,7.0], [3.,9], [3.0,11.], [3.1,12.8]])

I want to firtly find out which points have almost the same x values: it will be the first five rows, middle five rows and last five rows. One signal for finding these points is that y value decreases when I go to the next group. Then, I want to replace the x values of each group with the average value. For example in the fisrt five rows x values are 1.1, 0.85, 0.9, 1.1 and 1. and the average is 0.98. I want to do the same for next two parts.

For y values I again want to find similar ones which fall into five groups and then replace them with average of each group. y values of the first group are 5., 5.2 and 5.1 and average is 5.1. Finally, my points should be like the following array:

Regular_points = np.array([[0.98,5.1], [0.98,7.0], [0.98,9.0], [0.98,11.03], [0.98,13.0],
                   [1.98,5.1], [1.98,7.0], [1.98,9.0], [1.98,11.03], [1.98,13.0],
                   [3.04,5.1], [3.04,7.0], [3.04,9.0], [3.04,11.03], [3.04,13.0]])

I tried to round numbers but it did not work for real cases and I need to make these averages. I very much appreciate any help. The figure clearly shows what I want. Red dots are irregular points but by replacing averages, blue dots can be resulted.

Body:
Since you're averaging rows and columns, you'll need to use a different shape. Then separate x and y coords, average them by different axis and use np.transpose + np.meshgrid for nice display:

irregular_points = np.array([[1.1,5.], [0.85,7.1], [0.9,9], [1.1,11], [1.,13.1],
                             [1.9,5.2], [2.,6.9], [1.95,9], [2.1,11.1], [2.,13.1],
                             [3.0,5.1], [3.1,7.0], [3.,9], [3.0,11.], [3.1,12.8]])

points_reshape = irregular_points.reshape(3, 5, 2)
x, y = np.transpose(points_reshape)
x_mean = x.mean(axis=0)
y_mean = y.mean(axis=1)
regular_points = np.transpose(np.meshgrid(x_mean, y_mean))
regular_points
>>>
array([[[ 0.99      ,  5.1       ],
        [ 0.99      ,  7.        ],
        [ 0.99      ,  9.        ],
        [ 0.99      , 11.03333333],
        [ 0.99      , 13.        ]],

       [[ 1.99      ,  5.1       ],
        [ 1.99      ,  7.        ],
        [ 1.99      ,  9.        ],
        [ 1.99      , 11.03333333],
        [ 1.99      , 13.        ]],

       [[ 3.04      ,  5.1       ],
        [ 3.04      ,  7.        ],
        [ 3.04      ,  9.        ],
        [ 3.04      , 11.03333333],
        [ 3.04      , 13.        ]]])


问:
get URL of webview when URL changes
i use webview to make paypal payment on my android. payment is actually happening at server, i just upload the url into my webview. when payment is complete i redirect browser to a page. this is working fine. but what i want is when page is redirected to this success page i should be able to start new activity. i am using below method but it is not able to get success URL.</p>

```<code>_webView.setWebViewClient(new WebViewClient()
            {
                public boolean shouldOverrideUrlLoading(WebView view, String url)
                {
                    //Our servlet only uses one url for both success or failure
                    if (url.trim().equals("http://www.MyDomain.com/MobilePaypal/ReturnPage.aspx"))
                    {
                         Intent iPrintReciept = new Intent(getApplicationContext(), PrintReciept.class) ;
                        //Intent iPrintReciept = new Intent(Payment.this,PrintReciept.class);
                        startActivity(iPrintReciept);

                    }
                    return false;
                }
            });
</code>```

答:
If your working class is an activity then use like below

```<code>Intent iPrintReciept = new Intent(yourActivityName.this, PrintReciept.class);
</code>```

If your working class is not activity the use

```<code>Intent iPrintReciept = new Intent(context,PrintReciept.class);
</code>```

ContentLicense: CC BY-SA 3.0

Title: get URL of webview when URL changes

Body:
i use webview to make paypal payment on my android. payment is actually happening at server, i just upload the url into my webview. when payment is complete i redirect browser to a page. this is working fine. but what i want is when page is redirected to this success page i should be able to start new activity. i am using below method but it is not able to get success URL.

_webView.setWebViewClient(new WebViewClient()
            {
                public boolean shouldOverrideUrlLoading(WebView view, String url)
                {
                    //Our servlet only uses one url for both success or failure
                    if (url.trim().equals("http://www.MyDomain.com/MobilePaypal/ReturnPage.aspx"))
                    {
                         Intent iPrintReciept = new Intent(getApplicationContext(), PrintReciept.class) ;
                        //Intent iPrintReciept = new Intent(Payment.this,PrintReciept.class);
                        startActivity(iPrintReciept);

                    }
                    return false;
                }
            });

Body:
If your working class is an activity then use like below

Intent iPrintReciept = new Intent(yourActivityName.this, PrintReciept.class);

If your working class is not activity the use

Intent iPrintReciept = new Intent(context,PrintReciept.class);


问:
sliderInput `min`, `max` and `value` NULL problem in R Shiny App
I am trying to create a Time Series app in R-Shiny which shows data points on a Leaflet map between a selected Weekly time range via sliderInput. But sliderInput() is returning the following error:

```<code> Error: In sliderInput(): `min`, `max`, and `value` cannot be NULL, NA, or empty.
</code>```

How can this error be fixed?

```<code>Code

    # Time Series Map App v.1.1

    library(shiny)
    library(tidyverse)
    library(leaflet)

    # Create sample data
    Date = c("2014-04-08", "2014-06-04", "2014-04-30",
             "2014-05-30", "2014-05-01")
    lat = as.numeric(c("45.53814", "45.51076", "45.43560", "45.54332",
                       "45.52234"))
    lon = as.numeric(c("-73.63672", "-73.61029", "-73.60100",
                       "-73.56000 ", "-73.59022"))
    id = as.numeric(c("1", "2", "3", "4", "5"))

    # Create a df from the above columns
    df = data.frame(id, lat, lon, Date)
    df$Year = lubridate::year(df$Date)
    df$Month = lubridate::month(df$Date, label = TRUE, abbr=FALSE)
    df$Week = lubridate::week(df$Date)
    df$Date = as.Date(df$Date)

    ui = fluidPage(
        titlePanel("Time Series Map"),
        sidebarLayout(
            sidebarPanel(
                selectInput("Input_1", label = "Please select an ID", choices = unique(df$id)),

                # sliderInput("Input_2", label = "Select Year",
                #             min = min(fruit$year), max = max(fruit$year),
                #             value = median(fruit$year), step = 1),

                sliderInput("Input_2", label = "Please select a weekly range",
                            min = min(df$Week), max = max(df$Week),
                            value = unique(df$Week), step = 1)
            ),
            mainPanel(
                div(
                    class = "leaflet-full-screen",
                    leafletOutput("Time_Series_Map"))),
        ))

    server = function(input, output) {

        dataset = reactive({
            return(subset(df, (id   ==  input$Input_1 &
                                      #year   ==  input$codeInput2 &
                                   Week >= input$Input_3[1] && month <= input$Input_3[2])))
        })

    output$Time_Series_Map = leaflet(df) %>% addTiles() %>%
        addTiles(group = "OSM (default)") %>%
        addProviderTiles(provider = "Esri.WorldStreetMap",group = "World StreetMap") %>%
        addProviderTiles(provider = "Esri.WorldImagery",group = "World Imagery") %>%
        # addProviderTiles(provider = "NASAGIBS.ViirsEarthAtNight2012",group = "Nighttime Imagery") %>%
        addMarkers(lng = ~lon, lat = ~lat, popup = df$id, clusterOptions = markerClusterOptions()) %>%
        addLayersControl(
            baseGroups = c("OSM (default)","World StreetMap", "World Imagery"),
            options = layersControlOptions(collapsed = FALSE)
        )
}

shinyApp(ui = ui, server = server)
</code>```

答:
Seems that shiny::sliderInput expects explicit values instead of R expressions. However, you can set dummy values for e.g. max and min and then update them with the real data at the very beginning of the server function. Here is a more minimal example:

```<code>library(shiny)

# Create sample data
Date <- c(
  "2014-04-08", "2014-06-04", "2014-04-30",
  "2014-05-30", "2014-05-01"
)
id <- as.numeric(c("1", "2", "3", "4", "5"))

# Create a df from the above columns
df <- data.frame(id, lat, lon, Date)
df$Year <- lubridate::year(df$Date)
df$Month <- lubridate::month(df$Date, label = TRUE, abbr = FALSE)
df$Week <- lubridate::week(df$Date)
df$Date <- as.Date(df$Date)

ui <- fluidPage(
  sliderInput("Input_2",
    label = "Please select a weekly range",
    step = 1,
    # init with dummy values
    min = 0, max = 1,
    value = 1
  )
)

server <- function(input, output, session) {
  updateSliderInput(session, "Input_2",
    min = min(df$Week), max = max(df$Week),
    value = unique(df$Week)
  )
}

shinyApp(ui = ui, server = server)
</code>```

Body:
I am trying to create a Time Series app in R-Shiny which shows data points on a Leaflet map between a selected Weekly time range via sliderInput. But sliderInput() is returning the following error:

 Error: In sliderInput(): `min`, `max`, and `value` cannot be NULL, NA, or empty.

How can this error be fixed?

Code

    # Time Series Map App v.1.1

    library(shiny)
    library(tidyverse)
    library(leaflet)

    # Create sample data
    Date = c("2014-04-08", "2014-06-04", "2014-04-30",
             "2014-05-30", "2014-05-01")
    lat = as.numeric(c("45.53814", "45.51076", "45.43560", "45.54332",
                       "45.52234"))
    lon = as.numeric(c("-73.63672", "-73.61029", "-73.60100",
                       "-73.56000 ", "-73.59022"))
    id = as.numeric(c("1", "2", "3", "4", "5"))

    # Create a df from the above columns
    df = data.frame(id, lat, lon, Date)
    df$Year = lubridate::year(df$Date)
    df$Month = lubridate::month(df$Date, label = TRUE, abbr=FALSE)
    df$Week = lubridate::week(df$Date)
    df$Date = as.Date(df$Date)

    ui = fluidPage(
        titlePanel("Time Series Map"),
        sidebarLayout(
            sidebarPanel(
                selectInput("Input_1", label = "Please select an ID", choices = unique(df$id)),

                # sliderInput("Input_2", label = "Select Year",
                #             min = min(fruit$year), max = max(fruit$year),
                #             value = median(fruit$year), step = 1),

                sliderInput("Input_2", label = "Please select a weekly range",
                            min = min(df$Week), max = max(df$Week),
                            value = unique(df$Week), step = 1)
            ),
            mainPanel(
                div(
                    class = "leaflet-full-screen",
                    leafletOutput("Time_Series_Map"))),
        ))

    server = function(input, output) {

        dataset = reactive({
            return(subset(df, (id   ==  input$Input_1 &
                                      #year   ==  input$codeInput2 &
                                   Week >= input$Input_3[1] && month <= input$Input_3[2])))
        })

    output$Time_Series_Map = leaflet(df) %>% addTiles() %>%
        addTiles(group = "OSM (default)") %>%
        addProviderTiles(provider = "Esri.WorldStreetMap",group = "World StreetMap") %>%
        addProviderTiles(provider = "Esri.WorldImagery",group = "World Imagery") %>%
        # addProviderTiles(provider = "NASAGIBS.ViirsEarthAtNight2012",group = "Nighttime Imagery") %>%
        addMarkers(lng = ~lon, lat = ~lat, popup = df$id, clusterOptions = markerClusterOptions()) %>%
        addLayersControl(
            baseGroups = c("OSM (default)","World StreetMap", "World Imagery"),
            options = layersControlOptions(collapsed = FALSE)
        )
}

shinyApp(ui = ui, server = server)

Body:
Seems that shiny::sliderInput expects explicit values instead of R expressions. However, you can set dummy values for e.g. max and min and then update them with the real data at the very beginning of the server function. Here is a more minimal example:

library(shiny)

# Create sample data
Date <- c(
  "2014-04-08", "2014-06-04", "2014-04-30",
  "2014-05-30", "2014-05-01"
)
id <- as.numeric(c("1", "2", "3", "4", "5"))

# Create a df from the above columns
df <- data.frame(id, lat, lon, Date)
df$Year <- lubridate::year(df$Date)
df$Month <- lubridate::month(df$Date, label = TRUE, abbr = FALSE)
df$Week <- lubridate::week(df$Date)
df$Date <- as.Date(df$Date)

ui <- fluidPage(
  sliderInput("Input_2",
    label = "Please select a weekly range",
    step = 1,
    # init with dummy values
    min = 0, max = 1,
    value = 1
  )
)

server <- function(input, output, session) {
  updateSliderInput(session, "Input_2",
    min = min(df$Week), max = max(df$Week),
    value = unique(df$Week)
  )
}

shinyApp(ui = ui, server = server)


问:
Why can't Pipenv find the correct version of python for my venv?
I need a little assistance with an issue I'm having with one of my venvs.

TLDR

With a fresh virtual environment created with pipenv, running pipenv run python --version returns the following message, along with the wrong python version:

```<code>Warning: the which -a system utility is required for Pipenv to find Python installations properly.
  Please install it.
Python 3.9.7 <--- this should be 3.8.5
</code>```

Activating the virtual environment and then running python --version shows the correct version, but this prevents me from running anything via pipenv run <any command> with the venv not activated, and also raises suspicion that something isn't quite right. This is on MacOS Big Sur 11.6

My Process

Install my desired python version with pyenv install 3.8.5:

```<code>$ pyenv install 3.8.5
python-build: use openssl@1.1 from homebrew
python-build: use readline from homebrew
Downloading Python-3.8.5.tar.xz...
-> https://www.python.org/ftp/python/3.8.5/Python-3.8.5.tar.xz
Installing Python-3.8.5...
python-build: use tcl-tk from homebrew
python-build: use readline from homebrew
python-build: use zlib from xcode sdk
Installed Python-3.8.5 to /Users/<me>/.pyenv/versions/3.8.5
</code>```

Output of pyenv versions:

```<code>* system (set by /Users/<me>/.pyenv/version)
  3.6.4
  3.6.7
  3.8.12
  3.8.5
  3.9.1
</code>```

Create new environment and install reqs from Pipfile with pipenv install --dev. Pipfile contains

```<code>[requires]
python_full_version = "3.8.5"
</code>```

Output:

```<code>Creating a virtualenv for this project...
Pipfile: /Users/<me>/dev/<project>/Pipfile
Using /Users/<me>/.pyenv/versions/3.8.5/bin/python3.8 (3.8.5) to create virtualenv...
⠦ Creating virtual environment...created virtual environment CPython3.8.5.final.0-64 in 325ms
  creator CPython3Posix(dest=/Users/<me>/.local/share/virtualenvs/<project>-OYt9MQn5, clear=False, no_vcs_ignore=False, global=False)
  seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=/Users/<me>/Library/Application Support/virtualenv)
    added seed packages: pip==21.1.2, setuptools==57.0.0, wheel==0.36.2
  activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator

✔ Successfully created virtual environment!
Virtualenv location: /Users/<me>/.local/share/virtualenvs/<project>-OYt9MQn5
Installing dependencies from Pipfile.lock (62a518)...
     ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 108/108 — 00:00:50
To activate this project's virtualenv, run pipenv shell.
Alternatively, run a command inside the virtualenv with pipenv run.
</code>```

Try to run pipenv run python --version (it finds the wrong one):

```<code>$ pipenv run python --version
Loading .env environment variables...
Warning: the which -a system utility is required for Pipenv to find Python installations properly.
  Please install it.
Python 3.9.7
</code>```

Activate the shell, and run either the above command (with the same output), or just python --version, since the shell is activated now, and it finds the correct version:

```<code>(<project>) $ pipenv shell
Courtesy Notice: Pipenv found itself running within a virtual environment, so it will automatically use that environment, instead of creating its own for any project. You can set PIPENV_IGNORE_VIRTUALENVS=1 to force pipenv to ignore that environment and create its own instead. You can set PIPENV_VERBOSITY=-1 to suppress this warning.
Loading .env environment variables...
Launching subshell in virtual environment...
 . /Users/<me>/.local/share/virtualenvs/<project>-OYt9MQn5/bin/activate
N/A: version "N/A -> N/A" is not yet installed.

You need to run "nvm install N/A" to install it before using it.
 $  . /Users/ckz8780/.local/share/virtualenvs/<project>-OYt9MQn5/bin/activate
(<project>) $ python --version
Python 3.8.5
(<project>) $
</code>```

FWIW, I have several other venvs I've created in the exact same way (or so I thought) which work fine. In those venvs, when I run pipenv run python --version with the venv deactivated, the which -a error isn't there and they find the right python version. In fact, even if I activate the shell in those venvs and run pipenv run python --version, it still works fine and finds the right one. The only difference in those venvs is the python version (two are using python v3.6.x, and two are using python v3.8.9). They all work as expected, but this one just will not seem to find the right version no matter what I do. I am pulling my hair out.

Any help is greatly appreciated!!!

Thanks

答:
I am having a similar workflow when it comes to installing Python (using both Pyenv and Pipenv).

This is working for me:

Install new Python version with Pyenv:

```<code>pyenv install 3.9.0
</code>```

Run pyenv shell

```<code>pyenv shell 3.9.0
</code>```

In pyenv shell install pipenv via pip

```<code>pip install pipenv
</code>```

With pipenv install packages ...

```<code>pipenv install ...
</code>```

Finally create a virtualenv via Pipenv that is using the Python version from Pyenv:

```<code>pipenv shell 3.9.0
</code>```

Output:

```<code>Pipfile: /Users/fabianmeyer/Desktop/analytics/Pipfile
Using /Users/fabianmeyer/.pyenv/versions/3.9.0/bin/python3.9 (3.9.0) to create virtualenv...
⠹ Creating virtual environment...created virtual environment CPython3.9.0.final.0-64 in 1824ms
  creator CPython3Posix(dest=/Users/fabianmeyer/.local/share/virtualenvs/analytics-GC4g190F, clear=False, no_vcs_ignore=False, global=False)
  seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=/Users/fabianmeyer/Library/Application Support/virtualenv)
    added seed packages: pip==22.0.3, setuptools==60.6.0, wheel==0.37.1
  activators BashActivator,CShellActivator,FishActivator,NushellActivator,PowerShellActivator,PythonActivator

✔ Successfully created virtual environment!
Virtualenv location: /Users/fabianmeyer/.local/share/virtualenvs/analytics-GC4g190F
</code>```

Body:
I need a little assistance with an issue I'm having with one of my venvs.

TLDR

With a fresh virtual environment created with pipenv, running pipenv run python --version returns the following message, along with the wrong python version:

Warning: the which -a system utility is required for Pipenv to find Python installations properly.
  Please install it.
Python 3.9.7 <--- this should be 3.8.5

Activating the virtual environment and then running python --version shows the correct version, but this prevents me from running anything via pipenv run <any command> with the venv not activated, and also raises suspicion that something isn't quite right. This is on MacOS Big Sur 11.6

My Process

Install my desired python version with pyenv install 3.8.5:

$ pyenv install 3.8.5
python-build: use openssl@1.1 from homebrew
python-build: use readline from homebrew
Downloading Python-3.8.5.tar.xz...
-> https://www.python.org/ftp/python/3.8.5/Python-3.8.5.tar.xz
Installing Python-3.8.5...
python-build: use tcl-tk from homebrew
python-build: use readline from homebrew
python-build: use zlib from xcode sdk
Installed Python-3.8.5 to /Users/<me>/.pyenv/versions/3.8.5

Output of pyenv versions:

* system (set by /Users/<me>/.pyenv/version)
  3.6.4
  3.6.7
  3.8.12
  3.8.5
  3.9.1

Create new environment and install reqs from Pipfile with pipenv install --dev. Pipfile contains

[requires]
python_full_version = "3.8.5"

Output:

Creating a virtualenv for this project...
Pipfile: /Users/<me>/dev/<project>/Pipfile
Using /Users/<me>/.pyenv/versions/3.8.5/bin/python3.8 (3.8.5) to create virtualenv...
⠦ Creating virtual environment...created virtual environment CPython3.8.5.final.0-64 in 325ms
  creator CPython3Posix(dest=/Users/<me>/.local/share/virtualenvs/<project>-OYt9MQn5, clear=False, no_vcs_ignore=False, global=False)
  seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=/Users/<me>/Library/Application Support/virtualenv)
    added seed packages: pip==21.1.2, setuptools==57.0.0, wheel==0.36.2
  activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator

✔ Successfully created virtual environment!
Virtualenv location: /Users/<me>/.local/share/virtualenvs/<project>-OYt9MQn5
Installing dependencies from Pipfile.lock (62a518)...
     ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 108/108 — 00:00:50
To activate this project's virtualenv, run pipenv shell.
Alternatively, run a command inside the virtualenv with pipenv run.

Try to run pipenv run python --version (it finds the wrong one):

$ pipenv run python --version
Loading .env environment variables...
Warning: the which -a system utility is required for Pipenv to find Python installations properly.
  Please install it.
Python 3.9.7

Activate the shell, and run either the above command (with the same output), or just python --version, since the shell is activated now, and it finds the correct version:

(<project>) $ pipenv shell
Courtesy Notice: Pipenv found itself running within a virtual environment, so it will automatically use that environment, instead of creating its own for any project. You can set PIPENV_IGNORE_VIRTUALENVS=1 to force pipenv to ignore that environment and create its own instead. You can set PIPENV_VERBOSITY=-1 to suppress this warning.
Loading .env environment variables...
Launching subshell in virtual environment...
 . /Users/<me>/.local/share/virtualenvs/<project>-OYt9MQn5/bin/activate
N/A: version "N/A -> N/A" is not yet installed.

You need to run "nvm install N/A" to install it before using it.
 $  . /Users/ckz8780/.local/share/virtualenvs/<project>-OYt9MQn5/bin/activate
(<project>) $ python --version
Python 3.8.5
(<project>) $

FWIW, I have several other venvs I've created in the exact same way (or so I thought) which work fine. In those venvs, when I run pipenv run python --version with the venv deactivated, the which -a error isn't there and they find the right python version. In fact, even if I activate the shell in those venvs and run pipenv run python --version, it still works fine and finds the right one. The only difference in those venvs is the python version (two are using python v3.6.x, and two are using python v3.8.9). They all work as expected, but this one just will not seem to find the right version no matter what I do. I am pulling my hair out.

Any help is greatly appreciated!!!

Thanks

Body:
I am having a similar workflow when it comes to installing Python (using both Pyenv and Pipenv).

This is working for me:

Install new Python version with Pyenv:

pyenv install 3.9.0

Run pyenv shell

pyenv shell 3.9.0

In pyenv shell install pipenv via pip

pip install pipenv

With pipenv install packages ...

pipenv install ...

Finally create a virtualenv via Pipenv that is using the Python version from Pyenv:

pipenv shell 3.9.0

Output:

Pipfile: /Users/fabianmeyer/Desktop/analytics/Pipfile
Using /Users/fabianmeyer/.pyenv/versions/3.9.0/bin/python3.9 (3.9.0) to create virtualenv...
⠹ Creating virtual environment...created virtual environment CPython3.9.0.final.0-64 in 1824ms
  creator CPython3Posix(dest=/Users/fabianmeyer/.local/share/virtualenvs/analytics-GC4g190F, clear=False, no_vcs_ignore=False, global=False)
  seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=/Users/fabianmeyer/Library/Application Support/virtualenv)
    added seed packages: pip==22.0.3, setuptools==60.6.0, wheel==0.37.1
  activators BashActivator,CShellActivator,FishActivator,NushellActivator,PowerShellActivator,PythonActivator

✔ Successfully created virtual environment!
Virtualenv location: /Users/fabianmeyer/.local/share/virtualenvs/analytics-GC4g190F


问:
Std::nth_element is not giving the correct element
I don't know why in this case the function std::nth_element is not giving me the correct median for the X axis.

For this test I created a vector of point: std::vector<Point> points = {Point {70, 70}, Point {50, 30}, Point {35, 45}};

The function call is:

```<code>int median = (start + end) / 2;
Point split = get(points.begin() + start, points.begin() + median, points.begin() + end);
</code>```

Where start = 0; end = 2; In my mind the correct median for the X axis is Point(50, 30), instead this code gives me Point(70, 70).

Below there is the code for finding the median:

```<code>template <typename Iterator>
    Point get(Iterator start, Iterator median, Iterator end)
    {
        std::nth_element(
            start,
            median,
            end,
            [](const Point &point1, const Point &point2) {
                return point1.getX() < point2.getX();
            }
        );

        std::vector<Point>::iterator iter = median;
        std::cout << *iter << std::endl;
        return *iter;
    }
</code>```

答:
The variable end is not correctly pointing to the end of the vector. Hence, you only perform nth_element() on the first 2 elements. Since the variable median value is 1, the point with greater x value will be returned.

You can use points.end() instead of points.begin() + end.

Body:
I don't know why in this case the function std::nth_element is not giving me the correct median for the X axis.

For this test I created a vector of point: std::vector<Point> points = {Point {70, 70}, Point {50, 30}, Point {35, 45}};

The function call is:

int median = (start + end) / 2;
Point split = get(points.begin() + start, points.begin() + median, points.begin() + end);

Where start = 0; end = 2; In my mind the correct median for the X axis is Point(50, 30), instead this code gives me Point(70, 70).

Below there is the code for finding the median:

template <typename Iterator>
    Point get(Iterator start, Iterator median, Iterator end)
    {
        std::nth_element(
            start,
            median,
            end,
            [](const Point &point1, const Point &point2) {
                return point1.getX() < point2.getX();
            }
        );

        std::vector<Point>::iterator iter = median;
        std::cout << *iter << std::endl;
        return *iter;
    }


问:
SSL alert number 70 with TLSv1.3
```<code># nginx -V
nginx version: nginx/1.21.4
built with OpenSSL 1.1.1f  31 Mar 2020
</code>```

I've configured nginx to support TLSv1.3.

```<code>ssl_protocols  TLSv1.2 TLSv1.3;
</code>```

but i can't reach my host using TLSv1.3:

```<code># openssl s_client -connect hostname.com:443 -tls1_3
CONNECTED(00000003)
140544753464640:error:1409442E:SSL routines:ssl3_read_bytes:tlsv1 alert protocol version:../ssl/record/rec_layer_s3.c:1543:SSL alert number 70
---
no peer certificate available
...
</code>```

only TLSv1.2 works:

```<code># openssl s_client -connect hostname.com:443 -tls1_2
CONNECTED(00000003)
...
</code>```

Any host, like google.com or cloudflare.com connects fine using the same openssl command.

Of course, SSL Labs test also confirms TLSv1.3 support not enabled.

I've also read this thread and double-checked and I have one and only ssl_protocols line by cd /etc/nginx; grep -rl "ssl_protocols" which only outputs one file.

答:
I've found my issue, I've configured a default "catch all" server like this:

```<code>server {
    listen 443 ssl default_server;
    ssl_reject_handshake on;
}
</code>```

As specified in the docs here: https://nginx.org/en/docs/http/ngx_http_ssl_module.html#ssl_reject_handshake

Problem is fixed by removing ssl_reject_handshake on; and instead return 444 on that server, like:

```<code>server {
    listen 443 ssl default_server;
    ssl_certificate ssl/cert.pem;
    return 444;
}
</code>```

This is a known bug and should be fixed with OpenSSL 1.1.1h

Title: SSL alert number 70 with TLSv1.3

Body:
# nginx -V
nginx version: nginx/1.21.4
built with OpenSSL 1.1.1f  31 Mar 2020

I've configured nginx to support TLSv1.3.

ssl_protocols  TLSv1.2 TLSv1.3;

but i can't reach my host using TLSv1.3:

# openssl s_client -connect hostname.com:443 -tls1_3
CONNECTED(00000003)
140544753464640:error:1409442E:SSL routines:ssl3_read_bytes:tlsv1 alert protocol version:../ssl/record/rec_layer_s3.c:1543:SSL alert number 70
---
no peer certificate available
...

only TLSv1.2 works:

# openssl s_client -connect hostname.com:443 -tls1_2
CONNECTED(00000003)
...

Any host, like google.com or cloudflare.com connects fine using the same openssl command.

Of course, SSL Labs test also confirms TLSv1.3 support not enabled.

I've also read this thread and double-checked and I have one and only ssl_protocols line by cd /etc/nginx; grep -rl "ssl_protocols" which only outputs one file.

Body:
I've found my issue, I've configured a default "catch all" server like this:

server {
    listen 443 ssl default_server;
    ssl_reject_handshake on;
}

As specified in the docs here: https://nginx.org/en/docs/http/ngx_http_ssl_module.html#ssl_reject_handshake

Problem is fixed by removing ssl_reject_handshake on; and instead return 444 on that server, like:

server {
    listen 443 ssl default_server;
    ssl_certificate ssl/cert.pem;
    return 444;
}

This is a known bug and should be fixed with OpenSSL 1.1.1h


问:
Click "Exit" button through our Application It need to go Phones's Home page & remove SharedPreferences also
My question is when I click the "Exit" button through our application It need to go to Phones's Home screen.I have Tried like this

```<code>  public void onExitAction(View botton){
          // finish();
          // super.finish();
           // System.runFinalizersOnExit(true)

            //android.os.Process.killProcess(android.os.Process.myPid());

     System.exit(0);

}
</code>```

Not working.

When I put finish() its closing that particular activity & its go to previous screen.

seconds one is When we exit the system need to remove SharedPreferences also?

Please help me on this...

Thanks in advance

答:
use

```<code>    moveTaskToBack(true);
</code>```

for your exit button. Though it will not kill the application.it will just move the application to background and displays the Home screen

Body:
My question is when I click the "Exit" button through our application It need to go to Phones's Home screen.I have Tried like this

  public void onExitAction(View botton){
          // finish();
          // super.finish();
           // System.runFinalizersOnExit(true)

            //android.os.Process.killProcess(android.os.Process.myPid());

     System.exit(0);

}

Not working.

When I put finish() its closing that particular activity & its go to previous screen.

seconds one is When we exit the system need to remove SharedPreferences also?

Please help me on this...

Thanks in advance

Body:
use

    moveTaskToBack(true);

for your exit button. Though it will not kill the application.it will just move the application to background and displays the Home screen


问:
Comparing timespan object if it's between hours in C#
I want to filter an array of objects. The goal is to filter the objects between two timespan objects:

```<code>  TimeSpan tsFrom = TimeSpan.Parse("16:00");
  TimeSpan tsTo = TimeSpan.Parse("00:59");
</code>```

For example I have this object:

```<code>TimeSpan dateObject = TimeSpan.Parse("22:05:22");
</code>```

The problem comes when I try to compare if the dateObject is between tsFrom and tsTo:

```<code>if (dateObject > tsFrom && dateObject < tsTo)
{
// do something ....
}
</code>```

This won't work for cases like that. Do you have any ideas how I can make this work ?

答:
The problem with this one is that you're trying to use the timeSpan method in the wrong way, if I got it right you are trying to check if the dateObject time comes between tsFrom and tsTo, the problem is that you are trying to refer to a different day with the tsTo, something that timespan can not handle.
I fixed it using dateTime to specify at least the day the time is taken from, i suggest changing the code to this</p>
```<code>        string datevalue = @"15/03/2021 16:00:00";
        DateTime start = DateTime.Parse(datevalue);

        datevalue = @"16/03/2021 00:59:00";
        DateTime end = DateTime.Parse(datevalue);

        datevalue = @"15/03/2021 22:05:22";
        DateTime obj = DateTime.Parse(datevalue);

        if (obj > start && obj < end)
        {
            //Do something
        }
</code>```

Body:
I want to filter an array of objects. The goal is to filter the objects between two timespan objects:

  TimeSpan tsFrom = TimeSpan.Parse("16:00");
  TimeSpan tsTo = TimeSpan.Parse("00:59");

For example I have this object:

TimeSpan dateObject = TimeSpan.Parse("22:05:22");

The problem comes when I try to compare if the dateObject is between tsFrom and tsTo:

if (dateObject > tsFrom && dateObject < tsTo)
{
// do something ....
}

This won't work for cases like that. Do you have any ideas how I can make this work ?

Body:
The problem with this one is that you're trying to use the timeSpan method in the wrong way, if I got it right you are trying to check if the dateObject time comes between tsFrom and tsTo, the problem is that you are trying to refer to a different day with the tsTo, something that timespan can not handle.
I fixed it using dateTime to specify at least the day the time is taken from, i suggest changing the code to this

        string datevalue = @"15/03/2021 16:00:00";
        DateTime start = DateTime.Parse(datevalue);

        datevalue = @"16/03/2021 00:59:00";
        DateTime end = DateTime.Parse(datevalue);

        datevalue = @"15/03/2021 22:05:22";
        DateTime obj = DateTime.Parse(datevalue);

        if (obj > start && obj < end)
        {
            //Do something
        }


问:
Undefined property on an object
I have a Typescript project in which I am reassigning variables depending on the value that the object contains.

What I am trying to do is define a variable from a property of the object, instead, if this property does not exist, a default value is established.

This is my Object:

```<code>interface InsParams {
  host?: string,
  country?: string,
  pageLimit?: number,
  pageOffset?: number,
  pageToken?: string
}

let dataObj: InsParams;
</code>```

This is the variable I'm creating:

```<code>let limit: number = dataObj.pageLimit ? dataObj.pageLimit : 1000
</code>```

This is the error it shows:

```<code>Error: Cannot read properties of undefined
</code>```

My problem: I need if the property does not exist to assign another value to the limit variable, but it shows an error.

答:
Here is the solution:

let limit: number = dataObj?.pageLimit ? dataObj?.pageLimit : 1000;```

Title: Undefined property on an object

Body:
I have a Typescript project in which I am reassigning variables depending on the value that the object contains.

What I am trying to do is define a variable from a property of the object, instead, if this property does not exist, a default value is established.

This is my Object:

interface InsParams {
  host?: string,
  country?: string,
  pageLimit?: number,
  pageOffset?: number,
  pageToken?: string
}

let dataObj: InsParams;

This is the variable I'm creating:

let limit: number = dataObj.pageLimit ? dataObj.pageLimit : 1000

This is the error it shows:

Error: Cannot read properties of undefined

My problem: I need if the property does not exist to assign another value to the limit variable, but it shows an error.


问:
Laravel Broadcast Doesn't Send Message
I'm having trouble with sending new messages to users. I really tried a lot of things but they didn't solve the problem. I think client successfully connected to the websocket but there is no submitted message from the socket.

Here are my codes:

channels.php

```<code>Broadcast::channel('Conversations.{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
}, ['guards' => ['web', 'auth']]);
</code>```

MessageObserver.php

```<code>class MessageObserver
{
    /**
     * Handle the ConversationMessage "created" event.
     *
     * @param  \App\Models\ConversationMessage  $conversationMessage
     * @return void
     */
    public function created(ConversationMessage $message)
    {

        $conversation = $message->conversation;

        $user = $conversation->other_user;

        $notify = [
            "to" => $user->id,
            "from" => [
                "id" => Auth::user()->id,
                "username" => Auth::user()->username,
                "name" => Auth::user()->name,
                "avatar" => Auth::user()->avatar,
            ],
            'message' => $message->message,
            'attachment' => $message->attachment,
            'attachment_mime' => $message->attachment_mime,
            "created_at" => $message->created_at,
        ];

        broadcast(new \App\Events\NewMessage($user->id, $notify));

    }

}
</code>```

App\Events\NewMessage

```<code>class NewMessage
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $message;
    public $to;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($to, Array $message)
    {

        $this->message = $message;
        $this->to = $to;

    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn(): Channel
    {

        return [new PrivateChannel('Conversations.'.$this->to)];

    }

    public function broadcastAs()
    {
        return 'messages';
    }
}
</code>```

Lastly.. Conversation.js

```<code>window.laravelEcho.private(`Conversations.${usePage().props.value.auth.user.id}`)
.listen(`messages`, (messages) => {

    console.log(messages)

})
</code>```

答:
I figured out the solution. The event class should implement Illuminate\Contracts\Broadcasting\ShouldBroadcast.

To solve my problem, i added this:

```<code>class NewMessage implements ShouldBroadcast
</code>```

Title: Laravel Broadcast Doesn't Send Message

Body:
I'm having trouble with sending new messages to users. I really tried a lot of things but they didn't solve the problem. I think client successfully connected to the websocket but there is no submitted message from the socket.

Here are my codes:

channels.php

Broadcast::channel('Conversations.{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
}, ['guards' => ['web', 'auth']]);

MessageObserver.php

class MessageObserver
{
    /**
     * Handle the ConversationMessage "created" event.
     *
     * @param  \App\Models\ConversationMessage  $conversationMessage
     * @return void
     */
    public function created(ConversationMessage $message)
    {

        $conversation = $message->conversation;

        $user = $conversation->other_user;

        $notify = [
            "to" => $user->id,
            "from" => [
                "id" => Auth::user()->id,
                "username" => Auth::user()->username,
                "name" => Auth::user()->name,
                "avatar" => Auth::user()->avatar,
            ],
            'message' => $message->message,
            'attachment' => $message->attachment,
            'attachment_mime' => $message->attachment_mime,
            "created_at" => $message->created_at,
        ];

        broadcast(new \App\Events\NewMessage($user->id, $notify));

    }

}

App\Events\NewMessage

class NewMessage
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $message;
    public $to;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($to, Array $message)
    {

        $this->message = $message;
        $this->to = $to;

    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn(): Channel
    {

        return [new PrivateChannel('Conversations.'.$this->to)];

    }

    public function broadcastAs()
    {
        return 'messages';
    }
}

Lastly.. Conversation.js

window.laravelEcho.private(`Conversations.${usePage().props.value.auth.user.id}`)
.listen(`messages`, (messages) => {

    console.log(messages)

})

Body:
I figured out the solution. The event class should implement Illuminate\Contracts\Broadcasting\ShouldBroadcast.

To solve my problem, i added this:

class NewMessage implements ShouldBroadcast


答:
Try this,</p>

```<code> logbackbtn.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        //Intent myIntent = new Intent(v.getContext(),
        //      MyTestglobe.class);
        //startActivityForResult(myIntent, 0);
        finish();
    }
});
</code>```

Title: Click "Exit" button through our Application It need to go Phones's Home page & remove SharedPreferences also

Body:
Try this,

 logbackbtn.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        //Intent myIntent = new Intent(v.getContext(),
        //      MyTestglobe.class);
        //startActivityForResult(myIntent, 0);
        finish();
    }
});


问:
KeyError in Discord.py
```<code>import discord
from discord import client
from discord.ext import commands
import random
import json
import time

class AFK(commands.Cog):
    '''
    Class containing AFK commands/system.
    '''
    def __init__(self, client, *args, **kwargs):
        self.client = client
    async def update_data(self, afk, user):
        if not f'{user.id}' in afk:
            afk[f'{user.id}'] = {}
            afk[f'{user.id}']['AFK'] = 'False'
            afk[f'{user.id}']['reason'] = 'None'

    async def time_formatter(self, seconds: float):
        '''
        Convert UNIX time to human readable time.
        '''
        minutes, seconds = divmod(int(seconds), 60)
        hours, minutes = divmod(minutes, 60)
        days, hours = divmod(hours, 24)
        tmp = ((str(days) + "d, ") if days else "") + \
            ((str(hours) + "h, ") if hours else "") + \
            ((str(minutes) + "m, ") if minutes else "") + \
            ((str(seconds) + "s, ") if seconds else "")
        return tmp[:-2]

    @commands.Cog.listener()
    async def on_message(self, message):
        with open('db/afk.json', 'r') as f:
            afk = json.load(f)

        for user_mention in message.mentions:
            if afk[f'{user_mention.id}']['AFK'] == 'True':
                if message.author.bot:
                    return

                reason = afk[f'{user_mention.id}']['reason']
                meth = int(time.time()) - int(afk[f'{user_mention.id}']['time'])
                been_afk_for = await self.time_formatter(meth)
                await message.reply(f'<:afk:925069503010832424>┃`{user_mention.name}` **ist seit __{been_afk_for}__ abwesend**: <a:news1:925069477505273946> \n> {reason}')

                meeeth = int(afk[f'{user_mention.id}']['mentions']) + 1
                afk[f'{user_mention.id}']['mentions'] = meeeth
                with open('db/afk.json', 'w') as f:
                    json.dump(afk, f)

        if not message.author.bot:
            await self.update_data(afk, message.author)

            if afk[f'{message.author.id}']['AFK'] == 'True':
                meth = int(time.time()) - int(afk[f'{message.author.id}']['time'])
                been_afk_for = await self.time_formatter(meth)
                mentionz = afk[f'{message.author.id}']['mentions']

                await message.reply(f'<:afk1:925069501433794561>┃{message.author.mention} **ist wieder da!**\n_Dein AFK-Status wurde entfernt._')

                afk[f'{message.author.id}']['AFK'] = 'False'
                afk[f'{message.author.id}']['reason'] = 'None'
                afk[f'{message.author.id}']['time'] = '0'
                afk[f'{message.author.id}']['mentions'] = 0

                with open('db/afk.json', 'w') as f:
                    json.dump(afk, f)

                try:
                    await message.author.edit(nick=f'{message.author.display_name[4:]}')
                except:
                    print(f'I wasnt able to edit [{message.author}].')

        with open('afk.json', 'w') as f:
            json.dump(afk, f)

    @commands.command()
    async def afk(self, ctx, *, reason=None):
        with open('db/afk.json', 'r') as f:
            afk = json.load(f)

        if not reason:
            reason = 'Kein Grund angegeben'

        await self.update_data(afk, ctx.message.author)
        afk[f'{ctx.author.id}']['AFK'] = 'True'
        afk[f'{ctx.author.id}']['reason'] = f'{reason}'
        afk[f'{ctx.author.id}']['time'] = int(time.time())
        afk[f'{ctx.author.id}']['mentions'] = 0

        await ctx.reply(f'<:afk:925069503010832424>┃{ctx.message.author.mention} **ist nun abwesend**: <a:news1:925069477505273946>\n> {reason}')

        with open('db/afk.json', 'w') as f:
            json.dump(afk, f)
        try:
            await ctx.author.edit(nick=f'AFK┃{ctx.author.display_name}')
        except:
            print(f'I wasnt able to edit [{ctx.message.author}].')

def setup(client):
    client.add_cog(AFK(client))
</code>```

I get if i use this code like every 10 Minutes this Error Message:

File "/home/container/cogs/afk.py", line 39, in on_message
if afk[f'{user_mention.id}']['AFK'] == 'True':
KeyError: '890990740220547072'

I tried everything to fix this but nothing seems to work. And i dont know anymore what i can do to fix that problem.

答:
The problem is the afk has no 890990740220547072 key

If key existence is not mandatory, you should change if condition to:

```<code>if f'{user_mention.id}' in afk and afk[f'{user_mention.id}'].get('AFK', False) == True:
  ...
  do something
  ...
</code>```

Also, I don't know why you using f'{user_mention.id}' instead of user_mention.id, but that means that your id will be converted to string (same as str(user_mention.id)). If your json original value is number you should use afk[user_mention.id] without conversions

Title: KeyError in Discord.py

Body:
import discord
from discord import client
from discord.ext import commands
import random
import json
import time

class AFK(commands.Cog):
    '''
    Class containing AFK commands/system.
    '''
    def __init__(self, client, *args, **kwargs):
        self.client = client
    async def update_data(self, afk, user):
        if not f'{user.id}' in afk:
            afk[f'{user.id}'] = {}
            afk[f'{user.id}']['AFK'] = 'False'
            afk[f'{user.id}']['reason'] = 'None'

    async def time_formatter(self, seconds: float):
        '''
        Convert UNIX time to human readable time.
        '''
        minutes, seconds = divmod(int(seconds), 60)
        hours, minutes = divmod(minutes, 60)
        days, hours = divmod(hours, 24)
        tmp = ((str(days) + "d, ") if days else "") + \
            ((str(hours) + "h, ") if hours else "") + \
            ((str(minutes) + "m, ") if minutes else "") + \
            ((str(seconds) + "s, ") if seconds else "")
        return tmp[:-2]

    @commands.Cog.listener()
    async def on_message(self, message):
        with open('db/afk.json', 'r') as f:
            afk = json.load(f)

        for user_mention in message.mentions:
            if afk[f'{user_mention.id}']['AFK'] == 'True':
                if message.author.bot:
                    return

                reason = afk[f'{user_mention.id}']['reason']
                meth = int(time.time()) - int(afk[f'{user_mention.id}']['time'])
                been_afk_for = await self.time_formatter(meth)
                await message.reply(f'<:afk:925069503010832424>┃`{user_mention.name}` **ist seit __{been_afk_for}__ abwesend**:  \n> {reason}')

                meeeth = int(afk[f'{user_mention.id}']['mentions']) + 1
                afk[f'{user_mention.id}']['mentions'] = meeeth
                with open('db/afk.json', 'w') as f:
                    json.dump(afk, f)

        if not message.author.bot:
            await self.update_data(afk, message.author)

            if afk[f'{message.author.id}']['AFK'] == 'True':
                meth = int(time.time()) - int(afk[f'{message.author.id}']['time'])
                been_afk_for = await self.time_formatter(meth)
                mentionz = afk[f'{message.author.id}']['mentions']

                await message.reply(f'<:afk1:925069501433794561>┃{message.author.mention} **ist wieder da!**\n_Dein AFK-Status wurde entfernt._')

                afk[f'{message.author.id}']['AFK'] = 'False'
                afk[f'{message.author.id}']['reason'] = 'None'
                afk[f'{message.author.id}']['time'] = '0'
                afk[f'{message.author.id}']['mentions'] = 0

                with open('db/afk.json', 'w') as f:
                    json.dump(afk, f)

                try:
                    await message.author.edit(nick=f'{message.author.display_name[4:]}')
                except:
                    print(f'I wasnt able to edit [{message.author}].')

        with open('afk.json', 'w') as f:
            json.dump(afk, f)

    @commands.command()
    async def afk(self, ctx, *, reason=None):
        with open('db/afk.json', 'r') as f:
            afk = json.load(f)

        if not reason:
            reason = 'Kein Grund angegeben'

        await self.update_data(afk, ctx.message.author)
        afk[f'{ctx.author.id}']['AFK'] = 'True'
        afk[f'{ctx.author.id}']['reason'] = f'{reason}'
        afk[f'{ctx.author.id}']['time'] = int(time.time())
        afk[f'{ctx.author.id}']['mentions'] = 0

        await ctx.reply(f'<:afk:925069503010832424>┃{ctx.message.author.mention} **ist nun abwesend**: \n> {reason}')

        with open('db/afk.json', 'w') as f:
            json.dump(afk, f)
        try:
            await ctx.author.edit(nick=f'AFK┃{ctx.author.display_name}')
        except:
            print(f'I wasnt able to edit [{ctx.message.author}].')

def setup(client):
    client.add_cog(AFK(client))

I get if i use this code like every 10 Minutes this Error Message:

File "/home/container/cogs/afk.py", line 39, in on_message
if afk[f'{user_mention.id}']['AFK'] == 'True':
KeyError: '890990740220547072'

I tried everything to fix this but nothing seems to work. And i dont know anymore what i can do to fix that problem.

Body:
The problem is the afk has no 890990740220547072 key

If key existence is not mandatory, you should change if condition to:

if f'{user_mention.id}' in afk and afk[f'{user_mention.id}'].get('AFK', False) == True:
  ...
  do something
  ...

Also, I don't know why you using f'{user_mention.id}' instead of user_mention.id, but that means that your id will be converted to string (same as str(user_mention.id)). If your json original value is number you should use afk[user_mention.id] without conversions


问:
Uploading to Artifactory fails sometime randomaly
As part of my CI/CD part of our pipeline is to upload artifacts to our local Artifactory server for deployment
sometimes randomly this message pops up (estimably week of no-usage) and fails the pipeline

```<code>09:23:16  [Error] Server response: 401 Unauthorized
09:23:16  {
09:23:16    "errors": [
09:23:16      {
09:23:16        "status": 401,
09:23:16        "message": "Token failed verification: expired"
09:23:16      }
09:23:16    ]
09:23:16  }
09:23:16  [Error] Server response: 401 Unauthorized
09:23:16  {
09:23:16    "errors": [
09:23:16      {
09:23:16        "status": 401,
09:23:16        "message": "Token failed verification: expired"
09:23:16      }
09:23:16    ]
09:23:16  }
</code>```

After I just login to the server and log off it goes back to the normal message:

```<code>11:07:49  [Info] Searching items to download...
11:07:49  [Info] [Thread 2] Downloading Repo/xxx.tar.gz
11:07:49  [Info] [Thread 0] Downloading Repo/yyy.tar.gz
11:07:49  [Info] [Thread 2] [2]: 206 Partial Content...
11:07:49  [Info] [Thread 0] [0]: 206 Partial Content...
11:07:49  [Info] [Thread 2] [0]: 206 Partial Content...
11:07:49  [Info] [Thread 2] [1]: 206 Partial Content...
11:07:49  [Info] [Thread 0] [1]: 206 Partial Content...
11:07:49  [Info] [Thread 0] [2]: 206 Partial Content...
11:07:49  [Info] [Thread 2] Done downloading.
11:07:49  [Info] [Thread 0] Done downloading.
11:07:49  {
11:07:49    "status": "success",
11:07:49    "totals": {
11:07:49      "success": 2,
11:07:49      "failure": 0
11:07:49    }
11:07:49  }
</code>```

I use API key from our servers to connect to the Artifactory server with jfrog-cli

Any suggestions what might make it happen?

答:
Could you please confirm if the issue is specific to the repositories that are a part of NuGet packaging by any chance and also having the anonymous access enabled for the Artifactory instance?

If yes, consider configuring the "Force authentication" for the concerned repository that is a part of this build. This should help in overcoming the reported issue.

Body:
As part of my CI/CD part of our pipeline is to upload artifacts to our local Artifactory server for deployment
sometimes randomly this message pops up (estimably week of no-usage) and fails the pipeline

09:23:16  [Error] Server response: 401 Unauthorized
09:23:16  {
09:23:16    "errors": [
09:23:16      {
09:23:16        "status": 401,
09:23:16        "message": "Token failed verification: expired"
09:23:16      }
09:23:16    ]
09:23:16  }
09:23:16  [Error] Server response: 401 Unauthorized
09:23:16  {
09:23:16    "errors": [
09:23:16      {
09:23:16        "status": 401,
09:23:16        "message": "Token failed verification: expired"
09:23:16      }
09:23:16    ]
09:23:16  }

After I just login to the server and log off it goes back to the normal message:

11:07:49  [Info] Searching items to download...
11:07:49  [Info] [Thread 2] Downloading Repo/xxx.tar.gz
11:07:49  [Info] [Thread 0] Downloading Repo/yyy.tar.gz
11:07:49  [Info] [Thread 2] [2]: 206 Partial Content...
11:07:49  [Info] [Thread 0] [0]: 206 Partial Content...
11:07:49  [Info] [Thread 2] [0]: 206 Partial Content...
11:07:49  [Info] [Thread 2] [1]: 206 Partial Content...
11:07:49  [Info] [Thread 0] [1]: 206 Partial Content...
11:07:49  [Info] [Thread 0] [2]: 206 Partial Content...
11:07:49  [Info] [Thread 2] Done downloading.
11:07:49  [Info] [Thread 0] Done downloading.
11:07:49  {
11:07:49    "status": "success",
11:07:49    "totals": {
11:07:49      "success": 2,
11:07:49      "failure": 0
11:07:49    }
11:07:49  }

I use API key from our servers to connect to the Artifactory server with jfrog-cli

Any suggestions what might make it happen?


问:
Characters appearing different from API
I am trying to work with the Amazon Associates API, but whenever trying to get the information of a product, the characters come out in a weird way.

Example

Text on the Amazon page:
 【23800 mAh

Output of the JSON from the API: ðŸ”¥ ã€23800 mAh

Just like this, more weird characters are appearing, such as a dash transformation in a question mark.

I've used a code snippet in PHP that was provided by them, which contained the following line which determined the charset:

$awsv4->addHeader('content-type', 'application/json; charset=utf-8');

Does anyone have a pointer where I might be going wrong here, and what I could do to fix this weird conversion?

答:
This line

```<code>$awsv4->addHeader('content-type', 'application/json; charset=utf-8');
</code>```

tells that the request you are sending is UTF-8 encoded and is JSON encoded data. It does not ask for a specific encoding for the response.

However the response you are getting is UTF-8 encoded

You read ðŸ”¥ ã€23800 mAh because you are displaying the received data using a encoding different from UTF-8.

A more detailed answer may be given if we see how you are writing the output and which is the context (web page, terminal...)

Title: Characters appearing different from API

Body:
This line

$awsv4->addHeader('content-type', 'application/json; charset=utf-8');

tells that the request you are sending is UTF-8 encoded and is JSON encoded data. It does not ask for a specific encoding for the response.

However the response you are getting is UTF-8 encoded

You read ðŸ”¥ ã€23800 mAh because you are displaying the received data using a encoding different from UTF-8.

A more detailed answer may be given if we see how you are writing the output and which is the context (web page, terminal...)


问:
How to test loop with jest?
I am new to jest. There is a task to test a cycle.

```<code> let values = [];
    for (let i = 1; i <= 100; i++) {
      if (i % 3 === 0 && i % 5 === 0) {
        values.push("fizzbuzz");
      } else if (i % 3 === 0) {
        values.push("fizz");
      } else if (i % 5 === 0) {
        values.push("buzz");
      } else {
        values.push("-");
      }
    }
</code>```

I did the following.

```<code>require("./fizzBuzzLoop");

describe("loop for with fizzbuzz", () => {
   let values = [];

   test("define a conditions for string values in loop", () => {
      for (let i = 1; i <= 100; i++) {
         if (i % 3 === 0 && i % 5 === 0) {
            values.push("fizzbuzz");
            expect(values).toContain("fizzbuzz");
         } else if (i % 3 === 0) {
            values.push("fizz");
            expect(values).toContain("fizz");
         } else if (i % 5 === 0) {
            values.push("buzz");
            expect(values).toContain("buzz");
         } else {
            values.push("-");
            expect(values).toContain("-");
         }
      }
   });
});
</code>```

I don't fully understand how the loop should be tested. I will be grateful for help

答:
You don't need to write a loop in the test. Wrap the action in a function, run it in the test and offer a comparison option for the result of the function.

For example:

```<code>function fizzBuzz(n=100) {
  let values = [];

  for (let i = 1; i <= n; i++) {
    if (i % 3 === 0 && i % 5 === 0) {
      values.push("fizzbuzz");
    } else if (i % 3 === 0) {
      values.push("fizz");
    } else if (i % 5 === 0) {
      values.push("buzz");
    } else {
      values.push("-");
    }
  }
  return values
}
</code>```

And the test looks like:

```<code>require("./fizzBuzzLoop");

describe("loop for with fizzbuzz", () => {
   test("define a conditions for string values in loop", () => {
      expect(fizzBuzz(15)).toEqual([ '-',
        '-',
        'fizz',
        '-',
        'buzz',
        'fizz',
        '-',
        '-',
        'fizz',
        'buzz',
        '-',
        'fizz',
        '-',
        '-',
        'fizzbuzz' ]);

   });
});
</code>```

Title: How to test loop with jest?

Body:
I am new to jest. There is a task to test a cycle.

 let values = [];
    for (let i = 1; i <= 100; i++) {
      if (i % 3 === 0 && i % 5 === 0) {
        values.push("fizzbuzz");
      } else if (i % 3 === 0) {
        values.push("fizz");
      } else if (i % 5 === 0) {
        values.push("buzz");
      } else {
        values.push("-");
      }
    }

I did the following.

require("./fizzBuzzLoop");

describe("loop for with fizzbuzz", () => {
   let values = [];

   test("define a conditions for string values in loop", () => {
      for (let i = 1; i <= 100; i++) {
         if (i % 3 === 0 && i % 5 === 0) {
            values.push("fizzbuzz");
            expect(values).toContain("fizzbuzz");
         } else if (i % 3 === 0) {
            values.push("fizz");
            expect(values).toContain("fizz");
         } else if (i % 5 === 0) {
            values.push("buzz");
            expect(values).toContain("buzz");
         } else {
            values.push("-");
            expect(values).toContain("-");
         }
      }
   });
});

I don't fully understand how the loop should be tested. I will be grateful for help

Body:
You don't need to write a loop in the test. Wrap the action in a function, run it in the test and offer a comparison option for the result of the function.

For example:

function fizzBuzz(n=100) {
  let values = [];

  for (let i = 1; i <= n; i++) {
    if (i % 3 === 0 && i % 5 === 0) {
      values.push("fizzbuzz");
    } else if (i % 3 === 0) {
      values.push("fizz");
    } else if (i % 5 === 0) {
      values.push("buzz");
    } else {
      values.push("-");
    }
  }
  return values
}

And the test looks like:

require("./fizzBuzzLoop");

describe("loop for with fizzbuzz", () => {
   test("define a conditions for string values in loop", () => {
      expect(fizzBuzz(15)).toEqual([ '-',
        '-',
        'fizz',
        '-',
        'buzz',
        'fizz',
        '-',
        '-',
        'fizz',
        'buzz',
        '-',
        'fizz',
        '-',
        '-',
        'fizzbuzz' ]);

   });
});


问:
Android - I can access ViewModel method from fragment but the method does not return the list
I recently started studying android kotlin and I am expecting this to have a very simple answer but I have a ViewModel which has a method called getDataComment and I want to call the method from my fragment and provide the needed argument for it. But when I try to call it, there's no build error, it just doesn't show the list.

My method in view model:

```<code>fun getDataComment(postId: Int) {
        PostRepository().getDataComment(postId).enqueue(object : Callback<List<Comment>>{
            override fun onResponse(call: Call<List<Comment>>, response: Response<List<Comment>>) {
                val comments = response.body()
                comments?.let {
                    mPostsComment.value = comments!!
                }
            }

            override fun onFailure(call: Call<List<Comment>>, t: Throwable) {
                Log.e(TAG, "On Failure: ${t.message}")
                t.printStackTrace()
            }
        })
    }
</code>```

Fragment Class

```<code>class PostDetailFragment : Fragment() {

    var param2: Int = 0
    private lateinit var binding: FragmentPostDetailBinding
    private val viewModel by viewModels<PostCommentViewModel>()

    private val gson: Gson by lazy {
        Gson()
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding =
            DataBindingUtil.inflate(inflater, R.layout.fragment_post_detail, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        checkArguments()
    }

     private fun checkArguments() {
        arguments?.let { bundle ->
            if (bundle.containsKey("POST")) {
                val postString = bundle.getString("POST", "")
                val post: Post = gson.fromJson(postString, Post::class.java)

                binding.postDetailstvTitle.text = post.title
                binding.postDetailstvBody.text = post.body
                param2 = post.id

                viewModel.getDataComment(param2)
            }
        }
    }
}
</code>```

Here's what it's supposed to look like: 1
Here's what I'm getting: 2

Sorry in advance if It's messy this is my first time asking here and let me know if you need more information. Thank you!

答:
observe mPostsComment inside fragment from viewmodel

```<code>override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    checkArguments()

    viewModel.mPostsComment.observe(viewLifecycleOwner, { collectionList ->
                // do whatever you want with collectionList
    })
}
</code>```

Body:
I recently started studying android kotlin and I am expecting this to have a very simple answer but I have a ViewModel which has a method called getDataComment and I want to call the method from my fragment and provide the needed argument for it. But when I try to call it, there's no build error, it just doesn't show the list.

My method in view model:

fun getDataComment(postId: Int) {
        PostRepository().getDataComment(postId).enqueue(object : Callback<List<Comment>>{
            override fun onResponse(call: Call<List<Comment>>, response: Response<List<Comment>>) {
                val comments = response.body()
                comments?.let {
                    mPostsComment.value = comments!!
                }
            }

            override fun onFailure(call: Call<List<Comment>>, t: Throwable) {
                Log.e(TAG, "On Failure: ${t.message}")
                t.printStackTrace()
            }
        })
    }

Fragment Class

class PostDetailFragment : Fragment() {

    var param2: Int = 0
    private lateinit var binding: FragmentPostDetailBinding
    private val viewModel by viewModels<PostCommentViewModel>()

    private val gson: Gson by lazy {
        Gson()
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding =
            DataBindingUtil.inflate(inflater, R.layout.fragment_post_detail, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        checkArguments()
    }

     private fun checkArguments() {
        arguments?.let { bundle ->
            if (bundle.containsKey("POST")) {
                val postString = bundle.getString("POST", "")
                val post: Post = gson.fromJson(postString, Post::class.java)

                binding.postDetailstvTitle.text = post.title
                binding.postDetailstvBody.text = post.body
                param2 = post.id

                viewModel.getDataComment(param2)
            }
        }
    }
}

Here's what it's supposed to look like: 1
Here's what I'm getting: 2

Sorry in advance if It's messy this is my first time asking here and let me know if you need more information. Thank you!

Body:
observe mPostsComment inside fragment from viewmodel

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    checkArguments()

    viewModel.mPostsComment.observe(viewLifecycleOwner, { collectionList ->
                // do whatever you want with collectionList
    })
}


问:
Class instance can't see a function it refers to
I have this module containing a class definition and instantiation, like so:

```<code>class TestClass:
    def __init__(self, name):
        self.name = name
    def func(self, count):
        count = test_func(count)
        return count

my_inst = TestClass('my_inst')
</code>```

Note that TestClass.func refers to a function (test_func) that is not in the module. Then, I open a notebook where that function is defined and import the TestClass and its instance, my_inst. The count variable is also defined in the notebook, so the code in it looks as follows:

```<code>from test_module import *

count = 0

def test_func(count):
    count += 1
    return count
</code>```

Then, I try to run the my_inst.func(count) method...

```<code>for _ in range(10):
    count = my_inst.func(count)
</code>```

...and get a NameError: name 'test_func' is not defined.

What seems to be the problem here? Why doesn't the class instance see the test_func in the notebook? How can I make it see it?

答:
You need to import test_func within the file in which TestClass is defined. You're doing the opposite (i.e., you're importing TestClass within the file in which test_func is defined), which is wrong and will never work.

File test_function.py:

```<code>count = 0

def test_func(count):
    count += 1
    return count
</code>```

File test_class.py:

```<code>from test_function import test_func

class TestClass:
    def __init__(self, name):
        self.name = name
    def func(self, count):
        count = test_func(count)
        return count

my_inst = TestClass('my_inst')
</code>```

Now you can import everything you need in your notebook.

Body:
I have this module containing a class definition and instantiation, like so:

class TestClass:
    def __init__(self, name):
        self.name = name
    def func(self, count):
        count = test_func(count)
        return count

my_inst = TestClass('my_inst')

Note that TestClass.func refers to a function (test_func) that is not in the module. Then, I open a notebook where that function is defined and import the TestClass and its instance, my_inst. The count variable is also defined in the notebook, so the code in it looks as follows:

from test_module import *

count = 0

def test_func(count):
    count += 1
    return count

Then, I try to run the my_inst.func(count) method...

for _ in range(10):
    count = my_inst.func(count)

...and get a NameError: name 'test_func' is not defined.

What seems to be the problem here? Why doesn't the class instance see the test_func in the notebook? How can I make it see it?

Body:
You need to import test_func within the file in which TestClass is defined. You're doing the opposite (i.e., you're importing TestClass within the file in which test_func is defined), which is wrong and will never work.

File test_function.py:

count = 0

def test_func(count):
    count += 1
    return count

File test_class.py:

from test_function import test_func

class TestClass:
    def __init__(self, name):
        self.name = name
    def func(self, count):
        count = test_func(count)
        return count

my_inst = TestClass('my_inst')

Now you can import everything you need in your notebook.


问:
WebView crashing my app with VALIDATION_ERROR_DESERIALIZATION_FAILED
I'm loading a small angular webapp in a webview. I don't have control or any info of the app other than the webpacked bundle.

At an exact point in the web app, my whole Android app crashes with the following logs:

```<code>08-22 09:13:33.980 29145-29191/com.my.app E/chromium: [ERROR:validation_errors.cc(87)] Invalid message: VALIDATION_ERROR_DESERIALIZATION_FAILED
08-22 09:13:33.981 29145-29191/com.my.app E/chromium: [ERROR:render_process_host_impl.cc(4399)] Terminating render process for bad Mojo message: Received bad user message: Validation failed for SynchronousCompositorControlHost::ReturnFrame deserializer [VALIDATION_ERROR_DESERIALIZATION_FAILED]
    [ERROR:bad_message.cc(25)] Terminating renderer for bad IPC message, reason 123
08-22 10:05:25.284 18717-18717/mx.tide.fiuanalyticsapp E/chromium: [ERROR:aw_browser_terminator.cc(86)] Render process (18816) kill (OOM or update) wasn't handed by all associated webviews, killing application.
</code>```

I haven't found anything on the web other than the chromium source code where the errors are defined, I have no clue how to debug this problem as there is no problem while opening the web app directly on mobile Chrome browser.

So, have any of you idea of what this error could be? Or at least a lead for where could I start debugging the problem?

答:
use this solution</p>
```<code>        webView.webViewClient = object : WebViewClient() {
            override fun onRenderProcessGone(
                view: WebView?,
                detail: RenderProcessGoneDetail?
            ): Boolean {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
                    if (detail?.didCrash() == false) {
                        webView.loadUrl(url)
                        return true
                    }
                return false
            }
        }
</code>```

Body:
I'm loading a small angular webapp in a webview. I don't have control or any info of the app other than the webpacked bundle.

At an exact point in the web app, my whole Android app crashes with the following logs:

08-22 09:13:33.980 29145-29191/com.my.app E/chromium: [ERROR:validation_errors.cc(87)] Invalid message: VALIDATION_ERROR_DESERIALIZATION_FAILED
08-22 09:13:33.981 29145-29191/com.my.app E/chromium: [ERROR:render_process_host_impl.cc(4399)] Terminating render process for bad Mojo message: Received bad user message: Validation failed for SynchronousCompositorControlHost::ReturnFrame deserializer [VALIDATION_ERROR_DESERIALIZATION_FAILED]
    [ERROR:bad_message.cc(25)] Terminating renderer for bad IPC message, reason 123
08-22 10:05:25.284 18717-18717/mx.tide.fiuanalyticsapp E/chromium: [ERROR:aw_browser_terminator.cc(86)] Render process (18816) kill (OOM or update) wasn't handed by all associated webviews, killing application.

I haven't found anything on the web other than the chromium source code where the errors are defined, I have no clue how to debug this problem as there is no problem while opening the web app directly on mobile Chrome browser.

So, have any of you idea of what this error could be? Or at least a lead for where could I start debugging the problem?

Body:
use this solution

        webView.webViewClient = object : WebViewClient() {
            override fun onRenderProcessGone(
                view: WebView?,
                detail: RenderProcessGoneDetail?
            ): Boolean {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
                    if (detail?.didCrash() == false) {
                        webView.loadUrl(url)
                        return true
                    }
                return false
            }
        }


问:
Can't use go tool pprof with an existing server
I have an existing http server which I would like to profile. I have included _ "net/http/pprof"to my imports, and I already have http server running:

```<code>router := createRouter()
server := &http.Server {
    Addr:           ":8080",
    Handler:        router,
    ReadTimeout:    15*time.Second,
    WriteTimeout:   15*time.Second,
//  MaxHeaderBytes: 4096,
}

log.Fatal(server.ListenAndServe())
</code>```

When I'm trying to access http://localhost:8080/debug/pprof/ I get 404 page not found.

That's what I get when using go tool pprof on a local machine:

```<code>userver@userver:~/Desktop/gotest$ go tool pprof http://192.168.0.27:8080/
Use of uninitialized value $prefix in concatenation (.) or string at /usr/lib/go/pkg/tool/linux_amd64/pprof line 3019.
Read http://192.168.0.27:8080/pprof/symbol
Failed to get the number of symbols from http://192.168.0.27:8080/pprof/symbol

userver@userver:~/Desktop/gotest$ go tool pprof http://localhost:8080/debug/pprof/profile
Read http://localhost:8080/debug/pprof/symbol
Failed to get the number of symbols from http://localhost:8080/debug/pprof/symbol
</code>```

Same for a remote client:

```<code>MacBookAir:~ apple$ go tool pprof http://192.168.0.27:8080/
Use of uninitialized value $prefix in concatenation (.) or string at /usr/local/Cellar/go/1.3.2/libexec/pkg/tool/darwin_amd64/pprof line 3027.
Read http://192.168.0.27:8080/pprof/symbol
Failed to get the number of symbols from http://192.168.0.27:8080/pprof/symbol
</code>```

答:
Here's how to use pprof in combination with Gorilla mux. To avoid HTTP 404 errors we need to explicitly specify the route for /debug/pprof/{cmd} because Gorilla doesn't do prefix routing:

```<code>router := mux.NewRouter()
router.Handle("/debug/pprof/", http.HandlerFunc(pprof.Index))
router.Handle("/debug/pprof/cmdline", http.HandlerFunc(pprof.Cmdline))
router.Handle("/debug/pprof/profile", http.HandlerFunc(pprof.Profile))
router.Handle("/debug/pprof/symbol", http.HandlerFunc(pprof.Symbol))
router.Handle("/debug/pprof/trace", http.HandlerFunc(pprof.Trace))
router.Handle("/debug/pprof/{cmd}", http.HandlerFunc(pprof.Index)) // special handling for Gorilla mux

err := http.ListenAndServe("127.0.0.1:9999", router)
log.Errorf("pprof server listen failed: %v", err) // note: http.ListenAndServe never returns nil
</code>```

Body:
I have an existing http server which I would like to profile. I have included _ "net/http/pprof"to my imports, and I already have http server running:

router := createRouter()
server := &http.Server {
    Addr:           ":8080",
    Handler:        router,
    ReadTimeout:    15*time.Second,
    WriteTimeout:   15*time.Second,
//  MaxHeaderBytes: 4096,
}

log.Fatal(server.ListenAndServe())

When I'm trying to access http://localhost:8080/debug/pprof/ I get 404 page not found.

That's what I get when using go tool pprof on a local machine:

userver@userver:~/Desktop/gotest$ go tool pprof http://192.168.0.27:8080/
Use of uninitialized value $prefix in concatenation (.) or string at /usr/lib/go/pkg/tool/linux_amd64/pprof line 3019.
Read http://192.168.0.27:8080/pprof/symbol
Failed to get the number of symbols from http://192.168.0.27:8080/pprof/symbol

userver@userver:~/Desktop/gotest$ go tool pprof http://localhost:8080/debug/pprof/profile
Read http://localhost:8080/debug/pprof/symbol
Failed to get the number of symbols from http://localhost:8080/debug/pprof/symbol

Same for a remote client:

MacBookAir:~ apple$ go tool pprof http://192.168.0.27:8080/
Use of uninitialized value $prefix in concatenation (.) or string at /usr/local/Cellar/go/1.3.2/libexec/pkg/tool/darwin_amd64/pprof line 3027.
Read http://192.168.0.27:8080/pprof/symbol
Failed to get the number of symbols from http://192.168.0.27:8080/pprof/symbol

Body:
Here's how to use pprof in combination with Gorilla mux. To avoid HTTP 404 errors we need to explicitly specify the route for /debug/pprof/{cmd} because Gorilla doesn't do prefix routing:

router := mux.NewRouter()
router.Handle("/debug/pprof/", http.HandlerFunc(pprof.Index))
router.Handle("/debug/pprof/cmdline", http.HandlerFunc(pprof.Cmdline))
router.Handle("/debug/pprof/profile", http.HandlerFunc(pprof.Profile))
router.Handle("/debug/pprof/symbol", http.HandlerFunc(pprof.Symbol))
router.Handle("/debug/pprof/trace", http.HandlerFunc(pprof.Trace))
router.Handle("/debug/pprof/{cmd}", http.HandlerFunc(pprof.Index)) // special handling for Gorilla mux

err := http.ListenAndServe("127.0.0.1:9999", router)
log.Errorf("pprof server listen failed: %v", err) // note: http.ListenAndServe never returns nil


问:
Is there a Perl module to monitor an email queue?
I'm working on an issue tracking system and would like the application to handle email replies.  That is, I would like a script that can monitor an email queue and perform some action based on the email contents.  It should then be able to delete the email, etc.

I currently use MIME::Lite to send email, and I can handle writing the script etc. (read: I'm not new to Perl).  However, I have no idea what modules are good for doing this particular task.  I'd like to get started on this as quickly as possible so I hope to narrow my search space for possible modules.

In case you need to know, the application will be running on a standard linux, Perl, MySQL stack with Exchange as the mail server.

Can anyone suggest a Perl module to help me out?  Any tutorials or best practices related to this would also be helpful.

Thanks!

答:
Do you have access to the Exchange server via IMAP or WebDAV?

For IMAP:

Mail::IMAPClient

IMAP::Client

Net::IMAP::Client

Email::Folder::IMAP

For WebDAV:

Email::Folder::Exchange

POP3 would also be an option if it's enabled on the server.  IMAP is probably the way to go if you've got it.

OwnerDisplayName: James van Dyke

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: brian d foy

OwnerDisplayName: Mark Johnson

LastEditorDisplayName: Mark Johnson


问:
How to Add Custom Option in MS Word File Menu by Office Addin using manifest.xml
How can we add a custom option in "File Menu/Tab" by custom "Office Addin"?

I can find how to add "Control" in an office tab using "ExtensionPoint". But I am unable to find how can we add a custom option in "File Menu". Following are the documentation links I have gone through.

https://learn.microsoft.com/en-us/office/dev/add-ins/reference/manifest/extensionpoint

https://learn.microsoft.com/en-us/office/dev/add-ins/reference/manifest/officetab

image 1:

image 2:

答:
The Backstage UI can't be customized with web add-ins. See Add-in commands for Excel, PowerPoint, and Word for more information about possible customizations.

Feature requests on Tech Community are considered, when the dev team go through the planning process. Use the github label: “Type: product feature request” at https://aka.ms/M365dev-suggestions .

FYI these customizations are possible using COM add-ins, so you may also consider creating a VSTO based add-in instead, see Walkthrough: Create your first VSTO Add-in for Outlook.


问:
During state change in React, is it possible to append values to URL
I was wondering, if, on state change, I can add something like this to URL

www.abc.com/?state=on

without page reloading.

答:
You can use History.replaceState() in useEffect to change url when state changing

```<code>useEffect(() => {
    window.history.replaceState(
        history.state,
        null,
        `?state=${state}`
    );
}, [state]);
</code>```

Body:
You can use History.replaceState() in useEffect to change url when state changing

useEffect(() => {
    window.history.replaceState(
        history.state,
        null,
        `?state=${state}`
    );
}, [state]);


问:
Android build error: Unable to load 'javax.xml.bind.jaxbexception
I am a beginner in Android. I am not able to resolve this error in Android Studio. Whenever I run my application this error occurs. How do I fix it?

Error: Unable to load class 'javax.xml.bind.JAXBException' Possible
causes for this unexpected error include:

Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.) Re-download dependencies and sync
project (requires network)

The state of a Gradle build process (daemon) may be corrupt. Stopping all Gradle daemons may solve this problem. Stop Gradle build
processes (requires restart)

Your project may be using a third-party plugin which is not compatible with the other plugins in the project or the version of
Gradle requested by the project.

In the case of corrupt Gradle processes, you can also try closing the IDE and then killing all Java processes.

答: Just upgrade the Gradle version then it will fix the problem</p>


问:
Tried using Python flask to make data sent from HTML <form> a tuple to match selected data from a MySQL table if exit, but something went wrong
```<code>// SELECT
myDatabaseCursor.execute("SELECT username, password FROM member")
myDatabase.commit()

// get data from form to make a tuple
userCheck = (request.form["signInUsername"], request.form["signInPassword"])

// iterate selected data tuple into a list
results = []
for selectedData in myDatabaseCursor:
    results.append(selectedData)

// check if there is a match in MySQL database
if userCheck in results:
    session["status"]="logged"
    session["user_name"]=request.form["signInUsername"]
    return redirect("/member")
else:
    return redirect("/error/?message=wrong username or password")
</code>```

When I ran my server and tried typing in the username and the right password, successfully logged in; tried typing in the username and the wrong password, which, didn't have any match in the database, got rejected logging in. ALL GOOD...

BUT, when I tried typing in the username and the wrong password, which, HAS A MATCH IN THE PASSWORD COLUMN THOUGH DOESN'T BELONG TO THE RIGHT USERNAME, still successfully logged in.

I am really confused now, hope you guys have any idea about this situation.

Thanks, appreciate your replies.

答:
You could change your query to support WHERE clause. Something along the lines of:

```<code># get data from form to make a tuple
username, password = (
    request.form["signInUsername"],
    request.form["signInPassword"]
)

# SELECT
myDatabaseCursor.execute(
    """
        SELECT username, password
        FROM member
        WHERE username = '{username}' AND password = '{password}'
    """.format(username=username, password=password)
)

myDatabase.commit()

# set userCheck to True or False if the myDatabaseCursor result is not empty..
# TODO

# if row was in returned table
if userCheck:
    session["status"]="logged"
    session["user_name"]=request.form["signInUsername"]
    return redirect("/member")
else:
    return redirect("/error/?message=wrong username or password")
</code>```

Body:
// SELECT
myDatabaseCursor.execute("SELECT username, password FROM member")
myDatabase.commit()

// get data from form to make a tuple
userCheck = (request.form["signInUsername"], request.form["signInPassword"])

// iterate selected data tuple into a list
results = []
for selectedData in myDatabaseCursor:
    results.append(selectedData)

// check if there is a match in MySQL database
if userCheck in results:
    session["status"]="logged"
    session["user_name"]=request.form["signInUsername"]
    return redirect("/member")
else:
    return redirect("/error/?message=wrong username or password")

When I ran my server and tried typing in the username and the right password, successfully logged in; tried typing in the username and the wrong password, which, didn't have any match in the database, got rejected logging in. ALL GOOD...

BUT, when I tried typing in the username and the wrong password, which, HAS A MATCH IN THE PASSWORD COLUMN THOUGH DOESN'T BELONG TO THE RIGHT USERNAME, still successfully logged in.

I am really confused now, hope you guys have any idea about this situation.

Thanks, appreciate your replies.

Body:
You could change your query to support WHERE clause. Something along the lines of:

# get data from form to make a tuple
username, password = (
    request.form["signInUsername"],
    request.form["signInPassword"]
)

# SELECT
myDatabaseCursor.execute(
    """
        SELECT username, password
        FROM member
        WHERE username = '{username}' AND password = '{password}'
    """.format(username=username, password=password)
)

myDatabase.commit()

# set userCheck to True or False if the myDatabaseCursor result is not empty..
# TODO

# if row was in returned table
if userCheck:
    session["status"]="logged"
    session["user_name"]=request.form["signInUsername"]
    return redirect("/member")
else:
    return redirect("/error/?message=wrong username or password")


问:
No serializer found for class org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor and no properties discovered to create BeanSerializer
I am using Spring Boot with Spring Data JPA. However, when I try to retrieve data from my Repository, the following error is thrown:

```<code>Type definition error: [simple type, class org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: com.example.model.Pokemon$HibernateProxy$DuUnG9om[\"hibernateLazyInitializer\"])
</code>```

Most of the "duplicates" I see have relationships, but my Pokemon class does not. Is there something that I am missing?

My Pokemon class is a simple POJO class:

```<code>package com.example.model;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Pokemon implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = -2228784815938588107L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    private String name;
    private Double attack, defense, speed;

    public Pokemon() {

    }

    public Pokemon(int id, String name, double attack, double defense, double speed) {
        super();
        this.id = id;
        this.name = name;
        this.attack = attack;
        this.defense = defense;
        this.speed = speed;
    }

    // Getters and setters
}
</code>```

答:
What solved this issue for me was using
jackson-datatype-hibernate5
and registering this module in objectmapper</p>

Body:
I am using Spring Boot with Spring Data JPA. However, when I try to retrieve data from my Repository, the following error is thrown:

Type definition error: [simple type, class org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: com.example.model.Pokemon$HibernateProxy$DuUnG9om[\"hibernateLazyInitializer\"])

Most of the "duplicates" I see have relationships, but my Pokemon class does not. Is there something that I am missing?

My Pokemon class is a simple POJO class:

package com.example.model;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Pokemon implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = -2228784815938588107L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    private String name;
    private Double attack, defense, speed;

    public Pokemon() {

    }

    public Pokemon(int id, String name, double attack, double defense, double speed) {
        super();
        this.id = id;
        this.name = name;
        this.attack = attack;
        this.defense = defense;
        this.speed = speed;
    }

    // Getters and setters
}


问:
Vim: How to change the highlight color for search hits and quickfix selection
I am using the desert colorscheme, which uses white text on orange background for highlighting search hits. The same pattern is used for the selected entry in the quickfix window.

White on orange is not very readable. How do I change that in .vimrc?

Edit: Thanks for the fast reply, for the desert scheme I am now using the following search highlight modification:

```<code>highlight Search guibg='Purple' guifg='NONE'
</code>```

Purple is quite easy to detect visually and it is IMHO not used for syntax coloring in the desert scheme.

答:
Look at $VIMRUNTIME/colors/desert.vim.  Color mappings are defined there with the hi[ghlight] command.  The search highlighting is defined as

```<code>hi Search guibg=peru guifg=wheat
</code>```

for the GUI and

```<code>hi Search cterm=NONE ctermfg=grey ctermbg=blue
</code>```

for terminals.

You can override this setting in your .vimrc using the same command after you select your colorscheme.  Type :h hi for help.

Body:
I am using the desert colorscheme, which uses white text on orange background for highlighting search hits. The same pattern is used for the selected entry in the quickfix window.

White on orange is not very readable. How do I change that in .vimrc?

Edit: Thanks for the fast reply, for the desert scheme I am now using the following search highlight modification:

highlight Search guibg='Purple' guifg='NONE'

Purple is quite easy to detect visually and it is IMHO not used for syntax coloring in the desert scheme.

Body:
Look at $VIMRUNTIME/colors/desert.vim.  Color mappings are defined there with the hi[ghlight] command.  The search highlighting is defined as

hi Search guibg=peru guifg=wheat

for the GUI and

hi Search cterm=NONE ctermfg=grey ctermbg=blue

for terminals.

You can override this setting in your .vimrc using the same command after you select your colorscheme.  Type :h hi for help.