问:
Xcode Unit Testing with Cocoapods
I've been banging my head against a wall with this for the last few days but despite multiple Google/SO/Github searches I can't find a resolution to the issues I'm having!

All I'm trying to do is create some unit tests for my app which makes use of Firebase pods.

I'm using Xcode 7.3.1 & Cocoapods 1.0.1. Update: Issue remains with Xcode 8.0

With this podfile:

```<code>platform :ios, '9.0'
use_frameworks!
inhibit_all_warnings!

target 'MyApp' do
    pod 'Firebase'
    pod 'Firebase/Auth'
    pod 'Firebase/Database'
    pod 'Firebase/Storage'

    target 'MyAppTests' do
        inherit! :search_paths
    end
end
</code>```

In my XCTest class I get

Missing required module 'Firebase'

error at @testable import MyApp

Alternatively with this podfile:

```<code>platform :ios, '9.0'
use_frameworks!
inhibit_all_warnings!

def common_pods
    pod 'SwiftyTimer'
    pod 'Firebase'
    pod 'Firebase/Auth'
    pod 'Firebase/Database'
    pod 'Firebase/Storage'
end

target 'MyApp' do
    common_pods
end

target 'MyAppTests' do
    common_pods
end
</code>```

The tests build but my console is littered with warnings e.g.:

Class <-FirebaseClassName-> is implemented in both ...MyApp... and
  ...MyAppTests... One of the two will be used. Which one is undefined

答:
The problem is recorded in the firebase project here:

https://github.com/firebase/firebase-ios-sdk/issues/58

There is a workaround:

Add "${PODS_ROOT}/Firebase/Core/Sources" to your Tests target only
  under Build Settings -> Header Search Paths

but this is also fixed by upgrading to CocoaPods 1.4.0 or later, which is a better solution.

At the time I'm writing this (November 2017) cocoapods 1.4.0 is still in beta, so to install it you need to explicitly request the beta:

```<code>gem install cocoapods --pre
</code>```

This and then doing a pod install solved the problem running my tests.

Title: Xcode Unit Testing with Cocoapods

Body:
I've been banging my head against a wall with this for the last few days but despite multiple Google/SO/Github searches I can't find a resolution to the issues I'm having!

All I'm trying to do is create some unit tests for my app which makes use of Firebase pods.

I'm using Xcode 7.3.1 & Cocoapods 1.0.1. Update: Issue remains with Xcode 8.0

With this podfile:

platform :ios, '9.0'
use_frameworks!
inhibit_all_warnings!

target 'MyApp' do
    pod 'Firebase'
    pod 'Firebase/Auth'
    pod 'Firebase/Database'
    pod 'Firebase/Storage'

    target 'MyAppTests' do
        inherit! :search_paths
    end
end

In my XCTest class I get

Missing required module 'Firebase'

error at @testable import MyApp

Alternatively with this podfile:

platform :ios, '9.0'
use_frameworks!
inhibit_all_warnings!

def common_pods
    pod 'SwiftyTimer'
    pod 'Firebase'
    pod 'Firebase/Auth'
    pod 'Firebase/Database'
    pod 'Firebase/Storage'
end

target 'MyApp' do
    common_pods
end

target 'MyAppTests' do
    common_pods
end

The tests build but my console is littered with warnings e.g.:

Class <-FirebaseClassName-> is implemented in both ...MyApp... and
  ...MyAppTests... One of the two will be used. Which one is undefined

Body:
The problem is recorded in the firebase project here:

https://github.com/firebase/firebase-ios-sdk/issues/58

There is a workaround:

Add "${PODS_ROOT}/Firebase/Core/Sources" to your Tests target only
  under Build Settings -> Header Search Paths

but this is also fixed by upgrading to CocoaPods 1.4.0 or later, which is a better solution.

At the time I'm writing this (November 2017) cocoapods 1.4.0 is still in beta, so to install it you need to explicitly request the beta:

gem install cocoapods --pre

This and then doing a pod install solved the problem running my tests.


来源: stackexchange

问:
Drop unused factor combination in ggplot
I wonder if it is possible to plot factor "b" only on panel "2"?
I really appreciate any help!

```<code>library(tidyverse)

df <- tibble(
  group = c(1, 2, 1),
  item_name = factor(c("a", "b", "b")),
  value1 = 1:3
)

df %>% ggplot(aes(item_name, value1)) + geom_point() + facet_wrap(~group)
</code>```

答:
```<code>df %>%
ggplot(aes(item_name, value1)) +
geom_point() +
facet_wrap(~group, scale="free_x")
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I wonder if it is possible to plot factor "b" only on panel "2"?
I really appreciate any help!

library(tidyverse)

df <- tibble(
  group = c(1, 2, 1),
  item_name = factor(c("a", "b", "b")),
  value1 = 1:3
)

df %>% ggplot(aes(item_name, value1)) + geom_point() + facet_wrap(~group)


问:
Can onResume be called two times with no onPause in between in the same Activity?
I've made an observation that on certain Android devices (Galaxy S8, LG, Motorola) onResume is being called two times in a row with no onPause in between. This pattern happens after onNewIntent. Here is the sequence of logs in a dummy app:

```<code>Step 1. User starts the app
11-08 09:25:58.708 [MyActivity, hashcode - 126479478] onCreate
11-08 09:25:58.896 [MyActivity, hashcode - 126479478] onStart
11-08 09:25:58.971 [MyActivity, hashcode - 126479478] onResume

Step 2. User goes to background
11-08 09:26:04.949 [MyActivity, hashcode - 126479478] onPause
11-08 09:26:05.830 [MyActivity, hashcode - 126479478] onStop

Step 3. User comes back to the app
11-08 09:26:49.470 [MyActivity, hashcode - 126479478] onNewIntent
11-08 09:26:49.507 [MyActivity, hashcode - 126479478] onStart
11-08 09:26:49.530 [MyActivity, hashcode - 126479478] onResume

Step 4: We get second on resume
11-08 09:26:55.088 [MyActivity, hashcode - 126479478] onResume
</code>```

Does Android Framework guarantee onPause after each onResume given that the app is forcefully not killed by an OS? I always assumed it as true by default, but can’t find any reference for it in documentation.

答:
Did you check the Android Activity lifecycle?

https://developer.android.com/guide/components/activities/activity-lifecycle.html

Body:
I've made an observation that on certain Android devices (Galaxy S8, LG, Motorola) onResume is being called two times in a row with no onPause in between. This pattern happens after onNewIntent. Here is the sequence of logs in a dummy app:

Step 1. User starts the app
11-08 09:25:58.708 [MyActivity, hashcode - 126479478] onCreate
11-08 09:25:58.896 [MyActivity, hashcode - 126479478] onStart
11-08 09:25:58.971 [MyActivity, hashcode - 126479478] onResume

Step 2. User goes to background
11-08 09:26:04.949 [MyActivity, hashcode - 126479478] onPause
11-08 09:26:05.830 [MyActivity, hashcode - 126479478] onStop

Step 3. User comes back to the app
11-08 09:26:49.470 [MyActivity, hashcode - 126479478] onNewIntent
11-08 09:26:49.507 [MyActivity, hashcode - 126479478] onStart
11-08 09:26:49.530 [MyActivity, hashcode - 126479478] onResume

Step 4: We get second on resume
11-08 09:26:55.088 [MyActivity, hashcode - 126479478] onResume

Does Android Framework guarantee onPause after each onResume given that the app is forcefully not killed by an OS? I always assumed it as true by default, but can’t find any reference for it in documentation.


问:
Calculating modulus by recursion without using modulo division
I'm doing a problem with recursive functions for a class project.  I'm trying to write a program that uses a recursive function that calculates a modulus without actually using the modulus operator.  I'm trying to use a reference parameter because I think that's the easiest way to do this, however my program is not functioning as intended.  </p>

```<code>//Michael Hery
//COP 2001
//11/15/2017
//Recursive Modulus

#include <iostream>
#include <iomanip>

using namespace std;

int recursiveMod(int &, int);

int main()
{
    int num;
    int den;
    int displayNum;
    int total;

    cout << "Please input the numerator (an integer) >> ";
    cin >> num;
    while (num < 0)
    {
        cout << "Integer must be greater than or equal to zero. >> ";
        cin >> num;
    }
    displayNum = num;
    cout << "Please input the denominator (an integer) >> ";
    cin >> den;
    while (den <= 0)
    {
        cout << "Integer must be greater than zero. >> ";
        cin >> den;
    }
    cout << "You have entered " << num << " % " << den << endl;

    total = recursiveMod(num, den);

    cout << "Modulus result: " << displayNum << " % " << den << " = " << total << endl;

    system("PAUSE");
    return 0;
}

int recursiveMod(int &num, int den)
{
    if (num == 0)
        return 0;

    num = num - den;

    if ((num - den) > den)
    {
        recursiveMod(num, den);
    }
    return num;
}
</code>```

答:
The problem is this line:

```<code> if ((num - den) > den)
</code>```

For example, if num is 4 and den is 3, then 4-3 is 1 and 1 is not greater than 3, so you will return 4. What you want is

```<code> if (num > den)
</code>```

Body:
I'm doing a problem with recursive functions for a class project.  I'm trying to write a program that uses a recursive function that calculates a modulus without actually using the modulus operator.  I'm trying to use a reference parameter because I think that's the easiest way to do this, however my program is not functioning as intended.

//Michael Hery
//COP 2001
//11/15/2017
//Recursive Modulus

#include <iostream>
#include <iomanip>

using namespace std;

int recursiveMod(int &, int);

int main()
{
    int num;
    int den;
    int displayNum;
    int total;

    cout << "Please input the numerator (an integer) >> ";
    cin >> num;
    while (num < 0)
    {
        cout << "Integer must be greater than or equal to zero. >> ";
        cin >> num;
    }
    displayNum = num;
    cout << "Please input the denominator (an integer) >> ";
    cin >> den;
    while (den <= 0)
    {
        cout << "Integer must be greater than zero. >> ";
        cin >> den;
    }
    cout << "You have entered " << num << " % " << den << endl;

    total = recursiveMod(num, den);

    cout << "Modulus result: " << displayNum << " % " << den << " = " << total << endl;

    system("PAUSE");
    return 0;
}

int recursiveMod(int &num, int den)
{
    if (num == 0)
        return 0;

    num = num - den;

    if ((num - den) > den)
    {
        recursiveMod(num, den);
    }
    return num;
}

Body:
The problem is this line:

 if ((num - den) > den)

For example, if num is 4 and den is 3, then 4-3 is 1 and 1 is not greater than 3, so you will return 4. What you want is

 if (num > den)


问:
How to permanently rename C# project's Properties namespace
In another project I have classes that use the name Properties and thus it becomes a hassle to work with them when the pre-generated Settings' and Resources' Properties namespace gets in the way. Is there a way to force this namespace to stay renamed even after making modifications to resources or settings?

The following are the files causing issues.

Resources.Designer.cs

```<code>//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace ProjectNamespace.Properties {
    using System;
</code>```

Settings.Designer.cs

```<code>//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace ProjectNamespace.Properties {
</code>```

If it's not clear. I want to rename Properties, not ProjectName.

答:
It sounds like you've added your Settings and Resources files through the project properties window, under the corresponding tabs (where you can add default files for these items). When you do it this way, the name .Properties is appended to the namespace, and they are organized under the Properties node of the project in the Solution Explorer:

Instead, try adding them as separate project items. To do this, right-click on your project, choose Add --> New Item, select the General heading under Visual C# Items, and then you can add a new Resources File and/or Settings File:

These files will be added to your project like any other item (not under the Properties node), and will use your project's default namespace, and will not add .Properties to it:

Body:
In another project I have classes that use the name Properties and thus it becomes a hassle to work with them when the pre-generated Settings' and Resources' Properties namespace gets in the way. Is there a way to force this namespace to stay renamed even after making modifications to resources or settings?

The following are the files causing issues.

Resources.Designer.cs

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace ProjectNamespace.Properties {
    using System;

Settings.Designer.cs

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace ProjectNamespace.Properties {

If it's not clear. I want to rename Properties, not ProjectName.


问:
Why is my Python App Engine app using the Translate API getting an error of ImportError: No module named apiclient.discovery?
I got this error in Google App Engine's Python have used Google Translate API,
But I don't know how to fix,

```<code><module>
from apiclient.discovery import build
ImportError: No module named apiclient.discovery
</code>```

I'll try to set environment which indicates to Google App Engine SDK,
And upload to Google Apps Engine again, always get the error,

Error: Server Error

The server encountered an error and could not complete your request.
  If the problem persists, please report your problem and mention this error message and the query that caused it.

Please tell me how to fix,

Thanks

UPDATE : Fixed
Follow Nijjin's help,
I fixed problems by adding the following folders,

apiclient, gflags, httplib2, oauth2client, uritemplate

If you still got problem, please consider below Answer of this page to get more info. ex. : Varum answer, etc ...

答:
I got this same error when working on a project to parse recent calendar events from Google Calendar.

Using the standard install with pip did not work for me, here is what I did to get the packages I needed.

Go directly to the source, here is a link for the google-api-python-client, but if you need a different language it should not be too different.

https://github.com/google/google-api-python-client

Click on the green "Clone or Download" button near the top left and save it as a zip file. Move the zip to your project folder and extract it there. Then cut all the files from the folder it creates back into the root of your project folder.

Yes, this does clutter your work space, but many compilers have ways to hide files.

After doing this the standard

```<code>from googleapiclient import discovery
</code>```

works great.

Hope this helps.

ContentLicense: CC BY-SA 4.0

Body:
I got this error in Google App Engine's Python have used Google Translate API,
But I don't know how to fix,

<module>
from apiclient.discovery import build
ImportError: No module named apiclient.discovery

I'll try to set environment which indicates to Google App Engine SDK,
And upload to Google Apps Engine again, always get the error,

Error: Server Error

The server encountered an error and could not complete your request.
  If the problem persists, please report your problem and mention this error message and the query that caused it.

Please tell me how to fix,

Thanks

UPDATE : Fixed
Follow Nijjin's help,
I fixed problems by adding the following folders,

apiclient, gflags, httplib2, oauth2client, uritemplate

If you still got problem, please consider below Answer of this page to get more info. ex. : Varum answer, etc ...

Body:
I got this same error when working on a project to parse recent calendar events from Google Calendar.

Using the standard install with pip did not work for me, here is what I did to get the packages I needed.

Go directly to the source, here is a link for the google-api-python-client, but if you need a different language it should not be too different.

https://github.com/google/google-api-python-client

Click on the green "Clone or Download" button near the top left and save it as a zip file. Move the zip to your project folder and extract it there. Then cut all the files from the folder it creates back into the root of your project folder.

Yes, this does clutter your work space, but many compilers have ways to hide files.

After doing this the standard

from googleapiclient import discovery

works great.

Hope this helps.


问:
read and write same file bash/unix
I have a list of keys which are listed in a txt file

sample.txt
    address
    contact_id
    created_at
    creator_id
    custom_fields
    address
    contact_id
    phone
    name
    email
    name

I have the following recursive script which can remove duplicates

```<code>#!/bin/bash
function keyChecker(){
    if grep -q $i uniqueKeys.txt; then
        echo "Duplicate Key: ${i}"
    else
        echo $i >> uniqueKeys.txt
         echo "New key: ${i}"
    fi
}

function recursiveDoer(){
    for i in $(cat keys.txt); do
        keyChecker $i
    done
recursiveDoer
}
touch uniqueKeys.txt
counter=0
recursiveDoer
</code>```

This code will return a unique list of keys to uniqueKeys.txt

These methods will send into an infinite loop once there are no more duplicates. Every recursive method I have wrote runs into this problem. I usually cheat by adding a counter that forces an exit 1 after an arbitrarily large number like 10,000.

What is the proper way to write this method using recursion and no infinite loop?

Can this be simplified and written as a non-recursive method in a single loop?

答:
awk to the rescue!

this awk magic will only print the unique entries in the same order

```<code>awk '!a[$0]++' file
</code>```

you can overwrite the input file with this idiom

```<code>awk '!a[$0]++' file > temp && mv temp file
</code>```

this probably replicates your code

```<code>awk '!a[$0]++ {print "New key: " $0;
               print > "uniqueKeys.txt"
               next}
              {print "Duplicate Key: " $0}' file
</code>```

Explanation

a[$0] creates an entry in the associative map a for the read line as the key.  ++ forces the null value to be treated as 0 and increments. ! forces the value to be treated as Boolean and negates it.  Taken all together, it will be only true for the first time the key is seen, therefore effectively de-duplicating the lines in the file.

Title: read and write same file bash/unix

Body:
I have a list of keys which are listed in a txt file

sample.txt
    address
    contact_id
    created_at
    creator_id
    custom_fields
    address
    contact_id
    phone
    name
    email
    name

I have the following recursive script which can remove duplicates

#!/bin/bash
function keyChecker(){
    if grep -q $i uniqueKeys.txt; then
        echo "Duplicate Key: ${i}"
    else
        echo $i >> uniqueKeys.txt
         echo "New key: ${i}"
    fi
}

function recursiveDoer(){
    for i in $(cat keys.txt); do
        keyChecker $i
    done
recursiveDoer
}
touch uniqueKeys.txt
counter=0
recursiveDoer

This code will return a unique list of keys to uniqueKeys.txt

These methods will send into an infinite loop once there are no more duplicates. Every recursive method I have wrote runs into this problem. I usually cheat by adding a counter that forces an exit 1 after an arbitrarily large number like 10,000.

What is the proper way to write this method using recursion and no infinite loop?

Can this be simplified and written as a non-recursive method in a single loop?

Body:
awk to the rescue!

this awk magic will only print the unique entries in the same order

awk '!a[$0]++' file

you can overwrite the input file with this idiom

awk '!a[$0]++' file > temp && mv temp file

this probably replicates your code

awk '!a[$0]++ {print "New key: " $0;
               print > "uniqueKeys.txt"
               next}
              {print "Duplicate Key: " $0}' file

Explanation

a[$0] creates an entry in the associative map a for the read line as the key.  ++ forces the null value to be treated as 0 and increments. ! forces the value to be treated as Boolean and negates it.  Taken all together, it will be only true for the first time the key is seen, therefore effectively de-duplicating the lines in the file.


问:
JavaScript: Why is my While-Loop Infinitely Looping?
I have a while loop that is an algorithm for a certain array path and I made it in javaScript. Here is the code.

```<code>var Row1 = [0, 0, 0, 0, 0];
var Row2 = [0, 0, 0, 0, 0];
var Row3 = [0, 0, 0, 0, 0];
var Row4 = [0, 0, 0, 0, 0];
var Row5 = [0, 0, 0, 0, 0];
var AllRows = [];

//Add Rows
AllRows.push(Row1, Row2, Row3, Row4, Row5);
console.log(AllRows);

//First Value
var SV1 = [0, (AllRows.length - 1)];
var SV2 = [0, (AllRows.length - 1)];

var GetSV1 = Math.floor(Math.random()*(SV1.length - 1));
var GetSV2 = Math.floor(Math.random()*(SV2.length - 1));
AllRows[GetSV1][GetSV2] = 1;

var Steps = 1;
var PD = "false";
var RV1 = null;
var RV2 = null;
while(PD == "false"){
    RV1 = Math.floor(Math.random()*(AllRows.length - 1));
    RV2 = Math.floor(Math.random()*(AllRows.length - 1));
    if(AllRows[RV1][RV2] == AllRows[GetSV1][GetSV2] || AllRows[RV1][RV2] == "X"){
        continue;
    } else {
        AllRows[RV1][RV2] = 1;
    }

    if(AllRows[0][0] == 1){
        if(Steps >= 1 && AllRows[0][1] == 1){
            AllRows[1][0] = "X";
            Steps++;
            continue;
        } else if(Steps >= 1 && AllRows[1][0] == 1){
            AllRows[0][1] = "X";
            Steps++;
            continue;
        } else{
            AllRows[0][1] = 0;
            AllRows[1][0] = 0;
            AllRows[GetSV1][GetSV2] = 0;
        }
        if(Steps >= 2 && AllRows[0][2] == 1){
            AllRows[1][1] = "X";
            Steps++;
            continue;
        } else if(Steps >= 2 && AllRows[1][1] == 1){
            AllRows[0][2] = "X";
            AllRows[2][0] = "X";
            Steps++;
            continue;
        } else if(Steps >= 2 && AllRows[2][0] == 1){
            AllRows[1][1] = "X";
            Steps++;
            continue;
        } else{
            AllRows[0][2] = 0;
            AllRows[1][1] = 0;
            AllRows[2][0] = 0;
            AllRows[GetSV1][GetSV2] = 0;
        }
        if(Steps >= 3 && AllRows[0][3] == 1){
            AllRows[1][2] = "X";
            Steps++;
            continue;
        } else if(Steps >= 3 && AllRows[1][2] == 1){
            AllRows[0][3] = "X";
            AllRows[2][1] = "X";
            Steps++;
            continue;
        } else if(Steps >= 3 && AllRows[2][1] == 1){
            AllRows[3][0] = "X";
            AllRows[1][2] = "X";
            Steps++;
            continue;
        } else if(Steps >= 3 && AllRows[3][0] == 1){
            AllRows[2][1] = "X";
            Steps++;
            continue;
        }  else{
            AllRows[0][3] = 0;
            AllRows[1][2] = 0;
            AllRows[2][1] = 0;
            AllRows[3][0] = 0;
            AllRows[GetSV1][GetSV2] = 0;
        }
        if(Steps >= 4 && AllRows[0][4] == 1){
            AllRows[1][3] = "X";
            Steps++;
            continue;
        } else if(Steps >= 4 && AllRows[1][3] == 1){
            AllRows[0][4] = "X";
            AllRows[2][2] = "X";
            Steps++;
            continue;
        } else if(Steps >= 4 && AllRows[2][2] == 1){
            AllRows[3][1] = "X";
            AllRows[1][3] = "X";
            Steps++;
            continue;
        } else if(Steps >= 4 && AllRows[3][1] == 1){
            AllRows[2][2] = "X";
            AllRows[4][0] = "X";
            Steps++;
            continue;
        } else if(Steps >= 4 && AllRows[4][0] == 1){
            AllRows[3][1] = "X";
            PD = null;
        } else{
            AllRows[0][4] = 0;
            AllRows[1][3] = 0;
            AllRows[2][2] = 0;
            AllRows[3][1] = 0;
            AllRows[4][0] = 0;
            AllRows[GetSV1][GetSV2] = 0;
        }
        if(Steps >= 5 && AllRows[1][4] == 1){
            AllRows[2][3] = "X";
            Steps++;
            continue;
        } else if(Steps >= 5 && AllRows[2][3] == 1){
            AllRows[1][4] = "X";
            AllRows[3][2] = "X";
            Steps++;
            continue;
        } else if(Steps >= 5 && AllRows[3][2] == 1){
            AllRows[4][1] = "X";
            AllRows[2][3] = "X";
            Steps++;
            continue;
        } else if(Steps >= 5 && AllRows[4][1] == 1){
            AllRows[3][2] = "X";
            PD = null;
        } else{
            AllRows[1][4] = 0;
            AllRows[2][3] = 0;
            AllRows[3][2] = 0;
            AllRows[4][1] = 0;
            AllRows[GetSV1][GetSV2] = 0;
        }
        if(Steps >= 6 && AllRows[2][4] == 1){
            AllRows[3][3] = "X";
            Steps++;
            continue;
        } else if(Steps >= 6 && AllRows[3][3] == 1){
            AllRows[2][4] = "X";
            AllRows[4][2] = "X";
            Steps++;
            continue;
        } else if(Steps >= 6 && AllRows[4][2] == 1){
            AllRows[3][3] = "X";
            PD = null;
        } else{
            AllRows[2][4] = 0;
            AllRows[3][3] = 0;
            AllRows[4][2] = 0;
            AllRows[GetSV1][GetSV2] = 0;
        }
        if(Steps >= 7 && AllRows[3][4] == 1){
            AllRows[4][3] = "X";
            Steps++;
            continue;
        } else if(Steps >= 7 && AllRows[4][3] == 1){
            AllRows[3][4] = "X";
            PD = null;
        } else if(Steps >= 7 && AllRows[4][4] == 1){
            PD = null;
        } else{
            AllRows[3][4] = 0;
            AllRows[4][3] = 0;
            AllRows[4][4] = 0;
            AllRows[GetSV1][GetSV2] = 0;
        }
    }else{
        break;
    }
}
</code>```

}

Since I can't console out the problem, I can't find out what is causing this to infinitely loop but what I do know is it may have something to do with the declaration of RV1 and RV2. Can anyone tell me where in the code makes it loop forever?

Update I added my full code to help us further understand the problem.

答:
A few points.  One, "false" does not equate with false nor with true because the string is a string value and true/false are boolean values. Although, you may write code like this:

console.log(new Boolean("false") == true); // true
console.log("false" == String(true));      // false```
</div>
</div>
</p>

<p>See more info here</p>

<p>Don't have a mixed array with strings and numbers.  So, instead of "X", I use 99 but you can use whatever numeric value you deem fit.  You need to specify a condition to have the loop stop. Now the loop is no longer endless.  Also, see here</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var Row1 = [0, 0, 0, 0, 0];
var Row2 = [0, 0, 0, 0, 0];
var Row3 = [0, 0, 0, 0, 0];
var Row4 = [0, 0, 0, 0, 0];
var Row5 = [0, 0, 0, 0, 0];
var AllRows = [];

//Add Rows
AllRows.push(Row1, Row2, Row3, Row4, Row5);
console.log(AllRows);

//First Value
var SV1 = [0, (AllRows.length - 1)];
var SV2 = [0, (AllRows.length - 1)];

var GetSV1 = Math.floor(Math.random()*(SV1.length - 1));
var GetSV2 = Math.floor(Math.random()*(SV2.length - 1));
AllRows[GetSV1][GetSV2] = 1;

var Steps = 1;
var PD = true; // "false" to true
var RV1 = null;
var RV2 = null;

while(PD === true){
    RV1 = Math.floor(Math.random()*(AllRows.length - 1));
    RV2 = Math.floor(Math.random()*(AllRows.length - 1));
    if(AllRows[RV1][RV2] == AllRows[GetSV1][GetSV2] || AllRows[RV1][RV2] == 99){
        continue;
    } else {
        AllRows[RV1][RV2] = 1;
    }

    if(AllRows[0][0] == 0){
        if(Steps >= 1 && AllRows[0][1] == 1){
            AllRows[1][0] = 99;
            Steps++;
            continue;
        } else if(Steps >= 1 && AllRows[1][0] == 1){
            AllRows[0][1] = 99;
            Steps++;
            continue;
        } else{
            AllRows[0][1] = 0;
            AllRows[1][0] = 0;
            AllRows[GetSV1][GetSV2] = 0;
        }
        if(Steps >= 2 && AllRows[0][2] == 1){
            AllRows[1][1] = 99;
            Steps++;
            continue;
        } else if(Steps >= 2 && AllRows[1][1] == 1){
            AllRows[0][2] = 99;
            AllRows[2][0] = 99;
            Steps++;
            continue;
        } else if(Steps >= 2 && AllRows[2][0] == 1){
            AllRows[1][1] = 99;
            Steps++;
            continue;
        } else{
            AllRows[0][2] = 0;
            AllRows[1][1] = 0;
            AllRows[2][0] = 0;
            AllRows[GetSV1][GetSV2] = 0;
        }
        if(Steps >= 3 && AllRows[0][3] == 1){
            AllRows[1][2] = 99;
            Steps++;
            continue;
        } else if(Steps >= 3 && AllRows[1][2] == 1){
            AllRows[0][3] = 99;
            AllRows[2][1] = 99;
            Steps++;
            continue;
        } else if(Steps >= 3 && AllRows[2][1] == 1){
            AllRows[3][0] = 99;
            AllRows[1][2] = 99;
            Steps++;
            continue;
        } else if(Steps >= 3 && AllRows[3][0] == 1){
            AllRows[2][1] = 99;
            Steps++;
            continue;
        }  else{
            AllRows[0][3] = 0;
            AllRows[1][2] = 0;
            AllRows[2][1] = 0;
            AllRows[3][0] = 0;
            AllRows[GetSV1][GetSV2] = 0;
        }
        if(Steps >= 4 && AllRows[0][4] == 1){
            AllRows[1][3] = 99;
            Steps++;
            continue;
        } else if(Steps >= 4 && AllRows[1][3] == 1){
            AllRows[0][4] = "X";
            AllRows[2][2] = "X";
            Steps++;
            continue;
        } else if(Steps >= 4 && AllRows[2][2] == 1){
            AllRows[3][1] = "X";
            AllRows[1][3] = 99;
            Steps++;
            continue;
        } else if(Steps >= 4 && AllRows[3][1] == 1){
            AllRows[2][2] = 99;
            AllRows[4][0] = "X";
            Steps++;
            continue;
        }
      else
        if(Steps >= 4 && AllRows[4][0] == 1){
            AllRows[3][1] = 99;
            PD = false;
        } else{
            AllRows[0][4] = 0;
            AllRows[1][3] = 0;
            AllRows[2][2] = 0;
            AllRows[3][1] = 0;
            AllRows[4][0] = 0;
            AllRows[GetSV1][GetSV2] = 0;
        }
        if(Steps >= 5 && AllRows[1][4] == 1){
            AllRows[2][3] = 99;
            Steps++;
            continue;
        } else if(Steps >= 5 && AllRows[2][3] == 1){
            AllRows[1][4] = 99;
            AllRows[3][2] = 99;
            Steps++;
            continue;
        } else if(Steps >= 5 && AllRows[3][2] == 1){
            AllRows[4][1] = 99;
            AllRows[2][3] = 99;
            Steps++;
            continue;
        } else
          if(Steps >= 5 && AllRows[4][1] == 1){
            AllRows[3][2] = 99;
            PD = false; //null to false
        } else{
            AllRows[1][4] = 0;
            AllRows[2][3] = 0;
            AllRows[3][2] = 0;
            AllRows[4][1] = 0;
            AllRows[GetSV1][GetSV2] = 0;
        }
        if(Steps >= 6 && AllRows[2][4] == 1){
            AllRows[3][3] = 99;
            Steps++;
            continue;
        } else if(Steps >= 6 && AllRows[3][3] == 1){
            AllRows[2][4] = 99;
            AllRows[4][2] = 99;
            Steps++;
            continue;
        } else if(Steps >= 6 && AllRows[4][2] == 1){
            AllRows[3][3] = 99;
            PD = false;
        } else{
            AllRows[2][4] = 0;
            AllRows[3][3] = 0;
            AllRows[4][2] = 0;
            AllRows[GetSV1][GetSV2] = 0;
        }
        if(Steps >= 7 && AllRows[3][4] == 1){
            AllRows[4][3] = 99;
            Steps++;
            continue;
        } else if(Steps >= 7 && AllRows[4][3] == 1){
            AllRows[3][4] = 99;
            PD = false;
        } else if(Steps >= 7 && AllRows[4][4] == 1){
            PD = false;
        } else{
            AllRows[3][4] = 0;
            AllRows[4][3] = 0;
            AllRows[4][4] = 0;
            AllRows[GetSV1][GetSV2] = 0;
        }
    }
     else{
        break;
    }

}</code>```

Note it is best to strictly compare Booleans with Booleans per MDN. That is why this example uses the "===" operator for comparison and sets PD explicitly to true or false.

Body:
I have a while loop that is an algorithm for a certain array path and I made it in javaScript. Here is the code.

var Row1 = [0, 0, 0, 0, 0];
var Row2 = [0, 0, 0, 0, 0];
var Row3 = [0, 0, 0, 0, 0];
var Row4 = [0, 0, 0, 0, 0];
var Row5 = [0, 0, 0, 0, 0];
var AllRows = [];

//Add Rows
AllRows.push(Row1, Row2, Row3, Row4, Row5);
console.log(AllRows);

//First Value
var SV1 = [0, (AllRows.length - 1)];
var SV2 = [0, (AllRows.length - 1)];

var GetSV1 = Math.floor(Math.random()*(SV1.length - 1));
var GetSV2 = Math.floor(Math.random()*(SV2.length - 1));
AllRows[GetSV1][GetSV2] = 1;

var Steps = 1;
var PD = "false";
var RV1 = null;
var RV2 = null;
while(PD == "false"){
    RV1 = Math.floor(Math.random()*(AllRows.length - 1));
    RV2 = Math.floor(Math.random()*(AllRows.length - 1));
    if(AllRows[RV1][RV2] == AllRows[GetSV1][GetSV2] || AllRows[RV1][RV2] == "X"){
        continue;
    } else {
        AllRows[RV1][RV2] = 1;
    }

    if(AllRows[0][0] == 1){
        if(Steps >= 1 && AllRows[0][1] == 1){
            AllRows[1][0] = "X";
            Steps++;
            continue;
        } else if(Steps >= 1 && AllRows[1][0] == 1){
            AllRows[0][1] = "X";
            Steps++;
            continue;
        } else{
            AllRows[0][1] = 0;
            AllRows[1][0] = 0;
            AllRows[GetSV1][GetSV2] = 0;
        }
        if(Steps >= 2 && AllRows[0][2] == 1){
            AllRows[1][1] = "X";
            Steps++;
            continue;
        } else if(Steps >= 2 && AllRows[1][1] == 1){
            AllRows[0][2] = "X";
            AllRows[2][0] = "X";
            Steps++;
            continue;
        } else if(Steps >= 2 && AllRows[2][0] == 1){
            AllRows[1][1] = "X";
            Steps++;
            continue;
        } else{
            AllRows[0][2] = 0;
            AllRows[1][1] = 0;
            AllRows[2][0] = 0;
            AllRows[GetSV1][GetSV2] = 0;
        }
        if(Steps >= 3 && AllRows[0][3] == 1){
            AllRows[1][2] = "X";
            Steps++;
            continue;
        } else if(Steps >= 3 && AllRows[1][2] == 1){
            AllRows[0][3] = "X";
            AllRows[2][1] = "X";
            Steps++;
            continue;
        } else if(Steps >= 3 && AllRows[2][1] == 1){
            AllRows[3][0] = "X";
            AllRows[1][2] = "X";
            Steps++;
            continue;
        } else if(Steps >= 3 && AllRows[3][0] == 1){
            AllRows[2][1] = "X";
            Steps++;
            continue;
        }  else{
            AllRows[0][3] = 0;
            AllRows[1][2] = 0;
            AllRows[2][1] = 0;
            AllRows[3][0] = 0;
            AllRows[GetSV1][GetSV2] = 0;
        }
        if(Steps >= 4 && AllRows[0][4] == 1){
            AllRows[1][3] = "X";
            Steps++;
            continue;
        } else if(Steps >= 4 && AllRows[1][3] == 1){
            AllRows[0][4] = "X";
            AllRows[2][2] = "X";
            Steps++;
            continue;
        } else if(Steps >= 4 && AllRows[2][2] == 1){
            AllRows[3][1] = "X";
            AllRows[1][3] = "X";
            Steps++;
            continue;
        } else if(Steps >= 4 && AllRows[3][1] == 1){
            AllRows[2][2] = "X";
            AllRows[4][0] = "X";
            Steps++;
            continue;
        } else if(Steps >= 4 && AllRows[4][0] == 1){
            AllRows[3][1] = "X";
            PD = null;
        } else{
            AllRows[0][4] = 0;
            AllRows[1][3] = 0;
            AllRows[2][2] = 0;
            AllRows[3][1] = 0;
            AllRows[4][0] = 0;
            AllRows[GetSV1][GetSV2] = 0;
        }
        if(Steps >= 5 && AllRows[1][4] == 1){
            AllRows[2][3] = "X";
            Steps++;
            continue;
        } else if(Steps >= 5 && AllRows[2][3] == 1){
            AllRows[1][4] = "X";
            AllRows[3][2] = "X";
            Steps++;
            continue;
        } else if(Steps >= 5 && AllRows[3][2] == 1){
            AllRows[4][1] = "X";
            AllRows[2][3] = "X";
            Steps++;
            continue;
        } else if(Steps >= 5 && AllRows[4][1] == 1){
            AllRows[3][2] = "X";
            PD = null;
        } else{
            AllRows[1][4] = 0;
            AllRows[2][3] = 0;
            AllRows[3][2] = 0;
            AllRows[4][1] = 0;
            AllRows[GetSV1][GetSV2] = 0;
        }
        if(Steps >= 6 && AllRows[2][4] == 1){
            AllRows[3][3] = "X";
            Steps++;
            continue;
        } else if(Steps >= 6 && AllRows[3][3] == 1){
            AllRows[2][4] = "X";
            AllRows[4][2] = "X";
            Steps++;
            continue;
        } else if(Steps >= 6 && AllRows[4][2] == 1){
            AllRows[3][3] = "X";
            PD = null;
        } else{
            AllRows[2][4] = 0;
            AllRows[3][3] = 0;
            AllRows[4][2] = 0;
            AllRows[GetSV1][GetSV2] = 0;
        }
        if(Steps >= 7 && AllRows[3][4] == 1){
            AllRows[4][3] = "X";
            Steps++;
            continue;
        } else if(Steps >= 7 && AllRows[4][3] == 1){
            AllRows[3][4] = "X";
            PD = null;
        } else if(Steps >= 7 && AllRows[4][4] == 1){
            PD = null;
        } else{
            AllRows[3][4] = 0;
            AllRows[4][3] = 0;
            AllRows[4][4] = 0;
            AllRows[GetSV1][GetSV2] = 0;
        }
    }else{
        break;
    }
}

}

Since I can't console out the problem, I can't find out what is causing this to infinitely loop but what I do know is it may have something to do with the declaration of RV1 and RV2. Can anyone tell me where in the code makes it loop forever?

Update I added my full code to help us further understand the problem.

Body:
A few points.  One, "false" does not equate with false nor with true because the string is a string value and true/false are boolean values. Although, you may write code like this:

console.log(new Boolean("false") == true); // true
console.log("false" == String(true));      // false

See more info here

Don't have a mixed array with strings and numbers.  So, instead of "X", I use 99 but you can use whatever numeric value you deem fit.  You need to specify a condition to have the loop stop. Now the loop is no longer endless.  Also, see here

var Row1 = [0, 0, 0, 0, 0];
var Row2 = [0, 0, 0, 0, 0];
var Row3 = [0, 0, 0, 0, 0];
var Row4 = [0, 0, 0, 0, 0];
var Row5 = [0, 0, 0, 0, 0];
var AllRows = [];

//Add Rows
AllRows.push(Row1, Row2, Row3, Row4, Row5);
console.log(AllRows);

//First Value
var SV1 = [0, (AllRows.length - 1)];
var SV2 = [0, (AllRows.length - 1)];

var GetSV1 = Math.floor(Math.random()*(SV1.length - 1));
var GetSV2 = Math.floor(Math.random()*(SV2.length - 1));
AllRows[GetSV1][GetSV2] = 1;

var Steps = 1;
var PD = true; // "false" to true
var RV1 = null;
var RV2 = null;

while(PD === true){
    RV1 = Math.floor(Math.random()*(AllRows.length - 1));
    RV2 = Math.floor(Math.random()*(AllRows.length - 1));
    if(AllRows[RV1][RV2] == AllRows[GetSV1][GetSV2] || AllRows[RV1][RV2] == 99){
        continue;
    } else {
        AllRows[RV1][RV2] = 1;
    }

    if(AllRows[0][0] == 0){
        if(Steps >= 1 && AllRows[0][1] == 1){
            AllRows[1][0] = 99;
            Steps++;
            continue;
        } else if(Steps >= 1 && AllRows[1][0] == 1){
            AllRows[0][1] = 99;
            Steps++;
            continue;
        } else{
            AllRows[0][1] = 0;
            AllRows[1][0] = 0;
            AllRows[GetSV1][GetSV2] = 0;
        }
        if(Steps >= 2 && AllRows[0][2] == 1){
            AllRows[1][1] = 99;
            Steps++;
            continue;
        } else if(Steps >= 2 && AllRows[1][1] == 1){
            AllRows[0][2] = 99;
            AllRows[2][0] = 99;
            Steps++;
            continue;
        } else if(Steps >= 2 && AllRows[2][0] == 1){
            AllRows[1][1] = 99;
            Steps++;
            continue;
        } else{
            AllRows[0][2] = 0;
            AllRows[1][1] = 0;
            AllRows[2][0] = 0;
            AllRows[GetSV1][GetSV2] = 0;
        }
        if(Steps >= 3 && AllRows[0][3] == 1){
            AllRows[1][2] = 99;
            Steps++;
            continue;
        } else if(Steps >= 3 && AllRows[1][2] == 1){
            AllRows[0][3] = 99;
            AllRows[2][1] = 99;
            Steps++;
            continue;
        } else if(Steps >= 3 && AllRows[2][1] == 1){
            AllRows[3][0] = 99;
            AllRows[1][2] = 99;
            Steps++;
            continue;
        } else if(Steps >= 3 && AllRows[3][0] == 1){
            AllRows[2][1] = 99;
            Steps++;
            continue;
        }  else{
            AllRows[0][3] = 0;
            AllRows[1][2] = 0;
            AllRows[2][1] = 0;
            AllRows[3][0] = 0;
            AllRows[GetSV1][GetSV2] = 0;
        }
        if(Steps >= 4 && AllRows[0][4] == 1){
            AllRows[1][3] = 99;
            Steps++;
            continue;
        } else if(Steps >= 4 && AllRows[1][3] == 1){
            AllRows[0][4] = "X";
            AllRows[2][2] = "X";
            Steps++;
            continue;
        } else if(Steps >= 4 && AllRows[2][2] == 1){
            AllRows[3][1] = "X";
            AllRows[1][3] = 99;
            Steps++;
            continue;
        } else if(Steps >= 4 && AllRows[3][1] == 1){
            AllRows[2][2] = 99;
            AllRows[4][0] = "X";
            Steps++;
            continue;
        }
      else
        if(Steps >= 4 && AllRows[4][0] == 1){
            AllRows[3][1] = 99;
            PD = false;
        } else{
            AllRows[0][4] = 0;
            AllRows[1][3] = 0;
            AllRows[2][2] = 0;
            AllRows[3][1] = 0;
            AllRows[4][0] = 0;
            AllRows[GetSV1][GetSV2] = 0;
        }
        if(Steps >= 5 && AllRows[1][4] == 1){
            AllRows[2][3] = 99;
            Steps++;
            continue;
        } else if(Steps >= 5 && AllRows[2][3] == 1){
            AllRows[1][4] = 99;
            AllRows[3][2] = 99;
            Steps++;
            continue;
        } else if(Steps >= 5 && AllRows[3][2] == 1){
            AllRows[4][1] = 99;
            AllRows[2][3] = 99;
            Steps++;
            continue;
        } else
          if(Steps >= 5 && AllRows[4][1] == 1){
            AllRows[3][2] = 99;
            PD = false; //null to false
        } else{
            AllRows[1][4] = 0;
            AllRows[2][3] = 0;
            AllRows[3][2] = 0;
            AllRows[4][1] = 0;
            AllRows[GetSV1][GetSV2] = 0;
        }
        if(Steps >= 6 && AllRows[2][4] == 1){
            AllRows[3][3] = 99;
            Steps++;
            continue;
        } else if(Steps >= 6 && AllRows[3][3] == 1){
            AllRows[2][4] = 99;
            AllRows[4][2] = 99;
            Steps++;
            continue;
        } else if(Steps >= 6 && AllRows[4][2] == 1){
            AllRows[3][3] = 99;
            PD = false;
        } else{
            AllRows[2][4] = 0;
            AllRows[3][3] = 0;
            AllRows[4][2] = 0;
            AllRows[GetSV1][GetSV2] = 0;
        }
        if(Steps >= 7 && AllRows[3][4] == 1){
            AllRows[4][3] = 99;
            Steps++;
            continue;
        } else if(Steps >= 7 && AllRows[4][3] == 1){
            AllRows[3][4] = 99;
            PD = false;
        } else if(Steps >= 7 && AllRows[4][4] == 1){
            PD = false;
        } else{
            AllRows[3][4] = 0;
            AllRows[4][3] = 0;
            AllRows[4][4] = 0;
            AllRows[GetSV1][GetSV2] = 0;
        }
    }
     else{
        break;
    }

}

Note it is best to strictly compare Booleans with Booleans per MDN. That is why this example uses the "===" operator for comparison and sets PD explicitly to true or false.


问:
Domain not resolving to elastic IP amazon linux
I pointed my domain name that I registered through route 53 here: Response returned by Route 53

```<code>DNS request sent to Route 53
arcadeidea.com.     IN     A
EDNS0 client subnet IP
24
DNS response code
NOERROR
Protocol
UDP
Response returned by Route 53
34.214.33.108
</code>```

And when I try going to the elastic IP (34.214.33.108) I get the hello world html page served by a sample

```<code>arcadeidea.com’s server DNS address could not be found.
DNS_PROBE_FINISHED_NXDOMAIN
</code>```

I think it may be a problem with port forwarding, as I'm forwarding 80 to 8080 which is what the sample node app was setup as a default. Not sure how to debug that though...Any thoughts?

答:
This DNS server is not answering for this domain. Check that you have inserted the correct AWS DNS hosts on your domain registrar.</p>

```<code>% nslookup
> server NS-1316.AWSDNS-36.ORG
Default server: NS-1316.AWSDNS-36.ORG
Address: 205.251.197.36#53
> arcadeidea.com
Server:     NS-1316.AWSDNS-36.ORG
Address:    205.251.197.36#53

** server can't find arcadeidea.com: REFUSED
</code>```

Body:
I pointed my domain name that I registered through route 53 here: Response returned by Route 53

DNS request sent to Route 53
arcadeidea.com.     IN     A
EDNS0 client subnet IP
24
DNS response code
NOERROR
Protocol
UDP
Response returned by Route 53
34.214.33.108

And when I try going to the elastic IP (34.214.33.108) I get the hello world html page served by a sample

arcadeidea.com’s server DNS address could not be found.
DNS_PROBE_FINISHED_NXDOMAIN

I think it may be a problem with port forwarding, as I'm forwarding 80 to 8080 which is what the sample node app was setup as a default. Not sure how to debug that though...Any thoughts?

Body:
This DNS server is not answering for this domain. Check that you have inserted the correct AWS DNS hosts on your domain registrar.

% nslookup
> server NS-1316.AWSDNS-36.ORG
Default server: NS-1316.AWSDNS-36.ORG
Address: 205.251.197.36#53
> arcadeidea.com
Server:     NS-1316.AWSDNS-36.ORG
Address:    205.251.197.36#53

** server can't find arcadeidea.com: REFUSED


问:
Evaluating a function call constructed from a string
Say I have two functions whose names are contained within a vector. I would like to test if each function works.

My approach, which I readily admit could be wrong, was to loop through the vector then paste () to the function name. But then I realized I have no idea how to evaluate the function call which is current stored as a string. Here is a reprex:

```<code>func1 <- function(){
  message("func1 works")
}

func2 <- function(){
  message("func2 works")
}

fv <- c("func1","func2")

for(i in seq_along(fv)){
  fv_func <- paste0(fv[i],"()")
  print(fv_func)
}
[1] "func1()"
[1] "func2()"
</code>```

So in this context I am asking how to evaluate func1() and func2() though the ultimate goal is to evaluate function whose names are stored in a vector - meaning i'm open to better solution.

答:
We can do it in one line without a for loop if we use vectorised eval(parse):

```<code>eval(parse(text = paste0(fv,'()')))
</code>```

Body:
Say I have two functions whose names are contained within a vector. I would like to test if each function works.

My approach, which I readily admit could be wrong, was to loop through the vector then paste () to the function name. But then I realized I have no idea how to evaluate the function call which is current stored as a string. Here is a reprex:

func1 <- function(){
  message("func1 works")
}

func2 <- function(){
  message("func2 works")
}

fv <- c("func1","func2")

for(i in seq_along(fv)){
  fv_func <- paste0(fv[i],"()")
  print(fv_func)
}
[1] "func1()"
[1] "func2()"

So in this context I am asking how to evaluate func1() and func2() though the ultimate goal is to evaluate function whose names are stored in a vector - meaning i'm open to better solution.

Body:
We can do it in one line without a for loop if we use vectorised eval(parse):

eval(parse(text = paste0(fv,'()')))


问:
Implementing Click on anywhere on Layout
I want to implement Click on anywhere on Layout but for some reason app get stopped and I don't understand why. here is relevant part of my code

```<code>public class MainActivity extends AppCompatActivity {
....
    private TextView Issue;
 ....
 private Handler handler = new Handler();
 private Runnable runnable = new Runnable() {
        @Override
        public void run() {
....

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

 ////here is where I code to touch screen
 RelativeLayout rlayout = (RelativeLayout) findViewById(R.id.mainlayout);
        rlayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View arg0, MotionEvent arg1) {

               mp.stop();
                return true;
            }
        });
</code>```

I also tried OnClickListener instead of setOnTouchListener and it didn't solve. Thanks

答:
Put your relativelayout clickable

```<code> <RelativeLayout
        android:id="@+id/mainlayout"
        android:layout_width="match_parent"
        android:clickable="true"
        android:layout_height="wrap_content"/>
</code>```

Then use onclicklistener

```<code>rlayout.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
         mp.stop();
      }
    });
</code>```

Body:
I want to implement Click on anywhere on Layout but for some reason app get stopped and I don't understand why. here is relevant part of my code

public class MainActivity extends AppCompatActivity {
....
    private TextView Issue;
 ....
 private Handler handler = new Handler();
 private Runnable runnable = new Runnable() {
        @Override
        public void run() {
....

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

 ////here is where I code to touch screen
 RelativeLayout rlayout = (RelativeLayout) findViewById(R.id.mainlayout);
        rlayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View arg0, MotionEvent arg1) {

               mp.stop();
                return true;
            }
        });

I also tried OnClickListener instead of setOnTouchListener and it didn't solve. Thanks

Body:
Put your relativelayout clickable

 <RelativeLayout
        android:id="@+id/mainlayout"
        android:layout_width="match_parent"
        android:clickable="true"
        android:layout_height="wrap_content"/>

Then use onclicklistener

rlayout.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
         mp.stop();
      }
    });


问:
If else statement not being executed correctly
I am facing a very strange problem. I have written the below code.

```<code>    if (verifiedStatus.equals("1")) {
    imageView.setImageResource(R.drawable.ic_verified_user_black_24dp);
    }
    else if (verifiedStatus.equals("0")) {
    imageView.setImageResource(R.drawable.ic_not_interested_black_24dp);
    } else {}
</code>```

As the code runs, if the value is 1, first the verified image comes but later it changes to the not interested image. I tried debugging and I saw that the code goes into an internal file/code and in the below lines, it changes the image to the other image.

```<code>for (;;) {
    Message msg = queue.next(); // might block
    if (msg == null) {
        // No message indicates that the message queue is quitting.
        return;
    }
</code>```

Can someone help me in resolving this issue?

答:
First of all, you don't need two nested if else if else. Do it like this if else if or if else statements.

```<code>if (verifiedStatus.equals("1")) {
  imageView.setImageResource(R.drawable.ic_verified_user_black_24dp);
}
else if (verifiedStatus.equals("0")) {
 imageView.setImageResource(R.drawable.ic_not_interested_black_24dp);
}
</code>```

or

```<code>if (verifiedStatus.equals("1")) {
  imageView.setImageResource(R.drawable.ic_verified_user_black_24dp);
}
else {
 imageView.setImageResource(R.drawable.ic_not_interested_black_24dp);
}
</code>```

or  use switch statments, case 1: ..do something..break, case 2: ..do something.. break
Also, you need to return something with the return statement.

One main thing about your question, it doesn't give all the information so please edit your question if my answer won't be helpful to get help from others in the community.

Body:
I am facing a very strange problem. I have written the below code.

    if (verifiedStatus.equals("1")) {
    imageView.setImageResource(R.drawable.ic_verified_user_black_24dp);
    }
    else if (verifiedStatus.equals("0")) {
    imageView.setImageResource(R.drawable.ic_not_interested_black_24dp);
    } else {}

As the code runs, if the value is 1, first the verified image comes but later it changes to the not interested image. I tried debugging and I saw that the code goes into an internal file/code and in the below lines, it changes the image to the other image.

for (;;) {
    Message msg = queue.next(); // might block
    if (msg == null) {
        // No message indicates that the message queue is quitting.
        return;
    }

Can someone help me in resolving this issue?

Body:
First of all, you don't need two nested if else if else. Do it like this if else if or if else statements.

if (verifiedStatus.equals("1")) {
  imageView.setImageResource(R.drawable.ic_verified_user_black_24dp);
}
else if (verifiedStatus.equals("0")) {
 imageView.setImageResource(R.drawable.ic_not_interested_black_24dp);
}

or

if (verifiedStatus.equals("1")) {
  imageView.setImageResource(R.drawable.ic_verified_user_black_24dp);
}
else {
 imageView.setImageResource(R.drawable.ic_not_interested_black_24dp);
}

or  use switch statments, case 1: ..do something..break, case 2: ..do something.. break
Also, you need to return something with the return statement.

One main thing about your question, it doesn't give all the information so please edit your question if my answer won't be helpful to get help from others in the community.


问:
How to handle auto completion on multi word text?
My input text is a multiword english text and I have the requirement to implement a autocompletion feature for that text.

I initially looked at search completion suggesters only to figure out that those can only match the first characters of the input. This is fine for auto completion of product names or address but not very useful when requiring a auto completion on any word in the input text.

After that I setup an edge_ngram analyzer and query to locate those documents which contain the input string. That works just fine but I don't know how to use this information to provide options for my auto completion.

I could use a highlighter in order to show the words which match the query. That data could in turn be used to setup a list of options. This solution seems rather hacky and not very elegant and I wonder how this problem is usually solved?

I'm unfortunately not able to maintain another field which could include the auto completion options for the documents.

答:
I think your best option is to create a dedicated index for storing just the suggestions using the edge_ngram analyzer. If you use the completion suggesters you need to explicitly define your actual suggestions anyway. The completion suggester is also document centric in ES 5.x so if you index multiple documents with the same suggestions you will get duplicate suggestions returned on a match. There is a de-duplication option in ES 6, but that has only just been released.

If you have a dedicated suggestion index you can use a hash of the suggestion as a document ID to avoid duplicates. You can start indexing document titles and other useful meta data as suggestions. Later on you could include historical searches entered by users that are seen as successful due to the user ultimately clicking on or purchasing the returned results.


问:
Converting rdd to dataframe: AttributeError: 'RDD' object has no attribute 'toDF'
```<code>from pyspark import SparkContext, SparkConf
from pyspark.sql import SQLContext

conf = SparkConf().setAppName("myApp").setMaster("local")
sc = SparkContext(conf=conf)

a = sc.parallelize([[1, "a"], [2, "b"], [3, "c"], [4, "d"], [5, "e"]]).toDF(['ind', "state"])

a.show()
</code>```

Results in:

```<code>Traceback (most recent call last):
  File "/Users/ktemlyakov/messing_around/SparkStuff/mock_maersk_data.py", line 7, in <module>
    a = sc.parallelize([[1, "a"], [2, "b"], [3, "c"], [4, "d"], [5, "e"]]).toDF(['ind', "state"])
AttributeError: 'RDD' object has no attribute 'toDF'
</code>```

What am I missing?

答:
sqlContext is missing; it needs to be created. The following code works:

```<code>from pyspark import SparkContext, SparkConf
from pyspark.sql import SQLContext
from pyspark import sql

conf = SparkConf().setAppName("myFirstApp").setMaster("local")
sc = SparkContext(conf=conf)
sqlContext = sql.SQLContext(sc)

a = sc.parallelize([[1, "a"], [2, "b"], [3, "c"], [4, "d"], [5, "e"]]).toDF(['ind', "state"])

a.show()
</code>```

Edit:

In Spark 2.0, the above can be achieved with:

```<code>from pyspark import SparkConf
from pyspark.sql import SparkSession

spark = SparkSession.builder.master("local").config(conf=SparkConf()).getOrCreate()

a = spark.createDataFrame([[1, "a"], [2, "b"], [3, "c"], [4, "d"], [5, "e"]], ['ind', "state"])
a.show()
</code>```

Body:
from pyspark import SparkContext, SparkConf
from pyspark.sql import SQLContext

conf = SparkConf().setAppName("myApp").setMaster("local")
sc = SparkContext(conf=conf)

a = sc.parallelize([[1, "a"], [2, "b"], [3, "c"], [4, "d"], [5, "e"]]).toDF(['ind', "state"])

a.show()

Results in:

Traceback (most recent call last):
  File "/Users/ktemlyakov/messing_around/SparkStuff/mock_maersk_data.py", line 7, in <module>
    a = sc.parallelize([[1, "a"], [2, "b"], [3, "c"], [4, "d"], [5, "e"]]).toDF(['ind', "state"])
AttributeError: 'RDD' object has no attribute 'toDF'

What am I missing?

Body:
sqlContext is missing; it needs to be created. The following code works:

from pyspark import SparkContext, SparkConf
from pyspark.sql import SQLContext
from pyspark import sql

conf = SparkConf().setAppName("myFirstApp").setMaster("local")
sc = SparkContext(conf=conf)
sqlContext = sql.SQLContext(sc)

a = sc.parallelize([[1, "a"], [2, "b"], [3, "c"], [4, "d"], [5, "e"]]).toDF(['ind', "state"])

a.show()

Edit:

In Spark 2.0, the above can be achieved with:

from pyspark import SparkConf
from pyspark.sql import SparkSession

spark = SparkSession.builder.master("local").config(conf=SparkConf()).getOrCreate()

a = spark.createDataFrame([[1, "a"], [2, "b"], [3, "c"], [4, "d"], [5, "e"]], ['ind', "state"])
a.show()


问:
SQL Select where condition : value 1 <> value 2
Need your help to know if possible to select values from a table with the below condition :

Table content : matching between 2 objects
(Id_obj_A; name_obj_A; country_obj_A; Id_obj_B; name_obj_B; country_obj_B)

```<code>Select *
from table
Where (only if country_obj_A <> country_obj_B)
</code>```

Many thanks for your help

答:
Yes. There are a few ways, one is to use NOT EXISTS like this:

```<code>select
       *
from tableA
where NOT EXISTS (
   select NULL
   from tableB
   where tableB.country_obj_B = tableA.country_obj_A
   )
</code>```

or, using NOT IN

```<code>select
       *
from tableA
where country_obj_A NOT IN (
   select country_obj_B
   from tableB
   )
</code>```

or, using a LEFT JOIN then exclude the joined rows:

```<code>select
       *
from tableA
left join tableB on tableA.country_obj_A = tableB.country_obj_B
where tableB.country_obj_B IS NULL
</code>```

Body:
Need your help to know if possible to select values from a table with the below condition :

Table content : matching between 2 objects
(Id_obj_A; name_obj_A; country_obj_A; Id_obj_B; name_obj_B; country_obj_B)

Select *
from table
Where (only if country_obj_A <> country_obj_B)

Many thanks for your help

Body:
Yes. There are a few ways, one is to use NOT EXISTS like this:

select
       *
from tableA
where NOT EXISTS (
   select NULL
   from tableB
   where tableB.country_obj_B = tableA.country_obj_A
   )

or, using NOT IN

select
       *
from tableA
where country_obj_A NOT IN (
   select country_obj_B
   from tableB
   )

or, using a LEFT JOIN then exclude the joined rows:

select
       *
from tableA
left join tableB on tableA.country_obj_A = tableB.country_obj_B
where tableB.country_obj_B IS NULL


问:
I got the json data false.
Here Is my PHP code to encode the JSON data from MySQL database. And this is my URL http://fwtest.ga/appoint.php; I tested on the online website JSONLint to validate my JSON data. It is valid, but I got the result [false] instead of the data in JSON format. Can anybody tell what am I doing wrong?</p>

```<code> <?php

    $host = "my_host";
    $user = "user";
    $password = "pass";
    $db = "db_name";

    $con = mysqli_connect($host, $user, $password, $db);

    $sql = "select time, date from table_name;";

    $result = mysqli_query($con, $sql)
     or die("Error: ".mysqli_error($con));

    $response = array();

    while ($row = mysqli_fetch_array($result))
    {
    array_push($response, array("time" >= $row[1], "date" >= $row[2]));

    }
    echo json_encode(array("server_response">= $response));
    echo (json_last_error()=== JSON_ERROR_UTF8);
    mysqli_close($con)

     ?>
</code>```

答:
Probably because you're returning a single boolean here:

```<code>json_encode(array("server_response">= $response));
                                    ↑
</code>```

That's not the array operator.

Title: I got the json data false.

Body:
Here Is my PHP code to encode the JSON data from MySQL database. And this is my URL http://fwtest.ga/appoint.php; I tested on the online website JSONLint to validate my JSON data. It is valid, but I got the result [false] instead of the data in JSON format. Can anybody tell what am I doing wrong?

 <?php

    $host = "my_host";
    $user = "user";
    $password = "pass";
    $db = "db_name";

    $con = mysqli_connect($host, $user, $password, $db);

    $sql = "select time, date from table_name;";

    $result = mysqli_query($con, $sql)
     or die("Error: ".mysqli_error($con));

    $response = array();

    while ($row = mysqli_fetch_array($result))
    {
    array_push($response, array("time" >= $row[1], "date" >= $row[2]));

    }
    echo json_encode(array("server_response">= $response));
    echo (json_last_error()=== JSON_ERROR_UTF8);
    mysqli_close($con)

     ?>

Body:
Probably because you're returning a single boolean here:

json_encode(array("server_response">= $response));
                                    ↑

That's not the array operator.


问:
tf.train.shuffle_batch doen't seem to produce random images
I'm loading TFRecords and I have 6 different classes and a total of about 8000 images.

Here is what my current arguments look like:

```<code>images, labels = tf.train.shuffle_batch([image, label], batch_size=10,
capacity=3000, num_threads=3, min_after_dequeue=2000)
</code>```

Here are the images I am producing:

```<code>10, 299, 299, 3)
[1 0 1 1 1 1 1 1 0 0]
(10, 299, 299, 3)
[2 2 0 2 0 2 1 0 0 2]
(10, 299, 299, 3)
[0 1 1 1 2 2 2 2 1 2]
(10, 299, 299, 3)
[0 0 2 0 2 2 0 1 1 0]
(10, 299, 299, 3)
[0 2 0 0 2 0 0 2 1 2]
</code>```

As you can see by the labels, I'm only getting images from the first three
classes.

Are there certain values or ratios to use with capacity and min_after_dequeue?
(I tried really upping both values but my PC seemed to slowed down considerably, I may need to restart and try again)

Thank you

答:
TensorFlow API webpage says

min_after_dequeue: Minimum number elements in the queue after a dequeue, used to ensure a level of mixing of elements.

capacity: The maximum number of elements in the queue.

So, you should increase min_after_dequeue (e.g. 8000) and make sure capacity is greater or equal to min_after_dequeue.

Body:
I'm loading TFRecords and I have 6 different classes and a total of about 8000 images.

Here is what my current arguments look like:

images, labels = tf.train.shuffle_batch([image, label], batch_size=10,
capacity=3000, num_threads=3, min_after_dequeue=2000)

Here are the images I am producing:

10, 299, 299, 3)
[1 0 1 1 1 1 1 1 0 0]
(10, 299, 299, 3)
[2 2 0 2 0 2 1 0 0 2]
(10, 299, 299, 3)
[0 1 1 1 2 2 2 2 1 2]
(10, 299, 299, 3)
[0 0 2 0 2 2 0 1 1 0]
(10, 299, 299, 3)
[0 2 0 0 2 0 0 2 1 2]

As you can see by the labels, I'm only getting images from the first three
classes.

Are there certain values or ratios to use with capacity and min_after_dequeue?
(I tried really upping both values but my PC seemed to slowed down considerably, I may need to restart and try again)

Thank you


问:
mysql query with double join
I have 3 tables, but I can only get to join another table count. See below.
The one below works like a charm, but I need to add another "count" from another table.

there is a 3rd table called "ci_nomatch" and contains a reference to ci_address_book.reference
which could have multiple entries (many on many) but I only need the count of that table.

so if ci_address_book would have an entries called "item1","item 2","item3"
and ci_nomatch would have "1,item1,user1","2,item1,user4"

I would like to have returned "2" for Item1 on the query.

Any ideas? I tried another join, but it tells me that the reference does not exist, while it does!

```<code>SELECT c.*, IFNULL(p.total, 0) AS matchcount
FROM ci_address_book c
LEFT JOIN (
    SELECT addressbook_id, COUNT(match_id) AS total
    FROM ci_matched_sanctions
    GROUP BY addressbook_id
) AS p
ON c.id=p.addressbook_id
ORDER BY matchcount DESC
LIMIT 0,15
</code>```

答:
You could subquery it directly in the select

```<code>SELECT c.*, IFNULL(p.total, 0) AS matchcount,
   (SELECT COUNT(*) FROM ci_nomatch n on n.reference = c.reference) AS othercount
FROM ci_address_book c
LEFT JOIN (
    SELECT addressbook_id, COUNT(match_id) AS total
    FROM ci_matched_sanctions
    GROUP BY addressbook_id
) AS p
ON c.id=p.addressbook_id
ORDER BY matchcount DESC
LIMIT 0,15
</code>```

@updated for comment. Including an extra column "(matchcount - othercount) AS deducted" would be best done by sub-querying.

```<code>SELECT *, matchcount - othercount AS deducted
FROM
(
    SELECT c.* , IFNULL( p.total, 0 ) AS matchcount, (
        SELECT COUNT( * ) FROM ci_falsepositives n
        WHERE n.addressbook_id = c.reference ) AS othercount
    FROM ci_address_book c
    LEFT JOIN (
        SELECT addressbook_id, COUNT( match_id ) AS total
        FROM ci_matched_sanctions GROUP BY addressbook_id ) AS p
        ON c.id = p.addressbook_id ORDER BY matchcount DESC LIMIT 0 , 15
) S
</code>```

ContentLicense: CC BY-SA 2.5

Title: mysql query with double join

Body:
I have 3 tables, but I can only get to join another table count. See below.
The one below works like a charm, but I need to add another "count" from another table.

there is a 3rd table called "ci_nomatch" and contains a reference to ci_address_book.reference
which could have multiple entries (many on many) but I only need the count of that table.

so if ci_address_book would have an entries called "item1","item 2","item3"
and ci_nomatch would have "1,item1,user1","2,item1,user4"

I would like to have returned "2" for Item1 on the query.

Any ideas? I tried another join, but it tells me that the reference does not exist, while it does!

SELECT c.*, IFNULL(p.total, 0) AS matchcount
FROM ci_address_book c
LEFT JOIN (
    SELECT addressbook_id, COUNT(match_id) AS total
    FROM ci_matched_sanctions
    GROUP BY addressbook_id
) AS p
ON c.id=p.addressbook_id
ORDER BY matchcount DESC
LIMIT 0,15

Body:
You could subquery it directly in the select

SELECT c.*, IFNULL(p.total, 0) AS matchcount,
   (SELECT COUNT(*) FROM ci_nomatch n on n.reference = c.reference) AS othercount
FROM ci_address_book c
LEFT JOIN (
    SELECT addressbook_id, COUNT(match_id) AS total
    FROM ci_matched_sanctions
    GROUP BY addressbook_id
) AS p
ON c.id=p.addressbook_id
ORDER BY matchcount DESC
LIMIT 0,15

@updated for comment. Including an extra column "(matchcount - othercount) AS deducted" would be best done by sub-querying.

SELECT *, matchcount - othercount AS deducted
FROM
(
    SELECT c.* , IFNULL( p.total, 0 ) AS matchcount, (
        SELECT COUNT( * ) FROM ci_falsepositives n
        WHERE n.addressbook_id = c.reference ) AS othercount
    FROM ci_address_book c
    LEFT JOIN (
        SELECT addressbook_id, COUNT( match_id ) AS total
        FROM ci_matched_sanctions GROUP BY addressbook_id ) AS p
        ON c.id = p.addressbook_id ORDER BY matchcount DESC LIMIT 0 , 15
) S


问:
Run a list of String through a list of filters
I have List<String> and List<Filter>.

```<code>public interface Filter{
     List<String> filter(List<String> strToFilter);
}
</code>```

How can I pass the List<String> through the list of filters and use the output of one filter as an input to the other filter? I can do this using for-loop. I wanted to know how to achieve this using java 8 stream and lambda

答:
The idea of the function api is using "functional interfaces" which represent operations, similar to methods. In this case, a Predicate<T> represents an operation which acts on T and returns a boolean, which is what the Stream#filter method requires. So instead of having something which filters your list for you, you can simply have a Predicate<T> which filters a Stream<T> (from your list):

```<code>//in our example, 'T' will be a String
List<Predicate<String>> filters = Arrays.asList(s -> s.startsWith("Hello"));
Stream<String> stream = Stream.of("Test", "Hello world");
//because we have a list of predicates, we need to apply the #filter for each one
for (Predicate<String> pred : filters) {
    stream = stream.filter(pred);
}
stream.forEach(System.out::println); //prints "Hello world"
</code>```

This can be chained similarly if you don't require storing a list of them:

```<code>Stream.of("Test", "Hello world")
    .filter(s -> s.startsWith("Hello"))
    .filter(s -> s.length() > 5)
    .forEach(System.out::println); //prints "Hello world"
</code>```

Achieving the application of the List<"Filter"> isn't too viable with lambdas themselves, the lambdas need variables to be (effectively) final if they exist outside the scope of the lambda.

Body:
I have List<String> and List<Filter>.

public interface Filter{
     List<String> filter(List<String> strToFilter);
}

How can I pass the List<String> through the list of filters and use the output of one filter as an input to the other filter? I can do this using for-loop. I wanted to know how to achieve this using java 8 stream and lambda

Body:
The idea of the function api is using "functional interfaces" which represent operations, similar to methods. In this case, a Predicate<T> represents an operation which acts on T and returns a boolean, which is what the Stream#filter method requires. So instead of having something which filters your list for you, you can simply have a Predicate<T> which filters a Stream<T> (from your list):

//in our example, 'T' will be a String
List<Predicate<String>> filters = Arrays.asList(s -> s.startsWith("Hello"));
Stream<String> stream = Stream.of("Test", "Hello world");
//because we have a list of predicates, we need to apply the #filter for each one
for (Predicate<String> pred : filters) {
    stream = stream.filter(pred);
}
stream.forEach(System.out::println); //prints "Hello world"

This can be chained similarly if you don't require storing a list of them:

Stream.of("Test", "Hello world")
    .filter(s -> s.startsWith("Hello"))
    .filter(s -> s.length() > 5)
    .forEach(System.out::println); //prints "Hello world"

Achieving the application of the List<"Filter"> isn't too viable with lambdas themselves, the lambdas need variables to be (effectively) final if they exist outside the scope of the lambda.


问:
UWP - How to specify the order of updates when use x:Bind?
I'm developing a UWP app and I'm facing a problem. The app uses the MVVM pattern with Template10. I have created a similar solution that recreates the problem that I'm facing. In that solution, a list of orders are displayed, the user chooses an order and then click the "Edit" button. Then a second page is displayed and pre-loaded with the previous selected order, in this second page the user can edit the order. The problem is in the second page, the data bound to comboboxes doesn't show. Maybe the problem is related to this question. In my case, the SelectedValue is set before the ItemsSource. After debugging, I have reached these lines of code in OrderEditionPage.g.cs:

```<code>private void Update_ViewModel(global::ComboApp.ViewModels.OrderEditionPageViewModel obj, int phase)
{
    this.bindingsTracking.UpdateChildListeners_ViewModel(obj);
    if (obj != null)
    {
        if ((phase & (NOT_PHASED | DATA_CHANGED | (1 << 0))) != 0)
        {
            this.Update_ViewModel_SelectedOrder(obj.SelectedOrder, phase);
        }
        if ((phase & (NOT_PHASED | (1 << 0))) != 0)
        {
            this.Update_ViewModel_BusinessAssociates(obj.BusinessAssociates, phase);
            this.Update_ViewModel_TransactionTypes(obj.TransactionTypes, phase);
            this.Update_ViewModel_OrderTypes(obj.OrderTypes, phase);
            this.Update_ViewModel_ShowSelectedOrder(obj.ShowSelectedOrder, phase);
        }
    }
}
</code>```

If I could achieve this line of code be executed at last, my problem would be solved: this.Update_ViewModel_SelectedOrder(obj.SelectedOrder, phase);

How could I achieve this? How does Visual Studio determine the order of this lines?

OrderEditionPage.xaml

```<code><Page
    x:Class="ComboApp.Views.OrderEditionPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:myconverters="using:ComboApp.Converters"
    xmlns:t10converters="using:Template10.Converters"
    mc:Ignorable="d">

    <Page.Resources>
        <t10converters:ChangeTypeConverter x:Key="TypeConverter" />
        <myconverters:DateTimeConverter x:Key="DateTimeConverter" />
    </Page.Resources>

    <ScrollViewer VerticalScrollBarVisibility="Auto">
        <StackPanel
            Padding="15, 5"
            Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
            <TextBox
                Header="Order #"
                Margin="5"
                Width="150"
                HorizontalAlignment="Left"
                Text="{x:Bind ViewModel.SelectedOrder.ExternalId, Mode=TwoWay}" />
            <ComboBox
                Header="Business Associate"
                Margin="5"
                MinWidth="300"
                SelectedValuePath="BusinessAssociateId"
                DisplayMemberPath="Name1"
                ItemsSource="{x:Bind ViewModel.BusinessAssociates}"
                SelectedValue="{x:Bind ViewModel.SelectedOrder.BusinessAssociateId, Mode=TwoWay, Converter={StaticResource TypeConverter}}" />
            <DatePicker
                Header="Delivery Date"
                Margin="5"
                MinWidth="0"
                Width="200"
                Date="{x:Bind ViewModel.SelectedOrder.DeliveryDate, Mode=TwoWay, Converter={StaticResource DateTimeConverter}}" />
            <ComboBox
                Header="Transaction"
                MinWidth="200"
                Margin="5"
                SelectedValuePath="Value"
                DisplayMemberPath="Display"
                ItemsSource="{x:Bind ViewModel.TransactionTypes}"
                SelectedValue="{x:Bind ViewModel.SelectedOrder.TransactionType, Mode=TwoWay}" />
            <TextBox
                Header="Priority"
                Margin="5"
                MaxWidth="150"
                HorizontalAlignment="Left"
                Text="{x:Bind ViewModel.SelectedOrder.Priority}" />
            <ComboBox
                Header="Type"
                Margin="5"
                MinWidth="200"
                SelectedValuePath="Value"
                DisplayMemberPath="Display"
                ItemsSource="{x:Bind ViewModel.OrderTypes}"
                SelectedValue="{x:Bind ViewModel.SelectedOrder.OrderType, Mode=TwoWay}" />
            <TextBox
                Header="Information"
                Margin="5"
                Height="100"
                AcceptsReturn="True"
                TextWrapping="Wrap"
                ScrollViewer.VerticalScrollBarVisibility="Auto"
                Text="{x:Bind ViewModel.SelectedOrder.Information, Mode=TwoWay}" />
            <Button
                Margin="5"
                Content="Show"
                Width="100"
                HorizontalAlignment="Right"
                Command="{x:Bind ViewModel.ShowSelectedOrder}" />
        </StackPanel>
    </ScrollViewer>
</Page>
</code>```

OrderEditionPage.xaml.cs

```<code>using ComboApp.ViewModels;
using Windows.UI.Xaml.Controls;

namespace ComboApp.Views
{
    public sealed partial class OrderEditionPage : Page
    {
        public OrderEditionPageViewModel ViewModel => DataContext as OrderEditionPageViewModel;

        public OrderEditionPage()
        {
            this.InitializeComponent();
        }
    }
}
</code>```

OrderEditionPageViewModel.cs

```<code>using ComboApp.Models;
using ComboApp.Services;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using Template10.Mvvm;
using Template10.Utils;
using Windows.UI.Xaml.Navigation;

namespace ComboApp.ViewModels
{
    public class OrderEditionPageViewModel
        : ViewModelBase
    {
        private IBusinessAssociateService businessAssociateService;

        private Order selectedOrder;
        public Order SelectedOrder
        {
            get { return selectedOrder; }
            set { Set(ref selectedOrder, value); }
        }

        public ObservableCollection<object> TransactionTypes { get; set; } = new ObservableCollection<object>();
        public ObservableCollection<object> OrderTypes { get; set; } = new ObservableCollection<object>();
        public ObservableCollection<BusinessAssociate> BusinessAssociates { get; set; } = new ObservableCollection<BusinessAssociate>();

        public OrderEditionPageViewModel(IBusinessAssociateService businessAssociateService)
        {
            this.businessAssociateService = businessAssociateService;

            TransactionTypes.Add(new { Value = "I", Display = "Incoming" });
            TransactionTypes.Add(new { Value = "O", Display = "Outgoing" });
            TransactionTypes.Add(new { Value = "T", Display = "Transfer" });

            OrderTypes.Add(new { Value = "M", Display = "Manual" });
            OrderTypes.Add(new { Value = "A", Display = "Automatic" });
            OrderTypes.Add(new { Value = "S", Display = "Semi-automatic" });
        }

        public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary<string, object> state)
        {
            // Loading buiness associates
            var response = await businessAssociateService.GetNextPageAsync();
            if (response.IsSuccessful)
            {
                BusinessAssociates.AddRange(response.Result.Items);
            }

            SelectedOrder = (Order)parameter;
            await base.OnNavigatedToAsync(parameter, mode, state);
        }

        private DelegateCommand showSelectedOrder;
        public DelegateCommand ShowSelectedOrder => showSelectedOrder ?? (showSelectedOrder = new DelegateCommand(async () =>
        {
            await Views.MessageBox.ShowAsync(JsonConvert.SerializeObject(SelectedOrder, Formatting.Indented));
        }));

    }
}
</code>```

答:
It is a known issue of x:Bind when the SelectedValue of a ComboBox is sometimes set before its ItemsSource, you can read more about it here.

As a workaround you can use Bindings instead of x:Bind, but make sure that ItemsSource binding is placed before SelectedValue binding in XAML.

Alternatively you can try calling Bindings.Update() in the Page_Loaded event of your second page.

Body:
I'm developing a UWP app and I'm facing a problem. The app uses the MVVM pattern with Template10. I have created a similar solution that recreates the problem that I'm facing. In that solution, a list of orders are displayed, the user chooses an order and then click the "Edit" button. Then a second page is displayed and pre-loaded with the previous selected order, in this second page the user can edit the order. The problem is in the second page, the data bound to comboboxes doesn't show. Maybe the problem is related to this question. In my case, the SelectedValue is set before the ItemsSource. After debugging, I have reached these lines of code in OrderEditionPage.g.cs:

private void Update_ViewModel(global::ComboApp.ViewModels.OrderEditionPageViewModel obj, int phase)
{
    this.bindingsTracking.UpdateChildListeners_ViewModel(obj);
    if (obj != null)
    {
        if ((phase & (NOT_PHASED | DATA_CHANGED | (1 << 0))) != 0)
        {
            this.Update_ViewModel_SelectedOrder(obj.SelectedOrder, phase);
        }
        if ((phase & (NOT_PHASED | (1 << 0))) != 0)
        {
            this.Update_ViewModel_BusinessAssociates(obj.BusinessAssociates, phase);
            this.Update_ViewModel_TransactionTypes(obj.TransactionTypes, phase);
            this.Update_ViewModel_OrderTypes(obj.OrderTypes, phase);
            this.Update_ViewModel_ShowSelectedOrder(obj.ShowSelectedOrder, phase);
        }
    }
}

If I could achieve this line of code be executed at last, my problem would be solved: this.Update_ViewModel_SelectedOrder(obj.SelectedOrder, phase);

How could I achieve this? How does Visual Studio determine the order of this lines?

OrderEditionPage.xaml

<Page
    x:Class="ComboApp.Views.OrderEditionPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:myconverters="using:ComboApp.Converters"
    xmlns:t10converters="using:Template10.Converters"
    mc:Ignorable="d">

    <Page.Resources>
        <t10converters:ChangeTypeConverter x:Key="TypeConverter" />
        <myconverters:DateTimeConverter x:Key="DateTimeConverter" />
    </Page.Resources>

    <ScrollViewer VerticalScrollBarVisibility="Auto">
        <StackPanel
            Padding="15, 5"
            Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
            <TextBox
                Header="Order #"
                Margin="5"
                Width="150"
                HorizontalAlignment="Left"
                Text="{x:Bind ViewModel.SelectedOrder.ExternalId, Mode=TwoWay}" />
            <ComboBox
                Header="Business Associate"
                Margin="5"
                MinWidth="300"
                SelectedValuePath="BusinessAssociateId"
                DisplayMemberPath="Name1"
                ItemsSource="{x:Bind ViewModel.BusinessAssociates}"
                SelectedValue="{x:Bind ViewModel.SelectedOrder.BusinessAssociateId, Mode=TwoWay, Converter={StaticResource TypeConverter}}" />
            <DatePicker
                Header="Delivery Date"
                Margin="5"
                MinWidth="0"
                Width="200"
                Date="{x:Bind ViewModel.SelectedOrder.DeliveryDate, Mode=TwoWay, Converter={StaticResource DateTimeConverter}}" />
            <ComboBox
                Header="Transaction"
                MinWidth="200"
                Margin="5"
                SelectedValuePath="Value"
                DisplayMemberPath="Display"
                ItemsSource="{x:Bind ViewModel.TransactionTypes}"
                SelectedValue="{x:Bind ViewModel.SelectedOrder.TransactionType, Mode=TwoWay}" />
            <TextBox
                Header="Priority"
                Margin="5"
                MaxWidth="150"
                HorizontalAlignment="Left"
                Text="{x:Bind ViewModel.SelectedOrder.Priority}" />
            <ComboBox
                Header="Type"
                Margin="5"
                MinWidth="200"
                SelectedValuePath="Value"
                DisplayMemberPath="Display"
                ItemsSource="{x:Bind ViewModel.OrderTypes}"
                SelectedValue="{x:Bind ViewModel.SelectedOrder.OrderType, Mode=TwoWay}" />
            <TextBox
                Header="Information"
                Margin="5"
                Height="100"
                AcceptsReturn="True"
                TextWrapping="Wrap"
                ScrollViewer.VerticalScrollBarVisibility="Auto"
                Text="{x:Bind ViewModel.SelectedOrder.Information, Mode=TwoWay}" />
            <Button
                Margin="5"
                Content="Show"
                Width="100"
                HorizontalAlignment="Right"
                Command="{x:Bind ViewModel.ShowSelectedOrder}" />
        </StackPanel>
    </ScrollViewer>
</Page>

OrderEditionPage.xaml.cs

using ComboApp.ViewModels;
using Windows.UI.Xaml.Controls;

namespace ComboApp.Views
{
    public sealed partial class OrderEditionPage : Page
    {
        public OrderEditionPageViewModel ViewModel => DataContext as OrderEditionPageViewModel;

        public OrderEditionPage()
        {
            this.InitializeComponent();
        }
    }
}

OrderEditionPageViewModel.cs

using ComboApp.Models;
using ComboApp.Services;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using Template10.Mvvm;
using Template10.Utils;
using Windows.UI.Xaml.Navigation;

namespace ComboApp.ViewModels
{
    public class OrderEditionPageViewModel
        : ViewModelBase
    {
        private IBusinessAssociateService businessAssociateService;

        private Order selectedOrder;
        public Order SelectedOrder
        {
            get { return selectedOrder; }
            set { Set(ref selectedOrder, value); }
        }

        public ObservableCollection<object> TransactionTypes { get; set; } = new ObservableCollection<object>();
        public ObservableCollection<object> OrderTypes { get; set; } = new ObservableCollection<object>();
        public ObservableCollection<BusinessAssociate> BusinessAssociates { get; set; } = new ObservableCollection<BusinessAssociate>();

        public OrderEditionPageViewModel(IBusinessAssociateService businessAssociateService)
        {
            this.businessAssociateService = businessAssociateService;

            TransactionTypes.Add(new { Value = "I", Display = "Incoming" });
            TransactionTypes.Add(new { Value = "O", Display = "Outgoing" });
            TransactionTypes.Add(new { Value = "T", Display = "Transfer" });

            OrderTypes.Add(new { Value = "M", Display = "Manual" });
            OrderTypes.Add(new { Value = "A", Display = "Automatic" });
            OrderTypes.Add(new { Value = "S", Display = "Semi-automatic" });
        }

        public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary<string, object> state)
        {
            // Loading buiness associates
            var response = await businessAssociateService.GetNextPageAsync();
            if (response.IsSuccessful)
            {
                BusinessAssociates.AddRange(response.Result.Items);
            }

            SelectedOrder = (Order)parameter;
            await base.OnNavigatedToAsync(parameter, mode, state);
        }

        private DelegateCommand showSelectedOrder;
        public DelegateCommand ShowSelectedOrder => showSelectedOrder ?? (showSelectedOrder = new DelegateCommand(async () =>
        {
            await Views.MessageBox.ShowAsync(JsonConvert.SerializeObject(SelectedOrder, Formatting.Indented));
        }));

    }
}


问:
Startup.cs security measures
I would like to know whether I am

(a) engaging in good coding practices,

(b) repeating myself harmlessly, or

(c) adding inefficient redundancies

For example:

1) In Configure() I can add RewriteOptions().AddRedirectToHttps();

2) In ConfigureServices() I can add
 services.Configure<MvcOptions>(options =>
            { options.Filters.Add(new RequireHttpsAttribute()); });

Another example:

1) In Configure() I can add app.UseAuthentication();

2) In ConfigureServices() I can add .RequireAuthenticatedUser() to my AddMvc() call.

It seems in both examples that I can get away with just one call. Am I free and clear to keep only one call? And if so, which one is the better to keep?

I've searched around a fair bit and I can see all of these approaches in use, but I haven't found a resource that compares the relative merits of these calls, let alone indicates whether it's good or bad practice to use them together.

答:
To take your first example:

1) In Configure() I can add RewriteOptions().AddRedirectToHttps();

2) In ConfigureServices() I can add  services.Configure<MvcOptions>(options =>
             { options.Filters.Add(new RequireHttpsAttribute()); });

Both of these achieve essentially the same thing - they will redirect HTTP requests to HTTPS. The difference is which requests they are applied to.

If you use the rewriter middleware, all requests that make it to the middleware will be redirected to HTTPS.

```<code>public void Configure(IApplicationBuilder app)
{
    app.UseStaticFiles(); // Requests handled by this middleware won't be redirected to HTTPS

    var options = new RewriteOptions()
       .AddRedirectToHttps();

    app.UseRewriter(options); // All requests that make it this far will be redirected from HTTP to HTTPS

    app.UseMvc(); // Requests guaranteed to be HTTPS
}
</code>```

In the second case, where you use a global filter to apply the RequireHttpsAttribute, only requests that make it to the MvcMiddleware will be redirected to HTTPS.

In terms of best practices, I recommend using the rewriter middleware - you can add it to the start of your middleware pipeline, and then all of your requests are required to HTTPS, instead of just the requests that make it to the MVC middleware.

In your second example, the two methods actually do different things:

app.UseAuthentication() - authenticates the request, and sets the User associated with the request by e.g. deserializing the user principal stored in the cookie

RequireAuthenticatedUser() - Requires that a User has logged in before action methods on your controllers are called. If the user hasn't logged in, they are redirected to the login page. In this case, you must call app.UseAuthentication() before app.UseMvc(), otherwise the User for the request will not be set even if you've logged in, and you will be redirected to the login page.

Title: Startup.cs security measures

Body:
To take your first example:

1) In Configure() I can add RewriteOptions().AddRedirectToHttps();

2) In ConfigureServices() I can add  services.Configure<MvcOptions>(options =>
             { options.Filters.Add(new RequireHttpsAttribute()); });

Both of these achieve essentially the same thing - they will redirect HTTP requests to HTTPS. The difference is which requests they are applied to.

If you use the rewriter middleware, all requests that make it to the middleware will be redirected to HTTPS.

public void Configure(IApplicationBuilder app)
{
    app.UseStaticFiles(); // Requests handled by this middleware won't be redirected to HTTPS

    var options = new RewriteOptions()
       .AddRedirectToHttps();

    app.UseRewriter(options); // All requests that make it this far will be redirected from HTTP to HTTPS

    app.UseMvc(); // Requests guaranteed to be HTTPS
}

In the second case, where you use a global filter to apply the RequireHttpsAttribute, only requests that make it to the MvcMiddleware will be redirected to HTTPS.

In terms of best practices, I recommend using the rewriter middleware - you can add it to the start of your middleware pipeline, and then all of your requests are required to HTTPS, instead of just the requests that make it to the MVC middleware.

In your second example, the two methods actually do different things:

app.UseAuthentication() - authenticates the request, and sets the User associated with the request by e.g. deserializing the user principal stored in the cookie

RequireAuthenticatedUser() - Requires that a User has logged in before action methods on your controllers are called. If the user hasn't logged in, they are redirected to the login page. In this case, you must call app.UseAuthentication() before app.UseMvc(), otherwise the User for the request will not be set even if you've logged in, and you will be redirected to the login page.


问:
Convert attribute value into element
I'm trying to transform this xml:

```<code><tokens>
 <token cle="a">
  <token cle="b">nomX</token>
  <token cle="c">prenomX</token>
  <token cle="d">villeX</token>
 </token>
 <token cle="a">
  <token cle="b">nomY</token>
  <token cle="c">prenomY</token>
  <token cle="d">villeY</token>
 </token>
 <token cle="e">nomZ</token>
</tokens>
</code>```

into this xml:

```<code><tokens>
 <a>
  <b>nomX</b>
  <c>prenomX</c>
  <d>villeX</d>
 </a>
 <a>
  <b>nomY</b>
  <c>prenomY</c>
  <d>villeY</d>
 </a>
 <e>nomZ</e>
</tokens>
</code>```

so convert the attribute value into an element , but i need to keep the whole structure and deph.

I've tried using XSL, but i didn't succeed yet.
If anyone has an idea, it would be  greatly appreciated.

Thx.

答:
so xslt is the right way I think:</p>

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8"
        indent="yes" />
    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()" />
        </xsl:copy>
    </xsl:template>
    <xsl:template match="token">
        <xsl:element name="{@cle}">
            <xsl:apply-templates />
        </xsl:element>
    </xsl:template>
</xsl:stylesheet>
</code>```

Title: Convert attribute value into element

Body:
I'm trying to transform this xml:

<tokens>
 <token cle="a">
  <token cle="b">nomX</token>
  <token cle="c">prenomX</token>
  <token cle="d">villeX</token>
 </token>
 <token cle="a">
  <token cle="b">nomY</token>
  <token cle="c">prenomY</token>
  <token cle="d">villeY</token>
 </token>
 <token cle="e">nomZ</token>
</tokens>

into this xml:

<tokens>

  nomX
  <c>prenomX</c>
  <d>villeX</d>

  nomY
  <c>prenomY</c>
  <d>villeY</d>

 <e>nomZ</e>
</tokens>

so convert the attribute value into an element , but i need to keep the whole structure and deph.

I've tried using XSL, but i didn't succeed yet.
If anyone has an idea, it would be  greatly appreciated.

Thx.

Body:
so xslt is the right way I think:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8"
        indent="yes" />
    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()" />
        </xsl:copy>
    </xsl:template>
    <xsl:template match="token">
        <xsl:element name="{@cle}">
            <xsl:apply-templates />
        </xsl:element>
    </xsl:template>
</xsl:stylesheet>