问:
Fitting a Logistic Curve to Data
I would like to fit a logaritmic function to some data with scipy.

Unfortunatley I get the following error: Covariance of the parameters could not be estimated

How can I prevent this?

import numpy as np
import scipy.optimize as opt
import matplotlib.pyplot as plt

x = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0]
y = [0.073, 2.521, 15.879, 48.365, 72.68, 90.298, 92.111, 93.44, 93.439, 93.389, 93.381, 93.367, 93.94, 93.269, 96.376]

def f(x, a, b, c, d):
    return a / (1. + np.exp(-c * (x - d))) + b

(a_, b_, c_, d_), _ = opt.curve_fit(f, x, y)

y_fit = f(x, a_, b_, c_, d_)
fig, ax = plt.subplots(1, 1, figsize=(6, 4))
ax.plot(x, y, 'o')
ax.plot(x, y_fit, '-')
```

答:
Here is a graphical fitter with your data and equation, using scipy's Differential Evolution genetic algorithm to make initial parameter estimates. The scipy implementation uses the Latin Hypercube algorithm to ensure a thorough search of parameter space, which requires bounds within which to search - as you can see from the code, those ranges can be generous and it is much easier to come up with ranges for the initial parameter estimates than to give specific values.

```<code>import numpy, scipy, matplotlib
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy.optimize import differential_evolution
import warnings

xData = numpy.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0])
yData = numpy.array([0.073, 2.521, 15.879, 48.365, 72.68, 90.298, 92.111, 93.44, 93.439, 93.389, 93.381, 93.367, 93.94, 93.269, 96.376])

def func(x, a, b, c, d):
    return a / (1.0 + numpy.exp(-c * (x - d))) + b

# function for genetic algorithm to minimize (sum of squared error)
def sumOfSquaredError(parameterTuple):
    warnings.filterwarnings("ignore") # do not print warnings by genetic algorithm
    val = func(xData, *parameterTuple)
    return numpy.sum((yData - val) ** 2.0)

def generate_Initial_Parameters():
    parameterBounds = []
    parameterBounds.append([0.0, 100.0]) # search bounds for a
    parameterBounds.append([-10.0, 0.0]) # search bounds for b
    parameterBounds.append([0.0, 10.0]) # search bounds for c
    parameterBounds.append([0.0, 10.0]) # search bounds for d

    # "seed" the numpy random number generator for repeatable results
    result = differential_evolution(sumOfSquaredError, parameterBounds, seed=3)
    return result.x

# by default, differential_evolution completes by calling curve_fit() using parameter bounds
geneticParameters = generate_Initial_Parameters()

# now call curve_fit without passing bounds from the genetic algorithm,
# just in case the best fit parameters are aoutside those bounds
fittedParameters, pcov = curve_fit(func, xData, yData, geneticParameters)
print('Fitted parameters:', fittedParameters)
print()

modelPredictions = func(xData, *fittedParameters)

absError = modelPredictions - yData

SE = numpy.square(absError) # squared errors
MSE = numpy.mean(SE) # mean squared errors
RMSE = numpy.sqrt(MSE) # Root Mean Squared Error, RMSE
Rsquared = 1.0 - (numpy.var(absError) / numpy.var(yData))

print()
print('RMSE:', RMSE)
print('R-squared:', Rsquared)

print()

##########################################################
# graphics output section
def ModelAndScatterPlot(graphWidth, graphHeight):
    f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)
    axes = f.add_subplot(111)

    # first the raw data as a scatter plot
    axes.plot(xData, yData,  'D')

    # create data for the fitted equation plot
    xModel = numpy.linspace(min(xData), max(xData))
    yModel = func(xModel, *fittedParameters)

    # now the model as a line plot
    axes.plot(xModel, yModel)

    axes.set_xlabel('X Data') # X axis data label
    axes.set_ylabel('Y Data') # Y axis data label

    plt.show()
    plt.close('all') # clean up after using pyplot

graphWidth = 800
graphHeight = 600
ModelAndScatterPlot(graphWidth, graphHeight)
</code>```

Title: Fitting a Logistic Curve to Data

Body:
Here is a graphical fitter with your data and equation, using scipy's Differential Evolution genetic algorithm to make initial parameter estimates. The scipy implementation uses the Latin Hypercube algorithm to ensure a thorough search of parameter space, which requires bounds within which to search - as you can see from the code, those ranges can be generous and it is much easier to come up with ranges for the initial parameter estimates than to give specific values.

import numpy, scipy, matplotlib
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy.optimize import differential_evolution
import warnings

xData = numpy.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0])
yData = numpy.array([0.073, 2.521, 15.879, 48.365, 72.68, 90.298, 92.111, 93.44, 93.439, 93.389, 93.381, 93.367, 93.94, 93.269, 96.376])

def func(x, a, b, c, d):
    return a / (1.0 + numpy.exp(-c * (x - d))) + b

# function for genetic algorithm to minimize (sum of squared error)
def sumOfSquaredError(parameterTuple):
    warnings.filterwarnings("ignore") # do not print warnings by genetic algorithm
    val = func(xData, *parameterTuple)
    return numpy.sum((yData - val) ** 2.0)

def generate_Initial_Parameters():
    parameterBounds = []
    parameterBounds.append([0.0, 100.0]) # search bounds for a
    parameterBounds.append([-10.0, 0.0]) # search bounds for b
    parameterBounds.append([0.0, 10.0]) # search bounds for c
    parameterBounds.append([0.0, 10.0]) # search bounds for d

    # "seed" the numpy random number generator for repeatable results
    result = differential_evolution(sumOfSquaredError, parameterBounds, seed=3)
    return result.x

# by default, differential_evolution completes by calling curve_fit() using parameter bounds
geneticParameters = generate_Initial_Parameters()

# now call curve_fit without passing bounds from the genetic algorithm,
# just in case the best fit parameters are aoutside those bounds
fittedParameters, pcov = curve_fit(func, xData, yData, geneticParameters)
print('Fitted parameters:', fittedParameters)
print()

modelPredictions = func(xData, *fittedParameters)

absError = modelPredictions - yData

SE = numpy.square(absError) # squared errors
MSE = numpy.mean(SE) # mean squared errors
RMSE = numpy.sqrt(MSE) # Root Mean Squared Error, RMSE
Rsquared = 1.0 - (numpy.var(absError) / numpy.var(yData))

print()
print('RMSE:', RMSE)
print('R-squared:', Rsquared)

print()

##########################################################
# graphics output section
def ModelAndScatterPlot(graphWidth, graphHeight):
    f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)
    axes = f.add_subplot(111)

    # first the raw data as a scatter plot
    axes.plot(xData, yData,  'D')

    # create data for the fitted equation plot
    xModel = numpy.linspace(min(xData), max(xData))
    yModel = func(xModel, *fittedParameters)

    # now the model as a line plot
    axes.plot(xModel, yModel)

    axes.set_xlabel('X Data') # X axis data label
    axes.set_ylabel('Y Data') # Y axis data label

    plt.show()
    plt.close('all') # clean up after using pyplot

graphWidth = 800
graphHeight = 600
ModelAndScatterPlot(graphWidth, graphHeight)


来源: stackexchange

问:
In d3 selection method chaining, how can I reference the values of the selected element?
I have a simple horizontal bar chart, and I'm trying to place an image to the left of each horizontal bar to serve as a label for the bar.

At this point in the script, the bars have been created and are displayed.

I've taken a code sample for adding the labels to the right of the bars (which are included in the image) and tried to update it to place an image to the left.

```<code>    bars.append("image")
        .attr("class", "bar_image")
        //y position of the image is halfway down the bar
        .attr("y", function(d){
            return y(d.Candidate) + y.rangeBand() / 2 + 4;
        })
        //x position to left of bar
        .attr("x", function(d) {
            return -10;
        })
        .attr('xlink:href', function(d){
            return "/static/images/yang.png";
        })
</code>```

My understanding here is that I'm selecting each of the 'bar' elements and appending an image (which is the same image for all right now while I work on placement).

I'm setting the y attribute of the image element to midrange of each y range. This is how the label on the right has its y attr set. x, for now I'm just setting to left of the bar. Then I set the actual href to the image.

My problem now has to do with SIZING the image, and I'd like to be able to set its height/width dynamically based on the height of the 'bar' elements. These heights are obviously dependent on how many bars there are (this graph should scale up or down to any number of people)

Obviously the positioning isn't perfect, but for now I'd just be happy being able to resize the height/width attributes of the image based on the height of the bars in the chart.

Is there a way to reference in the selection and method chaining the attributes of the elements being selected?

Thanks for any help.

答:
Not exactly what I was looking for, but I can set the

```<code>attr("height", x)
</code>```

of the image element using the same function that sets the height attribute of the bars

```<code>.attr("height", y.rangeBand())
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a simple horizontal bar chart, and I'm trying to place an image to the left of each horizontal bar to serve as a label for the bar.

At this point in the script, the bars have been created and are displayed.

I've taken a code sample for adding the labels to the right of the bars (which are included in the image) and tried to update it to place an image to the left.

    bars.append("image")
        .attr("class", "bar_image")
        //y position of the image is halfway down the bar
        .attr("y", function(d){
            return y(d.Candidate) + y.rangeBand() / 2 + 4;
        })
        //x position to left of bar
        .attr("x", function(d) {
            return -10;
        })
        .attr('xlink:href', function(d){
            return "/static/images/yang.png";
        })

My understanding here is that I'm selecting each of the 'bar' elements and appending an image (which is the same image for all right now while I work on placement).

I'm setting the y attribute of the image element to midrange of each y range. This is how the label on the right has its y attr set. x, for now I'm just setting to left of the bar. Then I set the actual href to the image.

My problem now has to do with SIZING the image, and I'd like to be able to set its height/width dynamically based on the height of the 'bar' elements. These heights are obviously dependent on how many bars there are (this graph should scale up or down to any number of people)

Obviously the positioning isn't perfect, but for now I'd just be happy being able to resize the height/width attributes of the image based on the height of the bars in the chart.

Is there a way to reference in the selection and method chaining the attributes of the elements being selected?

Thanks for any help.

Body:
Not exactly what I was looking for, but I can set the

attr("height", x)

of the image element using the same function that sets the height attribute of the bars

.attr("height", y.rangeBand())


问:
Android: UnitTest
Need some advice. I have an App. And I need do write some UnitTest. But I really don't know what to test. I already test Settings and all preferences, that's easy. What else usually people test ? Lets say that I have 3 Activities. Main one is list activity, when you click on list item its forward you on a second List Activity...and on list item click its forward you on third Activity. I think maybe I should test the switching between activities ? How to simulate click on list item in UnitTest and how to check that activity was open or not ? Thanks !</p>

答:
Android provides test classes for you to be able to be as exhaustive in your unit testing as you want to be.
You can unit test your java components, your android-architecture dependant components, and your workflow as a whole.

In your case, to test sequences between activities, you can use the InstrumentationTestCase class and extend it, and then in your tests, you should use the following methods:

```<code>// Prepare a monitor for your activity
Instrumentation instrumentation = getInstrumentation()
Instrumentation.ActivityMonitor monitor = instrumentation.addMonitor(YourClass.class.getName(), null, false);

// Start your activity manually
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClassName(instrumentation.getTargetContext(), YourClass.class.getName());
        instrumentation.startActivitySync(intent);

// Get the started Activity
Activity currentActivity = getInstrumentation().waitForMonitor(monitor);
</code>```

Then you can remove the monitor and add another monitor for the next activity you expect to catch in the workflow sequence. With this sequence you can programatically interact and verify sequences of actions that go through multiple activities.

ContentLicense: CC BY-SA 3.0

Title: Android: UnitTest

Body:
Android provides test classes for you to be able to be as exhaustive in your unit testing as you want to be.
You can unit test your java components, your android-architecture dependant components, and your workflow as a whole.

In your case, to test sequences between activities, you can use the InstrumentationTestCase class and extend it, and then in your tests, you should use the following methods:

// Prepare a monitor for your activity
Instrumentation instrumentation = getInstrumentation()
Instrumentation.ActivityMonitor monitor = instrumentation.addMonitor(YourClass.class.getName(), null, false);

// Start your activity manually
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClassName(instrumentation.getTargetContext(), YourClass.class.getName());
        instrumentation.startActivitySync(intent);

// Get the started Activity
Activity currentActivity = getInstrumentation().waitForMonitor(monitor);

Then you can remove the monitor and add another monitor for the next activity you expect to catch in the workflow sequence. With this sequence you can programatically interact and verify sequences of actions that go through multiple activities.


问:
Will my app update automatically or will user need to update the app when the code is updated?
I am creating a weather app and want to give local warnings to people through an app. I want to be able to give up to date warnings, but I am wondering: does updating information in Xcode get automatically pushed to the devices or will it need an update every time I put new information in?</p>

答:
If I understand your question correctly - you have an app, which warns people about some unexpected weather conditions?

You basically have two options:

Do a code push to your app every time you do a change. This is not supported by default in Swift and Xcode, and can only be done via some third-party integration or framework (e.g. React Native), and is generally a hard thing to implement.

Setup a back-end server and link it with your app, so the new information is downloaded from this back-end server dynamically.

The only suitable and easy thing to do for your use case seems to be option 2.


问:
Extracting data from one text file to another using a batch file
Recently I've been having problems with my internet connection. In order to find the problem in the chain I looked into some code I found online. I have never written code for a batch-file before, so just go ahead and expect me to know barrely anything. Anyway, I played around with it a bit and found out what each of the lines does.. to an extend at least. Now the results I'm getting from that file are included below as well. What I want to do is write a seperate file which I can run that takes the results from the first file and filters them into a new textfile.

I've already dug through some of the examples I've found here, but I don't simply want to copy paste (not that such a solution would work... I tried so I could reverse engineer it, but to no avail). I found some examples of how to get data from a file using a FOR and a FOREACH-Object, but it makes very little sense to me and I can't get it to work.

In short, I would like the pinging data that's placed in the first text file to be filtered by a batch file so it only sends part of the text to the new text file. Is anything like this possible and if so how do I go about this? Some explanation about how it works would be great as I like to take code apart and play around with it.

The code I use to get the pinging data whenever a connection fault is detected is listed below. I'm not saying it works perfectly mainly because I'm not 100% on how the %SystemRoot%-part works... But so far every time it triggers it also finds a request timeout. I'm open for suggestions to improve this but I would like for the focus to be on the noted challenge of extracting from one file and sending it to another.

```<code>:Loop
::Starting up the loop

PING -n 5 127.0.0.1 > NUL
::Set the ping delay

set Address=google.com
::Set the address to ping to google.com

%SystemRoot%\system32\ping.exe -n 1 %Address%|%SystemRoot%\system32\find.exe "TTL=" > NUL
::Check the connection

if %ERRORLEVEL% EQU 0 goto Loop
::If no error, return to Loop
::So if error, continue to next statement

echo Pinging %Address% >> D:\pingtest\Test\logfiletest.log
::Echo the pinging action

echo Trace route %Address% at %date% %time% >>
D:\pingtest\Test\logfiletest.log
::Echo the route to trace and the timestamp

tracert %Address% >> D:\pingtest\Test\logfiletest.log
::Echo the pinging and results

echo. >> D:\pingtest\Test\logfiletest.log
::Nextline

goto Loop
::Return to Loop
</code>```

These are the results I'm getting that I'm trying to filter into the new file.

```<code>Pinging google.com
Trace route google.com at Fri 05/24/2019 10:22:40.92
Tracing route to google.com [172.217.168.238]

over a maximum of 30 hops:
1    <1 ms    <1 ms    <1 ms  MyLocation
2    13 ms    12 ms    13 ms  195.190.228.150
3     *        *        *     Request timed out.
4     7 ms    10 ms     8 ms  139.156.127.75
5     7 ms     8 ms     9 ms  108.170.241.193
6    15 ms    18 ms    17 ms  72.14.238.245
7     8 ms     7 ms     7 ms  ams16s31-in-f14.1e100.net [172.217.19.206]

Trace complete.
</code>```

So that is the result I am currently getting from the batch-file that I made after looking at the suggested code for another issue. Now what I would like to see something along the lines of the following

```<code>Trace route google.com at Fri 05/24/2019 10:22:40.92
3     *        *        *     Request timed out.
5     7 ms     8 ms     9 ms  108.170.241.193
</code>```

I'm taking rows 3 and 5 as examples because they often return a 'Request timed out'

答:
The quick and dirty solution to this, assuming you already have a large logfile of items to go through, is to make a new batch file to filter the results.

When hardcoded, this is really simple however if you ever want dynamic results you'll need to heavily modify this.

```<code>for /f "tokens=1,*" %%i in (logfile.log) do (
    if "%%i"=="Trace" echo %%i %%j >> shortlog.log
    if "%%i"=="3" echo %%i %%j >> shortlog.log
    if "%%i"=="5" echo %%i %%j >> shortlog.log
)
</code>```

This outputs

```<code>Trace route google.com at Fri 05/24/2019 10:22:40.92
3     *        *        *     Request timed out.
5     7 ms     8 ms     9 ms  108.170.241.193
Trace complete.
</code>```

If you want to remove the last line, you can change your original code from

echo Trace route %Address% at %date% %time% >> D:\pingtest\Test\logfiletest.log

to

echo #Trace route %Address% at %date% %time% >> D:\pingtest\Test\logfiletest.log

and change my code to

if "%%i"=="#Trace" echo %%i %%j >> shortlog.log

Body:
Recently I've been having problems with my internet connection. In order to find the problem in the chain I looked into some code I found online. I have never written code for a batch-file before, so just go ahead and expect me to know barrely anything. Anyway, I played around with it a bit and found out what each of the lines does.. to an extend at least. Now the results I'm getting from that file are included below as well. What I want to do is write a seperate file which I can run that takes the results from the first file and filters them into a new textfile.

I've already dug through some of the examples I've found here, but I don't simply want to copy paste (not that such a solution would work... I tried so I could reverse engineer it, but to no avail). I found some examples of how to get data from a file using a FOR and a FOREACH-Object, but it makes very little sense to me and I can't get it to work.

In short, I would like the pinging data that's placed in the first text file to be filtered by a batch file so it only sends part of the text to the new text file. Is anything like this possible and if so how do I go about this? Some explanation about how it works would be great as I like to take code apart and play around with it.

The code I use to get the pinging data whenever a connection fault is detected is listed below. I'm not saying it works perfectly mainly because I'm not 100% on how the %SystemRoot%-part works... But so far every time it triggers it also finds a request timeout. I'm open for suggestions to improve this but I would like for the focus to be on the noted challenge of extracting from one file and sending it to another.

:Loop
::Starting up the loop

PING -n 5 127.0.0.1 > NUL
::Set the ping delay

set Address=google.com
::Set the address to ping to google.com

%SystemRoot%\system32\ping.exe -n 1 %Address%|%SystemRoot%\system32\find.exe "TTL=" > NUL
::Check the connection

if %ERRORLEVEL% EQU 0 goto Loop
::If no error, return to Loop
::So if error, continue to next statement

echo Pinging %Address% >> D:\pingtest\Test\logfiletest.log
::Echo the pinging action

echo Trace route %Address% at %date% %time% >>
D:\pingtest\Test\logfiletest.log
::Echo the route to trace and the timestamp

tracert %Address% >> D:\pingtest\Test\logfiletest.log
::Echo the pinging and results

echo. >> D:\pingtest\Test\logfiletest.log
::Nextline

goto Loop
::Return to Loop

These are the results I'm getting that I'm trying to filter into the new file.

Pinging google.com
Trace route google.com at Fri 05/24/2019 10:22:40.92
Tracing route to google.com [172.217.168.238]

over a maximum of 30 hops:
1    <1 ms    <1 ms    <1 ms  MyLocation
2    13 ms    12 ms    13 ms  195.190.228.150
3     *        *        *     Request timed out.
4     7 ms    10 ms     8 ms  139.156.127.75
5     7 ms     8 ms     9 ms  108.170.241.193
6    15 ms    18 ms    17 ms  72.14.238.245
7     8 ms     7 ms     7 ms  ams16s31-in-f14.1e100.net [172.217.19.206]

Trace complete.

So that is the result I am currently getting from the batch-file that I made after looking at the suggested code for another issue. Now what I would like to see something along the lines of the following

Trace route google.com at Fri 05/24/2019 10:22:40.92
3     *        *        *     Request timed out.
5     7 ms     8 ms     9 ms  108.170.241.193

I'm taking rows 3 and 5 as examples because they often return a 'Request timed out'

Body:
The quick and dirty solution to this, assuming you already have a large logfile of items to go through, is to make a new batch file to filter the results.

When hardcoded, this is really simple however if you ever want dynamic results you'll need to heavily modify this.

for /f "tokens=1,*" %%i in (logfile.log) do (
    if "%%i"=="Trace" echo %%i %%j >> shortlog.log
    if "%%i"=="3" echo %%i %%j >> shortlog.log
    if "%%i"=="5" echo %%i %%j >> shortlog.log
)

This outputs

Trace route google.com at Fri 05/24/2019 10:22:40.92
3     *        *        *     Request timed out.
5     7 ms     8 ms     9 ms  108.170.241.193
Trace complete.

If you want to remove the last line, you can change your original code from

echo Trace route %Address% at %date% %time% >> D:\pingtest\Test\logfiletest.log

to

echo #Trace route %Address% at %date% %time% >> D:\pingtest\Test\logfiletest.log

and change my code to

if "%%i"=="#Trace" echo %%i %%j >> shortlog.log


问:
Not setting headers for request
I have an Angular 7 app and an API in Java Spring with JTW. The app must at each request in the API send the token, but this is not happening, and so all requests return the 401 error.

app modules

```<code>     ...

        @NgModule

({
      declarations: [
        AppComponent,
        PatientComponent,
        HeaderComponent,
        FooterComponent,
        AlertComponent,
        NotFoundComponent,
        UserRegisterComponent,
        LoginComponent,
        AuthGuardComponent
      ],
      imports: [
        BrowserModule,
        FormsModule,
        NgSelectModule,
        ReactiveFormsModule,
        HttpClientModule,
        AppRoutingModule,
        NgbModule,
      ],
      providers: [
        {
          provide : HTTP_INTERCEPTORS,
          useClass: AuthInterceptor,
          multi   : true,
        },
      ],
      bootstrap: [AppComponent]
    })

    export class AppModule {

    }
</code>```

AuthInterceptor

```<code>import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { GeneralService } from '../_service/general.service';
import { Observable } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    constructor(private generalService: GeneralService) {

    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        req = req.clone({
            setHeaders: {
                Authorization: 'Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyIiwic2NvcGVzIjpbeyJhdXRob3JpdHkiOiJTeXN0ZW0gVXNlciJ9XSwiaXNzIjoiaHR0cHM6Ly9hcGkubmVvZ3JpZC5jb20vIiwiaWF0IjoxNTU4OTgwOTAxLCJleHAiOjE1NTg5OTg5MDF9.vZByXryTI-1wGLYY1bU8DurOF15qlxA7QkdMW5UeM8c')
            }
        });

       console.log(req);
       return next.handle(req);
    }
}
</code>```

Request

```<code>listAll() {
     return this.http.get('http://localhost:8080/api/listAll');
}

async get() {
    let error = null;

    let response = await this.listAll()
    .toPromise()
    .catch(error => error = error);

    console.log(response);
  }
</code>```

Result of console.log(req);

Looks like okay, the authorization and the token is there

The request

Dont pass the token here :c

Erros

OPTIONS 401 Access to XMLHttpRequest
  at'http://localhost:4200' has been blocked by CORS policy: Response to
  preflight request doesn't pass access control check: It does not have
  HTTP ok status.

I done the  same request with insonmia (passed Authorization and the token) e all is okay, the problem is with the angular request.

答:
Thanks for the comments, I was able to formulate a solution, I modified my WebSecurityConfig.java api file, the problem was not the angular requests.
Thanks to all.</p>

```<code>@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private ParametersProperties parameters;

    @Resource(name = "userService")
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtAuthenticationEntryPoint unauthorizedHandler;

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService)
                .passwordEncoder(encoder());
    }

    @Bean
    public JwtAuthenticationFilter authenticationTokenFilterBean() {
        return new JwtAuthenticationFilter();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable().
                authorizeRequests()
                .antMatchers(
                         "/swagger-resources/**",
                         "/swagger-ui.html",
                         "/webjars/**",
                         "/h2/**",
                         "/auth/signin",
                ).permitAll()
                /* the saver is the line below*/
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http
                .addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class)
                .headers().frameOptions().sameOrigin();
    }

    @Bean
    public BCryptPasswordEncoder encoder(){
        return new BCryptPasswordEncoder();
    }
}
</code>```

Title: Not setting headers for request

Body:
I have an Angular 7 app and an API in Java Spring with JTW. The app must at each request in the API send the token, but this is not happening, and so all requests return the 401 error.

app modules

     ...

        @NgModule

({
      declarations: [
        AppComponent,
        PatientComponent,
        HeaderComponent,
        FooterComponent,
        AlertComponent,
        NotFoundComponent,
        UserRegisterComponent,
        LoginComponent,
        AuthGuardComponent
      ],
      imports: [
        BrowserModule,
        FormsModule,
        NgSelectModule,
        ReactiveFormsModule,
        HttpClientModule,
        AppRoutingModule,
        NgbModule,
      ],
      providers: [
        {
          provide : HTTP_INTERCEPTORS,
          useClass: AuthInterceptor,
          multi   : true,
        },
      ],
      bootstrap: [AppComponent]
    })

    export class AppModule {

    }

AuthInterceptor

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { GeneralService } from '../_service/general.service';
import { Observable } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    constructor(private generalService: GeneralService) {

    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        req = req.clone({
            setHeaders: {
                Authorization: 'Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyIiwic2NvcGVzIjpbeyJhdXRob3JpdHkiOiJTeXN0ZW0gVXNlciJ9XSwiaXNzIjoiaHR0cHM6Ly9hcGkubmVvZ3JpZC5jb20vIiwiaWF0IjoxNTU4OTgwOTAxLCJleHAiOjE1NTg5OTg5MDF9.vZByXryTI-1wGLYY1bU8DurOF15qlxA7QkdMW5UeM8c')
            }
        });

       console.log(req);
       return next.handle(req);
    }
}

Request

listAll() {
     return this.http.get('http://localhost:8080/api/listAll');
}

async get() {
    let error = null;

    let response = await this.listAll()
    .toPromise()
    .catch(error => error = error);

    console.log(response);
  }

Result of console.log(req);

Looks like okay, the authorization and the token is there

The request

Dont pass the token here :c

Erros

OPTIONS 401 Access to XMLHttpRequest
  at'http://localhost:4200' has been blocked by CORS policy: Response to
  preflight request doesn't pass access control check: It does not have
  HTTP ok status.

I done the  same request with insonmia (passed Authorization and the token) e all is okay, the problem is with the angular request.

Body:
Thanks for the comments, I was able to formulate a solution, I modified my WebSecurityConfig.java api file, the problem was not the angular requests.
Thanks to all.

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private ParametersProperties parameters;

    @Resource(name = "userService")
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtAuthenticationEntryPoint unauthorizedHandler;

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService)
                .passwordEncoder(encoder());
    }

    @Bean
    public JwtAuthenticationFilter authenticationTokenFilterBean() {
        return new JwtAuthenticationFilter();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable().
                authorizeRequests()
                .antMatchers(
                         "/swagger-resources/**",
                         "/swagger-ui.html",
                         "/webjars/**",
                         "/h2/**",
                         "/auth/signin",
                ).permitAll()
                /* the saver is the line below*/
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http
                .addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class)
                .headers().frameOptions().sameOrigin();
    }

    @Bean
    public BCryptPasswordEncoder encoder(){
        return new BCryptPasswordEncoder();
    }
}


问:
Global variable is not defined propperly [ PYTHON 3 ]
Got the error:
 File "labpm3.py", line 37, in child

```<code>print("I'm child pid:", os.getpid(), "my next bro is:", nextS)
</code>```

NameError: name 'nextS' is not defined.

I would like to know what should I do to define properly the global variable, thank you in advance for the feedback

```<code>import os, time, sys, signal

children = []

count = 0

def parent(nc, numiter):
    nextS = os.getppid()
    i = 0
    while i < nc:
        i+= 1
        newpid = os.fork()
        if newpid == 0:
            child(i)
        else:
            nextS = newpid
            children.append(nextS)

    i = 0
    while i < numiter:
        os.kill(nextS, signal.SIGALRM)
        time.sleep(1)
        signal.signal(signal.SIGALRM, handler_parent)
        i+=1
    i = 0
    while i < nc:
        os.kill(children[i], signal.SIGUSR1)
        (pid, sts) = os.waitpid(children[i], 0)
        print(pid, os.WEXITSTATUS(sts))
        i+=1

def child(number):
    global nextS
    global count
    print("I'm child pid:", os.getpid(), "my next bro is:", nextS)
    signal.signal(signal.SIGALRM, handler)
    signal.signal(signal.SIGUSR1, handler2)
    while True:
        time.sleep(10)

def handler(signum, frame):
    global nextS
    global count
    count += 1
    print("I'm child pid:", os.getpid(), "sending signal to:", nextS)
    os.kill(nextsibl, signal.SIGALRM)

def handler2(signum, frame):
    global nextS
    global count
    sys.exit(count)

def handler_parent(signum, frame):
    global count
    global nextS

try:
    numchild = int(sys.argv[1])
    numiter = int(sys.argv[2])
except:
   print ('First parameter must be a number', sys.argv[1])
   print ('Second parameter must be a number', sys.argv[2])
</code>```

parent(numchild,numiter)

答:
First, you should define the variable outside the method. For example:

```<code>c = 0 # global variable

def add():
    global c
    c = c + 2 # increment by 2
    print("Inside add():", c)

add()
print("In main:", c)
</code>```

Output:

```<code>Inside add(): 2
In main: 2
</code>```

For more look at https://www.programiz.com/python-programming/global-keyword

Body:
Got the error:
 File "labpm3.py", line 37, in child

print("I'm child pid:", os.getpid(), "my next bro is:", nextS)

NameError: name 'nextS' is not defined.

I would like to know what should I do to define properly the global variable, thank you in advance for the feedback

import os, time, sys, signal

children = []

count = 0

def parent(nc, numiter):
    nextS = os.getppid()
    i = 0
    while i < nc:
        i+= 1
        newpid = os.fork()
        if newpid == 0:
            child(i)
        else:
            nextS = newpid
            children.append(nextS)

    i = 0
    while i < numiter:
        os.kill(nextS, signal.SIGALRM)
        time.sleep(1)
        signal.signal(signal.SIGALRM, handler_parent)
        i+=1
    i = 0
    while i < nc:
        os.kill(children[i], signal.SIGUSR1)
        (pid, sts) = os.waitpid(children[i], 0)
        print(pid, os.WEXITSTATUS(sts))
        i+=1

def child(number):
    global nextS
    global count
    print("I'm child pid:", os.getpid(), "my next bro is:", nextS)
    signal.signal(signal.SIGALRM, handler)
    signal.signal(signal.SIGUSR1, handler2)
    while True:
        time.sleep(10)

def handler(signum, frame):
    global nextS
    global count
    count += 1
    print("I'm child pid:", os.getpid(), "sending signal to:", nextS)
    os.kill(nextsibl, signal.SIGALRM)

def handler2(signum, frame):
    global nextS
    global count
    sys.exit(count)

def handler_parent(signum, frame):
    global count
    global nextS

try:
    numchild = int(sys.argv[1])
    numiter = int(sys.argv[2])
except:
   print ('First parameter must be a number', sys.argv[1])
   print ('Second parameter must be a number', sys.argv[2])

parent(numchild,numiter)

Body:
First, you should define the variable outside the method. For example:

c = 0 # global variable

def add():
    global c
    c = c + 2 # increment by 2
    print("Inside add():", c)

add()
print("In main:", c)

Output:

Inside add(): 2
In main: 2

For more look at https://www.programiz.com/python-programming/global-keyword


问:
recursively read in csv files and perform calculation on two files
I have a list of files I would like to import, perform a calculation and save the result.

I have a few folders labeled as follows:

2005, 2006, 2007... 2018.

The files are saved as:

file_2005.csv, file_2006.csv, file_2007.csv... file_2018.csv.

(one file per folder)

I am trying to write a function which will do the following:

read in file_2005.csv and file_2006.csv from folder 2005 and 2006 respectively.

perform some cleaning, processing and some calculations on these 2 datasets.

save the results.

-- read in file_2006.csv and now file_2007.csv from folder 2006 and 2007.
-- perform the same calculations as before.
-- save the results.

--- read in file_2007.csv and file_2008.csv from folder 2007 and 2008.

--- perform same calculations

--- save the results.

etc...

So I would like to know how I can recursively créate such a function which essentially reads in all the data and processes the results.

When I read in all of the years together I obtain memory issues.

答:
List the files

```<code>LF <- list.files(path="Years",pattern=".csv",full.names=T,recursive=T)
</code>```

Create a data.frame with two columns - 1 with all years less the last, and the other with all columns less the first

```<code>data <- data.frame(V1=LF[-c(length(LF))])
data$V2 <- LF[-c(1)]
</code>```

Then split into list of data frames by row

```<code>li <- split(data, seq(nrow(data)))
</code>```

Then read in both files in each row (i.e. one year in column 1 and the next in col 2. Do this using lapply, where you can also apply the function f(x) and write the csv outputs. I have used sprintf to customise the file names

```<code>RF <- lapply(li, function(x) {
  dat1 <- read.csv(as.character(x$V1))
  dat2 <- read.csv(as.character(x$V2))
  ndat1 <- f(dat1)
  ndat2 <- f(dat2)
  write.csv (ndat1, sprintf("new_%s",x$V1))
  write.csv (ndat2, sprintf("new_%s",x$V2))
})

</code>```

Body:
List the files

LF <- list.files(path="Years",pattern=".csv",full.names=T,recursive=T)

Create a data.frame with two columns - 1 with all years less the last, and the other with all columns less the first

data <- data.frame(V1=LF[-c(length(LF))])
data$V2 <- LF[-c(1)]

Then split into list of data frames by row

li <- split(data, seq(nrow(data)))

Then read in both files in each row (i.e. one year in column 1 and the next in col 2. Do this using lapply, where you can also apply the function f(x) and write the csv outputs. I have used sprintf to customise the file names

RF <- lapply(li, function(x) {
  dat1 <- read.csv(as.character(x$V1))
  dat2 <- read.csv(as.character(x$V2))
  ndat1 <- f(dat1)
  ndat2 <- f(dat2)
  write.csv (ndat1, sprintf("new_%s",x$V1))
  write.csv (ndat2, sprintf("new_%s",x$V2))
})


问:
Group By Multiple Columns Separately
I know that you can use the GROUP BY keyword to group by multiple columns, but here's what I'm trying to do:

```<code>Table: Codes

user_id    day_of_week    id
------------------------------
  1          T             1
  1          W             2
  1          W             3
  2          F             4
  2          F             5
  2          M             6
</code>```

And I am trying to find a command to output to get this:

```<code>Table: Codes

user_id    day_of_week    count(*)
-------------------------------------
  1          T              1
  1          W              2
  2          F              2
  2          M              1
</code>```

So as you can see, it's grouping by the day of the week and the user_id Can someone help me achieve this with MySQL?

答:
You can use multiple columns in GROUP BY clause:

```<code>SELECT user_id, day_of_week, COUNT(*) AS cnt
FROM Codes
GROUP BY user_id, day_of_week
</code>```

Title: Group By Multiple Columns Separately

Body:
I know that you can use the GROUP BY keyword to group by multiple columns, but here's what I'm trying to do:

Table: Codes

user_id    day_of_week    id
------------------------------
  1          T             1
  1          W             2
  1          W             3
  2          F             4
  2          F             5
  2          M             6

And I am trying to find a command to output to get this:

Table: Codes

user_id    day_of_week    count(*)
-------------------------------------
  1          T              1
  1          W              2
  2          F              2
  2          M              1

So as you can see, it's grouping by the day of the week and the user_id Can someone help me achieve this with MySQL?

Body:
You can use multiple columns in GROUP BY clause:

SELECT user_id, day_of_week, COUNT(*) AS cnt
FROM Codes
GROUP BY user_id, day_of_week


问:
Why am I getting NullPointer Exception in this Android project
I am a beginner in FireBase database. I wrote this code for retrieving user data after authentication. The authentication part is working well but the data retrieving part is crashing my app with this error.

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference

at com.kcw.firebasebasics.UserInterface$1.onDataChange(UserInterface.java:58)

  at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@17.0.0:75)

  at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@17.0.0:63)

  at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@17.0.0:55)

  at android.os.Handler.handleCallback(Handler.java:739)

  at android.os.Handler.dispatchMessage(Handler.java:95)

Here is the code that I wrote and I wrote a comment on line 58 (the line causing error) to identify it.

```<code>FirebaseUser firebaseUser;
DatabaseReference reference;
TextView greeting;
String name,text;

protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_user_interface);
    firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
    reference = FirebaseDatabase.getInstance().getReference()
                                .child(firebaseUser.getUid());
    greeting = findViewById(R.id.greet_msg);

    reference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                String text = dataSnapshot.getValue().toString();//line 58

            try {
                JSONObject object = new JSONObject(text);
                name = object.getString("username");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            String message = "WELCOME ";
            message = message + name.toUpperCase();
            greeting.setText(message);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
</code>```

Help me resolve this.

I verified whether there is any null object in my database and I didn't find any.

I also tried making all my String variables global but that didn't work either

And finally a picture of my database after registering users.

link to database screenshot

答:
You have wrong path in the database reference, it should be under users node :

```<code>reference = FirebaseDatabase.getInstance().getReference()
    .child("users").child(firebaseUser.getUid());
greeting = findViewById(R.id.greet_msg);

reference.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        if(dataSnapshot.exist()) {
          String text = dataSnapshot.getValue().toString();//line 58

          try {
            JSONObject object = new JSONObject(text);
            name = object.getString("username");
          } catch (JSONException e) {
            e.printStackTrace();
          }
          String message = "WELCOME ";
          message = message + name.toUpperCase();
          greeting.setText(message);
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
});
</code>```

Body:
I am a beginner in FireBase database. I wrote this code for retrieving user data after authentication. The authentication part is working well but the data retrieving part is crashing my app with this error.

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference

at com.kcw.firebasebasics.UserInterface$1.onDataChange(UserInterface.java:58)

  at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@17.0.0:75)

  at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@17.0.0:63)

  at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@17.0.0:55)

  at android.os.Handler.handleCallback(Handler.java:739)

  at android.os.Handler.dispatchMessage(Handler.java:95)

Here is the code that I wrote and I wrote a comment on line 58 (the line causing error) to identify it.

FirebaseUser firebaseUser;
DatabaseReference reference;
TextView greeting;
String name,text;

protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_user_interface);
    firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
    reference = FirebaseDatabase.getInstance().getReference()
                                .child(firebaseUser.getUid());
    greeting = findViewById(R.id.greet_msg);

    reference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                String text = dataSnapshot.getValue().toString();//line 58

            try {
                JSONObject object = new JSONObject(text);
                name = object.getString("username");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            String message = "WELCOME ";
            message = message + name.toUpperCase();
            greeting.setText(message);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

Help me resolve this.

I verified whether there is any null object in my database and I didn't find any.

I also tried making all my String variables global but that didn't work either

And finally a picture of my database after registering users.

link to database screenshot

Body:
You have wrong path in the database reference, it should be under users node :

reference = FirebaseDatabase.getInstance().getReference()
    .child("users").child(firebaseUser.getUid());
greeting = findViewById(R.id.greet_msg);

reference.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        if(dataSnapshot.exist()) {
          String text = dataSnapshot.getValue().toString();//line 58

          try {
            JSONObject object = new JSONObject(text);
            name = object.getString("username");
          } catch (JSONException e) {
            e.printStackTrace();
          }
          String message = "WELCOME ";
          message = message + name.toUpperCase();
          greeting.setText(message);
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
});


问:
React - to manipulate DOM or use state?
This Is more of a "theoretical" question that often buffles me in different situations and use cases, I will give a simple example to demonstrate it.

Let's say I have a list of 10 buttons.
Everrytime I click a button, a floating menu appears on top of the clicked button - there is only one menu visible for any given time.
Let's assume that I can't render this floating menu within the button component and I can only render it in the buttons parent level (meaning that this menu is sibling to those buttons).

I have 2 possible options to do that:

Keep the  x,y position of the last clicked button and render the menu in this given position

Render the menu once and using "ref" to directly relocate the menu

On the one hand, the first approach seems more "Reactish". On the other hand, the possible implemention I can think of is pretty ugly (capturing the clicked item position and saving it to state which triggers defender), and further more, I am not so sure about re re rendering the whole container just because I need to move a small piece of it.

The second approach touches the DOM directly using refs. Although possible , doing DOM manipulations sometimes feel bad to me.

Is there a better approach? Which of the 2 makes more sense?

Any suggestion or thoughts will be appreciated!
Thanks

答:
React uses whats called a virtual DOM, which is a representation of the DOM,  that sits on top of the real browser DOM. Whenever you update state or a user performs an action the virtual DOM compares and checks the changes with the real DOM and then updates the UI accordingly.

So if certain DOM elements like a  are not different between changes it does not get re rendered, only the DOM elements that have changed are re rendered. And if a property on a DOM element is changed, only the property is updated and the DOM element is not re rendered.

```<code><div color="blue" />
</code>```

to

```<code><div color="red" />
</code>```

The whole element is not destroyed and re created, only the property is changed.

However if the element in the host tree is different than the entire host tree is destroyed and recreated.

```<code><div />
</code>```

to

```<code><p>
</code>```

This is refereed to as reconciliation
https://reactjs.org/docs/reconciliation.html

So using refs is definitely more of a hacky solution since its more of an escape hatch and directly manipulates the DOM.

I would definitely stick with option 1, I think there is an elegant solution to the use case you described, it would involve just adding a click event listener in the componentDidMount and keeping track of the click position that way.

And also its hard to say without code but since your buttons will be the same, they will not be re rendered only the menu will.

Would recommend for further reading
https://overreacted.io/react-as-a-ui-runtime/

Title: React - to manipulate DOM or use state?

Body:
React uses whats called a virtual DOM, which is a representation of the DOM,  that sits on top of the real browser DOM. Whenever you update state or a user performs an action the virtual DOM compares and checks the changes with the real DOM and then updates the UI accordingly.

So if certain DOM elements like a  are not different between changes it does not get re rendered, only the DOM elements that have changed are re rendered. And if a property on a DOM element is changed, only the property is updated and the DOM element is not re rendered.

<div color="blue" />

to

<div color="red" />

The whole element is not destroyed and re created, only the property is changed.

However if the element in the host tree is different than the entire host tree is destroyed and recreated.

<div />

to

<p>

This is refereed to as reconciliation
https://reactjs.org/docs/reconciliation.html

So using refs is definitely more of a hacky solution since its more of an escape hatch and directly manipulates the DOM.

I would definitely stick with option 1, I think there is an elegant solution to the use case you described, it would involve just adding a click event listener in the componentDidMount and keeping track of the click position that way.

And also its hard to say without code but since your buttons will be the same, they will not be re rendered only the menu will.

Would recommend for further reading
https://overreacted.io/react-as-a-ui-runtime/


问:
How to store a reference in boost::variant<T> instead of copying the object?
Suppose I have a boost::variant defined as boost::variant<Point, Line, Circle> shape. Now if I make an object of the Point class, Point p and store it in shape as shape = p what I'm doing here is making a copy of p. How do I actually store a reference to p such that when I call boost::apply_visitior(visitor, shape) the visitor mutates not just the Point stored in the variant but also p itself?

答:
```<code>boost::variant<Point*, Line*, Circle*>
</code>```

then

```<code>shape = &p;
</code>```

then have your visitor overload on pointers.

Body:
boost::variant<Point*, Line*, Circle*>

then

shape = &p;

then have your visitor overload on pointers.


问:
openGL lighting rotates with camera
I'm trying to build something simple for uni coursework and I've just tried to light it, but the lights seem to rotate with the camera, which is totally annoying...

I've pasted my code below using a pastebin (so that it doesn't stretch the page), but here's a little explanation too:

I added the lights in Display::Init (using the PoolLight class).
The camera is set up in Display::Resize. It's placed above the 'pool table' at (0, 0, 80), looking down (0, 0, -1), with the X axis being forward/up (1, 0, 0).

This simple movement and rotation of the camera adjusts the lights too, but not the geometry (or perhaps it adjusts the geometry, and not the lights, I'm not really sure).

I have read some of the other answers here concerning the same issue, but I don't really understand too well. I'm hoping someone can explain it to me in simpler terms, or maybe spot something obvious that I've accidentally excluded.

Anyway, here is the code:

Main Display Class

PoolLight Class:

```<code>#include "PoolLight.h"
#include "Glut/glut.h"
#include "GL/gl.h"
#include "GL/glu.h"

PoolLight::PoolLight(GLenum lightNumber, GLenum lightType, float red, float green, float blue, bool distant, float posX, float posY, float posZ)
{
    this->lightNumber = lightNumber;
    this->lightType = lightType;

    color[0] = red; color[1] = green; color[2] = blue; color[3] = 1;
    position[0] = posX; position[1] = posY; position[2] = posZ; position[3] = (int) (!distant);
    glLightfv(lightNumber, lightType, color);
    glLightfv(lightNumber, GL_POSITION, position);

    enabled(true);
}

PoolLight::~PoolLight(void)
{
}

void PoolLight::setSpotlight(float angle, float attenuation, float dirX, float dirY, float dirZ) {
    glLightf(lightNumber, GL_SPOT_EXPONENT, angle);
    glLightf(lightNumber, GL_CONSTANT_ATTENUATION, attenuation);
    glLightf(lightNumber, GL_LINEAR_ATTENUATION, 0.0f);
    glLightf(lightNumber, GL_QUADRATIC_ATTENUATION, 0.0f);
    spotDirection[0] = dirX; spotDirection[1] = dirY; spotDirection[2] = dirZ;
    glLightfv(lightNumber, GL_SPOT_DIRECTION, spotDirection);
    glLightf(lightNumber, GL_SPOT_CUTOFF, 60);
}

void PoolLight::enabled(bool enabled) {
    if (enabled) glEnable(lightNumber);
    else glDisable(lightNumber);
}
</code>```

答: After changing the camera position, call glLightfv(lightNumber, GL_POSITION, position) again with the world-coordinates of the light.  Then draw the scene.

Title: openGL lighting rotates with camera

Body:
I'm trying to build something simple for uni coursework and I've just tried to light it, but the lights seem to rotate with the camera, which is totally annoying...

I've pasted my code below using a pastebin (so that it doesn't stretch the page), but here's a little explanation too:

I added the lights in Display::Init (using the PoolLight class).
The camera is set up in Display::Resize. It's placed above the 'pool table' at (0, 0, 80), looking down (0, 0, -1), with the X axis being forward/up (1, 0, 0).

This simple movement and rotation of the camera adjusts the lights too, but not the geometry (or perhaps it adjusts the geometry, and not the lights, I'm not really sure).

I have read some of the other answers here concerning the same issue, but I don't really understand too well. I'm hoping someone can explain it to me in simpler terms, or maybe spot something obvious that I've accidentally excluded.

Anyway, here is the code:

Main Display Class

PoolLight Class:

#include "PoolLight.h"
#include "Glut/glut.h"
#include "GL/gl.h"
#include "GL/glu.h"

PoolLight::PoolLight(GLenum lightNumber, GLenum lightType, float red, float green, float blue, bool distant, float posX, float posY, float posZ)
{
    this->lightNumber = lightNumber;
    this->lightType = lightType;

    color[0] = red; color[1] = green; color[2] = blue; color[3] = 1;
    position[0] = posX; position[1] = posY; position[2] = posZ; position[3] = (int) (!distant);
    glLightfv(lightNumber, lightType, color);
    glLightfv(lightNumber, GL_POSITION, position);

    enabled(true);
}

PoolLight::~PoolLight(void)
{
}

void PoolLight::setSpotlight(float angle, float attenuation, float dirX, float dirY, float dirZ) {
    glLightf(lightNumber, GL_SPOT_EXPONENT, angle);
    glLightf(lightNumber, GL_CONSTANT_ATTENUATION, attenuation);
    glLightf(lightNumber, GL_LINEAR_ATTENUATION, 0.0f);
    glLightf(lightNumber, GL_QUADRATIC_ATTENUATION, 0.0f);
    spotDirection[0] = dirX; spotDirection[1] = dirY; spotDirection[2] = dirZ;
    glLightfv(lightNumber, GL_SPOT_DIRECTION, spotDirection);
    glLightf(lightNumber, GL_SPOT_CUTOFF, 60);
}

void PoolLight::enabled(bool enabled) {
    if (enabled) glEnable(lightNumber);
    else glDisable(lightNumber);
}


问:
Is it possible to use a SPI flash chip with a arduino (Atmega328p)
Is it possible to use an SPI flash chip with a minimum sector erase size of 4KB with an Atmega 328p (2KB of internal RAM)?

The problem I'm seeing: in order for data to be written to the flash, a page must be erased. If you want to update data inside a sector you first need to read all the pages inside the sector, save them off the chip, erase the sector and write the pages in order back with your changes.

But a sector of 4KB can't be saved inside a 2KB RAM, so what solutions do other people use for this situation? Because I have seen Arduinos be used in this setup but couldn't determine what their solution was.

(Arduino is just an example of a small microcontroller in this question)

答:
It's a bit unclear, what content (size) you expect to write and how often.

You could think of several smaller NV blocks, which are way less then the page size. Each NV block has some block header identifying the block (e.g. BlockID + Size). Then you could update the page as long as a new NV block fits into that page. If not, write this to the next page, and copy all the latest other blocks over to the new page too. Then you can erase and prepare the old page for the next swap meanwhile.


问:
TensorFlow: Why is my Keras callback monitor value not available?
I use TensorFlow 1.12. I try to fit a model using Keras callbacks:

```<code>checkpoint_full = tf.keras.callbacks.ModelCheckpoint(filepath='model/dir/model.{epoch:02d}.hdf5', monitor='val_dice_loss', save_best_only=True, mode="min")
tensorboard = tf.keras.callbacks.TensorBoard(log_dir='/media/nfs/7_raid/ebos/models/fcn/logs/', write_graph=False)
history = model.fit(train,
                    steps_per_epoch=int(np.ceil(num_samples / float(BATCH_SIZE))),
                    epochs=NUM_EPOCHS,
                    validation_data=val,
                    verbose=0,
                    callbacks=[checkpoint_full, tensorboard])
</code>```

However, this throws the following error:

```<code>WARNING:tensorflow:Can save best model only with val_dice_loss available, skipping.
</code>```

Firstly, I do not understand how the string given to monitor is being resolved. I'm following two guides on Keras (1, 2), and both supply string names which aren't referenced anywhere else in their code. I assume these specify strings which the user can later use to retrieve the development of performance after training, rather than specify which metric fit is supposed to monitor? If so, why is it saying that the value isn't available?

Secondly, answers to similar questions all point out that the problem is the absence of validation data. However, I am pretty sure that I am supplying fit with data, as evidenced by looping through val and counting the number of records. What am I doing wrong?

For reference, my datasets are generated like this:

```<code>def train_sample_fetcher():
    return sample_fetcher()

def val_sample_fetcher():
    return sample_fetcher(is_validations=True)

def sample_fetcher(is_validations=False):
    sample_names = [filename[:-4] for filename in os.listdir(DIR_DATASET + "ndarrays/")]
    if not is_validations: sample_names = sample_names[:int(len(sample_names) * TRAIN_VAL_SPLIT)]
    else: sample_names = sample_names[int(len(sample_names) * TRAIN_VAL_SPLIT):]
    for sample_name in sample_names:
        rgb = tf.image.decode_jpeg(tf.read_file(DIR_DATASET + sample_name + ".jpg"))
        rgb = tf.image.resize_images(rgb, (HEIGHT, WIDTH))
        #d = tf.image.decode_jpeg(tf.read_file(DIR_DATASET + "depth/" + sample_name + ".jpg"))
        #d = tf.image.resize_images(d, (HEIGHT, WIDTH))
        #rgbd = tf.concat([rgb,d], axis=2)
        onehots = tf.convert_to_tensor(np.load(DIR_DATASET + "ndarrays/" + sample_name + ".npy"), dtype=tf.float32)
        yield rgb, onehots

train = tf.data.Dataset.from_generator(generator=train_sample_fetcher, output_types=(tf.uint8, tf.uint8))
#train = train.repeat()
train = train.batch(BATCH_SIZE)
#train = train.shuffle(10)
val = tf.data.Dataset.from_generator(generator=val_sample_fetcher, output_types=(tf.uint8, tf.uint8))
</code>```

My loss function looks as follows:

```<code>def dice_loss(y_true, y_pred):
    smooth = 1.
    y_true_f = tf.reshape(y_true, [-1]) # Flatten
    y_pred_f = tf.reshape(y_pred, [-1]) # Flatten
    intersection = tf.reduce_sum(y_true_f * y_pred_f)
    dice_coefficient = (2. * intersection + smooth) / (tf.reduce_sum(y_true_f) + tf.reduce_sum(y_pred_f) + smooth)
    loss = 1 - dice_coefficient
    return loss
</code>```

I perform semantic segmentation, and the dice loss is calculated per pixel.

答:
Monitor 'val_loss' since your loss function is already set to your custom dice loss function.

The monitor parameter expects a metric. 'loss' is always available, and if you have validation data, so is 'val_loss'. Some folks like to use 'accuracy' and the validation therefor. If you had a custom metric function like sensitivity called (for example) sensitivity_deluxe(), you could include sensitivity_deluxe in the array of metrics in compile(), and it would be available to any callbacks referencing it in their monitor field. Any time you have validation data, you can prefix the metric string with 'val_'.

Example:

```<code>model.compile(loss=my_loss_function(), optimizer='Adam', metrics=[sensitivity_deluxe])
reduce_lr = ReduceLROnPlateau(monitor='val_loss', patience=3, mode='min')
earlystop = EarlyStopping(monitor='val_sensitivity_deluxe', patience=5, mode='max')
model.fit(X, y, validation_split=0.5, callbacks=[earlystop, reduce_lr])
</code>```

I can't speak to your second question regarding validation without seeing your fit() function, but it looks like you're probably fine since you set up separate generators.

Body:
I use TensorFlow 1.12. I try to fit a model using Keras callbacks:

checkpoint_full = tf.keras.callbacks.ModelCheckpoint(filepath='model/dir/model.{epoch:02d}.hdf5', monitor='val_dice_loss', save_best_only=True, mode="min")
tensorboard = tf.keras.callbacks.TensorBoard(log_dir='/media/nfs/7_raid/ebos/models/fcn/logs/', write_graph=False)
history = model.fit(train,
                    steps_per_epoch=int(np.ceil(num_samples / float(BATCH_SIZE))),
                    epochs=NUM_EPOCHS,
                    validation_data=val,
                    verbose=0,
                    callbacks=[checkpoint_full, tensorboard])

However, this throws the following error:

WARNING:tensorflow:Can save best model only with val_dice_loss available, skipping.

Firstly, I do not understand how the string given to monitor is being resolved. I'm following two guides on Keras (1, 2), and both supply string names which aren't referenced anywhere else in their code. I assume these specify strings which the user can later use to retrieve the development of performance after training, rather than specify which metric fit is supposed to monitor? If so, why is it saying that the value isn't available?

Secondly, answers to similar questions all point out that the problem is the absence of validation data. However, I am pretty sure that I am supplying fit with data, as evidenced by looping through val and counting the number of records. What am I doing wrong?

For reference, my datasets are generated like this:

def train_sample_fetcher():
    return sample_fetcher()

def val_sample_fetcher():
    return sample_fetcher(is_validations=True)

def sample_fetcher(is_validations=False):
    sample_names = [filename[:-4] for filename in os.listdir(DIR_DATASET + "ndarrays/")]
    if not is_validations: sample_names = sample_names[:int(len(sample_names) * TRAIN_VAL_SPLIT)]
    else: sample_names = sample_names[int(len(sample_names) * TRAIN_VAL_SPLIT):]
    for sample_name in sample_names:
        rgb = tf.image.decode_jpeg(tf.read_file(DIR_DATASET + sample_name + ".jpg"))
        rgb = tf.image.resize_images(rgb, (HEIGHT, WIDTH))
        #d = tf.image.decode_jpeg(tf.read_file(DIR_DATASET + "depth/" + sample_name + ".jpg"))
        #d = tf.image.resize_images(d, (HEIGHT, WIDTH))
        #rgbd = tf.concat([rgb,d], axis=2)
        onehots = tf.convert_to_tensor(np.load(DIR_DATASET + "ndarrays/" + sample_name + ".npy"), dtype=tf.float32)
        yield rgb, onehots

train = tf.data.Dataset.from_generator(generator=train_sample_fetcher, output_types=(tf.uint8, tf.uint8))
#train = train.repeat()
train = train.batch(BATCH_SIZE)
#train = train.shuffle(10)
val = tf.data.Dataset.from_generator(generator=val_sample_fetcher, output_types=(tf.uint8, tf.uint8))

My loss function looks as follows:

def dice_loss(y_true, y_pred):
    smooth = 1.
    y_true_f = tf.reshape(y_true, [-1]) # Flatten
    y_pred_f = tf.reshape(y_pred, [-1]) # Flatten
    intersection = tf.reduce_sum(y_true_f * y_pred_f)
    dice_coefficient = (2. * intersection + smooth) / (tf.reduce_sum(y_true_f) + tf.reduce_sum(y_pred_f) + smooth)
    loss = 1 - dice_coefficient
    return loss

I perform semantic segmentation, and the dice loss is calculated per pixel.

Body:
Monitor 'val_loss' since your loss function is already set to your custom dice loss function.

The monitor parameter expects a metric. 'loss' is always available, and if you have validation data, so is 'val_loss'. Some folks like to use 'accuracy' and the validation therefor. If you had a custom metric function like sensitivity called (for example) sensitivity_deluxe(), you could include sensitivity_deluxe in the array of metrics in compile(), and it would be available to any callbacks referencing it in their monitor field. Any time you have validation data, you can prefix the metric string with 'val_'.

Example:

model.compile(loss=my_loss_function(), optimizer='Adam', metrics=[sensitivity_deluxe])
reduce_lr = ReduceLROnPlateau(monitor='val_loss', patience=3, mode='min')
earlystop = EarlyStopping(monitor='val_sensitivity_deluxe', patience=5, mode='max')
model.fit(X, y, validation_split=0.5, callbacks=[earlystop, reduce_lr])

I can't speak to your second question regarding validation without seeing your fit() function, but it looks like you're probably fine since you set up separate generators.


问:
How do I get the url for a model?
Given the following situation:

# models.py
class Book(Model):
    pass

# views.py
class BookDetail(DetailView):
    model = Book

# books/urls.py
urlpatterns += [path('detail/<int:pk>', BookDetail.as_view(), 'book_detail')]

# page/urls.py
urlpatterns += [path('books/', include('books.urls'))]
```

I can load the detail view for the object with the private key id 42 at /books/detail/42/. If I am in another request with a completely different path and hold a reference to the object with the private key id 42, is there an "official" or builtin way to generate the url /books/detail/42/? Preferably outside of templating, so I can respond with a JSON.

Or is the idiomatic way to parametrize the path elements (books and detail) and just rebuild it myself?

答:
Yes, you can make use of get_absolute_url for model-specific views and the {% url ... %} template tag to calculate the name of a view.

Model-specific views

If a Model has a specific view to show details, you can implement a get_absolute_url [Django-doc] on your model, like:

```<code>from django.urls import <b>reverse</b>

class Book(Model):

    def <b>get_absolute_url</b>(self):
        return <b>reverse</b>('book_detail', kwargs={'pk': self.pk})</code>```

Here we use reverse [Django-doc] to "calculate" the URL for the given name of the view (specified in your path(..., name='book_detail')) with as pk parameter, the pk of self.

In your template you can then write:

```<code><a href="<b>{{ my_object.get_absolute_url }}</b>">{{ my_object }}</a></code>```

with my_object the name of the variable in your template.

It is note that the redirect [Django-doc] function understands the get_absolute_url, and thus you can write return redirect(my_object) in a view, and it will automatically call get_absolute_url to redirect to the proper view.

If you serialize a model with the Django REST framework, then you can reuse the get_absolute_url as well, by using a URLField [drf-doc] for example:

```from rest_framework.serializers import ModelSerializer, <b>URLField</b>

class BookSerializer(serializers.ModelSerializer):

    absolute_url = serializers.URLField(
        read_only=True,
        <b>source='get_absolute_url'</b>
    )```

This specific use case is documented in the documentation of the Django REST framework.

Making use of {% url ...%} in the template

You can also calculate the URL of a view, by using the {% url ... %} template tag [Django-doc]. You can for example write:

```<code><a href="<b>{% url 'book_detail' pk=my_object.pk %}</b>">{{ my_object }}</a></code>```

to calculate the URL, just like we did with the get_absolute_url. It is however useful as well for other, non model-specific views.

Title: How do I get the url for a model?

Body:
Given the following situation:

# models.py
class Book(Model):
    pass

# views.py
class BookDetail(DetailView):
    model = Book

# books/urls.py
urlpatterns += [path('detail/<int:pk>', BookDetail.as_view(), 'book_detail')]

# page/urls.py
urlpatterns += [path('books/', include('books.urls'))]

I can load the detail view for the object with the private key id 42 at /books/detail/42/. If I am in another request with a completely different path and hold a reference to the object with the private key id 42, is there an "official" or builtin way to generate the url /books/detail/42/? Preferably outside of templating, so I can respond with a JSON.

Or is the idiomatic way to parametrize the path elements (books and detail) and just rebuild it myself?

Body:
Yes, you can make use of get_absolute_url for model-specific views and the {% url ... %} template tag to calculate the name of a view.

Model-specific views

If a Model has a specific view to show details, you can implement a get_absolute_url [Django-doc] on your model, like:

from django.urls import reverse

class Book(Model):

    def get_absolute_url(self):
        return reverse('book_detail', kwargs={'pk': self.pk})

Here we use reverse [Django-doc] to "calculate" the URL for the given name of the view (specified in your path(..., name='book_detail')) with as pk parameter, the pk of self.

In your template you can then write:

<a href="{{ my_object.get_absolute_url }}">{{ my_object }}</a>

with my_object the name of the variable in your template.

It is note that the redirect [Django-doc] function understands the get_absolute_url, and thus you can write return redirect(my_object) in a view, and it will automatically call get_absolute_url to redirect to the proper view.

If you serialize a model with the Django REST framework, then you can reuse the get_absolute_url as well, by using a URLField [drf-doc] for example:

from rest_framework.serializers import ModelSerializer, URLField

class BookSerializer(serializers.ModelSerializer):

    absolute_url = serializers.URLField(
        read_only=True,
        source='get_absolute_url'
    )

This specific use case is documented in the documentation of the Django REST framework.

Making use of {% url ...%} in the template

You can also calculate the URL of a view, by using the {% url ... %} template tag [Django-doc]. You can for example write:

<a href="{% url 'book_detail' pk=my_object.pk %}">{{ my_object }}</a>

to calculate the URL, just like we did with the get_absolute_url. It is however useful as well for other, non model-specific views.


答:
You should use Django Rest Framework

All built-in, you just have to set up.

Title: How do I get the url for a model?


问:
How do I add parallel computation to this example?
I have an algorithm for synchronous calculation of a certain integral on a given segment. I want to use the Control.Parallel library, or rather par :: a -> b -> b to add parallel computing to this algorithm.
How can I do this?

```<code>integrate :: (Double -> Double) -> Double -> Double -> Double
integrate f a b =
  let
    step     = (b - a) / 1000
    segments = [a + x * step | x <- [0..999]]
    area x   = step * (f x + f (x + step)) / 2
  in sum $ map area segments
</code>```

答:
my default go-to for any map composition would be by using parmap from Strategies API http://hackage.haskell.org/package/parallel-3.2.2.0/docs/Control-Parallel-Strategies.html#g:7 , I'll add an example once I'm around my PC.

Edit:

You'd use parMap in the following way,

```<code>module Main where

import Control.Parallel.Strategies

main = putStrLn $ show $ integrate f 1.1 1.2

f :: Double -> Double
f x = x

integrate :: (Double -> Double) -> Double -> Double -> Double
integrate f a b =
  let
    step     = (b - a) / 1000
    segments = [a + x * step | x <- [0..999]]
    area x   = step * (f x + f (x + step)) / 2
  in sum $ parMap rpar area segments
</code>```

Then compile with:

ghc -O2 -threaded -rtsopts Main.hs and run using the RTS + N flag to control the parallelism ./Main +RTS -N -RTS -N can be specified e.g. -N6 to run on 6 threads or can be left empty to use all possible threads.

Body:
I have an algorithm for synchronous calculation of a certain integral on a given segment. I want to use the Control.Parallel library, or rather par :: a -> b -> b to add parallel computing to this algorithm.
How can I do this?

integrate :: (Double -> Double) -> Double -> Double -> Double
integrate f a b =
  let
    step     = (b - a) / 1000
    segments = [a + x * step | x <- [0..999]]
    area x   = step * (f x + f (x + step)) / 2
  in sum $ map area segments

Body:
my default go-to for any map composition would be by using parmap from Strategies API http://hackage.haskell.org/package/parallel-3.2.2.0/docs/Control-Parallel-Strategies.html#g:7 , I'll add an example once I'm around my PC.

Edit:

You'd use parMap in the following way,

module Main where

import Control.Parallel.Strategies

main = putStrLn $ show $ integrate f 1.1 1.2

f :: Double -> Double
f x = x

integrate :: (Double -> Double) -> Double -> Double -> Double
integrate f a b =
  let
    step     = (b - a) / 1000
    segments = [a + x * step | x <- [0..999]]
    area x   = step * (f x + f (x + step)) / 2
  in sum $ parMap rpar area segments

Then compile with:

ghc -O2 -threaded -rtsopts Main.hs and run using the RTS + N flag to control the parallelism ./Main +RTS -N -RTS -N can be specified e.g. -N6 to run on 6 threads or can be left empty to use all possible threads.


问:
UIButton selector not working after button tapped within WKWebView
I have a custom titleView with 2 custom UIButtons with arrow images that allow navigation to the next view controller in the paging structure. They work perfectly fine until a button is tapped within the WKWebView. Then they don't work anymore and the selector is not called. Note that other buttons in the nav bar still work (UIBarButtonItems). The buttons work properly again after the user swipes over to the next view controller.

After looking into it some, it looks like a WKCompositingView becomes first responder and if I override becomeFirstResponder() in a WKWebView subclass, the issue goes away. I'm still a little baffled though, and would like to understand the root of the problem.

```<code>class NonFirstRespondableWebView: WKWebView {

    override func becomeFirstResponder() -> Bool {
        return false
    }
}
</code>```

Does anyone have any insight into why this is happening?

答:
Most UI elements in swift have a UIResponder. Unhandled events are passed up the responder chain to enclosing views. My guess is that the WKWebView is absorbing all touch events once the window has become active. You can learn more about the responder chain here

Regarding a first responder. From the docs:

The first responder is usually the first object in a responder chain to receive an event or action message. In most cases, the first responder is a view object that the user selects or activates with the mouse or keyboard.

Assuming you want to keep interactivity with the WKWebView fully functional (e.g. you need to bring up a keyboard or something), you can use

```<code>webView.resignFirstResponder()
</code>```

To resign the responder at any time.

Otherwise, an extension that would give you the same functionality might look something like this:

```<code>extension WKWebView {

    open override func becomeFirstResponder() -> Bool {
        if self.superview?.superview is UIWebView {
            return false
        } else {
            return super.becomeFirstResponder()
        }
    }

}
</code>```

Body:
I have a custom titleView with 2 custom UIButtons with arrow images that allow navigation to the next view controller in the paging structure. They work perfectly fine until a button is tapped within the WKWebView. Then they don't work anymore and the selector is not called. Note that other buttons in the nav bar still work (UIBarButtonItems). The buttons work properly again after the user swipes over to the next view controller.

After looking into it some, it looks like a WKCompositingView becomes first responder and if I override becomeFirstResponder() in a WKWebView subclass, the issue goes away. I'm still a little baffled though, and would like to understand the root of the problem.

class NonFirstRespondableWebView: WKWebView {

    override func becomeFirstResponder() -> Bool {
        return false
    }
}

Does anyone have any insight into why this is happening?

Body:
Most UI elements in swift have a UIResponder. Unhandled events are passed up the responder chain to enclosing views. My guess is that the WKWebView is absorbing all touch events once the window has become active. You can learn more about the responder chain here

Regarding a first responder. From the docs:

The first responder is usually the first object in a responder chain to receive an event or action message. In most cases, the first responder is a view object that the user selects or activates with the mouse or keyboard.

Assuming you want to keep interactivity with the WKWebView fully functional (e.g. you need to bring up a keyboard or something), you can use

webView.resignFirstResponder()

To resign the responder at any time.

Otherwise, an extension that would give you the same functionality might look something like this:

extension WKWebView {

    open override func becomeFirstResponder() -> Bool {
        if self.superview?.superview is UIWebView {
            return false
        } else {
            return super.becomeFirstResponder()
        }
    }

}


问:
QVBoxLayout how to add spacer row
Is it possible to add a spacing row to a QVBoxLayout?  I tried using a QPushButton and then hiding, but this doesn't work.

I want the layout to contain 5 buttons with a spacing row between buttons 4 and 5.

答:
Try adding QSpacerItem.

```<code>QVBoxLayout* layout = new QVBoxLayout;
layout->addWidget(new QPushButton("first"));
layout->addWidget(new QPushButton("second"));
layout->addWidget(new QPushButton("third"));
layout->addWidget(new QPushButton("fourth"));
layout->addItem(new QSpacerItem(0, 0, QSizePolicy::Fixed, QSizePolicy::Expanding));
layout->addWidget(new QPushButton("fifth"));
</code>```

Title: QVBoxLayout how to add spacer row

Body:
Try adding QSpacerItem.

QVBoxLayout* layout = new QVBoxLayout;
layout->addWidget(new QPushButton("first"));
layout->addWidget(new QPushButton("second"));
layout->addWidget(new QPushButton("third"));
layout->addWidget(new QPushButton("fourth"));
layout->addItem(new QSpacerItem(0, 0, QSizePolicy::Fixed, QSizePolicy::Expanding));
layout->addWidget(new QPushButton("fifth"));


问:
Why does setState in this promise take longer to update than the same code as an async function?
I have 2 versions of the same fetch functions here, the first one uses promises, the second one async-await. To my understanding there should be no difference between those two, so I'd appreciate some clarification to what's actually happening here.

The following version, which uses async-await, sets the state by the time console log runs:

```<code>async fetchPostList(query) {
  const response = await fetch(`https://hacker-news.firebaseio.com/v0/${query}.json`)
  const data = await response.json()
  this.setState({ postList: data });
  console.log(this.state.postList);
}
</code>```

Console: Array(474) [ ... ]

The version that uses promises sets state after the console log:

```<code>fetchPostList(query) {
  fetch(`https://hacker-news.firebaseio.com/v0/${query}.json`)
    .then( response => response.json())
    .then( data => this.setState({ postList: data }))
  console.log(this.state.postList);
}
</code>```

Console: Array []

答:
The first function is an async function. In an async function the code pauses while the awaited promises resolve.

```<code>async fetchPostList(query) {
  const response = await fetch(`https://hacker-news.firebaseio.com/v0/${query}.json`)
  /* Pause ...*/

  const data = await response.json()
  /* Pause ... */

  this.setState({ postList: data });
  console.log(this.state.postList);
}
</code>```

The second function is not async, which means it runs to completion. It just fires off the promises and callbacks and continues, so the console.log() is called immediately after creating the promises.

```<code>fetchPostList(query) {
  fetch(`https://hacker-news.firebaseio.com/v0/${query}.json`)
    .then( response => response.json())
    .then( data => this.setState({ postList: data }))

  /* does NOT pause */
  console.log(this.state.postList);
}
</code>```

Body:
I have 2 versions of the same fetch functions here, the first one uses promises, the second one async-await. To my understanding there should be no difference between those two, so I'd appreciate some clarification to what's actually happening here.

The following version, which uses async-await, sets the state by the time console log runs:

async fetchPostList(query) {
  const response = await fetch(`https://hacker-news.firebaseio.com/v0/${query}.json`)
  const data = await response.json()
  this.setState({ postList: data });
  console.log(this.state.postList);
}

Console: Array(474) [ ... ]

The version that uses promises sets state after the console log:

fetchPostList(query) {
  fetch(`https://hacker-news.firebaseio.com/v0/${query}.json`)
    .then( response => response.json())
    .then( data => this.setState({ postList: data }))
  console.log(this.state.postList);
}

Console: Array []

Body:
The first function is an async function. In an async function the code pauses while the awaited promises resolve.

async fetchPostList(query) {
  const response = await fetch(`https://hacker-news.firebaseio.com/v0/${query}.json`)
  /* Pause ...*/

  const data = await response.json()
  /* Pause ... */

  this.setState({ postList: data });
  console.log(this.state.postList);
}

The second function is not async, which means it runs to completion. It just fires off the promises and callbacks and continues, so the console.log() is called immediately after creating the promises.

fetchPostList(query) {
  fetch(`https://hacker-news.firebaseio.com/v0/${query}.json`)
    .then( response => response.json())
    .then( data => this.setState({ postList: data }))

  /* does NOT pause */
  console.log(this.state.postList);
}


问:
Compatibility between Azure Message and BrokeredMessage
We have two projects. One with .NET FrameWork and one with .NET Core. For .NET Core, we have to use the Azure ServiceBus, and for .NET Framework, we have to use the old ServiceBus as we are still working with 5.4.
The .NET Framework receives a BrokeredMessage, and .NET Core sends an Azure Message. How can I make this compatible? Do I have to write my own serializer?</p>

答:
The .NET Framework receives a BrokeredMessage, and .NET Core sends an Azure Message. How can I make this compatible? Do I have to write my own serializer?

This topic has been covered a few times. In your case, if it's truly uni-directional the way you describe it, to process messages of type Message sent from the Standard Service Bus library, you will need to receive those message using the old client and process as a Stream. The stream will provide you with the bytes, which you'll be able to deserialize utilizing the same method used to serialize the content. More on this topic in the (now decommissioned) Service Bus client issue here.

In case you cannot modify how BrokeredMessages are handled, this Stack Overflow question has an answer to handle interop the other way around.


问:
Batch file to check if another batch is open and do something when it gets closed
I’m trying to get a batch-file my other program can call upon, so that when my other program is closed it deletes a temp file the other program created, the program runs a loop so I can’t just put it before an exit command within the program as it would never get to it.</p>

```<code>@echo off
Title watcher
:start
//if other .bat file is open then
goto start
Else //then when it is closed
Del file.txt
Exit
</code>```

答:
Does something like

```<code>@ECHO OFF
START "" /WAIT "C:\Program Files\Foo\OtherApplication.exe"
DEL "C:\Temp\Foo.tmp"
</code>```

not work?

Body:
I’m trying to get a batch-file my other program can call upon, so that when my other program is closed it deletes a temp file the other program created, the program runs a loop so I can’t just put it before an exit command within the program as it would never get to it.

@echo off
Title watcher
:start
//if other .bat file is open then
goto start
Else //then when it is closed
Del file.txt
Exit

Body:
Does something like

@ECHO OFF
START "" /WAIT "C:\Program Files\Foo\OtherApplication.exe"
DEL "C:\Temp\Foo.tmp"

not work?


问:
Rock Paper Scissors score keeps resetting
I'm making a rock, paper, scissors game with a pointing system and it seems to always give me a value of zero every time the scores are revealed. Help is appreciated.-------------------------------------------------------------------------------------------------------------------------------------------------------------</p>

```<code>def play():
    player = input("Which will you choose? Rock, Paper or Scissors? Type 'E' to exit ")

    elements = ['rock', 'paper', 'scissors']

    cpu = random.choice(elements)

    scoreplayer = 0

    scorecpu = 0

    if player.lower() == cpu:
        print("This is a tie, no one scores a point")
        play()

    elif player.lower() == "rock":
        if cpu == "paper":
            print("Paper beats Rock, CPU gains 1 point")
            scorecpu = scorecpu + 1
            play()
        elif cpu == "scissors":
            print("Rock beats Scissors, you gain 1 point")
            scoreplayer = scoreplayer + 1
            play()

    elif player.lower() == "paper":
        if cpu == "scissors":
            print("Scissors beats Paper, CPU gains 1 point")
            scorecpu = scorecpu + 1
            play()
        elif cpu == "rock":
            print("Paper Beats Rock, you gain 1 point")
            scoreplayer = scoreplayer + 1
            play()

    elif player == "scissors":
        if cpu == "rock":
            print("Rock beats Scissors, CPU gains 1 point")
            scorecpu = scorecpu + 1
            play()
        elif cpu == "paper":
            print("Scissors beats Paper, you gain 1 point")
            scoreplayer = scoreplayer + 1
            play()

    elif player.lower() == "e":
        print("")
        print("You have " + str(scoreplayer) + " points")
        print("")
        print("CPU has " + str(scorecpu) + " points")
        sys.exit()

    else:
        play()
</code>```

答:
scoreplayer = 0 and the other assignment are running every time play is called, which creates new variables with values of 0 each time. Pass the current scores as arguments to play instead:

```<code>def play(scoreplayer, scorecpu):
   # Get rid of these lines
   # scoreplayer = 0
   # scorecpu = 0

   . . .
   # Update the scores here

   else:
        play(scoreplayer, scorecpu)

play(0, 0) # Start with scores of 0
</code>```

Or switch to using a loop construct like while from recursion and update the scores within the loop. In a language like Python, recursion isn't really suitable here anyways.

Body:
I'm making a rock, paper, scissors game with a pointing system and it seems to always give me a value of zero every time the scores are revealed. Help is appreciated.-------------------------------------------------------------------------------------------------------------------------------------------------------------

def play():
    player = input("Which will you choose? Rock, Paper or Scissors? Type 'E' to exit ")

    elements = ['rock', 'paper', 'scissors']

    cpu = random.choice(elements)

    scoreplayer = 0

    scorecpu = 0

    if player.lower() == cpu:
        print("This is a tie, no one scores a point")
        play()

    elif player.lower() == "rock":
        if cpu == "paper":
            print("Paper beats Rock, CPU gains 1 point")
            scorecpu = scorecpu + 1
            play()
        elif cpu == "scissors":
            print("Rock beats Scissors, you gain 1 point")
            scoreplayer = scoreplayer + 1
            play()

    elif player.lower() == "paper":
        if cpu == "scissors":
            print("Scissors beats Paper, CPU gains 1 point")
            scorecpu = scorecpu + 1
            play()
        elif cpu == "rock":
            print("Paper Beats Rock, you gain 1 point")
            scoreplayer = scoreplayer + 1
            play()

    elif player == "scissors":
        if cpu == "rock":
            print("Rock beats Scissors, CPU gains 1 point")
            scorecpu = scorecpu + 1
            play()
        elif cpu == "paper":
            print("Scissors beats Paper, you gain 1 point")
            scoreplayer = scoreplayer + 1
            play()

    elif player.lower() == "e":
        print("")
        print("You have " + str(scoreplayer) + " points")
        print("")
        print("CPU has " + str(scorecpu) + " points")
        sys.exit()

    else:
        play()

Body:
scoreplayer = 0 and the other assignment are running every time play is called, which creates new variables with values of 0 each time. Pass the current scores as arguments to play instead:

def play(scoreplayer, scorecpu):
   # Get rid of these lines
   # scoreplayer = 0
   # scorecpu = 0

   . . .
   # Update the scores here

   else:
        play(scoreplayer, scorecpu)

play(0, 0) # Start with scores of 0

Or switch to using a loop construct like while from recursion and update the scores within the loop. In a language like Python, recursion isn't really suitable here anyways.


问:
How can I get Url Referrer in ASP.NET Core MVC?
I am trying to migrate an ASP.NET MVC webform to ASP.NET Core MVC. Currently, I am having trouble with the Request.UrlReferrer class.

The original line is:

```<code>    [HttpPost]
    public async Task<ActionResult> ContactUsFormSubmit(ContactUs request)
    {
        var siteUrl = Request.UrlReferrer.ToString().ToLower();
        ....
    }
</code>```

However, with ASP.NET Core, UrlReferrer is not available. I have found the following:

```<code>    Request.Headers["Referer"]
</code>```

which returns StringValues instead of a String. I am not sure if I should try to use this one or if there is any other solutions to this situation. Request.ServerVariables is also not available or maybe I don't have the namespace. My namespaces are as follows:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
</code>```

I would really appreciate if someone can direct me in the right direction.

答:
As of asp.net core 2 use GetTypedHeaders

```<code>RequestHeaders header = request.GetTypedHeaders();
Uri uriReferer = header.Referer;
</code>```

Body:
I am trying to migrate an ASP.NET MVC webform to ASP.NET Core MVC. Currently, I am having trouble with the Request.UrlReferrer class.

The original line is:

    [HttpPost]
    public async Task<ActionResult> ContactUsFormSubmit(ContactUs request)
    {
        var siteUrl = Request.UrlReferrer.ToString().ToLower();
        ....
    }

However, with ASP.NET Core, UrlReferrer is not available. I have found the following:

    Request.Headers["Referer"]

which returns StringValues instead of a String. I am not sure if I should try to use this one or if there is any other solutions to this situation. Request.ServerVariables is also not available or maybe I don't have the namespace. My namespaces are as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

I would really appreciate if someone can direct me in the right direction.

Body:
As of asp.net core 2 use GetTypedHeaders

RequestHeaders header = request.GetTypedHeaders();
Uri uriReferer = header.Referer;


问:
bootstrap-datepicker : how to close only when clicking outside
I want to make datepicker close only if click outside.
To prevent closing before clicking outside, I delete hide function like this:

```<code>$('#datepicker').data('datepicker').hide = function () {};
</code>```

But if I do this, it's not able to close datepicker.

How do I fix this?

Code below:

```<code><input type="text" name="datepicker" id="datepicker" class="form-control" value='<%=selectDate%>' onchange="hide()">

<script>

    $('#datepicker').datepicker({
        dateFormat : 'yyyy-mm-dd',
        autoclose: false
    });
    $('#datepicker').data('datepicker').hide = function () {};

</script>
</code>```

答:
just add the class datetimepicker-input ej.

```<code><input type="text" class=" datetimepicker-input" id="datetimepicker4" data-toggle="datetimepicker" data-target="#datetimepicker4" dir="auto" required=""  readonly >
</code>```

when de jquery is

```<code>$('#datetimepicker4').datetimepicker();
</code>```

I found this page to explain the details https://tempusdominus.github.io/bootstrap-4

Body:
I want to make datepicker close only if click outside.
To prevent closing before clicking outside, I delete hide function like this:

$('#datepicker').data('datepicker').hide = function () {};

But if I do this, it's not able to close datepicker.

How do I fix this?

Code below:

<input type="text" name="datepicker" id="datepicker" class="form-control" value='<%=selectDate%>' onchange="hide()">

Body:
just add the class datetimepicker-input ej.

<input type="text" class=" datetimepicker-input" id="datetimepicker4" data-toggle="datetimepicker" data-target="#datetimepicker4" dir="auto" required=""  readonly >

when de jquery is

$('#datetimepicker4').datetimepicker();

I found this page to explain the details https://tempusdominus.github.io/bootstrap-4