问:
Attaching a debugger to code running in another app domain programmatically
I am working on a Visual Studio extension and one of it's functions creates a new app domain and load an assembly into that app domain. Then it runs some functions in the app domain. What I'd like to do, and am not sure if it's possible, is have my extension attach a debugger to the code running in the new app domain so when that code fails, I can actually see what's going on. Right now I'm flying blind and debugging the dynamical loaded assembly is a pain.

So I have a class that creates my app domain something like this:

```<code>domain = AppDomain.CreateDomain("Test_AppDomain",
    AppDomain.CurrentDomain.Evidence,
    AppDomain.CurrentDomain.SetupInformation);
</code>```

And then creates an object like this:

```<code>myCollection = domain.CreateInstanceAndUnwrap(
            typeof(MyCollection).Assembly.FullName,
            typeof(MyCollection).FullName,
            false,
            BindingFlags.Default,
            null,
            new object[] { assemblyPath }, null, null);
</code>```

MyCollection does something like this in it's constructor:

```<code>_assembly = Assembly.LoadFrom(assemblyPath);
</code>```

So now that assembly has been loaded into Test_AppDomain since the MyCollection object was created in that domain. And it's that loaded assembly that I need to be able to attach the debugger to.

At some point myCollection creates an instance of an object and hooks up some events:

```<code>currentObject = Activator.CreateInstance(objectType) as IObjectBase;
proxy.RunRequested += (o, e) => { currentObject?.Run(); };
</code>```

And basically where I have the handler for RunRequested and it runs currentObject?.Run(), I want to have a debugger attached, although it probably wouldn't be a problem (and may actually work better) if the debugger was attached earlier.

So is there a way to achieve this? Is it possible to programmatically attach a debugger when the user triggers the event that will lead to the Run function of the object created in the new AppDomain being called? How do I get the debugger attached to that (and not the extension itself)?

I tried something like this:

```<code>var processes = dte.Debugger.LocalProcesses.Cast<EnvDTE.Process>();
var currentProcess = System.Diagnostics.Process.GetCurrentProcess().Id;
var process = processes.FirstOrDefault(p => p.ProcessID == currentProcess);
process?.Attach();
</code>```

But it seems the id from System.Diagnostics.Process.GetCurrentProcess().Id doesn't exist within LocalProcesses?

答: One way to get around this is to generate another assembly with a function that will take in a MethodInfo object and simply call System.Diagnostics.Debugger.Launch() and then the given MethodInfo, and then all you have to do is unwrap that assembly's function call it with whatever Method's Info you want to start the actual domain in, and your good it will enable the debugger and then call the method you want it to start in.</p>

Body:
I am working on a Visual Studio extension and one of it's functions creates a new app domain and load an assembly into that app domain. Then it runs some functions in the app domain. What I'd like to do, and am not sure if it's possible, is have my extension attach a debugger to the code running in the new app domain so when that code fails, I can actually see what's going on. Right now I'm flying blind and debugging the dynamical loaded assembly is a pain.

So I have a class that creates my app domain something like this:

domain = AppDomain.CreateDomain("Test_AppDomain",
    AppDomain.CurrentDomain.Evidence,
    AppDomain.CurrentDomain.SetupInformation);

And then creates an object like this:

myCollection = domain.CreateInstanceAndUnwrap(
            typeof(MyCollection).Assembly.FullName,
            typeof(MyCollection).FullName,
            false,
            BindingFlags.Default,
            null,
            new object[] { assemblyPath }, null, null);

MyCollection does something like this in it's constructor:

_assembly = Assembly.LoadFrom(assemblyPath);

So now that assembly has been loaded into Test_AppDomain since the MyCollection object was created in that domain. And it's that loaded assembly that I need to be able to attach the debugger to.

At some point myCollection creates an instance of an object and hooks up some events:

currentObject = Activator.CreateInstance(objectType) as IObjectBase;
proxy.RunRequested += (o, e) => { currentObject?.Run(); };

And basically where I have the handler for RunRequested and it runs currentObject?.Run(), I want to have a debugger attached, although it probably wouldn't be a problem (and may actually work better) if the debugger was attached earlier.

So is there a way to achieve this? Is it possible to programmatically attach a debugger when the user triggers the event that will lead to the Run function of the object created in the new AppDomain being called? How do I get the debugger attached to that (and not the extension itself)?

I tried something like this:

var processes = dte.Debugger.LocalProcesses.Cast<EnvDTE.Process>();
var currentProcess = System.Diagnostics.Process.GetCurrentProcess().Id;
var process = processes.FirstOrDefault(p => p.ProcessID == currentProcess);
process?.Attach();

But it seems the id from System.Diagnostics.Process.GetCurrentProcess().Id doesn't exist within LocalProcesses?


来源: stackexchange

问:
Android AsyncTask blocks back key dispatch Event
The Problem is:

My Activity starts an AsyncTask in onStart().
In the doInBackground Method I make a short webrequest, and depending on your network connetion, this may take a little, so I want this task cancelable...

BUT..

After hours of searching, testing and debugging I noticed now, when the user presses the back button during the doInBackground Method, the Keyevent ist always dispatched AFTER my doInBackground method is finished.

So I dont have to wonder why the asynctask never is cancelled when the users presses the backbutton,
the AsyncTask.cancel(true) is invoked too late..... (even if I am not sure if cancel(true) will help)

So is this normal behavoiur with asynctask and backbutton?

This cant be normal, because how should the user ever get back from the activity on slow connection?

wait for timeout?

I am Begging for Help, cancel an async webrequest SHOULD be possible :)

答:
This is the expected behavior. The documentation says :

Cancelling a task

A task can be cancelled at any time by
  invoking cancel(boolean). Invoking
  this method will cause subsequent
  calls to isCancelled() to return true.
  After invoking this method,
  onCancelled(Object), instead of
  onPostExecute(Object) will be invoked
  after doInBackground(Object[])
  returns. To ensure that a task is
  cancelled as quickly as possible, you
  should always check the return value
  of isCancelled() periodically from
  doInBackground(Object[]), if possible
  (inside a loop for instance.)

ContentLicense: CC BY-SA 3.0


问:
I got a small project on wireshark and I'm kinda stuck
Access the website and look at the packets you captured.  What TCP/IP protocol is used?  What are the two IP address that are interacting?
Did you capture any DNS packets?  What information did you get from those?
What other protocols were in packets from this interaction?  What information was on them?
The websites you should visit are:

https://www.cnn.com/
https://cway.cisco.com/support/

Can you help me out do this one? anyone?

答:
Run the wireshark application.

Open a browser and visit whatever website you want to.

Go back to wireshark and you will see a whole bunch of network data and a textbox on the top of the window where you can apply a filter.

Applying a filter will help you limit your results to those you are interested in. A filter can be for example a protocol or a source/destination ip.

In your case, typing http and hitting enter, will filter the results to those associated with the websites you visited (because http is the application layer protocol used in that case).
Find the lines containing GET / HTTP/1.1 as the info column and select them. You will see a list of all the protocols involded in those requests (in the middle section of the window). Inspect the protocol list and you will get all the information you need.

Respectively, applying a dns filter will give you a line with an info column like A xxxx.cnn.com and you can again inspect the middle section of wireshark's window to get the information you need.

ContentLicense: CC BY-SA 4.0


问:
Pandas multiple conditions groupby
How can i achieve to groupby multiple conditions. example:

column CL rows == a,b,c groupby column A & C .[TOTAL].min() and column CL rows == rows d,e,f groupby B [TOTAL].min()

```<code>CL  | A | B | C | TOTAL
a   | 1 | 6 | 5 | 125,000
b   | 2 | 5 | 5 | 140,000
c   | 3 | 4 | 5 | 148,000
d   | 4 | 3 | 6 | 125,000
e   | 5 | 2 | 6 | 136,000
f   | 6 | 1 | 6 | 156,000
</code>```

答:
Ok, do I see 2 options here:

(1) you do the grouping and aggregating separately, then merge it back:

pd.concat([df.loc[df["CL"].isin(["a", "b", "c"])].groupby(["A", "C"])["TOTAL"].min(),
df.loc[df["CL"].isin(["d", "e", "f"])].groupby("B")["TOTAL"].min()])
```

<p>Outputs:</p>

<pre class="lang-py prettyprint-override"><code>(1, 5)    125000
(2, 5)    140000
(3, 5)    148000
1         156000
2         136000
3         125000
Name: TOTAL, dtype: int64
</code>```

(2) alternatively - you need to make up a dummy grouping key - you can do it for instance by masking unwanted grouping keys by -1, so:

import numpy as np

#using the copy so original df won't be amended:
df2=df.copy()

#mask unwanted grouping keys by any object, other than None (None-s are automatically excluded from the group)
#choose key, so it won't get mixed up with any of other grouping keys

df2["B"]=np.where(df["CL"].isin(["a", "b", "c"]), -1, df["B"])
df2["A"]=np.where(df["CL"].isin(["a", "b", "c"]), df["A"], -1)
df2["C"]=np.where(df["CL"].isin(["a", "b", "c"]), df["C"], -1)

df2.groupby(["A", "B", "C"])["TOTAL"].min()
```

<p>Outputs:</p>

<pre class="lang-py prettyprint-override"><code>A   B   C
-1   1  -1    156000
     2  -1    136000
     3  -1    125000
 1  -1   5    125000
 2  -1   5    140000
 3  -1   5    148000
Name: TOTAL, dtype: int64
</code>```

Title: Pandas multiple conditions groupby

Body:
How can i achieve to groupby multiple conditions. example:

column CL rows == a,b,c groupby column A & C .[TOTAL].min() and column CL rows == rows d,e,f groupby B [TOTAL].min()

CL  | A | B | C | TOTAL
a   | 1 | 6 | 5 | 125,000
b   | 2 | 5 | 5 | 140,000
c   | 3 | 4 | 5 | 148,000
d   | 4 | 3 | 6 | 125,000
e   | 5 | 2 | 6 | 136,000
f   | 6 | 1 | 6 | 156,000

Body:
Ok, do I see 2 options here:

(1) you do the grouping and aggregating separately, then merge it back:

pd.concat([df.loc[df["CL"].isin(["a", "b", "c"])].groupby(["A", "C"])["TOTAL"].min(),
df.loc[df["CL"].isin(["d", "e", "f"])].groupby("B")["TOTAL"].min()])

Outputs:

(1, 5)    125000
(2, 5)    140000
(3, 5)    148000
1         156000
2         136000
3         125000
Name: TOTAL, dtype: int64

(2) alternatively - you need to make up a dummy grouping key - you can do it for instance by masking unwanted grouping keys by -1, so:

import numpy as np

#using the copy so original df won't be amended:
df2=df.copy()

#mask unwanted grouping keys by any object, other than None (None-s are automatically excluded from the group)
#choose key, so it won't get mixed up with any of other grouping keys

df2["B"]=np.where(df["CL"].isin(["a", "b", "c"]), -1, df["B"])
df2["A"]=np.where(df["CL"].isin(["a", "b", "c"]), df["A"], -1)
df2["C"]=np.where(df["CL"].isin(["a", "b", "c"]), df["C"], -1)

df2.groupby(["A", "B", "C"])["TOTAL"].min()

Outputs:

A   B   C
-1   1  -1    156000
     2  -1    136000
     3  -1    125000
 1  -1   5    125000
 2  -1   5    140000
 3  -1   5    148000
Name: TOTAL, dtype: int64


问:
OpenCV 4.x+ requires enabled C++11 support compilation darknet fatal error
I just compiled and installed the last version of OpenCV 3.4.0 and I would like to compile darknet (for yolo object detection), but at compilation, I have

```<code>gcc -Iinclude/ -Isrc/ -DOPENCV `pkg-config --cflags opencv`  -DGPU -I/usr/local/cuda-9.1/include/ -Wall -Wno-unused-result -Wno-unknown-pragmas -Wfatal-errors -fPIC -Ofast -DOPENCV  -DGPU  -c ./src/gemm.c -o obj/gemm.o
In file included from /usr/local/include/opencv2/core/types_c.h:59:0,
                 from /usr/local/include/opencv2/core/core_c.h:48,
                 from /usr/local/include/opencv2/highgui/highgui_c.h:45,
                 from include/darknet.h:25,
                 from ./src/utils.h:5,
                 from ./src/gemm.c:2:
/usr/local/include/opencv2/core/cvdef.h:421:4: error: #error "OpenCV 4.x+ requires enabled C++11 support"
 #  error "OpenCV 4.x+ requires enabled C++11 support"
    ^
compilation terminated due to -Wfatal-errors.
Makefile:86: recipe for target 'obj/gemm.o' failed
make: *** [obj/gemm.o] Error 1
</code>```

How it is possible, because in Makefile (below), I compile C

```<code>GPU=1
CUDNN=0
OPENCV=1
OPENMP=0
DEBUG=0

ARCH= -gencode arch=compute_30,code=sm_30 \
      -gencode arch=compute_35,code=sm_35 \
      -gencode arch=compute_50,code=[sm_50,compute_50] \
      -gencode arch=compute_52,code=[sm_52,compute_52]
#      -gencode arch=compute_20,code=[sm_20,sm_21] \ This one is deprecated?

# This is what I use, uncomment if you know your arch and want to specify
# ARCH= -gencode arch=compute_52,code=compute_52

VPATH=./src/:./examples
SLIB=libdarknet.so
ALIB=libdarknet.a
EXEC=darknet
OBJDIR=./obj/

CC=gcc
NVCC=nvcc
NVCCFLAGS += -D_FORCE_INLINES -ccbin=$(CXX) -Xcompiler -fPIC $(COMMON_FLAGS)
AR=ar
ARFLAGS=rcs
OPTS=-Ofast
LDFLAGS= -lm -pthread
COMMON= -Iinclude/ -Isrc/
CFLAGS=-Wall -Wno-unused-result -Wno-unknown-pragmas -Wfatal-errors -fPIC

ifeq ($(OPENMP), 1)
CFLAGS+= -fopenmp
endif

ifeq ($(DEBUG), 1)
OPTS=-O0 -g
endif

CFLAGS+=$(OPTS)

ifeq ($(OPENCV), 1)
COMMON+= -DOPENCV
CFLAGS+= -DOPENCV
LDFLAGS+= `pkg-config --libs opencv`
COMMON+= `pkg-config --cflags opencv`
endif

ifeq ($(GPU), 1)
COMMON+= -DGPU -I/usr/local/cuda-9.1/include/
CFLAGS+= -DGPU
LDFLAGS+= -L/usr/local/cuda-9.1/lib64 -lcudart -lcublas -lcurand
endif

ifeq ($(CUDNN), 1)
COMMON+= -DCUDNN
CFLAGS+= -DCUDNN
LDFLAGS+= -lcudnn
endif

OBJ=gemm.o utils.o cuda.o deconvolutional_layer.o convolutional_layer.o list.o image.o activations.o im2col.o col2im.o blas.o crop_layer.o dropout_layer.o maxpool_layer.o softmax_layer.o data.o matrix.o network.o connected_layer.o cost_layer.o parser.o option_list.o detection_layer.o route_layer.o upsample_layer.o box.o normalization_layer.o avgpool_layer.o layer.o local_layer.o shortcut_layer.o logistic_layer.o activation_layer.o rnn_layer.o gru_layer.o crnn_layer.o demo.o batchnorm_layer.o region_layer.o reorg_layer.o tree.o  lstm_layer.o l2norm_layer.o yolo_layer.o
EXECOBJA=captcha.o lsd.o super.o art.o tag.o cifar.o go.o rnn.o segmenter.o regressor.o classifier.o coco.o yolo.o detector.o nightmare.o darknet.o
ifeq ($(GPU), 1)
LDFLAGS+= -lstdc++
OBJ+=convolutional_kernels.o deconvolutional_kernels.o activation_kernels.o im2col_kernels.o col2im_kernels.o blas_kernels.o crop_layer_kernels.o dropout_layer_kernels.o maxpool_layer_kernels.o avgpool_layer_kernels.o
endif

EXECOBJ = $(addprefix $(OBJDIR), $(EXECOBJA))
OBJS = $(addprefix $(OBJDIR), $(OBJ))
DEPS = $(wildcard src/*.h) Makefile include/darknet.h

#all: obj backup results $(SLIB) $(ALIB) $(EXEC)
all: obj  results $(SLIB) $(ALIB) $(EXEC)

$(EXEC): $(EXECOBJ) $(ALIB)
    $(CC) $(COMMON) $(CFLAGS) $^ -o $@ $(LDFLAGS) $(ALIB)

$(ALIB): $(OBJS)
    $(AR) $(ARFLAGS) $@ $^

$(SLIB): $(OBJS)
    $(CC) $(CFLAGS) -shared $^ -o $@ $(LDFLAGS)

$(OBJDIR)%.o: %.c $(DEPS)
    $(CC) $(COMMON) $(CFLAGS) -c $< -o $@

$(OBJDIR)%.o: %.cu $(DEPS)
    $(NVCC) $(ARCH) $(COMMON) --compiler-options "$(CFLAGS)" -c $< -o $@

obj:
    mkdir -p obj
backup:
    mkdir -p backup
results:
    mkdir -p results

.PHONY: clean

clean:
    rm -rf $(OBJS) $(SLIB) $(ALIB) $(EXEC) $(EXECOBJ) $(OBJDIR)
</code>```

And what's the solution for this error ? How I can enable C++11 support ?

Thank for your help !

答:
add this line to your CMake file:</p>

```<code>set (CMAKE_CXX_STANDARD 11)
</code>```

Body:
I just compiled and installed the last version of OpenCV 3.4.0 and I would like to compile darknet (for yolo object detection), but at compilation, I have

gcc -Iinclude/ -Isrc/ -DOPENCV `pkg-config --cflags opencv`  -DGPU -I/usr/local/cuda-9.1/include/ -Wall -Wno-unused-result -Wno-unknown-pragmas -Wfatal-errors -fPIC -Ofast -DOPENCV  -DGPU  -c ./src/gemm.c -o obj/gemm.o
In file included from /usr/local/include/opencv2/core/types_c.h:59:0,
                 from /usr/local/include/opencv2/core/core_c.h:48,
                 from /usr/local/include/opencv2/highgui/highgui_c.h:45,
                 from include/darknet.h:25,
                 from ./src/utils.h:5,
                 from ./src/gemm.c:2:
/usr/local/include/opencv2/core/cvdef.h:421:4: error: #error "OpenCV 4.x+ requires enabled C++11 support"
 #  error "OpenCV 4.x+ requires enabled C++11 support"
    ^
compilation terminated due to -Wfatal-errors.
Makefile:86: recipe for target 'obj/gemm.o' failed
make: *** [obj/gemm.o] Error 1

How it is possible, because in Makefile (below), I compile C

GPU=1
CUDNN=0
OPENCV=1
OPENMP=0
DEBUG=0

ARCH= -gencode arch=compute_30,code=sm_30 \
      -gencode arch=compute_35,code=sm_35 \
      -gencode arch=compute_50,code=[sm_50,compute_50] \
      -gencode arch=compute_52,code=[sm_52,compute_52]
#      -gencode arch=compute_20,code=[sm_20,sm_21] \ This one is deprecated?

# This is what I use, uncomment if you know your arch and want to specify
# ARCH= -gencode arch=compute_52,code=compute_52

VPATH=./src/:./examples
SLIB=libdarknet.so
ALIB=libdarknet.a
EXEC=darknet
OBJDIR=./obj/

CC=gcc
NVCC=nvcc
NVCCFLAGS += -D_FORCE_INLINES -ccbin=$(CXX) -Xcompiler -fPIC $(COMMON_FLAGS)
AR=ar
ARFLAGS=rcs
OPTS=-Ofast
LDFLAGS= -lm -pthread
COMMON= -Iinclude/ -Isrc/
CFLAGS=-Wall -Wno-unused-result -Wno-unknown-pragmas -Wfatal-errors -fPIC

ifeq ($(OPENMP), 1)
CFLAGS+= -fopenmp
endif

ifeq ($(DEBUG), 1)
OPTS=-O0 -g
endif

CFLAGS+=$(OPTS)

ifeq ($(OPENCV), 1)
COMMON+= -DOPENCV
CFLAGS+= -DOPENCV
LDFLAGS+= `pkg-config --libs opencv`
COMMON+= `pkg-config --cflags opencv`
endif

ifeq ($(GPU), 1)
COMMON+= -DGPU -I/usr/local/cuda-9.1/include/
CFLAGS+= -DGPU
LDFLAGS+= -L/usr/local/cuda-9.1/lib64 -lcudart -lcublas -lcurand
endif

ifeq ($(CUDNN), 1)
COMMON+= -DCUDNN
CFLAGS+= -DCUDNN
LDFLAGS+= -lcudnn
endif

OBJ=gemm.o utils.o cuda.o deconvolutional_layer.o convolutional_layer.o list.o image.o activations.o im2col.o col2im.o blas.o crop_layer.o dropout_layer.o maxpool_layer.o softmax_layer.o data.o matrix.o network.o connected_layer.o cost_layer.o parser.o option_list.o detection_layer.o route_layer.o upsample_layer.o box.o normalization_layer.o avgpool_layer.o layer.o local_layer.o shortcut_layer.o logistic_layer.o activation_layer.o rnn_layer.o gru_layer.o crnn_layer.o demo.o batchnorm_layer.o region_layer.o reorg_layer.o tree.o  lstm_layer.o l2norm_layer.o yolo_layer.o
EXECOBJA=captcha.o lsd.o super.o art.o tag.o cifar.o go.o rnn.o segmenter.o regressor.o classifier.o coco.o yolo.o detector.o nightmare.o darknet.o
ifeq ($(GPU), 1)
LDFLAGS+= -lstdc++
OBJ+=convolutional_kernels.o deconvolutional_kernels.o activation_kernels.o im2col_kernels.o col2im_kernels.o blas_kernels.o crop_layer_kernels.o dropout_layer_kernels.o maxpool_layer_kernels.o avgpool_layer_kernels.o
endif

EXECOBJ = $(addprefix $(OBJDIR), $(EXECOBJA))
OBJS = $(addprefix $(OBJDIR), $(OBJ))
DEPS = $(wildcard src/*.h) Makefile include/darknet.h

#all: obj backup results $(SLIB) $(ALIB) $(EXEC)
all: obj  results $(SLIB) $(ALIB) $(EXEC)

$(EXEC): $(EXECOBJ) $(ALIB)
    $(CC) $(COMMON) $(CFLAGS) $^ -o $@ $(LDFLAGS) $(ALIB)

$(ALIB): $(OBJS)
    $(AR) $(ARFLAGS) $@ $^

$(SLIB): $(OBJS)
    $(CC) $(CFLAGS) -shared $^ -o $@ $(LDFLAGS)

$(OBJDIR)%.o: %.c $(DEPS)
    $(CC) $(COMMON) $(CFLAGS) -c $< -o $@

$(OBJDIR)%.o: %.cu $(DEPS)
    $(NVCC) $(ARCH) $(COMMON) --compiler-options "$(CFLAGS)" -c $< -o $@

obj:
    mkdir -p obj
backup:
    mkdir -p backup
results:
    mkdir -p results

.PHONY: clean

clean:
    rm -rf $(OBJS) $(SLIB) $(ALIB) $(EXEC) $(EXECOBJ) $(OBJDIR)

And what's the solution for this error ? How I can enable C++11 support ?

Thank for your help !

Body:
add this line to your CMake file:

set (CMAKE_CXX_STANDARD 11)


问:
When do I use if/endif versus If{}?
Well the question is self explanatory.

In PHP when do I use the if/endif notation instead of the standard if(something){} notation?

Example:

```<code><?php if($a == 5): ?>
A is equal to 5
<?php endif; ?>
</code>```

Versus:

```<code><?php if($a == 5){ ?>
A is equal to 5
<?php } ?>
</code>```

答: Both methods are acceptable. Some people maintain that the alternative syntax (endif) is more legible in templates. IMHO, with a modern syntax coloring/highlighting error, that no longer holds true. Just pick a style and stick with it.</p>

Title: When do I use if/endif versus If{}?

Body:
Well the question is self explanatory.

In PHP when do I use the if/endif notation instead of the standard if(something){} notation?

Example:

<?php if($a == 5): ?>
A is equal to 5
<?php endif; ?>

Versus:

<?php if($a == 5){ ?>
A is equal to 5
<?php } ?>


问:
Importing one dimensional dataset for Complete Spatial Randomness win spatstat
I have a set of one-dimensional data points (locations on a segment), and I would like to test for Complete Spatial randomness. I was planning to run Gest (nearest neighbor), Fest (empty space)  and Kest (pairwise distances) functions on it.

I am not sure how I should import my data set though. I can use ppp by setting a second dimension to 0, e.g.:

```<code>myDistTEST<- data.frame(
  col1= sample(x = 1:100, size = 50, replace = FALSE),
  col2= paste('Event', 1:50, sep = ''), stringsAsFactors = FALSE)
myDistTEST<- myDistTEST[order(myDistTEST$col1),]
myPPPTest<- ppp(x = myDistTEST[,1], y = replicate(n = 50, expr = 0),
                c(1,120), c(0,0))
</code>```

But I am not sure it is the proper way to format my data. I have also tried to use lpp, but I am not sure how to set the linnet object. What would be the correct way to import my data?
Thank you for your kind attention.

答:
It will be wrong to simply let y=0 for all your points and then proceed as if you had a point pattern in two dimensions. Your suggestion of using lpp is good. Regarding how to define the linnet and lpp try to look at my answer here.

I have considered making a small package to handle one dimensional patterns more easily in spatstat, but so far I have only started the package with a single function to make the definition of the appropriate lpp easier. If you feel adventurous you can install it from the GitHub repo via the remotes package:

```<code>remotes::install_github("rubak/spatstat.1d")
</code>```

The single function you can use is called lpp1. It basically just wraps up the few steps described in the linked answer.

Body:
I have a set of one-dimensional data points (locations on a segment), and I would like to test for Complete Spatial randomness. I was planning to run Gest (nearest neighbor), Fest (empty space)  and Kest (pairwise distances) functions on it.

I am not sure how I should import my data set though. I can use ppp by setting a second dimension to 0, e.g.:

myDistTEST<- data.frame(
  col1= sample(x = 1:100, size = 50, replace = FALSE),
  col2= paste('Event', 1:50, sep = ''), stringsAsFactors = FALSE)
myDistTEST<- myDistTEST[order(myDistTEST$col1),]
myPPPTest<- ppp(x = myDistTEST[,1], y = replicate(n = 50, expr = 0),
                c(1,120), c(0,0))

But I am not sure it is the proper way to format my data. I have also tried to use lpp, but I am not sure how to set the linnet object. What would be the correct way to import my data?
Thank you for your kind attention.

Body:
It will be wrong to simply let y=0 for all your points and then proceed as if you had a point pattern in two dimensions. Your suggestion of using lpp is good. Regarding how to define the linnet and lpp try to look at my answer here.

I have considered making a small package to handle one dimensional patterns more easily in spatstat, but so far I have only started the package with a single function to make the definition of the appropriate lpp easier. If you feel adventurous you can install it from the GitHub repo via the remotes package:

remotes::install_github("rubak/spatstat.1d")

The single function you can use is called lpp1. It basically just wraps up the few steps described in the linked answer.


问:
React - How to detect when all sub-components of a parent component are visible to the user?
TL;DR

How can a parent component know when the rendering of every child
  component under it has finished and the DOM visible to the user with its most up to date version?

Let's say I have a component A that has a child Grid component consisting of 3x3 grandchild components. Each of those grandchild components fetches data from a restful API endpoint and renders itself when the data becomes available.

I would like to cover the entire area of Component A with a loader placeholder, to be unveiled only when the last of the components in the grid has fetched the data successfully, and rendered it, such that it's already on the DOM and can be viewed.

The user experience should be a super smooth transition from "loader" to a fully populated grid without flickering.

My problem is knowing exactly when to unveil the components under the loader.

Is there any mechanism I can rely on to do this with absolute accuracy? I don't to hard code a time limit for the loader. As I understand relying on ComponentDidMount for every child is also unreliable as it doesn't actually guarantee the component is fully visible to the user at the time of the call.

To distill the question even further:

I have a component that renders some kind of data. After it's
  initialized it doesn't have it, so in its componentDidMount it hits
  an API endpoint for it. Once it receives the data, it's changing its
  state to reflect it. This understandably causes a re-render of the
  final state of that component. My question is this: How do I know when
  that re-render has taken place and is reflected in the User
  facing DOM. That point in time != the point in time when the
  component's state has changed to contain data.

答:
You could potentially solve this using React Suspense.

The caveat is that it's not a good idea to Suspend past the component tree that does the render (that is: If your component kicks off a render process, it's not a good idea to have that component suspend, in my experience), so it's probably a better idea to kick the requests off in the component that renders the cells. Something like this:

```<code>export default function App() {
  const cells = React.useMemo(
    () =>
      ingredients.map((_, index) => {
        // This starts the fetch but *does not wait for it to finish*.
        return <Cell resource={fetchIngredient(index)} />;
      }),
    []
  );

  return (
    <div className="App">
      <Grid>{cells}</Grid>
    </div>
  );
}
</code>```

Now, quite how Suspense pairs with Redux I'm not sure. The whole idea behind this (experimental!) version of Suspense is that you start the fetch immediately during the render cycle of a parent component and pass an object that represents a fetch to the children. This prevents you having to have some kind of Barrier object (which you would need in other approaches).

I will say that I don't think waiting until everything has fetched to display anything is the right approach because then the UI will be as slow as the slowest connection or may not work at all!

Here's the rest of the missing code:

```<code>const ingredients = [
  "Potato",
  "Cabbage",
  "Beef",
  "Bok Choi",
  "Prawns",
  "Red Onion",
  "Apple",
  "Raisin",
  "Spinach"
];

function randomTimeout(ms) {
  return Math.ceil(Math.random(1) * ms);
}

function fetchIngredient(id) {
  const task = new Promise(resolve => {
    setTimeout(() => resolve(ingredients[id]), randomTimeout(5000));
  });

  return new Resource(task);
}

// This is a stripped down version of the Resource class displayed in the React Suspense docs. It doesn't handle errors (and probably should).
// Calling read() will throw a Promise and, after the first event loop tick at the earliest, will return the value. This is a synchronous-ish API,
// Making it easy to use in React's render loop (which will not let you return anything other than a React element).
class Resource {
  constructor(promise) {
    this.task = promise.then(value => {
      this.value = value;
      this.status = "success";
    });
  }

  read() {
    switch (this.status) {
      case "success":
        return this.value;

      default:
        throw this.task;
    }
  }
}

function Cell({ resource }) {
  const data = resource.read();
  return <td>{data}</td>;
}

function Grid({ children }) {
  return (
    // This suspense boundary will cause a Loading sign to be displayed if any of the children suspend (throw a Promise).
    // Because we only have the one suspense boundary covering all children (and thus Cells), the fallback will be rendered
    // as long as at least one request is in progress.
    // Thanks to this approach, the Grid component need not be aware of how many Cells there are.
    <React.Suspense fallback={<h1>Loading..</h1>}>
      <table>{children}</table>
    </React.Suspense>
  );
}
</code>```

And a sandbox:
https://codesandbox.io/s/falling-dust-b8e7s

Body:
You could potentially solve this using React Suspense.

The caveat is that it's not a good idea to Suspend past the component tree that does the render (that is: If your component kicks off a render process, it's not a good idea to have that component suspend, in my experience), so it's probably a better idea to kick the requests off in the component that renders the cells. Something like this:

export default function App() {
  const cells = React.useMemo(
    () =>
      ingredients.map((_, index) => {
        // This starts the fetch but *does not wait for it to finish*.
        return <Cell resource={fetchIngredient(index)} />;
      }),
    []
  );

  return (
    <div className="App">
      <Grid>{cells}</Grid>
    </div>
  );
}

Now, quite how Suspense pairs with Redux I'm not sure. The whole idea behind this (experimental!) version of Suspense is that you start the fetch immediately during the render cycle of a parent component and pass an object that represents a fetch to the children. This prevents you having to have some kind of Barrier object (which you would need in other approaches).

I will say that I don't think waiting until everything has fetched to display anything is the right approach because then the UI will be as slow as the slowest connection or may not work at all!

Here's the rest of the missing code:

const ingredients = [
  "Potato",
  "Cabbage",
  "Beef",
  "Bok Choi",
  "Prawns",
  "Red Onion",
  "Apple",
  "Raisin",
  "Spinach"
];

function randomTimeout(ms) {
  return Math.ceil(Math.random(1) * ms);
}

function fetchIngredient(id) {
  const task = new Promise(resolve => {
    setTimeout(() => resolve(ingredients[id]), randomTimeout(5000));
  });

  return new Resource(task);
}

// This is a stripped down version of the Resource class displayed in the React Suspense docs. It doesn't handle errors (and probably should).
// Calling read() will throw a Promise and, after the first event loop tick at the earliest, will return the value. This is a synchronous-ish API,
// Making it easy to use in React's render loop (which will not let you return anything other than a React element).
class Resource {
  constructor(promise) {
    this.task = promise.then(value => {
      this.value = value;
      this.status = "success";
    });
  }

  read() {
    switch (this.status) {
      case "success":
        return this.value;

      default:
        throw this.task;
    }
  }
}

function Cell({ resource }) {
  const data = resource.read();
  return <td>{data}</td>;
}

function Grid({ children }) {
  return (
    // This suspense boundary will cause a Loading sign to be displayed if any of the children suspend (throw a Promise).
    // Because we only have the one suspense boundary covering all children (and thus Cells), the fallback will be rendered
    // as long as at least one request is in progress.
    // Thanks to this approach, the Grid component need not be aware of how many Cells there are.
    <React.Suspense fallback={<h1>Loading..</h1>}>
      <table>{children}</table>
    </React.Suspense>
  );
}

And a sandbox:
https://codesandbox.io/s/falling-dust-b8e7s


问:
how to display and group values
I have data that is state+cities in a column. how can I group or filter them as their corresponding states. partial data in picture. </p>

答:
if all states has only 2 character then you can just trim the first 2 indexes of the string</p>

```<code>import pandas as pd

data = {'A':['AZ:Foo','AZ:Bar','AB:Foo','AB:Bar']}

df = pd.DataFrame(data)

df['new_column'] = df['A'].apply(lambda x: x[:2])

df.groupby('new_column')['A'].count()
</code>```

Title: how to display and group values

Body:
if all states has only 2 character then you can just trim the first 2 indexes of the string

import pandas as pd

data = {'A':['AZ:Foo','AZ:Bar','AB:Foo','AB:Bar']}

df = pd.DataFrame(data)

df['new_column'] = df['A'].apply(lambda x: x[:2])

df.groupby('new_column')['A'].count()


问:
SQL Trigger After Insert is not inserting values to new table
I have a wordpress website and a plugin that I can import products with. When a product is imported, it has meta tags attached to it, like below (47226 is the product and 47227 is a variation of 47226):

When a new item is imported via the plugin, it automatically inserts all this metadata into a table called wp_postmeta.
 Since each product always has '_price' , and variations have both '_price' and '_regular_price', I am trying to extract only the '_price' and '_regular_price' rows, with the respective values for post_id, meta_key and meta_value, and save these values to a new table called original_price with a trigger.

 The plugin also inserts price updates into wp_postmeta for existing products in the original_price table, so I want to exclude them and only insert items that don't already exist in original_prices table.

So far my trigger is:

```<code>DELIMITER //
CREATE TRIGGER `new_import_INSERT` AFTER INSERT ON `wp_postmeta`
 FOR EACH ROW BEGIN
INSERT INTO original_prices (date_added,post_id,meta_key,meta_starting_price)
SELECT now(),post_id,meta_key,meta_value FROM wp_postmeta
WHERE post_id=NEW.post_id AND NEW.meta_key IN ('_price','_regular_price') AND NOT EXISTS (SELECT * FROM original_prices WHERE post_id=new.post_id);
   END//
DELIMITER ;
</code>```

This works, but for each _price and _regular_price, it duplicates the results 18 times. I tried changing the FROM wp_postmeta to FROM inserted , but that makes it so no entries are added to original_prices when a new product is imported via the plguin.  I also tried changing the SELECT now(),post_id,meta_key,meta_value to SELECT now(),NEW.post_id,NEW.meta_key,NEW.meta_value but this didn't resolve the duplicate issue either.

 Where am I going wrong for it to duplicate the results so many times?

答:
If you only want that a riow is inserted when 'meta_key is _price' or '_regular_price'

So you do something like this

```<code>DELIMITER //
CREATE TRIGGER `new_import_INSERT` AFTER INSERT ON `wp_postmeta`
 FOR EACH ROW BEGIN
     IF (NEW.meta_key  = '_price' OR NEW.meta_key = '_regular_price') THEN
        INSERT INTO original_prices (date_added,post_id,meta_key,meta_starting_price) VALUES
           (now(),NEW.post_id,NEW.meta_key,NEW.meta_value );
    END IF;
   END//
DELIMITER ;
</code>```

Body:
I have a wordpress website and a plugin that I can import products with. When a product is imported, it has meta tags attached to it, like below (47226 is the product and 47227 is a variation of 47226):

When a new item is imported via the plugin, it automatically inserts all this metadata into a table called wp_postmeta.
 Since each product always has '_price' , and variations have both '_price' and '_regular_price', I am trying to extract only the '_price' and '_regular_price' rows, with the respective values for post_id, meta_key and meta_value, and save these values to a new table called original_price with a trigger.

 The plugin also inserts price updates into wp_postmeta for existing products in the original_price table, so I want to exclude them and only insert items that don't already exist in original_prices table.

So far my trigger is:

DELIMITER //
CREATE TRIGGER `new_import_INSERT` AFTER INSERT ON `wp_postmeta`
 FOR EACH ROW BEGIN
INSERT INTO original_prices (date_added,post_id,meta_key,meta_starting_price)
SELECT now(),post_id,meta_key,meta_value FROM wp_postmeta
WHERE post_id=NEW.post_id AND NEW.meta_key IN ('_price','_regular_price') AND NOT EXISTS (SELECT * FROM original_prices WHERE post_id=new.post_id);
   END//
DELIMITER ;

This works, but for each _price and _regular_price, it duplicates the results 18 times. I tried changing the FROM wp_postmeta to FROM inserted , but that makes it so no entries are added to original_prices when a new product is imported via the plguin.  I also tried changing the SELECT now(),post_id,meta_key,meta_value to SELECT now(),NEW.post_id,NEW.meta_key,NEW.meta_value but this didn't resolve the duplicate issue either.

 Where am I going wrong for it to duplicate the results so many times?

Body:
If you only want that a riow is inserted when 'meta_key is _price' or '_regular_price'

So you do something like this

DELIMITER //
CREATE TRIGGER `new_import_INSERT` AFTER INSERT ON `wp_postmeta`
 FOR EACH ROW BEGIN
     IF (NEW.meta_key  = '_price' OR NEW.meta_key = '_regular_price') THEN
        INSERT INTO original_prices (date_added,post_id,meta_key,meta_starting_price) VALUES
           (now(),NEW.post_id,NEW.meta_key,NEW.meta_value );
    END IF;
   END//
DELIMITER ;


问:
Do we need to specifically call previous state to retain previous values?
I currently have a state like so:

```<code>  const [startDate, setStartDate] = useState({
    bDay: new Date(),
    anniversary: new Date(),
  });
</code>```

Let us suppose I want to retain bDay and change anniversary date would I need to copy the previous state to change only part of it?

Like so:

```<code>    setDropdowns(prevState => ({
    ...prevState,
    anniversary: new Date(datefrom4yearsago)
  }))
</code>```

or can I just set the state for only the one I want and the state will be kept the same for all other object entries?

```<code>setDropdowns({anniversary: new Date(datefrom4yearsago)})
</code>```

答:
As stated in the React docs:

Unlike the setState method found in class components, useState does not automatically merge update objects. You can replicate this behavior by combining the function updater form with object spread syntax:

```<code>setState(prevState => {
   // Object.assign would also work
   return {...prevState, ...updatedValues};
});
</code>```

Body:
I currently have a state like so:

  const [startDate, setStartDate] = useState({
    bDay: new Date(),
    anniversary: new Date(),
  });

Let us suppose I want to retain bDay and change anniversary date would I need to copy the previous state to change only part of it?

Like so:

    setDropdowns(prevState => ({
    ...prevState,
    anniversary: new Date(datefrom4yearsago)
  }))

or can I just set the state for only the one I want and the state will be kept the same for all other object entries?

setDropdowns({anniversary: new Date(datefrom4yearsago)})

Body:
As stated in the React docs:

Unlike the setState method found in class components, useState does not automatically merge update objects. You can replicate this behavior by combining the function updater form with object spread syntax:

setState(prevState => {
   // Object.assign would also work
   return {...prevState, ...updatedValues};
});


问:
Matching Values from Separate Sheet - Need Tweak to Formula
We just need a little help refining a formula used to match values from a separate sheet (SHEET2) with those in our MAIN sheet. We have something that is close to working as follows:

```<code>=IFERROR(VLOOKUP(D2,SHEET2!$A$1:$I$380,1,0),"")
</code>```

This adds a numerical value found in column 1 of SHEET2 to a column in our MAIN sheet if the value is found in the 'D' column of our MAIN sheet. This works properly if there is only a single number in the D column (e.g, 2222). But some of the rows in our MAIN sheet have multiple numbers listed (e.g, '2222, 2223, 2224, 2227').

How would we modify the formula to add the value if it matches ANY of the numbers listed in column D (which are always a comma-delimited list when they appear)?

If there are multiple matches for a single row (e.g., if it matched both 2222 and 2224), we would want both values to be added.

SAMPLE DATA
(Col. E on MAIN sheet is one we're filling based on Col. A on SHEET2)

MAIN SHEET:

```
    | - | A       | B               | C        | D                | E          |
    | 1 | Name    | Email           | Phone    | Customer ID      | Promotion  |
    | 2 | Joe S.  | joes@email.com  | 555-1212 | 2200             | 2200       |
    | 3 | Sue M.  | suem@email.com  | 555-1212 | 2232             |            |
    | 4 | Fred J. | fredj@email.com | 555-1212 | 2222, 2223, 2224 | 2222, 2224 |
    | 5 | Mary E. | marye@email.com | 555-1212 | 2224             | 2224       |
```

SHEET2 (only unique single numbers per row in Col. A):

```
| A        | B | C | D | E | F | G | H | I |
| Promo ID | Other unimportant data...
| 2200     |
| 2222     |
| 2224     |
```

Body:
We just need a little help refining a formula used to match values from a separate sheet (SHEET2) with those in our MAIN sheet. We have something that is close to working as follows:

=IFERROR(VLOOKUP(D2,SHEET2!$A$1:$I$380,1,0),"")

This adds a numerical value found in column 1 of SHEET2 to a column in our MAIN sheet if the value is found in the 'D' column of our MAIN sheet. This works properly if there is only a single number in the D column (e.g, 2222). But some of the rows in our MAIN sheet have multiple numbers listed (e.g, '2222, 2223, 2224, 2227').

How would we modify the formula to add the value if it matches ANY of the numbers listed in column D (which are always a comma-delimited list when they appear)?

If there are multiple matches for a single row (e.g., if it matched both 2222 and 2224), we would want both values to be added.

SAMPLE DATA
(Col. E on MAIN sheet is one we're filling based on Col. A on SHEET2)

MAIN SHEET:

    | - | A       | B               | C        | D                | E          |
    | 1 | Name    | Email           | Phone    | Customer ID      | Promotion  |
    | 2 | Joe S.  | joes@email.com  | 555-1212 | 2200             | 2200       |
    | 3 | Sue M.  | suem@email.com  | 555-1212 | 2232             |            |
    | 4 | Fred J. | fredj@email.com | 555-1212 | 2222, 2223, 2224 | 2222, 2224 |
    | 5 | Mary E. | marye@email.com | 555-1212 | 2224             | 2224       |

SHEET2 (only unique single numbers per row in Col. A):

| A        | B | C | D | E | F | G | H | I |
| Promo ID | Other unimportant data...
| 2200     |
| 2222     |
| 2224     |

Body:
Use SUMPRODUCT(SUMIFS())

=SUMPRODUCT(SUMIFS(SHEET2!$A:$A,SHEET2!$A:$A,TRIM(FILTERXML("<A><B>"&SUBSTITUTE(D2,",","</B><B>")&"</B></A>","//B"))))


问:
How can I get the click event inside an innerHTML?
I've this layout that was created dynamically:

for (let i = 1; i < 10; i++) {
  document.querySelector('.card-body').innerHTML += `

Name

            state

            city

            zip

     `
  document.getElementById("title" + i).addEventListener('click', function() {
    console.log(i)
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<div class="card-body">
  <!-- person -->
</div></code>```

And I want to get the event click on each h4 class="name" and show a log with the number i related.

However, console.log shows only the last i related (i=9 in this case), and doesn't work with the other i numbers. Why does this happen? What do I have to do?

答:
innerHTML redraws the full html, as a result all the previously attached events are lost. Use insertAdjacentHTML()

for(let i=1;i<10;i++){
    document.querySelector('.card-body').insertAdjacentHTML('beforeend',`

Name

            state

            city

            zip

     `);
   document.getElementById("title"+i).addEventListener('click', function () {
    console.log(i)
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<div class="card-body">
<!-- person -->
</div></code>```

Body:
I've this layout that was created dynamically:

for (let i = 1; i < 10; i++) {
  document.querySelector('.card-body').innerHTML += `

<a href="#" id="title` + i + `">Name

            state

            city

            zip

     `
  document.getElementById("title" + i).addEventListener('click', function() {
    console.log(i)
  });
}

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

And I want to get the event click on each h4 class="name" and show a log with the number i related.

However, console.log shows only the last i related (i=9 in this case), and doesn't work with the other i numbers. Why does this happen? What do I have to do?

Body:
innerHTML redraws the full html, as a result all the previously attached events are lost. Use insertAdjacentHTML()

for(let i=1;i<10;i++){
    document.querySelector('.card-body').insertAdjacentHTML('beforeend',`<div class="row" id="img_div">
        <div class="col-12 col-sm-12 col-md-2 text-center">
          <img src="http://placehold.it/120x80" alt="prewiew" width="120" height="80">
        </div>
        <div id="text_div" class="col-12 text-sm-center col-sm-12 text-md-left col-md-6">
        <h4 class="name"><a href="#" id="title`+i+`">Name</a></h4>
          <h4>
            <small>state</small>
          </h4>
          <h4>
            <small>city</small>
          </h4>
          <h4>
            <small>zip</small>
          </h4>
        </div>
        <div class="col-12 col-sm-12 text-sm-center col-md-4 text-md-right row">
        </div>
      </div>
     `);
   document.getElementById("title"+i).addEventListener('click', function () {
    console.log(i)
  });
}

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<div class="card-body">
<!-- person -->
</div>


问:
Can't perform I/O in foldr?
I have a Data.Map structure that maps Strings to Stringss. For whatever reason, I want to print the contents of the map in the format key: value using foldrWithKey, like so:

```<code>M.foldrWithKey (\k v b -> putStrLn (k++": "++v++"\n")) (return ()) data
</code>```

However, only the first element of the map appears in the output (even though the map has more than one element). But when I try to construct a list using foldrWithKey and then print it, all of the elements show up:

```<code>print (M.foldrWithKey (\k v b -> k:b) [] data)
</code>```

So, why don't the other elemnts show up when trying to perform I/O? Is it the way foldr works or is there some subtle lazy-io-related quirk that I'm missing?

答: when you fold with (\k v b -> putStrLn (k++": "++v++"\n")) you don't use the b anywhere, so all you got left is the last IO () that is left in the fold. Therefore it prints the first value. You can prevent this by folding with (\k v b -> putStrLn (k++": "++v++"\n") >> b).</p>

Title: Can't perform I/O in foldr?

Body:
I have a Data.Map structure that maps Strings to Stringss. For whatever reason, I want to print the contents of the map in the format key: value using foldrWithKey, like so:

M.foldrWithKey (\k v b -> putStrLn (k++": "++v++"\n")) (return ()) data

However, only the first element of the map appears in the output (even though the map has more than one element). But when I try to construct a list using foldrWithKey and then print it, all of the elements show up:

print (M.foldrWithKey (\k v b -> k:b) [] data)

So, why don't the other elemnts show up when trying to perform I/O? Is it the way foldr works or is there some subtle lazy-io-related quirk that I'm missing?


问:
How can tune MySQL for Wordpress sites?
I'm facing a problem that my MySQL database is slow, so I decided to check with mysqltuner.pl, I don't want to make any changes before I'm sure what I'm doing.

I'm running MySQL 5.7 on Ubuntu 18.04 LTS server.

This is a response from mysqltuner:

```<code>    -------- Performance Metrics -----------------------------------------------------------------------
    [--] Up for: 17h 51m 40s (400K q [6.226 qps], 15K conn, TX: 1G, RX: 63M)
    [--] Reads / Writes: 98% / 2%
    [--] Binary logging is disabled
    [--] Physical Memory     : 7.8G
    [--] Max MySQL memory    : 352.4M
    [--] Other process memory: 1.6G
    [--] Total buffers: 192.0M global + 1.1M per thread (151 max threads)
    [--] P_S Max memory usage: 72B
[OK] Maximum reached memory usage: 207.9M (2.61% of installed RAM)
[OK] Maximum possible memory usage: 352.4M (4.43% of installed RAM)
[OK] Overall possible memory usage with other process is compatible with memory available
[OK] Slow queries: 0% (0/400K)
[OK] Highest usage of available connections: 9% (15/151)
[OK] Aborted connections: 0.01%  (1/15256)
[!!] name resolution is active : a reverse name resolution is made for each new connection and can reduce performance
[!!] Query cache may be disabled by default due to mutex contention.
[!!] Query cache efficiency: 0.0% (0 cached / 338K selects)
[OK] Query cache prunes per day: 0
[OK] Sorts requiring temporary tables: 0% (0 temp sorts / 37K sorts)
[!!] Joins performed without indexes: 494
[!!] Temporary tables created on disk: 78% (15K on disk / 20K total)
[OK] Thread cache hit rate: 99% (30 created / 15K connections)
[OK] Table cache hit rate: 29% (1K open / 6K opened)
[OK] Open file limit used: 2% (136/5K)
[OK] Table locks acquired immediately: 100% (1K immediate / 1K locks)

-------- Performance schema ------------------------------------------------------------------------
[--] Memory used by P_S: 72B
[--] Sys schema is installed.

-------- ThreadPool Metrics ------------------------------------------------------------------------
[--] ThreadPool stat is disabled.

-------- MyISAM Metrics ----------------------------------------------------------------------------
[!!] Key buffer used: 18.2% (3M used / 16M cache)
[OK] Key buffer size / total MyISAM indexes: 16.0M/126.0K
[!!] Read Key buffer hit rate: 68.8% (16 cached / 5 reads)

-------- InnoDB Metrics ----------------------------------------------------------------------------
[--] InnoDB is enabled.
[--] InnoDB Thread Concurrency: 0
[OK] InnoDB File per table is activated
[OK] InnoDB buffer pool / data size: 128.0M/77.4M
[!!] Ratio InnoDB log file size / InnoDB Buffer pool size (75 %): 48.0M * 2/128.0M should be equal 25%
[OK] InnoDB buffer pool instances: 1
[--] Number of InnoDB Buffer Pool Chunk : 1 for 1 Buffer Pool Instance(s)
[OK] Innodb_buffer_pool_size aligned with Innodb_buffer_pool_chunk_size & Innodb_buffer_pool_instances
[OK] InnoDB Read buffer efficiency: 99.96% (12403660 hits/ 12408102 total)
[!!] InnoDB Write Log efficiency: 51.81% (14419 hits/ 27833 total)
[OK] InnoDB log waits: 0.00% (0 waits / 13414 writes)

-------- AriaDB Metrics ----------------------------------------------------------------------------
[--] AriaDB is disabled.

-------- TokuDB Metrics ----------------------------------------------------------------------------
[--] TokuDB is disabled.

-------- XtraDB Metrics ----------------------------------------------------------------------------
[--] XtraDB is disabled.

-------- RocksDB Metrics ---------------------------------------------------------------------------
[--] RocksDB is disabled.

-------- Spider Metrics ----------------------------------------------------------------------------
[--] Spider is disabled.

-------- Connect Metrics ---------------------------------------------------------------------------
[--] Connect is disabled.

-------- Galera Metrics ----------------------------------------------------------------------------
[--] Galera is disabled.

-------- Replication Metrics -----------------------------------------------------------------------
[--] Galera Synchronous replication: NO
[--] No replication slave(s) for this server.
[--] This is a standalone server.

-------- Recommendations ---------------------------------------------------------------------------
General recommendations:
    Control warning line(s) into /var/log/mysql/error.log file
    Control error line(s) into /var/log/mysql/error.log file
    MySQL started within last 24 hours - recommendations may be inaccurate
    Configure your accounts with ip or subnets only, then update your configuration with skip-name-resolve=1
    Adjust your join queries to always utilize indexes
    When making adjustments, make tmp_table_size/max_heap_table_size equal
    Reduce your SELECT DISTINCT queries which have no LIMIT clause
Variables to adjust:
    query_cache_size (=0)
    query_cache_type (=0)
    query_cache_limit (> 1M, or use smaller result sets)
    join_buffer_size (> 256.0K, or always use indexes with joins)
    tmp_table_size (> 16M)
    max_heap_table_size (> 16M)
    innodb_log_file_size * innodb_log_files_in_group should be equal to 1/4 of buffer pool size (=64M) if possible.
</code>```

All of my websites are running on latest version Wordpress, and most of the content is static - like business websites.

How can I improve performance of MySQL based on mysqltuner analyze?

答:
Suggestions for your my.cnf [mysqld] section from the incomplete MySQLTuner posted report,

```<code>thread_cache_size=64
tmp_table_size=32M
max_heap_table_size=32M
table_open_cache=4K
innodb_open_files=4K  # to reduce opened_tables count
</code>```

Please consider posting additional information requested about 24 hours ago and complete MySQLTuner report after shutdown; restart and minimum 24 hours regular workday use.

Title: How can tune MySQL for Wordpress sites?

Body:
I'm facing a problem that my MySQL database is slow, so I decided to check with mysqltuner.pl, I don't want to make any changes before I'm sure what I'm doing.

I'm running MySQL 5.7 on Ubuntu 18.04 LTS server.

This is a response from mysqltuner:

    -------- Performance Metrics -----------------------------------------------------------------------
    [--] Up for: 17h 51m 40s (400K q [6.226 qps], 15K conn, TX: 1G, RX: 63M)
    [--] Reads / Writes: 98% / 2%
    [--] Binary logging is disabled
    [--] Physical Memory     : 7.8G
    [--] Max MySQL memory    : 352.4M
    [--] Other process memory: 1.6G
    [--] Total buffers: 192.0M global + 1.1M per thread (151 max threads)
    [--] P_S Max memory usage: 72B
[OK] Maximum reached memory usage: 207.9M (2.61% of installed RAM)
[OK] Maximum possible memory usage: 352.4M (4.43% of installed RAM)
[OK] Overall possible memory usage with other process is compatible with memory available
[OK] Slow queries: 0% (0/400K)
[OK] Highest usage of available connections: 9% (15/151)
[OK] Aborted connections: 0.01%  (1/15256)
[!!] name resolution is active : a reverse name resolution is made for each new connection and can reduce performance
[!!] Query cache may be disabled by default due to mutex contention.
[!!] Query cache efficiency: 0.0% (0 cached / 338K selects)
[OK] Query cache prunes per day: 0
[OK] Sorts requiring temporary tables: 0% (0 temp sorts / 37K sorts)
[!!] Joins performed without indexes: 494
[!!] Temporary tables created on disk: 78% (15K on disk / 20K total)
[OK] Thread cache hit rate: 99% (30 created / 15K connections)
[OK] Table cache hit rate: 29% (1K open / 6K opened)
[OK] Open file limit used: 2% (136/5K)
[OK] Table locks acquired immediately: 100% (1K immediate / 1K locks)

-------- Performance schema ------------------------------------------------------------------------
[--] Memory used by P_S: 72B
[--] Sys schema is installed.

-------- ThreadPool Metrics ------------------------------------------------------------------------
[--] ThreadPool stat is disabled.

-------- MyISAM Metrics ----------------------------------------------------------------------------
[!!] Key buffer used: 18.2% (3M used / 16M cache)
[OK] Key buffer size / total MyISAM indexes: 16.0M/126.0K
[!!] Read Key buffer hit rate: 68.8% (16 cached / 5 reads)

-------- InnoDB Metrics ----------------------------------------------------------------------------
[--] InnoDB is enabled.
[--] InnoDB Thread Concurrency: 0
[OK] InnoDB File per table is activated
[OK] InnoDB buffer pool / data size: 128.0M/77.4M
[!!] Ratio InnoDB log file size / InnoDB Buffer pool size (75 %): 48.0M * 2/128.0M should be equal 25%
[OK] InnoDB buffer pool instances: 1
[--] Number of InnoDB Buffer Pool Chunk : 1 for 1 Buffer Pool Instance(s)
[OK] Innodb_buffer_pool_size aligned with Innodb_buffer_pool_chunk_size & Innodb_buffer_pool_instances
[OK] InnoDB Read buffer efficiency: 99.96% (12403660 hits/ 12408102 total)
[!!] InnoDB Write Log efficiency: 51.81% (14419 hits/ 27833 total)
[OK] InnoDB log waits: 0.00% (0 waits / 13414 writes)

-------- AriaDB Metrics ----------------------------------------------------------------------------
[--] AriaDB is disabled.

-------- TokuDB Metrics ----------------------------------------------------------------------------
[--] TokuDB is disabled.

-------- XtraDB Metrics ----------------------------------------------------------------------------
[--] XtraDB is disabled.

-------- RocksDB Metrics ---------------------------------------------------------------------------
[--] RocksDB is disabled.

-------- Spider Metrics ----------------------------------------------------------------------------
[--] Spider is disabled.

-------- Connect Metrics ---------------------------------------------------------------------------
[--] Connect is disabled.

-------- Galera Metrics ----------------------------------------------------------------------------
[--] Galera is disabled.

-------- Replication Metrics -----------------------------------------------------------------------
[--] Galera Synchronous replication: NO
[--] No replication slave(s) for this server.
[--] This is a standalone server.

-------- Recommendations ---------------------------------------------------------------------------
General recommendations:
    Control warning line(s) into /var/log/mysql/error.log file
    Control error line(s) into /var/log/mysql/error.log file
    MySQL started within last 24 hours - recommendations may be inaccurate
    Configure your accounts with ip or subnets only, then update your configuration with skip-name-resolve=1
    Adjust your join queries to always utilize indexes
    When making adjustments, make tmp_table_size/max_heap_table_size equal
    Reduce your SELECT DISTINCT queries which have no LIMIT clause
Variables to adjust:
    query_cache_size (=0)
    query_cache_type (=0)
    query_cache_limit (> 1M, or use smaller result sets)
    join_buffer_size (> 256.0K, or always use indexes with joins)
    tmp_table_size (> 16M)
    max_heap_table_size (> 16M)
    innodb_log_file_size * innodb_log_files_in_group should be equal to 1/4 of buffer pool size (=64M) if possible.

All of my websites are running on latest version Wordpress, and most of the content is static - like business websites.

How can I improve performance of MySQL based on mysqltuner analyze?

Body:
Suggestions for your my.cnf [mysqld] section from the incomplete MySQLTuner posted report,

thread_cache_size=64
tmp_table_size=32M
max_heap_table_size=32M
table_open_cache=4K
innodb_open_files=4K  # to reduce opened_tables count

Please consider posting additional information requested about 24 hours ago and complete MySQLTuner report after shutdown; restart and minimum 24 hours regular workday use.


问:
Create navbar i have problem with floating my links is left but i want to be right
I want to create a simple navbar but I don't know what I am doing wrong. I want my links to be on the right, site logo on the left side.

My links are on the left side but I want to the right site I added float:right; but doesn't work.

* {
  margin: 0;
  padding: 0;
  border: 0;
  box-sizing: border-box;
}

a,
li,
ul {
  text-decoration: none;
  list-style-type: none;
}

.bg-dark {
  background-color: #000;
}

.gyaro-bar {
  position: relative;
  display: flex;
  width: 100%;
  height: 50px;
}

.gyaro-bar>a.gyaro-brand {
  display: inline-flex;
  font-size: 20px;
  color: red;
  align-items: center;
  justify-content: center;
  float: left;
  margin-left: 15px;
}

.gyaro-bar>ul.gyaro-bar-items {
  display: inline-flex;
  float: right;
}

.gyaro-bar>ul.gyaro-bar-items>li.gyaro-bar-links {}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav class="gyaro-bar bg-dark">

    GYARO

  <ul class="gyaro-bar-items">
    <li class="">

        Home

    </li>
  </ul>
</nav></code>```

Here codepen link

答:
Just use justify-content: space-between on the .gyaro-bar element:

* {
  margin: 0;
  padding: 0;
  border: 0;
  box-sizing: border-box;
}

a,
li,
ul {
  text-decoration: none;
  list-style-type: none;
}

.bg-dark {
  background-color: #000;
}

.gyaro-bar {
  position: relative;
  display: flex;
  justify-content: space-between;
  width: 100%;
  height: 50px;
}

.gyaro-bar>a.gyaro-brand {
  display: inline-flex;
  font-size: 20px;
  color: red;
  align-items: center;
  justify-content: center;
  float: left;
  margin-left: 15px;
}

.gyaro-bar>ul.gyaro-bar-items {
  display: inline-flex;
  float: right;
}

.gyaro-bar>ul.gyaro-bar-items>li.gyaro-bar-links {}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav class="gyaro-bar bg-dark">

    GYARO

  <ul class="gyaro-bar-items">
    <li class="">

        Home

    </li>
  </ul>
</nav></code>```

Body:
I want to create a simple navbar but I don't know what I am doing wrong. I want my links to be on the right, site logo on the left side.

My links are on the left side but I want to the right site I added float:right; but doesn't work.

* {
  margin: 0;
  padding: 0;
  border: 0;
  box-sizing: border-box;
}

a,
li,
ul {
  text-decoration: none;
  list-style-type: none;
}

.bg-dark {
  background-color: #000;
}

.gyaro-bar {
  position: relative;
  display: flex;
  width: 100%;
  height: 50px;
}

.gyaro-bar>a.gyaro-brand {
  display: inline-flex;
  font-size: 20px;
  color: red;
  align-items: center;
  justify-content: center;
  float: left;
  margin-left: 15px;
}

.gyaro-bar>ul.gyaro-bar-items {
  display: inline-flex;
  float: right;
}

.gyaro-bar>ul.gyaro-bar-items>li.gyaro-bar-links {}

    GYARO

        Home

Here codepen link

Body:
Just use justify-content: space-between on the .gyaro-bar element:

* {
  margin: 0;
  padding: 0;
  border: 0;
  box-sizing: border-box;
}

a,
li,
ul {
  text-decoration: none;
  list-style-type: none;
}

.bg-dark {
  background-color: #000;
}

.gyaro-bar {
  position: relative;
  display: flex;
  justify-content: space-between;
  width: 100%;
  height: 50px;
}

.gyaro-bar>a.gyaro-brand {
  display: inline-flex;
  font-size: 20px;
  color: red;
  align-items: center;
  justify-content: center;
  float: left;
  margin-left: 15px;
}

.gyaro-bar>ul.gyaro-bar-items {
  display: inline-flex;
  float: right;
}

.gyaro-bar>ul.gyaro-bar-items>li.gyaro-bar-links {}

<nav class="gyaro-bar bg-dark">
  <a href="index.php" class="gyaro-brand">
    GYARO
  </a>
  <ul class="gyaro-bar-items">
    <li class="">
      <a href="index.php" class="">
        Home
      </a>
    </li>
  </ul>
</nav>


问:
What can I do to get the _PublishedWebsites folder include missing DLLs
My IIS project references a setup project that references an NServiceBus project that has a nuget package for a dll:

IISProject->SetupProject->NServiceBusProject->NugetPackage.

When I run my auto build (TFS) the NugetPackage.dll and NServiceBusProject are copied to the output folder.  But they are not copied to the _PublishedWebsites folder.  (But all other dlls that I need are copied.)

I am at a loss for how to get those files to copy over automatically.

The common answer on the internet is to set CopyLocal = True.  But it is already true for the NugetPackage and NServiceBusProject references.

Does anyone know how to say "I really do want you to include dependent projects in the published sites?

Or is there anything else I can look at?

答: I opened the .proj XML and reviewed the Reference for the DLL not getting copied.  I made sure <Private>True</Private> was included for the reference.  Somehow it wasn't being set even though UI showed Copy Local.  This is probably the same effect as removing/readding the reference as per other answer.


问:
How to convert a column number (e.g. 127) into an Excel column (e.g. AA)
How do you convert a numerical number to an Excel column name in C# without using automation getting the value directly from Excel.

Excel 2007 has a possible range of 1 to 16384, which is the number of columns that it supports. The resulting values should be in the form of excel column names, e.g. A, AA, AAA etc.

答:
Seems like so many answers are much more complex than necessary. Here is a generic Ruby answer based on the recursion described above:

One nice thing about this answer is that it's not limited to the 26 characters of English Alphabet. You can define any range you like in COLUMNS constant and it will do the right thing.

```<code>  # vim: ft=ruby
  class Numeric
    COLUMNS = ('A'..'Z').to_a

    def to_excel_column(n = self)
      n < 1 ?  '' : begin
        base = COLUMNS.size
        to_excel_column((n - 1) / base) + COLUMNS[(n - 1) % base]
      end
    end
  end

  # verify:
  (1..52).each { |i| printf "%4d => %4s\n", i, i.to_excel_column }
</code>```

This prints the following, eg:

```<code>   1 =>    A
   2 =>    B
   3 =>    C
  ....
  33 =>   AG
  34 =>   AH
  35 =>   AI
  36 =>   AJ
  37 =>   AK
  38 =>   AL
  39 =>   AM
  40 =>   AN
  41 =>   AO
  42 =>   AP
  43 =>   AQ
  44 =>   AR
  45 =>   AS
  46 =>   AT
  47 =>   AU
  48 =>   AV
  49 =>   AW
  50 =>   AX
  51 =>   AY
  52 =>   AZ
</code>```

OwnerDisplayName: krolley

LastEditorDisplayName: Unsliced

Body:
Seems like so many answers are much more complex than necessary. Here is a generic Ruby answer based on the recursion described above:

One nice thing about this answer is that it's not limited to the 26 characters of English Alphabet. You can define any range you like in COLUMNS constant and it will do the right thing.

  # vim: ft=ruby
  class Numeric
    COLUMNS = ('A'..'Z').to_a

    def to_excel_column(n = self)
      n < 1 ?  '' : begin
        base = COLUMNS.size
        to_excel_column((n - 1) / base) + COLUMNS[(n - 1) % base]
      end
    end
  end

  # verify:
  (1..52).each { |i| printf "%4d => %4s\n", i, i.to_excel_column }

This prints the following, eg:

   1 =>    A
   2 =>    B
   3 =>    C
  ....
  33 =>   AG
  34 =>   AH
  35 =>   AI
  36 =>   AJ
  37 =>   AK
  38 =>   AL
  39 =>   AM
  40 =>   AN
  41 =>   AO
  42 =>   AP
  43 =>   AQ
  44 =>   AR
  45 =>   AS
  46 =>   AT
  47 =>   AU
  48 =>   AV
  49 =>   AW
  50 =>   AX
  51 =>   AY
  52 =>   AZ


问:
Program to Create an image grid dynamically from a folder with images in it
I have a folder with a set of images in it. I want to create any type of program that can take in the path of the folder, number of rows and columns and give me output with an image grid. I am not sure how to do that.</p>

答:
Primitive example.

It uses sys.argv to get arguments pattern instead of path (like "path/*.jpg"), rows, columns

```<code>python script 'images/dot-*.png' 2 3
</code>```

It uses module PIL/pillow to read images, resize them and paste on output image.

```<code>import sys
import glob
from PIL import Image

# for test only
#sys.argv += ['images/dot-*.png', 2, 3]

# get arguments
pattern = sys.argv[1]
rows = int(sys.argv[2])
cols = int(sys.argv[3])

# get filenames
filenames = glob.glob(pattern)

# load images and resize to (100, 100)
images = [Image.open(name).resize((100, 100)) for name in filenames]

# create empty image to put thumbnails
new_image = Image.new('RGB', (cols*100, rows*100))

# put thumbnails
i = 0
for y in range(rows):
    if i >= len(images):
        break
    y *= 100
    for x in range(cols):
        x *= 100
        img = images[i]
        new_image.paste(img, (x, y, x+100, y+100))
        print('paste:', x, y)
        i += 1

# save it
new_image.save('output.jpg')
</code>```

Body:
Primitive example.

It uses sys.argv to get arguments pattern instead of path (like "path/*.jpg"), rows, columns

python script 'images/dot-*.png' 2 3

It uses module PIL/pillow to read images, resize them and paste on output image.

import sys
import glob
from PIL import Image

# for test only
#sys.argv += ['images/dot-*.png', 2, 3]

# get arguments
pattern = sys.argv[1]
rows = int(sys.argv[2])
cols = int(sys.argv[3])

# get filenames
filenames = glob.glob(pattern)

# load images and resize to (100, 100)
images = [Image.open(name).resize((100, 100)) for name in filenames]

# create empty image to put thumbnails
new_image = Image.new('RGB', (cols*100, rows*100))

# put thumbnails
i = 0
for y in range(rows):
    if i >= len(images):
        break
    y *= 100
    for x in range(cols):
        x *= 100
        img = images[i]
        new_image.paste(img, (x, y, x+100, y+100))
        print('paste:', x, y)
        i += 1

# save it
new_image.save('output.jpg')


问:
NoMethodError in AuthenticationsController#create | omniauth + devise
NoMethodError in AuthenticationsController#create

undefined method `user' for # /Authentication:0x00000105c7b1f8\

I'm pulling my hair out.. I downloaded the sample app from railscasts and it works.. mine has what looks like one last bug.

I am attempting to follow the railscasts to add this in to my app that is/was otherwise working -
http://railscasts.com/episodes/236-omniauth-part-2

It seems that it's mostly getting there - in the authorizations table there is a record..

I'm not getting as far as the step where the page asks for an email because it doesn't have one.

I'm sure this is super simple - here are some snippets:

controller:

```<code>class AuthenticationsController < ApplicationController

  def create
    omniauth = request.env["omniauth.auth"]
    authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])
    if authentication
      flash[:notice] = "Signed in successfully."
      sign_in_and_redirect(:user, authentication.user)
    elsif current_user
      current_user.authentications.create!(:provider => omniauth['provider'], :uid => omniauth['uid'])
      flash[:notice] = "Authentication successful."
      redirect_to authentications_url
    else
      @user = User.new
      @user.apply_omniauth(omniauth)
      if @user.save
        flash[:notice] = "Signed in successfully."
        sign_in_and_redirect(:user, user)
      else
        session[:omniauth] = omniauth.except('extra')
        redirect_to new_user_registration_url
      end

    end
  end

end
</code>```

devise user model:

```<code>class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable, :lockable and :timeoutable
  has_many :authentications

  devise :database_authenticatable,
         :recoverable, :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  #attr_accessible :email, :password, :password_confirmation, :remember_me

  def apply_omniauth(omniauth)
    self.email = omniauth['user_info']['email'] if email.blank?
    authentications.build(:provider => omniauth['provider'], :uid => omniauth['uid'])
  end

  def password_required?
    (authentications.empty? || !password.blank?) && super
  end

end
</code>```

some of the routes.rb:

```<code>  resources :authentications
  match '/auth/:provider/callback' => 'authentications#create'

  get "search/show"

  #devise_for :users
  devise_for :users, :controllers => {:registrations => 'registrations'}
</code>```

答: There should be @user in sign_in_and_redirect(:user, user). Not user.

Body:
NoMethodError in AuthenticationsController#create

undefined method `user' for # /Authentication:0x00000105c7b1f8\

I'm pulling my hair out.. I downloaded the sample app from railscasts and it works.. mine has what looks like one last bug.

I am attempting to follow the railscasts to add this in to my app that is/was otherwise working -
http://railscasts.com/episodes/236-omniauth-part-2

It seems that it's mostly getting there - in the authorizations table there is a record..

I'm not getting as far as the step where the page asks for an email because it doesn't have one.

I'm sure this is super simple - here are some snippets:

controller:

class AuthenticationsController < ApplicationController

  def create
    omniauth = request.env["omniauth.auth"]
    authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])
    if authentication
      flash[:notice] = "Signed in successfully."
      sign_in_and_redirect(:user, authentication.user)
    elsif current_user
      current_user.authentications.create!(:provider => omniauth['provider'], :uid => omniauth['uid'])
      flash[:notice] = "Authentication successful."
      redirect_to authentications_url
    else
      @user = User.new
      @user.apply_omniauth(omniauth)
      if @user.save
        flash[:notice] = "Signed in successfully."
        sign_in_and_redirect(:user, user)
      else
        session[:omniauth] = omniauth.except('extra')
        redirect_to new_user_registration_url
      end

    end
  end

end

devise user model:

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable, :lockable and :timeoutable
  has_many :authentications

  devise :database_authenticatable,
         :recoverable, :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  #attr_accessible :email, :password, :password_confirmation, :remember_me

  def apply_omniauth(omniauth)
    self.email = omniauth['user_info']['email'] if email.blank?
    authentications.build(:provider => omniauth['provider'], :uid => omniauth['uid'])
  end

  def password_required?
    (authentications.empty? || !password.blank?) && super
  end

end

some of the routes.rb:

  resources :authentications
  match '/auth/:provider/callback' => 'authentications#create'

  get "search/show"

  #devise_for :users
  devise_for :users, :controllers => {:registrations => 'registrations'}


问:
How can I count the number of elements in a vector that fall within a particular range using r?
Let's say we a vector a = (10,23,57,37,59,25,63,33) and we want to calculate the frequency in the bins 10-19,20-29,30-39,40-49,50-59,60-69.The output should be in the form of a vector, in this case (1,2,2,2,1).

答:
We can use cut with table

```<code>table(cut(a, breaks = c(-Inf, seq(10, 70, by = 10), Inf)))
</code>```

Or another option is

```<code>table(findInterval, seq(10, 70, by = 10)))
</code>```

Body:
We can use cut with table

table(cut(a, breaks = c(-Inf, seq(10, 70, by = 10), Inf)))

Or another option is

table(findInterval, seq(10, 70, by = 10)))


答:
Using += on innerHTML destroys event listeners on the elements inside the HTML. Using document.createElement ensures event listeners are preserved after appending children to a container.

Here's a minimal, complete example:

for (let i = 1; i < 10; i++) {
  const anchor = document.createElement("a");
  document.body.appendChild(anchor);
  anchor.id = "title" + i;
  anchor.href = "#";
  anchor.textContent = "link " + i;
  document.getElementById("title" + i)
    .addEventListener("click", e => console.log(i));
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>a {
  margin-left: 0.3em;
}</code>```

Of course, the document.getElementById isn't necessary here since we just created the object in the loop block. This approach might help avoid generating ids dynamically, which seems like an antipattern.

for (let i = 1; i < 10; i++) {
  const anchor = document.createElement("a");
  document.body.appendChild(anchor);
  anchor.href = "#";
  anchor.textContent = "link " + i;
  anchor.addEventListener("click", e => console.log(i));
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>a {
  margin-left: 0.3em;
}</code>```

If you have arbitrary chunks of stringified HTML as in your example, you can use createElement("div"), set its innerHTML once to the chunk and add listeners as needed. Then append the divs as children of your container element.

for (let i = 1; i < 10; i++) {
  const rawHTML = `<div>link ${i}</div>`;
  const div = document.createElement("div");
  document.body.appendChild(div);
  div.href = "#";
  div.innerHTML = rawHTML;
  div.querySelector(`#link-${i}`)
    .addEventListener("click", e => console.log(i));
}```

Other approaches include appending to the innerHTML but providing a class name on the links, then using a document.querySelectorAll(className) after the HTML is built to add listeners to each link, or using event delegation to add a listener to the parent.

As a final note, usually styled <button> elements are preferred over links that have a no-action # href.

Title: How can I get the click event inside an innerHTML?

Body:
Using += on innerHTML destroys event listeners on the elements inside the HTML. Using document.createElement ensures event listeners are preserved after appending children to a container.

Here's a minimal, complete example:

for (let i = 1; i < 10; i++) {
  const anchor = document.createElement("a");
  document.body.appendChild(anchor);
  anchor.id = "title" + i;
  anchor.href = "#";
  anchor.textContent = "link " + i;
  document.getElementById("title" + i)
    .addEventListener("click", e => console.log(i));
}

a {
  margin-left: 0.3em;
}

Of course, the document.getElementById isn't necessary here since we just created the object in the loop block. This approach might help avoid generating ids dynamically, which seems like an antipattern.

for (let i = 1; i < 10; i++) {
  const anchor = document.createElement("a");
  document.body.appendChild(anchor);
  anchor.href = "#";
  anchor.textContent = "link " + i;
  anchor.addEventListener("click", e => console.log(i));
}

a {
  margin-left: 0.3em;
}

If you have arbitrary chunks of stringified HTML as in your example, you can use createElement("div"), set its innerHTML once to the chunk and add listeners as needed. Then append the divs as children of your container element.

for (let i = 1; i < 10; i++) {
  const rawHTML = `<div><a href="#" id="link-${i}">link ${i}</a></div>`;
  const div = document.createElement("div");
  document.body.appendChild(div);
  div.href = "#";
  div.innerHTML = rawHTML;
  div.querySelector(`#link-${i}`)
    .addEventListener("click", e => console.log(i));
}

Other approaches include appending to the innerHTML but providing a class name on the links, then using a document.querySelectorAll(className) after the HTML is built to add listeners to each link, or using event delegation to add a listener to the parent.

As a final note, usually styled <button> elements are preferred over links that have a no-action # href.


问:
Updating an xml attribute with boolean value using powershell
I have a sample XML as below:

```<code><?xml version="1.0" encoding="utf-8"?>
<Searchable xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" label="$RESX('Ebr.Crdm.Store.2_0','Item','Item')" xmlns="http://sysrepublic.com/Secure/4.0/DSL/SearchService">

  <Fields>
    <Field data-type="System.Int64" is-editable="true" id="item_transactionid" label="$RESX('Ebr.Crdm.Store.2_0','TransactionID','Transaction ID')" is-mandatory-display-field="false" is-hidden-display-field="false" is-virtual-date-time="false" is-display-field-only="false" use-utc-datetime="true" apply-user-timezone-offset="false" show-date="true" show-time="true" is-favourite="false" common-field="true">
      <FieldDescription primary-key="false" nullable="false" readonly="false" hidden="true" format="text" enable-required-validation="true" />
      <Operators>
        <Operator name="equal" />
        <Operator name="notequal" />
        <Operator name="greaterthan" />
        <Operator name="greaterthanequal" />
        <Operator name="lessthan" />
        <Operator name="lessthanequal" />
        <Operator name="between" />
        <Operator name="notbetween" />
        <Operator name="in" />
        <Operator name="notin" />
      </Operators>
      <LeftExpression>
        <Field data-type="System.Int64" common-field="true">
          <CollectionDescription collection="pos.CRDM_Item">
            <Relationship parent="pos.CRDM_Header">
              <RelatedField from="TransactionID" to="TransactionID" common-to-field="true" />
              <RelatedField from="TradingDay" to="TradingDay" common-to-field="true" />
            </Relationship>
          </CollectionDescription>
          <Description>TransactionID</Description>
        </Field>
      </LeftExpression>
    </Field>

 </Fields>
</Searchable>
</code>```

Below is the powershell code that I tried:

```<code>$xmlFile = "C:\Users\rparpani\Desktop\test2.xml"
[xml]$xml = Get-Content $xmlFile -Raw

$nodes = $xml.SelectNodes("//Field[@id = 'item_transactionid']")
foreach ($node in $nodes)
{
$node.is-hidden-display-field = 'True'

}

xml.Save('C:\Users\rparpani\Desktop\test2.xml')
</code>```

It appears that there is a different way to update a Boolean attribute. I'm trying to change the is-hidden-display-field from false to true. Can someone please suggest what is wrong with my code

答:
Your XML document uses namespaces, so you cannot locate your Field elements unless you pass a namespace-manager instance to the .SelectNodes() call.
Without that, no nodes match, and your loop is never entered.

However, PowerShell's convenient adaption of the XML DOM via dot notation is namespace-agnostic, which enables a more convenient (albeit slower) solution:

```<code>$xml.Searchable.Fields.Field |
  where id -eq 'item_transactionid' |
   foreach { $_.'is-hidden-display-field' = 'true' }
</code>```

Also note how attribute name is-hidden-display-field must be quoted in order to be used as a PowerShell property name.

For background information, see this answer.

Body:
I have a sample XML as below:

<?xml version="1.0" encoding="utf-8"?>
<Searchable xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" label="$RESX('Ebr.Crdm.Store.2_0','Item','Item')" xmlns="http://sysrepublic.com/Secure/4.0/DSL/SearchService">

  <Fields>
    <Field data-type="System.Int64" is-editable="true" id="item_transactionid" label="$RESX('Ebr.Crdm.Store.2_0','TransactionID','Transaction ID')" is-mandatory-display-field="false" is-hidden-display-field="false" is-virtual-date-time="false" is-display-field-only="false" use-utc-datetime="true" apply-user-timezone-offset="false" show-date="true" show-time="true" is-favourite="false" common-field="true">
      <FieldDescription primary-key="false" nullable="false" readonly="false" hidden="true" format="text" enable-required-validation="true" />
      <Operators>
        <Operator name="equal" />
        <Operator name="notequal" />
        <Operator name="greaterthan" />
        <Operator name="greaterthanequal" />
        <Operator name="lessthan" />
        <Operator name="lessthanequal" />
        <Operator name="between" />
        <Operator name="notbetween" />
        <Operator name="in" />
        <Operator name="notin" />
      </Operators>
      <LeftExpression>
        <Field data-type="System.Int64" common-field="true">
          <CollectionDescription collection="pos.CRDM_Item">
            <Relationship parent="pos.CRDM_Header">
              <RelatedField from="TransactionID" to="TransactionID" common-to-field="true" />
              <RelatedField from="TradingDay" to="TradingDay" common-to-field="true" />
            </Relationship>
          </CollectionDescription>
          <Description>TransactionID</Description>
        </Field>
      </LeftExpression>
    </Field>

 </Fields>
</Searchable>

Below is the powershell code that I tried:

$xmlFile = "C:\Users\rparpani\Desktop\test2.xml"
[xml]$xml = Get-Content $xmlFile -Raw

$nodes = $xml.SelectNodes("//Field[@id = 'item_transactionid']")
foreach ($node in $nodes)
{
$node.is-hidden-display-field = 'True'

}

xml.Save('C:\Users\rparpani\Desktop\test2.xml')

It appears that there is a different way to update a Boolean attribute. I'm trying to change the is-hidden-display-field from false to true. Can someone please suggest what is wrong with my code

Body:
Your XML document uses namespaces, so you cannot locate your Field elements unless you pass a namespace-manager instance to the .SelectNodes() call.
Without that, no nodes match, and your loop is never entered.

However, PowerShell's convenient adaption of the XML DOM via dot notation is namespace-agnostic, which enables a more convenient (albeit slower) solution:

$xml.Searchable.Fields.Field |
  where id -eq 'item_transactionid' |
   foreach { $_.'is-hidden-display-field' = 'true' }

Also note how attribute name is-hidden-display-field must be quoted in order to be used as a PowerShell property name.

For background information, see this answer.


问:
Android - cdma snr or ber
Would like to determine via code whether the voice channel on an Android is experiencing noise.

There is a list of functions at http://developer.android.com/reference/android/telephony/SignalStrength.html

I see a function getGsmBitErrorRate() and that will be useful when I switch to GSM.

I see the function getEvdoSnr() but I think that is only for the "data channel."

The only other function with CDMA is getCdmaEci0().  How can one derive SNR from Eci0()?
Is there some other way of deriving this value?

Review:  I'm looking for a function that returns something like Bit Error Rate OR a Signal to Noise Ratio.  I find one link that implies that ec/i0 is exactly the same thing as SNR.
But other pages have indicated that ec/i0 is the amount of signal that is available.

答:
Ec refers to the pilot signal energy.  Io refers to the noise energy.  Thus, Ec/Io is the "pilot-to-noise ratio", instead of the "signal-to-noise ratio" (i.e. SNR).  While, strictly speaking, the PNR is not the same as the SNR, as a practical matter you should be able to use the PNR as a proxy for the SNR.  The whole point of the pilot is to give the receiver information about the signal and allow it to estimate channel effects.

This web page looks useful- Ec/Io.

Edit: I forgot that there is a parameter set by the network provider that specifies what the power of the pilot should be as compared to the actual signal.  For instance, they could be the same power, in which case Ec/Io would be equal to the SNR, or the pilot could be half the power of the signal, in which case the SNR would always be 3 dB higher than Ec/Io.  The pilot to signal ratio can be any of a number of different values and is, as mentioned earlier, set by the network.  I don't recall what the parameter is called.

Title: Android - cdma snr or ber


问:
Android é showing as black diamond in email intent
I'm building a simple app in Android studio and using the ACTION_SEND intent to send a pre-populated email. For some reason gmail is not showing the "é" correctly in the subject of the email (black diamond with a question mark instead). Below is the code I'm using:

```<code>        public static final String s="String with é";
        byte[] b = s.getBytes(StandardCharsets.UTF_8);
        String emailSubject="";
        try{
            emailSubject = new String(b, "UTF-8");
        }
        catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Intent emailIntent = new Intent(Intent.ACTION_SEND);
        emailIntent.setType("application/image");
        emailIntent.putExtra(Intent.EXTRA_SUBJECT, emailSubject + " - blabla");
        emailIntent.putExtra(Intent.EXTRA_TEXT, textIntent);
        emailIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
        startActivityForResult(emailIntent, GMAILSENT);
</code>```

Thank you,

答:
I was able to fix the issue by adding the following line in gradle:
    compileOptions.encoding = 'ISO-8859-1'</p>

Body:
I'm building a simple app in Android studio and using the ACTION_SEND intent to send a pre-populated email. For some reason gmail is not showing the "é" correctly in the subject of the email (black diamond with a question mark instead). Below is the code I'm using:

        public static final String s="String with é";
        byte[] b = s.getBytes(StandardCharsets.UTF_8);
        String emailSubject="";
        try{
            emailSubject = new String(b, "UTF-8");
        }
        catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Intent emailIntent = new Intent(Intent.ACTION_SEND);
        emailIntent.setType("application/image");
        emailIntent.putExtra(Intent.EXTRA_SUBJECT, emailSubject + " - blabla");
        emailIntent.putExtra(Intent.EXTRA_TEXT, textIntent);
        emailIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
        startActivityForResult(emailIntent, GMAILSENT);

Thank you,


问:
Argument of type 'number' is not assignable to parameter of type 'never' in array.includes()
I'm receiving a Typescript error,

error TS2345: Argument of type 'number' is not assignable to parameter
of type 'string & number'. Type 'number' is not assignable to type
'string'. 112

```<code>setProductPrices(productPrices.filter(
  (p): boolean => !selectedProductIds.includes(p.id)));
                                               ^^^^
</code>```

from the following code:

```<code>export interface IProductPrice {
    id: number;
}
const [productPrices, setProductPrices] = useState<IProductPrice[]>([]);
const [selectedProductIds, setSelectedProductIds] = useState<string[] | number[]>([]);

const deleteSelectedProducts = (): void => {
        setProductPrices(productPrices.filter((p): boolean => !selectedProductIds.includes(p.id)));
        setSelectedProductIds([]);
};
</code>```

The includes() method is supposedly
expecting a parameter of 'never' while p.id is a number. Does anyone know how to fix this?

答:
For your useState instead of

```<code>const [selectedProductIds, setSelectedProductIds] = useState<string[] | number[]>([]);
</code>```

Can you try

```<code>const [selectedProductIds, setSelectedProductIds] = useState< (string|number)[]>([]);
</code>```

instead?

This is because there is probably some missing code where you've set selectedProductIds as an array of string. And in your code you've strictly defined it as 1 array and not the other. Maybe the above change fixes that. Kindly confirm.

Body:
I'm receiving a Typescript error,

error TS2345: Argument of type 'number' is not assignable to parameter
of type 'string & number'. Type 'number' is not assignable to type
'string'. 112

setProductPrices(productPrices.filter(
  (p): boolean => !selectedProductIds.includes(p.id)));
                                               ^^^^

from the following code:

export interface IProductPrice {
    id: number;
}
const [productPrices, setProductPrices] = useState<IProductPrice[]>([]);
const [selectedProductIds, setSelectedProductIds] = useState<string[] | number[]>([]);

const deleteSelectedProducts = (): void => {
        setProductPrices(productPrices.filter((p): boolean => !selectedProductIds.includes(p.id)));
        setSelectedProductIds([]);
};

The includes() method is supposedly
expecting a parameter of 'never' while p.id is a number. Does anyone know how to fix this?

Body:
For your useState instead of

const [selectedProductIds, setSelectedProductIds] = useState<string[] | number[]>([]);

Can you try

const [selectedProductIds, setSelectedProductIds] = useState< (string|number)[]>([]);

instead?

This is because there is probably some missing code where you've set selectedProductIds as an array of string. And in your code you've strictly defined it as 1 array and not the other. Maybe the above change fixes that. Kindly confirm.


问:
Combining Multiple Dataframes with Unique Name
I have for example 2 data frames with user and their rating for each place such as:

Dataframe 1:

```<code>Name    Golden Gate
Adam    1
Susan   4
Mike    5
John    4
</code>```

Dataframe 2:

```<code>Name    Botanical Garden
Jenny   1
Susan   4
Leslie  5
John    3
</code>```

I want to combine them into a single data frame with the result:

Combined Dataframe:

```<code>Name    Golden Gate   Botanical Garden
Adam    1             NA
Susan   4             4
Mike    5             NA
John    4             3
Jenny   NA            1
Leslie  NA            5
</code>```

How to do that?

Thank you.

答: I found that pandas merge with how='outer' solves the problem. The link provided by @Celius Stingher is useful</p>

Body:
I have for example 2 data frames with user and their rating for each place such as:

Dataframe 1:

Name    Golden Gate
Adam    1
Susan   4
Mike    5
John    4

Dataframe 2:

Name    Botanical Garden
Jenny   1
Susan   4
Leslie  5
John    3

I want to combine them into a single data frame with the result:

Combined Dataframe:

Name    Golden Gate   Botanical Garden
Adam    1             NA
Susan   4             4
Mike    5             NA
John    4             3
Jenny   NA            1
Leslie  NA            5

How to do that?

Thank you.


问:
How to select positive square root expression in SymPy solve?
I'm calculating an expression for a variable (p2) in terms of other variables (q1,q2,p1) by solving an expression (hamiltonian=energy). The solve method returns two solutions (positive and negative) corresponding to the same square root. Below is the sample code:

```<code>state_symbols = ['q1', 'q2','p1','p2']
sympy_symbols = sp.symbols([tuple(state_symbols)])

hamiltonian = "(q1**2+q2**2+p1**2+p2**2)/(2)+ (q1**2*q2 - (q2**3)/(3))"
sys_fn = sp.sympify(sys_hamiltonian, evaluate=False)

sym_energy = sp.Symbol('energy')

expr_p2 = sp.solve(
            sys_fn - sym_energy, sympy_symbols[0][-1])
</code>```

Now this expr_p2 is a list of two solutions one of which is positive square root. How do I assert that the one I pick is always a positive square?

答:
```<code>pos_soln = max(expr_p2)
</code>```

This is direct and simple.

Body:
I'm calculating an expression for a variable (p2) in terms of other variables (q1,q2,p1) by solving an expression (hamiltonian=energy). The solve method returns two solutions (positive and negative) corresponding to the same square root. Below is the sample code:

state_symbols = ['q1', 'q2','p1','p2']
sympy_symbols = sp.symbols([tuple(state_symbols)])

hamiltonian = "(q1**2+q2**2+p1**2+p2**2)/(2)+ (q1**2*q2 - (q2**3)/(3))"
sys_fn = sp.sympify(sys_hamiltonian, evaluate=False)

sym_energy = sp.Symbol('energy')

expr_p2 = sp.solve(
            sys_fn - sym_energy, sympy_symbols[0][-1])

Now this expr_p2 is a list of two solutions one of which is positive square root. How do I assert that the one I pick is always a positive square?

Body:
pos_soln = max(expr_p2)

This is direct and simple.