问:
View model not returning any data after reloading fragment
Trying to implement:

1.An internet check before loading data from view model.
2.The fragment shouldn't fetch any data(doesn't set any observer) from view model and shows alert dialog if their is no connection.
3.If connection is available reload/fetch data from view model using "try again" button inside alert dialog.

Problem:
But when trying to reload the data from try again button,no data is getting fetched from view model. It doesn't happen if I have internet connection available from beginning,then view model works just fine. But if I don't have internet from beginning and try to reload the data again from "try again" button then happens.

I have also tried to reload the whole fragment instead of just calling the "getDataFromViewModel" method using below code:

```<code>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            getParentFragmentManager().beginTransaction().detach(this).commitNow();
            getParentFragmentManager().beginTransaction().attach(this).commitNow();
        } else {
            getParentFragmentManager().beginTransaction().detach(this).attach(this).commit();
        }
</code>```

but this also doesn't work.

Here is my fragment class:

```<code>public class GlobalDataFragment extends Fragment implements AlertDialogClass.AlertDialogClickInterface {

    public GlobalDataFragment() {

    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        viewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(getActivity().getApplication())).get(GlobalDataViewModel.class);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_global_data, container, false);

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        totalCase = (TextView) view.findViewById(R.id.tvTotalCases);
        activeCase = (TextView) view.findViewById(R.id.tvActiveCases);
        recovered = (TextView) view.findViewById(R.id.tvRecovered);
        caseToday = (TextView) view.findViewById(R.id.tvTodayCase);
        casePM = (TextView) view.findViewById(R.id.tvCasesPM);
        todayDeath = (TextView) view.findViewById(R.id.tvTodayDeaths);
        totalDeath = (TextView) view.findViewById(R.id.tvTotalDeaths);
        deathsPM = (TextView) view.findViewById(R.id.tvDeathsPM);
        criticalCondition = (TextView) view.findViewById(R.id.tvCriticalCase);
        totalTested = (TextView) view.findViewById(R.id.tvTested);
        testsPM = (TextView) view.findViewById(R.id.tvTestsPM);
        affectedCountries = (TextView) view.findViewById(R.id.tvAffectedCountries);
        simpleArcLoader = (ProgressBar) view.findViewById(R.id.simpleArcLoader);
        pieChart = (PieChart) view.findViewById(R.id.pieChart);
        nestedScrollView = (ScrollView) view.findViewById(R.id.nestedScrollView);
        navController = Navigation.findNavController(view);
        alertDialogClass = new AlertDialogClass(getContext(), this);

        getDataFromViewModel();

    }

    private void getDataFromViewModel() {
        try {
            if (CheckConnection.isConnected()) {

                viewModel.getGlobalData().observe(getViewLifecycleOwner(), this::setViewData);

            } else {

                alertDialogClass.show();

            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void setViewData(GlobalData globalData) {

        if (globalData != null) {
            totalTested.setText(globalData.getTests());
            testsPM.setText(globalData.getTestsPerOneMillion());
            affectedCountries.setText(globalData.getAffectedCountries());

            setPieGraph(globalData);
            simpleArcLoader.setVisibility(View.GONE);
            nestedScrollView.setVisibility(View.VISIBLE);

        }
    }

//Called when clicked on try again button of alert dialog
    @Override
    public void OnAlertButtonClicked() {

        alertDialogClass.dismiss();
        getDataFromViewModel();

    }
}
</code>```

My view model Class:

```<code>public class GlobalDataViewModel extends AndroidViewModel {

    private Repository repository;
    private LiveData<GlobalData> globalData = new MutableLiveData<>();

    public GlobalDataViewModel(@NonNull Application application) {
        super(application);

        repository = Repository.getInstance();
        globalData = repository.getGlobalData();

    }

    public void init() {

    }

    public LiveData<GlobalData> getGlobalData() {
        return globalData;
    }
}
</code>```

My fragment looks like this when an internet connection occurs:

After pressing try again the method(getDataFromViewModel) is called but view model is not returning any data.But the same method is working fine when I load the fragment having internet from the beginning.Is it happening because of the way i initialize and set observer on view model or something else?Please help and suggest me how to solve this problem.

答:
You didnt show your repository config, anyhow I believe your problem is that you are fetching data from your repository (in this case what I believe to be in an external network [internet]) without internet and you are not trying to fetch again, to sum up, you are observing this:

```<code>private LiveData<GlobalData> globalData = new MutableLiveData<>();
</code>```

And as you didn't have internet connection at the time you initialize your viewmodel it is empty.

What you can do to fix it:

```<code>private LiveData<GlobalData> globalData = repository.getGlobalData();
</code>```

This way, you are only going to trigger a network fetch if/when you observe this globalData

let me know if it makes sense to you.

Body:
Trying to implement:

1.An internet check before loading data from view model.
2.The fragment shouldn't fetch any data(doesn't set any observer) from view model and shows alert dialog if their is no connection.
3.If connection is available reload/fetch data from view model using "try again" button inside alert dialog.

Problem:
But when trying to reload the data from try again button,no data is getting fetched from view model. It doesn't happen if I have internet connection available from beginning,then view model works just fine. But if I don't have internet from beginning and try to reload the data again from "try again" button then happens.

I have also tried to reload the whole fragment instead of just calling the "getDataFromViewModel" method using below code:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            getParentFragmentManager().beginTransaction().detach(this).commitNow();
            getParentFragmentManager().beginTransaction().attach(this).commitNow();
        } else {
            getParentFragmentManager().beginTransaction().detach(this).attach(this).commit();
        }

but this also doesn't work.

Here is my fragment class:

public class GlobalDataFragment extends Fragment implements AlertDialogClass.AlertDialogClickInterface {

    public GlobalDataFragment() {

    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        viewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(getActivity().getApplication())).get(GlobalDataViewModel.class);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_global_data, container, false);

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        totalCase = (TextView) view.findViewById(R.id.tvTotalCases);
        activeCase = (TextView) view.findViewById(R.id.tvActiveCases);
        recovered = (TextView) view.findViewById(R.id.tvRecovered);
        caseToday = (TextView) view.findViewById(R.id.tvTodayCase);
        casePM = (TextView) view.findViewById(R.id.tvCasesPM);
        todayDeath = (TextView) view.findViewById(R.id.tvTodayDeaths);
        totalDeath = (TextView) view.findViewById(R.id.tvTotalDeaths);
        deathsPM = (TextView) view.findViewById(R.id.tvDeathsPM);
        criticalCondition = (TextView) view.findViewById(R.id.tvCriticalCase);
        totalTested = (TextView) view.findViewById(R.id.tvTested);
        testsPM = (TextView) view.findViewById(R.id.tvTestsPM);
        affectedCountries = (TextView) view.findViewById(R.id.tvAffectedCountries);
        simpleArcLoader = (ProgressBar) view.findViewById(R.id.simpleArcLoader);
        pieChart = (PieChart) view.findViewById(R.id.pieChart);
        nestedScrollView = (ScrollView) view.findViewById(R.id.nestedScrollView);
        navController = Navigation.findNavController(view);
        alertDialogClass = new AlertDialogClass(getContext(), this);

        getDataFromViewModel();

    }

    private void getDataFromViewModel() {
        try {
            if (CheckConnection.isConnected()) {

                viewModel.getGlobalData().observe(getViewLifecycleOwner(), this::setViewData);

            } else {

                alertDialogClass.show();

            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void setViewData(GlobalData globalData) {

        if (globalData != null) {
            totalTested.setText(globalData.getTests());
            testsPM.setText(globalData.getTestsPerOneMillion());
            affectedCountries.setText(globalData.getAffectedCountries());

            setPieGraph(globalData);
            simpleArcLoader.setVisibility(View.GONE);
            nestedScrollView.setVisibility(View.VISIBLE);

        }
    }

//Called when clicked on try again button of alert dialog
    @Override
    public void OnAlertButtonClicked() {

        alertDialogClass.dismiss();
        getDataFromViewModel();

    }
}

My view model Class:

public class GlobalDataViewModel extends AndroidViewModel {

    private Repository repository;
    private LiveData<GlobalData> globalData = new MutableLiveData<>();

    public GlobalDataViewModel(@NonNull Application application) {
        super(application);

        repository = Repository.getInstance();
        globalData = repository.getGlobalData();

    }

    public void init() {

    }

    public LiveData<GlobalData> getGlobalData() {
        return globalData;
    }
}

My fragment looks like this when an internet connection occurs:

After pressing try again the method(getDataFromViewModel) is called but view model is not returning any data.But the same method is working fine when I load the fragment having internet from the beginning.Is it happening because of the way i initialize and set observer on view model or something else?Please help and suggest me how to solve this problem.

Body:
You didnt show your repository config, anyhow I believe your problem is that you are fetching data from your repository (in this case what I believe to be in an external network [internet]) without internet and you are not trying to fetch again, to sum up, you are observing this:

private LiveData<GlobalData> globalData = new MutableLiveData<>();

And as you didn't have internet connection at the time you initialize your viewmodel it is empty.

What you can do to fix it:

private LiveData<GlobalData> globalData = repository.getGlobalData();

This way, you are only going to trigger a network fetch if/when you observe this globalData

let me know if it makes sense to you.


来源: stackexchange

问:
Ticks position in heatmap with categorical data (seaborn)
I am trying to plot a confusion matrix of my predictions. My data is multi-class (13 different labels) so I'm using a heatmap.

As you can see below, my heat map looks generally okay but the labels are a bit out of position: y ticks should be a little lower and x ticks should be a bit more to the right. I want to move both axis ticks a bit so they will aligned with the center of each square.

my code:

sns.set()
my_mask = np.zeros((con_matrix.shape[0], con_matrix.shape[0]), dtype=int)
for i in range(con_matrix.shape[0]):
    for j in range(con_matrix.shape[0]):
        my_mask[i][j] = con_matrix[i][j] == 0

fig_dims = (10, 10)
plt.subplots(figsize=fig_dims)
ax = sns.heatmap(con_matrix, annot=True, fmt="d", linewidths=.5, cmap="Pastel1", cbar=False, mask=my_mask, vmax=15)
plt.xticks(range(len(party_names)), party_names, rotation=45)
plt.yticks(range(len(party_names)), party_names, rotation='horizontal')
plt.show()
```

<p>and for reproduction purpose, here are <code>con_matrix</code> and <code>party_names</code> hard-coded:</p>

<pre class="lang-py prettyprint-override"><code>import numpy as np
from matplotlib import pyplot as plt
import seaborn as sns

con_matrix = np.array([[55, 0, 0, 0,0, 0, 0,0,0,0,0,0,2], [0,199,0,0,0,0,0,0,0,0,2,0,1],
 [0, 0,52,0,0,0,0,0,0,0,0,0,1],
 [0,0,0,39,0,0,0,0,0,0,0,0,0],
 [0,0,0,0,90,0,0,0,0,0,0,4,3],
 [0,0,0,1,0,35,0,0,0,0,0,0,0],
 [0,0,0,0,5,0,26,0,0,1,0,1,0],
 [0,5,0,0,0,1,0,44,0,0,3,0,1],
 [0,1,0,0,0,0,0,0,52,0,0,0,0],
 [0,1,0,0,2,0,0,0,0,235,0,1,1],
 [1,2,0,0,0,0,0,3,0,0,34,0,3],
 [0,0,0,0,5,0,0,0,0,1,0,40,0],
 [0,0,0,0,0,0,0,0,0,1,0,0,46]])

party_names = ['Blues', 'Browns', 'Greens', 'Greys', 'Khakis', 'Oranges', 'Pinks', 'Purples', 'Reds', 'Turquoises', 'Violets', 'Whites', 'Yellows']
</code>```

I already tried to work with position argument of different axes, but it did not turn out well. Could not find an exactly answer in this site as well (at least not a solution that works for categorical data).

I'm new in visualization with seaborn, any improvement with explanations would be appreciated (not only for my problem but on my code & visualization as well).

答:
You can shift both the ticklabels by 0.5 offset to have the desired alignment. To do so, I have used NumPy's arange that enables vectorized addition of 0.5 to the whole array.

```<code>plt.xticks(np.arange(len(party_names))+0.5, party_names, rotation=45)
plt.yticks(np.arange(len(party_names))+0.5, party_names, rotation='horizontal')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to plot a confusion matrix of my predictions. My data is multi-class (13 different labels) so I'm using a heatmap.

As you can see below, my heat map looks generally okay but the labels are a bit out of position: y ticks should be a little lower and x ticks should be a bit more to the right. I want to move both axis ticks a bit so they will aligned with the center of each square.

my code:

sns.set()
my_mask = np.zeros((con_matrix.shape[0], con_matrix.shape[0]), dtype=int)
for i in range(con_matrix.shape[0]):
    for j in range(con_matrix.shape[0]):
        my_mask[i][j] = con_matrix[i][j] == 0

fig_dims = (10, 10)
plt.subplots(figsize=fig_dims)
ax = sns.heatmap(con_matrix, annot=True, fmt="d", linewidths=.5, cmap="Pastel1", cbar=False, mask=my_mask, vmax=15)
plt.xticks(range(len(party_names)), party_names, rotation=45)
plt.yticks(range(len(party_names)), party_names, rotation='horizontal')
plt.show()

and for reproduction purpose, here are con_matrix and party_names hard-coded:

import numpy as np
from matplotlib import pyplot as plt
import seaborn as sns

con_matrix = np.array([[55, 0, 0, 0,0, 0, 0,0,0,0,0,0,2], [0,199,0,0,0,0,0,0,0,0,2,0,1],
 [0, 0,52,0,0,0,0,0,0,0,0,0,1],
 [0,0,0,39,0,0,0,0,0,0,0,0,0],
 [0,0,0,0,90,0,0,0,0,0,0,4,3],
 [0,0,0,1,0,35,0,0,0,0,0,0,0],
 [0,0,0,0,5,0,26,0,0,1,0,1,0],
 [0,5,0,0,0,1,0,44,0,0,3,0,1],
 [0,1,0,0,0,0,0,0,52,0,0,0,0],
 [0,1,0,0,2,0,0,0,0,235,0,1,1],
 [1,2,0,0,0,0,0,3,0,0,34,0,3],
 [0,0,0,0,5,0,0,0,0,1,0,40,0],
 [0,0,0,0,0,0,0,0,0,1,0,0,46]])

party_names = ['Blues', 'Browns', 'Greens', 'Greys', 'Khakis', 'Oranges', 'Pinks', 'Purples', 'Reds', 'Turquoises', 'Violets', 'Whites', 'Yellows']

I already tried to work with position argument of different axes, but it did not turn out well. Could not find an exactly answer in this site as well (at least not a solution that works for categorical data).

I'm new in visualization with seaborn, any improvement with explanations would be appreciated (not only for my problem but on my code & visualization as well).

Body:
You can shift both the ticklabels by 0.5 offset to have the desired alignment. To do so, I have used NumPy's arange that enables vectorized addition of 0.5 to the whole array.

plt.xticks(np.arange(len(party_names))+0.5, party_names, rotation=45)
plt.yticks(np.arange(len(party_names))+0.5, party_names, rotation='horizontal')


问:
How to perform filter in java script objects?
How to filter javascript objects based on a condition?

I tried this , but still it fills the remaining index of the object as null , I don't want the part of object if it doesn't meet my condition ,here the condition is only if the index of the object is less the selectedIndex (which is some value in my program) it should be selected, remaining are not required

```<code>console.log(Object.keys(registrationData).map((val,ind)=>{
            return (ind<=selectedIndex ) ? registrationData[val] :null
   }));

</code>```

答:
Try this</p>

```<code>Object
  .values(registrationData)
  .filter((value, index) => index <= selectedIndex)
</code>```

Body:
How to filter javascript objects based on a condition?

I tried this , but still it fills the remaining index of the object as null , I don't want the part of object if it doesn't meet my condition ,here the condition is only if the index of the object is less the selectedIndex (which is some value in my program) it should be selected, remaining are not required

console.log(Object.keys(registrationData).map((val,ind)=>{
            return (ind<=selectedIndex ) ? registrationData[val] :null
   }));

Body:
Try this

Object
  .values(registrationData)
  .filter((value, index) => index <= selectedIndex)


问:
c++ function to find the sum of four minimum maximum elements in an array not working
I am solving a question in which i have to write a function which finds the maximum and minimum sum of any four integers in an array passed to it and then displays it.

here is my code:

```<code>void miniMaxSum(vector<int> arr) {

        int minsum=0;
        int maxsum=0;
        int l1,l2,l3,l4;
        int s1,s2,s3,s4;
        l1=arr[0];
        s1=arr[0];
        for(int i=1;i<arr.size();++i)
        {
            if(l1<arr[i])
            l1=arr[i];
            if(s1>arr[i])
            s1=arr[i];
        }
        l2=arr[0];
        s2=arr[0];
        for(int i=1;i<arr.size();++i)
        {
            if(l2<arr[i]&&arr[i]!=l1)
            l2=arr[i];
            if(s2>arr[i]&&arr[i]!=s1)
            s2=arr[i];
        }
        l3=arr[0];
        s3=arr[0];
        for(int i=1;i<arr.size();++i)
        {
            if(l3<arr[i]&&arr[i]!=l2&&arr[i]!=l1)
            l3=arr[i];
            if(s3>arr[i]&&arr[i]!=s2&&arr[i]!=s1)
            s3=arr[i];
        }
        l4=arr[0];
        s4=arr[0];
        for(int i=1;i<arr.size();++i)
        {
            if(l4<arr[i]&&arr[i]!=l2&&arr[i]!=l1&&arr[i]!=l3)
            l4=arr[i];
            if(s4>arr[i]&&arr[i]!=s3&&arr[i]!=s2&&arr[i]!=s1)
            s4=arr[i];
        }
        minsum=s1+s2+s3+s4;
        maxsum=l1+l2+l3+l4;
        cout<<minsum<<" "<<maxsum;
}
</code>```

this code gives the correct output for maxsum but the minsum is wrong in all the testcases.
please help me find the error in the code
Thanks in advance.

答:
```<code>void miniMaxSum(vector<int> arr) {
    sort(arr.begin(), arr.end());
    int sumMin = 0, sumMax = 0, len = arr.size() - 1;
    for(int i = 0; i < 4; i++){
        sumMin += arr[i];
        sumMax += arr[len - i];
    }
    cout<<"minimum sum: "<<sumMin<<endl;
    cout<<"maximum sum: "<<sumMax<<endl;
}
</code>```

Body:
I am solving a question in which i have to write a function which finds the maximum and minimum sum of any four integers in an array passed to it and then displays it.

here is my code:

void miniMaxSum(vector<int> arr) {

        int minsum=0;
        int maxsum=0;
        int l1,l2,l3,l4;
        int s1,s2,s3,s4;
        l1=arr[0];
        s1=arr[0];
        for(int i=1;i<arr.size();++i)
        {
            if(l1<arr[i])
            l1=arr[i];
            if(s1>arr[i])
            s1=arr[i];
        }
        l2=arr[0];
        s2=arr[0];
        for(int i=1;i<arr.size();++i)
        {
            if(l2<arr[i]&&arr[i]!=l1)
            l2=arr[i];
            if(s2>arr[i]&&arr[i]!=s1)
            s2=arr[i];
        }
        l3=arr[0];
        s3=arr[0];
        for(int i=1;i<arr.size();++i)
        {
            if(l3<arr[i]&&arr[i]!=l2&&arr[i]!=l1)
            l3=arr[i];
            if(s3>arr[i]&&arr[i]!=s2&&arr[i]!=s1)
            s3=arr[i];
        }
        l4=arr[0];
        s4=arr[0];
        for(int i=1;i<arr.size();++i)
        {
            if(l4<arr[i]&&arr[i]!=l2&&arr[i]!=l1&&arr[i]!=l3)
            l4=arr[i];
            if(s4>arr[i]&&arr[i]!=s3&&arr[i]!=s2&&arr[i]!=s1)
            s4=arr[i];
        }
        minsum=s1+s2+s3+s4;
        maxsum=l1+l2+l3+l4;
        cout<<minsum<<" "<<maxsum;
}

this code gives the correct output for maxsum but the minsum is wrong in all the testcases.
please help me find the error in the code
Thanks in advance.


问:
how to test the data after training the train data with k-fold cross validation?
Here in the code, I have:

Split the dataset into two part: Train set and Test set (7:3). The dataset consists of 200 rows and 9394 columns.

Define the model

cross validation used: 10 folds on train set

accuracy obtained for each fold

mean accuracy obtained: 94.29%

The confusion is:

Is it the right way I am doing?

Is cross_val_predict() used in the right way to predict the x over the test data?

Tasks remaining:

To plot accuracy of model.

To plot loss of model.

Can anyone suggest in this regards.
Sorry for this long notes!!!

The dataset is as: (These are tfidf of each words in the title and body of news)

```<code>    Unnamed: 0  Unnamed: 0.1    Label   Cosine_Similarity   c0  c1  c2  c3  c4  c5  ... c9386   c9387   c9388   c9389   c9390   c9391   c9392   c9393   c9394   c9395
0   0   0   Real    0.180319    0.000000    0.0 0.000000    0.0 0.0 0.0 ... 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
1   1   1   Real    0.224159    0.166667    0.0 0.000000    0.0 0.0 0.0 ... 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
2   2   2   Real    0.233877    0.142857    0.0 0.000000    0.0 0.0 0.0 ... 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
3   3   3   Real    0.155789    0.111111    0.0 0.000000    0.0 0.0 0.0 ... 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
4   4   4   Real    0.225480    0.000000    0.0 0.111111    0.0 0.0 0.0 ... 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
</code>```

The code and output are:

```<code>df_all = pd.read_csv("C:/Users/shiva/Desktop/allinone200.csv")

dataset=df_all.values
x=dataset[0:,3:]
Y= dataset[0:,2]
encoder = LabelEncoder()
encoder.fit(Y)
encoded_Y = encoder.transform(Y)
y = np_utils.to_categorical(encoded_Y)

from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3,random_state=15,shuffle=True)
x_train.shape,y_train.shape

def baseline_model():
    model = Sequential()
    model.add(Dense(512, activation='relu',input_dim=x_train.shape[1]))
    model.add(Dense(64, activation='relu')))
    model.add(Dense(2, activation='softmax'))

    model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
</code>```

code for fitting the model:

```<code>estimator = KerasClassifier(build_fn=baseline_model, epochs=5, batch_size=4, verbose=1)
kf = KFold(n_splits=10, shuffle=True,random_state=15)

for train_index, test_index in kf.split(x_train,y_train):
    print("Train Index: ", train_index, "\n")
    print("Test Index: ", test_index)
</code>```

code for taking out the results:

```<code>results = cross_val_score(estimator, x_train, y_train, cv=kf)
print results
</code>```

Output:

```<code>[0.9285714  1.         0.9285714  1.         0.78571427 0.85714287
 1.         1.         0.9285714  1.        ]
</code>```

Mean accuracy:`

```<code>print("Accuracy: %0.2f (+/-%0.2f)" % (results.mean()*100, results.std()*2))
</code>```

Output:

```<code>Accuracy: 94.29 (+/-0.14)
</code>```

code for prediction:

```<code>from sklearn.model_selection import cross_val_predict
y_pred = cross_val_predict(estimator, x_test, y_test,cv=kf)
print(y_test[0])
print(y_pred[0])
</code>```

Output:after processing

```<code>[1. 0.]
0
</code>```

Here prediction seems seems okay. Because 1 is REAL and O is FALSE. y_test is 0 and y_predict is also 0.

Confusion matrix:

```<code>import numpy as np
y_test=np.argmax(y_test, axis=1)
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)
cm
</code>```

Output:

```<code>array([[32,  0],
       [ 1, 27]], dtype=int64)
</code>```

答:
Unfortunately my comment became to long therefore I try it here:

Please have a look at this: https://medium.com/mini-distill/effect-of-batch-size-on-training-dynamics-21c14f7a716e in short, larger batch sizes have often worse results but are faster, which in your case might be irrelevant (200 rows).
Secondly you do not have a (reusable) hold-out which might give you false assumptions regarding your true accuracy. That you have an accuracy of over 90% on your first try can mean either: overfitting, leaking or imbalanced data (e.g. here: https://www.kdnuggets.com/2017/06/7-techniques-handle-imbalanced-data.html) or that you were really lucky.
K-fold in combination with small samples sizes can lead to wrong assumptions:
https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0224365

A few rule of thumbs:
1. you want to have 2x as much datapoints (rows) as features (columns).
2. If you still get a good result, this can mean multiple things. Most likely its an error in code or methodology.

Imagine you have to predict the fraud risk of a bank. If the chance a fraud happens is 1% I can build you a modell which is right 99% of the time by simply saying there is never any fraud....

Neuronal Nets are extremly powerfull, that is good and bad. The bad thing is that they nearly always find some kind of pattern, even if there isn't one. If you give them 2000 columns essentially it gets a bit like the number "Pi" if you search long enough in the numbers after the comma you will find any number combination you want.
Here its explained in a bit more detail:
https://medium.com/@jennifer.zzz/more-features-than-data-points-in-linear-regression-5bcabba6883e

Body:
Here in the code, I have:

Split the dataset into two part: Train set and Test set (7:3). The dataset consists of 200 rows and 9394 columns.

Define the model

cross validation used: 10 folds on train set

accuracy obtained for each fold

mean accuracy obtained: 94.29%

The confusion is:

Is it the right way I am doing?

Is cross_val_predict() used in the right way to predict the x over the test data?

Tasks remaining:

To plot accuracy of model.

To plot loss of model.

Can anyone suggest in this regards.
Sorry for this long notes!!!

The dataset is as: (These are tfidf of each words in the title and body of news)

    Unnamed: 0  Unnamed: 0.1    Label   Cosine_Similarity   c0  c1  c2  c3  c4  c5  ... c9386   c9387   c9388   c9389   c9390   c9391   c9392   c9393   c9394   c9395
0   0   0   Real    0.180319    0.000000    0.0 0.000000    0.0 0.0 0.0 ... 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
1   1   1   Real    0.224159    0.166667    0.0 0.000000    0.0 0.0 0.0 ... 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
2   2   2   Real    0.233877    0.142857    0.0 0.000000    0.0 0.0 0.0 ... 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
3   3   3   Real    0.155789    0.111111    0.0 0.000000    0.0 0.0 0.0 ... 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
4   4   4   Real    0.225480    0.000000    0.0 0.111111    0.0 0.0 0.0 ... 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0

The code and output are:

df_all = pd.read_csv("C:/Users/shiva/Desktop/allinone200.csv")

dataset=df_all.values
x=dataset[0:,3:]
Y= dataset[0:,2]
encoder = LabelEncoder()
encoder.fit(Y)
encoded_Y = encoder.transform(Y)
y = np_utils.to_categorical(encoded_Y)

from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3,random_state=15,shuffle=True)
x_train.shape,y_train.shape

def baseline_model():
    model = Sequential()
    model.add(Dense(512, activation='relu',input_dim=x_train.shape[1]))
    model.add(Dense(64, activation='relu')))
    model.add(Dense(2, activation='softmax'))

    model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
return model

code for fitting the model:

estimator = KerasClassifier(build_fn=baseline_model, epochs=5, batch_size=4, verbose=1)
kf = KFold(n_splits=10, shuffle=True,random_state=15)

for train_index, test_index in kf.split(x_train,y_train):
    print("Train Index: ", train_index, "\n")
    print("Test Index: ", test_index)

code for taking out the results:

results = cross_val_score(estimator, x_train, y_train, cv=kf)
print results

Output:

[0.9285714  1.         0.9285714  1.         0.78571427 0.85714287
 1.         1.         0.9285714  1.        ]

Mean accuracy:`

print("Accuracy: %0.2f (+/-%0.2f)" % (results.mean()*100, results.std()*2))

Output:

Accuracy: 94.29 (+/-0.14)

code for prediction:

from sklearn.model_selection import cross_val_predict
y_pred = cross_val_predict(estimator, x_test, y_test,cv=kf)
print(y_test[0])
print(y_pred[0])

Output:after processing

[1. 0.]
0

Here prediction seems seems okay. Because 1 is REAL and O is FALSE. y_test is 0 and y_predict is also 0.

Confusion matrix:

import numpy as np
y_test=np.argmax(y_test, axis=1)
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)
cm

Output:

array([[32,  0],
       [ 1, 27]], dtype=int64)


问:
GKE not able to reach MongoDB Atlas
I have an issue with trying to deploy my containerized app to GKE. It is not able to reach my MongoDB Atlas cluster. Running the Docker container locally creates no issues and works perfectly. I am by no means an expert in Docker or Kubernetes, but I am assuming it is something to do with the DNS name resolution.

I have followed this tutorial - Deploying a containerized web application, with an addition of adding an EXTERNAL-IP of the LoadBalancer to my 'Network Access' IP Whitelist in the MongoDB Atlas console and using port mapping 443 -> 8443 since I am using HTTPS.

Only logs that my app is able to produce before failing:

```<code>(mongodb): 2020/05/30 15:07:39 logger.go:96: 2020-05-30T15:07:39Z
[error] Failed to connect to mongodb. Check if mongo is running...
(mongodb): 2020/05/30 15:07:39 logger.go:132: 2020-05-30T15:07:39Z
[fatal] server selection error: server selection timeout, current
topology: { Type: ReplicaSetNoPrimary, Servers: [{ Addr: biomas-
cluster-shard-<removed>.azure.mongodb.net:27017, Type: Unknown,
State: Connected, Average RTT: 0, Last error: connection() :
connection(biomas-cluster-shard-<removed>.azure.mongodb.net:27017[-180]) incomplete read of message
header: EOF }, { Addr: biomas-cluster-shard-<removed>.azure.mongodb.net:27017, Type: Unknown, State: Connected, Average RTT: 0, Last error: connection() : connection(biomas-cluster-shard-<removed>.azure.mongodb.net:27017[-181]) incomplete read of message header: EOF }, { Addr: biomas-cluster-shard-<removed>.azure.mongodb.net:27017, Type: Unknown, State: Connected, Average RTT: 0, Last error: connection() : connection(biomas-cluster-shard-<removed>.azure.mongodb.net:27017[-179]) incomplete read of message header: EOF }, ] }
</code>```

If there is a simple workaround with to this, that would be preferred since the app is in the development stage still, so I just need a basically working application using the said technologies.

The full workflow:

Android App -> Golang API running on Docker -> MongoDB Atlas

Thanks

答:
Exactly as @Marc point, your traffic got out with EXTERNAL-IP of your worker nodes, not your load balancer.

To find nodes EXTERNAL-IP IPs use:

kubectl get nodes -owide
```
<p>To be more precise and output only IPs use (taken from kubectl Cheat Sheet):</p>
<pre class="lang-sh prettyprint-override"><code>kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="ExternalIP")].address}'
</code>```

Next whitelist those IPs and you should be good, but keep in mind that after Kubernetes upgrade or cluster scaling the IPs might change, so I recommend using Cloud NAT to always have the same IP for your outgoing traffic.

Title: GKE not able to reach MongoDB Atlas

Body:
I have an issue with trying to deploy my containerized app to GKE. It is not able to reach my MongoDB Atlas cluster. Running the Docker container locally creates no issues and works perfectly. I am by no means an expert in Docker or Kubernetes, but I am assuming it is something to do with the DNS name resolution.

I have followed this tutorial - Deploying a containerized web application, with an addition of adding an EXTERNAL-IP of the LoadBalancer to my 'Network Access' IP Whitelist in the MongoDB Atlas console and using port mapping 443 -> 8443 since I am using HTTPS.

Only logs that my app is able to produce before failing:

(mongodb): 2020/05/30 15:07:39 logger.go:96: 2020-05-30T15:07:39Z
[error] Failed to connect to mongodb. Check if mongo is running...
(mongodb): 2020/05/30 15:07:39 logger.go:132: 2020-05-30T15:07:39Z
[fatal] server selection error: server selection timeout, current
topology: { Type: ReplicaSetNoPrimary, Servers: [{ Addr: biomas-
cluster-shard-<removed>.azure.mongodb.net:27017, Type: Unknown,
State: Connected, Average RTT: 0, Last error: connection() :
connection(biomas-cluster-shard-<removed>.azure.mongodb.net:27017[-180]) incomplete read of message
header: EOF }, { Addr: biomas-cluster-shard-<removed>.azure.mongodb.net:27017, Type: Unknown, State: Connected, Average RTT: 0, Last error: connection() : connection(biomas-cluster-shard-<removed>.azure.mongodb.net:27017[-181]) incomplete read of message header: EOF }, { Addr: biomas-cluster-shard-<removed>.azure.mongodb.net:27017, Type: Unknown, State: Connected, Average RTT: 0, Last error: connection() : connection(biomas-cluster-shard-<removed>.azure.mongodb.net:27017[-179]) incomplete read of message header: EOF }, ] }

If there is a simple workaround with to this, that would be preferred since the app is in the development stage still, so I just need a basically working application using the said technologies.

The full workflow:

Android App -> Golang API running on Docker -> MongoDB Atlas

Thanks

Body:
Exactly as @Marc point, your traffic got out with EXTERNAL-IP of your worker nodes, not your load balancer.

To find nodes EXTERNAL-IP IPs use:

kubectl get nodes -owide

To be more precise and output only IPs use (taken from kubectl Cheat Sheet):

kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="ExternalIP")].address}'

Next whitelist those IPs and you should be good, but keep in mind that after Kubernetes upgrade or cluster scaling the IPs might change, so I recommend using Cloud NAT to always have the same IP for your outgoing traffic.


问:
Consistency of MPI_Fetch_and_op
I am trying to understand the MPI-Function `MPI_Fetch_and_op() through a small example and ran into a strange behaviour I would like to understand.

In the example the process with rank 0 is waiting till the processes 1..4 have each incremented the value of result by one before carrying on.

With the default value 0 for assert used in the function MPI_Win_lock_all() I sometimes (1 out of 10)  get an infinite loop, that is updating the value of result[0] in the MASTER to the value of 3. The terminal output looks like the following code snippet:

```<code>result: 3
result: 3
result: 3
...
</code>```

According to the documentation the function MPI_Fetch_and_op is atomic.

This operations is atomic with respect to other "accumulate"
  operations.

First Question:
Why is it not updating the value of result[0] to 4?

If I change the value of assert to MPI_MODE_NOCHECK it seems to work

Second Question:
Why is it working with MPI_MODE_NOCHECK

According to the documentation I thought this means the mutual exclusion has to be organized in a different way. Can someone explain the passage from the documentation of MPI_Win_lock_all()?

MPI_MODE_NOCHECK

No other process holds, or will attempt to acquire a conflicting lock, while the caller holds the window lock. This is useful when
  mutual exclusion is achieved by other means, but the coherence
  operations that may be attached to the lock and unlock calls are still
  required.

Thanks in advance!

Example program:

#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>

#define MASTER 0

int main(int argc, char *argv[])
{
  MPI_Init(&argc, &argv);
  MPI_Comm comm = MPI_COMM_WORLD;
  int r, p;
  MPI_Comm_rank(comm, &r);
  MPI_Comm_size(comm, &p);
  printf("Hello from %d\n", r);
  int result[1] = {0};
  //int assert = MPI_MODE_NOCHECK;
  int assert = 0;
  int one = 1;
  MPI_Win win_res;
  MPI_Win_allocate(1 * sizeof(MPI_INT), sizeof(MPI_INT), MPI_INFO_NULL, comm, &result[0], &win_res);
  MPI_Win_lock_all(assert, win_res);
  if (r == MASTER) {
    result[0] = 0;
    do{
      MPI_Fetch_and_op(&result, &result , MPI_INT, r, 0, MPI_NO_OP, win_res);
      printf("result: %d\n", result[0]);
    } while(result[0] != 4);
    printf("Master is done!\n");
  } else {
    MPI_Fetch_and_op(&one, &result, MPI_INT, 0, 0, MPI_SUM, win_res);
  }
  MPI_Win_unlock_all(win_res);
  MPI_Win_free(&win_res);
  MPI_Finalize();
  return 0;
}
```

<p>Compiled with the following Makefile:</p>

```MPICC = mpicc
CFLAGS = -g -std=c99 -Wall -Wpedantic -Wextra

all: fetch_and

fetch_and: main.c
    $(MPICC) $(CFLAGS) -o $@ main.c

clean:
    rm fetch_and

run: all
    mpirun -np 5 ./fetch_and
```

答:
Your code works for me, unchanged. But that may be coincidence. There are many problems with your code. Let me point out what I see:

You hard-coded the number of processes in the test result[0] != 4

You hard-coded the master value into MPI_Fetch_and_op(&one, &result, MPI_INT, 0

Passing the same address as update and result seems dangerous to me: MPI_Fetch_and_op(&result, &result

And my compiler complains about the first parameter since it is in effect an int** (actually int (*)[1])

I'm not sure why you don't get the same complaint on the second parameter,

....but I'm not happy about that second parameter anyway, since the fetch operation writes in memory that you designated to be the window buffer. I guess the lack of coherence here saves you.

You initialize the window with result[0] = 0; but I don't think that is coherent with the window so again, you may just be lucky.

I would think that MPI_Win_allocate(1 * sizeof(MPI_INT), sizeof(MPI_INT), MPI_INFO_NULL, comm, &result[0] would also be some sort of memory corruption since result is an output here, but it is a statically allocated array.

Similarly, Win_free tries to deallocate the memory buffer, but that was, as already remarked, a static buffer, so again: memory corruption.

Your use of Win_lock_all is not appropriate: it means that one process locks the window on all targets. Without any competing locks!! You are locking the window on only one process, but from all possible origins. I'd use an ordinary lock.

Finally, RMA calls are non-blocking. Normally, consistency is made by a Win_fence or Win_unlock. But because you are using a long-lived lock, you need to follow the Fetch_and_op by a MPI_Win_flush_local.

Ok, so that's a dozen cases of, eh, less than ideal programming. Still, in my set up it works. (Sometimes. Sometimes it also hangs.) So you may want to clean up your code a little. Your logic is correct, but your actual implementation not.

Title: Consistency of MPI_Fetch_and_op

Body:
I am trying to understand the MPI-Function `MPI_Fetch_and_op() through a small example and ran into a strange behaviour I would like to understand.

In the example the process with rank 0 is waiting till the processes 1..4 have each incremented the value of result by one before carrying on.

With the default value 0 for assert used in the function MPI_Win_lock_all() I sometimes (1 out of 10)  get an infinite loop, that is updating the value of result[0] in the MASTER to the value of 3. The terminal output looks like the following code snippet:

result: 3
result: 3
result: 3
...

According to the documentation the function MPI_Fetch_and_op is atomic.

This operations is atomic with respect to other "accumulate"
  operations.

First Question:
Why is it not updating the value of result[0] to 4?

If I change the value of assert to MPI_MODE_NOCHECK it seems to work

Second Question:
Why is it working with MPI_MODE_NOCHECK

According to the documentation I thought this means the mutual exclusion has to be organized in a different way. Can someone explain the passage from the documentation of MPI_Win_lock_all()?

MPI_MODE_NOCHECK

No other process holds, or will attempt to acquire a conflicting lock, while the caller holds the window lock. This is useful when
  mutual exclusion is achieved by other means, but the coherence
  operations that may be attached to the lock and unlock calls are still
  required.

Thanks in advance!

Example program:

#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>

#define MASTER 0

int main(int argc, char *argv[])
{
  MPI_Init(&argc, &argv);
  MPI_Comm comm = MPI_COMM_WORLD;
  int r, p;
  MPI_Comm_rank(comm, &r);
  MPI_Comm_size(comm, &p);
  printf("Hello from %d\n", r);
  int result[1] = {0};
  //int assert = MPI_MODE_NOCHECK;
  int assert = 0;
  int one = 1;
  MPI_Win win_res;
  MPI_Win_allocate(1 * sizeof(MPI_INT), sizeof(MPI_INT), MPI_INFO_NULL, comm, &result[0], &win_res);
  MPI_Win_lock_all(assert, win_res);
  if (r == MASTER) {
    result[0] = 0;
    do{
      MPI_Fetch_and_op(&result, &result , MPI_INT, r, 0, MPI_NO_OP, win_res);
      printf("result: %d\n", result[0]);
    } while(result[0] != 4);
    printf("Master is done!\n");
  } else {
    MPI_Fetch_and_op(&one, &result, MPI_INT, 0, 0, MPI_SUM, win_res);
  }
  MPI_Win_unlock_all(win_res);
  MPI_Win_free(&win_res);
  MPI_Finalize();
  return 0;
}

Compiled with the following Makefile:

MPICC = mpicc
CFLAGS = -g -std=c99 -Wall -Wpedantic -Wextra

all: fetch_and

fetch_and: main.c
    $(MPICC) $(CFLAGS) -o $@ main.c

clean:
    rm fetch_and

run: all
    mpirun -np 5 ./fetch_and


问:
CSS Transitions max-width and max-height
So I have an object inside a div container. The object has the max-width (600px) and max-height (400px) properties set. When I hover the object, the properties are set to none so the object's width and height can be rendered properly. However when moving the mouse out of the object it immediatly changes it's width and height to the max-width (600px) and max-height (400px) values and after one second it falls back to it's original width and height values.

So how can I do the transitions to make the object change it's width and height smoothly, both, when hovering over it and when mousing out.

HTML:

```<code><html>
<!-- Blah blah some head tags here. -->
<body>
  <div id="c_a">
    <object data="https://www.google.ro/images/srpr/logo11w.png" type="image/png"></object>
  </div>
</body>
</html>
</code>```

CSS:

```<code>html{
  font-size: larger;
  width: 100%;
  height: 100%;
}
#c_a object{
  transition: width 1s linear .5s, height 1s linear .5s;
  -webkit-transition: width 1s linear .5s, height 1s linear .5s;
  -o-transition: width 1s linear .5s, height 1s linear .5s;
  -moz-transition: width 1s linear .5s, height 1s linear .5s;
  position: relative;
  width: 100%;
  height: 100%;
  max-width: 600px;
  max-height: 400px;
  vertical-align: text-top;
}
#c_a object:hover{
  width: 200%;
  height: 200%;
  max-width: none;
  max-height: none;
}
</code>```

Fiddle

答:
Simply, you can do like this

```<code>transition: max-width 1s linear .5s;
</code>```

Demo: http://jsfiddle.net/hvosanzL/

ContentLicense: CC BY-SA 3.0

Body:
So I have an object inside a div container. The object has the max-width (600px) and max-height (400px) properties set. When I hover the object, the properties are set to none so the object's width and height can be rendered properly. However when moving the mouse out of the object it immediatly changes it's width and height to the max-width (600px) and max-height (400px) values and after one second it falls back to it's original width and height values.

So how can I do the transitions to make the object change it's width and height smoothly, both, when hovering over it and when mousing out.

HTML:

    <object data="https://www.google.ro/images/srpr/logo11w.png" type="image/png"></object>

CSS:

html{
  font-size: larger;
  width: 100%;
  height: 100%;
}
#c_a object{
  transition: width 1s linear .5s, height 1s linear .5s;
  -webkit-transition: width 1s linear .5s, height 1s linear .5s;
  -o-transition: width 1s linear .5s, height 1s linear .5s;
  -moz-transition: width 1s linear .5s, height 1s linear .5s;
  position: relative;
  width: 100%;
  height: 100%;
  max-width: 600px;
  max-height: 400px;
  vertical-align: text-top;
}
#c_a object:hover{
  width: 200%;
  height: 200%;
  max-width: none;
  max-height: none;
}

Fiddle

Body:
Simply, you can do like this

transition: max-width 1s linear .5s;

Demo: http://jsfiddle.net/hvosanzL/


问:
How do I get all the links on a web page using requests-html
I am new to web parsing and want to make a program that gets all the internal and external links on a web page and I have no idea how to do this at all and all I have written is this

```<code>from requests_html import *

sss = HTMLSession()
k = sss.get('https://en.wikipedia.org/wiki')
hhh = HTML(html=k.html.html)
print(hhh.find('href'))
</code>```

I don't know why it prints [] when the href tags are everywhere
Thank you in advance

答:
You can get all the internal and external links using the code below. The code converts all relative links to absolute links.</p>

```<code>from requests_html import HTMLSession

base_url = 'https://en.wikipedia.org'
sss = HTMLSession()
k = sss.get('https://en.wikipedia.org/wiki')
links = k.html.absolute_links
print(links)
</code>```

Body:
I am new to web parsing and want to make a program that gets all the internal and external links on a web page and I have no idea how to do this at all and all I have written is this

from requests_html import *

sss = HTMLSession()
k = sss.get('https://en.wikipedia.org/wiki')
hhh = HTML(html=k.html.html)
print(hhh.find('href'))

I don't know why it prints [] when the href tags are everywhere
Thank you in advance

Body:
You can get all the internal and external links using the code below. The code converts all relative links to absolute links.

from requests_html import HTMLSession

base_url = 'https://en.wikipedia.org'
sss = HTMLSession()
k = sss.get('https://en.wikipedia.org/wiki')
links = k.html.absolute_links
print(links)


问:
Coldfusion page executed twice
Hi I am having a strange problem. On our development server coldfusion pages are executed twice. This happens everytime. To find out what is causing this issue, I send an email containing the request details to myself like this:

```<code><Cfmail from="*" to="*" type="html">
<cfdump var=#GetHttpRequestData()#>
#gettickcount()#
#createUUID()#
</cfmail>
</code>```

I get the following response when calling a page containing .cfm:

```<code>content [empty string]
headers struct
TOMCATCGIHTTPURL000000006A6B0000    /test.cfm
accept  */*
content-length  0
host    *
user-agent  curl/7.40.0

method  GET
protocol    HTTP/1.1
1590760731452
C7487929-D679-B029-6E236DEE7E19B8EB
</code>```

and a second mail containing

```<code>content [empty string]
headers struct
X-Original-URL  /test.cfm
accept  */*
content-length  0
host    *
user-agent  curl/7.40.0

method  GET
protocol    HTTP/1.1
1590760731425
C7487814-FA6F-4699-182C2E7382A06A47
</code>```

Now the really strange part. When i call an index.cfm without the filename like / the page is only executed once. For example calling a page located on /test/index.cfm as /test/ returns as single response:

```<code>content [empty string]
headers struct
X-Original-URL  /test/
accept  */*
content-length  0
host    *
user-agent  curl/7.40.0

method  GET
protocol    HTTP/1.1
1590762636945
C86B3A74-025F-6DBA-EA187DFEF7751F03
</code>```

Details of environment: Windows 2016 server, IIS 10, Coldfusion 2016

Any thoughts on what is causing this issue.

UPDATE

I use rewrite rules. I tested disabling the rewrite rules (as suggested by Miguel-F) and then the page is executed only once. When adding a simple rewrite rule like this the page is executed twice:

```<code><rule name="Test rule" stopProcessing="true">
<match url="^(.*)$" />
<action type="Rewrite" url="/{R:1}" appendQueryString="true" />
</rule>
</code>```

This behavior only occurs on our development server. Our production server has none of these issues and also runs on windows 2016 IIS 10 and coldfusion 2016.

Coldfusion version for development server: 2016.0.13.316217 (Production server runs on exactly the same version and has no issues)

答:
This is not really an answer, but a really long comment.

You need to find out if this is one request or two. Add in some code like this:

```<code>  <cfparam name="request.count" default="0">
  <cfset request.count++>

  <Cfmail from="*" to="*" type="html">
  <cfdump var=#GetHttpRequestData()#>
  Request.count: #request.count#
  <br />
  #gettickcount()#
  #createUUID()#
  </cfmail>
</code>```

If the file was requested twice, each email will say 1

If the file is being included somehow, then then second email will say the request count is 2

Title: Coldfusion page executed twice

Body:
Hi I am having a strange problem. On our development server coldfusion pages are executed twice. This happens everytime. To find out what is causing this issue, I send an email containing the request details to myself like this:

<Cfmail from="*" to="*" type="html">
<cfdump var=#GetHttpRequestData()#>
#gettickcount()#
#createUUID()#
</cfmail>

I get the following response when calling a page containing .cfm:

content [empty string]
headers struct
TOMCATCGIHTTPURL000000006A6B0000    /test.cfm
accept  */*
content-length  0
host    *
user-agent  curl/7.40.0

method  GET
protocol    HTTP/1.1
1590760731452
C7487929-D679-B029-6E236DEE7E19B8EB

and a second mail containing

content [empty string]
headers struct
X-Original-URL  /test.cfm
accept  */*
content-length  0
host    *
user-agent  curl/7.40.0

method  GET
protocol    HTTP/1.1
1590760731425
C7487814-FA6F-4699-182C2E7382A06A47

Now the really strange part. When i call an index.cfm without the filename like / the page is only executed once. For example calling a page located on /test/index.cfm as /test/ returns as single response:

content [empty string]
headers struct
X-Original-URL  /test/
accept  */*
content-length  0
host    *
user-agent  curl/7.40.0

method  GET
protocol    HTTP/1.1
1590762636945
C86B3A74-025F-6DBA-EA187DFEF7751F03

Details of environment: Windows 2016 server, IIS 10, Coldfusion 2016

Any thoughts on what is causing this issue.

UPDATE

I use rewrite rules. I tested disabling the rewrite rules (as suggested by Miguel-F) and then the page is executed only once. When adding a simple rewrite rule like this the page is executed twice:

<rule name="Test rule" stopProcessing="true">
<match url="^(.*)$" />
<action type="Rewrite" url="/{R:1}" appendQueryString="true" />
</rule>

This behavior only occurs on our development server. Our production server has none of these issues and also runs on windows 2016 IIS 10 and coldfusion 2016.

Coldfusion version for development server: 2016.0.13.316217 (Production server runs on exactly the same version and has no issues)

Body:
This is not really an answer, but a really long comment.

You need to find out if this is one request or two. Add in some code like this:

  <cfparam name="request.count" default="0">
  <cfset request.count++>

  <Cfmail from="*" to="*" type="html">
  <cfdump var=#GetHttpRequestData()#>
  Request.count: #request.count#
  <br />
  #gettickcount()#
  #createUUID()#
  </cfmail>

If the file was requested twice, each email will say 1

If the file is being included somehow, then then second email will say the request count is 2


问:
reactor zip two sources with conditions
I have two sources of sorted integers: A and B.

And I need to zip the two sources into one the restriction: Only zip these items who exist both in A and B.

For example:

A is:   1 2 3 10 11 12 13 14

B is:         10    12 13 14 15 16

The reactor's zip operator would generate (1,10),(2,12),(3,13),(10,14),(11,15),(12,16)

But I want to get this source: (10,10),(12,12),(13,13),(14,14)

I tried a zip and match approach below, but failed, because the first complete source will cause zip operator too complete the result source, and thus left source integer unmatched.

```<code>public static Flux<Tuple2<Integer, Integer>> match(Flux<Tuple2<Integer, Integer>> flux) {
        Tuple2<Integer, Integer> invalidValue = Tuples.of(0, 0);
        return flux.compose(f -> f.map(new Function<Tuple2<Integer, Integer>, Tuple2<Integer, Integer>>() {
            private final Queue<Integer> left = new ArrayDeque<>(); // here is a problem: when complete, left or right queue may still have some data.
            private final Queue<Integer> right = new ArrayDeque<>();

            @Override
            public Tuple2<Integer, Integer> apply(Tuple2<Integer, Integer> pair) {
                left.add(pair.getT1());
                right.add(pair.getT2());

                return tryMatch();
            }

            private Tuple2<Integer, Integer> tryMatch() {
                if (left.isEmpty() || right.isEmpty()) {
                    return invalidValue;
                }
                Integer t1 = left.peek();
                Integer t2 = right.peek();
                if (t1.equals(t2)) {
                    left.poll();
                    right.poll();
                    return Tuples.of(t1, t2);
                } else if (t1 < t2) {
                    Integer item = left.poll();
                    log.warn("not matched: {}", item);
                    return tryMatch();
                } else {
                    Integer item = right.poll();
                    log.warn("not matched: {}", item);
                    return tryMatch();
                }
            }
        })).filter(pair -> pair != invalidValue);
    }
</code>```

Could someone help me, tell me what operator can I use?

答:
No need to map it yourself you can use join and filter

```<code>Flux<Integer> f1 = Flux.just(1,2,3,10,11,12,13,14);
Flux<Integer> f2 = Flux.just(10,12,13,14,15,16);

f1.join(f2,f ->Flux.never(),f-> Flux.never(),Tuples::of)
                .filter(t -> t.getT1().equals(t.getT2()));
</code>```

Or if you want a function

```<code>public <T> Flux<Tuple2<T,T>> match(Flux<T> f1, Flux<T> f2){

    return f1.join(f2,f ->Flux.never(),f-> Flux.never(),Tuples::of)
            .filter(t -> t.getT1().equals(t.getT2()));

}
</code>```

Title: reactor zip two sources with conditions

Body:
I have two sources of sorted integers: A and B.

And I need to zip the two sources into one the restriction: Only zip these items who exist both in A and B.

For example:

A is:   1 2 3 10 11 12 13 14

B is:         10    12 13 14 15 16

The reactor's zip operator would generate (1,10),(2,12),(3,13),(10,14),(11,15),(12,16)

But I want to get this source: (10,10),(12,12),(13,13),(14,14)

I tried a zip and match approach below, but failed, because the first complete source will cause zip operator too complete the result source, and thus left source integer unmatched.

public static Flux<Tuple2<Integer, Integer>> match(Flux<Tuple2<Integer, Integer>> flux) {
        Tuple2<Integer, Integer> invalidValue = Tuples.of(0, 0);
        return flux.compose(f -> f.map(new Function<Tuple2<Integer, Integer>, Tuple2<Integer, Integer>>() {
            private final Queue<Integer> left = new ArrayDeque<>(); // here is a problem: when complete, left or right queue may still have some data.
            private final Queue<Integer> right = new ArrayDeque<>();

            @Override
            public Tuple2<Integer, Integer> apply(Tuple2<Integer, Integer> pair) {
                left.add(pair.getT1());
                right.add(pair.getT2());

                return tryMatch();
            }

            private Tuple2<Integer, Integer> tryMatch() {
                if (left.isEmpty() || right.isEmpty()) {
                    return invalidValue;
                }
                Integer t1 = left.peek();
                Integer t2 = right.peek();
                if (t1.equals(t2)) {
                    left.poll();
                    right.poll();
                    return Tuples.of(t1, t2);
                } else if (t1 < t2) {
                    Integer item = left.poll();
                    log.warn("not matched: {}", item);
                    return tryMatch();
                } else {
                    Integer item = right.poll();
                    log.warn("not matched: {}", item);
                    return tryMatch();
                }
            }
        })).filter(pair -> pair != invalidValue);
    }

Could someone help me, tell me what operator can I use?

Body:
No need to map it yourself you can use join and filter

Flux<Integer> f1 = Flux.just(1,2,3,10,11,12,13,14);
Flux<Integer> f2 = Flux.just(10,12,13,14,15,16);

f1.join(f2,f ->Flux.never(),f-> Flux.never(),Tuples::of)
                .filter(t -> t.getT1().equals(t.getT2()));

Or if you want a function

public <T> Flux<Tuple2<T,T>> match(Flux<T> f1, Flux<T> f2){

    return f1.join(f2,f ->Flux.never(),f-> Flux.never(),Tuples::of)
            .filter(t -> t.getT1().equals(t.getT2()));

}


问:
Box plot for specific columns in dataframe, with different colour
I am struggling to plot a boxplot for custom column names of dataframe and afterwards fill them with custom different colors. </p>

```<code>df=pd.DataFrame([[1,2,3],[3,4,3],[3,4,3]],columns=['x','y','z'])
df.boxplot(column=['x', 'y'])
plt.show()
</code>```

<p>I can't customize colours of my boxplots. Is there any way how to do it with simple code? </p>

答:
Try using this:</p>

```<code>df = pd.DataFrame([[1,2,3],[3,4,3],[3,4,3]], columns=['x','y','z'])
box = plt.boxplot([df['x'], df['y']], patch_artist=True)
colors = ['blue', 'green']
for patch, color in zip(box['boxes'], colors):
    patch.set_facecolor(color)
plt.show()
</code>```

Body:
I am struggling to plot a boxplot for custom column names of dataframe and afterwards fill them with custom different colors.

df=pd.DataFrame([[1,2,3],[3,4,3],[3,4,3]],columns=['x','y','z'])
df.boxplot(column=['x', 'y'])
plt.show()

I can't customize colours of my boxplots. Is there any way how to do it with simple code?

Body:
Try using this:

df = pd.DataFrame([[1,2,3],[3,4,3],[3,4,3]], columns=['x','y','z'])
box = plt.boxplot([df['x'], df['y']], patch_artist=True)
colors = ['blue', 'green']
for patch, color in zip(box['boxes'], colors):
    patch.set_facecolor(color)
plt.show()


问:
My tkinter button only works half the time
Im trying to learn to code, but my button "BuyRobot" only works sometimes and i dont know why. I want to be able to press the button multiple times, and for the label that show how many i have to be updated (labelRobot) I think it has something to do with being in a loop, but i have tried putting it outside the loop but i cant seem to get it to work. Any help would be greatly apreciated!</p>

```<code>from tkinter import *
import tkinter.font as tkFont
import time

n=1
Robot=0
def BuyRobotCommand():
    global n
    global Robot
    Robot+=n

vindu=Tk()
vindu.title("Robo Wood")
geo="1920x1080"
vindu.geometry("1920x1080")

WoodCurrency=99
Money=0
WoodCutter=0

fontStyle=tkFont.Font(size=20)
#labelWood=Label(vindu, text="You have "+str(WoodCurrency)+" wood", font=fontStyle).place(x=(1920/2)-100, y=100)
#BuyRobot=Button(vindu, text="Kjøp en robot", font=fontStyle, command=BuyRobotCommand(1)).place(x=300, y=300)

true=1
delay=0.1
while true:
    vindu.update()

    #Fikser penger, og trær
    WoodCurrency+=1*Robot
    labelWood=Label(vindu, text="You have "+str(WoodCurrency)+" wood", font=fontStyle).place(x=(1920/2)-100, y=80)
    if WoodCurrency>0:
        Money+=1
        WoodCurrency-=1
    labelMoney=Label(vindu, text="You have "+str(Money)+" money", font=fontStyle).place(x=(1920/2)-100, y=130)

    BuyRobot=Button(vindu, text="Kjøp en robot", font=fontStyle, command=BuyRobotCommand).place(x=300, y=300)
    labelRobot=Label(vindu, text="You have "+str(Robot)+" wood cutter robots", font=fontStyle).place(x=500, y=300)

    time.sleep(delay)

vindu.mainloop()
</code>```

答:
Here, you have to use window.after().

Code:

from tkinter import *
import tkinter.font as tkFont
import time

n=1
Robot=0
def BuyRobotCommand():
    global n
    global Robot
    Robot+=1

vindu=Tk()
vindu.title("Robo Wood")
geo="1920x1080"
vindu.geometry("1920x1080")

WoodCurrency=99
Money=0
WoodCutter=0

fontStyle=tkFont.Font(size=20)
labelMoney=Label(vindu, text="You have "+str(Money)+" money", font=fontStyle).place(x=(1920/2)-100, y=130)

BuyRobot=Button(vindu, text="Kjøp en robot", font=fontStyle, command=BuyRobotCommand).place(x=300, y=300)

#labelWood=Label(vindu, text="You have "+str(WoodCurrency)+" wood", font=fontStyle).place(x=(1920/2)-100, y=100)
#BuyRobot=Button(vindu, text="Kjøp en robot", font=fontStyle, command=BuyRobotCommand(1)).place(x=300, y=300)

true=1
delay=0.1
labelRobot=Label(vindu, text="You have "+str(Robot)+" wood cutter robots", font=fontStyle)
labelRobot.place(x=500, y=300)
def main_loop():
    global delay, true, WoodCurrency, Money, WoodCutter

    #Fikser penger, og trær
    WoodCurrency+=1*Robot
    if WoodCurrency>0:
        Money+=1
        WoodCurrency-=1

    labelRobot.configure(text = "You have "+str(Robot)+" wood cutter robots")

    vindu.after(100, main_loop)
main_loop()

vindu.mainloop()
```

Hope this helps!

Body:
Im trying to learn to code, but my button "BuyRobot" only works sometimes and i dont know why. I want to be able to press the button multiple times, and for the label that show how many i have to be updated (labelRobot) I think it has something to do with being in a loop, but i have tried putting it outside the loop but i cant seem to get it to work. Any help would be greatly apreciated!

from tkinter import *
import tkinter.font as tkFont
import time

n=1
Robot=0
def BuyRobotCommand():
    global n
    global Robot
    Robot+=n

vindu=Tk()
vindu.title("Robo Wood")
geo="1920x1080"
vindu.geometry("1920x1080")

WoodCurrency=99
Money=0
WoodCutter=0

fontStyle=tkFont.Font(size=20)
#labelWood=Label(vindu, text="You have "+str(WoodCurrency)+" wood", font=fontStyle).place(x=(1920/2)-100, y=100)
#BuyRobot=Button(vindu, text="Kjøp en robot", font=fontStyle, command=BuyRobotCommand(1)).place(x=300, y=300)

true=1
delay=0.1
while true:
    vindu.update()

    #Fikser penger, og trær
    WoodCurrency+=1*Robot
    labelWood=Label(vindu, text="You have "+str(WoodCurrency)+" wood", font=fontStyle).place(x=(1920/2)-100, y=80)
    if WoodCurrency>0:
        Money+=1
        WoodCurrency-=1
    labelMoney=Label(vindu, text="You have "+str(Money)+" money", font=fontStyle).place(x=(1920/2)-100, y=130)

    BuyRobot=Button(vindu, text="Kjøp en robot", font=fontStyle, command=BuyRobotCommand).place(x=300, y=300)
    labelRobot=Label(vindu, text="You have "+str(Robot)+" wood cutter robots", font=fontStyle).place(x=500, y=300)

    time.sleep(delay)

vindu.mainloop()

Body:
Here, you have to use window.after().

Code:

from tkinter import *
import tkinter.font as tkFont
import time

n=1
Robot=0
def BuyRobotCommand():
    global n
    global Robot
    Robot+=1

vindu=Tk()
vindu.title("Robo Wood")
geo="1920x1080"
vindu.geometry("1920x1080")

WoodCurrency=99
Money=0
WoodCutter=0

fontStyle=tkFont.Font(size=20)
labelMoney=Label(vindu, text="You have "+str(Money)+" money", font=fontStyle).place(x=(1920/2)-100, y=130)

BuyRobot=Button(vindu, text="Kjøp en robot", font=fontStyle, command=BuyRobotCommand).place(x=300, y=300)

#labelWood=Label(vindu, text="You have "+str(WoodCurrency)+" wood", font=fontStyle).place(x=(1920/2)-100, y=100)
#BuyRobot=Button(vindu, text="Kjøp en robot", font=fontStyle, command=BuyRobotCommand(1)).place(x=300, y=300)

true=1
delay=0.1
labelRobot=Label(vindu, text="You have "+str(Robot)+" wood cutter robots", font=fontStyle)
labelRobot.place(x=500, y=300)
def main_loop():
    global delay, true, WoodCurrency, Money, WoodCutter

    #Fikser penger, og trær
    WoodCurrency+=1*Robot
    if WoodCurrency>0:
        Money+=1
        WoodCurrency-=1

    labelRobot.configure(text = "You have "+str(Robot)+" wood cutter robots")

    vindu.after(100, main_loop)
main_loop()

vindu.mainloop()

Hope this helps!


问:
Assembly reflection problem in Release mode
I'm facing some weird behavior trying to get the parent assembly in some logging class (only when it's compiled in Release mode).

In Debug mode this works like a charm:

```<code>StackFrame[] frames = new StackTrace().GetFrames();
var assemblies = (from f in frames
                  select f.GetMethod().ReflectedType.Assembly)
                  Distinct()
                  .Last();
</code>```

Example:
assembly A => assembly B => method

when I run the above script in debug mode I get assembly A (as expected) but when it runs in release mode I get: mscorlib instead.
but the most weird thing is that if a check for the whole assemblies stack there is not a single reference of assembly A. how is this possible? what can be happening?

PS: assembly A is a webapp project.

答:
I was able to solve this issue. I think this problem is related with the compiler behaviour in release mode. I think it has something to be with the method inlining (even when I can't not be sure).

I found this conditions in order to prohibit the JIT from being able to inline a method (from here):

Methods that are greater than 32 bytes of IL will not be inlined.

Virtual functions are not inlined.

Methods that have complex flow control will not be in-lined. Complex flow control is any flow control other than if/then/else; in this case, switch or while.

Methods that contain exception-handling blocks are not inlined, though methods that throw exceptions are still candidates for inlining.

If any of the method's formal arguments are structs, the method will not be inlined.

I tried with all the above recommendations, but the only one that worked for me was to add a parameter (optional) to my method in order to get it greater than 32 bytes.

Hope this helps to anyone!

Body:
I'm facing some weird behavior trying to get the parent assembly in some logging class (only when it's compiled in Release mode).

In Debug mode this works like a charm:

StackFrame[] frames = new StackTrace().GetFrames();
var assemblies = (from f in frames
                  select f.GetMethod().ReflectedType.Assembly)
                  Distinct()
                  .Last();

Example:
assembly A => assembly B => method

when I run the above script in debug mode I get assembly A (as expected) but when it runs in release mode I get: mscorlib instead.
but the most weird thing is that if a check for the whole assemblies stack there is not a single reference of assembly A. how is this possible? what can be happening?

PS: assembly A is a webapp project.


问:
MongoDB pagination on arrays - Check if $slice reached the beginning of the array
In my application i have an box where users can read comments. If some user scrolls down, it loads more and more comments, everything fine. I slice the array from the back to the begin because i use $push whenever somebody write some comment so i slice it like this $slice: [ -5 , 5]. This will slice the last 5 elements out of the array. The -5 is actually an variable in my aggregation pipeline. Whenever i loaded some comments i decrease the value from -5 to -10 and so on so on. The problem i got here is if my array has an legth for example of 50, and i execute this slice $slice: [ -70, 5] i get the first 5 comments, but i expected to receive 0. The result is that i have an infinity scrollbar witch loads over and over the same 5 first comments. How do i fix this?

```<code>let result = await Post.aggregate([
    {
      $match: {
        _id: userId,
        "posts._id": postId
      }
    },
    {
      $addFields: {
        posts: {
          $map: {
            input: "$posts",
            as: "p",
            in: {
              _id: "$$p._id",
              comments: { $slice: ["$$p.comments", -start, 5] }
            }
          }
        }
      }
    },
    {
      $project: {
        posts: {
          $filter: {
            input: "$posts",
            as: "posts",
            cond: { $eq: ["$$posts._id", postId] }
          }
        }
      }
    }
  ]);
</code>```

答:
One way to do is to use $cond operator :

Query :

```<code>let inputPosition = -70
let positionConverted = -position // 70
let maxNumber = 1000

db.collection.aggregate([
    {
      $project: {
        comments: {
          $slice: [ "$comments",
            { $cond: [ { $gte: [ { $size: "$comments" }, positionConverted ] }, inputPosition, maxNumber ] }, 5 ] }
      }
    }
  ])
</code>```

Test : mongoplayground

Explanation :

So syntax of $slice is { $slice: [ <array>, <position>, <n> ] } from that if you pass a value larger than size of array for <position> then you'll get an empty array in response.

Here we're using $cond to conditionally send either value of inputPosition or value of maxNumber to <position>. Additionally, I've a hard coded value of maxNumber to 1000 but in general it all depends on your choice - You can use a lesser number, it doesn't matter, that number should be a greater value than size of your array, You can also you size of array + 1 but instead of doing that operation if you believe your array is always less than 1000 then directly use 1000.

Ref : $slice

Body:
In my application i have an box where users can read comments. If some user scrolls down, it loads more and more comments, everything fine. I slice the array from the back to the begin because i use $push whenever somebody write some comment so i slice it like this $slice: [ -5 , 5]. This will slice the last 5 elements out of the array. The -5 is actually an variable in my aggregation pipeline. Whenever i loaded some comments i decrease the value from -5 to -10 and so on so on. The problem i got here is if my array has an legth for example of 50, and i execute this slice $slice: [ -70, 5] i get the first 5 comments, but i expected to receive 0. The result is that i have an infinity scrollbar witch loads over and over the same 5 first comments. How do i fix this?

let result = await Post.aggregate([
    {
      $match: {
        _id: userId,
        "posts._id": postId
      }
    },
    {
      $addFields: {
        posts: {
          $map: {
            input: "$posts",
            as: "p",
            in: {
              _id: "$$p._id",
              comments: { $slice: ["$$p.comments", -start, 5] }
            }
          }
        }
      }
    },
    {
      $project: {
        posts: {
          $filter: {
            input: "$posts",
            as: "posts",
            cond: { $eq: ["$$posts._id", postId] }
          }
        }
      }
    }
  ]);

Body:
One way to do is to use $cond operator :

Query :

let inputPosition = -70
let positionConverted = -position // 70
let maxNumber = 1000

db.collection.aggregate([
    {
      $project: {
        comments: {
          $slice: [ "$comments",
            { $cond: [ { $gte: [ { $size: "$comments" }, positionConverted ] }, inputPosition, maxNumber ] }, 5 ] }
      }
    }
  ])

Test : mongoplayground

Explanation :

So syntax of $slice is { $slice: [ <array>, <position>, <n> ] } from that if you pass a value larger than size of array for <position> then you'll get an empty array in response.

Here we're using $cond to conditionally send either value of inputPosition or value of maxNumber to <position>. Additionally, I've a hard coded value of maxNumber to 1000 but in general it all depends on your choice - You can use a lesser number, it doesn't matter, that number should be a greater value than size of your array, You can also you size of array + 1 but instead of doing that operation if you believe your array is always less than 1000 then directly use 1000.

Ref : $slice


问:
Universal Links while app is not running
I am implementing Universal Links in my app. Every things works for me, except when the app is not running in the background. In that case how i can open a specific page in my app? iOS launches my app but i am not getting any callback in

- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray *))restorationHandler

in this function neither i am getting any url with this line

NSURL *launchURL = [launchOptions valueForKey:UIApplicationLaunchOptionsURLKey];
inside

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions this function.

Does anybody have an idea how i can get the url which caused to launch my application.

Thanks

答:
In Swift 5 with a SceneDelegate file it will call:

```<code>    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { }
</code>```

When your app is NOT running in background and user clicks on a universal link.

Body:
In Swift 5 with a SceneDelegate file it will call:

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { }

When your app is NOT running in background and user clicks on a universal link.


问:
How to remove a field completely from a MongoDB document?
```<code>{
    name: 'book',
    tags: {
        words: ['abc','123'],
        lat: 33,
        long: 22
    }
}
</code>```

Suppose this is a document. How do I remove "words" completely from all the documents in this collection? I want all documents to be without "words":

```<code> {
     name: 'book',
     tags: {
         lat: 33,
         long: 22
     }
}
</code>```

答:
Because I kept finding this page when looking for a way to remove a field using MongoEngine, I guess it might be helpful to post the MongoEngine way here too:</p>
```<code>Example.objects.all().update(unset__tags__words=1)
</code>```

Body:
{
    name: 'book',
    tags: {
        words: ['abc','123'],
        lat: 33,
        long: 22
    }
}

Suppose this is a document. How do I remove "words" completely from all the documents in this collection? I want all documents to be without "words":

 {
     name: 'book',
     tags: {
         lat: 33,
         long: 22
     }
}

Body:
Because I kept finding this page when looking for a way to remove a field using MongoEngine, I guess it might be helpful to post the MongoEngine way here too:

Example.objects.all().update(unset__tags__words=1)


问:
Selecting UITableViewCell programmatically?
I want to make a now playing button for my radio application. So would like to know how can I select a row programmatically I thought of calling didSelectRowAtIndexPath method but apparently we can't call it. </p>

答:
didSelectRowAtIndexPath is the method from delegate and it's called when you touch (select) the row in UITableView

Use below method to selct a row on your UITableView instance.

```<code>- (void)selectRowAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated scrollPosition:(UITableViewScrollPosition)scrollPosition
</code>```

See Sample code.

```<code>[myTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionMiddle];
</code>```

Body:
didSelectRowAtIndexPath is the method from delegate and it's called when you touch (select) the row in UITableView

Use below method to selct a row on your UITableView instance.

- (void)selectRowAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated scrollPosition:(UITableViewScrollPosition)scrollPosition

See Sample code.

[myTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionMiddle];


问:
Delimited file "|" with paragraph text including line breaks spanning multiple lines
I have a large TXT dataset that is delimited by | but there is a field that allows for paragraph text, which contains line breaks and blank lines. All lines that are not part of the paragraph text start with AA|. When I try to import into R via readr these values become NA because it doesn't follow the structure

Is there a way to use sed or awk to take a line if it doesn't start with AA| then to append it to the prior line that does with a space?

Input:

```<code>AA|5904060|9001084471200270|9000263372600200|Result Comment:
No (1, 3) Beta-D-Glucan detected.

This assay does not detect certain fungi, including
Cryptococcus species, which produce very low levels of (1,
3) Beta-D-Glucan (BDG) and the Mucorales (e.g., Lichthemia,
Mucor and Rhizopus), which are not known to produce BDG.
Additionally, the yeast phase of Blastomyces dermatitidis
produces little BDG and may not be detected by this assay.
|North Building|0|0
</code>```

Goal Output:

```<code>AA|5904060|9001084471200270|9000263372600200|Result Comment: No (1, 3) Beta-D-Glucan detected.  This assay does not detect certain fungi, including Cryptococcus species, which produce very low levels of (1, 3) Beta-D-Glucan (BDG) and the Mucorales (e.g., Lichthemia, Mucor and Rhizopus), which are not known to produce BDG. Additionally, the yeast phase of Blastomyces dermatitidis produces little BDG and may not be detected by this assay.|North Building|0|0
</code>```

答:
With GNU awk for multi-char RS and RT and assuming you know how many fields you should have in each record (8):

```<code>$ awk -v RS='([^|]*[|]){7}[^\n]*\n' '{$0=RT; $1=$1; gsub(/ *[|] */,"|")}1' file
AA|5904060|9001084471200270|9000263372600200|Result Comment: No (1, 3) Beta-D-Glucan detected. This assay does not detect certain fungi, including Cryptococcus species, which produce very low levels of (1, 3) Beta-D-Glucan (BDG) and the Mucorales (e.g., Lichthemia, Mucor and Rhizopus), which are not known to produce BDG. Additionally, the yeast phase of Blastomyces dermatitidis produces little BDG and may not be detected by this assay.|North Building|0|0
</code>```

Otherwise if you don't have GNU awk or only know that all records start with a line starting with AA| then using any awk:

```<code>$ awk '/^AA\|/ { if (NR>1) prt(); rec="" } { rec = rec OFS $0 } END{ prt() }
    function prt(o){o=$0; $0=rec; $1=$1; gsub(/[[:space:]]*[|][[:space:]]*/,"|"); print; $0=o}
' file
AA|5904060|9001084471200270|9000263372600200|Result Comment: No (1, 3) Beta-D-Glucan detected. This assay does not detect certain fungi, including Cryptococcus species, which produce very low levels of (1, 3) Beta-D-Glucan (BDG) and the Mucorales (e.g., Lichthemia, Mucor and Rhizopus), which are not known to produce BDG. Additionally, the yeast phase of Blastomyces dermatitidis produces little BDG and may not be detected by this assay.|North Building|0|0
</code>```

Body:
I have a large TXT dataset that is delimited by | but there is a field that allows for paragraph text, which contains line breaks and blank lines. All lines that are not part of the paragraph text start with AA|. When I try to import into R via readr these values become NA because it doesn't follow the structure

Is there a way to use sed or awk to take a line if it doesn't start with AA| then to append it to the prior line that does with a space?

Input:

AA|5904060|9001084471200270|9000263372600200|Result Comment:
No (1, 3) Beta-D-Glucan detected.

This assay does not detect certain fungi, including
Cryptococcus species, which produce very low levels of (1,
3) Beta-D-Glucan (BDG) and the Mucorales (e.g., Lichthemia,
Mucor and Rhizopus), which are not known to produce BDG.
Additionally, the yeast phase of Blastomyces dermatitidis
produces little BDG and may not be detected by this assay.
|North Building|0|0

Goal Output:

AA|5904060|9001084471200270|9000263372600200|Result Comment: No (1, 3) Beta-D-Glucan detected.  This assay does not detect certain fungi, including Cryptococcus species, which produce very low levels of (1, 3) Beta-D-Glucan (BDG) and the Mucorales (e.g., Lichthemia, Mucor and Rhizopus), which are not known to produce BDG. Additionally, the yeast phase of Blastomyces dermatitidis produces little BDG and may not be detected by this assay.|North Building|0|0

Body:
With GNU awk for multi-char RS and RT and assuming you know how many fields you should have in each record (8):

$ awk -v RS='([^|]*[|]){7}[^\n]*\n' '{$0=RT; $1=$1; gsub(/ *[|] */,"|")}1' file
AA|5904060|9001084471200270|9000263372600200|Result Comment: No (1, 3) Beta-D-Glucan detected. This assay does not detect certain fungi, including Cryptococcus species, which produce very low levels of (1, 3) Beta-D-Glucan (BDG) and the Mucorales (e.g., Lichthemia, Mucor and Rhizopus), which are not known to produce BDG. Additionally, the yeast phase of Blastomyces dermatitidis produces little BDG and may not be detected by this assay.|North Building|0|0

Otherwise if you don't have GNU awk or only know that all records start with a line starting with AA| then using any awk:

$ awk '/^AA\|/ { if (NR>1) prt(); rec="" } { rec = rec OFS $0 } END{ prt() }
    function prt(o){o=$0; $0=rec; $1=$1; gsub(/[[:space:]]*[|][[:space:]]*/,"|"); print; $0=o}
' file
AA|5904060|9001084471200270|9000263372600200|Result Comment: No (1, 3) Beta-D-Glucan detected. This assay does not detect certain fungi, including Cryptococcus species, which produce very low levels of (1, 3) Beta-D-Glucan (BDG) and the Mucorales (e.g., Lichthemia, Mucor and Rhizopus), which are not known to produce BDG. Additionally, the yeast phase of Blastomyces dermatitidis produces little BDG and may not be detected by this assay.|North Building|0|0


问:
Updating URL window history based on multi groups of checkboxes
How can I update the parameters of URL(window.history) based on multi groups of check-boxes if any of group been checked?

Like (if only the make selected)

```<code>www.mydomain/filters?make=toyota,honda
</code>```

or if make and model is selected

```<code>www.mydomain/filters?make=toyota,honda&model=crv,cx5
</code>```

$(document).ready(function() {

  $("input:checkbox[name='make']").change(function() {
    var makechecks = [];
    $("input[type='checkbox']:checked").each(function() {
      makechecks[makechecks.length] = this.value;
    });
      console.log( makechecks.join() );
  });

  $("input:checkbox[name='model']").change(function() {
    var modelchecks = [];
    $("input[type='checkbox']:checked").each(function() {
      modelchecks[modelchecks.length] = this.value;
    });
      console.log( modelchecks.join() );
  });

  $("input:checkbox[name='year']").change(function() {
    var yearchecks = [];
    $("input[type='checkbox']:checked").each(function() {
      yearchecks[yearchecks.length] = this.value;
    });
      console.log( yearchecks.join() );
  });

  function UpdateURL(){
     window.history.pushState( {} , '', '');
  }

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 <div id="make">
    <p>Toyota :<input type="checkbox" name="make" value="toyota"></p>
    <p>Honda : <input type="checkbox" name="make" value="honda"></p>
    <p>Mazda : <input type="checkbox" name="make" value="mazda"></p>
  </div>

  <div id="model">
    <p>CRV  :<input type="checkbox" name="model" value="crv"></p>
    <p>RAV4 :<input type="checkbox" name="model" value="rav4"></p>
    <p>CX5  :<input type="checkbox" name="model" value="cx5"></p>
  </div>

  <div id="year">
    <p>2020 :<input type="checkbox" name="year" value="2020"></p>
    <p>2019 :<input type="checkbox" name="year" value="2019"></p>
    <p>2018 :<input type="checkbox" name="year" value="2018"></p>
  </div></code>```

答:
Something like this?

const createURL = () => {
  let urlSearch = new URLSearchParams()
  let make  = $("[name=make]:checked" ).map((_,chk) => chk.value).get()
  let model = $("[name=model]:checked").map((_,chk) => chk.value).get()
  let year  = $("[name=year]:checked" ).map((_,chk) => chk.value).get()
  if (make.length  > 0) urlSearch.set("make",  make.join(","))
  if (model.length > 0) urlSearch.set("model", model.join(","))
  if (year.length  > 0) urlSearch.set("year",  year.join(","))
  const srch = urlSearch.toString();
  console.log(srch);
  // history.pushState({}, "Results for `Cars`", srch ? "?"+srch : "");
};
$(function() {
  $("input:checkbox").on("change", createURL)
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="make">
  <p>Toyota :<input type="checkbox" name="make" value="toyota"></p>
  <p>Honda : <input type="checkbox" name="make" value="honda"></p>
  <p>Mazda : <input type="checkbox" name="make" value="mazda"></p>
</div>

<div id="model">
  <p>CRV :<input type="checkbox" name="model" value="crv"></p>
  <p>RAV4 :<input type="checkbox" name="model" value="rav4"></p>
  <p>CX5 :<input type="checkbox" name="model" value="cx5"></p>
</div>

<div id="year">
  <p>2020 :<input type="checkbox" name="year" value="2020"></p>
  <p>2019 :<input type="checkbox" name="year" value="2019"></p>
  <p>2018 :<input type="checkbox" name="year" value="2018"></p>
</div></code>```

Body:
How can I update the parameters of URL(window.history) based on multi groups of check-boxes if any of group been checked?

Like (if only the make selected)

www.mydomain/filters?make=toyota,honda

or if make and model is selected

www.mydomain/filters?make=toyota,honda&model=crv,cx5

$(document).ready(function() {

  $("input:checkbox[name='make']").change(function() {
    var makechecks = [];
    $("input[type='checkbox']:checked").each(function() {
      makechecks[makechecks.length] = this.value;
    });
      console.log( makechecks.join() );
  });

  $("input:checkbox[name='model']").change(function() {
    var modelchecks = [];
    $("input[type='checkbox']:checked").each(function() {
      modelchecks[modelchecks.length] = this.value;
    });
      console.log( modelchecks.join() );
  });

  $("input:checkbox[name='year']").change(function() {
    var yearchecks = [];
    $("input[type='checkbox']:checked").each(function() {
      yearchecks[yearchecks.length] = this.value;
    });
      console.log( yearchecks.join() );
  });

  function UpdateURL(){
     window.history.pushState( {} , '', '');
  }

});

Toyota :<input type="checkbox" name="make" value="toyota">

Honda : <input type="checkbox" name="make" value="honda">

Mazda : <input type="checkbox" name="make" value="mazda">

CRV  :<input type="checkbox" name="model" value="crv">

RAV4 :<input type="checkbox" name="model" value="rav4">

CX5  :<input type="checkbox" name="model" value="cx5">

2020 :<input type="checkbox" name="year" value="2020">

2019 :<input type="checkbox" name="year" value="2019">

2018 :<input type="checkbox" name="year" value="2018">

Body:
Something like this?

const createURL = () => {
  let urlSearch = new URLSearchParams()
  let make  = $("[name=make]:checked" ).map((_,chk) => chk.value).get()
  let model = $("[name=model]:checked").map((_,chk) => chk.value).get()
  let year  = $("[name=year]:checked" ).map((_,chk) => chk.value).get()
  if (make.length  > 0) urlSearch.set("make",  make.join(","))
  if (model.length > 0) urlSearch.set("model", model.join(","))
  if (year.length  > 0) urlSearch.set("year",  year.join(","))
  const srch = urlSearch.toString();
  console.log(srch);
  // history.pushState({}, "Results for `Cars`", srch ? "?"+srch : "");
};
$(function() {
  $("input:checkbox").on("change", createURL)
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="make">
  <p>Toyota :<input type="checkbox" name="make" value="toyota"></p>
  <p>Honda : <input type="checkbox" name="make" value="honda"></p>
  <p>Mazda : <input type="checkbox" name="make" value="mazda"></p>
</div>

<div id="model">
  <p>CRV :<input type="checkbox" name="model" value="crv"></p>
  <p>RAV4 :<input type="checkbox" name="model" value="rav4"></p>
  <p>CX5 :<input type="checkbox" name="model" value="cx5"></p>
</div>

<div id="year">
  <p>2020 :<input type="checkbox" name="year" value="2020"></p>
  <p>2019 :<input type="checkbox" name="year" value="2019"></p>
  <p>2018 :<input type="checkbox" name="year" value="2018"></p>
</div>