问:
Convert an array which contains strings into key value pairs
I have a string "101-2000-10-102-2000-15" which I have to map as key: 101 values: {2000, 10}.
With the below code I am able to get the output as 101 => 2000 but I am unable to the one remaining value.
This is the Code:

```<code>let myString = "101-2000-10-102-2000-15"
let strArray = myString.match(/[^-]+-[^-]+-[^-]+/g);
console.log(strArray);
let compartmentMap = new Map(strArray.map(x => x.split("-")));
console.log(compartmentMap);
</code>```

My input: "101-2000-10-102-2000-15"
Desired Output: {101 => {2000,10}, 102 => {2000,15}}

答:
You need to get an array of values as well.

let myString = "101-2000-10-102-2000-15"
let strArray = myString.match(/[^-]+-[^-]+-[^-]+/g);
console.log(strArray);
let compartmentMap = new Map(strArray.map(x => {
    const [k, ...v] = x.split("-");
    return [k, v];
}));

console.log(Array.from(compartmentMap));```

Body:
I have a string "101-2000-10-102-2000-15" which I have to map as key: 101 values: {2000, 10}.
With the below code I am able to get the output as 101 => 2000 but I am unable to the one remaining value.
This is the Code:

let myString = "101-2000-10-102-2000-15"
let strArray = myString.match(/[^-]+-[^-]+-[^-]+/g);
console.log(strArray);
let compartmentMap = new Map(strArray.map(x => x.split("-")));
console.log(compartmentMap);

My input: "101-2000-10-102-2000-15"
Desired Output: {101 => {2000,10}, 102 => {2000,15}}


来源: stackexchange

问:
How to get http stream from wifi camera compressed format: h.264 on python?
Hy! I am working on a project for school using a HD-eyewear Wifi Camera that uses H.264 compressed format. I have read a lot of documentation about how to get the frames from the camera, but I shouldn't manage my problem. My code looks like this:

```<code>import cv2

while True:
    cap = cv2.VideoCapture('http://admin:@192.168.10.1/videostream.asf?user=admin&pwd=')
    ret, frame = cap.read()
    print(frame)
</code>```

I only want to see that it gets correctly the frames, but it drops errors like this:

```<code>[h264 @ 0x1e0a100] non-existing PPS 0 referenced

[h264 @ 0x1e0a100] non-existing PPS 0 referenced

[h264 @ 0x1e0a100] decode_slice_header error

[h264 @ 0x1e0a100] no frame!
</code>```

I really apreciate the help! Thanks! :D

答:
With a little help from comments, I could solve my problem, and works, with some initial frame loss.

```<code>import cv2
from threading import Thread
import time

url = ('http://admin:@192.168.10.1/videostream.asf?user=admin&pwd=')

class VideoStream(object):
    def __init__(self,url = ('http://admin:@192.168.10.1/videostream.asf?user=admin&pwd=')):
            self.capture = cv2.VideoCapture(url)
            self.thread = Thread(target=self.update, args=())
            self.thread.daemon = True
            self.thread.start()

    def update(self):
            while True:
                    if self.capture.isOpened():
                            (self.status, self.frame) = self.capture.read()
                    time.sleep(.01)

    def show_frame(self):
            cv2.imshow('frame', self.frame)
            key = cv2.waitKey(1)
            if key == ord('q'):
                    self.capture.release()
                    cv2.destroyAllWindows()
                    exit(1)

if __name__ == '__main__':
    video_stream = VideoStream()
    while True:
            try:
                    video_stream.show_frame()
            except AttributeError:
                    pass
</code>```

Copied from this link: Video Streaming from IP Camera in Python Using OpenCV cv2.VideoCapture

ContentLicense: CC BY-SA 4.0

Body:
Hy! I am working on a project for school using a HD-eyewear Wifi Camera that uses H.264 compressed format. I have read a lot of documentation about how to get the frames from the camera, but I shouldn't manage my problem. My code looks like this:

import cv2

while True:
    cap = cv2.VideoCapture('http://admin:@192.168.10.1/videostream.asf?user=admin&pwd=')
    ret, frame = cap.read()
    print(frame)

I only want to see that it gets correctly the frames, but it drops errors like this:

[h264 @ 0x1e0a100] non-existing PPS 0 referenced

[h264 @ 0x1e0a100] non-existing PPS 0 referenced

[h264 @ 0x1e0a100] decode_slice_header error

[h264 @ 0x1e0a100] no frame!

I really apreciate the help! Thanks! :D

Body:
With a little help from comments, I could solve my problem, and works, with some initial frame loss.

import cv2
from threading import Thread
import time

url = ('http://admin:@192.168.10.1/videostream.asf?user=admin&pwd=')

class VideoStream(object):
    def __init__(self,url = ('http://admin:@192.168.10.1/videostream.asf?user=admin&pwd=')):
            self.capture = cv2.VideoCapture(url)
            self.thread = Thread(target=self.update, args=())
            self.thread.daemon = True
            self.thread.start()

    def update(self):
            while True:
                    if self.capture.isOpened():
                            (self.status, self.frame) = self.capture.read()
                    time.sleep(.01)

    def show_frame(self):
            cv2.imshow('frame', self.frame)
            key = cv2.waitKey(1)
            if key == ord('q'):
                    self.capture.release()
                    cv2.destroyAllWindows()
                    exit(1)

if __name__ == '__main__':
    video_stream = VideoStream()
    while True:
            try:
                    video_stream.show_frame()
            except AttributeError:
                    pass

Copied from this link: Video Streaming from IP Camera in Python Using OpenCV cv2.VideoCapture


问:
Targeting IE 11 in css not working
I'm trying to fix a tiny layout issue in IE11 where slider pip jumps out of its place (it's fine in the rest of major browsers)

I've added media query to stylesheet (below) but no luck. I've also tried conditional code, various hacks etc. But nothing worked or affected all browsers. I've spent a couple of hours trying various solutions without any luck and ran out of ideas. Need help please. Layout issue illustrated

  @media screen and (-ms-high-contrast: active),
  (-ms-high-contrast: none) {
    #yardstick-text-6-1 {
      margin-top: -43px;
    }
    #yardstick6-1 {
      margin-top: -53px;
    }
  }
```

The web page can be seen here with password:quote321

答:
The following should solve your problem. The idea is to apply CSS specific to IE. </p>

```<code>@media all and (-ms-high-contrast:active), all and (-ms-high-contrast:none) {
 //Your CSS
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Targeting IE 11 in css not working

Body:
I'm trying to fix a tiny layout issue in IE11 where slider pip jumps out of its place (it's fine in the rest of major browsers)

I've added media query to stylesheet (below) but no luck. I've also tried conditional code, various hacks etc. But nothing worked or affected all browsers. I've spent a couple of hours trying various solutions without any luck and ran out of ideas. Need help please. Layout issue illustrated

  @media screen and (-ms-high-contrast: active),
  (-ms-high-contrast: none) {
    #yardstick-text-6-1 {
      margin-top: -43px;
    }
    #yardstick6-1 {
      margin-top: -53px;
    }
  }

The web page can be seen here with password:quote321

Body:
The following should solve your problem. The idea is to apply CSS specific to IE.

@media all and (-ms-high-contrast:active), all and (-ms-high-contrast:none) {
 //Your CSS
}


问:
Creating a custom android UI
does anyone know how I would get started creating a custom android UI?
it wouldn't be an app. Once you install it, it would change the appearance of your UI until you uninstall it.

I've done some research but it doesn't seem to be possible/available yet??

If anyone could help or link me to a site on how to to get started that'd be awesome, thx!

I program using eclipse, btw.

This is basically what i want to do, but i want to design it myself http://www.intomobile.com/2011/02/09/sentio-ui-android-home-replacement-app/
How would I get started?

答:
I did not understand your question about what you really want. So i am trying to provide every possible solution.

If you are talking about Home Replacements.

Here is an example by Google :-

Android Home Replacement Sample

and if you are not talking about Home Replacement and you found android layout designing a bit hard then you can use DroidDraw. Just Google DroidDraw, download it and install it on your PC/MAC. It gives you the features like drag and drop widgets, set their property visually and lots more. You can generate the android layout without writing a single line of xml code using droid draw.

Title: Creating a custom android UI


问:
Preventing JHipster import-jdl from overwriting changes when updating entities
With my current workflow I have to check in git and manually read changes like added functions after every import-jdl that touches an entitiy I changed.

Is there a way to add functions to the classes JHipster creates without actually changing the files? Like code generation with anotations or extending JHipster created clasees? I feel like I am missing some important documentation from JHipster, I would be grateful for pointers in the right direction.

Thanks!

答:
I faced this problem in one of my projects and I'm afraid there is no easy way to tell JHipster not to overwrite your changes.

The good news is you have two ways of mitigating this and both will make your life much easier.

Update your entities in a separate branch

The idea is to update your entities (execute the import-jdl command) in a different branch and then, once the whole process is finished merge the changes back to master.

This requires no extra changes to your code. The problem I had with this approach is that sometimes the merges were not trivial and I still had to go through a lot of code just to be sure that everything was still in place and working properly.

Do not change the generated code

This is known as the side-by-side practice. The general idea is that you never change the generated code directly, instead you put your custom code in new files and extend the original ones whenever possible.

This way you can update your entities and JHipster will never remove or modify your custom code.

There are two videos available that will teach you (with examples) how to manage this:

Custom and Generated Code Side by Side by Antonio Goncalves

JHipster side-by-side in practice by David Steiman

In my opinion this is the best approach.

I know this probably isn't the answer you were looking for, but to my knowledge there's no better way.


问:
React Native, UI Kitten Input custom style on default and onFocus states
I need some help about creating a custom input style on default and onFocus states.

```<code>import React, {useState} from 'react';
import {
  StyleSheet,
  View,
} from 'react-native';
import {
  Input,
  Layout,
} from '@ui-kitten/components';

export const CustomInputExample = () => {
  const [ focusStatus, setFocusStatus ] = useState(false)

  const onMouseEnter = () => {
     setFocusStatus(true)
  }

  const onMouseLeave = () => {
     setFocusStatus(false)
  }

  return (
    <Layout>
      <Input
        style={focusStatus ? styles.customStyle : styles.basicStyle}
        status={focusStatus ? 'success' : 'basic'}
        placeholder='Success'
        onMouseEnter={onMouseEnter}
        onMouseLeave={onMouseLeave}
      />
    </Layout>
  );
};

const styles = StyleSheet.create({
  basicStyle: {
    borderColor: grey,
  },
  customStyle: {
    borderColor: '#3CB46E'
  },
});

</code>```

But, none of the methods are working in my case. I've tried other InputProps like focus, onTextFieldFocus, onTextFieldBlur...May be I do not know how to use them.

Also this is the error from ts =>

Property 'onMouseEnter' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes> & Readonly<...> & Readonly<...>'.ts(2322)

Any help can be grateful.

答: You don't need to implement these interfaces in case you follow Branding guide. You can change primary colors everywhere so your app will follow a single source of truth about styling.</p>

Body:
I need some help about creating a custom input style on default and onFocus states.

import React, {useState} from 'react';
import {
  StyleSheet,
  View,
} from 'react-native';
import {
  Input,
  Layout,
} from '@ui-kitten/components';

export const CustomInputExample = () => {
  const [ focusStatus, setFocusStatus ] = useState(false)

  const onMouseEnter = () => {
     setFocusStatus(true)
  }

  const onMouseLeave = () => {
     setFocusStatus(false)
  }

  return (
    <Layout>
      <Input
        style={focusStatus ? styles.customStyle : styles.basicStyle}
        status={focusStatus ? 'success' : 'basic'}
        placeholder='Success'
        onMouseEnter={onMouseEnter}
        onMouseLeave={onMouseLeave}
      />
    </Layout>
  );
};

const styles = StyleSheet.create({
  basicStyle: {
    borderColor: grey,
  },
  customStyle: {
    borderColor: '#3CB46E'
  },
});

But, none of the methods are working in my case. I've tried other InputProps like focus, onTextFieldFocus, onTextFieldBlur...May be I do not know how to use them.

Also this is the error from ts =>

Property 'onMouseEnter' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes> & Readonly<...> & Readonly<...>'.ts(2322)

Any help can be grateful.


答:
According to @cangrejo's answer: https://stats.stackexchange.com/a/310956/194535, suppose the original output probability of your model is the vector v, and then you can define the prior distribution:

π=(1/θ1, 1/θ2,..., 1/θN), for θi∈(0,1) and Σθi = 1, where N is the total number of labeled classes, i is the class index.

Take v' = v⊙π as the new output probability of your model, where ⊙ denotes an element-wise product.

Now, your question can be reformulate to this: Finding the π which optimize the metrics you have specified (eg. roc_auc_score) from the new output probability model. Once you find it, the θs (θ1, θ2, ..., θN) is your optimal threshold for each classes.

The Code part:

Create a proxyModel class which takes your original model object as an argument and return a proxyModel object. When you called predict_proba() through the proxyModel object, it will calculate new probability automatically based on the threshold you specified:

```<code>class proxyModel():
    def __init__(self, origin_model):
        self.origin_model = origin_model

    def predict_proba(self, x, threshold_list=None):
        # get origin probability
        ori_proba = self.origin_model.predict_proba(x)

        # set default threshold
        if threshold_list is None:
            threshold_list = np.full(ori_proba[0].shape, 1)

        # get the output shape of threshold_list
        output_shape = np.array(threshold_list).shape

        # element-wise divide by the threshold of each classes
        new_proba = np.divide(ori_proba, threshold_list)

        # calculate the norm (sum of new probability of each classes)
        norm = np.linalg.norm(new_proba, ord=1, axis=1)

        # reshape the norm
        norm = np.broadcast_to(np.array([norm]).T, (norm.shape[0],output_shape[0]))

        # renormalize the new probability
        new_proba = np.divide(new_proba, norm)

        return new_proba

    def predict(self, x, threshold_list=None):
        return np.argmax(self.predict_proba(x, threshold_list), axis=1)
</code>```

Implement a score function:

```<code>def scoreFunc(model, X, y_true, threshold_list):
    y_pred = model.predict(X, threshold_list=threshold_list)
    y_pred_proba = model.predict_proba(X, threshold_list=threshold_list)

    ###### metrics ######
    from sklearn.metrics import accuracy_score
    from sklearn.metrics import roc_auc_score
    from sklearn.metrics import average_precision_score
    from sklearn.metrics import f1_score

    accuracy = accuracy_score(y_true, y_pred)
    roc_auc = roc_auc_score(y_true, y_pred_proba, average='macro')
    pr_auc = average_precision_score(y_true, y_pred_proba, average='macro')
    f1_value = f1_score(y_true, y_pred, average='macro')

    return accuracy, roc_auc, pr_auc, f1_value

</code>```

Define weighted_score_with_threshold() function, which takes the threshold as input and return weighted score:

```<code>def weighted_score_with_threshold(threshold, model, X_test, Y_test, metrics='accuracy', delta=5e-5):
    # if the sum of thresholds were not between 1+delta and 1-delta,
    # return infinity (just for reduce the search space of the minimizaiton algorithm,
    # because the sum of thresholds should be as close to 1 as possible).
    threshold_sum = np.sum(threshold)

    if threshold_sum > 1+delta:
        return np.inf

    if threshold_sum < 1-delta:
        return np.inf

    # to avoid objective function jump into nan solution
    if np.isnan(threshold_sum):
        print("threshold_sum is nan")
        return np.inf

    # renormalize: the sum of threshold should be 1
    normalized_threshold = threshold/threshold_sum

    # calculate scores based on thresholds
    # suppose it'll return 4 scores in a tuple: (accuracy, roc_auc, pr_auc, f1)
    scores = scoreFunc(model, X_test, Y_test, threshold_list=normalized_threshold)

    scores = np.array(scores)
    weight = np.array([1,1,1,1])

    # Give the metric you want to maximize a bigger weight:
    if metrics == 'accuracy':
        weight = np.array([10,1,1,1])
    elif metrics == 'roc_auc':
        weight = np.array([1,10,1,1])
    elif metrics == 'pr_auc':
        weight = np.array([1,1,10,1])
    elif metrics == 'f1':
        weight = np.array([1,1,1,10])
    elif 'all':
        weight = np.array([1,1,1,1])

    # return negatitive weighted sum (because you want to maximize the sum,
    # it's equivalent to minimize the negative sum)
    return -np.dot(weight, scores)
</code>```

Use optimize algorithm differential_evolution() (better then fmin) to find the optimal threshold:

```<code>from scipy import optimize

output_class_num = Y_test.shape[1]
bounds = optimize.Bounds([1e-5]*output_class_num,[1]*output_class_num)

pmodel = proxyModel(model)

result = optimize.differential_evolution(weighted_score_with_threshold, bounds, args=(pmodel, X_test, Y_test, 'accuracy'))

# calculate threshold
threshold = result.x/np.sum(result.x)

# print the optimized score
print(scoreFunc(model, X_test, Y_test, threshold_list=threshold))

</code>```

Title: How to choose optimal threshold for class probabilities?

Body:
My output of neural network is table of predicted class probabilities for multi-label classification:

print(probabilities)

|   |      1       |      3       | ... |     8354     |     8356     |     8357     |
|---|--------------|--------------|-----|--------------|--------------|--------------|
| 0 | 2.442745e-05 | 5.952136e-06 | ... | 4.254002e-06 | 1.894523e-05 | 1.033957e-05 |
| 1 | 7.685694e-05 | 3.252202e-06 | ... | 3.617730e-06 | 1.613792e-05 | 7.356643e-06 |
| 2 | 2.296657e-06 | 4.859554e-06 | ... | 9.934525e-06 | 9.244772e-06 | 1.377618e-05 |
| 3 | 5.163169e-04 | 1.044035e-04 | ... | 1.435158e-04 | 2.807420e-04 | 2.346930e-04 |
| 4 | 2.484626e-06 | 2.074290e-06 | ... | 9.958628e-06 | 6.002510e-06 | 8.434519e-06 |
| 5 | 1.297477e-03 | 2.211737e-04 | ... | 1.881772e-04 | 3.171079e-04 | 3.228884e-04 |

I converted it to class labels using a threshold (0.2) for measuring accuraccy of my prediction:

predictions = (probabilities > 0.2).astype(np.int)
print(predictions)

|   | 1 | 3 | ... | 8354 | 8356 | 8357 |
|---|---|---|-----|------|------|------|
| 0 | 0 | 0 | ... |    0 |    0 |    0 |
| 1 | 0 | 0 | ... |    0 |    0 |    0 |
| 2 | 0 | 0 | ... |    0 |    0 |    0 |
| 3 | 0 | 0 | ... |    0 |    0 |    0 |
| 4 | 0 | 0 | ... |    0 |    0 |    0 |
| 5 | 0 | 0 | ... |    0 |    0 |    0 |

Also I have a test set:

print(Y_test)

|   | 1 | 3 | ... | 8354 | 8356 | 8357 |
|---|---|---|-----|------|------|------|
| 0 | 0 | 0 | ... |    0 |    0 |    0 |
| 1 | 0 | 0 | ... |    0 |    0 |    0 |
| 2 | 0 | 0 | ... |    0 |    0 |    0 |
| 3 | 0 | 0 | ... |    0 |    0 |    0 |
| 4 | 0 | 0 | ... |    0 |    0 |    0 |
| 5 | 0 | 0 | ... |    0 |    0 |    0 |

Question: How to build an algorithm in Python that will choose the optimal threshold that maximize roc_auc_score(average = 'micro') or another metrics?

Maybe it is possible to build manual function in Python that optimize threshold, depending on the accuracy metric.

Body:
According to @cangrejo's answer: https://stats.stackexchange.com/a/310956/194535, suppose the original output probability of your model is the vector v, and then you can define the prior distribution:

π=(1/θ1, 1/θ2,..., 1/θN), for θi∈(0,1) and Σθi = 1, where N is the total number of labeled classes, i is the class index.

Take v' = v⊙π as the new output probability of your model, where ⊙ denotes an element-wise product.

Now, your question can be reformulate to this: Finding the π which optimize the metrics you have specified (eg. roc_auc_score) from the new output probability model. Once you find it, the θs (θ1, θ2, ..., θN) is your optimal threshold for each classes.

The Code part:

Create a proxyModel class which takes your original model object as an argument and return a proxyModel object. When you called predict_proba() through the proxyModel object, it will calculate new probability automatically based on the threshold you specified:

class proxyModel():
    def __init__(self, origin_model):
        self.origin_model = origin_model

    def predict_proba(self, x, threshold_list=None):
        # get origin probability
        ori_proba = self.origin_model.predict_proba(x)

        # set default threshold
        if threshold_list is None:
            threshold_list = np.full(ori_proba[0].shape, 1)

        # get the output shape of threshold_list
        output_shape = np.array(threshold_list).shape

        # element-wise divide by the threshold of each classes
        new_proba = np.divide(ori_proba, threshold_list)

        # calculate the norm (sum of new probability of each classes)
        norm = np.linalg.norm(new_proba, ord=1, axis=1)

        # reshape the norm
        norm = np.broadcast_to(np.array([norm]).T, (norm.shape[0],output_shape[0]))

        # renormalize the new probability
        new_proba = np.divide(new_proba, norm)

        return new_proba

    def predict(self, x, threshold_list=None):
        return np.argmax(self.predict_proba(x, threshold_list), axis=1)

Implement a score function:

def scoreFunc(model, X, y_true, threshold_list):
    y_pred = model.predict(X, threshold_list=threshold_list)
    y_pred_proba = model.predict_proba(X, threshold_list=threshold_list)

    ###### metrics ######
    from sklearn.metrics import accuracy_score
    from sklearn.metrics import roc_auc_score
    from sklearn.metrics import average_precision_score
    from sklearn.metrics import f1_score

    accuracy = accuracy_score(y_true, y_pred)
    roc_auc = roc_auc_score(y_true, y_pred_proba, average='macro')
    pr_auc = average_precision_score(y_true, y_pred_proba, average='macro')
    f1_value = f1_score(y_true, y_pred, average='macro')

    return accuracy, roc_auc, pr_auc, f1_value

Define weighted_score_with_threshold() function, which takes the threshold as input and return weighted score:

def weighted_score_with_threshold(threshold, model, X_test, Y_test, metrics='accuracy', delta=5e-5):
    # if the sum of thresholds were not between 1+delta and 1-delta,
    # return infinity (just for reduce the search space of the minimizaiton algorithm,
    # because the sum of thresholds should be as close to 1 as possible).
    threshold_sum = np.sum(threshold)

    if threshold_sum > 1+delta:
        return np.inf

    if threshold_sum < 1-delta:
        return np.inf

    # to avoid objective function jump into nan solution
    if np.isnan(threshold_sum):
        print("threshold_sum is nan")
        return np.inf

    # renormalize: the sum of threshold should be 1
    normalized_threshold = threshold/threshold_sum

    # calculate scores based on thresholds
    # suppose it'll return 4 scores in a tuple: (accuracy, roc_auc, pr_auc, f1)
    scores = scoreFunc(model, X_test, Y_test, threshold_list=normalized_threshold)

    scores = np.array(scores)
    weight = np.array([1,1,1,1])

    # Give the metric you want to maximize a bigger weight:
    if metrics == 'accuracy':
        weight = np.array([10,1,1,1])
    elif metrics == 'roc_auc':
        weight = np.array([1,10,1,1])
    elif metrics == 'pr_auc':
        weight = np.array([1,1,10,1])
    elif metrics == 'f1':
        weight = np.array([1,1,1,10])
    elif 'all':
        weight = np.array([1,1,1,1])

    # return negatitive weighted sum (because you want to maximize the sum,
    # it's equivalent to minimize the negative sum)
    return -np.dot(weight, scores)

Use optimize algorithm differential_evolution() (better then fmin) to find the optimal threshold:

from scipy import optimize

output_class_num = Y_test.shape[1]
bounds = optimize.Bounds([1e-5]*output_class_num,[1]*output_class_num)

pmodel = proxyModel(model)

result = optimize.differential_evolution(weighted_score_with_threshold, bounds, args=(pmodel, X_test, Y_test, 'accuracy'))

# calculate threshold
threshold = result.x/np.sum(result.x)

# print the optimized score
print(scoreFunc(model, X_test, Y_test, threshold_list=threshold))


问:
Datatable body become blank after sorting or serching problem
After building table body using .html() function by jQuery ajax call, sorting searching and export not working, make table blank.

```<code>var id = $("#userid").val();

$.ajax({
    type: "POST",
    url: "services/service.php",
    data: {
        cmd: 'get_users',
        id: id
    },
    cache: false,
    dataType: 'json',
    success: function (res) {
        var html = "";
        l = res.length;
        for (var i = 0; i < l; i++) {
            html += "<tr><td>" + res[i].id + "</td><td>" + res[i].username + "</td><td>" + res[i].name + "</td><td>" + res[i].role + "</td><td>" + res[i].parent + "</td><td>" + res[i].address + "</td><td>" + res[i].email + "</td><td>" + res[i].mobile_no + "</td><td><button class='uedit'>Edit</button></td><td><button>Delete</button></td></tr>";
        }
        $('#example tbody').html(html);
    }
})
</code>```

答:
From this code it seems that table will build properly with user's data when you call this ajax. But what you do while sorting, searching and export, it is important. Check the response of ajax for sorting, searching and export. May be response is empty so empty response makes response.length = 0 and html will be empty and it is overwrite to $('#example tbody') with empty html. html() replaces old elements with new elements.

All this is based on assumption that you get data from server on every sorting, searching and export request. If it is not then show me the code of sorting, searching and export.

Body:
After building table body using .html() function by jQuery ajax call, sorting searching and export not working, make table blank.

var id = $("#userid").val();

$.ajax({
    type: "POST",
    url: "services/service.php",
    data: {
        cmd: 'get_users',
        id: id
    },
    cache: false,
    dataType: 'json',
    success: function (res) {
        var html = "";
        l = res.length;
        for (var i = 0; i < l; i++) {
            html += "
" + res[i].id + "	" + res[i].username + "	" + res[i].name + "	" + res[i].role + "	" + res[i].parent + "	" + res[i].address + "	" + res[i].email + "	" + res[i].mobile_no + "	<button class='uedit'>Edit</button>	<button>Delete</button>
";
        }
        $('#example tbody').html(html);
    }
})


问:
How to set FuturedImage to og: image. in gatsby.js
I using gatsby.js.

I want to set the featuredimage described in markdown in the og: image attribute of the meta tag, but it does not work.

The featuredimage is optimized for different paths by gatsby, but the relative path is set to the physical path before build.

How do I set the path for the featuredimage created by the build?

My React Helmet code (excerpt):

```<code><Helmet
    meta={{
      property: `og:image`,
      content: `https://example.com/${post.frontmatter.featuredimage.relativePath}`
    }}
 />
</code>```

My GraphQL query:

export const pageQuery = graphql`
  query($slug: String!) {
    site {
      siteMetadata {
        title
        author
      }
    }
    mdx(fields: { slug: { eq: $slug } }) {
      frontmatter {
        featuredimage {
          relativePath
          childImageSharp {
            fluid(maxWidth: 400, quality: 100) {
              ...GatsbyImageSharpFluid
            }
          }
        }
      }
    }
  }
`
```

Thanks.

答:
You can query path of generated image (format is '/static/name') and use it with site root url like:</p>

```<code>export const pageQuery = graphql`
  query($slug: String!) {
    site {
      siteMetadata {
        title
        author
      }
    }
    mdx(fields: { slug: { eq: $slug } }) {
      frontmatter {
        featuredimage {
          childImageSharp {
            original {
              src
            }
          }
        }
      }
    }
  }
`

<Helmet
    meta={{
      property: `og:image`,
      content: `${siteUrlRoot}${post.frontmatter.featuredimage.childImageSharp.original.src}`
    }}
 />
</code>```

Body:
I using gatsby.js.

I want to set the featuredimage described in markdown in the og: image attribute of the meta tag, but it does not work.

The featuredimage is optimized for different paths by gatsby, but the relative path is set to the physical path before build.

How do I set the path for the featuredimage created by the build?

My React Helmet code (excerpt):

<Helmet
    meta={{
      property: `og:image`,
      content: `https://example.com/${post.frontmatter.featuredimage.relativePath}`
    }}
 />

My GraphQL query:

export const pageQuery = graphql`
  query($slug: String!) {
    site {
      siteMetadata {
        title
        author
      }
    }
    mdx(fields: { slug: { eq: $slug } }) {
      frontmatter {
        featuredimage {
          relativePath
          childImageSharp {
            fluid(maxWidth: 400, quality: 100) {
              ...GatsbyImageSharpFluid
            }
          }
        }
      }
    }
  }
`

Thanks.

Body:
You can query path of generated image (format is '/static/name') and use it with site root url like:

export const pageQuery = graphql`
  query($slug: String!) {
    site {
      siteMetadata {
        title
        author
      }
    }
    mdx(fields: { slug: { eq: $slug } }) {
      frontmatter {
        featuredimage {
          childImageSharp {
            original {
              src
            }
          }
        }
      }
    }
  }
`

<Helmet
    meta={{
      property: `og:image`,
      content: `${siteUrlRoot}${post.frontmatter.featuredimage.childImageSharp.original.src}`
    }}
 />


问:
Access nested values in json using System.Text.Json
I have a JSON file returned from a system that looks like this:

```<code>{
    "value1": "Hello",
    "value2": "World",
    "result":
    {
        "stats":
        {
            "count":"1"
        }
    }
}
</code>```

Getting to the values "Value1" and "Value2" is no issue.
However, I cannot get to "count" - Does not appear to be in a good format.

This is my code:

```<code>class Program
{
    static void Main(string[] args)
    {
        string json1 = File.ReadAllText("test.json");
        var info = JsonSerializer.Deserialize<SnData>(json1);
        WriteLine("Value1: {0} , Value2: {1}",info.value1,info.value2);
    }
}
class SnData
{
    public string value1 {get; set;}
    public string value2 {get; set;}
}
</code>```

How to get the value "count"?

答:
The simplest way would be to replicate the structure of your json. There are handy websites that can do this for you such as http://json2csharp.com/</p>

```<code>class SnData
{
    public string value1 { get; set; }
    public string value2 { get; set; }
    public Result result { get; set; }
}

class Result
{
    public Stats stats { get; set; }
}

class Stats
{
    public int count { get; set; }
}
</code>```

Body:
I have a JSON file returned from a system that looks like this:

{
    "value1": "Hello",
    "value2": "World",
    "result":
    {
        "stats":
        {
            "count":"1"
        }
    }
}

Getting to the values "Value1" and "Value2" is no issue.
However, I cannot get to "count" - Does not appear to be in a good format.

This is my code:

class Program
{
    static void Main(string[] args)
    {
        string json1 = File.ReadAllText("test.json");
        var info = JsonSerializer.Deserialize<SnData>(json1);
        WriteLine("Value1: {0} , Value2: {1}",info.value1,info.value2);
    }
}
class SnData
{
    public string value1 {get; set;}
    public string value2 {get; set;}
}

How to get the value "count"?

Body:
The simplest way would be to replicate the structure of your json. There are handy websites that can do this for you such as http://json2csharp.com/

class SnData
{
    public string value1 { get; set; }
    public string value2 { get; set; }
    public Result result { get; set; }
}

class Result
{
    public Stats stats { get; set; }
}

class Stats
{
    public int count { get; set; }
}


问:
How to set .env values in laravel programmatically on the fly
I have a custom CMS that I am writing from scratch in Laravel and want to set env values i.e. database details, mailer details, general configuration, etc from controller once the user sets up and want to give user the flexibility to change them on the go using the GUI that I am making.

So my question is how do I write the values received from user to the .env file as an when I need from the controller.

And is it a good idea to build the .env file on the go or is there any other way around it?

答:
You can use this custom method i located from internet  , </p>

```<code>  /**
 * Calls the method
 */
public function something(){
    // some code
    $env_update = $this->changeEnv([
        'DB_DATABASE'   => 'new_db_name',
        'DB_USERNAME'   => 'new_db_user',
        'DB_HOST'       => 'new_db_host'
    ]);
    if($env_update){
        // Do something
    } else {
        // Do something else
    }
    // more code
}

protected function changeEnv($data = array()){
        if(count($data) > 0){

            // Read .env-file
            $env = file_get_contents(base_path() . '/.env');

            // Split string on every " " and write into array
            $env = preg_split('/\s+/', $env);;

            // Loop through given data
            foreach((array)$data as $key => $value){

                // Loop through .env-data
                foreach($env as $env_key => $env_value){

                    // Turn the value into an array and stop after the first split
                    // So it's not possible to split e.g. the App-Key by accident
                    $entry = explode("=", $env_value, 2);

                    // Check, if new key fits the actual .env-key
                    if($entry[0] == $key){
                        // If yes, overwrite it with the new one
                        $env[$env_key] = $key . "=" . $value;
                    } else {
                        // If not, keep the old one
                        $env[$env_key] = $env_value;
                    }
                }
            }

            // Turn the array back to an String
            $env = implode("\n", $env);

            // And overwrite the .env with the new data
            file_put_contents(base_path() . '/.env', $env);

            return true;
        } else {
            return false;
        }
    }
</code>```

Body:
You can use this custom method i located from internet  ,

  /**
 * Calls the method
 */
public function something(){
    // some code
    $env_update = $this->changeEnv([
        'DB_DATABASE'   => 'new_db_name',
        'DB_USERNAME'   => 'new_db_user',
        'DB_HOST'       => 'new_db_host'
    ]);
    if($env_update){
        // Do something
    } else {
        // Do something else
    }
    // more code
}

protected function changeEnv($data = array()){
        if(count($data) > 0){

            // Read .env-file
            $env = file_get_contents(base_path() . '/.env');

            // Split string on every " " and write into array
            $env = preg_split('/\s+/', $env);;

            // Loop through given data
            foreach((array)$data as $key => $value){

                // Loop through .env-data
                foreach($env as $env_key => $env_value){

                    // Turn the value into an array and stop after the first split
                    // So it's not possible to split e.g. the App-Key by accident
                    $entry = explode("=", $env_value, 2);

                    // Check, if new key fits the actual .env-key
                    if($entry[0] == $key){
                        // If yes, overwrite it with the new one
                        $env[$env_key] = $key . "=" . $value;
                    } else {
                        // If not, keep the old one
                        $env[$env_key] = $env_value;
                    }
                }
            }

            // Turn the array back to an String
            $env = implode("\n", $env);

            // And overwrite the .env with the new data
            file_put_contents(base_path() . '/.env', $env);

            return true;
        } else {
            return false;
        }
    }


问:
Separate the nodes and avoid overlapping in tree graph in d3.js
I'm working on a responsive horizontal tree layout. The link: d3.js https://codesandbox.io/s/cool-field-vsc6m. My child nodes are getting overlapped.

How do I separate the nodes with a minimal distance and avoid the overlap?

. The code can be found in the above code sandbox link.

答:
I have checked your code and found out that you are using a constant value for radius(45).

I have edited your code and saved the logic for dynamic radius. I am not sure if you will
be able to save it or not. So, I am putting the logic of radius here as well.

I would also suggest you to not use labels inside the nodes for better visual experience and use tooltip for that. Just a suggestion and its upto you.

Please let me know if it resolves your issue.

node.append("circle").attr("r", function(d, i) {
  const padding = 5
  // find siblings of a  node
  let siblings = (d.parent && d.parent.children) || null;
  // find minimum radius based on their x values so they don't overlap.
  let radius =
    siblings && siblings.length > 1 ?
    (siblings[1].x - siblings[0].x - padding) / 2 :
    45;
  return radius;
});```


问:
How do I connect to Oracle Exadata from Python?
I have tried connecting exadata from python using cx_Oracle, but faced issue stating

cx_Oracle.DatabaseError: DPI - 1047: Cannot locate a 64bit Oracle client library.

I am trying to install a 64bit cx_Oracle, but I need to know can I connect from python to exadata.

答:
Welcome to Stack Overflow!

For the record, Oracle Exadata is a platform consisting of hardware and software designed for extreme Oracle Database performance. cx_Oracle is the Python client library to operate on an Oracle Database - hence you want to connect to an Oracle Database utilizing the Python programming language.

cx_Oracle depends on OCI (Oracle Call Interface). You need to download and install Oracle Client Library on your workstation before you can do import cx_Oracle from within Python.

You will find the Oracle Client Library here

Best of luck!


问:
Bind a function to all text input - jQuery
I want to bind a function to all the textarea and want to run it whenever a key gets pressed.

```<code>function fx(docid)
{
  $('#'+docid).val=encodeURIComponent($('#'+docid).val());
  //document.getElementByID('docid').value = encodeURIComponent(document.getElementByID('docid').value);
}
</code>```

Note: the page will have different textarea, I want a single function to do the same job for all the textarea. I don't want to hard code the event with the textarea <textarea onkeydown="..." />

Edit

I want to trigger the function on multiple events, thats on keypress, keydown,click

答:
Just pass in textarea as the selector.  If you want it to trigger for text inputs as well then use textarea, input[type="text"] for the selector:

```<code>var fxHandler = function (e) {
    var yourDocId;
    // code to find/set yourDocId
    fx( yourDocId );
};

// bind to whatever events you need
$('textarea').bind('keydown', fxHandler)
             .bind('keyup', fxHandler)
             .bind('click', fxHandler);
</code>```

Of course, if you run your function as written it will double, triply, etc encode the value, so you'll need to write a function that leaves %## values alone.

Body:
I want to bind a function to all the textarea and want to run it whenever a key gets pressed.

function fx(docid)
{
  $('#'+docid).val=encodeURIComponent($('#'+docid).val());
  //document.getElementByID('docid').value = encodeURIComponent(document.getElementByID('docid').value);
}

Note: the page will have different textarea, I want a single function to do the same job for all the textarea. I don't want to hard code the event with the textarea <textarea onkeydown="..." />

Edit

I want to trigger the function on multiple events, thats on keypress, keydown,click

Body:
Just pass in textarea as the selector.  If you want it to trigger for text inputs as well then use textarea, input[type="text"] for the selector:

var fxHandler = function (e) {
    var yourDocId;
    // code to find/set yourDocId
    fx( yourDocId );
};

// bind to whatever events you need
$('textarea').bind('keydown', fxHandler)
             .bind('keyup', fxHandler)
             .bind('click', fxHandler);

Of course, if you run your function as written it will double, triply, etc encode the value, so you'll need to write a function that leaves %## values alone.


答:
I think I'd be fairly pedestrian about it:

```<code>const result = new Map();
const rex = /(\d+)-(\d+)-(\d+)/g;
let match;
while ((match = rex.exec(myString)) !== null) {
    result.set(match[1], [match[2], match[3]]);
}
</code>```

That's assuming you want the 2000, 10 part as an array.

Live Example:

const myString = "101-2000-10-102-2000-15"
const result = new Map();
const rex = /(\d+)-(\d+)-(\d+)/g;
let match;
while ((match = rex.exec(myString)) !== null) {
    result.set(match[1], [match[2], match[3]]);
}
console.log([...result.entries()]);```
</div>
</div>
</p>

<p>Or with more meaningful names via named capture groups and destructuring:</p>

```const result = new Map();
const rex = /(?<key>\d+)-(?<value1>\d+)-(?<value2>\d+)/g;
let match;
while ((match = rex.exec(myString)) !== null) {
    const {key, value1, value2} = match.groups;
    result.set(key, [value1, value2]);
}
```

<p>Live Example:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const myString = "101-2000-10-102-2000-15"
const result = new Map();
const rex = /(?<key>\d+)-(?<value1>\d+)-(?<value2>\d+)/g;
let match;
while ((match = rex.exec(myString)) !== null) {
    const {key, value1, value2} = match.groups;
    result.set(key, [value1, value2]);
}
console.log([...result.entries()]);</code>```

Or with the new matchAll and destructuring:

```<code>const rex = /(\d+)-(\d+)-(\d+)/g;
const result = new Map(
    [...myString.matchAll(rex)].map(
        ([, key, value1, value2]) => [key, [value1, value2]]
    )
);
</code>```

Live Example:

const myString = "101-2000-10-102-2000-15"
const rex = /(\d+)-(\d+)-(\d+)/g;
const result = new Map(
    [...myString.matchAll(rex)].map(
        ([, key, value1, value2]) => [key, [value1, value2]]
    )
);
console.log([...result.entries()]);```

Title: Convert an array which contains strings into key value pairs

Body:
I think I'd be fairly pedestrian about it:

const result = new Map();
const rex = /(\d+)-(\d+)-(\d+)/g;
let match;
while ((match = rex.exec(myString)) !== null) {
    result.set(match[1], [match[2], match[3]]);
}

That's assuming you want the 2000, 10 part as an array.

Live Example:

const myString = "101-2000-10-102-2000-15"
const result = new Map();
const rex = /(\d+)-(\d+)-(\d+)/g;
let match;
while ((match = rex.exec(myString)) !== null) {
    result.set(match[1], [match[2], match[3]]);
}
console.log([...result.entries()]);

Or with more meaningful names via named capture groups and destructuring:

const result = new Map();
const rex = /(?<key>\d+)-(?<value1>\d+)-(?<value2>\d+)/g;
let match;
while ((match = rex.exec(myString)) !== null) {
    const {key, value1, value2} = match.groups;
    result.set(key, [value1, value2]);
}

Live Example:

const myString = "101-2000-10-102-2000-15"
const result = new Map();
const rex = /(?<key>\d+)-(?<value1>\d+)-(?<value2>\d+)/g;
let match;
while ((match = rex.exec(myString)) !== null) {
    const {key, value1, value2} = match.groups;
    result.set(key, [value1, value2]);
}
console.log([...result.entries()]);

Or with the new matchAll and destructuring:

const rex = /(\d+)-(\d+)-(\d+)/g;
const result = new Map(
    [...myString.matchAll(rex)].map(
        ([, key, value1, value2]) => [key, [value1, value2]]
    )
);

Live Example:

const myString = "101-2000-10-102-2000-15"
const rex = /(\d+)-(\d+)-(\d+)/g;
const result = new Map(
    [...myString.matchAll(rex)].map(
        ([, key, value1, value2]) => [key, [value1, value2]]
    )
);
console.log([...result.entries()]);


问:
Accessing Specific Element from List of Pairs in C++
I want to skip large weights in case of multiple edges. I think the code can be optimized if I can access the weight directly between the edges u and v. The code is from Dijkstra Algorithm by using priority queue. I can iterate and check but I think it's not efficient. How can I optimize the code?</p>

```<code>void Graph::addEdge(long long int u, long long int v, long long int weight){

    list<pair<long long int,long long int> >::iterator i;

    int flag = 0;
    for(i = adj[u].begin(); i!= adj[u].end(); ++i){
        if((*i).first == v && weight>(*i).second){
            flag = 1;
            break;
        }
    }
    if(flag == 1){
        return;
    }

    adj[u].push_back(make_pair(v, weight));
    adj[v].push_back(make_pair(u, weight));
}
</code>```

答:
I can suggest some optimizations to this code:

Use std::vector or std::array instead of std::list. list is implemented as linked list and traversal is slow. vector and array are cache-friendlier as well since data is stored sequentially and thus, more than one elements will be loaded at once in the cache.

Using an array/vector of an unordered_map instead of every pairs such that adj[u] will correspond to a hash map with node v as key and min weight as the value. To improve the performance of this hash map further, you can provide a custom hash function and a custom collision resolution method as well after going through the default behavior and if it suits your case. Otherwise std::unordered_map is quite efficient as it is.
Do note that using unordered_map is only more beneficial in case of insertion/queries For traversal, it's sad.

Body:
I want to skip large weights in case of multiple edges. I think the code can be optimized if I can access the weight directly between the edges u and v. The code is from Dijkstra Algorithm by using priority queue. I can iterate and check but I think it's not efficient. How can I optimize the code?

void Graph::addEdge(long long int u, long long int v, long long int weight){

    list<pair<long long int,long long int> >::iterator i;

    int flag = 0;
    for(i = adj[u].begin(); i!= adj[u].end(); ++i){
        if((*i).first == v && weight>(*i).second){
            flag = 1;
            break;
        }
    }
    if(flag == 1){
        return;
    }

    adj[u].push_back(make_pair(v, weight));
    adj[v].push_back(make_pair(u, weight));
}


问:
angular 8 how to disable button of child component that use multiple times in parent component
I have a child component that can be used multiple times in parent component with different action.now How can i disable button that exist in child component when i click on button in parent component.

My child component that can be used multiple times:

import {Component} from 'angular2/core';

```<code>@Component({
    selector: 'my-product',
    template: `<button [disabled]="isDisableButton">select</button>`
})

export class MyCardComponent {
  @Input() isDisableButton = false;
}
</code>```

my parent component html :

```<code><div>
   <p>Product Type 1<p>
  <my-product [isDisableButton]="isDisableType1Button"></my-product>
   <button (click)="onType1()">select type 1</button>
</div>

<div>
    <p>Product  Type 2<p>
  <my-product [isDisableButton]="isDisableType2Button"></my-product>
   <button (click)="onType2()">select type 1</button>
</div>
</code>```

my parent component ts :

```<code>      @Component({
      selector: 'my-parentComponent',
      templateUrl: '..'
    })
    export class PopupDirective {

        isDisableType1Button : boolean;
        isDisableType2Button: boolean;

     onType2(){
        this.isDisableType1Button = true;
        this.isDisableType2Button = false;
         }

    onType1(){
       this.isDisableType2Button = true;
       this.isDisableType1Button = false;
      }

  }
</code>```

this solution is not work correctly

答:
As you can see on this Stackblitz, there's nothing wrong with logic you implemented.

Maybe you missed on your child component the import of Input decorator:

```<code>import { Component, Input } from '@angular/core';
</code>```

Body:
I have a child component that can be used multiple times in parent component with different action.now How can i disable button that exist in child component when i click on button in parent component.

My child component that can be used multiple times:

import {Component} from 'angular2/core';

@Component({
    selector: 'my-product',
    template: `<button [disabled]="isDisableButton">select</button>`
})

export class MyCardComponent {
  @Input() isDisableButton = false;
}

my parent component html :

Product Type 1

  <my-product [isDisableButton]="isDisableType1Button"></my-product>
   <button (click)="onType1()">select type 1</button>

Product  Type 2

  <my-product [isDisableButton]="isDisableType2Button"></my-product>
   <button (click)="onType2()">select type 1</button>

my parent component ts :

      @Component({
      selector: 'my-parentComponent',
      templateUrl: '..'
    })
    export class PopupDirective {

        isDisableType1Button : boolean;
        isDisableType2Button: boolean;

     onType2(){
        this.isDisableType1Button = true;
        this.isDisableType2Button = false;
         }

    onType1(){
       this.isDisableType2Button = true;
       this.isDisableType1Button = false;
      }

  }

this solution is not work correctly

Body:
As you can see on this Stackblitz, there's nothing wrong with logic you implemented.

Maybe you missed on your child component the import of Input decorator:

import { Component, Input } from '@angular/core';


问:
My Python code pass simple tests but not extended ones due to performance constrains
I'm teaching myself to code with Python and I've been completing kata's (mainly 7 kyu for now) on Codewars for a while. While trying to level up stumbled on following 6 kyu kata, that looked to be achievable with my knowledge:

Complete the function that takes a string as an input, and return a list of all the unpaired characters (i.e. they show up an odd number of times in the string), in the order they were encountered as an array.

In case of multiple appearances to choose from, take the last occurence of the unpaired character.

Notes:

A wide range of characters is used, and some of them may not render properly in your browser.
  Your solution should be linear in terms of string length to pass the last test.
  Examples:

"Hello World"   -->  ["H", "e", " ", "W", "r", "l", "d"]

"Codewars"      -->  ["C", "o", "d", "e", "w", "a", "r", "s"]

"woowee"        -->  []

"wwoooowweeee"  -->  []

"racecar"       -->  ["e"]

"Mamma"         -->  ["M"]

"Mama"          -->  ["M", "m"]

The following Python 3.6.0 code pass sample tests:

def function_name(s):
    result = []
    lengthS = len(s)
    dictResult = {}

    for item in s[-1:(-1 * lengthS - 1):-1]:
        numLetters = 0
        for number in range(lengthS):
            if item == s[number]:
                numLetters = numLetters + 1
        if numLetters % 2 != 0:
            dictResult[item] = numLetters

    for key in list(dictResult.keys())[-1:(-1 * (len(list(dictResult))) - 1):-1]:
        result.append(key)

    return result
```

Running a full round of tests fails due to :

Execution Timed Out (12000 ms)

Commenting some parts of code allows me to fail full round of tests quicker so I could see tests use very long strings.

It is clear that my code is not performance optimised. Read some articles on algorithms and I suspect my code lacks in performance due to for loop within another for loop, which is O(n²) complexity operation. And this is where I've stuck for a while. I'm not sure if this is the only piece of code that needs to be changed and if it is - just cannot get around understanding how this could be done.

Note. Please do not post answers with complete solution to this problem. I'd rather wish to figure the final code myself. So I would be glad if you could point to sections of my code that requires attention with suggestions, example code or further reading.

答:
As per your note:

Note. Please do not post answers with complete solution to this
  problem. I'd rather wish to figure the final code myself. So I would
  be glad if you could point to sections of my code that requires
  attention with suggestions, example code or further reading.

I will be posting only the bottlenecks, rest is up to you to figure out.
Your code has

```<code>for number in range(lengthS):
        if item == s[number]:
            numLetters = numLetters + 1
</code>```

which basically means you are going through the entire string and checking where all item character exists and collect the count. This is making your code quadratic in nature(O(n^2)) because for each character, there is an entire scan in the string taking n^2 steps asymptotically.

To overcome this, you can collect the count while iterating the string itself by taking the help of the dictionary methods. So, your code can change from

```<code>for item in s[-1:(-1 * lengthS - 1):-1]:
        numLetters = 0
        for number in range(lengthS):
            if item == s[number]:
                numLetters = numLetters + 1
        if numLetters % 2 != 0:
            dictResult[item] = numLetters
</code>```

to

```<code>for item in s[-1:(-1 * lengthS - 1):-1]:
        dictResult[item] = dictResult.get(item,0) + 1
</code>```

This would collect all counts for a particular character in a single pass, making it O(n) in nature.

Second observation I found is that there is no point(or any advantage) in traversing the string in a reverse way, like below:

```<code>for item in s[-1:(-1 * lengthS - 1):-1]:
</code>```

You can instead try simply looping over them one by one, like below:

```<code>for item in s:
    dictResult[item] = dictResult.get(item,0) + 1
</code>```

Third is to observe whether you really need any item in dictResult if it's count is even. If any character's count comes out to be even at any point in iteration, you can simply remove it from dictResult. This way you would only have odd valued keys in dictResult. This also makes your code a bit space efficient(sometimes significant).
Note that the odd valued keys in dictResult will not be ordered in terms of the order of characters in which the output is expected. I leave this as an exercise for you to figure out.

Update:

It seems that from Python3.7, the keys in dictionary are stored in the order in which they are inserted. So, it's relatively easy to match the order of output.

Correct Snippet:

```<code>def odd_one_out(s):
    result = []
    dictResult = {}

    for item in s:
        dictResult[item] = dictResult.get(item,0) + 1
        if dictResult[item] % 2 == 0:
            dictResult.pop(item)
    return list(dictResult.keys())
</code>```

Body:
I'm teaching myself to code with Python and I've been completing kata's (mainly 7 kyu for now) on Codewars for a while. While trying to level up stumbled on following 6 kyu kata, that looked to be achievable with my knowledge:

Complete the function that takes a string as an input, and return a list of all the unpaired characters (i.e. they show up an odd number of times in the string), in the order they were encountered as an array.

In case of multiple appearances to choose from, take the last occurence of the unpaired character.

Notes:

A wide range of characters is used, and some of them may not render properly in your browser.
  Your solution should be linear in terms of string length to pass the last test.
  Examples:

"Hello World"   -->  ["H", "e", " ", "W", "r", "l", "d"]

"Codewars"      -->  ["C", "o", "d", "e", "w", "a", "r", "s"]

"woowee"        -->  []

"wwoooowweeee"  -->  []

"racecar"       -->  ["e"]

"Mamma"         -->  ["M"]

"Mama"          -->  ["M", "m"]

The following Python 3.6.0 code pass sample tests:

def function_name(s):
    result = []
    lengthS = len(s)
    dictResult = {}

    for item in s[-1:(-1 * lengthS - 1):-1]:
        numLetters = 0
        for number in range(lengthS):
            if item == s[number]:
                numLetters = numLetters + 1
        if numLetters % 2 != 0:
            dictResult[item] = numLetters

    for key in list(dictResult.keys())[-1:(-1 * (len(list(dictResult))) - 1):-1]:
        result.append(key)

    return result

Running a full round of tests fails due to :

Execution Timed Out (12000 ms)

Commenting some parts of code allows me to fail full round of tests quicker so I could see tests use very long strings.

It is clear that my code is not performance optimised. Read some articles on algorithms and I suspect my code lacks in performance due to for loop within another for loop, which is O(n²) complexity operation. And this is where I've stuck for a while. I'm not sure if this is the only piece of code that needs to be changed and if it is - just cannot get around understanding how this could be done.

Note. Please do not post answers with complete solution to this problem. I'd rather wish to figure the final code myself. So I would be glad if you could point to sections of my code that requires attention with suggestions, example code or further reading.

Body:
As per your note:

Note. Please do not post answers with complete solution to this
  problem. I'd rather wish to figure the final code myself. So I would
  be glad if you could point to sections of my code that requires
  attention with suggestions, example code or further reading.

I will be posting only the bottlenecks, rest is up to you to figure out.
Your code has

for number in range(lengthS):
        if item == s[number]:
            numLetters = numLetters + 1

which basically means you are going through the entire string and checking where all item character exists and collect the count. This is making your code quadratic in nature(O(n^2)) because for each character, there is an entire scan in the string taking n^2 steps asymptotically.

To overcome this, you can collect the count while iterating the string itself by taking the help of the dictionary methods. So, your code can change from

for item in s[-1:(-1 * lengthS - 1):-1]:
        numLetters = 0
        for number in range(lengthS):
            if item == s[number]:
                numLetters = numLetters + 1
        if numLetters % 2 != 0:
            dictResult[item] = numLetters

to

for item in s[-1:(-1 * lengthS - 1):-1]:
        dictResult[item] = dictResult.get(item,0) + 1

This would collect all counts for a particular character in a single pass, making it O(n) in nature.

Second observation I found is that there is no point(or any advantage) in traversing the string in a reverse way, like below:

for item in s[-1:(-1 * lengthS - 1):-1]:

You can instead try simply looping over them one by one, like below:

for item in s:
    dictResult[item] = dictResult.get(item,0) + 1

Third is to observe whether you really need any item in dictResult if it's count is even. If any character's count comes out to be even at any point in iteration, you can simply remove it from dictResult. This way you would only have odd valued keys in dictResult. This also makes your code a bit space efficient(sometimes significant).
Note that the odd valued keys in dictResult will not be ordered in terms of the order of characters in which the output is expected. I leave this as an exercise for you to figure out.

Update:

It seems that from Python3.7, the keys in dictionary are stored in the order in which they are inserted. So, it's relatively easy to match the order of output.

Correct Snippet:

def odd_one_out(s):
    result = []
    dictResult = {}

    for item in s:
        dictResult[item] = dictResult.get(item,0) + 1
        if dictResult[item] % 2 == 0:
            dictResult.pop(item)
    return list(dictResult.keys())


问:
Laravel, protecting a folder in public folder
I have a folder inside the public folder in Laravel app, this folder is called 'docs' and I want to protect it from unauthorised access. So basically when a user tries to access this folder they should get redirected to the login page. I tried doing this:

```<code>Route::get('\docs','DocsController@protected')->middleware('auth');
</code>```

But Laravel doesn't even get triggered and the user goes directly to the folder.

答: You can use .htaccess file to protect this folder. But IMHO the better way is to move this folder from public, and access the docs using php code (using something like thephpleague/flysystem).</p>

Body:
I have a folder inside the public folder in Laravel app, this folder is called 'docs' and I want to protect it from unauthorised access. So basically when a user tries to access this folder they should get redirected to the login page. I tried doing this:

Route::get('\docs','DocsController@protected')->middleware('auth');

But Laravel doesn't even get triggered and the user goes directly to the folder.


问:
Express.js Response Timeout
PROBLEM

I've been looking for request/response timeouts for Express.js but everything seems to be related to the connection rather than the request/response itself.

If a request is taking a long time, it should be timed out. Obviously this shouldn't happen but even a simple mistake as having a route handler without a call to the callback or without res.send(), the browser will keep waiting for a reply forever.

An empty route handler is a perfect example of this.

```<code>app.get('/sessions/', function(req, res, callback){});
</code>```

FIX

I added the following before app.use(app,router); and it seemed to add the timeout functionality. Does anyone have any experience/opinion on this?

```<code>app.use(function(req, res, next){
    res.setTimeout(120000, function(){
        console.log('Request has timed out.');
            res.send(408);
        });

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

Note that I've set the timeout to 2 minutes.

答:
In case you would like to use timeout middleware and exclude a specific route:</p>

```<code>var timeout = require('connect-timeout');
app.use(timeout('5s')); //set 5s timeout for all requests

app.use('/my_route', function(req, res, next) {
    req.clearTimeout(); // clear request timeout
    req.setTimeout(20000); //set a 20s timeout for this request
    next();
}).get('/my_route', function(req, res) {
    //do something that takes a long time
});
</code>```

Title: Express.js Response Timeout

Body:
PROBLEM

I've been looking for request/response timeouts for Express.js but everything seems to be related to the connection rather than the request/response itself.

If a request is taking a long time, it should be timed out. Obviously this shouldn't happen but even a simple mistake as having a route handler without a call to the callback or without res.send(), the browser will keep waiting for a reply forever.

An empty route handler is a perfect example of this.

app.get('/sessions/', function(req, res, callback){});

FIX

I added the following before app.use(app,router); and it seemed to add the timeout functionality. Does anyone have any experience/opinion on this?

app.use(function(req, res, next){
    res.setTimeout(120000, function(){
        console.log('Request has timed out.');
            res.send(408);
        });

    next();
});

Note that I've set the timeout to 2 minutes.

Body:
In case you would like to use timeout middleware and exclude a specific route:

var timeout = require('connect-timeout');
app.use(timeout('5s')); //set 5s timeout for all requests

app.use('/my_route', function(req, res, next) {
    req.clearTimeout(); // clear request timeout
    req.setTimeout(20000); //set a 20s timeout for this request
    next();
}).get('/my_route', function(req, res) {
    //do something that takes a long time
});


问:
Is there a compatibility list for Angular / Angular-CLI and Node.js?
I periodically run into the problem, having to spin up old Angular projects with deprecated dependencies of Angular.

Because I unsually run the latest Node.js version (at least lates LTS version) I often had the problem, that I wasn't able to get the old projects running.
I solved this by using a node version manager, but still I often have the problem that I'm not sure what is the best Node.js version to use for Angular Version X.

Sadly the official release notes handle this topic shabbily and are not a true help, especially if you like to know as of which Angular Version you can't use a specific Node.js version anymore...

Is there a complete compatibility list to check which Angular version is compatible with which Node.js version?

Body:
One more way to get to this details is by running npx ngvm compat

Wondering what NGVM is? Check it out https://youtu.be/tWCM69cucOA?t=1975

Angular CLI version
Angular version
Node.js version
TypeScript version
RxJS version

~15.0.0
~15.0.0
^14.20.0 || ^16.13.0 || ^18.10.0
~4.8.4
^6.5.5 || ^7.4.0

~14.2.0
~14.2.0
^14.15.0 || ^16.10.0
>= 4.6.4 < 4.9.0
^6.5.5 || ^7.4.0

~14.1.3
~14.1.3
^14.15.0 || ^16.10.0
>= 4.6.4 < 4.8.0
^6.5.5 || ^7.4.0

~14.0.7
~14.0.7
^14.15.0 || ^16.10.0
>= 4.6.4 < 4.8.0
^6.5.5 || ^7.4.0

~13.3.0
~13.3.0
^12.20.2 || ^14.15.0 || ^16.10.0
>= 4.4.4 < 4.7.0
^6.5.5 || ^7.4.0

~13.2.6
~13.2.7
^12.20.2 || ^14.15.0 || ^16.10.0
>= 4.4.4 <= 4.5.5
^6.5.5 || ^7.4.0

~13.1.4
~13.1.3
^12.20.2 || ^14.15.0 || ^16.10.0
>= 4.4.4 <= 4.5.5
^6.5.5 || ^7.4.0

~13.0.4
~13.0.3
^12.20.2 || ^14.15.0 || ^16.10.0
~4.4.4
^6.5.5 || ^7.4.0

~12.2.18
~12.2.17
^12.14.1 || ^14.15.0
>= 4.2.4 <= 4.3.5
^6.5.5 || ^7.0.1

~12.1.4
~12.1.5
^12.14.1 || ^14.15.0
>= 4.2.4 <= 4.3.5
^6.5.5

~12.0.5
~12.0.5
^12.14.1 || ^14.15.0
~4.2.4
^6.5.5

~11.2.19
~11.2.14
^10.13.0 || ^12.11.1
>= 4.0.8 <= 4.1.6
^6.5.5

~11.1.4
~11.1.2
^10.13.0 || ^12.11.1
>= 4.0.8 <= 4.1.6
^6.5.5

~11.0.7
~11.0.9
^10.13.0 || ^12.11.1
~4.0.8
^6.5.5

~10.2.4
~10.2.5
^10.13.0 || ^12.11.1
>= 3.9.4 <= 4.0.8
^6.5.5

~10.1.7
~10.1.6
^10.13.0 || ^12.11.1
>= 3.9.4 <= 4.0.8
^6.5.5

~10.0.8
~10.0.14
^10.13.0 || ^12.11.1
~3.9.4
^6.5.5

~9.1.15
~9.1.13
^10.13.0 || ^12.11.1
>= 3.6.5 <= 3.8.3
^6.5.5

~9.0.7
~9.0.7
^10.13.0 || ^12.11.1
>= 3.6.5 <= 3.7.7
^6.5.5

~8.3.29
~8.2.14
^10.9.0
~3.5.3
^6.4.0

~8.2.2
~8.2.14
^10.9.0
~3.4.5
^6.4.0

~8.1.3
~8.1.3
^10.9.0
~3.4.5
^6.4.0

~8.0.6
~8.0.3
^10.9.0
~3.4.5
^6.4.0

~7.3.9
~7.2.15
^8.9.4 || ^10.9.0
~3.2.4
^6.3.3

~7.2.4
~7.2.15
^8.9.4 || ^10.9.0
~3.2.4
^6.3.3

~7.1.4
~7.1.4
^8.9.4 || ^10.9.0
~3.1.6
^6.3.3

~7.0.7
~7.0.4
^8.9.4 || ^10.9.0
~3.1.6
^6.3.3

~6.2.9
~6.1.10
^8.9.4
~2.9.2
^6.2.2

~6.1.5
~6.1.10
^8.9.4
~2.7.2
^6.2.2

~6.0.8
~6.0.9
^8.9.4
~2.7.2
^6.0.0

~1.7.4
~5.2.11
^6.9.5 || ^8.9.4
~2.5.3
<= 5.5.12 < 6.0.0

~1.6.7
~5.2.11
^6.9.5 || ^8.9.4
~2.5.3
<= 5.5.12 < 6.0.0

~1.5.6
>= 5.0.5 <= 5.1.3
^6.9.5 || ^8.9.4
>= 2.4.2 <= 2.5.3
<= 5.5.12 < 6.0.0

~1.4.10
>= 4.2.6 <= 4.4.7
^6.9.5 || ^8.9.4
~2.4.2
^5.0.3

~1.3.2
>= 4.2.6 <= 4.4.7
^6.9.5
~2.4.2
^5.0.3

~1.2.7
>= 4.0.3 <= 4.1.3
^6.9.5
~2.3.4
^5.0.3

~1.1.3
>= 4.0.3 <= 4.1.3
^6.9.5
~2.3.4
^5.0.3

~1.0.6
>= 4.0.3 <= 4.1.3
^6.9.5
~2.2.2
^5.0.3

1.0.0-rc.4
~2.4.10
^6.9.5
~2.0.10
^5.0.3

1.0.0-beta.30
~2.3.1
^6.9.5
~2.0.10
^5.0.3

1.0.0-beta.22-1 (package name: angular-cli)
~2.2.4
^6.9.5
~2.0.10
^5.0.3

1.0.0-beta.20-1 (package name: angular-cli)
~2.1.2
^6.9.5
~2.0.10
^5.0.3

1.0.0-beta.17 (package name: angular-cli)
~2.0.2
^6.9.5
~2.0.10
^5.0.3

Credits: https://gist.github.com/LayZeeDK/c822cc812f75bb07b7c55d07ba2719b3 by Lars Gyrup Brink Nielsen


问:
How assign the name of a check box to a cell in Excel
I have created a check box in excel and I would like that when I click on the check box name be assigned to a cell in another sheet.

how can i do that?

Here is what I tried but I get an error 424

```<code>Private Sub checkbox1_click()
Worksheets("Produits").Range("A1") = checkbox1.Caption
End Sub
</code>```

Ps: I use Office2019

答:
You forgot about .Value
Try something like that:

```<code>ActiveWorkbook.Sheets("YourSheet").Range("A1").Value = CheckBox1.Caption
</code>```

But I don't know what's the point about your case. Maybe you'll fined that way more helpful.

```<code>If CheckBox1.Value = True Then
ActiveWorkbook.Sheets("YourSheet").Range("A1").Value = CheckBox1.Caption
End If

If CheckBox1.Value = False Then
ActiveWorkbook.Sheets("YourSheet").Range("A1").ClearContents
End If
</code>```

Body:
I have created a check box in excel and I would like that when I click on the check box name be assigned to a cell in another sheet.

how can i do that?

Here is what I tried but I get an error 424

Private Sub checkbox1_click()
Worksheets("Produits").Range("A1") = checkbox1.Caption
End Sub

Ps: I use Office2019

Body:
You forgot about .Value
Try something like that:

ActiveWorkbook.Sheets("YourSheet").Range("A1").Value = CheckBox1.Caption

But I don't know what's the point about your case. Maybe you'll fined that way more helpful.

If CheckBox1.Value = True Then
ActiveWorkbook.Sheets("YourSheet").Range("A1").Value = CheckBox1.Caption
End If

If CheckBox1.Value = False Then
ActiveWorkbook.Sheets("YourSheet").Range("A1").ClearContents
End If


问:
Android login screen works on Android Studio debug apk but not when downloaded from Play Store
My login screen runs fine when I test on the phone connected to android studio. When I upload it to the Play Store and download in the other phone, it won't work. When I press login, I get, immediately the result of execution of

```<code>toast("login: " + loginResult + " ok: " + false);
</code>```

and I do not get the result of

```<code>toast("fazendo login");
</code>```

Which indicates that the async task is returning immediately, it doesn't even try do login. Why this happens? I can't debug because it happens only on the downloaded app from play store.

```<code>import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import venko.Venko;

public class LoginActivity extends AppCompatActivity {
    private static final String TAG = "LoginActivity";

    TextView serverView;
    TextView passwordView;
    Button loginButton;
    Venko venkoAPI;
    String server;
    String password;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        venkoAPI = new Venko();

        serverView = findViewById(R.id.server);
        passwordView = findViewById(R.id.password);
        loginButton = findViewById(R.id.login);
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                server = serverView.getText().toString();
                password = passwordView.getText().toString();
                new LoginTask().execute();
            }
        });
        toast("faça login no servidor");
    }
    public void toast(final String text) {
        runOnUiThread(new Runnable() {
            public void run() {
                Toast.makeText(getBaseContext(), text, Toast.LENGTH_LONG).show();
            }
        });
    }
    private class LoginTask extends AsyncTask<Integer, Void, Boolean> {

        private LoginTask() {

        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Boolean doInBackground(Integer... params) {
            try {
                toast("fazendo login");

                venkoAPI.setPassword(password);
                venkoAPI.setAddress(server);
                Log.d(TAG, "doing login to " + server + " with password " + password);
                return venkoAPI.doLogin();
            } catch (Exception exception) {
                Log.d(TAG, exception.toString());
                toast(exception.toString());
                return false;
            }
        }

        @Override
        protected void onPostExecute(Boolean loginResult) {
            super.onPostExecute(loginResult);
            SharedPreferences sharedPref = getSharedPreferences("login", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPref.edit();
            boolean ok = loginResult;
            if (ok) {
                Log.d(TAG, "saving password info: " + serverView.getText().toString() + " and " + passwordView.getText().toString());
                editor.putString("server", serverView.getText().toString());
                editor.putString("password", passwordView.getText().toString());
                editor.commit();
                //go to main activity
                Intent intent = new Intent(LoginActivity.this, MainViewPager.class);
                startActivity(intent);
            } else {
                Log.d(TAG, "login did not work");
                toast("login: " + loginResult + " ok: " + false);
            }
        }
    }
}
</code>```

答:
The issue occurs in release build
try using proguard-rules

Add this line to your proguard-rules.pro

```<code>-keep class YOUR_PACKAGE_NAME.LoginActivity { *; }
</code>```

Body:
My login screen runs fine when I test on the phone connected to android studio. When I upload it to the Play Store and download in the other phone, it won't work. When I press login, I get, immediately the result of execution of

toast("login: " + loginResult + " ok: " + false);

and I do not get the result of

toast("fazendo login");

Which indicates that the async task is returning immediately, it doesn't even try do login. Why this happens? I can't debug because it happens only on the downloaded app from play store.

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import venko.Venko;

public class LoginActivity extends AppCompatActivity {
    private static final String TAG = "LoginActivity";

    TextView serverView;
    TextView passwordView;
    Button loginButton;
    Venko venkoAPI;
    String server;
    String password;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        venkoAPI = new Venko();

        serverView = findViewById(R.id.server);
        passwordView = findViewById(R.id.password);
        loginButton = findViewById(R.id.login);
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                server = serverView.getText().toString();
                password = passwordView.getText().toString();
                new LoginTask().execute();
            }
        });
        toast("faça login no servidor");
    }
    public void toast(final String text) {
        runOnUiThread(new Runnable() {
            public void run() {
                Toast.makeText(getBaseContext(), text, Toast.LENGTH_LONG).show();
            }
        });
    }
    private class LoginTask extends AsyncTask<Integer, Void, Boolean> {

        private LoginTask() {

        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Boolean doInBackground(Integer... params) {
            try {
                toast("fazendo login");

                venkoAPI.setPassword(password);
                venkoAPI.setAddress(server);
                Log.d(TAG, "doing login to " + server + " with password " + password);
                return venkoAPI.doLogin();
            } catch (Exception exception) {
                Log.d(TAG, exception.toString());
                toast(exception.toString());
                return false;
            }
        }

        @Override
        protected void onPostExecute(Boolean loginResult) {
            super.onPostExecute(loginResult);
            SharedPreferences sharedPref = getSharedPreferences("login", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPref.edit();
            boolean ok = loginResult;
            if (ok) {
                Log.d(TAG, "saving password info: " + serverView.getText().toString() + " and " + passwordView.getText().toString());
                editor.putString("server", serverView.getText().toString());
                editor.putString("password", passwordView.getText().toString());
                editor.commit();
                //go to main activity
                Intent intent = new Intent(LoginActivity.this, MainViewPager.class);
                startActivity(intent);
            } else {
                Log.d(TAG, "login did not work");
                toast("login: " + loginResult + " ok: " + false);
            }
        }
    }
}

Body:
The issue occurs in release build
try using proguard-rules

Add this line to your proguard-rules.pro

-keep class YOUR_PACKAGE_NAME.LoginActivity { *; }


问:
download file from google cloud compute instance
When I use format like

```<code>gcloud compute copy-files user@instance-1:/home/user/file \ /home/user/Desktop \ --zone europe-west1-b
</code>```

it gives me error

no such file or directory as desktop

答:
This worked for me

Syntax :

```<code>gcloud compute scp <UserName>@<ServerName/InstanceName>:~/<FilePathFromInstance> <LocalSystemFilePath>
</code>```

Body:
When I use format like

gcloud compute copy-files user@instance-1:/home/user/file \ /home/user/Desktop \ --zone europe-west1-b

it gives me error

no such file or directory as desktop

Body:
This worked for me

Syntax :

gcloud compute scp <UserName>@<ServerName/InstanceName>:~/<FilePathFromInstance> <LocalSystemFilePath>


问:
For loop returning only first json Object Flutter
While I tried to fetch data from a JSON am only able to return the first object.
I had mentioned the statement which I think the issue is. I want to return all the available object from the JSON so that I shall display it in a list of cards. I need to return all the JSON objects and pass it to another page containing list of cards. If anyone knows the solution please help me fix it.
Thanks in advance. </p>

```<code>import 'dart: convert';
import 'package:flutter/cupertino.dart';
import 'package:tts/tts.dart';
import 'package:wiizboo/service/Chatmsg_service.dart';
import 'package:wiizboo/widget/a%20copy.dart';
import 'package:wiizboo/widget/chat_in_message.dart';
import 'package:wiizboo/widget/chat_out_message.dart';
import 'package:wiizboo/widget/form.dart';
import 'package:wiizboo/widget/image_camera.dart';
import 'package:wiizboo/widget/image_gallery.dart';

class ChatMessageModel with ChangeNotifier {
  String data;
  List accntdet;

  ChatmessageService chatservice = ChatmessageService();
  List<Widget> messages = <Widget>[];

  ChatMessageModel() {
    sendMsg("Hi");
  }

  Future handlesubmission(String chattext) {
    Widget message = new ChatInMessage(
      text: chattext,
      name: "Me",
      type: true,
    );
    addMsg(message);
    sendMsg(chattext);
  }

  addMsg(Widget msg) {
    messages.insert(0, msg);
    notifyListeners();
  }

  sendMsg(String msg) {
    chatservice.SendMsg(msg).then((String msg) {
      responseBuilder(msg);
    });
  }

  responseBuilder(String msg) {
    Widget message;
    String identifier = '';

    var arr = msg.split("~");
    if (arr.length > 1) {
      identifier = arr[0];
      msg = arr[1];
    } else {
      msg = arr[0];
    }

    switch (identifier) {
      case 'email_phone':
        message = new Forms(onSubmitted: (String val) {
          Widget a = new ChatInMessage(
            text: val,
            name: "Me",
            type: true,
          );
          addMsg(a);
          sendMsg(val);
        });
        break;

      case 'selfie':
        message = new ImageCamera(onSubmitted: (String imageres) {
          Widget b = new ChatInMessage(
            text: imageres,
            name: "Me",
            type: true,
          );
          sendMsg(imageres);
        });
        break;

      case 'aadhar':
        message = new ImageGalery(onSubmitted: (String imageres) {
          Widget b = new ChatInMessage(
            text: imageres,
            name: "Me",
            type: true,
          );
          sendMsg(imageres);
        });
        break;

      case 'account_info':
        print(msg);
        data = msg;
        String receivedJson = data;
        List<dynamic> list = json.decode(receivedJson);
        accntdet = list;
        int l = list.length;
        print(l);

//------------ the statement --------//
        for (dynamic account in accntdet) {
          message = new AccountInfo(
            l: l,
            iban: account['ibn_no'],
            accno: account['account_no'],
            sort: account['sort-code'],
            currency: account['currency'],
          );
        }
//----------//

        print(message);
        break;

      default:
        message = new ChatOutMessage(
          text: msg,
          name: "WzBoo..",
        );
        Tts.speak(msg);
    }

    addMsg(message);
  }
}
</code>```

答:
Change this bloc</p>

```<code>     class ChatMessageModel with ChangeNotifier {
  String data;
  List accntdet;

  ChatmessageService chatservice = ChatmessageService();
  List<Widget> messages = <Widget>[];

  ChatMessageModel() {
    sendMsg("Hi");
  }

  Future handlesubmission(String chattext) {
    Widget message = new ChatInMessage(
      text: chattext,
      name: "Me",
      type: true,
    );
    addMsg(message);
    sendMsg(chattext);
  }

  addMsg(Widget msg) {
    messages.insert(0, msg);
    notifyListeners();
  }

  sendMsg(String msg) {
    chatservice.SendMsg(msg).then((String msg) {
      responseBuilder(msg);
    });
  }

  responseBuilder(String msg) {
    Widget message;
    String identifier = '';

    var arr = msg.split("~");
    if (arr.length > 1) {
      identifier = arr[0];
      msg = arr[1];
    } else {
      msg = arr[0];
    }

    switch (identifier) {
      case 'email_phone':
        message = new Forms(onSubmitted: (String val) {
          Widget a = new ChatInMessage(
            text: val,
            name: "Me",
            type: true,
          );
          addMsg(a);
          sendMsg(val);
        });
        break;

      case 'selfie':
        message = new ImageCamera(onSubmitted: (String imageres) {
          Widget b = new ChatInMessage(
            text: imageres,
            name: "Me",
            type: true,
          );
          sendMsg(imageres);
        });
        addMsg(message);
        break;

      case 'aadhar':
        message = new ImageGalery(onSubmitted: (String imageres) {
          Widget b = new ChatInMessage(
            text: imageres,
            name: "Me",
            type: true,
          );
          sendMsg(imageres);
        });
        break;

      case 'account_info':
        print(msg);
        data = msg;
        String receivedJson = data;
        List<dynamic> list = json.decode(receivedJson);
        accntdet = list;
        int l = list.length;
        print(l);

//------------ the statement --------//
        for (dynamic account in accntdet) {
          message = new AccountInfo(
            l: l,
            iban: account['ibn_no'],
            accno: account['account_no'],
            sort: account['sort-code'],
            currency: account['currency'],
          );
        print(message);
        addMsg(message);
        }
//----------//

        break;

      default:
        message = new ChatOutMessage(
          text: msg,
          name: "WzBoo..",
        );
        Tts.speak(msg);
        addMsg(message);
    }

  }
}
</code>```

Body:
While I tried to fetch data from a JSON am only able to return the first object.
I had mentioned the statement which I think the issue is. I want to return all the available object from the JSON so that I shall display it in a list of cards. I need to return all the JSON objects and pass it to another page containing list of cards. If anyone knows the solution please help me fix it.
Thanks in advance.

import 'dart: convert';
import 'package:flutter/cupertino.dart';
import 'package:tts/tts.dart';
import 'package:wiizboo/service/Chatmsg_service.dart';
import 'package:wiizboo/widget/a%20copy.dart';
import 'package:wiizboo/widget/chat_in_message.dart';
import 'package:wiizboo/widget/chat_out_message.dart';
import 'package:wiizboo/widget/form.dart';
import 'package:wiizboo/widget/image_camera.dart';
import 'package:wiizboo/widget/image_gallery.dart';

class ChatMessageModel with ChangeNotifier {
  String data;
  List accntdet;

  ChatmessageService chatservice = ChatmessageService();
  List<Widget> messages = <Widget>[];

  ChatMessageModel() {
    sendMsg("Hi");
  }

  Future handlesubmission(String chattext) {
    Widget message = new ChatInMessage(
      text: chattext,
      name: "Me",
      type: true,
    );
    addMsg(message);
    sendMsg(chattext);
  }

  addMsg(Widget msg) {
    messages.insert(0, msg);
    notifyListeners();
  }

  sendMsg(String msg) {
    chatservice.SendMsg(msg).then((String msg) {
      responseBuilder(msg);
    });
  }

  responseBuilder(String msg) {
    Widget message;
    String identifier = '';

    var arr = msg.split("~");
    if (arr.length > 1) {
      identifier = arr[0];
      msg = arr[1];
    } else {
      msg = arr[0];
    }

    switch (identifier) {
      case 'email_phone':
        message = new Forms(onSubmitted: (String val) {
          Widget a = new ChatInMessage(
            text: val,
            name: "Me",
            type: true,
          );
          addMsg(a);
          sendMsg(val);
        });
        break;

      case 'selfie':
        message = new ImageCamera(onSubmitted: (String imageres) {
          Widget b = new ChatInMessage(
            text: imageres,
            name: "Me",
            type: true,
          );
          sendMsg(imageres);
        });
        break;

      case 'aadhar':
        message = new ImageGalery(onSubmitted: (String imageres) {
          Widget b = new ChatInMessage(
            text: imageres,
            name: "Me",
            type: true,
          );
          sendMsg(imageres);
        });
        break;

      case 'account_info':
        print(msg);
        data = msg;
        String receivedJson = data;
        List<dynamic> list = json.decode(receivedJson);
        accntdet = list;
        int l = list.length;
        print(l);

//------------ the statement --------//
        for (dynamic account in accntdet) {
          message = new AccountInfo(
            l: l,
            iban: account['ibn_no'],
            accno: account['account_no'],
            sort: account['sort-code'],
            currency: account['currency'],
          );
        }
//----------//

        print(message);
        break;

      default:
        message = new ChatOutMessage(
          text: msg,
          name: "WzBoo..",
        );
        Tts.speak(msg);
    }

    addMsg(message);
  }
}

Body:
Change this bloc

     class ChatMessageModel with ChangeNotifier {
  String data;
  List accntdet;

  ChatmessageService chatservice = ChatmessageService();
  List<Widget> messages = <Widget>[];

  ChatMessageModel() {
    sendMsg("Hi");
  }

  Future handlesubmission(String chattext) {
    Widget message = new ChatInMessage(
      text: chattext,
      name: "Me",
      type: true,
    );
    addMsg(message);
    sendMsg(chattext);
  }

  addMsg(Widget msg) {
    messages.insert(0, msg);
    notifyListeners();
  }

  sendMsg(String msg) {
    chatservice.SendMsg(msg).then((String msg) {
      responseBuilder(msg);
    });
  }

  responseBuilder(String msg) {
    Widget message;
    String identifier = '';

    var arr = msg.split("~");
    if (arr.length > 1) {
      identifier = arr[0];
      msg = arr[1];
    } else {
      msg = arr[0];
    }

    switch (identifier) {
      case 'email_phone':
        message = new Forms(onSubmitted: (String val) {
          Widget a = new ChatInMessage(
            text: val,
            name: "Me",
            type: true,
          );
          addMsg(a);
          sendMsg(val);
        });
        break;

      case 'selfie':
        message = new ImageCamera(onSubmitted: (String imageres) {
          Widget b = new ChatInMessage(
            text: imageres,
            name: "Me",
            type: true,
          );
          sendMsg(imageres);
        });
        addMsg(message);
        break;

      case 'aadhar':
        message = new ImageGalery(onSubmitted: (String imageres) {
          Widget b = new ChatInMessage(
            text: imageres,
            name: "Me",
            type: true,
          );
          sendMsg(imageres);
        });
        break;

      case 'account_info':
        print(msg);
        data = msg;
        String receivedJson = data;
        List<dynamic> list = json.decode(receivedJson);
        accntdet = list;
        int l = list.length;
        print(l);

//------------ the statement --------//
        for (dynamic account in accntdet) {
          message = new AccountInfo(
            l: l,
            iban: account['ibn_no'],
            accno: account['account_no'],
            sort: account['sort-code'],
            currency: account['currency'],
          );
        print(message);
        addMsg(message);
        }
//----------//

        break;

      default:
        message = new ChatOutMessage(
          text: msg,
          name: "WzBoo..",
        );
        Tts.speak(msg);
        addMsg(message);
    }

  }
}


问:
Convert an array which contains strings into key value pairs
I have a string "101-2000-10-102-2000-15" which I have to map as key: 101 values: {2000, 10}.
With the below code I am able to get the output as 101 => 2000 but I am unable to the one remaining value.
This is the Code:

```<code>let myString = "101-2000-10-102-2000-15"
let strArray = myString.match(/[^-]+-[^-]+-[^-]+/g);
console.log(strArray);
let compartmentMap = new Map(strArray.map(x => x.split("-")));
console.log(compartmentMap);
</code>```

My input: "101-2000-10-102-2000-15"
Desired Output: {101 => {2000,10}, 102 => {2000,15}}

答:
One approach would be to just split the string, and then perform a reduce() operation for every three elements:

const s = '101-2000-10-102-2000-15';

const result = s.split('-').reduce((r, v, i, a) =>
    i % 3 ? r : {...r, [v]: a.slice(i + 1, i + 3)}, {});

console.log(result);```

Body:
I have a string "101-2000-10-102-2000-15" which I have to map as key: 101 values: {2000, 10}.
With the below code I am able to get the output as 101 => 2000 but I am unable to the one remaining value.
This is the Code:

let myString = "101-2000-10-102-2000-15"
let strArray = myString.match(/[^-]+-[^-]+-[^-]+/g);
console.log(strArray);
let compartmentMap = new Map(strArray.map(x => x.split("-")));
console.log(compartmentMap);

My input: "101-2000-10-102-2000-15"
Desired Output: {101 => {2000,10}, 102 => {2000,15}}


问:
KeyCloak Authentication Flow with jumbojett/OpenID-Connect-PHP Library
I‘m struggling setting up a secured application with an OpenID provider.

What I have done:

Set up KeyCloak Server

Created simple php Application

Loaded jumbojett library

Configured client

What am I doing:

Try to access my application

Get redirected to my KeyCloak instance

Log in successfully

Get redirected to my application

What the problem is:

The redirect url to my application contains some get parameters as code and so on. The problem is, when I refresh the page, I get an error message: the code can only be used once.

My question is, how can I provide a proper url, which the user can refresh?

答:
I did some research and discovered that I didn't really understand the flow of authentication.

So after the user is redirected to my application, I had to store the Refresh Token in a Session Variable. Afterwards, I was able to redirect the user to the new page.

On the new page I had to check, if a Refresh Token has been stored and if it was valid. If so, I can show the user the content, otherwise, I have to redirect the user to the login page.


问:
alternative to Google maps
My client wants some of the functionality of Google maps namely:
- geocoding
- generating maps with points based on postal code or long.lat
- optimal trip mapping

Their issues with Google maps
- cannot control outages
- postal codes are sometimes inaccurate or not updated frequently for Canada/UK
- they have no way to correct inaccurate information

They would prefer to host the mapping application themselves, but will require postal code updates.

Can anyone suggest such a product?

thanks

答:
Before rushing into rolling your own, I'd suggest a good think about the consequences of doing so. The first that springs to mind is whilst the pros are that you can now control your data, the cons are that you now control your data.

So you are going to have to consider where and when you get updates and the processes you are going to have to employ to keep your maps in sync with the rest of the world. There are a lot of headaches involved in these things which is why so many people use externally hosted solutions such as Googles.

Title: alternative to Google maps


问:
Error - React Native CI - Azure DevOps - Gulp
I'm trying to use Azure DevOps for a React Native app. I'm using gulp to generate an Android App which already has the signing-configs ready and I don't have any problem with it.

My error in Azure DevOps is:

And my .yml file has the following tasks:

Install Node 8.16.0

npm install

Using gulp task to generate the APK

My CI fails at the 3rd step. I googled so many kinds of stuff, all say to check the Node version which should be greater than 6 as you see I'm already on 8.

So far I tried the below three steps and nothing worked for me.

Installing @react-native-community/cli as a dev dependency or
   globally.

Installing gulp globally or as a dev dependency

Generating package.json without lock file and ignoring optional dependencies.

Any idea on how to resolve this?

答:
I was able to solve my issue for now by upgrading to the latest vmImage.

Changing this

```<code>vmImage: 'macOS-latest' #This is macOS Mojave
</code>```

to

```<code>vmImage: 'macOS-10.15' #This is macOS Catalina
</code>```

solved my problem

Body:
I was able to solve my issue for now by upgrading to the latest vmImage.

Changing this

vmImage: 'macOS-latest' #This is macOS Mojave

to

vmImage: 'macOS-10.15' #This is macOS Catalina

solved my problem