问:
Why is a Node.js 12 docker app connection to MongoDB 4 via the docker network giving a timeout while a connection via the public network works?
I'm seeing a problem I can't explain at all:

After upgrading a Meteor app to v 1.9 and therefore Node.js 12 we also have to switch docker containers to Node.js 12 based containers. In our case we use abernix/meteord:node-12-base (git).

After booting up the updated app we get a DB timeout in the docker container of the app:

```<code>/bundle/bundle/programs/server/node_modules/fibers/future.js:313
                                               throw(ex);
                                               ^

MongoTimeoutError: Server selection timed out after 10000 ms
    at Timeout._onTimeout (/bundle/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb-core/lib/sdam/topology.js:773:16)
    at listOnTimeout (internal/timers.js:531:17)
    at processTimers (internal/timers.js:475:7) {
  name: 'MongoTimeoutError',
  [Symbol(mongoErrorContextSymbol)]: {}
}
</code>```

This happens with the following MONGO_URL:

❌ mongodb://root:OurPw@mongo-docker-alias:27017/meteor?authSource=admin

Funnily enough when we expose the port 27017 in the MongoDB container the following MONGO_URL just works:

✔ mongodb://root:OurPw@docker-host:27017/meteor?authSource=admin

Now I thought we are having a docker problem but if I attach to a bash inside the Node.js 12 meteord container, apt install the MongoDB shell and try to connect with:

✔ mongo "mongodb://root:OurPw@mongo-docker-alias:27017/meteor?authSource=admin"

that also just works.

And now I'm left without a clue. I tried multiple MongoDB docker images between v4.0 and 4.2.3 as well as Node.js 12.14 and 12.10. And I also tried without MongoDB auth one time just to rule it out as the problem but the outcome is always the same.

Any idea would be very much appreciated since I'd like to avoid having to connect via an exposed port and the docker host's name because that is prone to errors obviously...

答:
tl;dr:

setting dns_search: '' for the backend in the docker-compose.yml (or via the docker CLI or other means) fixes the problem.

More information:

Docker seems to add any search directive of the host's /etc/resolv.conf to the container's /etc/resolv.conf per default. However resolving something like mongo-docker-alias.actual-intranet-domain.tld is likely to be problematic since the outside network and DNS has no knowledge of this subdomain. Actually we found out that it got still resolved inside the container in our case, it just took a few seconds (vs <1ms normally). And since the backend tries to establish multiple DB connection it always runs into the timeout.

Docker's DNS search option luckily allows to divert from the default behavior including setting a blank value. Knowing the problem another workaround should be to use docker aliases with a dot in it since then the search shouldn't be used, but we haven't tried that.

A few questions remain but they are not so important. Like in our case why did this happen with the Meteor update, maybe the actual reason was that also the docker version on the host changed since we wouldn't be aware of an infrastructure change. And in general why is docker adding these entries to /etc/resolv.conf? It doesn't seem very useful but if it is maybe there is in general a better approach for this?

A very helpful blog post on this matter was also published by davd.io.

Body:
I'm seeing a problem I can't explain at all:

After upgrading a Meteor app to v 1.9 and therefore Node.js 12 we also have to switch docker containers to Node.js 12 based containers. In our case we use abernix/meteord:node-12-base (git).

After booting up the updated app we get a DB timeout in the docker container of the app:

/bundle/bundle/programs/server/node_modules/fibers/future.js:313
                                               throw(ex);
                                               ^

MongoTimeoutError: Server selection timed out after 10000 ms
    at Timeout._onTimeout (/bundle/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb-core/lib/sdam/topology.js:773:16)
    at listOnTimeout (internal/timers.js:531:17)
    at processTimers (internal/timers.js:475:7) {
  name: 'MongoTimeoutError',
  [Symbol(mongoErrorContextSymbol)]: {}
}

This happens with the following MONGO_URL:

❌ mongodb://root:OurPw@mongo-docker-alias:27017/meteor?authSource=admin

Funnily enough when we expose the port 27017 in the MongoDB container the following MONGO_URL just works:

✔ mongodb://root:OurPw@docker-host:27017/meteor?authSource=admin

Now I thought we are having a docker problem but if I attach to a bash inside the Node.js 12 meteord container, apt install the MongoDB shell and try to connect with:

✔ mongo "mongodb://root:OurPw@mongo-docker-alias:27017/meteor?authSource=admin"

that also just works.

And now I'm left without a clue. I tried multiple MongoDB docker images between v4.0 and 4.2.3 as well as Node.js 12.14 and 12.10. And I also tried without MongoDB auth one time just to rule it out as the problem but the outcome is always the same.

Any idea would be very much appreciated since I'd like to avoid having to connect via an exposed port and the docker host's name because that is prone to errors obviously...


来源: stackexchange

问:
Alternative method to detect small grains beside larger ones in HED algorithm

My main task in my project is to detect the properties of the polygons encountered in the images of soil particles ,I use HED algorithm to detect the borders of the grains in the image as it is very intelligent in detecting the borders efficiently and is not affected by the noise in the image ,and it is based on deep neural network in opencv library however I faced a problem in case of taking images of small grains beside large grains as shown in the following image as it detect perfectly the larger ones and neglect to great extent the small grains , I don't know how to fix this issue as it affects the results I get from the image analysis .
My main question if there a way to enhance the efficiency of the algorithm to detect both grains effectively.
Find also attached the HED algorithm used .. I am using Canon 600D so I don't have doubt of the efficiency of the quality of images .

and the algorithm used HED

```<code># USAGE
# python detect_edges_image.py --edge-detector hed_model --image images/guitar.jpg

# import the necessary packages
import argparse
import cv2
import os
import easygui

path = easygui.fileopenbox()
print(path)
hdir = os.path.dirname(path)
print(hdir)
hfilename = os.path.basename(path)
print(hfilename)
hname = os.path.splitext(hfilename)[0]
print(hname)
houtname = hname+"_out.jpg"
print(houtname)
hout = os.path.sep.join([hdir,houtname])
print(hout)

# # construct the argument parser and parse the arguments
# ap = argparse.ArgumentParser()
# ap.add_argument("-d", "--edge-detector", type=str, required=True,
#   help="path to OpenCV's deep learning edge detector")
# ap.add_argument("-i", "--image", type=str, required=True,
#   help="path to input image")
# args = vars(ap.parse_args())

class CropLayer(object):
    def __init__(self, params, blobs):
        # initialize our starting and ending (x, y)-coordinates of
        # the crop
        self.startX = 0
        self.startY = 0
        self.endX = 0
        self.endY = 0

    def getMemoryShapes(self, inputs):
        # the crop layer will receive two inputs -- we need to crop
        # the first input blob to match the shape of the second one,
        # keeping the batch size and number of channels
        (inputShape, targetShape) = (inputs[0], inputs[1])
        (batchSize, numChannels) = (inputShape[0], inputShape[1])
        (H, W) = (targetShape[2], targetShape[3])

        # compute the starting and ending crop coordinates
        self.startX = int((inputShape[3] - targetShape[3]) / 2)
        self.startY = int((inputShape[2] - targetShape[2]) / 2)
        self.endX = self.startX + W
        self.endY = self.startY + H

        # return the shape of the volume (we'll perform the actual
        # crop during the forward pass
        return [[batchSize, numChannels, H, W]]

    def forward(self, inputs):
        # use the derived (x, y)-coordinates to perform the crop
        return [inputs[0][:, :, self.startY:self.endY,
                self.startX:self.endX]]

# load our serialized edge detector from disk
print("[INFO] loading edge detector...")

fpath = os.path.abspath(__file__)
fdir =  os.path.dirname(fpath)
print(fdir)
protoPath = os.path.sep.join([fdir,"hed_model", "deploy.prototxt"])
print(protoPath)
modelPath =  os.path.sep.join([fdir,"hed_model","hed_pretrained_bsds.caffemodel"])
print(modelPath)

net = cv2.dnn.readNetFromCaffe(protoPath, modelPath)

# register our new layer with the model
cv2.dnn_registerLayer("Crop", CropLayer)

# load the input image and grab its dimensions
image = cv2.imread('PATH')
# image = cv2.pyrMeanShiftFiltering(image1,10,20)
(H, W) = image.shape[:2]
# print(image.shape[:2])
# image.shape[:2] =(H*3, W*3)ho
# image = cv2.resize(image,0.5)

# convert the image to grayscale, blur it, and perform Canny
# edge detection
print("[INFO] performing Canny edge detection...")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
# blurred = cv2.addWeighted(gray,1.5,blurred,-0.5,0)
canny = cv2.Canny(blurred,30, 150)

# construct a blob out of the input image for the Holistically-Nested
# Edge Detector

# cc = cv2.cvtColor(canny, cv2.COLOR_GRAY2BGR)
# image = image+cc

# mean = (104.00698793, 116.66876762, 122.67891434),

blob = cv2.dnn.blobFromImage(image, scalefactor=1.0, size=(W, H),
                             # mean=(110,95,95),
                             mean=(104.00698793, 116.66876762, 122.67891434),
                            # mean=(104, 116, 122),
                            #  mean=(150, 120, 130),
                            #  mean=(145, 147, 180),
                             swapRB= False, crop=False)
print( blob)
cv2.waitKey(0)
# set the blob as the input to the network and perform a forward pass
# to compute the edges
print("[INFO] performing holistically-nested edge detection...")
net.setInput(blob)
hed = net.forward()
hed = cv2.resize(hed[0, 0], (W, H))
hed = (255 * hed).astype("uint8")

# show the output edge detection results for Canny and
# Holistically-Nested Edge Detection
cv2.imshow("Input", image)
cv2.imshow("Canny", canny)
cv2.imshow("HED", hed)
cv2.imwrite(hout, hed)

cv2.waitKey(0)
</code>```

I found that the mean values are very effective in the algorithm in the function cv2.dnn.blobFromImage()

答:
Instead of using the HED algorithm, another approach is to use connected component labeling already implemented as cv2.connectedComponentsWithStats. We can use this to separate objects and label cluster of pixels into individual segments.

Binary image

```<code>import cv2
import numpy as np

# Load image, grayscale, Gaussian Blur, Otsu's threshold
image = cv2.imread('1.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3,3), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
</code>```

Connected component labeling to create false color image

```<code># Perform connected component labeling
n_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(thresh, connectivity=4)

# Create false color image and color background black
colors = np.random.randint(0, 255, size=(n_labels, 3), dtype=np.uint8)
colors[0] = [0, 0, 0]  # for cosmetic reason we want the background black
false_colors = colors[labels]
</code>```

Now that we have segmented clusters of pixels, we can find the centroid of each labeled object. This information is already contained in the centroid variable returned from cv2.connectedComponentsWithStats

```<code># Obtain centroids
false_colors_centroid = false_colors.copy()
for centroid in centroids:
    cv2.drawMarker(false_colors_centroid, (int(centroid[0]), int(centroid[1])),
                   color=(255, 255, 255), markerType=cv2.MARKER_CROSS)
</code>```

There's a lot of centroids. We can filter using contour area to only keep the larger objects by using the information contained in stats.

```<code># Only keep larger objects by filtering using area
MIN_AREA = 50
false_color_centroid_filter = false_colors.copy()
for i, centroid in enumerate(centroids[1:], start=1):
    area = stats[i, 4]
    if area > MIN_AREA:
        cv2.drawMarker(false_color_centroid_filter, (int(centroid[0]), int(centroid[1])),
                       color=(255, 255, 255), markerType=cv2.MARKER_CROSS)
</code>```

Full code

```<code>import cv2
import numpy as np

# Load image, grayscale, Gaussian Blur, Otsu's threshold
image = cv2.imread('1.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3,3), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]

# Perform connected component labeling
n_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(thresh, connectivity=4)

# Create false color image and color background black
colors = np.random.randint(0, 255, size=(n_labels, 3), dtype=np.uint8)
colors[0] = [0, 0, 0]  # for cosmetic reason we want the background black
false_colors = colors[labels]

# Obtain centroids
false_colors_centroid = false_colors.copy()
for centroid in centroids:
    cv2.drawMarker(false_colors_centroid, (int(centroid[0]), int(centroid[1])),
                   color=(255, 255, 255), markerType=cv2.MARKER_CROSS)

# Only keep larger objects by filtering using area
MIN_AREA = 50
false_color_centroid_filter = false_colors.copy()
for i, centroid in enumerate(centroids[1:], start=1):
    area = stats[i, 4]
    if area > MIN_AREA:
        cv2.drawMarker(false_color_centroid_filter, (int(centroid[0]), int(centroid[1])),
                       color=(255, 255, 255), markerType=cv2.MARKER_CROSS)

cv2.imshow('binary', thresh)
cv2.imshow('false_colors', false_colors)
cv2.imshow('false_colors_centroids', false_colors_centroid)
cv2.imshow('false_color_centroid_filter', false_color_centroid_filter)
cv2.waitKey()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My main task in my project is to detect the properties of the polygons encountered in the images of soil particles ,I use HED algorithm to detect the borders of the grains in the image as it is very intelligent in detecting the borders efficiently and is not affected by the noise in the image ,and it is based on deep neural network in opencv library however I faced a problem in case of taking images of small grains beside large grains as shown in the following image as it detect perfectly the larger ones and neglect to great extent the small grains , I don't know how to fix this issue as it affects the results I get from the image analysis .
My main question if there a way to enhance the efficiency of the algorithm to detect both grains effectively.
Find also attached the HED algorithm used .. I am using Canon 600D so I don't have doubt of the efficiency of the quality of images .

and the algorithm used HED

# USAGE
# python detect_edges_image.py --edge-detector hed_model --image images/guitar.jpg

# import the necessary packages
import argparse
import cv2
import os
import easygui

path = easygui.fileopenbox()
print(path)
hdir = os.path.dirname(path)
print(hdir)
hfilename = os.path.basename(path)
print(hfilename)
hname = os.path.splitext(hfilename)[0]
print(hname)
houtname = hname+"_out.jpg"
print(houtname)
hout = os.path.sep.join([hdir,houtname])
print(hout)

# # construct the argument parser and parse the arguments
# ap = argparse.ArgumentParser()
# ap.add_argument("-d", "--edge-detector", type=str, required=True,
#   help="path to OpenCV's deep learning edge detector")
# ap.add_argument("-i", "--image", type=str, required=True,
#   help="path to input image")
# args = vars(ap.parse_args())

class CropLayer(object):
    def __init__(self, params, blobs):
        # initialize our starting and ending (x, y)-coordinates of
        # the crop
        self.startX = 0
        self.startY = 0
        self.endX = 0
        self.endY = 0

    def getMemoryShapes(self, inputs):
        # the crop layer will receive two inputs -- we need to crop
        # the first input blob to match the shape of the second one,
        # keeping the batch size and number of channels
        (inputShape, targetShape) = (inputs[0], inputs[1])
        (batchSize, numChannels) = (inputShape[0], inputShape[1])
        (H, W) = (targetShape[2], targetShape[3])

        # compute the starting and ending crop coordinates
        self.startX = int((inputShape[3] - targetShape[3]) / 2)
        self.startY = int((inputShape[2] - targetShape[2]) / 2)
        self.endX = self.startX + W
        self.endY = self.startY + H

        # return the shape of the volume (we'll perform the actual
        # crop during the forward pass
        return [[batchSize, numChannels, H, W]]

    def forward(self, inputs):
        # use the derived (x, y)-coordinates to perform the crop
        return [inputs[0][:, :, self.startY:self.endY,
                self.startX:self.endX]]

# load our serialized edge detector from disk
print("[INFO] loading edge detector...")

fpath = os.path.abspath(__file__)
fdir =  os.path.dirname(fpath)
print(fdir)
protoPath = os.path.sep.join([fdir,"hed_model", "deploy.prototxt"])
print(protoPath)
modelPath =  os.path.sep.join([fdir,"hed_model","hed_pretrained_bsds.caffemodel"])
print(modelPath)

net = cv2.dnn.readNetFromCaffe(protoPath, modelPath)

# register our new layer with the model
cv2.dnn_registerLayer("Crop", CropLayer)

# load the input image and grab its dimensions
image = cv2.imread('PATH')
# image = cv2.pyrMeanShiftFiltering(image1,10,20)
(H, W) = image.shape[:2]
# print(image.shape[:2])
# image.shape[:2] =(H*3, W*3)ho
# image = cv2.resize(image,0.5)

# convert the image to grayscale, blur it, and perform Canny
# edge detection
print("[INFO] performing Canny edge detection...")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
# blurred = cv2.addWeighted(gray,1.5,blurred,-0.5,0)
canny = cv2.Canny(blurred,30, 150)

# construct a blob out of the input image for the Holistically-Nested
# Edge Detector

# cc = cv2.cvtColor(canny, cv2.COLOR_GRAY2BGR)
# image = image+cc

# mean = (104.00698793, 116.66876762, 122.67891434),

blob = cv2.dnn.blobFromImage(image, scalefactor=1.0, size=(W, H),
                             # mean=(110,95,95),
                             mean=(104.00698793, 116.66876762, 122.67891434),
                            # mean=(104, 116, 122),
                            #  mean=(150, 120, 130),
                            #  mean=(145, 147, 180),
                             swapRB= False, crop=False)
print( blob)
cv2.waitKey(0)
# set the blob as the input to the network and perform a forward pass
# to compute the edges
print("[INFO] performing holistically-nested edge detection...")
net.setInput(blob)
hed = net.forward()
hed = cv2.resize(hed[0, 0], (W, H))
hed = (255 * hed).astype("uint8")

# show the output edge detection results for Canny and
# Holistically-Nested Edge Detection
cv2.imshow("Input", image)
cv2.imshow("Canny", canny)
cv2.imshow("HED", hed)
cv2.imwrite(hout, hed)

cv2.waitKey(0)

I found that the mean values are very effective in the algorithm in the function cv2.dnn.blobFromImage()

Body:
Instead of using the HED algorithm, another approach is to use connected component labeling already implemented as cv2.connectedComponentsWithStats. We can use this to separate objects and label cluster of pixels into individual segments.

Binary image

import cv2
import numpy as np

# Load image, grayscale, Gaussian Blur, Otsu's threshold
image = cv2.imread('1.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3,3), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]

Connected component labeling to create false color image

# Perform connected component labeling
n_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(thresh, connectivity=4)

# Create false color image and color background black
colors = np.random.randint(0, 255, size=(n_labels, 3), dtype=np.uint8)
colors[0] = [0, 0, 0]  # for cosmetic reason we want the background black
false_colors = colors[labels]

Now that we have segmented clusters of pixels, we can find the centroid of each labeled object. This information is already contained in the centroid variable returned from cv2.connectedComponentsWithStats

# Obtain centroids
false_colors_centroid = false_colors.copy()
for centroid in centroids:
    cv2.drawMarker(false_colors_centroid, (int(centroid[0]), int(centroid[1])),
                   color=(255, 255, 255), markerType=cv2.MARKER_CROSS)

There's a lot of centroids. We can filter using contour area to only keep the larger objects by using the information contained in stats.

# Only keep larger objects by filtering using area
MIN_AREA = 50
false_color_centroid_filter = false_colors.copy()
for i, centroid in enumerate(centroids[1:], start=1):
    area = stats[i, 4]
    if area > MIN_AREA:
        cv2.drawMarker(false_color_centroid_filter, (int(centroid[0]), int(centroid[1])),
                       color=(255, 255, 255), markerType=cv2.MARKER_CROSS)

Full code

import cv2
import numpy as np

# Load image, grayscale, Gaussian Blur, Otsu's threshold
image = cv2.imread('1.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3,3), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]

# Perform connected component labeling
n_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(thresh, connectivity=4)

# Create false color image and color background black
colors = np.random.randint(0, 255, size=(n_labels, 3), dtype=np.uint8)
colors[0] = [0, 0, 0]  # for cosmetic reason we want the background black
false_colors = colors[labels]

# Obtain centroids
false_colors_centroid = false_colors.copy()
for centroid in centroids:
    cv2.drawMarker(false_colors_centroid, (int(centroid[0]), int(centroid[1])),
                   color=(255, 255, 255), markerType=cv2.MARKER_CROSS)

# Only keep larger objects by filtering using area
MIN_AREA = 50
false_color_centroid_filter = false_colors.copy()
for i, centroid in enumerate(centroids[1:], start=1):
    area = stats[i, 4]
    if area > MIN_AREA:
        cv2.drawMarker(false_color_centroid_filter, (int(centroid[0]), int(centroid[1])),
                       color=(255, 255, 255), markerType=cv2.MARKER_CROSS)

cv2.imshow('binary', thresh)
cv2.imshow('false_colors', false_colors)
cv2.imshow('false_colors_centroids', false_colors_centroid)
cv2.imshow('false_color_centroid_filter', false_color_centroid_filter)
cv2.waitKey()


问:
Mips, how to get the second value in one .word using an offset with lw
I have this code

```<code>size:   .word 8 9
</code>```

I would like to get the 9 and store it in a register, so far I have tried this

```<code>lw $a0, size
lw $a0, 4(size)
</code>```

But I don't think I am using the right offset number, how do I get the 8 and the 9 from this .word and store them in seperate registers

答:
To load an address, use la, not lw. Then, go 4 bytes past it.

```<code>la $t0, size
lw $a0, 0($t0)  # 8
lw $a1, 4($t0)  # 9
</code>```

Additionally, as @Eraklon said, comma-separate your .word directive:

```<code>size:
    .word 8, 9
</code>```

Body:
I have this code

size:   .word 8 9

I would like to get the 9 and store it in a register, so far I have tried this

lw $a0, size
lw $a0, 4(size)

But I don't think I am using the right offset number, how do I get the 8 and the 9 from this .word and store them in seperate registers

Body:
To load an address, use la, not lw. Then, go 4 bytes past it.

la $t0, size
lw $a0, 0($t0)  # 8
lw $a1, 4($t0)  # 9

Additionally, as @Eraklon said, comma-separate your .word directive:

size:
    .word 8, 9


问:
How to compare every record to another record(name reverse problem) and erase duplicates one?
I have a terrible to identify unique record(value).
I have a table like this:

```<code>ID NAME            DESCRIPTION
1  Yanagida Fumit  best author
2  Ha Il-kwan      new author
3  Fumit Yanagida  best author
4  Ha Il Kwan      new author
5  Ilkwan Ha       new author
</code>```

There are 5 records in same table called autho table. But in actually, there are 2 authors.
First record and third record are stored from one author information and second, 4th and 5th are one author.
I want to make this like below.

```<code>ID NAME            DESCRIPTION
1  Yanagida Fumit  best author
2  Ha Il Kwan      new author
</code>```

It means that, I am going to erase all duplicates against reverse name problem.
I wonder if I can compare two values(string) in same column.
Help me please. I will be happy with your any help!

答:
Here is a php solution:</p>

```<code>remove_duplicates("Yanagida Fumit");

function remove_duplicates($full_search_str) {
    // establish connection to your db

    // fetch data
    $query = "          SELECT  `id`, `name`
                        FROM    `" . $tbl_name . "`
                        WHERE   MATCH (`name`) AGAINST ('" . $full_search_str . "' IN BOOLEAN MODE)
                        AND     `name` <> '" . $full_search_str . "'
             ";

    // run query
    $results = $conn->query($query);

    // loop through results
    foreach($results as $result) {
            // build query
            $query = "  DELETE
                        FROM    `" . $tbl_name . "`
                        WHERE   `id` = " . $result['id'];

            // run query
            $result = $conn->query($query);
    }
}
</code>```

Body:
I have a terrible to identify unique record(value).
I have a table like this:

ID NAME            DESCRIPTION
1  Yanagida Fumit  best author
2  Ha Il-kwan      new author
3  Fumit Yanagida  best author
4  Ha Il Kwan      new author
5  Ilkwan Ha       new author

There are 5 records in same table called autho table. But in actually, there are 2 authors.
First record and third record are stored from one author information and second, 4th and 5th are one author.
I want to make this like below.

ID NAME            DESCRIPTION
1  Yanagida Fumit  best author
2  Ha Il Kwan      new author

It means that, I am going to erase all duplicates against reverse name problem.
I wonder if I can compare two values(string) in same column.
Help me please. I will be happy with your any help!

Body:
Here is a php solution:

remove_duplicates("Yanagida Fumit");

function remove_duplicates($full_search_str) {
    // establish connection to your db

    // fetch data
    $query = "          SELECT  `id`, `name`
                        FROM    `" . $tbl_name . "`
                        WHERE   MATCH (`name`) AGAINST ('" . $full_search_str . "' IN BOOLEAN MODE)
                        AND     `name` <> '" . $full_search_str . "'
             ";

    // run query
    $results = $conn->query($query);

    // loop through results
    foreach($results as $result) {
            // build query
            $query = "  DELETE
                        FROM    `" . $tbl_name . "`
                        WHERE   `id` = " . $result['id'];

            // run query
            $result = $conn->query($query);
    }
}


问:
SQLite: UPDATE all rows/cols of all tables with the same (absolute) REPLACE function
How can all entries of all tables of a database be updated with - let's say - n = REPLACE(n,"abc","xyz")?
I don't know in advance, how many tables there are in the database and what are their names. Nor do I know how many columns there are in each table and what are their names.

答:
After confirming that you do in fact want to create a new database which has a certain string replaced outside of semantic considerations, the method I already proposed in my first comment has been confirmed by you to be the solution for you.

With some additional details and explanation:

Use the .dump feature, search-and-replace in the output (stored in a text file). Then create a new database with the desired change by simply reading the from an "empty" database.

The empty database can be created with calling sqlite with a filename of a non-existing file. Feeding that call with a .dumped file fills that new database with the changed input. The result of a .dump can of course be pipe-edited with sed as one way to do a search-and-replace.

I.e. , as you commented, sqlite3 db.sqlite .dump | sed 's|FROM|TO|g' | sqlite3 db-new.sqlite should work and seems to do the trick for you.


问:
Extracting all text from a website using scrapy / cleaning up the data
I have been trying to create a program (I will share the code below) that will scan each and every page it can find on a domain, then scrape all of the text that is contained on the site.

I have created a program that seems to take all of the text from each page however all of the information is "lost" in all of the website code and is showing as this.

n\t\t\t\t', '\n\t\t\t\t', '\n\t\t\t\t', '\n\t\t\t', 'Dry lining is a system for cladding the internal faces of buildin
gs, such as walls and ceilings when with plasterboard when "wet" plaster is not required.', '\t\t', '\n\t\t\t\t', '\n\t\t\t\t\t\t', '\n\t\t\t', '\n\t\t', '\n\t\t\t\t\t\t', '\n\t\t\t', '\n\
', '\n\t\t\t\t\t\t', '\n\t\t\t', '\n\t\t', '\n\t\t\t\t', '\n\t\t\t', '\n\t\t\t\t\t', '\n\t\t\t\t', '\n\t\t\t\t', '\n\t\t\t', 'Coving', '\t\t', '\n\t\t\t\t', '\n\
t\t\t\t', '\n\t\t\t\t', '\n\t\t\

Can anyone help me clean up the text so that I am left with just the relevant information please!

Here is the code:

```<code>from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor

class MySpider(CrawlSpider):
    name = 'c'
    allowed_domains = ['billsplastering.co.uk']
    start_urls = ['https://www.billsplastering.co.uk/']

    rules = (
        Rule(LinkExtractor(), callback='parse_item', follow=True),
    )

    def parse_item(self, response):
        filename = response.url.split("/")[-2] + '.html'
        with open(filename, 'wb') as f:
            f.write(response.body)
        print(response.css("::text").extract())```

```

答:
Try this. It removes leading and trailing blanks from the list you posted above the code. Then it filters out the empty strings. </p>

```<code>list_body = [
    'n\t\t\t\t', '\n\t\t\t\t', '\n\t\t\t\t', '\n\t\t\t',
    'Dry lining is a system for cladding the internal faces of buildin gs, such as walls and ceilings when with plasterboard when "wet" plaster is not required.',
    '\t\t', '\n\t\t\t\t', '\n\t\t\t\t\t\t', '\n\t\t\t', '\n\t\t',
    '\n\t\t\t\t\t\t', '\n\t\t\t', '\n\ ', '\n\t\t\t\t\t\t', '\n\t\t\t', '\n\t\t',
    '\n\t\t\t\t', '\n\t\t\t', '\n\t\t\t\t\t', '\n\t\t\t\t', '\n\t\t\t\t',
    '\n\t\t\t', 'Coving', '\t\t', '\n\t\t\t\t', '\n\ t\t\t\t', '\n\t\t\t\t', '\n\t\t\t']

# Strip blanks from items in list
list_no_blanks = [text.strip() for text in list_body]

# Filter out empty strings
list_filter = list(filter(lambda x: x != "", list_no_blanks))
</code>```

Body:
I have been trying to create a program (I will share the code below) that will scan each and every page it can find on a domain, then scrape all of the text that is contained on the site.

I have created a program that seems to take all of the text from each page however all of the information is "lost" in all of the website code and is showing as this.

n\t\t\t\t', '\n\t\t\t\t', '\n\t\t\t\t', '\n\t\t\t', 'Dry lining is a system for cladding the internal faces of buildin
gs, such as walls and ceilings when with plasterboard when "wet" plaster is not required.', '\t\t', '\n\t\t\t\t', '\n\t\t\t\t\t\t', '\n\t\t\t', '\n\t\t', '\n\t\t\t\t\t\t', '\n\t\t\t', '\n\
', '\n\t\t\t\t\t\t', '\n\t\t\t', '\n\t\t', '\n\t\t\t\t', '\n\t\t\t', '\n\t\t\t\t\t', '\n\t\t\t\t', '\n\t\t\t\t', '\n\t\t\t', 'Coving', '\t\t', '\n\t\t\t\t', '\n\
t\t\t\t', '\n\t\t\t\t', '\n\t\t\

Can anyone help me clean up the text so that I am left with just the relevant information please!

Here is the code:

from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor

class MySpider(CrawlSpider):
    name = 'c'
    allowed_domains = ['billsplastering.co.uk']
    start_urls = ['https://www.billsplastering.co.uk/']

    rules = (
        Rule(LinkExtractor(), callback='parse_item', follow=True),
    )

    def parse_item(self, response):
        filename = response.url.split("/")[-2] + '.html'
        with open(filename, 'wb') as f:
            f.write(response.body)
        print(response.css("::text").extract())```

Body:
Try this. It removes leading and trailing blanks from the list you posted above the code. Then it filters out the empty strings.

list_body = [
    'n\t\t\t\t', '\n\t\t\t\t', '\n\t\t\t\t', '\n\t\t\t',
    'Dry lining is a system for cladding the internal faces of buildin gs, such as walls and ceilings when with plasterboard when "wet" plaster is not required.',
    '\t\t', '\n\t\t\t\t', '\n\t\t\t\t\t\t', '\n\t\t\t', '\n\t\t',
    '\n\t\t\t\t\t\t', '\n\t\t\t', '\n\ ', '\n\t\t\t\t\t\t', '\n\t\t\t', '\n\t\t',
    '\n\t\t\t\t', '\n\t\t\t', '\n\t\t\t\t\t', '\n\t\t\t\t', '\n\t\t\t\t',
    '\n\t\t\t', 'Coving', '\t\t', '\n\t\t\t\t', '\n\ t\t\t\t', '\n\t\t\t\t', '\n\t\t\t']

# Strip blanks from items in list
list_no_blanks = [text.strip() for text in list_body]

# Filter out empty strings
list_filter = list(filter(lambda x: x != "", list_no_blanks))


问:
Is there an AppBar in flutter totally dynamic elevation and background color?
I'm trying to do a dynamic app bar, when the scroll offset of the page is 0, the background color need to be transparent, the logo need to be white and the elevation 0, and, when the scroll offset change from 0, need transition to change the background color to white, the elevation to 5 and the logo color to red

I've already tried this code:

```<code> @override
  void initState() {
    super.initState();
    _scrollController = ScrollController()
      ..addListener(() {
        setState(() {
          offset = _scrollController.offset;
        });
      });
  }

...

final double transitionColor = min(max(offset, 0), 100) / 100;
final double transitionElevation = min(max(offset, 0), 50) / 10;

LjAppBar.getAppBar(
  brandingColor: offset != 0 ? LjTheme.ljPrimary.withOpacity(transitionColor) : Colors.white,
  backgroundColor: Colors.white.withOpacity(transitionColor),
  elevation: transitionElevation,
),
</code>```

But, is so slowly the effects and the application and is not working well... i hope someone can help me

答:
To my knowledge, the only way you can deal with this is by using SliverAppBar. Slivers in Flutter are widgets that can respond dynamically different scrolling statuses. Check out Slivers, demystified for a nice introduction on the topic from Emily Fortuna from the Flutter team.

In your case, with SliverAppBar, you can change the color, elevation, etc. of your app bar depending on the scrolling of your list. You will need SliverList for that.

It's kind of difficult to wrap your head around Sliver widgets, but don't get discouraged! Once you get used to them you will be able to achieve what you want.

Body:
I'm trying to do a dynamic app bar, when the scroll offset of the page is 0, the background color need to be transparent, the logo need to be white and the elevation 0, and, when the scroll offset change from 0, need transition to change the background color to white, the elevation to 5 and the logo color to red

I've already tried this code:

 @override
  void initState() {
    super.initState();
    _scrollController = ScrollController()
      ..addListener(() {
        setState(() {
          offset = _scrollController.offset;
        });
      });
  }

...

final double transitionColor = min(max(offset, 0), 100) / 100;
final double transitionElevation = min(max(offset, 0), 50) / 10;

LjAppBar.getAppBar(
  brandingColor: offset != 0 ? LjTheme.ljPrimary.withOpacity(transitionColor) : Colors.white,
  backgroundColor: Colors.white.withOpacity(transitionColor),
  elevation: transitionElevation,
),

But, is so slowly the effects and the application and is not working well... i hope someone can help me


问:
Async task freeze on Android
I have weird problem with my Activity and I dont know what to do...

```<code>private Bitmap mBitmap;

@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    mBitmap = initBitmap();
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.menuItemNew:
            doSomething();
            return true;
        case R.id.menuItemNative:
            showList();
            return true;

    }

    return(super.onOptionsItemSelected(item));
}

private boolean selected;

private void showList() {
    CharSequence[] items = {"First", "Second"};

    selected = false;
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Selection mode");
    builder.setSingleChoiceItems(items, 0, new OnClickListener() {

        public void onClick(DialogInterface dialog, int item) {
            selected = item == 1;
        }
    });
    builder.setPositiveButton("OK", new OnClickListener() {

        public void onClick(DialogInterface dialog, int which) {
            if (selected) {
                new NativeTask().execute();
            }
        }
    });
    Dialog dia = builder.create();
    dia.show();

}

private class NativeTask extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... params) {
        Log.i("task", "before Native Call");
        int buffer[] = new int[mBitmap.getWidth() * mBitmap.getHeight()];
        mBitmap.getPixels(buffer, 0, mBitmap.getWidth(), 0, 0, mBitmap.getWidth(), mBitmap.getHeight());
        int[] result = NativeLibrary.process(pixels);
        Log.i("task", "after Native Call");

        return null;
    }

    @Override
    protected void onProgressUpdate(String... progress) {
        Log.i("task", "in progress");
    }

    @Override
    protected void onPostExecute(String a) {

        Log.i("task", "in postExecute");
    }
}
</code>```

This is relevant part of my Activity. As you see, I have menu there and if you click on second item, dialog with list of 2 items appears. Then if you select and confirm second item in list, AsyncTask is being executed and some method from native code is called.

Looks good (for me), but some problem is there - when I select second item from list, native method is correctly called... but Activity freezes.

Log contains all three messages:

task: before Native call

task: after Native call

task: in postExecute

I don't know what more I have to do. Am I missing something? Why is my Activity freezing when I use AsyncTask? Is problem I'm working with Bitmap inside AsyncTask?
NativeLibrary.process(int[]) return correct array, no problem there.... so WHY?

I will be happy for any tip!

P.S: I'm sorry for my bad english

EDIT: Here's log for freeze

```<code>05-17 01:44:53.831: INFO/task(27629): after Natvive Call
05-17 01:44:53.831: INFO/task(27629): in postExecute
05-17 01:44:56.391: DEBUG/dalvikvm(24817): GC_EXPLICIT freed 7 objects / 280 bytes in 67ms
05-17 01:45:05.991: DEBUG/dalvikvm(16702): GC_EXPLICIT freed 103 objects / 3760 bytes in 669ms
05-17 01:45:24.011: DEBUG/dalvikvm(16635): GC_EXPLICIT freed 7 objects / 280 bytes in 690ms
05-17 01:45:27.181: WARN/WindowManager(96): Key dispatching timed out sending to my.test.application/my.test.application.NativeActivity
05-17 01:45:27.181: WARN/WindowManager(96): Previous dispatch state: {{KeyEvent{action=0 code=82 repeat=0 meta=0 scancode=139 mFlags=8} to Window{46518640 my.test.application/my.test.application.NativeActivity paused=false} @ 1305589511983 lw=Window{46518640 my.test.application/my.test.application.NativeActivity paused=false} lb=android.os.BinderProxy@46426770 fin=false gfw=true ed=true tts=0 wf=false fp=false mcf=Window{46518640 my.test.application/my.test.application.NativeActivity paused=false}}}
05-17 01:45:27.181: WARN/WindowManager(96): Current dispatch state: {{KeyEvent{action=1 code=82 repeat=0 meta=0 scancode=139 mFlags=8} to Window{46518640 my.test.application/my.test.application.NativeActivity paused=false} @ 1305589527184 lw=Window{46518640 my.test.application/my.test.application.NativeActivity paused=false} lb=android.os.BinderProxy@46426770 fin=false gfw=true ed=true tts=0 wf=false fp=false mcf=Window{46518640 my.test.application/my.test.application.NativeActivity paused=false}}}
05-17 01:45:27.181: WARN/WindowManager(96): waitedFor: 15000, keyDispatchingTimeout: 15000
05-17 01:45:27.221: ERROR/ActivityManager(96): ANR in my.test.application (my.test.application/.NativeActivity)
05-17 01:45:27.221: ERROR/ActivityManager(96): Reason: keyDispatchingTimedOut
05-17 01:45:27.221: ERROR/ActivityManager(96): Load: 1.73 / 1.48 / 1.71
05-17 01:45:27.221: ERROR/ActivityManager(96): CPU usage from 682640ms to 23ms ago:
05-17 01:45:27.221: ERROR/ActivityManager(96):   system_server: 2% = 1% user + 0% kernel / faults: 14389 minor 3 major
05-17 01:45:27.221: ERROR/ActivityManager(96):   com.htc.album: 1% = 1% user + 0% kernel / faults: 23991 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   logcat: 0% = 0% user + 0% kernel
05-17 01:45:27.221: ERROR/ActivityManager(96):   akmd: 0% = 0% user + 0% kernel / faults: 828 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   debuggerd: 0% = 0% user + 0% kernel / faults: 49 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   d.process.acore: 0% = 0% user + 0% kernel / faults: 1272 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   gets.SenseClock: 0% = 0% user + 0% kernel / faults: 1212 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   d.process.media: 0% = 0% user + 0% kernel / faults: 285 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   rmClockPlusDock: 0% = 0% user + 0% kernel / faults: 298 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   m.android.phone: 0% = 0% user + 0% kernel / faults: 36 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   harrison.agenda: 0% = 0% user + 0% kernel / faults: 264 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   adbd: 0% = 0% user + 0% kernel / faults: 57 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   LocationService: 0% = 0% user + 0% kernel / faults: 169 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   e.process.gapps: 0% = 0% user + 0% kernel / faults: 225 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   mpz.audioplayer: 0% = 0% user + 0% kernel / faults: 130 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   com.htc.bg: 0% = 0% user + 0% kernel / faults: 91 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   panel_on/0: 0% = 0% user + 0% kernel
05-17 01:45:27.221: ERROR/ActivityManager(96):   w1_bus_master1: 0% = 0% user + 0% kernel
05-17 01:45:27.221: ERROR/ActivityManager(96):   zygote: 0% = 0% user + 0% kernel / faults: 342 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   .android.htcime: 0% = 0% user + 0% kernel / faults: 118 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   synaptics_wq: 0% = 0% user + 0% kernel
05-17 01:45:27.221: ERROR/ActivityManager(96):   events/0: 0% = 0% user + 0% kernel
05-17 01:45:27.221: ERROR/ActivityManager(96):   suspend: 0% = 0% user + 0% kernel
05-17 01:45:27.221: ERROR/ActivityManager(96):   ds2784-battery.: 0% = 0% user + 0% kernel
05-17 01:45:27.221: ERROR/ActivityManager(96):   rild: 0% = 0% user + 0% kernel / faults: 2 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   ancedtaskkiller: 0% = 0% user + 0% kernel / faults: 36 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   ny.lindamanager: 0% = 0% user + 0% kernel / faults: 17 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   com.htc.bgp: 0% = 0% user + 0% kernel / faults: 32 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   ksoftirqd/0: 0% = 0% user + 0% kernel
05-17 01:45:27.221: ERROR/ActivityManager(96):   ish.batterylife: 0% = 0% user + 0% kernel / faults: 26 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   com.android.mms: 0% = 0% user + 0% kernel / faults: 16 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   d.process.acore: 0% = 0% user + 0% kernel / faults: 17 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):  +ik.application: 0% = 0% user + 0% kernel
05-17 01:45:27.221: ERROR/ActivityManager(96):  +flush-31:0: 0% = 0% user + 0% kernel
05-17 01:45:27.221: ERROR/ActivityManager(96):  +ik.application: 0% = 0% user + 0% kernel
05-17 01:45:27.221: ERROR/ActivityManager(96):  -flush-179:0: 0% = 0% user + 0% kernel
05-17 01:45:27.221: ERROR/ActivityManager(96):  -flush-7:8: 0% = 0% user + 0% kernel
05-17 01:45:27.221: ERROR/ActivityManager(96):  -flush-31:0: 0% = 0% user + 0% kernel
05-17 01:45:27.221: ERROR/ActivityManager(96): TOTAL: 23% = 20% user + 2% kernel + 0% irq
05-17 01:45:27.491: INFO/Process(96): Sending signal. PID: 27629 SIG: 3
05-17 01:45:27.491: INFO/dalvikvm(27629): threadid=3: reacting to signal 3
05-17 01:45:27.691: INFO/Process(96): Sending signal. PID: 96 SIG: 3
05-17 01:45:27.691: INFO/dalvikvm(96): threadid=3: reacting to signal 3
</code>```

And sometimes I get this:

```<code>05-17 01:36:59.841: INFO/task(27583): after NativeCall
05-17 01:36:59.841: INFO/task(27583): in postExecute
05-17 01:36:59.953: INFO/DEBUG(11783): *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
05-17 01:36:59.953: INFO/DEBUG(11783): Build fingerprint: 'htc_wwe/htc_bravo/bravo/bravo:2.2/FRF91/293415:user/release-keys'
05-17 01:36:59.953: INFO/DEBUG(11783): pid: 27583, tid: 27583  >>> my.test.application <<<
05-17 01:36:59.953: INFO/DEBUG(11783): signal 11 (SIGSEGV), fault addr ffdbb660
05-17 01:36:59.953: INFO/DEBUG(11783):  r0 00000310  r1 002db970  r2 002db660  r3 afd42328
05-17 01:36:59.953: INFO/DEBUG(11783):  r4 1ff5bf9e  r5 afd4372c  r6 0000181f  r7 ffadfcf1
05-17 01:36:59.953: INFO/DEBUG(11783):  r8 bebb3470  r9 41873c1c  10 41873c04  fp bebb37b8
05-17 01:36:59.953: INFO/DEBUG(11783):  ip ffadfcf0  sp bebb33b8  lr afd0c6b5  pc afd0c192  cpsr 20000030
05-17 01:36:59.953: INFO/DEBUG(11783):  d0  6472656767756265  d1  6f6e5f746e65696e
05-17 01:36:59.953: INFO/DEBUG(11783):  d2  7379732f3a70692e  d3  6d6172662f6d6578
05-17 01:36:59.953: INFO/DEBUG(11783):  d4  72662f6b726f7765  d5  2d6b726f77656d61
05-17 01:36:59.953: INFO/DEBUG(11783):  d6  3a6b70612e736572  d7  0000000100000000
05-17 01:36:59.953: INFO/DEBUG(11783):  d8  000000004635d958  d9  4385800000000000
05-17 01:36:59.953: INFO/DEBUG(11783):  d10 00000000437d0000  d11 0000000000000000
05-17 01:36:59.953: INFO/DEBUG(11783):  d12 0000000000000000  d13 0000000000000000
05-17 01:36:59.953: INFO/DEBUG(11783):  d14 0000000000000000  d15 0000000000000000
05-17 01:36:59.953: INFO/DEBUG(11783):  d16 0000000b0000000a  d17 c070100000000000
05-17 01:36:59.953: INFO/DEBUG(11783):  d18 4035000000000000  d19 0000000000000000
05-17 01:36:59.953: INFO/DEBUG(11783):  d20 3ff0000000000000  d21 8000000000000000
05-17 01:36:59.953: INFO/DEBUG(11783):  d22 c035000000000000  d23 ff00080008000700
05-17 01:36:59.953: INFO/DEBUG(11783):  d24 ff00080008000700  d25 ff00080008000700
05-17 01:36:59.953: INFO/DEBUG(11783):  d26 0100010001000100  d27 0100010001000100
05-17 01:36:59.953: INFO/DEBUG(11783):  d28 0100010001000100  d29 3ff0000000000000
05-17 01:36:59.953: INFO/DEBUG(11783):  d30 0000000000000000  d31 3ff0000000000000
05-17 01:36:59.953: INFO/DEBUG(11783):  scr 60000012
05-17 01:37:00.031: INFO/DEBUG(11783):          #00  pc 0000c192  /system/lib/libc.so
05-17 01:37:00.061: INFO/DEBUG(11783):          #01  pc 0000c6b0  /system/lib/libc.so
05-17 01:37:00.061: INFO/DEBUG(11783):          #02  pc 0000cd9e  /system/lib/libc.so
05-17 01:37:00.071: INFO/DEBUG(11783):          #03  pc 00019732  /system/lib/libutils.so
05-17 01:37:00.071: INFO/DEBUG(11783):          #04  pc 00048c9a  /system/lib/libandroid_runtime.so
05-17 01:37:00.071: INFO/DEBUG(11783):          #05  pc 00017034  /system/lib/libdvm.so
05-17 01:37:00.071: INFO/DEBUG(11783):          #06  pc 00045784  /system/lib/libdvm.so
05-17 01:37:00.071: INFO/DEBUG(11783):          #07  pc 0001bfa0  /system/lib/libdvm.so
05-17 01:37:00.071: INFO/DEBUG(11783):          #08  pc 00022c04  /system/lib/libdvm.so
05-17 01:37:00.081: INFO/DEBUG(11783):          #09  pc 00021aa0  /system/lib/libdvm.so
05-17 01:37:00.081: INFO/DEBUG(11783):          #10  pc 0005d162  /system/lib/libdvm.so
05-17 01:37:00.081: INFO/DEBUG(11783):          #11  pc 000659ec  /system/lib/libdvm.so
05-17 01:37:00.081: INFO/DEBUG(11783):          #12  pc 0001bfa0  /system/lib/libdvm.so
05-17 01:37:00.081: INFO/DEBUG(11783):          #13  pc 00022c04  /system/lib/libdvm.so
05-17 01:37:00.081: INFO/DEBUG(11783):          #14  pc 00021aa0  /system/lib/libdvm.so
05-17 01:37:00.081: INFO/DEBUG(11783):          #15  pc 0005cfa0  /system/lib/libdvm.so
05-17 01:37:00.091: INFO/DEBUG(11783):          #16  pc 000480fe  /system/lib/libdvm.so
05-17 01:37:00.091: INFO/DEBUG(11783):          #17  pc 0002ffbc  /system/lib/libandroid_runtime.so
05-17 01:37:00.091: INFO/DEBUG(11783):          #18  pc 000310b8  /system/lib/libandroid_runtime.so
05-17 01:37:00.091: INFO/DEBUG(11783):          #19  pc 00008ca8  /system/bin/app_process
05-17 01:37:00.091: INFO/DEBUG(11783):          #20  pc 0000d430  /system/lib/libc.so
05-17 01:37:00.091: INFO/DEBUG(11783): code around pc:
05-17 01:37:00.091: INFO/DEBUG(11783): afd0c170 c004f8c2 f0436843 f8c00c01 e09ec004
05-17 01:37:00.091: INFO/DEBUG(11783): afd0c180 0403f040 ea4f6054 f04c04dc 2c1f0701
05-17 01:37:00.091: INFO/DEBUG(11783): afd0c190 f841604f d81dc00c c138f8df 070ceb03
05-17 01:37:00.091: INFO/DEBUG(11783): afd0c1a0 0624f107 500cf853 00c4eb06 fa162601
05-17 01:37:00.091: INFO/DEBUG(11783): afd0c1b0 422cf404 432cd104 400cf843 e0044603
05-17 01:37:00.091: INFO/DEBUG(11783): code around lr:
05-17 01:37:00.091: INFO/DEBUG(11783): afd0c694 0f41f115 f04fbf88 d80c35ff 350b4927
05-17 01:37:00.091: INFO/DEBUG(11783): afd0c6a4 0507f025 68431860 4628b12b fc1cf7ff
05-17 01:37:00.101: INFO/DEBUG(11783): afd0c6b4 28004606 4e21d132 689119a2 d819428d
05-17 01:37:00.101: INFO/DEBUG(11783): afd0c6c4 69561b4b d9082b0f 60931970 0c01f043
05-17 01:37:00.101: INFO/DEBUG(11783): afd0c6d4 f8c06150 50c3c004 2300e017 61536093
05-17 01:37:00.101: INFO/DEBUG(11783): stack:
05-17 01:37:00.101: INFO/DEBUG(11783):     bebb3378  afd4372c  /system/lib/libc.so
05-17 01:37:00.101: INFO/DEBUG(11783):     bebb337c  00000000
05-17 01:37:00.101: INFO/DEBUG(11783):     bebb3380  00357588  [heap]
05-17 01:37:00.101: INFO/DEBUG(11783):     bebb3384  0000a000  [heap]
05-17 01:37:00.101: INFO/DEBUG(11783):     bebb3388  bebb3470  [stack]
05-17 01:37:00.101: INFO/DEBUG(11783):     bebb338c  41873c1c
05-17 01:37:00.101: INFO/DEBUG(11783):     bebb3390  41873c04
05-17 01:37:00.101: INFO/DEBUG(11783):     bebb3394  afd0be7d  /system/lib/libc.so
05-17 01:37:00.101: INFO/DEBUG(11783):     bebb3398  00000000
05-17 01:37:00.101: INFO/DEBUG(11783):     bebb339c  00000000
05-17 01:37:00.111: INFO/DEBUG(11783):     bebb33a0  00001404
05-17 01:37:00.111: INFO/DEBUG(11783):     bebb33a4  bebb33e8  [stack]
05-17 01:37:00.111: INFO/DEBUG(11783):     bebb33a8  fffffff1
05-17 01:37:00.111: INFO/DEBUG(11783):     bebb33ac  bebb33e8  [stack]
05-17 01:37:00.111: INFO/DEBUG(11783):     bebb33b0  df002777
05-17 01:37:00.111: INFO/DEBUG(11783):     bebb33b4  e3a070ad
05-17 01:37:00.111: INFO/DEBUG(11783): #00 bebb33b8  00000308
05-17 01:37:00.111: INFO/DEBUG(11783):     bebb33bc  afd42328  /system/lib/libc.so
05-17 01:37:00.111: INFO/DEBUG(11783):     bebb33c0  afd438e4  /system/lib/libc.so
05-17 01:37:00.111: INFO/DEBUG(11783):     bebb33c4  afd1040c  /system/lib/libc.so
05-17 01:37:00.111: INFO/DEBUG(11783):     bebb33c8  00000003
05-17 01:37:00.111: INFO/DEBUG(11783):     bebb33cc  afd43860  /system/lib/libc.so
05-17 01:37:00.111: INFO/DEBUG(11783):     bebb33d0  00000003
05-17 01:37:00.121: INFO/DEBUG(11783):     bebb33d4  afd42328  /system/lib/libc.so
05-17 01:37:00.121: INFO/DEBUG(11783):     bebb33d8  00000310
05-17 01:37:00.121: INFO/DEBUG(11783):     bebb33dc  00000003
05-17 01:37:00.121: INFO/DEBUG(11783):     bebb33e0  00000308
05-17 01:37:00.121: INFO/DEBUG(11783):     bebb33e4  afd0c6b5  /system/lib/libc.so
05-17 01:37:00.121: INFO/DEBUG(11783): #01 bebb33e8  432c3dd3  /system/framework/framework-res.apk
05-17 01:37:00.121: INFO/DEBUG(11783):     bebb33ec  00000000
05-17 01:37:00.121: INFO/DEBUG(11783):     bebb33f0  00000187
05-17 01:37:00.121: INFO/DEBUG(11783):     bebb33f4  00298c90  [heap]
05-17 01:37:00.121: INFO/DEBUG(11783):     bebb33f8  00000000
05-17 01:37:00.121: INFO/DEBUG(11783):     bebb33fc  00000308
05-17 01:37:00.121: INFO/DEBUG(11783):     bebb3400  00000000
05-17 01:37:00.121: INFO/DEBUG(11783):     bebb3404  00236320  [heap]
05-17 01:37:00.121: INFO/DEBUG(11783):     bebb3408  00298988  [heap]
05-17 01:37:00.131: INFO/DEBUG(11783):     bebb340c  a8126a18  /system/lib/libutils.so
05-17 01:37:00.131: INFO/DEBUG(11783):     bebb3410  00000308
05-17 01:37:00.131: INFO/DEBUG(11783):     bebb3414  afd0cda1  /system/lib/libc.so
05-17 01:37:00.861: INFO/ActivityManager(96): Process my.test.application (pid 27583) has died.
</code>```

in this second case it doesnt freese but Activity crashes...

EDIT: I found weird memory leak in Native part and when I fixed it, everything is ok :)

答:
I am confused as the declaration of NativeTask declares that it takes a Parameter(s) of type String as in:

```<code>new NativeTask().execute(string1);
</code>```

not

```<code>new NativeTask().execute();
</code>```

also you do not seem to use the string parameter in doInBackground as:

```<code>String inString= params[0];
</code>```

Hope that helps,
JAL

ContentLicense: CC BY-SA 3.0

Title: Async task freeze on Android

Body:
I have weird problem with my Activity and I dont know what to do...

private Bitmap mBitmap;

@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    mBitmap = initBitmap();
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.menuItemNew:
            doSomething();
            return true;
        case R.id.menuItemNative:
            showList();
            return true;

    }

    return(super.onOptionsItemSelected(item));
}

private boolean selected;

private void showList() {
    CharSequence[] items = {"First", "Second"};

    selected = false;
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Selection mode");
    builder.setSingleChoiceItems(items, 0, new OnClickListener() {

        public void onClick(DialogInterface dialog, int item) {
            selected = item == 1;
        }
    });
    builder.setPositiveButton("OK", new OnClickListener() {

        public void onClick(DialogInterface dialog, int which) {
            if (selected) {
                new NativeTask().execute();
            }
        }
    });
    Dialog dia = builder.create();
    dia.show();

}

private class NativeTask extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... params) {
        Log.i("task", "before Native Call");
        int buffer[] = new int[mBitmap.getWidth() * mBitmap.getHeight()];
        mBitmap.getPixels(buffer, 0, mBitmap.getWidth(), 0, 0, mBitmap.getWidth(), mBitmap.getHeight());
        int[] result = NativeLibrary.process(pixels);
        Log.i("task", "after Native Call");

        return null;
    }

    @Override
    protected void onProgressUpdate(String... progress) {
        Log.i("task", "in progress");
    }

    @Override
    protected void onPostExecute(String a) {

        Log.i("task", "in postExecute");
    }
}

This is relevant part of my Activity. As you see, I have menu there and if you click on second item, dialog with list of 2 items appears. Then if you select and confirm second item in list, AsyncTask is being executed and some method from native code is called.

Looks good (for me), but some problem is there - when I select second item from list, native method is correctly called... but Activity freezes.

Log contains all three messages:

task: before Native call

task: after Native call

task: in postExecute

I don't know what more I have to do. Am I missing something? Why is my Activity freezing when I use AsyncTask? Is problem I'm working with Bitmap inside AsyncTask?
NativeLibrary.process(int[]) return correct array, no problem there.... so WHY?

I will be happy for any tip!

P.S: I'm sorry for my bad english

EDIT: Here's log for freeze

05-17 01:44:53.831: INFO/task(27629): after Natvive Call
05-17 01:44:53.831: INFO/task(27629): in postExecute
05-17 01:44:56.391: DEBUG/dalvikvm(24817): GC_EXPLICIT freed 7 objects / 280 bytes in 67ms
05-17 01:45:05.991: DEBUG/dalvikvm(16702): GC_EXPLICIT freed 103 objects / 3760 bytes in 669ms
05-17 01:45:24.011: DEBUG/dalvikvm(16635): GC_EXPLICIT freed 7 objects / 280 bytes in 690ms
05-17 01:45:27.181: WARN/WindowManager(96): Key dispatching timed out sending to my.test.application/my.test.application.NativeActivity
05-17 01:45:27.181: WARN/WindowManager(96): Previous dispatch state: {{KeyEvent{action=0 code=82 repeat=0 meta=0 scancode=139 mFlags=8} to Window{46518640 my.test.application/my.test.application.NativeActivity paused=false} @ 1305589511983 lw=Window{46518640 my.test.application/my.test.application.NativeActivity paused=false} lb=android.os.BinderProxy@46426770 fin=false gfw=true ed=true tts=0 wf=false fp=false mcf=Window{46518640 my.test.application/my.test.application.NativeActivity paused=false}}}
05-17 01:45:27.181: WARN/WindowManager(96): Current dispatch state: {{KeyEvent{action=1 code=82 repeat=0 meta=0 scancode=139 mFlags=8} to Window{46518640 my.test.application/my.test.application.NativeActivity paused=false} @ 1305589527184 lw=Window{46518640 my.test.application/my.test.application.NativeActivity paused=false} lb=android.os.BinderProxy@46426770 fin=false gfw=true ed=true tts=0 wf=false fp=false mcf=Window{46518640 my.test.application/my.test.application.NativeActivity paused=false}}}
05-17 01:45:27.181: WARN/WindowManager(96): waitedFor: 15000, keyDispatchingTimeout: 15000
05-17 01:45:27.221: ERROR/ActivityManager(96): ANR in my.test.application (my.test.application/.NativeActivity)
05-17 01:45:27.221: ERROR/ActivityManager(96): Reason: keyDispatchingTimedOut
05-17 01:45:27.221: ERROR/ActivityManager(96): Load: 1.73 / 1.48 / 1.71
05-17 01:45:27.221: ERROR/ActivityManager(96): CPU usage from 682640ms to 23ms ago:
05-17 01:45:27.221: ERROR/ActivityManager(96):   system_server: 2% = 1% user + 0% kernel / faults: 14389 minor 3 major
05-17 01:45:27.221: ERROR/ActivityManager(96):   com.htc.album: 1% = 1% user + 0% kernel / faults: 23991 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   logcat: 0% = 0% user + 0% kernel
05-17 01:45:27.221: ERROR/ActivityManager(96):   akmd: 0% = 0% user + 0% kernel / faults: 828 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   debuggerd: 0% = 0% user + 0% kernel / faults: 49 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   d.process.acore: 0% = 0% user + 0% kernel / faults: 1272 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   gets.SenseClock: 0% = 0% user + 0% kernel / faults: 1212 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   d.process.media: 0% = 0% user + 0% kernel / faults: 285 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   rmClockPlusDock: 0% = 0% user + 0% kernel / faults: 298 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   m.android.phone: 0% = 0% user + 0% kernel / faults: 36 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   harrison.agenda: 0% = 0% user + 0% kernel / faults: 264 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   adbd: 0% = 0% user + 0% kernel / faults: 57 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   LocationService: 0% = 0% user + 0% kernel / faults: 169 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   e.process.gapps: 0% = 0% user + 0% kernel / faults: 225 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   mpz.audioplayer: 0% = 0% user + 0% kernel / faults: 130 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   com.htc.bg: 0% = 0% user + 0% kernel / faults: 91 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   panel_on/0: 0% = 0% user + 0% kernel
05-17 01:45:27.221: ERROR/ActivityManager(96):   w1_bus_master1: 0% = 0% user + 0% kernel
05-17 01:45:27.221: ERROR/ActivityManager(96):   zygote: 0% = 0% user + 0% kernel / faults: 342 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   .android.htcime: 0% = 0% user + 0% kernel / faults: 118 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   synaptics_wq: 0% = 0% user + 0% kernel
05-17 01:45:27.221: ERROR/ActivityManager(96):   events/0: 0% = 0% user + 0% kernel
05-17 01:45:27.221: ERROR/ActivityManager(96):   suspend: 0% = 0% user + 0% kernel
05-17 01:45:27.221: ERROR/ActivityManager(96):   ds2784-battery.: 0% = 0% user + 0% kernel
05-17 01:45:27.221: ERROR/ActivityManager(96):   rild: 0% = 0% user + 0% kernel / faults: 2 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   ancedtaskkiller: 0% = 0% user + 0% kernel / faults: 36 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   ny.lindamanager: 0% = 0% user + 0% kernel / faults: 17 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   com.htc.bgp: 0% = 0% user + 0% kernel / faults: 32 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   ksoftirqd/0: 0% = 0% user + 0% kernel
05-17 01:45:27.221: ERROR/ActivityManager(96):   ish.batterylife: 0% = 0% user + 0% kernel / faults: 26 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   com.android.mms: 0% = 0% user + 0% kernel / faults: 16 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):   d.process.acore: 0% = 0% user + 0% kernel / faults: 17 minor
05-17 01:45:27.221: ERROR/ActivityManager(96):  +ik.application: 0% = 0% user + 0% kernel
05-17 01:45:27.221: ERROR/ActivityManager(96):  +flush-31:0: 0% = 0% user + 0% kernel
05-17 01:45:27.221: ERROR/ActivityManager(96):  +ik.application: 0% = 0% user + 0% kernel
05-17 01:45:27.221: ERROR/ActivityManager(96):  -flush-179:0: 0% = 0% user + 0% kernel
05-17 01:45:27.221: ERROR/ActivityManager(96):  -flush-7:8: 0% = 0% user + 0% kernel
05-17 01:45:27.221: ERROR/ActivityManager(96):  -flush-31:0: 0% = 0% user + 0% kernel
05-17 01:45:27.221: ERROR/ActivityManager(96): TOTAL: 23% = 20% user + 2% kernel + 0% irq
05-17 01:45:27.491: INFO/Process(96): Sending signal. PID: 27629 SIG: 3
05-17 01:45:27.491: INFO/dalvikvm(27629): threadid=3: reacting to signal 3
05-17 01:45:27.691: INFO/Process(96): Sending signal. PID: 96 SIG: 3
05-17 01:45:27.691: INFO/dalvikvm(96): threadid=3: reacting to signal 3

And sometimes I get this:

05-17 01:36:59.841: INFO/task(27583): after NativeCall
05-17 01:36:59.841: INFO/task(27583): in postExecute
05-17 01:36:59.953: INFO/DEBUG(11783): *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
05-17 01:36:59.953: INFO/DEBUG(11783): Build fingerprint: 'htc_wwe/htc_bravo/bravo/bravo:2.2/FRF91/293415:user/release-keys'
05-17 01:36:59.953: INFO/DEBUG(11783): pid: 27583, tid: 27583  >>> my.test.application <<<
05-17 01:36:59.953: INFO/DEBUG(11783): signal 11 (SIGSEGV), fault addr ffdbb660
05-17 01:36:59.953: INFO/DEBUG(11783):  r0 00000310  r1 002db970  r2 002db660  r3 afd42328
05-17 01:36:59.953: INFO/DEBUG(11783):  r4 1ff5bf9e  r5 afd4372c  r6 0000181f  r7 ffadfcf1
05-17 01:36:59.953: INFO/DEBUG(11783):  r8 bebb3470  r9 41873c1c  10 41873c04  fp bebb37b8
05-17 01:36:59.953: INFO/DEBUG(11783):  ip ffadfcf0  sp bebb33b8  lr afd0c6b5  pc afd0c192  cpsr 20000030
05-17 01:36:59.953: INFO/DEBUG(11783):  d0  6472656767756265  d1  6f6e5f746e65696e
05-17 01:36:59.953: INFO/DEBUG(11783):  d2  7379732f3a70692e  d3  6d6172662f6d6578
05-17 01:36:59.953: INFO/DEBUG(11783):  d4  72662f6b726f7765  d5  2d6b726f77656d61
05-17 01:36:59.953: INFO/DEBUG(11783):  d6  3a6b70612e736572  d7  0000000100000000
05-17 01:36:59.953: INFO/DEBUG(11783):  d8  000000004635d958  d9  4385800000000000
05-17 01:36:59.953: INFO/DEBUG(11783):  d10 00000000437d0000  d11 0000000000000000
05-17 01:36:59.953: INFO/DEBUG(11783):  d12 0000000000000000  d13 0000000000000000
05-17 01:36:59.953: INFO/DEBUG(11783):  d14 0000000000000000  d15 0000000000000000
05-17 01:36:59.953: INFO/DEBUG(11783):  d16 0000000b0000000a  d17 c070100000000000
05-17 01:36:59.953: INFO/DEBUG(11783):  d18 4035000000000000  d19 0000000000000000
05-17 01:36:59.953: INFO/DEBUG(11783):  d20 3ff0000000000000  d21 8000000000000000
05-17 01:36:59.953: INFO/DEBUG(11783):  d22 c035000000000000  d23 ff00080008000700
05-17 01:36:59.953: INFO/DEBUG(11783):  d24 ff00080008000700  d25 ff00080008000700
05-17 01:36:59.953: INFO/DEBUG(11783):  d26 0100010001000100  d27 0100010001000100
05-17 01:36:59.953: INFO/DEBUG(11783):  d28 0100010001000100  d29 3ff0000000000000
05-17 01:36:59.953: INFO/DEBUG(11783):  d30 0000000000000000  d31 3ff0000000000000
05-17 01:36:59.953: INFO/DEBUG(11783):  scr 60000012
05-17 01:37:00.031: INFO/DEBUG(11783):          #00  pc 0000c192  /system/lib/libc.so
05-17 01:37:00.061: INFO/DEBUG(11783):          #01  pc 0000c6b0  /system/lib/libc.so
05-17 01:37:00.061: INFO/DEBUG(11783):          #02  pc 0000cd9e  /system/lib/libc.so
05-17 01:37:00.071: INFO/DEBUG(11783):          #03  pc 00019732  /system/lib/libutils.so
05-17 01:37:00.071: INFO/DEBUG(11783):          #04  pc 00048c9a  /system/lib/libandroid_runtime.so
05-17 01:37:00.071: INFO/DEBUG(11783):          #05  pc 00017034  /system/lib/libdvm.so
05-17 01:37:00.071: INFO/DEBUG(11783):          #06  pc 00045784  /system/lib/libdvm.so
05-17 01:37:00.071: INFO/DEBUG(11783):          #07  pc 0001bfa0  /system/lib/libdvm.so
05-17 01:37:00.071: INFO/DEBUG(11783):          #08  pc 00022c04  /system/lib/libdvm.so
05-17 01:37:00.081: INFO/DEBUG(11783):          #09  pc 00021aa0  /system/lib/libdvm.so
05-17 01:37:00.081: INFO/DEBUG(11783):          #10  pc 0005d162  /system/lib/libdvm.so
05-17 01:37:00.081: INFO/DEBUG(11783):          #11  pc 000659ec  /system/lib/libdvm.so
05-17 01:37:00.081: INFO/DEBUG(11783):          #12  pc 0001bfa0  /system/lib/libdvm.so
05-17 01:37:00.081: INFO/DEBUG(11783):          #13  pc 00022c04  /system/lib/libdvm.so
05-17 01:37:00.081: INFO/DEBUG(11783):          #14  pc 00021aa0  /system/lib/libdvm.so
05-17 01:37:00.081: INFO/DEBUG(11783):          #15  pc 0005cfa0  /system/lib/libdvm.so
05-17 01:37:00.091: INFO/DEBUG(11783):          #16  pc 000480fe  /system/lib/libdvm.so
05-17 01:37:00.091: INFO/DEBUG(11783):          #17  pc 0002ffbc  /system/lib/libandroid_runtime.so
05-17 01:37:00.091: INFO/DEBUG(11783):          #18  pc 000310b8  /system/lib/libandroid_runtime.so
05-17 01:37:00.091: INFO/DEBUG(11783):          #19  pc 00008ca8  /system/bin/app_process
05-17 01:37:00.091: INFO/DEBUG(11783):          #20  pc 0000d430  /system/lib/libc.so
05-17 01:37:00.091: INFO/DEBUG(11783): code around pc:
05-17 01:37:00.091: INFO/DEBUG(11783): afd0c170 c004f8c2 f0436843 f8c00c01 e09ec004
05-17 01:37:00.091: INFO/DEBUG(11783): afd0c180 0403f040 ea4f6054 f04c04dc 2c1f0701
05-17 01:37:00.091: INFO/DEBUG(11783): afd0c190 f841604f d81dc00c c138f8df 070ceb03
05-17 01:37:00.091: INFO/DEBUG(11783): afd0c1a0 0624f107 500cf853 00c4eb06 fa162601
05-17 01:37:00.091: INFO/DEBUG(11783): afd0c1b0 422cf404 432cd104 400cf843 e0044603
05-17 01:37:00.091: INFO/DEBUG(11783): code around lr:
05-17 01:37:00.091: INFO/DEBUG(11783): afd0c694 0f41f115 f04fbf88 d80c35ff 350b4927
05-17 01:37:00.091: INFO/DEBUG(11783): afd0c6a4 0507f025 68431860 4628b12b fc1cf7ff
05-17 01:37:00.101: INFO/DEBUG(11783): afd0c6b4 28004606 4e21d132 689119a2 d819428d
05-17 01:37:00.101: INFO/DEBUG(11783): afd0c6c4 69561b4b d9082b0f 60931970 0c01f043
05-17 01:37:00.101: INFO/DEBUG(11783): afd0c6d4 f8c06150 50c3c004 2300e017 61536093
05-17 01:37:00.101: INFO/DEBUG(11783): stack:
05-17 01:37:00.101: INFO/DEBUG(11783):     bebb3378  afd4372c  /system/lib/libc.so
05-17 01:37:00.101: INFO/DEBUG(11783):     bebb337c  00000000
05-17 01:37:00.101: INFO/DEBUG(11783):     bebb3380  00357588  [heap]
05-17 01:37:00.101: INFO/DEBUG(11783):     bebb3384  0000a000  [heap]
05-17 01:37:00.101: INFO/DEBUG(11783):     bebb3388  bebb3470  [stack]
05-17 01:37:00.101: INFO/DEBUG(11783):     bebb338c  41873c1c
05-17 01:37:00.101: INFO/DEBUG(11783):     bebb3390  41873c04
05-17 01:37:00.101: INFO/DEBUG(11783):     bebb3394  afd0be7d  /system/lib/libc.so
05-17 01:37:00.101: INFO/DEBUG(11783):     bebb3398  00000000
05-17 01:37:00.101: INFO/DEBUG(11783):     bebb339c  00000000
05-17 01:37:00.111: INFO/DEBUG(11783):     bebb33a0  00001404
05-17 01:37:00.111: INFO/DEBUG(11783):     bebb33a4  bebb33e8  [stack]
05-17 01:37:00.111: INFO/DEBUG(11783):     bebb33a8  fffffff1
05-17 01:37:00.111: INFO/DEBUG(11783):     bebb33ac  bebb33e8  [stack]
05-17 01:37:00.111: INFO/DEBUG(11783):     bebb33b0  df002777
05-17 01:37:00.111: INFO/DEBUG(11783):     bebb33b4  e3a070ad
05-17 01:37:00.111: INFO/DEBUG(11783): #00 bebb33b8  00000308
05-17 01:37:00.111: INFO/DEBUG(11783):     bebb33bc  afd42328  /system/lib/libc.so
05-17 01:37:00.111: INFO/DEBUG(11783):     bebb33c0  afd438e4  /system/lib/libc.so
05-17 01:37:00.111: INFO/DEBUG(11783):     bebb33c4  afd1040c  /system/lib/libc.so
05-17 01:37:00.111: INFO/DEBUG(11783):     bebb33c8  00000003
05-17 01:37:00.111: INFO/DEBUG(11783):     bebb33cc  afd43860  /system/lib/libc.so
05-17 01:37:00.111: INFO/DEBUG(11783):     bebb33d0  00000003
05-17 01:37:00.121: INFO/DEBUG(11783):     bebb33d4  afd42328  /system/lib/libc.so
05-17 01:37:00.121: INFO/DEBUG(11783):     bebb33d8  00000310
05-17 01:37:00.121: INFO/DEBUG(11783):     bebb33dc  00000003
05-17 01:37:00.121: INFO/DEBUG(11783):     bebb33e0  00000308
05-17 01:37:00.121: INFO/DEBUG(11783):     bebb33e4  afd0c6b5  /system/lib/libc.so
05-17 01:37:00.121: INFO/DEBUG(11783): #01 bebb33e8  432c3dd3  /system/framework/framework-res.apk
05-17 01:37:00.121: INFO/DEBUG(11783):     bebb33ec  00000000
05-17 01:37:00.121: INFO/DEBUG(11783):     bebb33f0  00000187
05-17 01:37:00.121: INFO/DEBUG(11783):     bebb33f4  00298c90  [heap]
05-17 01:37:00.121: INFO/DEBUG(11783):     bebb33f8  00000000
05-17 01:37:00.121: INFO/DEBUG(11783):     bebb33fc  00000308
05-17 01:37:00.121: INFO/DEBUG(11783):     bebb3400  00000000
05-17 01:37:00.121: INFO/DEBUG(11783):     bebb3404  00236320  [heap]
05-17 01:37:00.121: INFO/DEBUG(11783):     bebb3408  00298988  [heap]
05-17 01:37:00.131: INFO/DEBUG(11783):     bebb340c  a8126a18  /system/lib/libutils.so
05-17 01:37:00.131: INFO/DEBUG(11783):     bebb3410  00000308
05-17 01:37:00.131: INFO/DEBUG(11783):     bebb3414  afd0cda1  /system/lib/libc.so
05-17 01:37:00.861: INFO/ActivityManager(96): Process my.test.application (pid 27583) has died.

in this second case it doesnt freese but Activity crashes...

EDIT: I found weird memory leak in Native part and when I fixed it, everything is ok :)

Body:
I am confused as the declaration of NativeTask declares that it takes a Parameter(s) of type String as in:

new NativeTask().execute(string1);

not

new NativeTask().execute();

also you do not seem to use the string parameter in doInBackground as:

String inString= params[0];

Hope that helps,
JAL


问:
Why does pass by reference cause this to crash (C++)?
I'm experiencing some weird behavior and I'm not really sure where to turn.

Basically, I have a set of classes and one of them should be constructed with instances of the other two. I'm using pass by reference to assign the resources but the second assignment is crashing on my machine. I don't understand why the second assignment crashes but the first works fine. To make this a little more confusing, I tried recreating the problem in an online cpp compiler, but it seems to run fine in that environment.

I obscured the class names and removed a few methods that didn't seem relevant to this problem. Does anyone have any ideas?

```<code>#include <iostream>

using namespace std;

class Driver{};
class ITransmission{};
class ManualTransmission : public ITransmission {};

class Car
{
public:
    Car(ITransmission &trans, Driver &driver);

private:
    ITransmission *m_trans;
    Driver *m_driver;
};

Car::Car(ITransmission &trans, Driver &driver)
{
    *m_trans = trans;
    *m_driver = driver; // <-- **** Crashes here!?!? ****
}

int main()
{
    ITransmission *trans = new ManualTransmission();
    Driver *driver = new Driver();
    Car car(*trans, *driver);

    return 0;
}
</code>```

答:
*m_trans and *m_drivers are only pointers to their respective types. They are not the object themselves. In your copy constructor you are calling

```<code>*m_trans = trans
</code>```

which crashes because m_trans doesn't point to anything and you are dereferencing it.
What you want instead is,

```<code>m_trans = &trans
m_driver = &driver
</code>```

This sets the pointer to point at the address of the object you've passed in, whereas before you were trying to assign to the pointed-to object.

Body:
I'm experiencing some weird behavior and I'm not really sure where to turn.

Basically, I have a set of classes and one of them should be constructed with instances of the other two. I'm using pass by reference to assign the resources but the second assignment is crashing on my machine. I don't understand why the second assignment crashes but the first works fine. To make this a little more confusing, I tried recreating the problem in an online cpp compiler, but it seems to run fine in that environment.

I obscured the class names and removed a few methods that didn't seem relevant to this problem. Does anyone have any ideas?

#include <iostream>

using namespace std;

class Driver{};
class ITransmission{};
class ManualTransmission : public ITransmission {};

class Car
{
public:
    Car(ITransmission &trans, Driver &driver);

private:
    ITransmission *m_trans;
    Driver *m_driver;
};

Car::Car(ITransmission &trans, Driver &driver)
{
    *m_trans = trans;
    *m_driver = driver; // <-- **** Crashes here!?!? ****
}

int main()
{
    ITransmission *trans = new ManualTransmission();
    Driver *driver = new Driver();
    Car car(*trans, *driver);

    return 0;
}

Body:
*m_trans and *m_drivers are only pointers to their respective types. They are not the object themselves. In your copy constructor you are calling

*m_trans = trans

which crashes because m_trans doesn't point to anything and you are dereferencing it.
What you want instead is,

m_trans = &trans
m_driver = &driver

This sets the pointer to point at the address of the object you've passed in, whereas before you were trying to assign to the pointed-to object.


问:
"can't connect to any url" and "authentication not supported"
I have a Git repo and project on Eclipse. I am trying to share project on github. But i always get this error:

```<code> Can't connect to any URI:
 https://github.com/<username>/<repositoryname>.git
 (https://github.com/<username>/<repositoryname>.git: authentication
 not supported)
</code>```

I have tried the solutions of people who have encountered this problem but nothing has changed. In my opinion, my git password is not going and I can not write my password when I use the console. I am beginner. I want to understand why happened and how can i fix?

答: I resolved the issue by increasing the timeout.

Body:
I have a Git repo and project on Eclipse. I am trying to share project on github. But i always get this error:

 Can't connect to any URI:
 https://github.com/<username>/<repositoryname>.git
 (https://github.com/<username>/<repositoryname>.git: authentication
 not supported)

I have tried the solutions of people who have encountered this problem but nothing has changed. In my opinion, my git password is not going and I can not write my password when I use the console. I am beginner. I want to understand why happened and how can i fix?


问:
How to print every third character of a string? java
I am trying to print every 3rd character of a string so an example would be:
  123456 returns 36

But my code below returns 14

public String getEveryThird() {
    String newString = "";

    for (int i = 0; i < string.length(); i++) {

        if (i % 3 == 0) {
            newString += (string.charAt(i));
        }
    }

    return newString;
}
```

答:
Your current approach is off in the remainder (as already mentioned), however a much faster approach is available; instead of iterating every character, start with the third character and increase your index by three on each iteration. Remember, the third character is at index two (0, 1, 2). Also, it is better to use a StringBuilder over String concatenation (as Java String is immutable). Like,

```<code>StringBuilder sb = new StringBuilder();
for (int i = 2; i < string.length(); i += 3) {
    sb.append(string.charAt(i));
}
return sb.toString();
</code>```

Body:
Your current approach is off in the remainder (as already mentioned), however a much faster approach is available; instead of iterating every character, start with the third character and increase your index by three on each iteration. Remember, the third character is at index two (0, 1, 2). Also, it is better to use a StringBuilder over String concatenation (as Java String is immutable). Like,

StringBuilder sb = new StringBuilder();
for (int i = 2; i < string.length(); i += 3) {
    sb.append(string.charAt(i));
}
return sb.toString();


问:
Java's unsigned bitshift right (>>>) is signed shifting
I'm trying to bitshift right in order to isolate certain bits from a byte so I wanted an unsigned shift, the "new" bits should be zeros by my understanding. However, I've found that >>> has no difference to >> in my tests. -128 >> 4 = -8 as expected, but -128 >>> 4 should be 8 but I still get -8.

```<code>byte data = (byte)-128;
System.out.println((byte)(data >>> 4));
System.out.println((byte)(data >> 4));
</code>```

Thanks for the help.

答:
The unsigned right-shift operator is indeed doing an unsigned right-shift in this code; it's just hidden because of implicit cast from byte to int. Says the Java Language Specification (§15.19):

The operators << (left shift), >> (signed right shift), and >>> (unsigned right shift) are called the shift operators. The left-hand operand of a shift operator is the value to be shifted; the right-hand operand specifies the shift distance. [...] Unary numeric promotion (§5.6.1) is performed on each operand separately.

Unary numeric promotion means (§5.6.1):

[...] if the operand is of compile-time type byte, short, or char, it is promoted to a value of type int by a widening primitive conversion (§5.1.2).

So your code is evaluated as follows:

The byte value -128 which is the left operand of >>> is promoted to the int value -128, which is 0b11111111111111111111111110000000 in binary.

The unsigned right-shift is done on this int value, with the result 268435448 which in binary is 0b00001111111111111111111111111000. Note that the four left-most bits are zero, as you would expect from an unsigned right-shift.

This result is then explicitly casted to (byte), giving the result -8.

Using the REPL:

> byte b = -128;
> int shifted = b >>> 4;
> shifted
268435448
> (byte) shifted
-8
```

<p>For the behaviour you want, you can use <code>& 0xFF</code> to do an "unsigned" conversion from <code>byte</code> to <code>int</code>:</p>

<pre class="lang-java prettyprint-override"><code>> ((b & 0xFF) >>> 4)
8
</code>```

Body:
I'm trying to bitshift right in order to isolate certain bits from a byte so I wanted an unsigned shift, the "new" bits should be zeros by my understanding. However, I've found that >>> has no difference to >> in my tests. -128 >> 4 = -8 as expected, but -128 >>> 4 should be 8 but I still get -8.

byte data = (byte)-128;
System.out.println((byte)(data >>> 4));
System.out.println((byte)(data >> 4));

Thanks for the help.

Body:
The unsigned right-shift operator is indeed doing an unsigned right-shift in this code; it's just hidden because of implicit cast from byte to int. Says the Java Language Specification (§15.19):

The operators << (left shift), >> (signed right shift), and >>> (unsigned right shift) are called the shift operators. The left-hand operand of a shift operator is the value to be shifted; the right-hand operand specifies the shift distance. [...] Unary numeric promotion (§5.6.1) is performed on each operand separately.

Unary numeric promotion means (§5.6.1):

[...] if the operand is of compile-time type byte, short, or char, it is promoted to a value of type int by a widening primitive conversion (§5.1.2).

So your code is evaluated as follows:

The byte value -128 which is the left operand of >>> is promoted to the int value -128, which is 0b11111111111111111111111110000000 in binary.

The unsigned right-shift is done on this int value, with the result 268435448 which in binary is 0b00001111111111111111111111111000. Note that the four left-most bits are zero, as you would expect from an unsigned right-shift.

This result is then explicitly casted to (byte), giving the result -8.

Using the REPL:

> byte b = -128;
> int shifted = b >>> 4;
> shifted
268435448
> (byte) shifted
-8

For the behaviour you want, you can use & 0xFF to do an "unsigned" conversion from byte to int:

> ((b & 0xFF) >>> 4)
8


问:
What is the best way to maintain previous versions of an API in Azure?
My goal is to have previous versions be immutable: they should not change in definition and function.
The API is build with ASP.NET Core based on .NET 4.7.2(cause of dependencies) and hosted as Azure App Service.

Preferably, I don't want to clutter my code by adding "version knowledge" to it. Also if the versions can be hosted under the same base URL that would be nice too.

My research:

ASP.NET API Versioning

With this you have full control over versioning inside your application. But when a new version is released, all older versions are also updated and thus can change. This means you cannot mutate any existing function but have to create new versions, like Scott does in URL PATH SEGMENT VERSIONING.

Azure Deploymentslots

As the documentation explains, this should be used for staging. However this could also be used to 'store' your versions, since every deploymentslot is hosted without any relation to each other.

Virtual Applications

Hosting versions as virtual applications is also an option. However all settings of the App Service are shared between these virtual applications. Which means when changing any setting this will impact every version.

Azure Web App for Containers

My knowledge of this is limited, but from what I have read this is also an option. Creating images based on versions of your application, uploading these to an Azure Container Registery. Then create an App Service for each version using these images.

答:
@SamaraSoucy-MSFT is correct - all of the options are valid. The best way is highly subjective, but I will elaborate further on the specific options for API Versioning.

API Versioning is orthogonal to your infrastructure. If you want to split things up into separate applications or add other levels of isolation, that is a supported scenario. The notion of Version Advertisement describes this in some detail. In short, it is possible for your application to advertise API versions that are not hosted in that particular implementation. There are many ways that version advertisement can be achieved, so there is no specific guidance on how to do that. In the simplest model, you'd simply update your application with new conventions, attributes, etc. However, there is very likely a desire to make no change whatsoever to existing deployments. This means that you need to come up with a way to update this information outside the app (ex: config, db, etc) or forego version advertisement. This partially depends on how isolated each implementation. If you don't care about advertising available or deprecated API versions, then this is a non-issue.

There are at least 4 ways you can achieve your goals using API Versioning.

Option 1 - Copy, Paste, Replace

The Copy, Paste, Replace (CPR) method involves literally copying and pasting the previous version of a service into a new folder and new code namespace. This forms the baseline of a new version from the previous version without changing the original. The differences in the new version are then replaced as necessary. This process can repeat for as long as you want.

If your changes are fairly minimal between versions, this can be a very simple and effective strategy. A key drawback is bloat and implementation coupling over time. If you have a solid versioning policy (e.g. N-2), then that can minimize the impact. The biggest challenge would making significant implementation changes, which do not make sense to co-host or could result in changing previous versions. Such an example would be trying to host 1.0 with ASP.NET Web API and 2.0 in ASP.NET Core in the same implementation.

I have seen this approach used a few times and it can be effective.

Option 2 - Inject and Compose

In this variant, you would implement each version in a separate assembly of APIs. You would have an API host application which injects and composes all APIs from each versioned assembly. This provides complete isolation between implementations, which still having all the benefits of API Versioning.

Like Option 1, you still have to consider bloat; especially since each assembly likely has different dependencies. It would also be quite difficult to host APIs authored for different platforms, but it should be technically feasible.

Option 3 - Host Header Mapping

Most web servers have some way of mapping the Host header to different applications. You can use this technique to host each version of the application as an independent application.

Option 4 - Gateway

Using a gateway provides the most flexibility, but can be the most challenging to setup. This method can use any number of routing methods such as DNS, URL rewriting, or URL redirection based on available version information in a request. The endpoint is then likely an isolated application such as in Option 3. The gateway is responsible for forwarding or redirecting a request to the correct version endpoint.

I use the term gateway loosely. This could an existing service or platform, hardware-based, or of your own custom design. It will depend on your needs and whether an out-of-the-box solution can satisfy them.

Additional Considerations

These certainly aren't the only options nor are they mutually exclusive. You could combine any variation of them to suit your needs.

Choosing Option 3 or Option 4 will come with some challenges for API Versioning since the physical isolation barriers transcend each deployed application. You'll either need to come up with a way to update advertised versions or discard the notion entirely - as mentioned above. If you end up not advertising versions at all, then each deployed implementation should be a single, independent codebase that likely negates the need for API Versioning at all since it's handled at a abstraction layer.

Your overall versioning strategy and policy will also play a factor. If you use symmetrical verisioning across your services, the URL design and API versions are consistent across the board, but come with added deployments to satisfy this requirement. If you choose to have independent, evolving services, then version discovery and advertisement becomes more interesting. For example, your policy might state that a deprecated version will be sunset after 6 months. Clients should then detect this advertisement by away of instrumenting the api-deprecated-versions response header. Version discovery can be supported by way of the HEAD and/or OPTIONS method.


问:
How can I stop webpack from polluting my folders with .js and .js.map files?
I recently setup webpack for an app I write.

This is my config:

```<code>var path = require("path");
const statements = require('tsx-control-statements').default;

const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');

module.exports = {
    mode: "development",
    entry: {
        bundle: "./React/index.ts",
        logonBundle: "./React/logonIndex.ts",
        otherBundle: "./React/otherEntryPoint.ts",
    },
    output: {
        filename: "[name].js",
        path: path.resolve(__dirname, "wwwroot/dist/")
    },
    devtool: "eval-source-map",
    module: {
        rules: [
            {
                test: /\.less/,
                use: [
                    "style-loader",
                    "css-loader",
                    "less-loader",
                ],
            },
            {
                test: /\.tsx?$/,
                loader: "awesome-typescript-loader",
                exclude: /node_modules/,
                options: {
                    getCustomTransformers: () => ({ before: [statements()] })
                }
            }
        ]
    },
    resolve: {
        extensions: [".tsx", ".ts", ".js", ".jsx"],
        plugins: [new TsconfigPathsPlugin({configFile: "./tsconfig.json"})],
        modules: ["node_modules"]
    },
};
</code>```

This works perfectly fine, but what I don't like is how webpack pollutes my folders with the transpiled files.

For every .ts and .tsx file, I have the following output now:

How can I get rid of this? Or, better said, where did I go wrong with my config? I'm sure it has to do with the sourcemap, but I can't figure out how to get around it.

EDIT: What's quite interesting... This only happens when I build from Visual Studio. It doesn't happen when building directly via CLI.

答:
The problem was not webpack, but Visual Studio.

Turns out, my VS did some build on its own as well. I added

```<code><PropertyGroup>
    <TypeScriptToolsVersion>Latest</TypeScriptToolsVersion>
</PropertyGroup>
</code>```

to my csproj and now it doesn't pollute my folders anymore.

Body:
I recently setup webpack for an app I write.

This is my config:

var path = require("path");
const statements = require('tsx-control-statements').default;

const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');

module.exports = {
    mode: "development",
    entry: {
        bundle: "./React/index.ts",
        logonBundle: "./React/logonIndex.ts",
        otherBundle: "./React/otherEntryPoint.ts",
    },
    output: {
        filename: "[name].js",
        path: path.resolve(__dirname, "wwwroot/dist/")
    },
    devtool: "eval-source-map",
    module: {
        rules: [
            {
                test: /\.less/,
                use: [
                    "style-loader",
                    "css-loader",
                    "less-loader",
                ],
            },
            {
                test: /\.tsx?$/,
                loader: "awesome-typescript-loader",
                exclude: /node_modules/,
                options: {
                    getCustomTransformers: () => ({ before: [statements()] })
                }
            }
        ]
    },
    resolve: {
        extensions: [".tsx", ".ts", ".js", ".jsx"],
        plugins: [new TsconfigPathsPlugin({configFile: "./tsconfig.json"})],
        modules: ["node_modules"]
    },
};

This works perfectly fine, but what I don't like is how webpack pollutes my folders with the transpiled files.

For every .ts and .tsx file, I have the following output now:

How can I get rid of this? Or, better said, where did I go wrong with my config? I'm sure it has to do with the sourcemap, but I can't figure out how to get around it.

EDIT: What's quite interesting... This only happens when I build from Visual Studio. It doesn't happen when building directly via CLI.

Body:
The problem was not webpack, but Visual Studio.

Turns out, my VS did some build on its own as well. I added

<PropertyGroup>
    <TypeScriptToolsVersion>Latest</TypeScriptToolsVersion>
</PropertyGroup>

to my csproj and now it doesn't pollute my folders anymore.


问:
Use multiple JWT Bearer Authentication
Is it possible to support multiple JWT Token issuers in ASP.NET Core 2?
I want to provide an API for external service and I need to use two sources of JWT tokens - Firebase and custom JWT token issuers. In ASP.NET core I can set the JWT authentication for Bearer auth scheme, but only for one Authority:

```<code>  services
        .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.Authority = "https://securetoken.google.com/my-firebase-project"
            options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidIssuer = "my-firebase-project"
                    ValidateAudience = true,
                    ValidAudience = "my-firebase-project"
                    ValidateLifetime = true
                };
        }
</code>```

I can have multiple issuers and audiences, but I can't set several Authorities.

答:
This is an extension of Mickaël Derriey's answer.

Our app has a custom authorization requirement that we resolve from an internal source.  We were using Auth0 but are switching to Microsoft Account authentication using OpenID.  Here is the slightly edited code from our ASP.Net Core 2.1 Startup.  For future readers, this works as of this writing for the versions specified.  The caller uses the id_token from OpenID on incoming requests passed as a Bearer token.  Hope it helps someone else trying to do an identity authority conversion as much as this question and answer helped me.

```<code>const string Auth0 = nameof(Auth0);
const string MsaOpenId = nameof(MsaOpenId);

string domain = "https://myAuth0App.auth0.com/";
services.AddAuthentication()
        .AddJwtBearer(Auth0, options =>
            {
                options.Authority = domain;
                options.Audience = "https://myAuth0Audience.com";
            })
        .AddJwtBearer(MsaOpenId, options =>
            {
                options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidateAudience = true,
                    ValidAudience = "00000000-0000-0000-0000-000000000000",

                    ValidateIssuer = true,
                    ValidIssuer = "https://login.microsoftonline.com/9188040d-6c67-4c5b-b112-36a304b66dad/v2.0",

                    ValidateIssuerSigningKey = true,
                    RequireExpirationTime = true,
                    ValidateLifetime = true,
                    RequireSignedTokens = true,
                    ClockSkew = TimeSpan.FromMinutes(10),
                };
                options.MetadataAddress = "https://login.microsoftonline.com/9188040d-6c67-4c5b-b112-36a304b66dad/v2.0/.well-known/openid-configuration";
            }
        );

services.AddAuthorization(options =>
{
    options.DefaultPolicy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .AddAuthenticationSchemes( Auth0, MsaOpenId )
        .Build();

    var approvedPolicyBuilder =  new AuthorizationPolicyBuilder()
           .RequireAuthenticatedUser()
           .AddAuthenticationSchemes(Auth0, MsaOpenId)
           ;

    approvedPolicyBuilder.Requirements.Add(new HasApprovedRequirement(domain));

    options.AddPolicy("approved", approvedPolicyBuilder.Build());
});
</code>```

Title: Use multiple JWT Bearer Authentication

Body:
Is it possible to support multiple JWT Token issuers in ASP.NET Core 2?
I want to provide an API for external service and I need to use two sources of JWT tokens - Firebase and custom JWT token issuers. In ASP.NET core I can set the JWT authentication for Bearer auth scheme, but only for one Authority:

  services
        .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.Authority = "https://securetoken.google.com/my-firebase-project"
            options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidIssuer = "my-firebase-project"
                    ValidateAudience = true,
                    ValidAudience = "my-firebase-project"
                    ValidateLifetime = true
                };
        }

I can have multiple issuers and audiences, but I can't set several Authorities.

Body:
This is an extension of Mickaël Derriey's answer.

Our app has a custom authorization requirement that we resolve from an internal source.  We were using Auth0 but are switching to Microsoft Account authentication using OpenID.  Here is the slightly edited code from our ASP.Net Core 2.1 Startup.  For future readers, this works as of this writing for the versions specified.  The caller uses the id_token from OpenID on incoming requests passed as a Bearer token.  Hope it helps someone else trying to do an identity authority conversion as much as this question and answer helped me.

const string Auth0 = nameof(Auth0);
const string MsaOpenId = nameof(MsaOpenId);

string domain = "https://myAuth0App.auth0.com/";
services.AddAuthentication()
        .AddJwtBearer(Auth0, options =>
            {
                options.Authority = domain;
                options.Audience = "https://myAuth0Audience.com";
            })
        .AddJwtBearer(MsaOpenId, options =>
            {
                options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidateAudience = true,
                    ValidAudience = "00000000-0000-0000-0000-000000000000",

                    ValidateIssuer = true,
                    ValidIssuer = "https://login.microsoftonline.com/9188040d-6c67-4c5b-b112-36a304b66dad/v2.0",

                    ValidateIssuerSigningKey = true,
                    RequireExpirationTime = true,
                    ValidateLifetime = true,
                    RequireSignedTokens = true,
                    ClockSkew = TimeSpan.FromMinutes(10),
                };
                options.MetadataAddress = "https://login.microsoftonline.com/9188040d-6c67-4c5b-b112-36a304b66dad/v2.0/.well-known/openid-configuration";
            }
        );

services.AddAuthorization(options =>
{
    options.DefaultPolicy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .AddAuthenticationSchemes( Auth0, MsaOpenId )
        .Build();

    var approvedPolicyBuilder =  new AuthorizationPolicyBuilder()
           .RequireAuthenticatedUser()
           .AddAuthenticationSchemes(Auth0, MsaOpenId)
           ;

    approvedPolicyBuilder.Requirements.Add(new HasApprovedRequirement(domain));

    options.AddPolicy("approved", approvedPolicyBuilder.Build());
});


问:
Is necessary to use a RMI Server in Esper 8 in order to Runtime deploy Esper Workflows
I'm trying to make an Esper application thats permits me to Runtime deploy dataflow based patterns. In order to implement this, I used a RMI based server for sending patterns, but thinking on that, it may be not necessary. There is a way embedded in the engine to implement my approach?

Thanks you in advance

答: You can embed Esper compiler and runtime any way you want. There are no requirements by Esper on anything. Therefore whether you use RMI or something else is all up to you. </p>