问:
plot_partial_dependence() from scikit-learn incorrectly raises NotFittedError for properly fitted models (e.g. KerasRegressor or LGBMClassifier)
I'm trying to create partial dependence plots using sklearn.inspection.plot_partial_dependence on a model that I successfully built using keras and the keras sklearn wrapper utility (see code block below). The wrapped model successfully builds, it can use the fit method, and after fitting it can use the predict method with expected results. All indications are that it's a valid estimator. However, when I try to run plot_partial_dependence from sklearn.inspection, I get some error text implying that it is is not a valid estimator, even though I can demonstrate that it is.

I have edited this to be more easily reproducible by using the sklearn example Boston housing data.

```<code>from sklearn.datasets import load_boston
from sklearn.inspection import plot_partial_dependence, partial_dependence
from keras.wrappers.scikit_learn import KerasRegressor
import keras
import tensorflow as tf
import pandas as pd

boston = load_boston()
feature_names = boston.feature_names
X = pd.DataFrame(boston.data, columns=boston.feature_names)
y = boston.target
mean = X.describe().transpose()['mean']
std = X.describe().transpose()['std']
X_norm = (X-mean)/std

def build_model_small():
    model = keras.Sequential([
        keras.layers.Dense(64, activation='relu', input_shape=[len(X.keys())]),
        keras.layers.Dense(64, activation='relu'),
        keras.layers.Dense(1)
        ])

    optimizer = keras.optimizers.RMSprop(0.0005)

    model.compile(loss='mse',
              optimizer=optimizer,
              metrics=['mae', 'mse', 'mape'])
    return model

kr = KerasRegressor(build_fn=build_model_small,verbose=0)
kr.fit(X_norm,y, epochs=100, validation_split = 0.2)
pdp_plot = plot_partial_dependence(kr,X_norm,feature_names)
</code>```

Like I said, if I run kr.predict(X.head(20)), I get 20 predictions of y values for the first 20 rows of X, as one would expect from a valid estimator.

But the error text I get from plot_partial_dependence is as follows:

```<code>Traceback (most recent call last):
  File "temp_ML_tf_sklearn_postproc.py", line 79, in <module>
    pdp_plot = plot_partial_dependence(kr,X,labels[:-1])
  File "/home/mymachine/anaconda3/lib/python3.7/site-packages/sklearn/inspection/_partial_dependence.py", line 678, in plot_partial_dependence
    for fxs in features)
  File "/home/mymachine/anaconda3/lib/python3.7/site-packages/joblib/parallel.py", line 921, in __call__
    if self.dispatch_one_batch(iterator):
  File "/home/mymachine/anaconda3/lib/python3.7/site-packages/joblib/parallel.py", line 759, in dispatch_one_batch
    self._dispatch(tasks)
  File "/home/mymachine/anaconda3/lib/python3.7/site-packages/joblib/parallel.py", line 716, in _dispatch
    job = self._backend.apply_async(batch, callback=cb)
  File "/home/mymachine/anaconda3/lib/python3.7/site-packages/joblib/_parallel_backends.py", line 182, in apply_async
    result = ImmediateResult(func)
  File "/home/mymachine/anaconda3/lib/python3.7/site-packages/joblib/_parallel_backends.py", line 549, in __init__
    self.results = batch()
  File "/home/mymachine/anaconda3/lib/python3.7/site-packages/joblib/parallel.py", line 225, in __call__
    for func, args, kwargs in self.items]
  File "/home/mymachine/anaconda3/lib/python3.7/site-packages/joblib/parallel.py", line 225, in <listcomp>
    for func, args, kwargs in self.items]
  File "/home/mymachine/anaconda3/lib/python3.7/site-packages/sklearn/inspection/_partial_dependence.py", line 307, in partial_dependence
    "'estimator' must be a fitted regressor or classifier."
ValueError: 'estimator' must be a fitted regressor or classifier.
</code>```

I looked at the source code for plot_partial_dependence, and it had the following to say.
First, in the docstring, it says the first input estimator must be...

```<code>  A fitted estimator object implementing :term:`predict`,
    :term:`predict_proba`, or :term:`decision_function`.
    Multioutput-multiclass classifiers are not supported.
</code>```

My estimator does in deed implement .predict.

Second, the line called out in the errr traceback calls a checker that checks whether it is a regressor or classifier:

```<code>if not (is_classifier(estimator) or is_regressor(estimator)):
    raise ValueError(
        "'estimator' must be a fitted regressor or classifier."
    )
</code>```

I looked into the source code of is_regressor(), and it is a one liner like so:

```<code>return getattr(estimator, "_estimator_type", None) == "regressor"
</code>```

So I tried to sort of hack it by doing setattr(mp,'_estimator_type','regressor') and it just said Attribute Error: can't set attribute, so that's one cheap workaround that didn't work.

I even tried the even hackier fix and temporarily commented out the offending check in the source of _partial_dependence.py (the if statement I copied above), and got the following error:

```<code>Traceback (most recent call last):
  File "temp_ML_tf_sklearn_postproc.py", line 79, in <module>
    pdp_plot = plot_partial_dependence(kr,X,labels[:-1])
  File "/home/billy/anaconda3/lib/python3.7/site-packages/sklearn/inspection/_partial_dependence.py", line 678, in plot_partial_dependence
    for fxs in features)
  File "/home/billy/anaconda3/lib/python3.7/site-packages/joblib/parallel.py", line 921, in __call__
    if self.dispatch_one_batch(iterator):
  File "/home/billy/anaconda3/lib/python3.7/site-packages/joblib/parallel.py", line 759, in dispatch_one_batch
    self._dispatch(tasks)
  File "/home/billy/anaconda3/lib/python3.7/site-packages/joblib/parallel.py", line 716, in _dispatch
    job = self._backend.apply_async(batch, callback=cb)
  File "/home/billy/anaconda3/lib/python3.7/site-packages/joblib/_parallel_backends.py", line 182, in apply_async
    result = ImmediateResult(func)
  File "/home/billy/anaconda3/lib/python3.7/site-packages/joblib/_parallel_backends.py", line 549, in __init__
    self.results = batch()
  File "/home/billy/anaconda3/lib/python3.7/site-packages/joblib/parallel.py", line 225, in __call__
    for func, args, kwargs in self.items]
  File "/home/billy/anaconda3/lib/python3.7/site-packages/joblib/parallel.py", line 225, in <listcomp>
    for func, args, kwargs in self.items]
  File "/home/billy/anaconda3/lib/python3.7/site-packages/sklearn/inspection/_partial_dependence.py", line 317, in partial_dependence
    check_is_fitted(est)
  File "/home/billy/anaconda3/lib/python3.7/site-packages/sklearn/utils/validation.py", line 967, in check_is_fitted
    raise NotFittedError(msg % {'name': type(estimator).__name__})
sklearn.exceptions.NotFittedError: This KerasRegressor instance is not fitted yet. Call 'fit' with appropriate arguments before using this estimator.
</code>```

Which goes all the way back around to the problem of the sklearn functions not thinking this model is fitted, when it really is. Anyway at this point I decided not to try any more dangerous, hacky fixes of tinkering with the source code.

I also tried passing kr.fit(X,y,etc...) directly in as the first argument of plot_partial_dependence. The computer spun up for a few minutes, indicating the fit was in fact running, but then I got the same error once it tried to run the partial dependence plot.

One more rather confusing clue. I tried using the keras/sklearn wrapped pipeline in another sklearn function entirely, to see if it would work with any sklearn utilities at all. This time, I did:

```<code>from sklearn.model_selection import cross_validate
cv_scores = cross_validate(kr,X_norm,y, cv=4, return_train_score=True, n_jobs=-1)`
</code>```

and it worked! So I don't think there is something inherently wrong with my use of keras.wrappers.scikit_learn.KerasRegressor.

This may just be a case where what I'm trying to do is an edge case not planned for in the plot_partial_dependence source code specifically and I'm out of luck, but I'm wondering if anyone else has seen issues like this and has a solution or work-around.

I am using sklearn 0.22.1 and Python 3.7.3 (Anaconda) by the way. And to be clear, I have used plot_partial_dependence on sklearn-built models and even pipelines. This problem is only happening with the keras-based model. Many thanks for any input people may have.

Edit:

The previous version of this question involved building a pipeline with StandardScaler() and then the KerasRegressor wrapped object. Since then I discovered it happens even with just the KerasRegressor object, i.e. I have isolated the problem to that, not the pipeline. So as one commenter suggested, I took the pipeline part out of the question to make it simpler and more to the point.

答:
The issue arises because non-scikit-learn model objects (such as LightGBMRegressor or LGBMClassifier) do not contain an attribute ending in an underscore, which check_is_fitted() uses as a test if the model is fitted (see docs).

So an easy workaround would be to add to your trained model object a dummy attribute with a name ending in an underscore:

```<code>test_model.dummy_ = "dummy"
</code>```

You can also verify that it works by invoking check_if_fitted() yourself:

```<code>from sklearn.utils import validation

validation.check_is_fitted(estimator=test_model)
</code>```

Body:
I'm trying to create partial dependence plots using sklearn.inspection.plot_partial_dependence on a model that I successfully built using keras and the keras sklearn wrapper utility (see code block below). The wrapped model successfully builds, it can use the fit method, and after fitting it can use the predict method with expected results. All indications are that it's a valid estimator. However, when I try to run plot_partial_dependence from sklearn.inspection, I get some error text implying that it is is not a valid estimator, even though I can demonstrate that it is.

I have edited this to be more easily reproducible by using the sklearn example Boston housing data.

from sklearn.datasets import load_boston
from sklearn.inspection import plot_partial_dependence, partial_dependence
from keras.wrappers.scikit_learn import KerasRegressor
import keras
import tensorflow as tf
import pandas as pd

boston = load_boston()
feature_names = boston.feature_names
X = pd.DataFrame(boston.data, columns=boston.feature_names)
y = boston.target
mean = X.describe().transpose()['mean']
std = X.describe().transpose()['std']
X_norm = (X-mean)/std

def build_model_small():
    model = keras.Sequential([
        keras.layers.Dense(64, activation='relu', input_shape=[len(X.keys())]),
        keras.layers.Dense(64, activation='relu'),
        keras.layers.Dense(1)
        ])

    optimizer = keras.optimizers.RMSprop(0.0005)

    model.compile(loss='mse',
              optimizer=optimizer,
              metrics=['mae', 'mse', 'mape'])
    return model

kr = KerasRegressor(build_fn=build_model_small,verbose=0)
kr.fit(X_norm,y, epochs=100, validation_split = 0.2)
pdp_plot = plot_partial_dependence(kr,X_norm,feature_names)

Like I said, if I run kr.predict(X.head(20)), I get 20 predictions of y values for the first 20 rows of X, as one would expect from a valid estimator.

But the error text I get from plot_partial_dependence is as follows:

Traceback (most recent call last):
  File "temp_ML_tf_sklearn_postproc.py", line 79, in <module>
    pdp_plot = plot_partial_dependence(kr,X,labels[:-1])
  File "/home/mymachine/anaconda3/lib/python3.7/site-packages/sklearn/inspection/_partial_dependence.py", line 678, in plot_partial_dependence
    for fxs in features)
  File "/home/mymachine/anaconda3/lib/python3.7/site-packages/joblib/parallel.py", line 921, in __call__
    if self.dispatch_one_batch(iterator):
  File "/home/mymachine/anaconda3/lib/python3.7/site-packages/joblib/parallel.py", line 759, in dispatch_one_batch
    self._dispatch(tasks)
  File "/home/mymachine/anaconda3/lib/python3.7/site-packages/joblib/parallel.py", line 716, in _dispatch
    job = self._backend.apply_async(batch, callback=cb)
  File "/home/mymachine/anaconda3/lib/python3.7/site-packages/joblib/_parallel_backends.py", line 182, in apply_async
    result = ImmediateResult(func)
  File "/home/mymachine/anaconda3/lib/python3.7/site-packages/joblib/_parallel_backends.py", line 549, in __init__
    self.results = batch()
  File "/home/mymachine/anaconda3/lib/python3.7/site-packages/joblib/parallel.py", line 225, in __call__
    for func, args, kwargs in self.items]
  File "/home/mymachine/anaconda3/lib/python3.7/site-packages/joblib/parallel.py", line 225, in <listcomp>
    for func, args, kwargs in self.items]
  File "/home/mymachine/anaconda3/lib/python3.7/site-packages/sklearn/inspection/_partial_dependence.py", line 307, in partial_dependence
    "'estimator' must be a fitted regressor or classifier."
ValueError: 'estimator' must be a fitted regressor or classifier.

I looked at the source code for plot_partial_dependence, and it had the following to say.
First, in the docstring, it says the first input estimator must be...

  A fitted estimator object implementing :term:`predict`,
    :term:`predict_proba`, or :term:`decision_function`.
    Multioutput-multiclass classifiers are not supported.

My estimator does in deed implement .predict.

Second, the line called out in the errr traceback calls a checker that checks whether it is a regressor or classifier:

if not (is_classifier(estimator) or is_regressor(estimator)):
    raise ValueError(
        "'estimator' must be a fitted regressor or classifier."
    )

I looked into the source code of is_regressor(), and it is a one liner like so:

return getattr(estimator, "_estimator_type", None) == "regressor"

So I tried to sort of hack it by doing setattr(mp,'_estimator_type','regressor') and it just said Attribute Error: can't set attribute, so that's one cheap workaround that didn't work.

I even tried the even hackier fix and temporarily commented out the offending check in the source of _partial_dependence.py (the if statement I copied above), and got the following error:

Traceback (most recent call last):
  File "temp_ML_tf_sklearn_postproc.py", line 79, in <module>
    pdp_plot = plot_partial_dependence(kr,X,labels[:-1])
  File "/home/billy/anaconda3/lib/python3.7/site-packages/sklearn/inspection/_partial_dependence.py", line 678, in plot_partial_dependence
    for fxs in features)
  File "/home/billy/anaconda3/lib/python3.7/site-packages/joblib/parallel.py", line 921, in __call__
    if self.dispatch_one_batch(iterator):
  File "/home/billy/anaconda3/lib/python3.7/site-packages/joblib/parallel.py", line 759, in dispatch_one_batch
    self._dispatch(tasks)
  File "/home/billy/anaconda3/lib/python3.7/site-packages/joblib/parallel.py", line 716, in _dispatch
    job = self._backend.apply_async(batch, callback=cb)
  File "/home/billy/anaconda3/lib/python3.7/site-packages/joblib/_parallel_backends.py", line 182, in apply_async
    result = ImmediateResult(func)
  File "/home/billy/anaconda3/lib/python3.7/site-packages/joblib/_parallel_backends.py", line 549, in __init__
    self.results = batch()
  File "/home/billy/anaconda3/lib/python3.7/site-packages/joblib/parallel.py", line 225, in __call__
    for func, args, kwargs in self.items]
  File "/home/billy/anaconda3/lib/python3.7/site-packages/joblib/parallel.py", line 225, in <listcomp>
    for func, args, kwargs in self.items]
  File "/home/billy/anaconda3/lib/python3.7/site-packages/sklearn/inspection/_partial_dependence.py", line 317, in partial_dependence
    check_is_fitted(est)
  File "/home/billy/anaconda3/lib/python3.7/site-packages/sklearn/utils/validation.py", line 967, in check_is_fitted
    raise NotFittedError(msg % {'name': type(estimator).__name__})
sklearn.exceptions.NotFittedError: This KerasRegressor instance is not fitted yet. Call 'fit' with appropriate arguments before using this estimator.

Which goes all the way back around to the problem of the sklearn functions not thinking this model is fitted, when it really is. Anyway at this point I decided not to try any more dangerous, hacky fixes of tinkering with the source code.

I also tried passing kr.fit(X,y,etc...) directly in as the first argument of plot_partial_dependence. The computer spun up for a few minutes, indicating the fit was in fact running, but then I got the same error once it tried to run the partial dependence plot.

One more rather confusing clue. I tried using the keras/sklearn wrapped pipeline in another sklearn function entirely, to see if it would work with any sklearn utilities at all. This time, I did:

from sklearn.model_selection import cross_validate
cv_scores = cross_validate(kr,X_norm,y, cv=4, return_train_score=True, n_jobs=-1)`

and it worked! So I don't think there is something inherently wrong with my use of keras.wrappers.scikit_learn.KerasRegressor.

This may just be a case where what I'm trying to do is an edge case not planned for in the plot_partial_dependence source code specifically and I'm out of luck, but I'm wondering if anyone else has seen issues like this and has a solution or work-around.

I am using sklearn 0.22.1 and Python 3.7.3 (Anaconda) by the way. And to be clear, I have used plot_partial_dependence on sklearn-built models and even pipelines. This problem is only happening with the keras-based model. Many thanks for any input people may have.

Edit:

The previous version of this question involved building a pipeline with StandardScaler() and then the KerasRegressor wrapped object. Since then I discovered it happens even with just the KerasRegressor object, i.e. I have isolated the problem to that, not the pipeline. So as one commenter suggested, I took the pipeline part out of the question to make it simpler and more to the point.

Body:
The issue arises because non-scikit-learn model objects (such as LightGBMRegressor or LGBMClassifier) do not contain an attribute ending in an underscore, which check_is_fitted() uses as a test if the model is fitted (see docs).

So an easy workaround would be to add to your trained model object a dummy attribute with a name ending in an underscore:

test_model.dummy_ = "dummy"

You can also verify that it works by invoking check_if_fitted() yourself:

from sklearn.utils import validation

validation.check_is_fitted(estimator=test_model)


来源: stackexchange

问:
get response.status in .then in Java Script
I tried to check if the status of my request is 200 (OK), but I do not know how to do these things together because the first and second .then, are not "like each other":

function f(path) {
    await fetch(path)
            .then(response => {
                // console.log(response.status);
                if (response.status != 200) {
                    throw response.status;
                } else {
                    // do something
                }
            })
            .then(response => response.json())
            .then(...method for the response.json()...)
            .catch(error => {
                // print some error message
            }
}
```

The second then failed and returned error.

I have a problem when I throw that.

It prints to the error to the console (when I check by changing the path to wrong path and I want to see if I treat errors).

what can I do?

答:
Actually, it's not clear what your function has to do. But I think your sturggle comes from not fully understanding how promises chain works. For that, I'd recommend familiarizing yourself with this article, it helped me a lot :)

So back to your function. The elegant solution is adding simple "tap" function, that allows you to do some stuff with current response, but still it passes response further for other .then chains.

Here's the tap function:

const tap = (callback) => (value) => (callback(value), value);
```
<p>And finally how you can use it:</p>
<pre class="lang-js prettyprint-override"><code>function f(path) {
  fetch(path)
    .then(
      tap((response) => {
        if (response.status !== 200) throw new Error(response.status);
      })
    )
    .then((response) => {
      // do other stuff
    })
    .catch((error) => console.error(error));
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I tried to check if the status of my request is 200 (OK), but I do not know how to do these things together because the first and second .then, are not "like each other":

function f(path) {
    await fetch(path)
            .then(response => {
                // console.log(response.status);
                if (response.status != 200) {
                    throw response.status;
                } else {
                    // do something
                }
            })
            .then(response => response.json())
            .then(...method for the response.json()...)
            .catch(error => {
                // print some error message
            }
}

The second then failed and returned error.

I have a problem when I throw that.

It prints to the error to the console (when I check by changing the path to wrong path and I want to see if I treat errors).

what can I do?

Body:
Actually, it's not clear what your function has to do. But I think your sturggle comes from not fully understanding how promises chain works. For that, I'd recommend familiarizing yourself with this article, it helped me a lot :)

So back to your function. The elegant solution is adding simple "tap" function, that allows you to do some stuff with current response, but still it passes response further for other .then chains.

Here's the tap function:

const tap = (callback) => (value) => (callback(value), value);

And finally how you can use it:

function f(path) {
  fetch(path)
    .then(
      tap((response) => {
        if (response.status !== 200) throw new Error(response.status);
      })
    )
    .then((response) => {
      // do other stuff
    })
    .catch((error) => console.error(error));
}


问:
OneSignal Wordpress Notifications not opening in App
I am struggeling to find a solution for my Cordova Native App.

I am using OneSignal to send out push notifications once a new Article has been published. The push notifications are working fine but the moment I click onto the notification the normal browser opens and not the app.

NB: When I send a test notification through OneSignal and click on it the App opens.
My code just does not want to work with Wordpress articles.

Here's the code which I am using in my index.js

```<code>document.addEventListener('deviceready', function () {
  // Enable to debug issues.
  // window.plugins.OneSignal.setLogLevel({logLevel: 4, visualLevel: 4});

var notificationOpenedCallback = function(jsonData) {
  var additionalData = jsonData.notification.payload.additionalData
  if (additionalData && additionalData.myKey)
    // Not familiar with Cordova, $state may or may not be available here
    $state.go('app.post', {'postId': + additionalData.myKey});
};

  window.plugins.OneSignal
    .startInit("0b8b7e69-1649-4616-XXXXXXX")
    .handleNotificationOpened(notificationOpenedCallback)
    .endInit();

  // Call syncHashedEmail anywhere in your app if you have the user's email.
  // This improves the effectiveness of OneSignal's "best-time" notification scheduling feature.
  // window.plugins.OneSignal.syncHashedEmail(userEmail);
}, false);
</code>```

Has anyone any idea what is possibly wrong with my code?

答:
Just leaving this here, in case someone else can make use of it. </p>

```<code>add_filter('onesignal_send_notification', 'onesignal_send_notication_filter_push', 10, 4);

function onesignal_send_notication_filter_push($fields, $new_status, $old_status, $post)
{
    $fields['isAndroid'] = true;
    $fields['isIos'] = true;
    $fields['isAnyWeb'] = false;
    $fields['isChrome'] = false;
    // overwrite http url with app_url so push notifications opens app instead of phone browser.
    $fields['url'] = $fields['app_url'];

    return $fields;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am struggeling to find a solution for my Cordova Native App.

I am using OneSignal to send out push notifications once a new Article has been published. The push notifications are working fine but the moment I click onto the notification the normal browser opens and not the app.

NB: When I send a test notification through OneSignal and click on it the App opens.
My code just does not want to work with Wordpress articles.

Here's the code which I am using in my index.js

document.addEventListener('deviceready', function () {
  // Enable to debug issues.
  // window.plugins.OneSignal.setLogLevel({logLevel: 4, visualLevel: 4});

var notificationOpenedCallback = function(jsonData) {
  var additionalData = jsonData.notification.payload.additionalData
  if (additionalData && additionalData.myKey)
    // Not familiar with Cordova, $state may or may not be available here
    $state.go('app.post', {'postId': + additionalData.myKey});
};

  window.plugins.OneSignal
    .startInit("0b8b7e69-1649-4616-XXXXXXX")
    .handleNotificationOpened(notificationOpenedCallback)
    .endInit();

  // Call syncHashedEmail anywhere in your app if you have the user's email.
  // This improves the effectiveness of OneSignal's "best-time" notification scheduling feature.
  // window.plugins.OneSignal.syncHashedEmail(userEmail);
}, false);

Has anyone any idea what is possibly wrong with my code?

Body:
Just leaving this here, in case someone else can make use of it.

add_filter('onesignal_send_notification', 'onesignal_send_notication_filter_push', 10, 4);

function onesignal_send_notication_filter_push($fields, $new_status, $old_status, $post)
{
    $fields['isAndroid'] = true;
    $fields['isIos'] = true;
    $fields['isAnyWeb'] = false;
    $fields['isChrome'] = false;
    // overwrite http url with app_url so push notifications opens app instead of phone browser.
    $fields['url'] = $fields['app_url'];

    return $fields;
}


问:
Where do I find Application cursor files in MacOS?
I'm specifically looking to find the files for the tool cursors in Final Cut Pro X.
Any help would be great thanks.

答:
These cursors don't look like system cursors, so they are the custom ones.

You can look at the system cursors ("pointers") here: https://support.apple.com/guide/mac-help/pointers-in-macos-mh35695/mac

The custom images should be located in Final Cut Pro X.app/Contents/Resources - just right-mouse-click on your Final Cut Pro X.app, select Show Package Contents, then navigate to Resources folder.

There should be a lot on png icons.


问:
how to force sleep or any other type of timer to execute at particular time in c++?
I am doing socket programming in C and I want to do the following thing:

```<code>pid = fork();
if(pid == 0){
    //child process
    for(int m=0;m<2;m++){
        j=0;
        for(i=0;i<len_neighbors;i++){
            socket_des1[i] = get_socket_connection_client(hostname1, neighbor_socket[i],(char *) "udp");
            //sending data to other routers
            cout<<"\nMessage: Sending routing table to neighbor, "<<neighbors[i];
            if (send(socket_des1[i], &message1[0], message1.length(), 0) < 0){
                perror("\nError:Message sending failed\n");
                exit(1);
            }
            j++;
        }
        for(i=0;i<len_neighbors;i++){
            close(socket_des1[i]);
        }
        sleep(30);
        cout<<"Hello";
    }
}else{
    // code for parent process
}
</code>```

So basically the process will send data to all the neighbors and the goto sleep. What is happening here is the process sends data to first neighbor and then sleeps for 30secs. How do I force the process to finish sending and then execute sleep(30) statement.

I am using forking for the process. And the code above is part of child process.

答: It seems you try use send function with udp protocol. It is wrong. use sendto   </p>

Body:
I am doing socket programming in C and I want to do the following thing:

pid = fork();
if(pid == 0){
    //child process
    for(int m=0;m<2;m++){
        j=0;
        for(i=0;i<len_neighbors;i++){
            socket_des1[i] = get_socket_connection_client(hostname1, neighbor_socket[i],(char *) "udp");
            //sending data to other routers
            cout<<"\nMessage: Sending routing table to neighbor, "<<neighbors[i];
            if (send(socket_des1[i], &message1[0], message1.length(), 0) < 0){
                perror("\nError:Message sending failed\n");
                exit(1);
            }
            j++;
        }
        for(i=0;i<len_neighbors;i++){
            close(socket_des1[i]);
        }
        sleep(30);
        cout<<"Hello";
    }
}else{
    // code for parent process
}

So basically the process will send data to all the neighbors and the goto sleep. What is happening here is the process sends data to first neighbor and then sleeps for 30secs. How do I force the process to finish sending and then execute sleep(30) statement.

I am using forking for the process. And the code above is part of child process.


问:
How to pass epoch timestamp in each requests of Gatling script dynamically
I have to pass current epoch timestamp in below "request_1" and "request_2" dynamically. How can I achieve this. Below are just few requests given, actually there are many requests in scripts.

Here all requests should have current timestamp only. So each requests will have different different timestamp.

Is there any function so that I can replace all timestamp directly without replacing one by one.

```<code>  val Transaction_Name_1 = group("Transaction_Name_1")
  {
      exec(http("request_1")
        .get("/abc/details1?_=1590748529401"))
      .pause(5)
      .exec(http("request_2")
        .get("/abc/details1?_=1590748535534"))
  }
</code>```

答:
There's no way to magically do this everywhere. You have to replace each occurrence.

As of Gatling 3.3.1 (current version as of now), the easiest way is to do:

val Transaction_Name_1 = group("Transaction_Name_1") {
  exec(http("request_1")
    .get(session => "/abc/details1?_=" + System.currentTimeMillis()))
  .pause(5)
  .exec(http("request_2")
    .get(session => "/abc/details1?_=" + System.currentTimeMillis()))
}
```

<p>In Gatling 3.4.0, we'll be introducing a new Gatling EL feature so you will be able to write:</p>

<pre class="lang-scala prettyprint-override"><code>val Transaction_Name_1 = group("Transaction_Name_1") {
  exec(http("request_1")
    .get("/abc/details1?_=${currentTimeMillis()}")
  .pause(5)
  .exec(http("request_2")
    .get("/abc/details1?_=${currentTimeMillis()}"))
}
</code>```

Body:
I have to pass current epoch timestamp in below "request_1" and "request_2" dynamically. How can I achieve this. Below are just few requests given, actually there are many requests in scripts.

Here all requests should have current timestamp only. So each requests will have different different timestamp.

Is there any function so that I can replace all timestamp directly without replacing one by one.

  val Transaction_Name_1 = group("Transaction_Name_1")
  {
      exec(http("request_1")
        .get("/abc/details1?_=1590748529401"))
      .pause(5)
      .exec(http("request_2")
        .get("/abc/details1?_=1590748535534"))
  }

Body:
There's no way to magically do this everywhere. You have to replace each occurrence.

As of Gatling 3.3.1 (current version as of now), the easiest way is to do:

val Transaction_Name_1 = group("Transaction_Name_1") {
  exec(http("request_1")
    .get(session => "/abc/details1?_=" + System.currentTimeMillis()))
  .pause(5)
  .exec(http("request_2")
    .get(session => "/abc/details1?_=" + System.currentTimeMillis()))
}

In Gatling 3.4.0, we'll be introducing a new Gatling EL feature so you will be able to write:

val Transaction_Name_1 = group("Transaction_Name_1") {
  exec(http("request_1")
    .get("/abc/details1?_=${currentTimeMillis()}")
  .pause(5)
  .exec(http("request_2")
    .get("/abc/details1?_=${currentTimeMillis()}"))
}


问:
Memoize Reselect selector output based on a single input selector instead of all
I have a Reselect selector that maps an array of chosen ids into objects from a normalized store.

```<code>const activeObjectsSelector = createSelector(
  state => state.activeIds,
  state => state.objects.byId,
  (activeIds, objectsById) => activeIds.map(id => objectsById[id])
)
</code>```

The problem is that it busts the cache and re-runs anytime new objects are added to the normalized store, because the value of state.objects.byId changes. The only change I care about busting the cache is the value of state.activeIds. Is this possible?

答:
You can use defaultMemoize of reselect for this to memoize the result of the map by passing it to a memoized function that will take the items of the array as arguments:

const { createSelector, defaultMemoize } = Reselect;
const state = {
  activeIds: [1, 2],
  objects: {
    1: { name: 'one' },
    2: { name: 'two' },
    3: { name: 'three' },
  },
};
const selectActiveIds = (state) => state.activeIds;
const selectObjects = (state) => state.objects;
const createMemoizedArray = () => {
  const memArray = defaultMemoize((...array) => array);
  return (array) => memArray.apply(null, array);
};
const createSelectAcitiveObjects = () => {
  const memoizedArray = createMemoizedArray();
  return createSelector(
    selectActiveIds,
    selectObjects,
    (ids, objects) =>
      memoizedArray(ids.map((id) => objects[id]))
  );
};
const selectAcitiveObjects = createSelectAcitiveObjects();
const one = selectAcitiveObjects(state);
console.log('one is:',one);
const two = selectAcitiveObjects(state);
console.log('one is two', two === one);
const newState = { ...state, activeIds: [1, 2, 3] };
const three = selectAcitiveObjects(newState);
console.log('three is two', three === two);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/reselect/4.0.0/reselect.min.js"></script>

<div id="root"></div></code>```

Body:
I have a Reselect selector that maps an array of chosen ids into objects from a normalized store.

const activeObjectsSelector = createSelector(
  state => state.activeIds,
  state => state.objects.byId,
  (activeIds, objectsById) => activeIds.map(id => objectsById[id])
)

The problem is that it busts the cache and re-runs anytime new objects are added to the normalized store, because the value of state.objects.byId changes. The only change I care about busting the cache is the value of state.activeIds. Is this possible?

Body:
You can use defaultMemoize of reselect for this to memoize the result of the map by passing it to a memoized function that will take the items of the array as arguments:

const { createSelector, defaultMemoize } = Reselect;
const state = {
  activeIds: [1, 2],
  objects: {
    1: { name: 'one' },
    2: { name: 'two' },
    3: { name: 'three' },
  },
};
const selectActiveIds = (state) => state.activeIds;
const selectObjects = (state) => state.objects;
const createMemoizedArray = () => {
  const memArray = defaultMemoize((...array) => array);
  return (array) => memArray.apply(null, array);
};
const createSelectAcitiveObjects = () => {
  const memoizedArray = createMemoizedArray();
  return createSelector(
    selectActiveIds,
    selectObjects,
    (ids, objects) =>
      memoizedArray(ids.map((id) => objects[id]))
  );
};
const selectAcitiveObjects = createSelectAcitiveObjects();
const one = selectAcitiveObjects(state);
console.log('one is:',one);
const two = selectAcitiveObjects(state);
console.log('one is two', two === one);
const newState = { ...state, activeIds: [1, 2, 3] };
const three = selectAcitiveObjects(newState);
console.log('three is two', three === two);

<script src="https://cdnjs.cloudflare.com/ajax/libs/reselect/4.0.0/reselect.min.js"></script>

<div id="root"></div>


问:
How do I release only changes project from multiple project in one .sln?
I have 7 projects in one .sln. I am using azure devops. There is 4 api and 3 web. I have created two different pipeline for api and web. When commit then both pipeline is triggered.

What I want....

I want only changes project will trigger, build and release. If project 1 is changes then only build and release project 1. Others no.

How do I manage this?

Currently for one change all projects are building and releasing.

答:
Firts of all, if you want only the project you change to trigger the pipeline, you have to create one "pipeline->release" for each project.

When I want something like this normally I create a pipeline whith my build template and then change the trigger option:

Go to edit your pipeline:

And then add the path of the project you want to trigger this pipeline.

So with this you will have a diferent artifact for each project and you will be able to have release only the project you push your changes.

I hope this work for you too!


问:
Export vs. check out in SVN
What does exporting do in SVN? Are there any major differences between checking out a copy and export?</p>

答:
When you do an svn export, you don't create the .svn directories. This is good when you don't want those directories. For example, I have my web-page under Subversion revision control. I can do a svn export to where my webpage should reside, and I end up with just the files and not the .svn directories.

However, without the .svn directories, you don't have any versioning information. You can't update your directory. You can't commit changes you make. You can't do diffs, run blames, or do anything else that requires the versioning information stored in those .svn directories.

Title: Export vs. check out in SVN


问:
Portable method to get a list of accepted color names with tkinter
It seems that Python Tkinter and Tcl/Tk ask the system for color names and do not maintain it themselves.  Looking at the standard Python/Tcl/Tk sources does not show any of those colors. You can only find them in color.n which is part of the Tk documentation and in an optional pygment library.

Is there a portable way to ask the system itself (and not any other source which might or might not match the system one) through Python and Tkinter or any other GUI library, for a list of the available color names?

This was previously marked as a duplicate of Named colors in tkinter, but the only answer there involves reading /etc and so is Linux-specific.  I am looking for a portable method that would work with Linux, Windows, and Mac.

答:
you can validate the color :  widget.winfo_rgb('color')

If color string is wrong the error arises


问:
use RSA encrypt/decrypt for client/server side on unity and node js
i working on a Online game with Unity and Node JS.

i used Node-RSA in my node js (server side) for Encrypt and Decrypt messages.
i create public key and private key in hear now i have this two keys on server.

now i want to make same keys in C# (unity) for Decrypt messages and Encrypt message for send to server.
in c# i used

```<code>RSACryptoServiceProvider
</code>```

create this two RSAParameters

```<code>private RSAParameters PrivateKey;
private RSAParameters PublickKey;
</code>```

but i don't now how can i change key value in them an put my server keys into them.

答:
try it in node js</p>

```<code> const NodeRSA   = require('node-rsa');
 const key       = new NodeRSA('-----BEGIN RSA PRIVATE KEY-----PRIVATE_key-----
 END RSA PRIVATE KEY-----");
 const text = 'helo';
 const encrypted = key.encrypt(text, 'base64');
 console.log('encrypted: ', encrypted);
</code>```

Body:
i working on a Online game with Unity and Node JS.

i used Node-RSA in my node js (server side) for Encrypt and Decrypt messages.
i create public key and private key in hear now i have this two keys on server.

now i want to make same keys in C# (unity) for Decrypt messages and Encrypt message for send to server.
in c# i used

RSACryptoServiceProvider

create this two RSAParameters

private RSAParameters PrivateKey;
private RSAParameters PublickKey;

but i don't now how can i change key value in them an put my server keys into them.

Body:
try it in node js

 const NodeRSA   = require('node-rsa');
 const key       = new NodeRSA('-----BEGIN RSA PRIVATE KEY-----PRIVATE_key-----
 END RSA PRIVATE KEY-----");
 const text = 'helo';
 const encrypted = key.encrypt(text, 'base64');
 console.log('encrypted: ', encrypted);


问:
How to reformat date from 26-MAY-20 03.43.48.861000000 to 'yyyy-mm-dd hh:mm:ss'?
How would I convert '26-MAY-20 03.43.48.861000000' into 'yyyy-mm-dd hh:mm:ss' using datetime in Python ?

答:
pandas.to_datetime would also parse the nanoseconds (I've modified the timestring to have some...):

```<code>import pandas as pd
t = pd.to_datetime('26-MAY-20 03.43.48.861000100', format="%d-%b-%y %H.%M.%S.%f")

t
Out[41]: Timestamp('2020-05-26 03:43:48.861000100')

t.microsecond
Out[42]: 861000

t.nanosecond
Out[43]: 100
</code>```

Body:
pandas.to_datetime would also parse the nanoseconds (I've modified the timestring to have some...):

import pandas as pd
t = pd.to_datetime('26-MAY-20 03.43.48.861000100', format="%d-%b-%y %H.%M.%S.%f")

t
Out[41]: Timestamp('2020-05-26 03:43:48.861000100')

t.microsecond
Out[42]: 861000

t.nanosecond
Out[43]: 100


问:
MySQL - Multiple Queries or Single Query
So I have a table that contains votes. The relevant columns for this issue being user and timestamp.

I need to grab the user's total vote count, and also their votes this month.

I know the queries - I'm not asking for those. I use these at the same time:

Votes this month / Total votes:

```<code>SELECT COUNT( 0 ) FROM votes WHERE ( timestamp BETWEEN DATE_FORMAT( NOW( ) ,'%Y-%m-01' ) AND NOW( ) ) AND user = ?;

SELECT COUNT( 0 ) FROM votes WHERE user = ?;
</code>```

At the moment, my database isn't large enough (or even queried enough) to where performance is an issue. However, that's expected to change shortly. Should I keep the queries separate, or should I:

```<code>SELECT COUNT( 0 ) AS totalVotes,
       SUM( IF( timestamp BETWEEN DATE_FORMAT( NOW( ) ,'%Y-%m-01' )
                              AND NOW( ), 1, 0 ) ) AS votesThisMonth
    FROM votes WHERE user = ?;
</code>```

What is the best practice? Are there any tips for querying multiple bits of information from the same table to prevent having to search it twice? Is my combined query even what I should be using?

Thanks!

答:
In MySQL, I would recommend:

```<code>SELECT COUNT(*) AS totalVotes,
       SUM(EXTRACT(YEAR_MONTH FROM timestamp) = EXTRACT(YEAR_MONTH FROM NOW())) AS votesThisMonth
FROM votes
WHERE user = ?;
</code>```

An alternative to the above is:

```<code> SUM(timestamp >= CURRENT_DATE - (DAY(CURRENT_DATE) - 1) DAY)
</code>```

I strongly discourage you from using strings for dates, unless you really have to.  There are multiple ways to get values from the current date that do NOT involves implicitly or explicitly converting a date/time value to a string.

Also, the IF() is redundant.  MySQL allows you to just add up boolean values.  Neither is standard SQL, so you might as well use the more concise version.

The COUNT(0) is jarring to me.  Although it works, COUNT(*) or COUNT(1) seem simpler.

Body:
So I have a table that contains votes. The relevant columns for this issue being user and timestamp.

I need to grab the user's total vote count, and also their votes this month.

I know the queries - I'm not asking for those. I use these at the same time:

Votes this month / Total votes:

SELECT COUNT( 0 ) FROM votes WHERE ( timestamp BETWEEN DATE_FORMAT( NOW( ) ,'%Y-%m-01' ) AND NOW( ) ) AND user = ?;

SELECT COUNT( 0 ) FROM votes WHERE user = ?;

At the moment, my database isn't large enough (or even queried enough) to where performance is an issue. However, that's expected to change shortly. Should I keep the queries separate, or should I:

SELECT COUNT( 0 ) AS totalVotes,
       SUM( IF( timestamp BETWEEN DATE_FORMAT( NOW( ) ,'%Y-%m-01' )
                              AND NOW( ), 1, 0 ) ) AS votesThisMonth
    FROM votes WHERE user = ?;

What is the best practice? Are there any tips for querying multiple bits of information from the same table to prevent having to search it twice? Is my combined query even what I should be using?

Thanks!

Body:
In MySQL, I would recommend:

SELECT COUNT(*) AS totalVotes,
       SUM(EXTRACT(YEAR_MONTH FROM timestamp) = EXTRACT(YEAR_MONTH FROM NOW())) AS votesThisMonth
FROM votes
WHERE user = ?;

An alternative to the above is:

 SUM(timestamp >= CURRENT_DATE - (DAY(CURRENT_DATE) - 1) DAY)

I strongly discourage you from using strings for dates, unless you really have to.  There are multiple ways to get values from the current date that do NOT involves implicitly or explicitly converting a date/time value to a string.

Also, the IF() is redundant.  MySQL allows you to just add up boolean values.  Neither is standard SQL, so you might as well use the more concise version.

The COUNT(0) is jarring to me.  Although it works, COUNT(*) or COUNT(1) seem simpler.


问:
Jquery $(this) node and its use
I am trying to understand some jquery code that uses a $(this) node.  What is it used for and when can it be used?

```<code>$("li").hover(border, noBorder);
function border()
{
    $(this).css("border", "1px solid black");
}
</code>```

答: you can use it like this http://jsfiddle.net/HwmEK/7/</p>

Title: Jquery $(this) node and its use

Body:
I am trying to understand some jquery code that uses a $(this) node.  What is it used for and when can it be used?

$("li").hover(border, noBorder);
function border()
{
    $(this).css("border", "1px solid black");
}


问:
Raise an Event Except when something happpen
Scenario: Only If the user follow the path Click on ListView > Click on Button the Button1 do something.

In other word I want to check in Button1_Click(object sender, EventArgs e) if the previous focus was on ListView.

So I tried this:

```<code>private void ListView_Test_Leave(object sender, EventArgs e)
    {
        _focusedControl = null;
    }
</code>```

I want raise previous event except when this event is raised:

```<code>    private void Button1_Click(object sender, EventArgs e)
        {
            if(_focusedControl == listView_Test)
            {
                // ...
            }
        }
</code>```

Edit:   I have a variable that holds a reference to the currently focused control:

```<code>private Control _focusedControl;
</code>```

and I update it in this way:

```<code>    private void ListView_Test_GotFocus(object sender, EventArgs e)
    {
        _focusedControl = (Control)sender;
    }
</code>```

If the user follow the path Click on ListView > Click on Button I want raise only the Button1_Click event, in all other case I want normal raise.

答:
You could use a helper variable.

```<code>bool wasRaised=false;
private void Button1_Click(object sender, EventArgs e) { wasRaised=true;}
</code>```

Then you can check that variable in your event, and only run if it is false.

Body:
Scenario: Only If the user follow the path Click on ListView > Click on Button the Button1 do something.

In other word I want to check in Button1_Click(object sender, EventArgs e) if the previous focus was on ListView.

So I tried this:

private void ListView_Test_Leave(object sender, EventArgs e)
    {
        _focusedControl = null;
    }

I want raise previous event except when this event is raised:

    private void Button1_Click(object sender, EventArgs e)
        {
            if(_focusedControl == listView_Test)
            {
                // ...
            }
        }

Edit:   I have a variable that holds a reference to the currently focused control:

private Control _focusedControl;

and I update it in this way:

    private void ListView_Test_GotFocus(object sender, EventArgs e)
    {
        _focusedControl = (Control)sender;
    }

If the user follow the path Click on ListView > Click on Button I want raise only the Button1_Click event, in all other case I want normal raise.

Body:
You could use a helper variable.

bool wasRaised=false;
private void Button1_Click(object sender, EventArgs e) { wasRaised=true;}

Then you can check that variable in your event, and only run if it is false.


问:
About " echo Test > Test.txt"
I wanna create a txt file only using a batch file that has multiple lines in it
For example :

In the txt file it will have:

I like to program

But I also like my name

But I cannot do that with :

```<code>echo I Like to program, But I also like my name > Test.txt
</code>```

Any help with this?

答:
Is this what you're trying to do?

@(  Echo I Like to program
    Echo But I also like my name
    Echo This is my next line
    Echo This is my etc. …
) 1> "Test.txt"
```

Title: About " echo Test > Test.txt"

Body:
I wanna create a txt file only using a batch file that has multiple lines in it
For example :

In the txt file it will have:

I like to program

But I also like my name

But I cannot do that with :

echo I Like to program, But I also like my name > Test.txt

Any help with this?


问:
In a simple Viewbag.Title, getting a RuntimeBinderException
I have a really simple ViewBag.Title. Like this:

```<code>@{
    ViewBag.Title = "My Title";
    ViewBag.MiniTitle = "Sub - Title";
}
</code>```

Which is being parsed on _Layout.cshtml, on the

```<code><title>@ViewBag.Title</title>
</code>```

However, I am getting this exception:

```<code>Thrown: "'System.Dynamic.DynamicObject' does not contain a definition for 'Title'"
(Microsoft.CSharp.RuntimeBinder.RuntimeBinderException)
Exception Message = "'System.Dynamic.DynamicObject' does not contain a definition for
'Title'", Exception Type = "Microsoft.CSharp.RuntimeBinder.RuntimeBinderException"
</code>```

I been searching and I could not find much information about it. It is basically the same issue this guy was facing: http://forums.asp.net/t/1715878.aspx?MVC3+Razor+Viewbag+Title+RuntimeBinderException

My issue is also the same as last guy that posted. This does not cause any problems for me, projects works fine and so does my titles. However, I am not liking the fact that an exception is being thrown due to the fact they are expensive.

Does anyone know how can i fix this issue? Thanks!

答: I was getting a similar issue.  The only way I could fix it was by changing ViewBag.Title, for instance, to ViewData["Title"].  Technically, ViewBag and ViewData are the same thing and ViewData is faster to use but you have to type cast... But if it was a string anyway it appears to work fine with no cast since it'll call ToString automatically.</p>

Body:
I have a really simple ViewBag.Title. Like this:

@{
    ViewBag.Title = "My Title";
    ViewBag.MiniTitle = "Sub - Title";
}

Which is being parsed on _Layout.cshtml, on the

<title>@ViewBag.Title</title>

However, I am getting this exception:

Thrown: "'System.Dynamic.DynamicObject' does not contain a definition for 'Title'"
(Microsoft.CSharp.RuntimeBinder.RuntimeBinderException)
Exception Message = "'System.Dynamic.DynamicObject' does not contain a definition for
'Title'", Exception Type = "Microsoft.CSharp.RuntimeBinder.RuntimeBinderException"

I been searching and I could not find much information about it. It is basically the same issue this guy was facing: http://forums.asp.net/t/1715878.aspx?MVC3+Razor+Viewbag+Title+RuntimeBinderException

My issue is also the same as last guy that posted. This does not cause any problems for me, projects works fine and so does my titles. However, I am not liking the fact that an exception is being thrown due to the fact they are expensive.

Does anyone know how can i fix this issue? Thanks!


问:
Unable to define first layer of DNN in keras
I was trying to design a multi-class Classification NN.

My train_x dataset contains 23 examples each containing 37 features (dimension : 23*37)

train_y contains output for each example (dimension : 23*7) [ 7 Labels/Classes ]. I used one-hot encoding for each example's output.

len(words) is the number of features
This is my model design :

```<code>model = tf.keras.models.Sequential([
    tf.keras.layers.Dense(units=len(words), input_shape=[len(words)]),
    tf.keras.layers.Dense(8, activation="relu"),
    tf.keras.layers.Dense(8, activation="relu"),
    tf.keras.layers.Dense(len(labels), activation="softmax")
])

</code>```

For optimizer I used Adam Optimizer and for loss function I used Sparse Categorical Entropy.

```<code>model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=['accuracy'])
model.fit(train_x, train_y, epochs=100)
</code>```

I am getting the following traceback call:

```<code>Epoch 1/100
Traceback (most recent call last):
  File "main.py", line 83, in <module>
    model.fit(train_x, train_y, epochs=100, callbacks=[callbacks])
  File "C:\Users\aaman\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\keras\engine\training.py", line 66, in _method_wrapper
    return method(self, *args, **kwargs)
  File "C:\Users\aaman\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\keras\engine\training.py", line 848, in fit
    tmp_logs = train_function(iterator)
  File "C:\Users\aaman\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\eager\def_function.py", line 580, in __call__
    result = self._call(*args, **kwds)
  File "C:\Users\aaman\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\eager\def_function.py", line 644, in _call
    return self._stateless_fn(*args, **kwds)
  File "C:\Users\aaman\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\eager\function.py", line 2420, in __call__
    return graph_function._filtered_call(args, kwargs)  # pylint: disable=protected-access
  File "C:\Users\aaman\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\eager\function.py", line 1661, in _filtered_call
    return self._call_flat(
  File "C:\Users\aaman\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\eager\function.py", line 1745, in _call_flat
    return self._build_call_outputs(self._inference_function.call(
  File "C:\Users\aaman\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\eager\function.py", line 593, in call
    outputs = execute.execute(
  File "C:\Users\aaman\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\eager\execute.py", line 59, in quick_execute
    tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
tensorflow.python.framework.errors_impl.InvalidArgumentError:  logits and labels must have the same first dimension, got logits shape [23,7] and labels shape [161]
         [[node sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits (defined at main.py:83) ]] [Op:__inference_train_function_709]

Function call stack:
train_function
</code>```

I have been searching in various sites for two days. But all of them flattens the input data for first layer. All of them use either grey scale images or RGB images as input. All of them requires the first layer to be flattened. But my input data is already flattened.

As much I am understanding this, I am getting the traceback call for the first layer. I may have misunderstood the concept of units and input_shape, thus defining them incorrectly.

答: Change sparse_categorical_crossentropy to categorical_crossentropy.

Body:
I was trying to design a multi-class Classification NN.

My train_x dataset contains 23 examples each containing 37 features (dimension : 23*37)

train_y contains output for each example (dimension : 23*7) [ 7 Labels/Classes ]. I used one-hot encoding for each example's output.

len(words) is the number of features
This is my model design :

model = tf.keras.models.Sequential([
    tf.keras.layers.Dense(units=len(words), input_shape=[len(words)]),
    tf.keras.layers.Dense(8, activation="relu"),
    tf.keras.layers.Dense(8, activation="relu"),
    tf.keras.layers.Dense(len(labels), activation="softmax")
])

For optimizer I used Adam Optimizer and for loss function I used Sparse Categorical Entropy.

model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=['accuracy'])
model.fit(train_x, train_y, epochs=100)

I am getting the following traceback call:

Epoch 1/100
Traceback (most recent call last):
  File "main.py", line 83, in <module>
    model.fit(train_x, train_y, epochs=100, callbacks=[callbacks])
  File "C:\Users\aaman\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\keras\engine\training.py", line 66, in _method_wrapper
    return method(self, *args, **kwargs)
  File "C:\Users\aaman\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\keras\engine\training.py", line 848, in fit
    tmp_logs = train_function(iterator)
  File "C:\Users\aaman\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\eager\def_function.py", line 580, in __call__
    result = self._call(*args, **kwds)
  File "C:\Users\aaman\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\eager\def_function.py", line 644, in _call
    return self._stateless_fn(*args, **kwds)
  File "C:\Users\aaman\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\eager\function.py", line 2420, in __call__
    return graph_function._filtered_call(args, kwargs)  # pylint: disable=protected-access
  File "C:\Users\aaman\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\eager\function.py", line 1661, in _filtered_call
    return self._call_flat(
  File "C:\Users\aaman\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\eager\function.py", line 1745, in _call_flat
    return self._build_call_outputs(self._inference_function.call(
  File "C:\Users\aaman\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\eager\function.py", line 593, in call
    outputs = execute.execute(
  File "C:\Users\aaman\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\eager\execute.py", line 59, in quick_execute
    tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
tensorflow.python.framework.errors_impl.InvalidArgumentError:  logits and labels must have the same first dimension, got logits shape [23,7] and labels shape [161]
         [[node sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits (defined at main.py:83) ]] [Op:__inference_train_function_709]

Function call stack:
train_function

I have been searching in various sites for two days. But all of them flattens the input data for first layer. All of them use either grey scale images or RGB images as input. All of them requires the first layer to be flattened. But my input data is already flattened.

As much I am understanding this, I am getting the traceback call for the first layer. I may have misunderstood the concept of units and input_shape, thus defining them incorrectly.


问:
Java How to get the percentage between 2 datetimes
I want get the percentage between two DateTimes so i can use a progress bar.

I have the following code i'm passing in two datetimes and doing the sum but i am getting an error.

```<code>private void getpercentage(String dateTimeStart, String dateTimeExpiration) {

    LocalDateTime start = LocalDateTime.parse(dateTimeStart.replace( " " , "T" ) );
    LocalDateTime end = LocalDateTime.parse(dateTimeExpiration.replace( " " , "T" ) );
    String start_date = start.toString().replace( "T", " " );
    String end_date = end.toString().replace( "T", " " );
    String p = Math.round( (end_date - start_date) * 100) + '%';
    Log.d("type", "Date parsed : " + p);

}
</code>```

答:
You can’t do that correctly without taking time zone into account.

```<code>private void getpercentage(String dateTimeStart, String dateTimeExpiration) {
    ZoneId zone = ZoneId.systemDefault();

    ZonedDateTime start = LocalDateTime.parse(dateTimeStart.replace( " " , "T" ) )
            .atZone(zone);
    ZonedDateTime end = LocalDateTime.parse(dateTimeExpiration.replace( " " , "T" ) )
            .atZone(zone);

    long total = ChronoUnit.MICROS.between(start, end);
    long passed = ChronoUnit.MICROS.between(start, ZonedDateTime.now(zone));

    long percentage = passed * 100 / total;

    System.out.println(String.valueOf(percentage) + " %");
}
</code>```

To see how much of the day has passed:

```<code>    getpercentage("2020-05-30 00:00:00", "2020-05-31 00:00:00");
</code>```

When run right now in my time zone, Europe/Copenhagen:

91 %

To illustrate my point about time zone: when instead run in Indian/Maldives time zone:

103 %

So in that time zone 30th May is already over and we’re 3 % into 31st May.

Using the long type and ChronoUnit.MICROS (microseconds) will work for spans of time up to 290 000 years. For a longer span, choose a coarrser unit. For more accuracy and a shorter span, use a finer unit, that is, nanoseconds.

Java 9 and later

```<code>long percentage = Duration.between(start, ZonedDateTime.now(zone))
        .multipliedBy(100)
        .dividedBy(Duration.between(start, end));
</code>```

The overloaded Duration.dividedBy(Duration) method was introduced in Java 9. This allows us to use the Duration class for the calculation so we don’t need to decide on a specific time unit.

Body:
I want get the percentage between two DateTimes so i can use a progress bar.

I have the following code i'm passing in two datetimes and doing the sum but i am getting an error.

private void getpercentage(String dateTimeStart, String dateTimeExpiration) {

    LocalDateTime start = LocalDateTime.parse(dateTimeStart.replace( " " , "T" ) );
    LocalDateTime end = LocalDateTime.parse(dateTimeExpiration.replace( " " , "T" ) );
    String start_date = start.toString().replace( "T", " " );
    String end_date = end.toString().replace( "T", " " );
    String p = Math.round( (end_date - start_date) * 100) + '%';
    Log.d("type", "Date parsed : " + p);

}

Body:
You can’t do that correctly without taking time zone into account.

private void getpercentage(String dateTimeStart, String dateTimeExpiration) {
    ZoneId zone = ZoneId.systemDefault();

    ZonedDateTime start = LocalDateTime.parse(dateTimeStart.replace( " " , "T" ) )
            .atZone(zone);
    ZonedDateTime end = LocalDateTime.parse(dateTimeExpiration.replace( " " , "T" ) )
            .atZone(zone);

    long total = ChronoUnit.MICROS.between(start, end);
    long passed = ChronoUnit.MICROS.between(start, ZonedDateTime.now(zone));

    long percentage = passed * 100 / total;

    System.out.println(String.valueOf(percentage) + " %");
}

To see how much of the day has passed:

    getpercentage("2020-05-30 00:00:00", "2020-05-31 00:00:00");

When run right now in my time zone, Europe/Copenhagen:

91 %

To illustrate my point about time zone: when instead run in Indian/Maldives time zone:

103 %

So in that time zone 30th May is already over and we’re 3 % into 31st May.

Using the long type and ChronoUnit.MICROS (microseconds) will work for spans of time up to 290 000 years. For a longer span, choose a coarrser unit. For more accuracy and a shorter span, use a finer unit, that is, nanoseconds.

Java 9 and later

long percentage = Duration.between(start, ZonedDateTime.now(zone))
        .multipliedBy(100)
        .dividedBy(Duration.between(start, end));

The overloaded Duration.dividedBy(Duration) method was introduced in Java 9. This allows us to use the Duration class for the calculation so we don’t need to decide on a specific time unit.


问:
Using VBscript and SQL on an Access database how do you select records based on a date comparison with todays date
This sounds like a very naive question but I can not get this simple requirement to work. A selection is made on one page of the website which passes a parameter time_period (which is 1, 7, 31 or 365) to the next page which should list all of the selected records where the LastUpdated date (a standard date field in Access db) is within that many days of the current date.

With single digit numbers (1 and 7) I get a result, but not 100% accurate and with 31 and 365 only very strange results. I guess there is an inconsistency in formats somewhere but I am at a loss to find a solution.

```<code>Dim my_time_period
my_time_period = Request.QueryString("time_period")
selection_list.Source = "SELECT *  FROM document WHERE DateDiff('d',LastUpdated,now) <= '"+my_time_period+"'"
</code>```

I have tried hard coding a number as below but get the same results.

```<code>selection_list.Source = "SELECT *  FROM document WHERE DateDiff('d',LastUpdated, now) <= '7'"
</code>```

I have also tried using Today instead of now but it gets thrown out as an error. Can anyone please help? Thank you

答:
You're comparing a number

```<code>DateDiff('d',LastUpdated, now)
</code>```

to a string

```<code>'7'
</code>```

Instead compare a number to a number:

```<code>"SELECT *  FROM document WHERE DateDiff('d',LastUpdated,now) <= "+my_time_period
</code>```

Note the difference: no single quotes

Also be aware this is inviting SQL Injection.

Also be aware that in a database that uses indexes, this expression should be rewritten something like this:

```<code>SELECT *  FROM document WHERE LastUpdated > DateAdd('d',now,-"+my_time_period+")"
</code>```

That way you're comparing a column (which may be indexed) to a fixed value. It doesn't matter so much in MS Access though

Body:
This sounds like a very naive question but I can not get this simple requirement to work. A selection is made on one page of the website which passes a parameter time_period (which is 1, 7, 31 or 365) to the next page which should list all of the selected records where the LastUpdated date (a standard date field in Access db) is within that many days of the current date.

With single digit numbers (1 and 7) I get a result, but not 100% accurate and with 31 and 365 only very strange results. I guess there is an inconsistency in formats somewhere but I am at a loss to find a solution.

Dim my_time_period
my_time_period = Request.QueryString("time_period")
selection_list.Source = "SELECT *  FROM document WHERE DateDiff('d',LastUpdated,now) <= '"+my_time_period+"'"

I have tried hard coding a number as below but get the same results.

selection_list.Source = "SELECT *  FROM document WHERE DateDiff('d',LastUpdated, now) <= '7'"

I have also tried using Today instead of now but it gets thrown out as an error. Can anyone please help? Thank you

Body:
You're comparing a number

DateDiff('d',LastUpdated, now)

to a string

'7'

Instead compare a number to a number:

"SELECT *  FROM document WHERE DateDiff('d',LastUpdated,now) <= "+my_time_period

Note the difference: no single quotes

Also be aware this is inviting SQL Injection.

Also be aware that in a database that uses indexes, this expression should be rewritten something like this:

SELECT *  FROM document WHERE LastUpdated > DateAdd('d',now,-"+my_time_period+")"

That way you're comparing a column (which may be indexed) to a fixed value. It doesn't matter so much in MS Access though


问:
How can I bypass SameSite cookie restrictions in my development environment?
Recently, Chrome changed the policy for whether cookies are attached to cross-origin requests. Now, cookies are not attached to cross-origin requests unless:

The SameSite cookie attribute is either Lax or None and the request was initiated by a user action, or

The SameSite cookie attribute is None and the Secure cookie attribute is true, meaning that the cross-origin request has to use the https scheme.

(The above is not wrong, but it is slightly simplified. Here is a more thorough writeup.)

In my development environment, I use a tool to compile my development language and hot-reload the changes into my browser tab. This tool serves the frontend code on its own port, and the backend is served on a separate port by a separate process, so we're dealing with cross-origin requests from browser to backend. Naturally, both the frontend and backend are served from localhost with scheme http. And many of the requests that the frontend app makes are not initiated by user action yet still need cookies for auth purposes.

As a result, anything requiring cookies will not work in my development environment. (Yeah, spent quite a while figuring that one out…)

My question is: how can I bypass, work around, or disable these SameSite cookie security restrictions for my development environment in an easy way that won't decrease my security as I'm browsing other sites?

It would be nice if, for example, there was a way to add localhost to a whitelist of origins in my browser that allowed SameSite=None cookies even without a Secure=true attribute. Slightly less nice, but still acceptable, would be an easy way to wrap or proxy my http://localhost:<port> services so that they can be accessed via the https scheme. Or perhaps there's another approach using some obscure cookie magic.

Update 2021-09-16: @tommueller points out that this question is related. This question is different in that it talks about a [cross origin but] same site situation, where both origins are from localhost.

答:
If all of your development environment is hosted under localhost then requests between different ports, while cross-origin, still count as same-site. See: https://web.dev/same-site-same-origin/

In your development environment, you can either drop SameSite=None; Secure completely or explicitly set SameSite=Lax.

Alternatively, look at creating self-signed certificates for localhost or local vms to better match your production environment - though that's slightly more involved.


问:
What is the correct SQL (MYSQL) for finding the value that occurs the most?
What is the correct SQL (MYSQL) for finding the value that occurs the most?

Here's what I thought it might have been:

```<code>SELECT TOP 1 `my_field` FROM `my_table`
GROUP BY COUNT(`my_field`)
ORDER BY DESC
</code>```

答:
To get the most commonly occuring value:</p>

```<code>SELECT `column`
FROM `table`
GROUP BY `column`
ORDER BY count(`column`) DESC
LIMIT 1
</code>```

Body:
What is the correct SQL (MYSQL) for finding the value that occurs the most?

Here's what I thought it might have been:

SELECT TOP 1 `my_field` FROM `my_table`
GROUP BY COUNT(`my_field`)
ORDER BY DESC

Body:
To get the most commonly occuring value:

SELECT `column`
FROM `table`
GROUP BY `column`
ORDER BY count(`column`) DESC
LIMIT 1


问:
Azure function application settings to pick enviroment other than production, staging and development
Azure function app provides app setting tab in azure portal.where I can created key as Azure_Functions_Environment and values as production, staging or development and it would be picked at runtime accordingly. But when I set value as UAT or Sandbox. at runtime system will still pick value as 'development'. Does anybody know reason behind it.</p>

答:
In version 2.x and later versions of the Functions runtime, configures app behavior based on the runtime environment. This value is read during initialization. You can set AZURE_FUNCTIONS_ENVIRONMENT to any value, but three values are supported: Development, Staging, and Production. When AZURE_FUNCTIONS_ENVIRONMENT isn't set, it defaults to Development on a local environment and Production on Azure. This setting should be used instead of ASPNETCORE_ENVIRONMENT to set the runtime environment.

For more details you could refer to this article.