问:
matrix by vector multiplication - R versus Matlab
I observed that matrix by vector multiplication with a large matrix is significantly slower in R (version 3.6.1) than in Matlab (version 2019b), while both languages rely on the (same?) BLAS library. See below a minimal example:

In Matlab:

```<code>n=900;
p=900;
A=reshape(1:(n*p),[n,p]);
x=ones(p,1);
tic()
for id = 1:1000
  x = A*x;
end
toc()
</code>```

In R:

```<code>n=900
p=900
A=matrix(c(1:(n*p)),nrow=n,ncol=p)
x=rep(1,ncol(A))
t0 <- Sys.time()
for(iter in 1:1000){
  x = A%*%x
}
t1 <- Sys.time()
print(t1-t0)
</code>```

I get a running execution time of roughly 0.05sec in Matlab versus 3.5sec in R using the same computer. Any idea of the reason for such difference?

Thanks.

[EDIT]: I add below a similar calculus in C (using the CBLAS library, compilation using gcc cblas_dgemv.c -lblas -o cblas_dgemv, where cblas_dgemv.c denotes the source file below). I get a running time of roughly 0.08s which is quite close to the running times obtained using Matlab (0.05s). I am still trying to figure out the reason of this huge running time in R (3.5s).

```<code>#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>
#include "cblas.h"

int main(int argc, char **argv)
{
  int m=900,adr;
  double *A,*x,*y;
  struct timeval t0,t1;

  /* memory allocation and initialization */
  A = (double*)malloc(m*m*sizeof(double));
  x = (double*)malloc(m*sizeof(double));
  y = (double*)malloc(m*sizeof(double));
  for(adr=0;adr<m;adr++) x[adr] = 1.;
  for(adr=0;adr<m*m;adr++) A[adr] = adr;

  /* main loop */
  gettimeofday(&t0, NULL);
  for(adr=0;adr<1000;adr++)
    cblas_dgemv(CblasColMajor,CblasNoTrans,m,m,1.,A,m,x,1,0.,y,1);
  gettimeofday(&t1, NULL);
  printf("elapsed time = %.2e seconds\n",(double)(t1.tv_usec-t0.tv_usec)/1000000. + (double)(t1.tv_sec-t0.tv_sec));

  /* free memory */
  free(A);
  free(x);
  free(y);

  return EXIT_SUCCESS;
}
</code>```

Notice that I was not able to set y=x in the cblas_dgemv routine. Thus, this C calculus is slightly different from that done in R and Matlab codes above. However the compilation was done without optimization flag (no option -O3) and I checked that the matrix-vector product was indeed called at each iteration of the loop (performing 10x more iterations leads to a 10x longer running time).

答:
I used Rcpp to interface a C++ implementation of the matrix-vector product with R.

Source C++ file ('cblas_dgemv2.cpp'): performes 'niter' times the product y = A*x

```<code>#include <cblas-openblas.h>
#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
Rcpp::NumericVector cblas_dgemv2(Rcpp::NumericMatrix A, Rcpp::NumericVector x, int niter)
{
  int m=A.ncol(),iter;
  Rcpp::NumericVector y(m);
  for(iter=0;iter<niter;iter++)
    cblas_dgemv(CblasColMajor,CblasNoTrans,m,m,1.,A.begin(),m,x.begin(),1,0.,y.begin(),1);
  return y;
}
</code>```

Then I perform two experiments using the R code below:

Experiment 1: from R, call y=cblas_dgmev2(A,x,1000) to perform 1000 times in C++ the computation of the product y=Ax*;

Experiment 2: from R, call 1000 times y=cblas_dgemv2(A,x,1), each call performs in C++ the product y=A*x.

```<code># compile cblas_dgemv2 (you may need to update the path to the library)
PKG_LIBS <- '/usr/lib/x86_64-linux-gnu/libopenblas.a'
PKG_CPPFLAGS <- '-I/usr/include/x86_64-linux-gnu'
Sys.setenv(PKG_LIBS = PKG_LIBS , PKG_CPPFLAGS = PKG_CPPFLAGS)
Rcpp::sourceCpp('cblas_dgemv2.cpp', rebuild = TRUE)

# create A and x
n=900
A=matrix(c(1:(n*n)),nrow=n,ncol=n)
x=rep(1,n)

# Experiment 1: call 1 time cblas_dgemv2 (with 1000 iterations in C++)
t0 <- Sys.time()
y=cblas_dgemv2(A,x,1000) # perform 1000 times the computation y = A%*%x
t1 <- Sys.time()
print(t1-t0)

# Experiment 2: call 1000 times cblas_dgemv2
t0 <- Sys.time()
for(iter in 1:1000){
  y=cblas_dgemv2(A,x,1) # perform 1 times the computation y = A%*%x
}
t1 <- Sys.time()
print(t1-t0)
</code>```

I get a running time of 0.08s for the first experiment versus 4.8s for the second experiment.

My conclusion: the bottleneck in terms of the running times comes from the data transferts between R and C++, not from the computation of the matrix-vector product itself. Surprising, isn't it?

Body:
I observed that matrix by vector multiplication with a large matrix is significantly slower in R (version 3.6.1) than in Matlab (version 2019b), while both languages rely on the (same?) BLAS library. See below a minimal example:

In Matlab:

n=900;
p=900;
A=reshape(1:(n*p),[n,p]);
x=ones(p,1);
tic()
for id = 1:1000
  x = A*x;
end
toc()

In R:

n=900
p=900
A=matrix(c(1:(n*p)),nrow=n,ncol=p)
x=rep(1,ncol(A))
t0 <- Sys.time()
for(iter in 1:1000){
  x = A%*%x
}
t1 <- Sys.time()
print(t1-t0)

I get a running execution time of roughly 0.05sec in Matlab versus 3.5sec in R using the same computer. Any idea of the reason for such difference?

Thanks.

[EDIT]: I add below a similar calculus in C (using the CBLAS library, compilation using gcc cblas_dgemv.c -lblas -o cblas_dgemv, where cblas_dgemv.c denotes the source file below). I get a running time of roughly 0.08s which is quite close to the running times obtained using Matlab (0.05s). I am still trying to figure out the reason of this huge running time in R (3.5s).

#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>
#include "cblas.h"

int main(int argc, char **argv)
{
  int m=900,adr;
  double *A,*x,*y;
  struct timeval t0,t1;

  /* memory allocation and initialization */
  A = (double*)malloc(m*m*sizeof(double));
  x = (double*)malloc(m*sizeof(double));
  y = (double*)malloc(m*sizeof(double));
  for(adr=0;adr<m;adr++) x[adr] = 1.;
  for(adr=0;adr<m*m;adr++) A[adr] = adr;

  /* main loop */
  gettimeofday(&t0, NULL);
  for(adr=0;adr<1000;adr++)
    cblas_dgemv(CblasColMajor,CblasNoTrans,m,m,1.,A,m,x,1,0.,y,1);
  gettimeofday(&t1, NULL);
  printf("elapsed time = %.2e seconds\n",(double)(t1.tv_usec-t0.tv_usec)/1000000. + (double)(t1.tv_sec-t0.tv_sec));

  /* free memory */
  free(A);
  free(x);
  free(y);

  return EXIT_SUCCESS;
}

Notice that I was not able to set y=x in the cblas_dgemv routine. Thus, this C calculus is slightly different from that done in R and Matlab codes above. However the compilation was done without optimization flag (no option -O3) and I checked that the matrix-vector product was indeed called at each iteration of the loop (performing 10x more iterations leads to a 10x longer running time).

Body:
I used Rcpp to interface a C++ implementation of the matrix-vector product with R.

Source C++ file ('cblas_dgemv2.cpp'): performes 'niter' times the product y = A*x

#include <cblas-openblas.h>
#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
Rcpp::NumericVector cblas_dgemv2(Rcpp::NumericMatrix A, Rcpp::NumericVector x, int niter)
{
  int m=A.ncol(),iter;
  Rcpp::NumericVector y(m);
  for(iter=0;iter<niter;iter++)
    cblas_dgemv(CblasColMajor,CblasNoTrans,m,m,1.,A.begin(),m,x.begin(),1,0.,y.begin(),1);
  return y;
}

Then I perform two experiments using the R code below:

Experiment 1: from R, call y=cblas_dgmev2(A,x,1000) to perform 1000 times in C++ the computation of the product y=Ax*;

Experiment 2: from R, call 1000 times y=cblas_dgemv2(A,x,1), each call performs in C++ the product y=A*x.

# compile cblas_dgemv2 (you may need to update the path to the library)
PKG_LIBS <- '/usr/lib/x86_64-linux-gnu/libopenblas.a'
PKG_CPPFLAGS <- '-I/usr/include/x86_64-linux-gnu'
Sys.setenv(PKG_LIBS = PKG_LIBS , PKG_CPPFLAGS = PKG_CPPFLAGS)
Rcpp::sourceCpp('cblas_dgemv2.cpp', rebuild = TRUE)

# create A and x
n=900
A=matrix(c(1:(n*n)),nrow=n,ncol=n)
x=rep(1,n)

# Experiment 1: call 1 time cblas_dgemv2 (with 1000 iterations in C++)
t0 <- Sys.time()
y=cblas_dgemv2(A,x,1000) # perform 1000 times the computation y = A%*%x
t1 <- Sys.time()
print(t1-t0)

# Experiment 2: call 1000 times cblas_dgemv2
t0 <- Sys.time()
for(iter in 1:1000){
  y=cblas_dgemv2(A,x,1) # perform 1 times the computation y = A%*%x
}
t1 <- Sys.time()
print(t1-t0)

I get a running time of 0.08s for the first experiment versus 4.8s for the second experiment.

My conclusion: the bottleneck in terms of the running times comes from the data transferts between R and C++, not from the computation of the matrix-vector product itself. Surprising, isn't it?


来源: stackexchange

问:
How to continue drawing a rectangle while dragging the mouse once the left button has been clicked?
I have understood how to capture the mouse movements to draw a rectangle by first clicking the left button, then dragging the mouse and then releasing the left button. My code is as follows. However, I want continue drawing a rectangle even when I am moving the mouse over the image after I have clicked the left button.

Unfortunately, Now, the rectangle is being displayed only after I release the left button at the end.

```<code># import the necessary packages
import argparse
import cv2

# initialize the list of reference points and boolean indicating
# whether cropping is being performed or not
refPt = []
cropping = False

def click_and_crop(event, x, y, flags, param):
    # grab references to the global variables
global refPt, cropping, image
drag = 0
# if the left mouse button was clicked, record the starting
# (x, y) coordinates and indicate that cropping is being
# performed
if event == cv2.EVENT_LBUTTONDOWN:
    refPt = [(x, y)]
        drag = 1
    cropping = True

# check to see if the left mouse button was released
elif event == cv2.EVENT_LBUTTONUP:
    # record the ending (x, y) coordinates and indicate that
    # the cropping operation is finished
    refPt.append((x, y))
    cropping = False

    # draw a rectangle around the region of interest
    cv2.rectangle(image, refPt[0], refPt[1], (0, 255, 0), 2)
    cv2.imshow("image", image)

elif event == cv2.EVENT_MOUSEMOVE and drag == 1:
    #image = clone.copy()
    cv2.rectangle(image, refPt[0], (x, y), (0, 255, 0), 2)

# load the image, clone it, and setup the mouse callback function
image = cv2.imread("image_00001.jpg")
clone = image.copy()
cv2.namedWindow("image")
cv2.setMouseCallback("image", click_and_crop)

# keep looping until the 'q' key is pressed
while True:
# display the image and wait for a keypress
    cv2.imshow("image", image)
    key = cv2.waitKey(1) & 0xFF

# if the 'r' key is pressed, reset the cropping region
if key == ord("r"):
    image = clone.copy()

# if the 'c' key is pressed, break from the loop
elif key == ord("c"):
    break

# if there are two reference points, then crop the region of interest
# from teh image and display it
if len(refPt) == 2:
    roi = clone[refPt[0][1]:refPt[1][1], refPt[0][0]:refPt[1][0]]
    cv2.imshow("ROI", roi)
    cv2.waitKey(0)

# close all open windows
cv2.destroyAllWindows()
</code>```

答:
Try below code: </p>

```

import cv2

refPt = []

final_boundaries = []
image = None

def click_and_crop(event, x, y, flags, param):
    global refPt, image
    if event == cv2.EVENT_LBUTTONDOWN:
        refPt = [(x, y)]
    elif event == cv2.EVENT_LBUTTONUP:
        refPt.append((x, y))
        final_boundaries.append((refPt[0],refPt[1]))
        cv2.rectangle(image, refPt[0], refPt[1], (0, 255, 0), 2)
        cv2.imshow("image", image)
    elif event == cv2.EVENT_MOUSEMOVE and flags == cv2.EVENT_FLAG_LBUTTON:
        clone = image.copy()
        cv2.rectangle(clone, refPt[0], (x, y), (0, 255, 0), 2)
        cv2.imshow("image", clone)

def main(image_name):
    global image
    image = cv2.imread("image.png") #convert to image boundary
    cv2.namedWindow("image")
    cv2.setMouseCallback("image", click_and_crop)
    cv2.imshow("image", image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    return (final_boundaries)

```

ContentLicense: CC BY-SA 3.0

Body:
I have understood how to capture the mouse movements to draw a rectangle by first clicking the left button, then dragging the mouse and then releasing the left button. My code is as follows. However, I want continue drawing a rectangle even when I am moving the mouse over the image after I have clicked the left button.

Unfortunately, Now, the rectangle is being displayed only after I release the left button at the end.

# import the necessary packages
import argparse
import cv2

# initialize the list of reference points and boolean indicating
# whether cropping is being performed or not
refPt = []
cropping = False

def click_and_crop(event, x, y, flags, param):
    # grab references to the global variables
global refPt, cropping, image
drag = 0
# if the left mouse button was clicked, record the starting
# (x, y) coordinates and indicate that cropping is being
# performed
if event == cv2.EVENT_LBUTTONDOWN:
    refPt = [(x, y)]
        drag = 1
    cropping = True

# check to see if the left mouse button was released
elif event == cv2.EVENT_LBUTTONUP:
    # record the ending (x, y) coordinates and indicate that
    # the cropping operation is finished
    refPt.append((x, y))
    cropping = False

    # draw a rectangle around the region of interest
    cv2.rectangle(image, refPt[0], refPt[1], (0, 255, 0), 2)
    cv2.imshow("image", image)

elif event == cv2.EVENT_MOUSEMOVE and drag == 1:
    #image = clone.copy()
    cv2.rectangle(image, refPt[0], (x, y), (0, 255, 0), 2)

# load the image, clone it, and setup the mouse callback function
image = cv2.imread("image_00001.jpg")
clone = image.copy()
cv2.namedWindow("image")
cv2.setMouseCallback("image", click_and_crop)

# keep looping until the 'q' key is pressed
while True:
# display the image and wait for a keypress
    cv2.imshow("image", image)
    key = cv2.waitKey(1) & 0xFF

# if the 'r' key is pressed, reset the cropping region
if key == ord("r"):
    image = clone.copy()

# if the 'c' key is pressed, break from the loop
elif key == ord("c"):
    break

# if there are two reference points, then crop the region of interest
# from teh image and display it
if len(refPt) == 2:
    roi = clone[refPt[0][1]:refPt[1][1], refPt[0][0]:refPt[1][0]]
    cv2.imshow("ROI", roi)
    cv2.waitKey(0)

# close all open windows
cv2.destroyAllWindows()

Body:
Try below code:

import cv2

refPt = []

final_boundaries = []
image = None

def click_and_crop(event, x, y, flags, param):
    global refPt, image
    if event == cv2.EVENT_LBUTTONDOWN:
        refPt = [(x, y)]
    elif event == cv2.EVENT_LBUTTONUP:
        refPt.append((x, y))
        final_boundaries.append((refPt[0],refPt[1]))
        cv2.rectangle(image, refPt[0], refPt[1], (0, 255, 0), 2)
        cv2.imshow("image", image)
    elif event == cv2.EVENT_MOUSEMOVE and flags == cv2.EVENT_FLAG_LBUTTON:
        clone = image.copy()
        cv2.rectangle(clone, refPt[0], (x, y), (0, 255, 0), 2)
        cv2.imshow("image", clone)

def main(image_name):
    global image
    image = cv2.imread("image.png") #convert to image boundary
    cv2.namedWindow("image")
    cv2.setMouseCallback("image", click_and_crop)
    cv2.imshow("image", image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    return (final_boundaries)

ContentLicense: CC BY-SA 4.0


问:
AWS Serverless + Cloud Formation: Error on single function deploy - Windows 10 Env
I have a problem regarding the deploy in AWS of a single function using Serverless and Cloud Formation. I am using Windows 10 - 64 bit as OS.

Env:

```<code> Your Environment Information ---------------------------
     Operating System:          win32
     Node Version:              10.16.3
     Framework Version:         1.52.1
     Plugin Version:            3.0.0
     SDK Version:               2.1.1
</code>```

Basically, when I run the classical deploy of all my AWS env (sls deploy -s dev), everything works just fine. But when I try to deploy a single Lambda Function, on which I have changes, using this command:

```<code>sls deploy function -f MyLambdaFunc -s dev
</code>```

I get this error:

```<code>TypeError: Cannot read property 'artifact' of undefined
      at ServerlessPythonRequirements.BbPromise.bind.then.then.then (C:\Users\user\Documents\company\client\AWS_environment\deployment\node_modules\serverless-python-requirements\index.js:176:48)
  From previous event:
      at PluginManager.invoke (C:\Users\user\AppData\Roaming\npm\node_modules\serverless\lib\classes\PluginManager.js:505:22)
      at getHooks.reduce.then (C:\Users\user\AppData\Roaming\npm\node_modules\serverless\lib\classes\PluginManager.js:540:24)
  From previous event:
      at PluginManager.run (C:\Users\user\AppData\Roaming\npm\node_modules\serverless\lib\classes\PluginManager.js:540:8)
      at variables.populateService.then (C:\Users\user\AppData\Roaming\npm\node_modules\serverless\lib\Serverless.js:115:33)
      at runCallback (timers.js:705:18)
      at tryOnImmediate (timers.js:676:5)
      at processImmediate (timers.js:658:5)
      at process.topLevelDomainCallback (domain.js:126:23)
  From previous event:
      at Serverless.run (C:\Users\user\AppData\Roaming\npm\node_modules\serverless\lib\Serverless.js:102:74)
      at serverless.init.then (C:\Users\user\AppData\Roaming\npm\node_modules\serverless\bin\serverless.js:67:28)
      at C:\Users\user\AppData\Roaming\npm\node_modules\serverless\node_modules\graceful-fs\graceful-fs.js:136:16
      at C:\Users\user\AppData\Roaming\npm\node_modules\serverless\node_modules\graceful-fs\graceful-fs.js:57:14
      at FSReqWrap.args [as oncomplete] (fs.js:140:20)
  From previous event:
      at initializeErrorReporter.then (C:\Users\user\AppData\Roaming\npm\node_modules\serverless\bin\serverless.js:67:6)
      at runCallback (timers.js:705:18)
      at tryOnImmediate (timers.js:676:5)
      at processImmediate (timers.js:658:5)
      at process.topLevelDomainCallback (domain.js:126:23)
  From previous event:
      at Object.<anonymous> (C:\Users\user\AppData\Roaming\npm\node_modules\serverless\bin\serverless.js:53:39)
      at Module._compile (internal/modules/cjs/loader.js:778:30)
      at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
      at Module.load (internal/modules/cjs/loader.js:653:32)
      at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
      at Function.Module._load (internal/modules/cjs/loader.js:585:3)
      at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
      at startup (internal/bootstrap/node.js:283:19)
      at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
</code>```

Someone knows why? Maybe is there something wrong with my npm installation on Windows 10?

答:
I found a workaround but I'm not sure about the side effects.

The problem is the following line (line # 176 in my version) in serverless-python-requirements/index.js file:

```<code>arguments[1].functionObj &&
    arguments[1].functionObj.package.artifact.
</code>```

It simply assumes the existence of package.artifact path in your function definition in serverless.yml.

As a work around I added "package: artifact:" to my function as follows and it worked:

```<code>hello:
    handler: hello.handler
    package:
      artifact:
    events:
      - http:
          path: hello
          method: get
</code>```

Again, I'm not sure if this breaks anything else. I have just tried an individual function deployment and it worked. But I didn't make a detailed test.

Body:
I have a problem regarding the deploy in AWS of a single function using Serverless and Cloud Formation. I am using Windows 10 - 64 bit as OS.

Env:

 Your Environment Information ---------------------------
     Operating System:          win32
     Node Version:              10.16.3
     Framework Version:         1.52.1
     Plugin Version:            3.0.0
     SDK Version:               2.1.1

Basically, when I run the classical deploy of all my AWS env (sls deploy -s dev), everything works just fine. But when I try to deploy a single Lambda Function, on which I have changes, using this command:

sls deploy function -f MyLambdaFunc -s dev

I get this error:

TypeError: Cannot read property 'artifact' of undefined
      at ServerlessPythonRequirements.BbPromise.bind.then.then.then (C:\Users\user\Documents\company\client\AWS_environment\deployment\node_modules\serverless-python-requirements\index.js:176:48)
  From previous event:
      at PluginManager.invoke (C:\Users\user\AppData\Roaming\npm\node_modules\serverless\lib\classes\PluginManager.js:505:22)
      at getHooks.reduce.then (C:\Users\user\AppData\Roaming\npm\node_modules\serverless\lib\classes\PluginManager.js:540:24)
  From previous event:
      at PluginManager.run (C:\Users\user\AppData\Roaming\npm\node_modules\serverless\lib\classes\PluginManager.js:540:8)
      at variables.populateService.then (C:\Users\user\AppData\Roaming\npm\node_modules\serverless\lib\Serverless.js:115:33)
      at runCallback (timers.js:705:18)
      at tryOnImmediate (timers.js:676:5)
      at processImmediate (timers.js:658:5)
      at process.topLevelDomainCallback (domain.js:126:23)
  From previous event:
      at Serverless.run (C:\Users\user\AppData\Roaming\npm\node_modules\serverless\lib\Serverless.js:102:74)
      at serverless.init.then (C:\Users\user\AppData\Roaming\npm\node_modules\serverless\bin\serverless.js:67:28)
      at C:\Users\user\AppData\Roaming\npm\node_modules\serverless\node_modules\graceful-fs\graceful-fs.js:136:16
      at C:\Users\user\AppData\Roaming\npm\node_modules\serverless\node_modules\graceful-fs\graceful-fs.js:57:14
      at FSReqWrap.args [as oncomplete] (fs.js:140:20)
  From previous event:
      at initializeErrorReporter.then (C:\Users\user\AppData\Roaming\npm\node_modules\serverless\bin\serverless.js:67:6)
      at runCallback (timers.js:705:18)
      at tryOnImmediate (timers.js:676:5)
      at processImmediate (timers.js:658:5)
      at process.topLevelDomainCallback (domain.js:126:23)
  From previous event:
      at Object.<anonymous> (C:\Users\user\AppData\Roaming\npm\node_modules\serverless\bin\serverless.js:53:39)
      at Module._compile (internal/modules/cjs/loader.js:778:30)
      at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
      at Module.load (internal/modules/cjs/loader.js:653:32)
      at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
      at Function.Module._load (internal/modules/cjs/loader.js:585:3)
      at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
      at startup (internal/bootstrap/node.js:283:19)
      at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

Someone knows why? Maybe is there something wrong with my npm installation on Windows 10?

Body:
I found a workaround but I'm not sure about the side effects.

The problem is the following line (line # 176 in my version) in serverless-python-requirements/index.js file:

arguments[1].functionObj &&
    arguments[1].functionObj.package.artifact.

It simply assumes the existence of package.artifact path in your function definition in serverless.yml.

As a work around I added "package: artifact:" to my function as follows and it worked:

hello:
    handler: hello.handler
    package:
      artifact:
    events:
      - http:
          path: hello
          method: get

Again, I'm not sure if this breaks anything else. I have just tried an individual function deployment and it worked. But I didn't make a detailed test.


问:
Excel: Finding the right match from matrix "scheme"
I am trying to "match" values or patterns from one sheet to another. I got like "matrix scheme" (the first pic) where I am looking for a certain pattern which is labeled as " _ " and "1". If there is a match ("1"), I should color it in red, or green when no match (" _ "). But that part is easy.
As you can see there are 4 "cases" for now, and that is exactly what I want to have on another sheet (the second pic) as match. But I am getting only one match (from Column S ("XC0")) and empty spaces (" _ ") for others even if there is a match.

Here is my match table (on picture beneath) where I used this function:

```<code>=VLOOKUP($A10;_0528_matrix[#All];MATCH(A$10;_0528_matrix[#Headers];0);0)
</code>```

Index/Match also gave me the same results. These NA errors are fine for now, that's what I am gonna remove later.

Tried with this and still nothing...

```<code>=SUM(INDIRECT("_0528_matrix[" & A2 & "]"))
</code>```

答:
It seems you need a count, not just a match. In this case, try putting this in the cell A3:

=COUNTIF(INDIRECT("_0528_matrix[" & A2 & "]");"1")
```

<p>Another version:</p>

```=COUNTIF(INDEX(Matrix;0;MATCH(A10;Matrix[#Headers];0));"1")
```

Body:
I am trying to "match" values or patterns from one sheet to another. I got like "matrix scheme" (the first pic) where I am looking for a certain pattern which is labeled as " _ " and "1". If there is a match ("1"), I should color it in red, or green when no match (" _ "). But that part is easy.
As you can see there are 4 "cases" for now, and that is exactly what I want to have on another sheet (the second pic) as match. But I am getting only one match (from Column S ("XC0")) and empty spaces (" _ ") for others even if there is a match.

Here is my match table (on picture beneath) where I used this function:

=VLOOKUP($A10;_0528_matrix[#All];MATCH(A$10;_0528_matrix[#Headers];0);0)

Index/Match also gave me the same results. These NA errors are fine for now, that's what I am gonna remove later.

Tried with this and still nothing...

=SUM(INDIRECT("_0528_matrix[" & A2 & "]"))

Body:
It seems you need a count, not just a match. In this case, try putting this in the cell A3:

=COUNTIF(INDIRECT("_0528_matrix[" & A2 & "]");"1")

Another version:

=COUNTIF(INDEX(Matrix;0;MATCH(A10;Matrix[#Headers];0));"1")


问:
Selected value on a DropDownList inside of a repeater
I'm adding a dropdwonlist inside of my repeater. Now I need to set a selected value for my dropdownlist.. but I'm not being very successful..

```<code>private void PhysicianSource()
{
    DataSet ds = new DataSet();
    DataTable dt = ds.Tables.Add("Source");
    dt.Columns.Add("ID", Type.GetType("System.String"));
    dt.Columns.Add("Desc", Type.GetType("System.String"));

    Provider oProvider = new Provider();
    List<ProviderLabel> lstprovider = oProvider.RetrievePhysicianList();
    foreach (ProviderLabel item in lstprovider)
    {
        DataRow dr = dt.NewRow();
        dr[0] = item.ProviderCode.ID.ToString();
        dr[1] = item.Name.ToString();
        dt.Rows.Add(dr);
    }

    drpPhysicianCode.DataSource = ds;
    drpPhysicianCode.DataMember = "Source";
    drpPhysicianCode.DataTextField = "ID";
    drpPhysicianCode.DataValueField = "ID";
    drpPhysicianCode.DataBind();
}
</code>```

asp.net

```<code><asp:Repeater ID="rptrPatientList" runat="server" >
    <HeaderTemplate></HeaderTemplate>
    <ItemTemplate>
        <tr>
            <td class="style2">
            <asp:DropDownList  ID="DropDownList1"
                DataTextField="ID" runat="server"
                DataValueField="Desc"
                SelectedValue='<%# Eval("Code") %>'
                DataSource="ds">
            </asp:DropDownList>
            </td>

            </td>
        </tr>
</code>```

nothing happens on my codes.. help me guys I'm just a beginner on this.. thank you very much..

答:
Try setting the selected value after data binding

Don't set the list contents with every postback. Check for Page.IsPostBack(). Note that this only works if you have ViewState enabled.

Body:
I'm adding a dropdwonlist inside of my repeater. Now I need to set a selected value for my dropdownlist.. but I'm not being very successful..

private void PhysicianSource()
{
    DataSet ds = new DataSet();
    DataTable dt = ds.Tables.Add("Source");
    dt.Columns.Add("ID", Type.GetType("System.String"));
    dt.Columns.Add("Desc", Type.GetType("System.String"));

    Provider oProvider = new Provider();
    List<ProviderLabel> lstprovider = oProvider.RetrievePhysicianList();
    foreach (ProviderLabel item in lstprovider)
    {
        DataRow dr = dt.NewRow();
        dr[0] = item.ProviderCode.ID.ToString();
        dr[1] = item.Name.ToString();
        dt.Rows.Add(dr);
    }

    drpPhysicianCode.DataSource = ds;
    drpPhysicianCode.DataMember = "Source";
    drpPhysicianCode.DataTextField = "ID";
    drpPhysicianCode.DataValueField = "ID";
    drpPhysicianCode.DataBind();
}

asp.net

<asp:Repeater ID="rptrPatientList" runat="server" >
    <HeaderTemplate></HeaderTemplate>
    <ItemTemplate>

            <asp:DropDownList  ID="DropDownList1"
                DataTextField="ID" runat="server"
                DataValueField="Desc"
                SelectedValue='<%# Eval("Code") %>'
                DataSource="ds">
            </asp:DropDownList>

nothing happens on my codes.. help me guys I'm just a beginner on this.. thank you very much..


问:
Twitter Kit cannot be redirect in Swift app
TwitterKit cannot be Redirect in my app.

1. Info.Plist
Added lines

```<code><key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>twitterkit-{your consumer key}</string>
        </array>
    </dict>
</array>
<key>LSApplicationQueriesSchemes</key>
<array>
    <string>twitter</string>
    <string>twitterauth</string>
</array>
</code>```

2. App delegate

```<code>import TwitterKit
application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    Twitter.sharedInstance().start(withConsumerKey:consumer_key, consumerSecret:consumer_secret)
}

application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
    if Twitter.sharedInstance().application(app, open: url, options: options) {
        return true
    }
    return false
}
</code>```

3. LoginScreen

```<code>func twitter(){
    TWTRTwitter.sharedInstance().logIn(with: self, completion: { (session, error) in
          --
    })
}

</code>```

Can anyone show me where I'm going wrong?

答:
this is a callBack problem
So
Please Comment AppDelegate in the

func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set) {
}
and Add didFinishlaunchWithOption function in

self.window = UIWindow(frame: UIScreen.main.bounds)
let vc =  UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "GoThrough") as! UINavigationController
self.window?.rootViewController = vc
  self.window?.makeKeyAndVisible()

Body:
TwitterKit cannot be Redirect in my app.

1. Info.Plist
Added lines

<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>twitterkit-{your consumer key}</string>
        </array>
    </dict>
</array>
<key>LSApplicationQueriesSchemes</key>
<array>
    <string>twitter</string>
    <string>twitterauth</string>
</array>

2. App delegate

import TwitterKit
application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    Twitter.sharedInstance().start(withConsumerKey:consumer_key, consumerSecret:consumer_secret)
}

application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
    if Twitter.sharedInstance().application(app, open: url, options: options) {
        return true
    }
    return false
}

3. LoginScreen

func twitter(){
    TWTRTwitter.sharedInstance().logIn(with: self, completion: { (session, error) in
          --
    })
}

Can anyone show me where I'm going wrong?


问:
Page Not Found Error occured while trying to render form in django
I've been following the instructions here.

This is the error it gives me, when i try to run it on localhost:

```<code>Page not found (404)
Request Method:     GET
Request URL:    http://localhost:7000/account.html

Using the URLconf defined in gettingstarted.urls, Django tried these URL patterns, in this
order:

[name='index']
[name='account']
db/ [name='db']
admin/
^celery-progress/

The current path, account.html, didn't match any of these.

You're seeing this error because you have DEBUG = True in your Django settings file. Change
that to False, and Django will display a standard 404 page.
</code>```

This is what i have in my urls.py

```<code> urlpatterns = [
 path("", hello.views.index, name="index"),
 path("", hello.views.account, name="account"),
 path("db/", hello.views.db, name="db"),
 path("admin/", admin.site.urls),
 re_path(r'^celery-progress/', include('celery_progress.urls'))
 ]
</code>```

This is what i have in views.py

```<code>def account(request):
if request.method == 'POST':
    form = AccountForm(request.POST)

    if form.is_valid():
        return HttpResponseRedirect('loading.html')

else:
    form = Nameform()

return render(request, 'account.html', {'form': form})
</code>```

Finally this is the form itself(account.html):

```<code><form action="/account/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
</code>```

I have the feeling i'm missing something really simple but i can't for the life of me see it. Any help would be greatly appreciated.

答:
You are requesting for the url that could match the string /account/ but in your urlpatterns variable you have an empty string so it can't match anything.

Remember that the first argument of urlpatterns is a pattern string that can be matched with regex.

Perhaps you could map it like:

```<code>path("/account/", hello.views.account, name="account")
</code>```

Body:
I've been following the instructions here.

This is the error it gives me, when i try to run it on localhost:

Page not found (404)
Request Method:     GET
Request URL:    http://localhost:7000/account.html

Using the URLconf defined in gettingstarted.urls, Django tried these URL patterns, in this
order:

[name='index']
[name='account']
db/ [name='db']
admin/
^celery-progress/

The current path, account.html, didn't match any of these.

You're seeing this error because you have DEBUG = True in your Django settings file. Change
that to False, and Django will display a standard 404 page.

This is what i have in my urls.py

 urlpatterns = [
 path("", hello.views.index, name="index"),
 path("", hello.views.account, name="account"),
 path("db/", hello.views.db, name="db"),
 path("admin/", admin.site.urls),
 re_path(r'^celery-progress/', include('celery_progress.urls'))
 ]

This is what i have in views.py

def account(request):
if request.method == 'POST':
    form = AccountForm(request.POST)

    if form.is_valid():
        return HttpResponseRedirect('loading.html')

else:
    form = Nameform()

return render(request, 'account.html', {'form': form})

Finally this is the form itself(account.html):

<form action="/account/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>

I have the feeling i'm missing something really simple but i can't for the life of me see it. Any help would be greatly appreciated.

Body:
You are requesting for the url that could match the string /account/ but in your urlpatterns variable you have an empty string so it can't match anything.

Remember that the first argument of urlpatterns is a pattern string that can be matched with regex.

Perhaps you could map it like:

path("/account/", hello.views.account, name="account")


问:
How to add items in select dynamically in react?
Could you please tell me How to add items in select dynamically in react ?

I am getting response from server (name , label etc).For example I just mock my response and after two second I fetch that .

In my example I have two select box or drop down .first dropdown have value “one” and “two”(which is given as options in json).

In json there is one more option dependentField  it mean the field is dependent on another field (value mentioned is dependent).In my example second field is dependent on first field.

So the value of second select or dropdown field will be ["three", "four"] if first select box or dropdown value id one.

So the value of second select or dropdown field will be ["five", "six"] if first select box or dropdown value id two.

So I need to watch the value of field as mention in hook form

https://react-hook-form.com/get-started

Can we dynamically add options

here is code

https://codesandbox.io/s/stoic-benz-lxb8i

```<code>useEffect(() => {
    console.log("====");
    (async () => {
      var a = await FETCH_API();
      console.log("sssss");
      setState(a);
      console.log(a);
    })();
  }, []);

const getForm = () => {
    try {
      return state.map((i, index) => {
        switch (i.type) {
          case "text":
            return (
              <div key={index}>
                <label>{i.label}</label>
                <input type="text" ref={register()} name={i.name} />
              </div>
            );

          case "select":
            if (i.watch) {
              watch(i.name, null);
            }
            return (
              <div key={index}>
                <label>{i.label}</label>
                <select name={i.name} ref={register()}>
                  {i.options.map((i, idx) => {
                    return (
                      <option key={idx} value={i}>
                        {i}
                      </option>
                    );
                  })}
                  /
                </select>
              </div>
            );
          default:
            return <div>ddd</div>;
        }
      });
      return <div>ddd</div>;
    } catch (e) {}
  };
</code>```

I don’t wan’t want to do any harcoading like

```<code>useEffect(()=>{

},[‘first’])
</code>```

can we watch or add useeffect dynamically to watch change dynamically ?

Any update

答:
this is a simpl two select. Where frist select depend on second</p>

```<code>import React,{useState, useEffect} from "react"

const App = () => {

  const [state,setState] = useState({
    option1:["one","two"],
    option2: []
  })

  useEffect(()=> {
    (async () => {
      var a = await FETCH_API();
      console.log("sssss");
      setState({
        ...state,
        option2: a
      });
      console.log(a);
    })();
  },[state.option1])

  return(
    <div>
      <select>
        {
          state.option1.map((i,idx)=>{
            return(
              <option key={idx} value={i}>
              {i}
              </option>
            )
          })
        }

      </select>
      <select>
        {
          state.option2.map((i,idx)=>{
            return(
              <option key={idx} value={i}>
              {i}
              </option>
            )
          })
        }

      </select>
    </div>
  )
}

export default App
</code>```

Body:
Could you please tell me How to add items in select dynamically in react ?

I am getting response from server (name , label etc).For example I just mock my response and after two second I fetch that .

In my example I have two select box or drop down .first dropdown have value “one” and “two”(which is given as options in json).

In json there is one more option dependentField  it mean the field is dependent on another field (value mentioned is dependent).In my example second field is dependent on first field.

So the value of second select or dropdown field will be ["three", "four"] if first select box or dropdown value id one.

So the value of second select or dropdown field will be ["five", "six"] if first select box or dropdown value id two.

So I need to watch the value of field as mention in hook form

https://react-hook-form.com/get-started

Can we dynamically add options

here is code

https://codesandbox.io/s/stoic-benz-lxb8i

useEffect(() => {
    console.log("====");
    (async () => {
      var a = await FETCH_API();
      console.log("sssss");
      setState(a);
      console.log(a);
    })();
  }, []);

const getForm = () => {
    try {
      return state.map((i, index) => {
        switch (i.type) {
          case "text":
            return (

                {i.label}
                <input type="text" ref={register()} name={i.name} />

            );

          case "select":
            if (i.watch) {
              watch(i.name, null);
            }
            return (

                {i.label}
                <select name={i.name} ref={register()}>
                  {i.options.map((i, idx) => {
                    return (
                      <option key={idx} value={i}>
                        {i}
                      </option>
                    );
                  })}
                  /
                </select>

            );
          default:
            return
ddd
;
        }
      });
      return
ddd
;
    } catch (e) {}
  };

I don’t wan’t want to do any harcoading like

useEffect(()=>{

},[‘first’])

can we watch or add useeffect dynamically to watch change dynamically ?

Any update

Body:
this is a simpl two select. Where frist select depend on second

import React,{useState, useEffect} from "react"

const App = () => {

  const [state,setState] = useState({
    option1:["one","two"],
    option2: []
  })

  useEffect(()=> {
    (async () => {
      var a = await FETCH_API();
      console.log("sssss");
      setState({
        ...state,
        option2: a
      });
      console.log(a);
    })();
  },[state.option1])

  return(
    <div>
      <select>
        {
          state.option1.map((i,idx)=>{
            return(
              <option key={idx} value={i}>
              {i}
              </option>
            )
          })
        }

      </select>
      <select>
        {
          state.option2.map((i,idx)=>{
            return(
              <option key={idx} value={i}>
              {i}
              </option>
            )
          })
        }

      </select>
    </div>
  )
}

export default App


问:
Python set to array and dataframe
Interpretation by a friendly editor:

I have data in the form of a set.

```<code>import numpy as n , pandas as p
s={12,34,78,100}
print(n.array(s))
print(p.DataFrame(s))
</code>```

The above code converts the set without a problem into a numpy array.
But when I try to create a DataFrame from it I get the following error:

ValueError: DataFrame constructor not properly called!

So is there any way to convert a python set/nested set into a numpy array/dictionary so I can create a DataFrame from it?

Original Question:

I have a data in form of set .
Code

```<code> import numpy as n , pandas as p
 s={12,34,78,100}
 print(n.array(s))
 print(p.DataFrame(s))
</code>```

The above code returns same set for numpyarray  and DataFrame constructor not called at o/p . So is  there any way  to convert python set , nested set into numpy array and dictionary ??

答:
```<code>import numpy as n , pandas as p

s={12,34,78,100}

#Create DataFrame directly from set
df = p.DataFrame(s)

#Can also create a keys, values pair (dictionary) and then create Data Frame,
#it useful as key will be used as Column Header and values as data
df1 = p.DataFrame({'Values': data} for data in s)
</code>```

Title: Python set to array and dataframe

Body:
Interpretation by a friendly editor:

I have data in the form of a set.

import numpy as n , pandas as p
s={12,34,78,100}
print(n.array(s))
print(p.DataFrame(s))

The above code converts the set without a problem into a numpy array.
But when I try to create a DataFrame from it I get the following error:

ValueError: DataFrame constructor not properly called!

So is there any way to convert a python set/nested set into a numpy array/dictionary so I can create a DataFrame from it?

Original Question:

I have a data in form of set .
Code

 import numpy as n , pandas as p
 s={12,34,78,100}
 print(n.array(s))
 print(p.DataFrame(s))

The above code returns same set for numpyarray  and DataFrame constructor not called at o/p . So is  there any way  to convert python set , nested set into numpy array and dictionary ??


问:
Verilog LRM Nondeterminism
I am facing some doubts regarding the nondeterminism in Verilog Scheduling Semantics mentioned in the Verilog LRM. Below is the excerpt which I am unable to understand:

"Another source of nondeterminism is that statements without time-control constructs in behavioral blocks do not have to be
  executed as one event. Time control statements are the # expression
  and @ expression constructs (see 9.7). At any time while evaluating a
  behavioral statement, the simulator may suspend execution and place
  the partially completed event as a pending active event on the event
  queue. The effect of this is to allow the interleaving of process
  execution. Note that the order of interleaved execution is
  non-deterministic and not under control of the user."

The only inference I could make was that statements in a behavioral block may be paused for the execution of other behavioral blocks (which are active in the same timestep) so as to interleave process execution though I am not sure.

Also, I don't understand the line "statements without time-control constructs in behavioral
blocks do not have to be executed as one event". What does the LRM mean by saying it doesn't execute as one event and what would happen if a behavioral block would contain all time-controlled statements?

Can anyone please explain this with the help of some examples? Thanks in advance.

答:
The only thing which simulation guarantees is that all statements in the always blocks will be executed sequentially. Say, as in the following block:

```<code>always @(b,c,e,f) begin
   a = b | c;
   d = e & f;
   g = a ^ d ^ x;
   ...
end
</code>```

However, the simulator can decide to execute first 2 statements in a row, but then stop execution of this block before the last statement and let other blocks to continue. Then it will return to the last statement. In this sense you have a non-deterministic order of the execution of the statements.

Guess what?!  Value of x can definitely change while it is waiting. a and d can potentially also change while other statements are executed. So, result of g could be non-deterministic. Good programming will help to remove this type of non-determinism: list all events in the sensitivity list, do not multiply-drive signals, ... The simulator then will do the best to avoid those situations.

The need for this interleave simulation is to allow simulators to do better optimization for performance reasons and allow other blocks to progress in case of the very long and loopy statements.

Answering the comment about time and event controls

In the above block a simulator can decide when to break the execution. From the point of view of the programmer, it is non-deterministic. You do not know when it can happen. The only thing that is known that it would happen in the same simulation (time) tick. A good simulator will try its best to avoid any side effect of this.

Timing and delay controls provide deterministic stops. For example,

```<code>always @(b,c,e,f) begin
   a = b | c;
   d = e & f;
   #1 g = a ^ d ^ x;
   ...
end
</code>```

In the above statement with #1 you actually tell the simulator to stop execution of the statements and wait till the next time tick.

```<code>always @(b,c,e,f) begin
   a = b | c;
   d = e & f;
   @(posedge clk)
   g = a ^ d ^ x;
   ...
end
</code>```

Here it will stop execution and wait for the posedge clk event.

Note that above examples are not synthesizable and should be used in behavioral code (test bench) only. For synthesis you have to stick with the very first example and make sure that your code is written in accordance to the good Verilog coding practices.

Title: Verilog LRM Nondeterminism

Body:
The only thing which simulation guarantees is that all statements in the always blocks will be executed sequentially. Say, as in the following block:

always @(b,c,e,f) begin
   a = b | c;
   d = e & f;
   g = a ^ d ^ x;
   ...
end

However, the simulator can decide to execute first 2 statements in a row, but then stop execution of this block before the last statement and let other blocks to continue. Then it will return to the last statement. In this sense you have a non-deterministic order of the execution of the statements.

Guess what?!  Value of x can definitely change while it is waiting. a and d can potentially also change while other statements are executed. So, result of g could be non-deterministic. Good programming will help to remove this type of non-determinism: list all events in the sensitivity list, do not multiply-drive signals, ... The simulator then will do the best to avoid those situations.

The need for this interleave simulation is to allow simulators to do better optimization for performance reasons and allow other blocks to progress in case of the very long and loopy statements.

Answering the comment about time and event controls

In the above block a simulator can decide when to break the execution. From the point of view of the programmer, it is non-deterministic. You do not know when it can happen. The only thing that is known that it would happen in the same simulation (time) tick. A good simulator will try its best to avoid any side effect of this.

Timing and delay controls provide deterministic stops. For example,

always @(b,c,e,f) begin
   a = b | c;
   d = e & f;
   #1 g = a ^ d ^ x;
   ...
end

In the above statement with #1 you actually tell the simulator to stop execution of the statements and wait till the next time tick.

always @(b,c,e,f) begin
   a = b | c;
   d = e & f;
   @(posedge clk)
   g = a ^ d ^ x;
   ...
end

Here it will stop execution and wait for the posedge clk event.

Note that above examples are not synthesizable and should be used in behavioral code (test bench) only. For synthesis you have to stick with the very first example and make sure that your code is written in accordance to the good Verilog coding practices.


问:
How can I extract in excel certain strings that begin with a word from a row that contains multiple strings delimited by commas?
I have the following row in excel: ['milk', 'milk with honey','bread','milk with bread','butter','milk with butter']
I want to be able to extract all the strings that begin with the word "milk" either on separate columns or in the same column.
The extract should look like: milk, milk with honey, milk with bread, milk with butter.</p>

答:
This is a rough scetch of an VBA approach. Obviously you gotta fit it into an appropriate loop to apply for the whole sheet. Maybe there need to be some more error handling, but it should give you an idea:</p>

```<code>Sub extract_string()

Dim l As Long
Dim search_string As String
Dim next_item As Integer
Dim next_col As Integer

search_string = Cells(1, 1).Value

For l = 1 To Len(search_string) 'loop through string

    If (Mid(search_string, l, 4) = "milk") Then 'check, if milk

        On Error GoTo Last_Item
        next_item = WorksheetFunction.Find(",", search_string, l + 1)

        next_col = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column + 1 'find end

        If (next_item <> 0) Then

            Cells(1, next_col).Value = Mid(search_string, l, next_item - l)

        Else
Last_Item:
            Cells(1, next_col + 1).Value = Mid(search_string, l, Len(search_string) - l + 1) 'last item handling

        End If

    End If

next_item = 0

Next l

End Sub
</code>```

Body:
This is a rough scetch of an VBA approach. Obviously you gotta fit it into an appropriate loop to apply for the whole sheet. Maybe there need to be some more error handling, but it should give you an idea:

Sub extract_string()

Dim l As Long
Dim search_string As String
Dim next_item As Integer
Dim next_col As Integer

search_string = Cells(1, 1).Value

For l = 1 To Len(search_string) 'loop through string

    If (Mid(search_string, l, 4) = "milk") Then 'check, if milk

        On Error GoTo Last_Item
        next_item = WorksheetFunction.Find(",", search_string, l + 1)

        next_col = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column + 1 'find end

        If (next_item <> 0) Then

            Cells(1, next_col).Value = Mid(search_string, l, next_item - l)

        Else
Last_Item:
            Cells(1, next_col + 1).Value = Mid(search_string, l, Len(search_string) - l + 1) 'last item handling

        End If

    End If

next_item = 0

Next l

End Sub


问:
Passing variables to Class from HTML
I want to pass some image names and numbers as string to my flash, so in html file I have :

```<code>src="imgvid-00.swf?imageData=image00/00.gif,3,image00/01.gif,6,image00/02.gif,10"
</code>```

in flash swf I have a class like this:

```<code>package src{
    import flash.display.*;
    import flash....

    public class imgvid extends MovieClip {
        public var dataBANK:Array = new Array();

        public function imgvid():void {
            //put all var in Array dataBANK
        }
    }
}
</code>```

How I do this?
I try :
public var paramObj = this.loaderInfo.parameters;
but that does not work ...

答:
You need to pass paramters  in as flashvars. query parameters are not passed into flash in the way you have in your example. Read up about flashvars here:

http://kb2.adobe.com/cps/164/tn_16417.html

```<code><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="550" height="400" id="myFlashMovie" align="middle">
    <param name="movie" value="myFlashMovie.swf" />
    <param name=FlashVars value="myVariable=Hello%20World&mySecondVariable=Goodbye">
    <!--[if !IE]>-->
    <object type="application/x-shockwave-flash" data="myFlashMovie.swf" width="550" height="400">
        <param name="movie" value="myFlashMovie.swf" />
        <param name=FlashVars value="myVariable=Hello%20World&mySecondVariable=Goodbye">
    <!--<![endif]-->
        <a href="http://www.adobe.com/go/getflash">
            <img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" />
        </a>
    <!--[if !IE]>-->
    </object>
    <!--<![endif]-->
</object>
</code>```

using swf object to do all this makes it easier than doing it manually as above

http://code.google.com/p/swfobject/

Title: Passing variables to Class from HTML

Body:
I want to pass some image names and numbers as string to my flash, so in html file I have :

src="imgvid-00.swf?imageData=image00/00.gif,3,image00/01.gif,6,image00/02.gif,10"

in flash swf I have a class like this:

package src{
    import flash.display.*;
    import flash....

    public class imgvid extends MovieClip {
        public var dataBANK:Array = new Array();

        public function imgvid():void {
            //put all var in Array dataBANK
        }
    }
}

How I do this?
I try :
public var paramObj = this.loaderInfo.parameters;
but that does not work ...

Body:
You need to pass paramters  in as flashvars. query parameters are not passed into flash in the way you have in your example. Read up about flashvars here:

http://kb2.adobe.com/cps/164/tn_16417.html

<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="550" height="400" id="myFlashMovie" align="middle">
    <param name="movie" value="myFlashMovie.swf" />
    <param name=FlashVars value="myVariable=Hello%20World&mySecondVariable=Goodbye">
    <!--[if !IE]>-->
    <object type="application/x-shockwave-flash" data="myFlashMovie.swf" width="550" height="400">
        <param name="movie" value="myFlashMovie.swf" />
        <param name=FlashVars value="myVariable=Hello%20World&mySecondVariable=Goodbye">
    <!--<![endif]-->
        <a href="http://www.adobe.com/go/getflash">
            <img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" />
        </a>
    <!--[if !IE]>-->
    </object>
    <!--<![endif]-->
</object>

using swf object to do all this makes it easier than doing it manually as above

http://code.google.com/p/swfobject/


问:
Parse and render SVG from string
I'm trying to parse SVG from string with DOMParser. If SVG string has attribute xmlns, then element renders correctly. Otherwise browser don't render it, but element exist in DOM (it's visible in dev tools).

In this example renders only first element:
https://jsfiddle.net/Severn101/jatkyvw7/

```<code>var circle1 = '<circle cx="25" cy="25" r="25" xmlns="http://www.w3.org/2000/svg" />';
var circle2 = '<circle cx="25" cy="25" r="25" />';
var svgElement = document.getElementById('svg');

var parser = new DOMParser();
var doc1 = parser.parseFromString(circle1, "image/svg+xml").documentElement;
var doc2 = parser.parseFromString(circle2, "image/svg+xml").documentElement;

svgElement.appendChild(doc1);
svgElement.appendChild(doc2);
</code>```

Why is this happening and how parse svg string without mlns attribute?

答:
When you create the elements using DOMParser it's create them as an html element, not as svg element. That's why it's not displaying, even it's added to the DOM.

In the first circle you add a namspace. it's indicate that it is xml and it is why it's appear in your fiddle. (However you have same cx and cy for both circles, so even if they both will rendered you will see only one, since they will be on top of one another)

But if you have it as a String, why not just use innerHTML?

innerHTML=circle1 for replace, and innserHTML+=circle1 for append

var circle1 = '<circle cx="50" cy="25" r="25" fill="green"/>';
var circle2 = '<circle cx="100" cy="25" r="25" fill="red"/>';
var svgElement = document.getElementById('svg');
svgElement.innerHTML += circle1+circle2;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 150 50" id="svg"></svg></code>```

Title: Parse and render SVG from string

Body:
I'm trying to parse SVG from string with DOMParser. If SVG string has attribute xmlns, then element renders correctly. Otherwise browser don't render it, but element exist in DOM (it's visible in dev tools).

In this example renders only first element:
https://jsfiddle.net/Severn101/jatkyvw7/

var circle1 = '<circle cx="25" cy="25" r="25" xmlns="http://www.w3.org/2000/svg" />';
var circle2 = '<circle cx="25" cy="25" r="25" />';
var svgElement = document.getElementById('svg');

var parser = new DOMParser();
var doc1 = parser.parseFromString(circle1, "image/svg+xml").documentElement;
var doc2 = parser.parseFromString(circle2, "image/svg+xml").documentElement;

svgElement.appendChild(doc1);
svgElement.appendChild(doc2);

Why is this happening and how parse svg string without mlns attribute?

Body:
When you create the elements using DOMParser it's create them as an html element, not as svg element. That's why it's not displaying, even it's added to the DOM.

In the first circle you add a namspace. it's indicate that it is xml and it is why it's appear in your fiddle. (However you have same cx and cy for both circles, so even if they both will rendered you will see only one, since they will be on top of one another)

But if you have it as a String, why not just use innerHTML?

innerHTML=circle1 for replace, and innserHTML+=circle1 for append

var circle1 = '<circle cx="50" cy="25" r="25" fill="green"/>';
var circle2 = '<circle cx="100" cy="25" r="25" fill="red"/>';
var svgElement = document.getElementById('svg');
svgElement.innerHTML += circle1+circle2;

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 150 50" id="svg"></svg>


问:
Jmeter script for SSO authentication in Kerberos (Windows)
I am trying to implement a Jmeter script (jmeter version 5.1)for SSO functionality with Kerberos.
I have done the set-up in the krb5 and jass conf files and have also updated HTTP Authorization Manager with the Domain,Realm and mechanism as Kerberos.

The script does not output the SAML Response in the URL when running the script. Checking the jmeter logs gives the below error:

```<code>2020-02-14 12:32:23,453 WARN o.a.j.p.h.c.KerberosManager: Could not log in user gl0
javax.security.auth.login.LoginException: null (68)
        at com.sun.security.auth.module.Krb5LoginModule.attemptAuthentication(Unknown Source) ~[?:1.8.0_241]
        at com.sun.security.auth.module.Krb5LoginModule.login(Unknown Source) ~[?:1.8.0_241]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_241]
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[?:1.8.0_241]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[?:1.8.0_241]
        at java.lang.reflect.Method.invoke(Unknown Source) ~[?:1.8.0_241]
        at javax.security.auth.login.LoginContext.invoke(Unknown Source) ~[?:1.8.0_241]
        at javax.security.auth.login.LoginContext.access$000(Unknown Source) ~[?:1.8.0_241]
        at javax.security.auth.login.LoginContext$4.run(Unknown Source) ~[?:1.8.0_241]
        at javax.security.auth.login.LoginContext$4.run(Unknown Source) ~[?:1.8.0_241]
        at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_241]
        at javax.security.auth.login.LoginContext.invokePriv(Unknown Source) ~[?:1.8.0_241]
        at javax.security.auth.login.LoginContext.login(Unknown Source) ~[?:1.8.0_241]
        at org.apache.jmeter.protocol.http.control.KerberosManager.lambda$getSubjectForUser$0(KerberosManager.java:70) ~[ApacheJMeter_http.jar:5.1 r1853635]
        at java.util.concurrent.FutureTask.run(Unknown Source) [?:1.8.0_241]
        at org.apache.jmeter.protocol.http.control.KerberosManager.getSubjectForUser(KerberosManager.java:83) [ApacheJMeter_http.jar:5.1 r1853635]
        at org.apache.jmeter.protocol.http.control.AuthManager.getSubjectForUrl(AuthManager.java:294) [ApacheJMeter_http.jar:5.1 r1853635]
        at org.apache.jmeter.protocol.http.sampler.HTTPHC4Impl.executeRequest(HTTPHC4Impl.java:829) [ApacheJMeter_http.jar:5.1 r1853635]
        at org.apache.jmeter.protocol.http.sampler.HTTPHC4Impl.sample(HTTPHC4Impl.java:572) [ApacheJMeter_http.jar:5.1 r1853635]
        at org.apache.jmeter.protocol.http.sampler.HTTPSamplerProxy.sample(HTTPSamplerProxy.java:67) [ApacheJMeter_http.jar:5.1 r1853635]
        at org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase.sample(HTTPSamplerBase.java:1231) [ApacheJMeter_http.jar:5.1 r1853635]
        at org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase.sample(HTTPSamplerBase.java:1220) [ApacheJMeter_http.jar:5.1 r1853635]
        at org.apache.jmeter.threads.JMeterThread.doSampling(JMeterThread.java:622) [ApacheJMeter_core.jar:5.1 r1853635]
        at org.apache.jmeter.threads.JMeterThread.executeSamplePackage(JMeterThread.java:546) [ApacheJMeter_core.jar:5.1 r1853635]
        at org.apache.jmeter.threads.JMeterThread.processSampler(JMeterThread.java:486) [ApacheJMeter_core.jar:5.1 r1853635]
        at org.apache.jmeter.threads.JMeterThread.run(JMeterThread.java:253) [ApacheJMeter_core.jar:5.1 r1853635]
        at java.lang.Thread.run(Unknown Source) [?:1.8.0_241]
    Caused by: sun.security.krb5.KrbException: null (68)
        at sun.security.krb5.KrbAsRep.<init>(Unknown Source) ~[?:1.8.0_241]
        at sun.security.krb5.KrbAsReqBuilder.send(Unknown Source) ~[?:1.8.0_241]
        at sun.security.krb5.KrbAsReqBuilder.action(Unknown Source) ~[?:1.8.0_241]
        ... 27 more
</code>```

答:
Unfortunately your question doesn't have enough details in order to guess the failure reason, going forward consider adding screenshots of:

HTTP Request sampler

HTTP Authorization Manager

Contents of krb5.conf and jaas.conf files

It would be also beneficial to have more verbose logs, add the next line to log4j2.xml file:

```<code><Logger name="org.apache.jmeter.protocol.http.control" level="debug" />
</code>```

and set sun.security.krb5.debug system property to true

More information:

Logging and error messages

Windows Authentication with Apache JMeter

Kerberos Troubleshooting

Body:
I am trying to implement a Jmeter script (jmeter version 5.1)for SSO functionality with Kerberos.
I have done the set-up in the krb5 and jass conf files and have also updated HTTP Authorization Manager with the Domain,Realm and mechanism as Kerberos.

The script does not output the SAML Response in the URL when running the script. Checking the jmeter logs gives the below error:

2020-02-14 12:32:23,453 WARN o.a.j.p.h.c.KerberosManager: Could not log in user gl0
javax.security.auth.login.LoginException: null (68)
        at com.sun.security.auth.module.Krb5LoginModule.attemptAuthentication(Unknown Source) ~[?:1.8.0_241]
        at com.sun.security.auth.module.Krb5LoginModule.login(Unknown Source) ~[?:1.8.0_241]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_241]
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[?:1.8.0_241]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[?:1.8.0_241]
        at java.lang.reflect.Method.invoke(Unknown Source) ~[?:1.8.0_241]
        at javax.security.auth.login.LoginContext.invoke(Unknown Source) ~[?:1.8.0_241]
        at javax.security.auth.login.LoginContext.access$000(Unknown Source) ~[?:1.8.0_241]
        at javax.security.auth.login.LoginContext$4.run(Unknown Source) ~[?:1.8.0_241]
        at javax.security.auth.login.LoginContext$4.run(Unknown Source) ~[?:1.8.0_241]
        at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_241]
        at javax.security.auth.login.LoginContext.invokePriv(Unknown Source) ~[?:1.8.0_241]
        at javax.security.auth.login.LoginContext.login(Unknown Source) ~[?:1.8.0_241]
        at org.apache.jmeter.protocol.http.control.KerberosManager.lambda$getSubjectForUser$0(KerberosManager.java:70) ~[ApacheJMeter_http.jar:5.1 r1853635]
        at java.util.concurrent.FutureTask.run(Unknown Source) [?:1.8.0_241]
        at org.apache.jmeter.protocol.http.control.KerberosManager.getSubjectForUser(KerberosManager.java:83) [ApacheJMeter_http.jar:5.1 r1853635]
        at org.apache.jmeter.protocol.http.control.AuthManager.getSubjectForUrl(AuthManager.java:294) [ApacheJMeter_http.jar:5.1 r1853635]
        at org.apache.jmeter.protocol.http.sampler.HTTPHC4Impl.executeRequest(HTTPHC4Impl.java:829) [ApacheJMeter_http.jar:5.1 r1853635]
        at org.apache.jmeter.protocol.http.sampler.HTTPHC4Impl.sample(HTTPHC4Impl.java:572) [ApacheJMeter_http.jar:5.1 r1853635]
        at org.apache.jmeter.protocol.http.sampler.HTTPSamplerProxy.sample(HTTPSamplerProxy.java:67) [ApacheJMeter_http.jar:5.1 r1853635]
        at org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase.sample(HTTPSamplerBase.java:1231) [ApacheJMeter_http.jar:5.1 r1853635]
        at org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase.sample(HTTPSamplerBase.java:1220) [ApacheJMeter_http.jar:5.1 r1853635]
        at org.apache.jmeter.threads.JMeterThread.doSampling(JMeterThread.java:622) [ApacheJMeter_core.jar:5.1 r1853635]
        at org.apache.jmeter.threads.JMeterThread.executeSamplePackage(JMeterThread.java:546) [ApacheJMeter_core.jar:5.1 r1853635]
        at org.apache.jmeter.threads.JMeterThread.processSampler(JMeterThread.java:486) [ApacheJMeter_core.jar:5.1 r1853635]
        at org.apache.jmeter.threads.JMeterThread.run(JMeterThread.java:253) [ApacheJMeter_core.jar:5.1 r1853635]
        at java.lang.Thread.run(Unknown Source) [?:1.8.0_241]
    Caused by: sun.security.krb5.KrbException: null (68)
        at sun.security.krb5.KrbAsRep.<init>(Unknown Source) ~[?:1.8.0_241]
        at sun.security.krb5.KrbAsReqBuilder.send(Unknown Source) ~[?:1.8.0_241]
        at sun.security.krb5.KrbAsReqBuilder.action(Unknown Source) ~[?:1.8.0_241]
        ... 27 more

Body:
Unfortunately your question doesn't have enough details in order to guess the failure reason, going forward consider adding screenshots of:

HTTP Request sampler

HTTP Authorization Manager

Contents of krb5.conf and jaas.conf files

It would be also beneficial to have more verbose logs, add the next line to log4j2.xml file:

<Logger name="org.apache.jmeter.protocol.http.control" level="debug" />

and set sun.security.krb5.debug system property to true

More information:

Logging and error messages

Windows Authentication with Apache JMeter

Kerberos Troubleshooting


问:
Error when I tried to assign a value in Angular
I have an object in angular:

```<code>export class Task {
  taskId: number;
  description: string;
  date: string;
  project: Project;
}
</code>```

And in a component, I want to have a method that adds a new task. And for this I created a component:

```<code>export class CreateNewTaskComponent implements OnInit {

  task: Task = new Task();
  projectName: string;
  newTask: Task = new Task();

  constructor(
    private taskService: TaskService,
    private projectService: ProjectService,
    private router: Router) {
  }

  addANewTask() {
    this.projectService.getProjectByProjectName(this.projectName).subscribe(
      (project) => {
        this.project = project;
        console.log('Project: ' + JSON.stringify(this.project));
      }
    );

    this.newTask.description = this.task.description;
    this.newTask.date = this.task.date;
    this.newTask.project = this.project;

    this.taskService.createNewTask(this.newTask).subscribe(
      task => {
        console.log(task);
        this.router.navigate(['/tasks']);
      });
  }
</code>```

I have created a Project object based on the project name. When I did console.log('Project: ' + JSON.stringify(this.project)); I received the correct answer. But when I tried to assign the project to a new task  this.newTask.project = this.project; the result is undefined.

答:
Because this.newTaskProject = this.project operation happens before this.project = project; which is in subscribe.

You can consider this:

addANewTask() {
    this.projectService
        .getProjectByProjectName(this.projectName)
        .pipe(
            switchMap(project => {
                this.newTask.description = this.task.description;
                this.newTask.date = this.task.date;
                this.newTask.project = project;

                return this.taskService.createNewTask(this.newTask);
            })
        )
        .subscribe(task => {
            console.log(task);
            this.router.navigate(['/tasks']);
        });
}
```

Body:
I have an object in angular:

export class Task {
  taskId: number;
  description: string;
  date: string;
  project: Project;
}

And in a component, I want to have a method that adds a new task. And for this I created a component:

export class CreateNewTaskComponent implements OnInit {

  task: Task = new Task();
  projectName: string;
  newTask: Task = new Task();

  constructor(
    private taskService: TaskService,
    private projectService: ProjectService,
    private router: Router) {
  }

  addANewTask() {
    this.projectService.getProjectByProjectName(this.projectName).subscribe(
      (project) => {
        this.project = project;
        console.log('Project: ' + JSON.stringify(this.project));
      }
    );

    this.newTask.description = this.task.description;
    this.newTask.date = this.task.date;
    this.newTask.project = this.project;

    this.taskService.createNewTask(this.newTask).subscribe(
      task => {
        console.log(task);
        this.router.navigate(['/tasks']);
      });
  }

I have created a Project object based on the project name. When I did console.log('Project: ' + JSON.stringify(this.project)); I received the correct answer. But when I tried to assign the project to a new task  this.newTask.project = this.project; the result is undefined.


问:
Application not terminated after all code executed
I'm about to learn the java threading facility.

I have 2 classes:

```<code>public class Main {
    public static void main(String[] arg) throws Exception {

        Timer timer = new Timer();
        timer.schedule(new ExecuteTimer(Thread.currentThread()), 2000);

        try {
            Thread.currentThread().join();
        } catch (InterruptedException ex) {
            System.out.println("timer stopped");
        }
        System.out.println("try block executed");
    }
}
</code>```

and the timer class:

```<code>public class ExecuteTimer extends TimerTask {
    public ExecuteTimer(Thread thread) {
        creatingThread = thread;
    }
    private Thread creatingThread;

    @Override
    public void run() {
        System.out.println("I'm executed!");
        creatingThread.interrupt();

    }

}
</code>```

When I debug the code. I have following output:

```<code>I'm executed!
timer stopped
try block executed
</code>```

Everything seems to be final except the app didn't exit after I have the output above. The eclipse remain in debug mode and no exception has been thrown.

答: Use thread.setDaemon(true) to tell the JVM to make the thread a daemon thread. Daemon threads do not prevent the program from exiting.

Body:
I'm about to learn the java threading facility.

I have 2 classes:

public class Main {
    public static void main(String[] arg) throws Exception {

        Timer timer = new Timer();
        timer.schedule(new ExecuteTimer(Thread.currentThread()), 2000);

        try {
            Thread.currentThread().join();
        } catch (InterruptedException ex) {
            System.out.println("timer stopped");
        }
        System.out.println("try block executed");
    }
}

and the timer class:

public class ExecuteTimer extends TimerTask {
    public ExecuteTimer(Thread thread) {
        creatingThread = thread;
    }
    private Thread creatingThread;

    @Override
    public void run() {
        System.out.println("I'm executed!");
        creatingThread.interrupt();

    }

}

When I debug the code. I have following output:

I'm executed!
timer stopped
try block executed

Everything seems to be final except the app didn't exit after I have the output above. The eclipse remain in debug mode and no exception has been thrown.


问:
SSRS Conditional Max
I would like my expression to return the max value of a column where another column equals "0".

example :

0 12

0 11

0 7

1 3

1 40

1 1

This should return 12.
I tried several things but can't make it work.
Any ideas?

答:
Try something like.

```<code>=MAX(IIF(Fields!ColumnA.Value = 0, Fields!ColumnB.Value, -99999))
</code>```

Column A and B refer to your unnamed columns in your sample data. The -99999 should be a value lower than the lowest Columb B value you will ever get. If Column B is always positive then any negative value or even 0 will suffice here.

The expression reads:
"for each row, look in Column A. If Column A is zero then return Column B's value, if Column A is not zero, return -99999. Now get the MAX value from these values"

Title: SSRS Conditional Max

Body:
Try something like.

=MAX(IIF(Fields!ColumnA.Value = 0, Fields!ColumnB.Value, -99999))

Column A and B refer to your unnamed columns in your sample data. The -99999 should be a value lower than the lowest Columb B value you will ever get. If Column B is always positive then any negative value or even 0 will suffice here.

The expression reads:
"for each row, look in Column A. If Column A is zero then return Column B's value, if Column A is not zero, return -99999. Now get the MAX value from these values"


问:
Port was already in use
I'm developing spring boot application. Everything was great, until another restart. Now i always get this error on Windows 10:

```<code>***************************
APPLICATION FAILED TO START
***************************

Description:

Web server failed to start. Port 8080 was already in use.
</code>```

For every port

```<code>Web server failed to start. Port 27010 was already in use.

Web server failed to start. Port 9090 was already in use.
</code>```

i tried to seek the process using port by netstat -ano and got nothing. Reload doesn't help, administrator mode on Intellij IDEA too. As you see, changing port doesn't help and i think that the problem is deeper, maybe there are couple of active instances of application, but i cant find them and terminate

EDIT: SOLUTION

In application.properties was defined a static IP of PC. When Internet connection have changed, tomcat became unable to bind any of ports, because of DHCP

答: Try to stop the application from intellij and re run. You might have missed it.</p>

Title: Port was already in use

Body:
I'm developing spring boot application. Everything was great, until another restart. Now i always get this error on Windows 10:

***************************
APPLICATION FAILED TO START
***************************

Description:

Web server failed to start. Port 8080 was already in use.

For every port

Web server failed to start. Port 27010 was already in use.

Web server failed to start. Port 9090 was already in use.

i tried to seek the process using port by netstat -ano and got nothing. Reload doesn't help, administrator mode on Intellij IDEA too. As you see, changing port doesn't help and i think that the problem is deeper, maybe there are couple of active instances of application, but i cant find them and terminate

EDIT: SOLUTION

In application.properties was defined a static IP of PC. When Internet connection have changed, tomcat became unable to bind any of ports, because of DHCP


问:
How to create a iter repeats last element in rust
How to create a iter repeats last element?

for example:

[1, 2, 3] => [1, 2, 3, 3, 3, ...]

My attempt:

```<code>fn main() {
    let v = vec![1, 2, 3];
    let mut vi = v.iter().chain(repeat(v[v.len()]));
    println!("{}", vi.next().unwrap())
}
</code>```

error[E0271]: type mismatch resolving `<std::iter::Repeat<{integer}> as std::iter::IntoIterator>::Item == &{integer}`
   --> projects\notedown-ast\src\traits\to_html.rs:120:27
    |
120 |     let mut vi = v.iter().chain(repeat(v[v.len()]));
    |                           ^^^^^ expected integer, found `&{integer}`

error[E0599]: no method named `next` found for struct `std::iter::Chain<std::slice::Iter<'_, {integer}>, std::iter::Repeat<{integer}>>` in the current scope
   --> projects\notedown-ast\src\traits\to_html.rs:121:23
    |
121 |     println!("{}", vi.next().unwrap())
    |                       ^^^^ method not found in `std::iter::Chain<std::slice::Iter<'_, {integer}>, std::iter::Repeat<{integer}>>`
    |
    = note: the method `next` exists but the following trait bounds were not satisfied:
            `std::iter::Chain<std::slice::Iter<'_, {integer}>, std::iter::Repeat<{integer}>> : std::iter::Iterator`

error: aborting due to 2 previous errors
```

答:
v.iter() is an iterator of references whereas repeat is of values themselves. Plus, the last element of a vector is v[v.len() - 1].

To make it work:

```<code>use std::iter::repeat;

fn main() {
    let v = vec![1, 2, 3];
    let mut vi = v.iter().chain(repeat(&v[v.len() - 1]));
    println!("{}", vi.nth(10).unwrap());
}

</code>```

Body:
How to create a iter repeats last element?

for example:

[1, 2, 3] => [1, 2, 3, 3, 3, ...]

My attempt:

fn main() {
    let v = vec![1, 2, 3];
    let mut vi = v.iter().chain(repeat(v[v.len()]));
    println!("{}", vi.next().unwrap())
}

error[E0271]: type mismatch resolving `<std::iter::Repeat<{integer}> as std::iter::IntoIterator>::Item == &{integer}`
   --> projects\notedown-ast\src\traits\to_html.rs:120:27
    |
120 |     let mut vi = v.iter().chain(repeat(v[v.len()]));
    |                           ^^^^^ expected integer, found `&{integer}`

error[E0599]: no method named `next` found for struct `std::iter::Chain<std::slice::Iter<'_, {integer}>, std::iter::Repeat<{integer}>>` in the current scope
   --> projects\notedown-ast\src\traits\to_html.rs:121:23
    |
121 |     println!("{}", vi.next().unwrap())
    |                       ^^^^ method not found in `std::iter::Chain<std::slice::Iter<'_, {integer}>, std::iter::Repeat<{integer}>>`
    |
    = note: the method `next` exists but the following trait bounds were not satisfied:
            `std::iter::Chain<std::slice::Iter<'_, {integer}>, std::iter::Repeat<{integer}>> : std::iter::Iterator`

error: aborting due to 2 previous errors

Body:
v.iter() is an iterator of references whereas repeat is of values themselves. Plus, the last element of a vector is v[v.len() - 1].

To make it work:

use std::iter::repeat;

fn main() {
    let v = vec![1, 2, 3];
    let mut vi = v.iter().chain(repeat(&v[v.len() - 1]));
    println!("{}", vi.nth(10).unwrap());
}


问:
Xamarin.Forms not debuggable in release mode
I am trying to publish my Xamarin.Forms app to the play store and I am walking through the prep doc.

The document says I should include the following code in the AssemblyInfo.cs file.

```<code>#if DEBUG
[assembly: Application(Debuggable=true)]
#else
[assembly: Application(Debuggable=false)]
#endif
</code>```

I looked around but I can only find this file in my obj dirs which means it get's generated during the build. But not in my folder of my android project (the MyApp.Android\obj\debug or release dir)

The comments say this info is outdated but do not refer to how the 2020 way of working should be.

Where do I find this info?

答:
.NET Standard and .NET Core assemblies do not include an AssemblyInfo.cs anymore (see this question for example, actually this is related to the new Project file format, but I believe that .NET Framework assemblies still contain an AssemblyInfo.cs even in current versions of Visual Studio). The assembly information properties are now generated from the project file, see the documentation.

Anyway, nothing keeps you from defining an AssemblyInfo.cs by yourself. Just add the respective file (or another .cs file, e.g. something in the line of AssemblyProperties.cs or AssemblyAttributes.cs) to the project in question and then add the lines to that file. The default action for .cs files is to compile them, so the respective lines are automatically compiled to your assembly.

Body:
I am trying to publish my Xamarin.Forms app to the play store and I am walking through the prep doc.

The document says I should include the following code in the AssemblyInfo.cs file.

#if DEBUG
[assembly: Application(Debuggable=true)]
#else
[assembly: Application(Debuggable=false)]
#endif

I looked around but I can only find this file in my obj dirs which means it get's generated during the build. But not in my folder of my android project (the MyApp.Android\obj\debug or release dir)

The comments say this info is outdated but do not refer to how the 2020 way of working should be.

Where do I find this info?


答:
The Actions in subscribe are asynchronous therefore you have to place all the subsequent operations in the success response of the service as well.

Project variable is also not defined in the component so you can't use this.project either.

```<code>    addANewTask() {
        this.projectService.getProjectByProjectName(this.projectName).subscribe(
          (project) => {
            console.log('Project: ' + JSON.stringify(project));

            this.newTask.description = this.task.description;
            this.newTask.date = this.task.date;
            this.newTask.project = project;

            this.taskService.createNewTask(this.newTask).subscribe(
             task => {
               console.log(task);
              this.router.navigate(['/tasks']);
             });
          }
        );
      }
</code>```

Title: Error when I tried to assign a value in Angular

Body:
The Actions in subscribe are asynchronous therefore you have to place all the subsequent operations in the success response of the service as well.

Project variable is also not defined in the component so you can't use this.project either.

    addANewTask() {
        this.projectService.getProjectByProjectName(this.projectName).subscribe(
          (project) => {
            console.log('Project: ' + JSON.stringify(project));

            this.newTask.description = this.task.description;
            this.newTask.date = this.task.date;
            this.newTask.project = project;

            this.taskService.createNewTask(this.newTask).subscribe(
             task => {
               console.log(task);
              this.router.navigate(['/tasks']);
             });
          }
        );
      }


问:
Something like margin or padding except where background doesn't draw
Is there something that will do what margin does but without the background drawing in that area? For instance, when you give an element margin: 1em you get a 1em border of blank space around the element, but the background draws in that area. Is there something similar to that except where the background doesn't draw?

My problem is I'm trying to put something below three float: lefted divs and right now I can't get any spacing between that and the floated divs above it. They just abut directly against each other.

The div that is going below the float: lefted divs has the property clear: both. If there was something that made that div have space between it and that floated div above it then that would work too.

答:
Margins are supposed to be transparent. I think what you're seeing here is collapsing margins. Try putting a 1px border around your divs and see what happens.

Check out the CSS 2.1 spec:

http://www.w3.org/TR/CSS21/box.html#collapsing-margins


问:
Multiple variables definition in a bash sourced file behave differently
I have a .env file with the following:

FST_TEST=1
SCD_TEST=2
```

I run source .env and then:

If I run echo "$FST_TEST$FST_TEST" it prints 1.

If I run echo "$SCD_TEST$SCD_TEST" it prints 22.

I would have expected echo "$FST_TEST$FST_TEST" to also prints 11 but I can't manage to do it... I think there is something with the Return character.

答:
Not sure what does your .env file contains. Can you send its content??

Maybe try this:
    echo ${FST_TEST}${FST_TEST}

Hope it helps.

Body:
I have a .env file with the following:

FST_TEST=1
SCD_TEST=2

I run source .env and then:

If I run echo "$FST_TEST$FST_TEST" it prints 1.

If I run echo "$SCD_TEST$SCD_TEST" it prints 22.

I would have expected echo "$FST_TEST$FST_TEST" to also prints 11 but I can't manage to do it... I think there is something with the Return character.


问:
SQLAlchemy insert from a JSON list to database
I have a list with a JSON like so:

```<code>print(type(listed)) # <class 'list'>
print (listed)

[
   {
       "email": "x@gmail.com",
       "fullname": "xg gf",
       "points": 5,
       "image_url", "https://imgur.com/random.pmg"
   },
   {
        ... similar json for the next user and so on
   }
]
</code>```

I'm trying to insert them into my postgres database that has a model like this:

```<code>class Users(db.Model):
    __tablename__ = 'users'

    email = db.Column(db.String(), primary_key=True)
    displayName = db.Column(db.String())
    image = db.Column(db.String())
    points = db.Column(db.Integer())
</code>```

But I'm quite stuck, I've tried several approaches but none worked, anyone can guide me with an example on how to do it properly?

答:
Here is an example json list, like you provided.

```<code>json = [
   {
       "email": "x@gmail.com",
       "fullname": "xg gf",
       "points": 5,
       "image_url": "https://imgur.com/random.pmg"
   },
    {
       "email": "onur@gmail.com",
       "fullname": "o g",
       "points": 7,
       "image_url": "https://imgur.com/random_x.pmg"
   }
]
</code>```

Now create an empty dataframe all_df and run iterations inside your json list.
Each iteration creates a dataframe with the data from dictionary inside the list, transpose it and append to all_df.

```<code>import pandas as pd

all_df = pd.DataFrame()
for i in json:
    df = pd.DataFrame.from_dict(data=i, orient='index').T
    all_df = all_df.append(df)
</code>```

Output:

Now you can go ahead create a session to your database and push all_df

```<code>all_df.to_sql(con=your_session.bind, name='your_table_name', if_exists='your_preferred_method', index=False)
</code>```

Body:
I have a list with a JSON like so:

print(type(listed)) # <class 'list'>
print (listed)

[
   {
       "email": "x@gmail.com",
       "fullname": "xg gf",
       "points": 5,
       "image_url", "https://imgur.com/random.pmg"
   },
   {
        ... similar json for the next user and so on
   }
]

I'm trying to insert them into my postgres database that has a model like this:

class Users(db.Model):
    __tablename__ = 'users'

    email = db.Column(db.String(), primary_key=True)
    displayName = db.Column(db.String())
    image = db.Column(db.String())
    points = db.Column(db.Integer())

But I'm quite stuck, I've tried several approaches but none worked, anyone can guide me with an example on how to do it properly?

Body:
Here is an example json list, like you provided.

json = [
   {
       "email": "x@gmail.com",
       "fullname": "xg gf",
       "points": 5,
       "image_url": "https://imgur.com/random.pmg"
   },
    {
       "email": "onur@gmail.com",
       "fullname": "o g",
       "points": 7,
       "image_url": "https://imgur.com/random_x.pmg"
   }
]

Now create an empty dataframe all_df and run iterations inside your json list.
Each iteration creates a dataframe with the data from dictionary inside the list, transpose it and append to all_df.

import pandas as pd

all_df = pd.DataFrame()
for i in json:
    df = pd.DataFrame.from_dict(data=i, orient='index').T
    all_df = all_df.append(df)

Output:

Now you can go ahead create a session to your database and push all_df

all_df.to_sql(con=your_session.bind, name='your_table_name', if_exists='your_preferred_method', index=False)


问:
How can I make git accept a self signed certificate?
Using Git, is there a way to tell it to accept a self signed certificate?

I am using an https server to host a git server but for now the certificate is self signed.

When I try to create the repo there for the first time:

```<code>git push origin master -f
</code>```

I get the error:

```<code>error: Cannot access URL
https://the server/git.aspx/PocketReferences/, return code 22

fatal: git-http-push failed
</code>```

答:
It’s not a good practice to set http.sslVerify false.
Instead we can use SSL certificate.

So, build agent will use https with SSL certificate and PAT for authentication.

Copy the content of cer file including –begin—and –end--.

git bash on build agent =>
git config –global http.sslcainfo “C:/Program Files/Git/mingw64/ssl/certs/ca-bundle.crt”
Go to this file and append the .cer content.

Thus, build agent can access the SSL certificate

Body:
Using Git, is there a way to tell it to accept a self signed certificate?

I am using an https server to host a git server but for now the certificate is self signed.

When I try to create the repo there for the first time:

git push origin master -f

I get the error:

error: Cannot access URL
https://the server/git.aspx/PocketReferences/, return code 22

fatal: git-http-push failed


问:
Need suggestion to use suitable design pattern to create JAVA objects
I am currently having below parent child relation java objects
JCL > JOB > steps > step > dd

Class looks like below

```<code>public class Jcl {
Private  Job job;
}

public class Job {

private  String jobname;
//Below is direct property of job object
 private  List<Jobparam> jobparam;
//Below is child object of the job object
 private  List<Step> step;

}

public class Step {
private  String stepname;
//Below is direct property of step object
 private  List<Stepparam> stepparam;
//Below is child object of the step object
 private  List<Ddstatement> ddstatement;
 }

public class Stepparam {
private  String name;
private  String value;
}

public class Jobparam{
private  String name;
private  String value;
 }
</code>```

I am using getters and setters to create objects with new instance of each object.

```<code>  Job job = new Job();
    ArrayList<Jobparam> myList = new ArrayList<Jobparam>();

    job.getJobparam().addAll(myList);

   Step step = new Step();
    ArrayList<Stepparam> myList = new ArrayList<Stepparam>();

   jcl.getJob().getStep().add(step);
</code>```

And also jobparam and stepparam have same property.(I want to reuse but donno how)
I feel I am creating each new object every time and this long coding can be avoided by java design pattern.
Any suggestion  how should I proceed to make simple code would be helpful.

答:
I would suggest creating a common class for the parameter types since they are the same

```<code>public class Parameter {
    private  String name;
    private  String value;
}
</code>```

and then to declare the job and step list members to be

```<code>List<Parameter> ...
</code>```

I would also suggest adding wrapper methods for adding stuff to list, it makes the code clearer and the List is hidden and it will be easier to change to another collection type if you want. For instance

```<code>public class Job {
    //other stuff

    public void addJobParameter(Parameter parameter) {
        jobparam.add(parameter);
    }

  // and/or

    public void addJobParameters(Collection<Parameter> parameters) {
        jobparam.addAll(parameters);
    }
</code>```

Body:
I am currently having below parent child relation java objects
JCL > JOB > steps > step > dd

Class looks like below

public class Jcl {
Private  Job job;
}

public class Job {

private  String jobname;
//Below is direct property of job object
 private  List<Jobparam> jobparam;
//Below is child object of the job object
 private  List<Step> step;

}

public class Step {
private  String stepname;
//Below is direct property of step object
 private  List<Stepparam> stepparam;
//Below is child object of the step object
 private  List<Ddstatement> ddstatement;
 }

public class Stepparam {
private  String name;
private  String value;
}

public class Jobparam{
private  String name;
private  String value;
 }

I am using getters and setters to create objects with new instance of each object.

  Job job = new Job();
    ArrayList<Jobparam> myList = new ArrayList<Jobparam>();

    job.getJobparam().addAll(myList);

   Step step = new Step();
    ArrayList<Stepparam> myList = new ArrayList<Stepparam>();

   jcl.getJob().getStep().add(step);

And also jobparam and stepparam have same property.(I want to reuse but donno how)
I feel I am creating each new object every time and this long coding can be avoided by java design pattern.
Any suggestion  how should I proceed to make simple code would be helpful.

Body:
I would suggest creating a common class for the parameter types since they are the same

public class Parameter {
    private  String name;
    private  String value;
}

and then to declare the job and step list members to be

List<Parameter> ...

I would also suggest adding wrapper methods for adding stuff to list, it makes the code clearer and the List is hidden and it will be easier to change to another collection type if you want. For instance

public class Job {
    //other stuff

    public void addJobParameter(Parameter parameter) {
        jobparam.add(parameter);
    }

  // and/or

    public void addJobParameters(Collection<Parameter> parameters) {
        jobparam.addAll(parameters);
    }


问:
One promise with undefined as return type infects other promises in Promise.all with undefined
I have a few await functions:

```<code>public async func1(): Promise<ResultType1>();
public async func2(): Promise<ResultType2>();
</code>```

One of them can return undefined:

```<code>public async func3(): Promise<ResultType3|undefined>();
</code>```

(All code is simplified and all my production defails are removed for readability).

When I use Promise.all on first two functions, all is good:

```<code>const resultAll = await Promise.all([func1(), func2()];
// resultAll: [ResultType1, ResultType2]
</code>```

But when I include func3 in the array of promises to wait on, suddenly ALL return values can be undefined:

```<code>const resultAll2 = await Promise.all([func1(), func2(), func3()]);
// resultAll: [ResultType1 | undefined, ResultType2 | undefined, ResultType3 | undefined]
</code>```

But I want to get value of type [ResultType1, ResultType2, ResultType3 | undefined].

Why does it happen, and how can I avoid it?

答:
Thanks to this answer, I was able to fix it by declaring types explicitly:

```<code>const resultAllExplicit = await Promise.all<ResultType1, ResultType2, ResultTyp3 | undefined>([func1(), func2(), func3()]);
</code>```

Still curious as to what's the reason for this.

Body:
I have a few await functions:

public async func1(): Promise<ResultType1>();
public async func2(): Promise<ResultType2>();

One of them can return undefined:

public async func3(): Promise<ResultType3|undefined>();

(All code is simplified and all my production defails are removed for readability).

When I use Promise.all on first two functions, all is good:

const resultAll = await Promise.all([func1(), func2()];
// resultAll: [ResultType1, ResultType2]

But when I include func3 in the array of promises to wait on, suddenly ALL return values can be undefined:

const resultAll2 = await Promise.all([func1(), func2(), func3()]);
// resultAll: [ResultType1 | undefined, ResultType2 | undefined, ResultType3 | undefined]

But I want to get value of type [ResultType1, ResultType2, ResultType3 | undefined].

Why does it happen, and how can I avoid it?

Body:
Thanks to this answer, I was able to fix it by declaring types explicitly:

const resultAllExplicit = await Promise.all<ResultType1, ResultType2, ResultTyp3 | undefined>([func1(), func2(), func3()]);

Still curious as to what's the reason for this.


问:
Is C really used for a lot of Scientific Computing?
I'm currently taking a math class in College called "Scientific Computing" and the professor told us that C is the most common language used for, well, scientific computing and am just wondering as to how accurate this professor is?</p>

答: For bioinformatics and computational biology, C is very popular.</p>

ContentLicense: CC BY-SA 2.5


问:
Cannot import name 'easter' from 'holidays'
I am trying to import fbprophet on Python Anaconda, however, I get this error:

```<code> ImportError: cannot import name 'easter' from 'holidays'
</code>```

Can anyone suggest what might have gone wrong?

Code:

```<code>from fbprophet import fbprophet
</code>```

答:
I faced this problem, googled and solved it.
For solution, do the followings;

Open python3.6/site-packages/fbprophet/hdays.py file.

Replace

from holidays import WEEKEND, HolidayBase, easter, rd

to

```<code>    from holidays import WEEKEND, HolidayBase
    from dateutil.easter import easter
    from dateutil.relativedelta import relativedelta as rd
</code>```

Body:
I am trying to import fbprophet on Python Anaconda, however, I get this error:

 ImportError: cannot import name 'easter' from 'holidays'

Can anyone suggest what might have gone wrong?

Code:

from fbprophet import fbprophet

Body:
I faced this problem, googled and solved it.
For solution, do the followings;

Open python3.6/site-packages/fbprophet/hdays.py file.

Replace

from holidays import WEEKEND, HolidayBase, easter, rd

to

    from holidays import WEEKEND, HolidayBase
    from dateutil.easter import easter
    from dateutil.relativedelta import relativedelta as rd