问:
casting exception
```<code>Set cust = customer.getCustomerBills();
Iterator<Customer> seriter = (Iterator)cust;
</code>```

I am facing a casting exception when I iterate on Set.

Exception is: org.hibernate.collection.PersistentSet cannot be cast to java.util.Iterator. What am I doing wrong?

答:
You don't cast a collection to Iterator. You obtain one: cust.iterator():

```<code>Set<Customer> cust = customer.getCustomerBills();
Iterator<Customer> seriter = cust.iterator();
</code>```

(A Collection is Iterable, which defines the iterator() method.)

Title: casting exception

Body:
Set cust = customer.getCustomerBills();
Iterator<Customer> seriter = (Iterator)cust;

I am facing a casting exception when I iterate on Set.

Exception is: org.hibernate.collection.PersistentSet cannot be cast to java.util.Iterator. What am I doing wrong?

Body:
You don't cast a collection to Iterator. You obtain one: cust.iterator():

Set<Customer> cust = customer.getCustomerBills();
Iterator<Customer> seriter = cust.iterator();

(A Collection is Iterable, which defines the iterator() method.)


来源: stackexchange

问:
"The method selectByValue(String) undefined for the type WebElement" in Selenium
Can you please some one help me to finish this..

I want to write selenium code for drop down. when I'm trying to use below syntax. Im getting this error in eclipse "The method selectByValue(String) undefined for the type WebElement".

I'm using below syntax:

```<code>ele.selectByIndex(5);
ele.selectByValue("3");
ele.selectByVisibleText(Feb);
</code>```

Thanks in advance...

I have updated after I found the solution.
I have written the code like this for others can use. it's working fine for me.

```<code>public void selectCreditCardType(WebElement selectCreditCardType) throws Exception {
    logger.info("Select Card");
    browser.selectByText(selectCreditCardType, "Visa Card");
    browser.Wait(10);
}
</code>```

答:
Actually selectByVisibleText(); method takes argument as String and you are passing value as webelement that's why it showing error

Just change your argument type to String (enclose in ") and try

```<code>ele.selectByVisibleText("Feb");
</code>```

Updated :

```<code>    @FindBy(xpath = "//select[@name='CTYPE']")
    private WebElement selectCreditCard;
    public void selectCreditCardType() throws Exception
    {
    logger.info("Select Card");
    Select select = new Select(selectCreditCard);
    select.selectByIndex(2);
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Can you please some one help me to finish this..

I want to write selenium code for drop down. when I'm trying to use below syntax. Im getting this error in eclipse "The method selectByValue(String) undefined for the type WebElement".

I'm using below syntax:

ele.selectByIndex(5);
ele.selectByValue("3");
ele.selectByVisibleText(Feb);

Thanks in advance...

I have updated after I found the solution.
I have written the code like this for others can use. it's working fine for me.

public void selectCreditCardType(WebElement selectCreditCardType) throws Exception {
    logger.info("Select Card");
    browser.selectByText(selectCreditCardType, "Visa Card");
    browser.Wait(10);
}

Body:
Actually selectByVisibleText(); method takes argument as String and you are passing value as webelement that's why it showing error

Just change your argument type to String (enclose in ") and try

ele.selectByVisibleText("Feb");

Updated :

    @FindBy(xpath = "//select[@name='CTYPE']")
    private WebElement selectCreditCard;
    public void selectCreditCardType() throws Exception
    {
    logger.info("Select Card");
    Select select = new Select(selectCreditCard);
    select.selectByIndex(2);
    }


问:
My java code resulted in a double spaced output
I'm doing an assignment in MyProgrammingLab for JAVA and my code resulted in an error. The output is double spaced and I can't figure out why. I thought it might have something to do with the 'System.out.println' from reading other discussions, but I was not successful when I left off the 'ln'. This is my first course in JAVA. I apologize if the solution is obvious. Any hint would be helpful. Thank you!

```<code>CODELAB ANALYSIS: LOGICAL ERROR(S)
Problems Detected:
     ⇒     The contents of your standard output is incorrect.

Given the following was entered from the keyboard:
!!!!!If you built your letter counter properly it will not count anything
but proper letters@@@@@@.
AlsO The DegRee OF captilization SHOULD NOT AFFECT YOUR COUNTER in any way
shape or form.
Multiple sentences on one line are fine. As long as the line ends with a
period.
aaaaa bbbbb ttttt uuuuuuuuuu.
Goodbye

you displayed:
...
The letter B occurred 2 times in the sentence.

The letter C occurred 2 times in the sentence.

The letter E occurred 7 times in the sentence.

The letter F occurred 1 times in the sentence.

...
instead of:
...
The letter B occurred 2 times in the sentence.
The letter C occurred 2 times in the sentence.
The letter E occurred 7 times in the sentence.
The letter F occurred 1 times in the sentence.
The letter G occurred 1 times in the sentence.
The letter H occurred 1 times in the sentence.
The letter I occurred 5 times in the sentence.
The letter L occurred 6 times in the sentence.
The letter N occurred 5 times in the sentence.
...

     ⇒     Failed 4 out of 4 test runs.

Failed Test Run #1

     ⇒     The contents of your standard output is incorrect.
     ⇒     There is an error in your prompts.

Hide Invisibles
Expected Result:
</code>```

Enter·a·sentence·ending·with·a·period·or·anything·not·ending·in·a·period·to·end:

The·letter·A·occurred·4·times·in·the·sentence.↵
      The·letter·B·occurred·1·times·in·the·sentence.↵
      The·letter·C·occurred·1·times·in·the·sentence.↵
      The·letter·E·occurred·9·times·in·the·sentence.↵
      The·letter·H·occurred·3·times·in·the·sentence.↵
      The·letter·I·occurred·1·times·in·the·sentence.↵
      The·letter·N·occurred·4·times·in·the·sentence.↵
      The·letter·O·occurred·2·times·in·the·sentence.↵
      The·letter·R·occurred·4·times·in·the·sentence.↵
      The·letter·S·occurred·4·times·in·the·sentence.↵
      The·letter·T·occurred·1·times·in·the·sentence.↵
      The·letter·U·occurred·1·times·in·the·sentence.↵
      The·letter·V·occurred·2·times·in·the·sentence.↵
      The·letter·W·occurred·1·times·in·the·sentence.↵ Enter·a·sentence·ending·with·a·period·or·anything·not·ending·in·a·period·to·end:
      The·letter·A·occurred·15·times·in·the·sentence.↵
      The·letter·B·occurred·5·times·in·the·sentence.↵
      The·letter·C·occurred·10·times·in·the·sentence.↵ Enter·a·sentence·ending·with·a·period·or·anything·not·ending·in·a·period·to·end:
      The·letter·Z·occurred·5·times·in·the·sentence.↵ Enter·a·sentence·ending·with·a·period·or·anything·not·ending·in·a·period·to·end:
      The·letter·G·occurred·8·times·in·the·sentence.↵
      The·letter·R·occurred·9·times·in·the·sentence.↵ Enter·a·sentence·ending·with·a·period·or·anything·not·ending·in·a·period·to·end:
      The·letter·A·occurred·1·times·in·the·sentence.↵
      The·letter·C·occurred·1·times·in·the·sentence.↵
      The·letter·D·occurred·1·times·in·the·sentence.↵
      The·letter·E·occurred·4·times·in·the·sentence.↵
      The·letter·G·occurred·2·times·in·the·sentence.↵
      The·letter·H·occurred·3·times·in·the·sentence.↵
      The·letter·I·occurred·2·times·in·the·sentence.↵
      The·letter·L·occurred·4·times·in·the·sentence.↵
      The·letter·M·occurred·1·times·in·the·sentence.↵
      The·letter·N·occurred·4·times·in·the·sentence.↵
      The·letter·O·occurred·5·times·in·the·sentence.↵
      The·letter·P·occurred·1·times·in·the·sentence.↵
      The·letter·R·occurred·3·times·in·the·sentence.↵
      The·letter·S·occurred·4·times·in·the·sentence.↵
      The·letter·T·occurred·5·times·in·the·sentence.↵
      The·letter·U·occurred·2·times·in·the·sentence.↵
      The·letter·Y·occurred·1·times·in·the·sentence.↵ Enter·a·sentence·ending·with·a·period·or·anything·not·ending·in·a·period·to·end:
      The·letter·A·occurred·9·times·in·the·sentence.↵
      The·letter·B·occurred·2·times·in·the·sentence.↵
      The·letter·C·occurred·3·times·in·the·sentence.↵
      The·letter·E·occurred·24·times·in·the·sentence.↵
      The·letter·F·occurred·3·times·in·the·sentence.↵
      The·letter·G·occurred·7·times·in·the·sentence.↵
      The·letter·H·occurred·14·times·in·the·sentence.↵
      The·letter·I·occurred·12·times·in·the·sentence.↵
      The·letter·K·occurred·1·times·in·the·sentence.↵
      The·letter·L·occurred·7·times·in·the·sentence.↵
      The·letter·M·occurred·2·times·in·the·sentence.↵
      The·letter·N·occurred·10·times·in·the·sentence.↵
      The·letter·O·occurred·9·times·in·the·sentence.↵
      The·letter·P·occurred·4·times·in·the·sentence.↵
      The·letter·Q·occurred·1·times·in·the·sentence.↵
      The·letter·R·occurred·5·times·in·the·sentence.↵
      The·letter·S·occurred·9·times·in·the·sentence.↵
      The·letter·T·occurred·22·times·in·the·sentence.↵
      The·letter·U·occurred·8·times·in·the·sentence.↵
      The·letter·V·occurred·1·times·in·the·sentence.↵
      The·letter·W·occurred·3·times·in·the·sentence.↵
      The·letter·X·occurred·1·times·in·the·sentence.↵
      The·letter·Y·occurred·5·times·in·the·sentence.↵ Enter·a·sentence·ending·with·a·period·or·anything·not·ending·in·a·period·to·end:
      The·letter·A·occurred·6·times·in·the·sentence.↵
      The·letter·B·occurred·1·times·in·the·sentence.↵
      The·letter·C·occurred·1·times·in·the·sentence.↵
      The·letter·D·occurred·2·times·in·the·sentence.↵
      The·letter·E·occurred·7·times·in·the·sentence.↵
      The·letter·G·occurred·2·times·in·the·sentence.↵
      The·letter·H·occurred·5·times·in·the·sentence.↵
      The·letter·I·occurred·6·times·in·the·sentence.↵
      The·letter·L·occurred·2·times·in·the·sentence.↵
      The·letter·M·occurred·2·times·in·the·sentence.↵
      The·letter·N·occurred·5·times·in·the·sentence.↵
      The·letter·O·occurred·5·times·in·the·sentence.↵
      The·letter·P·occurred·2·times·in·the·sentence.↵
      The·letter·R·occurred·4·times·in·the·sentence.↵
      The·letter·S·occurred·2·times·in·the·sentence.↵
      The·letter·T·occurred·12·times·in·the·sentence.↵
      The·letter·U·occurred·3·times·in·the·sentence.↵
      The·letter·W·occurred·2·times·in·the·sentence.↵
      The·letter·Y·occurred·1·times·in·the·sentence.↵ Enter·a·sentence·ending·with·a·period·or·anything·not·ending·in·a·period·to·end:↵

Your Code's Actual Result:

Enter·a·sentence·ending·with·a·period·or·anything·not·ending·in·a·period·to·end:
      The·letter·A·occurred·4·times·in·the·sentence.↵
      ↵
      The·letter·B·occurred·1·times·in·the·sentence.↵
      ↵
      The·letter·C·occurred·1·times·in·the·sentence.↵
      ↵
      The·letter·E·occurred·9·times·in·the·sentence.↵
      ↵
      The·letter·H·occurred·3·times·in·the·sentence.↵
      ↵
      The·letter·I·occurred·1·times·in·the·sentence.↵
      ↵
      The·letter·N·occurred·4·times·in·the·sentence.↵
      ↵
      The·letter·O·occurred·2·times·in·the·sentence.↵
      ↵
      The·letter·R·occurred·4·times·in·the·sentence.↵
      ↵
      The·letter·S·occurred·4·times·in·the·sentence.↵
      ↵
      The·letter·T·occurred·1·times·in·the·sentence.↵
      ↵
      The·letter·U·occurred·1·times·in·the·sentence.↵
      ↵
      The·letter·V·occurred·2·times·in·the·sentence.↵
      ↵
      The·letter·W·occurred·1·times·in·the·sentence.↵
      ↵
      ↵

Here is my code:

```<code>import java.util.Scanner;
public class LetterFreq
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        String input = "";
        int a[] = new int[26];
        System.out.print("Enter a sentence ending with a period or anything not ending in a period to end:");
        input = sc.nextLine();
        char[] c = input.toCharArray();
        for(int i = 0; i < c.length; i++)
        {
            if(Character.isDigit(c[i]))
            {
                System.out.println();
                System.exit(0);
            }
            if(Character.isLetter(c[i]))
            {
                if(Character.isLowerCase(c[i]))
                    c[i] = Character.toUpperCase(c[i]);
                int index = c[i] - 'A';
                int b = a[index];
                b++;
                a[index] = b;
            }
        }
        for(int i = 0; i < a.length; i++)
        {
            if(a[i] > 0)
            {
                System.out.println("The letter " + (char)(i + 'A') + " occurred " + a[i] + " times in the sentence.");
                System.out.println();
            }
        }
        System.out.println();
    }
}
</code>```

UPDATE:
When I remove the 'System.out.println();' that appears after the one with '"The letter "', I get another output error:
    CODELAB ANALYSIS: LOGICAL ERROR(S)

```<code>Problems Detected:
     ⇒     The contents of your standard output is incorrect.

Given the following was entered from the keyboard:
!!!!!If you built your letter counter properly it will not count anything
</code>```

but proper letters@@@@@@.
    AlsO The DegRee OF captilization SHOULD NOT AFFECT YOUR COUNTER in any way shape or form.
    Multiple sentences on one line are fine. As long as the line ends with a period.
    aaaaa bbbbb ttttt uuuuuuuuuu.
    Goodbye

```<code>you displayed:
...

instead of:
...
Enter a sentence ending with a period or anything not ending in a period to
end:The letter A occurred 7 times in the sentence.
The letter C occurred 3 times in the sentence.
The letter D occurred 2 times in the sentence.
The letter E occurred 7 times in the sentence.
The letter F occurred 4 times in the sentence.
The letter G occurred 1 times in the sentence.
The letter H occurred 3 times in the sentence.
The letter I occurred 4 times in the sentence.
The letter L occurred 3 times in the sentence.
...

     ⇒     Failed 4 out of 4 test runs.

     ⇒     The contents of your standard output is incorrect.
     ⇒     There is an error in your prompts.
</code>```

The output for my code shows up far down the page on the test runs, but the double-spacing has been corrected. I'm not sure how to fix the error mentioned above. Thoughts?

答: println adds the newline character at the end of your output, and you have two of them - one with the output you want, and another one after it. Remove it, and you should be OK.

Body:
I'm doing an assignment in MyProgrammingLab for JAVA and my code resulted in an error. The output is double spaced and I can't figure out why. I thought it might have something to do with the 'System.out.println' from reading other discussions, but I was not successful when I left off the 'ln'. This is my first course in JAVA. I apologize if the solution is obvious. Any hint would be helpful. Thank you!

CODELAB ANALYSIS: LOGICAL ERROR(S)
Problems Detected:
     ⇒     The contents of your standard output is incorrect.

Given the following was entered from the keyboard:
!!!!!If you built your letter counter properly it will not count anything
but proper letters@@@@@@.
AlsO The DegRee OF captilization SHOULD NOT AFFECT YOUR COUNTER in any way
shape or form.
Multiple sentences on one line are fine. As long as the line ends with a
period.
aaaaa bbbbb ttttt uuuuuuuuuu.
Goodbye

you displayed:
...
The letter B occurred 2 times in the sentence.

The letter C occurred 2 times in the sentence.

The letter E occurred 7 times in the sentence.

The letter F occurred 1 times in the sentence.

...
instead of:
...
The letter B occurred 2 times in the sentence.
The letter C occurred 2 times in the sentence.
The letter E occurred 7 times in the sentence.
The letter F occurred 1 times in the sentence.
The letter G occurred 1 times in the sentence.
The letter H occurred 1 times in the sentence.
The letter I occurred 5 times in the sentence.
The letter L occurred 6 times in the sentence.
The letter N occurred 5 times in the sentence.
...

     ⇒     Failed 4 out of 4 test runs.

Failed Test Run #1

     ⇒     The contents of your standard output is incorrect.
     ⇒     There is an error in your prompts.

Hide Invisibles
Expected Result:

Enter·a·sentence·ending·with·a·period·or·anything·not·ending·in·a·period·to·end:

The·letter·A·occurred·4·times·in·the·sentence.↵
      The·letter·B·occurred·1·times·in·the·sentence.↵
      The·letter·C·occurred·1·times·in·the·sentence.↵
      The·letter·E·occurred·9·times·in·the·sentence.↵
      The·letter·H·occurred·3·times·in·the·sentence.↵
      The·letter·I·occurred·1·times·in·the·sentence.↵
      The·letter·N·occurred·4·times·in·the·sentence.↵
      The·letter·O·occurred·2·times·in·the·sentence.↵
      The·letter·R·occurred·4·times·in·the·sentence.↵
      The·letter·S·occurred·4·times·in·the·sentence.↵
      The·letter·T·occurred·1·times·in·the·sentence.↵
      The·letter·U·occurred·1·times·in·the·sentence.↵
      The·letter·V·occurred·2·times·in·the·sentence.↵
      The·letter·W·occurred·1·times·in·the·sentence.↵ Enter·a·sentence·ending·with·a·period·or·anything·not·ending·in·a·period·to·end:
      The·letter·A·occurred·15·times·in·the·sentence.↵
      The·letter·B·occurred·5·times·in·the·sentence.↵
      The·letter·C·occurred·10·times·in·the·sentence.↵ Enter·a·sentence·ending·with·a·period·or·anything·not·ending·in·a·period·to·end:
      The·letter·Z·occurred·5·times·in·the·sentence.↵ Enter·a·sentence·ending·with·a·period·or·anything·not·ending·in·a·period·to·end:
      The·letter·G·occurred·8·times·in·the·sentence.↵
      The·letter·R·occurred·9·times·in·the·sentence.↵ Enter·a·sentence·ending·with·a·period·or·anything·not·ending·in·a·period·to·end:
      The·letter·A·occurred·1·times·in·the·sentence.↵
      The·letter·C·occurred·1·times·in·the·sentence.↵
      The·letter·D·occurred·1·times·in·the·sentence.↵
      The·letter·E·occurred·4·times·in·the·sentence.↵
      The·letter·G·occurred·2·times·in·the·sentence.↵
      The·letter·H·occurred·3·times·in·the·sentence.↵
      The·letter·I·occurred·2·times·in·the·sentence.↵
      The·letter·L·occurred·4·times·in·the·sentence.↵
      The·letter·M·occurred·1·times·in·the·sentence.↵
      The·letter·N·occurred·4·times·in·the·sentence.↵
      The·letter·O·occurred·5·times·in·the·sentence.↵
      The·letter·P·occurred·1·times·in·the·sentence.↵
      The·letter·R·occurred·3·times·in·the·sentence.↵
      The·letter·S·occurred·4·times·in·the·sentence.↵
      The·letter·T·occurred·5·times·in·the·sentence.↵
      The·letter·U·occurred·2·times·in·the·sentence.↵
      The·letter·Y·occurred·1·times·in·the·sentence.↵ Enter·a·sentence·ending·with·a·period·or·anything·not·ending·in·a·period·to·end:
      The·letter·A·occurred·9·times·in·the·sentence.↵
      The·letter·B·occurred·2·times·in·the·sentence.↵
      The·letter·C·occurred·3·times·in·the·sentence.↵
      The·letter·E·occurred·24·times·in·the·sentence.↵
      The·letter·F·occurred·3·times·in·the·sentence.↵
      The·letter·G·occurred·7·times·in·the·sentence.↵
      The·letter·H·occurred·14·times·in·the·sentence.↵
      The·letter·I·occurred·12·times·in·the·sentence.↵
      The·letter·K·occurred·1·times·in·the·sentence.↵
      The·letter·L·occurred·7·times·in·the·sentence.↵
      The·letter·M·occurred·2·times·in·the·sentence.↵
      The·letter·N·occurred·10·times·in·the·sentence.↵
      The·letter·O·occurred·9·times·in·the·sentence.↵
      The·letter·P·occurred·4·times·in·the·sentence.↵
      The·letter·Q·occurred·1·times·in·the·sentence.↵
      The·letter·R·occurred·5·times·in·the·sentence.↵
      The·letter·S·occurred·9·times·in·the·sentence.↵
      The·letter·T·occurred·22·times·in·the·sentence.↵
      The·letter·U·occurred·8·times·in·the·sentence.↵
      The·letter·V·occurred·1·times·in·the·sentence.↵
      The·letter·W·occurred·3·times·in·the·sentence.↵
      The·letter·X·occurred·1·times·in·the·sentence.↵
      The·letter·Y·occurred·5·times·in·the·sentence.↵ Enter·a·sentence·ending·with·a·period·or·anything·not·ending·in·a·period·to·end:
      The·letter·A·occurred·6·times·in·the·sentence.↵
      The·letter·B·occurred·1·times·in·the·sentence.↵
      The·letter·C·occurred·1·times·in·the·sentence.↵
      The·letter·D·occurred·2·times·in·the·sentence.↵
      The·letter·E·occurred·7·times·in·the·sentence.↵
      The·letter·G·occurred·2·times·in·the·sentence.↵
      The·letter·H·occurred·5·times·in·the·sentence.↵
      The·letter·I·occurred·6·times·in·the·sentence.↵
      The·letter·L·occurred·2·times·in·the·sentence.↵
      The·letter·M·occurred·2·times·in·the·sentence.↵
      The·letter·N·occurred·5·times·in·the·sentence.↵
      The·letter·O·occurred·5·times·in·the·sentence.↵
      The·letter·P·occurred·2·times·in·the·sentence.↵
      The·letter·R·occurred·4·times·in·the·sentence.↵
      The·letter·S·occurred·2·times·in·the·sentence.↵
      The·letter·T·occurred·12·times·in·the·sentence.↵
      The·letter·U·occurred·3·times·in·the·sentence.↵
      The·letter·W·occurred·2·times·in·the·sentence.↵
      The·letter·Y·occurred·1·times·in·the·sentence.↵ Enter·a·sentence·ending·with·a·period·or·anything·not·ending·in·a·period·to·end:↵

Your Code's Actual Result:

Enter·a·sentence·ending·with·a·period·or·anything·not·ending·in·a·period·to·end:
      The·letter·A·occurred·4·times·in·the·sentence.↵
      ↵
      The·letter·B·occurred·1·times·in·the·sentence.↵
      ↵
      The·letter·C·occurred·1·times·in·the·sentence.↵
      ↵
      The·letter·E·occurred·9·times·in·the·sentence.↵
      ↵
      The·letter·H·occurred·3·times·in·the·sentence.↵
      ↵
      The·letter·I·occurred·1·times·in·the·sentence.↵
      ↵
      The·letter·N·occurred·4·times·in·the·sentence.↵
      ↵
      The·letter·O·occurred·2·times·in·the·sentence.↵
      ↵
      The·letter·R·occurred·4·times·in·the·sentence.↵
      ↵
      The·letter·S·occurred·4·times·in·the·sentence.↵
      ↵
      The·letter·T·occurred·1·times·in·the·sentence.↵
      ↵
      The·letter·U·occurred·1·times·in·the·sentence.↵
      ↵
      The·letter·V·occurred·2·times·in·the·sentence.↵
      ↵
      The·letter·W·occurred·1·times·in·the·sentence.↵
      ↵
      ↵

Here is my code:

import java.util.Scanner;
public class LetterFreq
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        String input = "";
        int a[] = new int[26];
        System.out.print("Enter a sentence ending with a period or anything not ending in a period to end:");
        input = sc.nextLine();
        char[] c = input.toCharArray();
        for(int i = 0; i < c.length; i++)
        {
            if(Character.isDigit(c[i]))
            {
                System.out.println();
                System.exit(0);
            }
            if(Character.isLetter(c[i]))
            {
                if(Character.isLowerCase(c[i]))
                    c[i] = Character.toUpperCase(c[i]);
                int index = c[i] - 'A';
                int b = a[index];
                b++;
                a[index] = b;
            }
        }
        for(int i = 0; i  0)
            {
                System.out.println("The letter " + (char)(i + 'A') + " occurred " + a[i] + " times in the sentence.");
                System.out.println();
            }
        }
        System.out.println();
    }
}

UPDATE:
When I remove the 'System.out.println();' that appears after the one with '"The letter "', I get another output error:
    CODELAB ANALYSIS: LOGICAL ERROR(S)

Problems Detected:
     ⇒     The contents of your standard output is incorrect.

Given the following was entered from the keyboard:
!!!!!If you built your letter counter properly it will not count anything

but proper letters@@@@@@.
    AlsO The DegRee OF captilization SHOULD NOT AFFECT YOUR COUNTER in any way shape or form.
    Multiple sentences on one line are fine. As long as the line ends with a period.
    aaaaa bbbbb ttttt uuuuuuuuuu.
    Goodbye

you displayed:
...

instead of:
...
Enter a sentence ending with a period or anything not ending in a period to
end:The letter A occurred 7 times in the sentence.
The letter C occurred 3 times in the sentence.
The letter D occurred 2 times in the sentence.
The letter E occurred 7 times in the sentence.
The letter F occurred 4 times in the sentence.
The letter G occurred 1 times in the sentence.
The letter H occurred 3 times in the sentence.
The letter I occurred 4 times in the sentence.
The letter L occurred 3 times in the sentence.
...

     ⇒     Failed 4 out of 4 test runs.

     ⇒     The contents of your standard output is incorrect.
     ⇒     There is an error in your prompts.

The output for my code shows up far down the page on the test runs, but the double-spacing has been corrected. I'm not sure how to fix the error mentioned above. Thoughts?


问:
Json Deserialize C#
I want to parsing this json file.

{"features":[{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[26.4217861898109,40.127607984644],[26.4219934821323,40.1275230229872],[26.4218810759267,40.1273800013679],[26.4216801413981,40.1274730404221],[26.4217861898109,40.127607984644]]]},"properties":{"ParselNo":"1","Alan":"340.48
  m2","Mevkii":"-","Nitelik":"Arsa","Ada":"698","Il":"Çanakkale","Ilce":"Merkez","Pafta":"16","Mahalle":"Barbaros"}}],"type":"FeatureCollection","crs":{"type":"name","properties":{"name":"EPSG:4326"}}}

I try this code:

```<code>string fileName = file.FileName;
string json = System.IO.File.ReadAllText(fileName);
dynamic stuff = JsonConvert.DeserializeObject(json);

string s1 = Convert.ToString(stuff.features.Count);
string s2 = stuff.properties.ParselNo;
MessageBox.Show(s1);
MessageBox.Show(s2);
</code>```

s1 is working but s2 give error. How can I fix it?

I want to get it like this:

```<code>Coordinates[] coordinates = [(26.xx, 40.xx), (26.xx,40.xx) ... ]
ParselNo = 1
Alan = 340.48
Nitelik = Arsa
Ada = 698
İl = Çanakkale
İlçe = Merkez
Pafta = 16
dat_name = EPSG:4326
</code>```

what can i do?

Title: Json Deserialize C#

Body:
I want to parsing this json file.

{"features":[{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[26.4217861898109,40.127607984644],[26.4219934821323,40.1275230229872],[26.4218810759267,40.1273800013679],[26.4216801413981,40.1274730404221],[26.4217861898109,40.127607984644]]]},"properties":{"ParselNo":"1","Alan":"340.48
  m2","Mevkii":"-","Nitelik":"Arsa","Ada":"698","Il":"Çanakkale","Ilce":"Merkez","Pafta":"16","Mahalle":"Barbaros"}}],"type":"FeatureCollection","crs":{"type":"name","properties":{"name":"EPSG:4326"}}}

I try this code:

string fileName = file.FileName;
string json = System.IO.File.ReadAllText(fileName);
dynamic stuff = JsonConvert.DeserializeObject(json);

string s1 = Convert.ToString(stuff.features.Count);
string s2 = stuff.properties.ParselNo;
MessageBox.Show(s1);
MessageBox.Show(s2);

s1 is working but s2 give error. How can I fix it?

I want to get it like this:

Coordinates[] coordinates = [(26.xx, 40.xx), (26.xx,40.xx) ... ]
ParselNo = 1
Alan = 340.48
Nitelik = Arsa
Ada = 698
İl = Çanakkale
İlçe = Merkez
Pafta = 16
dat_name = EPSG:4326

what can i do?

Body:
If you properly format your json as below i believe

 stuff.features.properties.ParselNo;

should get the the Parse1No

  {
   "features":[
      {
         "type":"Feature",
         "geometry":{
            "type":"Polygon",
            "coordinates":[
               [
                  [
                     26.4217861898109,
                     40.127607984644
                  ],
                  [
                     26.4219934821323,
                     40.1275230229872
                  ],
                  [
                     26.4218810759267,
                     40.1273800013679
                  ],
                  [
                     26.4216801413981,
                     40.1274730404221
                  ],
                  [
                     26.4217861898109,
                     40.127607984644
                  ]
               ]
            ]
         },
         "properties":{
            "ParselNo":"1",
            "Alan":"340.48 m2",
            "Mevkii":"-",
            "Nitelik":"Arsa",
            "Ada":"698",
            "Il":"Çanakkale",
            "Ilce":"Merkez",
            "Pafta":"16",
            "Mahalle":"Barbaros"
         }
      }
   ],
   "type":"FeatureCollection",
   "crs":{
      "type":"name",
      "properties":{
         "name":"EPSG:4326"
      }
   }
}


问:
laravel 5.4: PHP Fatal error: Call to undefined method Illuminate\Foundation\Application::configure()
I am new to laravel. I am trying to use Snappy PDF from barryvdh. I have installed snappy pdf by following instruction from https://github.com/barryvdh/laravel-snappy. But when i run php artisan serve command following error is showed

PHP Fatal error:  Call to undefined method Illuminate\Foundation\Application::configure() in F:\xampp\htdocs\Laravel\doctorApp\vendor\barryvdh\laravel-snappy\src\LumenServiceProvider.php on line 21

Here is that line from my LumenServiceProvider.php:

```<code>public function register()
{
   $this->app->configure('snappy'); // line 21

   $configPath = __DIR__ . '/../config/snappy.php';
   $this->mergeConfigFrom($configPath, 'snappy');
}
</code>```

I have installed wkhtmltopdf using this:

```<code>$ composer require h4cc/wkhtmltopdf-amd64 0.12.x
$ composer require h4cc/wkhtmltoimage-amd64 0.12.x
</code>```

in config/app.php i have added follwing lines in my providers and aliases:

in providers: Barryvdh\Snappy\ServiceProvider::class,

in aliases:

```<code>'PDF' => Barryvdh\Snappy\Facades\SnappyPdf::class,
'SnappyImage' => Barryvdh\Snappy\Facades\SnappyImage::class,
</code>```

The path to the binaries in my config file (config/snappy.php): first one for pdf..

```<code>'binary' => base_path('vendor/h4cc/wkhtmltopdf-amd64/bin/wkhtmltopdf-amd64'),
</code>```

2nd one for image...

```<code>'binary' => base_path('vendor/h4cc/wkhtmltoimage-amd64/bin/wkhtmltoimage-amd64'),
</code>```

my bootstrap/app.php:

```<code><?php

$app = new Illuminate\Foundation\Application(
    realpath(__DIR__.'/../')
);

/*snappy pdf start--- i added this part*/
class_alias('Barryvdh\Snappy\Facades\SnappyPdf', 'PDF');
$app->register(Barryvdh\Snappy\LumenServiceProvider::class);

//Optionally, add the facades like so:

class_alias(Barryvdh\Snappy\Facades\SnappyPdf::class, 'PDF');
class_alias(Barryvdh\Snappy\Facades\SnappyImage::class, 'SnappyImage');

/*snappy pdf end*/

$app->singleton(
    Illuminate\Contracts\Http\Kernel::class,
    App\Http\Kernel::class
);

$app->singleton(
    Illuminate\Contracts\Console\Kernel::class,
    App\Console\Kernel::class
);

$app->singleton(
    Illuminate\Contracts\Debug\ExceptionHandler::class,
    App\Exceptions\Handler::class
);

return $app;
</code>```

In my controller i added:

```<code>use Barryvdh\Snappy\Facades as PDF;
</code>```

This is my controller:

```<code>public function PdfView(Request $request, $patient_id)
{
   $patients = Patient::where('id', $patient_id)->first();
   $pdf = PDF::loadView('pdfview', ['patients'=>$patients]);
   return $pdf->download('pdfview.pdf');

}
</code>```

Can someone please say, why this error occurred and how to resolve this?

答:
If you are using Laravel you shouldn't use LumenServiceProvider but:

```<code>Barryvdh\Snappy\ServiceProvider::class,
</code>```

as stated in package documentation

EDIT

Ok, I see the problem is different reading it again. You added:

```<code>class_alias('Barryvdh\Snappy\Facades\SnappyPdf', 'PDF');
$app->register(Barryvdh\Snappy\LumenServiceProvider::class);

//Optionally, add the facades like so:

class_alias(Barryvdh\Snappy\Facades\SnappyPdf::class, 'PDF');
class_alias(Barryvdh\Snappy\Facades\SnappyImage::class, 'SnappyImage');
</code>```

into bootstrap/app.php but you shouldn't. This is for Lumen only, not for Laravel

Body:
I am new to laravel. I am trying to use Snappy PDF from barryvdh. I have installed snappy pdf by following instruction from https://github.com/barryvdh/laravel-snappy. But when i run php artisan serve command following error is showed

PHP Fatal error:  Call to undefined method Illuminate\Foundation\Application::configure() in F:\xampp\htdocs\Laravel\doctorApp\vendor\barryvdh\laravel-snappy\src\LumenServiceProvider.php on line 21

Here is that line from my LumenServiceProvider.php:

public function register()
{
   $this->app->configure('snappy'); // line 21

   $configPath = __DIR__ . '/../config/snappy.php';
   $this->mergeConfigFrom($configPath, 'snappy');
}

I have installed wkhtmltopdf using this:

$ composer require h4cc/wkhtmltopdf-amd64 0.12.x
$ composer require h4cc/wkhtmltoimage-amd64 0.12.x

in config/app.php i have added follwing lines in my providers and aliases:

in providers: Barryvdh\Snappy\ServiceProvider::class,

in aliases:

'PDF' => Barryvdh\Snappy\Facades\SnappyPdf::class,
'SnappyImage' => Barryvdh\Snappy\Facades\SnappyImage::class,

The path to the binaries in my config file (config/snappy.php): first one for pdf..

'binary' => base_path('vendor/h4cc/wkhtmltopdf-amd64/bin/wkhtmltopdf-amd64'),

2nd one for image...

'binary' => base_path('vendor/h4cc/wkhtmltoimage-amd64/bin/wkhtmltoimage-amd64'),

my bootstrap/app.php:

<?php

$app = new Illuminate\Foundation\Application(
    realpath(__DIR__.'/../')
);

/*snappy pdf start--- i added this part*/
class_alias('Barryvdh\Snappy\Facades\SnappyPdf', 'PDF');
$app->register(Barryvdh\Snappy\LumenServiceProvider::class);

//Optionally, add the facades like so:

class_alias(Barryvdh\Snappy\Facades\SnappyPdf::class, 'PDF');
class_alias(Barryvdh\Snappy\Facades\SnappyImage::class, 'SnappyImage');

/*snappy pdf end*/

$app->singleton(
    Illuminate\Contracts\Http\Kernel::class,
    App\Http\Kernel::class
);

$app->singleton(
    Illuminate\Contracts\Console\Kernel::class,
    App\Console\Kernel::class
);

$app->singleton(
    Illuminate\Contracts\Debug\ExceptionHandler::class,
    App\Exceptions\Handler::class
);

return $app;

In my controller i added:

use Barryvdh\Snappy\Facades as PDF;

This is my controller:

public function PdfView(Request $request, $patient_id)
{
   $patients = Patient::where('id', $patient_id)->first();
   $pdf = PDF::loadView('pdfview', ['patients'=>$patients]);
   return $pdf->download('pdfview.pdf');

}

Can someone please say, why this error occurred and how to resolve this?

Body:
If you are using Laravel you shouldn't use LumenServiceProvider but:

Barryvdh\Snappy\ServiceProvider::class,

as stated in package documentation

EDIT

Ok, I see the problem is different reading it again. You added:

class_alias('Barryvdh\Snappy\Facades\SnappyPdf', 'PDF');
$app->register(Barryvdh\Snappy\LumenServiceProvider::class);

//Optionally, add the facades like so:

class_alias(Barryvdh\Snappy\Facades\SnappyPdf::class, 'PDF');
class_alias(Barryvdh\Snappy\Facades\SnappyImage::class, 'SnappyImage');

into bootstrap/app.php but you shouldn't. This is for Lumen only, not for Laravel


问:
Electron - Stand alone node js server
I'm trying to make a quiz game with electron, where client can open quiz page on localhost:8888 on their mobile phone.

The question is, can you make a web server application with electron, with shipping encrypted server.js (express.js script) and the user that install my app to NOT REQUIRED TO install node.js?

My app might look like this:

```<code>|-----------------------------|
|QuizApp Window         _ [] x|
|-----------------------------|
|Open 192.168.1.1:8888        |
|to start game on your mobile |
|                             |
-------------------------------
</code>```

答:
the question is, can you make web server application with electron, with shipping encrypted server.js (express.js script) and the user that install my app to NOT REQUIRED TO install node.js?

You can embed a Node server inside of your Electron app just like you can use any Node code there, and the user will not need to install anything more than for using any other Electron app especially - it will be especially easy if you don't want to spawn external processes but just use a framework like Express in Electron like you can do any other Node module.

But you will not be able to encrypt the server.js file in any way that wouldn't be very easy to decrypt by the user who wants to do it. This is not hard but fundamentally impossible, as the user will have to be able to encrypt it to run it so you need to give the user all of the information needed to decrypt it and there is no way around it.

If you want to keep the server code secret then you need to host it on your own server. If you want to do that then see some of those answers:

Deploy node.js in production

Simple node.js app deployment on DigitalOcean from GitHub

How to host website in NodeJS and MongoDB? And what will be the cost?

How to host Node.Js server and PostgreSQL database from my computer?

Title: Electron - Stand alone node js server

Body:
I'm trying to make a quiz game with electron, where client can open quiz page on localhost:8888 on their mobile phone.

The question is, can you make a web server application with electron, with shipping encrypted server.js (express.js script) and the user that install my app to NOT REQUIRED TO install node.js?

My app might look like this:

|-----------------------------|
|QuizApp Window         _ [] x|
|-----------------------------|
|Open 192.168.1.1:8888        |
|to start game on your mobile |
|                             |
-------------------------------


问:
Using Wget to download an entire rss feed
Im trying to move a Drupal sites content http://www.philcooke.com/rss.xml using wget, but I am unable to download more then the 10 most recent stories. Ive set the rss feed in the Drupal admin to set rss feeds to show 30 items per feed. Ive done some searching, but I cant seem to find a way to have this display "all" and then use wget to download the posts.

If anyone knows of another way to download all of the posts (and comments for that matter) I wouldnt be opposed to trying that out as well, as at this point, Im willing to give any xml importing method a try. I should also mention the site runs Drupal 5.2 and Im trying to move it to Wordpress 3.0.1

答: You could use the views data source module to re-create a rss feed of any length - http://drupal.org/project/views_datasource </p>

ContentLicense: CC BY-SA 2.5


问:
Spring boot: cannot return index page instead of error page not found
I am building web application using spring boot for backend and angular2 for frontend, spring boot return whitelabel page if a none root url was accessed (because the servlet container does not know about the angular routing), so I am trying to replace the whitelabel page with the index.html page.

After reading some article about this i tried this but not working

```<code>@Component
public class CustomizationBean
 implements EmbeddedServletContainerCustomizer {

@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
    container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/index.html"));
}
}
</code>```

index.html is placed under src/main/resources/static

Am I missing something?

答:
The above code works perfectly fine to display index.html page (instead of white label error), but you need to ensure that your CustomizationBean is available for scanning for the Spring container during the start up @ComponentScan(basePackages = { "com.yourproject"})

As far as I know, in spring boot the scan is automatic , I have my
  CustomizationBean annotation with @Component.

Spring boot, by default only scans the classes under the myproject packages (where ApplicationLauncher main class resides) as explained in this doc here. The rest of the packages need to be specified in @ComponentScan

Body:
I am building web application using spring boot for backend and angular2 for frontend, spring boot return whitelabel page if a none root url was accessed (because the servlet container does not know about the angular routing), so I am trying to replace the whitelabel page with the index.html page.

After reading some article about this i tried this but not working

@Component
public class CustomizationBean
 implements EmbeddedServletContainerCustomizer {

@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
    container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/index.html"));
}
}

index.html is placed under src/main/resources/static

Am I missing something?


问:
How to do typesafe remote procedure call (RPC) in Kotlin?
When developing both the frontend and backend in Kotlin it's just weird that we have to bother with rest json apis to connect them.
Ideal would be the ability to define an interface

```<code>interface Api {
    fun sum(x: Int, y: Int): Int
}
</code>```

Implement it on the server side.

And on the client side be able to call it as easy as

```<code>val api = RPCMagic<Api>
val result: Future<Int> = api.sum(2, 2)
</code>```

Much like scala autowire library does.

答: At this time Kotlin provides no functionality for this, but it's on our medium-term roadmap (after 1.2).</p>

Body:
When developing both the frontend and backend in Kotlin it's just weird that we have to bother with rest json apis to connect them.
Ideal would be the ability to define an interface

interface Api {
    fun sum(x: Int, y: Int): Int
}

Implement it on the server side.

And on the client side be able to call it as easy as

val api = RPCMagic<Api>
val result: Future<Int> = api.sum(2, 2)

Much like scala autowire library does.


问:
Angular 2 - HTTP basic auth request unable to enter details
I've been trying multiple approaches to accessing an API that uses basic auth. The problem is Angular 2 is unable to enter the username and password.

If you navigate to a basic auth website, it will ask you to put in a username and password and then on most browser you click Log In or Cancel. If you click cancel on this website it will return a string saying User pressed Cancel, and that exactly what I am getting by doing it through Angular's HTTP request.

At this stage it doesn't even matter if the encode username and password in the Authorization header is correct, I just need to be able to send a username and password and have it try to login.

Any suggestions?

```<code>request() {
        let headers = new Headers();
        headers.append('Authorization', "Basic dWRpZDM6cGFzc3dvcmQ=");

        this.http.get('http://localhost:8888/api/', {
            headers: headers
        })
            .subscribe(
                data => this.example = data.text(),
                err => this.logError(err.text()),
                () => console.log('Request Complete')
            );
        console.log(this.example);
    }
</code>```

答:
Adding authorization using username & password should help. Please try following :

```<code>      let username : string = 'username';
      let password : string = 'password';
      let headers = new Headers();
      headers.append("Authorization", "Basic " + btoa(username + ":" + password));
      headers.append("Content-Type", "application/x-www-form-urlencoded");
      this.http.get('http://localhost:8888/api/', {
        headers: headers
      }).subscribe(
            data => this.example = data.text(),
            err => this.logError(err.text()),
            () => console.log('Request Complete')
        );
    console.log(this.example);
</code>```

Hope this helps.

Body:
I've been trying multiple approaches to accessing an API that uses basic auth. The problem is Angular 2 is unable to enter the username and password.

If you navigate to a basic auth website, it will ask you to put in a username and password and then on most browser you click Log In or Cancel. If you click cancel on this website it will return a string saying User pressed Cancel, and that exactly what I am getting by doing it through Angular's HTTP request.

At this stage it doesn't even matter if the encode username and password in the Authorization header is correct, I just need to be able to send a username and password and have it try to login.

Any suggestions?

request() {
        let headers = new Headers();
        headers.append('Authorization', "Basic dWRpZDM6cGFzc3dvcmQ=");

        this.http.get('http://localhost:8888/api/', {
            headers: headers
        })
            .subscribe(
                data => this.example = data.text(),
                err => this.logError(err.text()),
                () => console.log('Request Complete')
            );
        console.log(this.example);
    }

Body:
Adding authorization using username & password should help. Please try following :

      let username : string = 'username';
      let password : string = 'password';
      let headers = new Headers();
      headers.append("Authorization", "Basic " + btoa(username + ":" + password));
      headers.append("Content-Type", "application/x-www-form-urlencoded");
      this.http.get('http://localhost:8888/api/', {
        headers: headers
      }).subscribe(
            data => this.example = data.text(),
            err => this.logError(err.text()),
            () => console.log('Request Complete')
        );
    console.log(this.example);

Hope this helps.


问:
How to calculate "score" based on tags match
This will be a bit hard to explain. I have 3 tables, 1 for User, 1 for Interest & 1 for User_Interests. I want to calculate a score and add it to a new column. The score calculation is not that hard: Base points: 50. For each interest both users have I want to add 3 points to score, if a user has a interest that I don't have, I want to add 1 point to score. Is this possible using mySQL SELECT?

User:

| ID |

| 0 |

| 1 |

| 2 |

Interest:

| ID | title |

User_Interests:

| User_ID | Interest_ID |

This will however depends on my own ID. The end result I am looking is a list of all users and there score based on the tags from the user I supply. Let's say my user ID is 0:

Result:

| ID | score |

| 1 | 69 |

| 2 | 54 |

答:
This LEFT JOIN lists common interests and interests of the other user that this user does not have.

```<code>SELECT
    count(my.interest_id) AS common_interests,
    count(*) AS all_interests

FROM users_interests ui
LEFT JOIN users_interest my ON
    (   my.user_id=$user_id
    AND my.interest_id=ui.interest_id )
GROUP BY ui.user_id
</code>```

The answer (according to the number of points you assign) would be common_interests*2 + all_interests

Body:
This LEFT JOIN lists common interests and interests of the other user that this user does not have.

SELECT
    count(my.interest_id) AS common_interests,
    count(*) AS all_interests

FROM users_interests ui
LEFT JOIN users_interest my ON
    (   my.user_id=$user_id
    AND my.interest_id=ui.interest_id )
GROUP BY ui.user_id

The answer (according to the number of points you assign) would be common_interests*2 + all_interests


问:
Session size in Java EE/Seam Application
I'm running into problems with the size of my Sessions with my Web Application that is based on the Jboss Seam Framework. I am using MessAdmin to investigate and it is reporting that as soon as a User logs in, their session size jumps from 50KB to 55MB (ouch). This seems crazy as I keep very few Objects in the Conversation/Session scopes.

The output from MessAdmin makes it hard to determine the cause. I'm hoping that someone with more experience with this tool will be able to point me in the right direction.

Here's the output:

(source: locuslive.com)

(source: locuslive.com)

答:
An explanation to shared objects can be found in the [MessAdmin documentation][1]

[1]: http://messadmin.sourceforge.net/#[[HttpSession size]]

ContentLicense: CC BY-SA 4.0


问:
How can I evenly divide space between two frames using the grid geometry manager in tkinter?
I have a tkinter application I'm trying to create. I've deiced to use the grid geometry manger instead of pack. It has been working well so far, but I've come across a strange problem.

The basic layout I want in my application is to have a toolbar frame on the top side of the window, which will expand to fill the window horizontally, and take up 1/5 of the screen space in terms of height. Another frame will fill the reaming 4/5 screen space(again in terms of height), and will also fill the screen horizontally. Another third frame will be under the second, and I will use frame.tkraise() to switch between the two.

Here is a minimal example of what I'm trying to accomplish:

```<code>import tkinter as tk

class Toolbar(tk.Frame):
    def __init__(self, parent, root, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        self.root = root

        self.lbl = tk.Label(self, text='Toolbar')
        self.lbl.pack()

class PageOne(tk.Frame):
    def __init__(self, parent, root, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        self.root = root

        self.lbl = tk.Label(self, text='PageOne')
        self.lbl.pack()

        self.btn = tk.Button(self, text='MainPage', command=lambda: self.root.show_frame(MainPage))
        self.btn.pack()

class MainPage(tk.Frame):
    def __init__(self, parent, root, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        self.root = root

        self.lbl = tk.Label(self, text='MainPage')
        self.lbl.pack()

        self.btn = tk.Button(self, text='PageOne', command=lambda: self.root.show_frame(PageOne))
        self.btn.pack()

class App(tk.Tk):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._setup_window()
        self.frames = {}

        container = tk.Frame(self, bg='yellow')
        container.pack(side='top', fill='both', expand=True)

        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)
        container.grid_rowconfigure(1, weight=3)

        self.toolbar = Toolbar(container, self, bg='red')
        self.toolbar.grid(row=0, column=0, sticky='new')

        for page in (MainPage, PageOne):
            frame = page(container, self, bg='blue')
            self.frames[page] = frame
            frame.grid(row=1, column=0, sticky='nsew')

        self.show_frame(MainPage)

    def _setup_window(self):
        self.geometry('420x280')
        self.title('backup')

    def show_frame(self, page_name):
        frame = self.frames[page_name]
        frame.tkraise()

if __name__ == '__main__':
    app = App()
    app.mainloop()
</code>```

The code above displays the following frame:

The yellow frame is the window which holds the tool bar and two other frames. The red frame is the tool bar. And the blue frames are the two main windows, which can be toggled between using the "MainPage" and "PageOne" buttons respectively.

As you can probably tell, my problem is that the tool bar frame(the red part)is not fully expanding to fill the reaming yellow space. No matter how much space I allocate for the tool bar frame, it does not expand.

My understanding was that if I put the tool bar frame in the zeroth column, and the
two main windows in the first, and I did container.grid_rowconfigure(0, weight=1) and container.grid_rowconfigure(1, weight=4) that would meet my needs. I made this assumption based on this excerpt from here:

To make a column or row stretchable, use this option and supply a value that  gives the relative weight of this column or row when distributing the extra  space. For example, if a widget w contains a grid layout, these lines will distribute three-fourths of the extra space to the first column and one-fourth  to the second column:

```<code>   w.columnconfigure(0, weight=3)
   w.columnconfigure(1, weight=1)
</code>```

If this option is not used, the column or row will not stretch.

Was I wrong to assume this? Is there something I'm missing? How can I make my tool bar frame expand to fill the extra space?

答:
You just need to tell your toolbar to stick to the south side of the available space as well: </p>

```<code>self.toolbar.grid(row=0, column=0, sticky='nesw')
</code>```

Body:
I have a tkinter application I'm trying to create. I've deiced to use the grid geometry manger instead of pack. It has been working well so far, but I've come across a strange problem.

The basic layout I want in my application is to have a toolbar frame on the top side of the window, which will expand to fill the window horizontally, and take up 1/5 of the screen space in terms of height. Another frame will fill the reaming 4/5 screen space(again in terms of height), and will also fill the screen horizontally. Another third frame will be under the second, and I will use frame.tkraise() to switch between the two.

Here is a minimal example of what I'm trying to accomplish:

import tkinter as tk

class Toolbar(tk.Frame):
    def __init__(self, parent, root, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        self.root = root

        self.lbl = tk.Label(self, text='Toolbar')
        self.lbl.pack()

class PageOne(tk.Frame):
    def __init__(self, parent, root, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        self.root = root

        self.lbl = tk.Label(self, text='PageOne')
        self.lbl.pack()

        self.btn = tk.Button(self, text='MainPage', command=lambda: self.root.show_frame(MainPage))
        self.btn.pack()

class MainPage(tk.Frame):
    def __init__(self, parent, root, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        self.root = root

        self.lbl = tk.Label(self, text='MainPage')
        self.lbl.pack()

        self.btn = tk.Button(self, text='PageOne', command=lambda: self.root.show_frame(PageOne))
        self.btn.pack()

class App(tk.Tk):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._setup_window()
        self.frames = {}

        container = tk.Frame(self, bg='yellow')
        container.pack(side='top', fill='both', expand=True)

        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)
        container.grid_rowconfigure(1, weight=3)

        self.toolbar = Toolbar(container, self, bg='red')
        self.toolbar.grid(row=0, column=0, sticky='new')

        for page in (MainPage, PageOne):
            frame = page(container, self, bg='blue')
            self.frames[page] = frame
            frame.grid(row=1, column=0, sticky='nsew')

        self.show_frame(MainPage)

    def _setup_window(self):
        self.geometry('420x280')
        self.title('backup')

    def show_frame(self, page_name):
        frame = self.frames[page_name]
        frame.tkraise()

if __name__ == '__main__':
    app = App()
    app.mainloop()

The code above displays the following frame:

The yellow frame is the window which holds the tool bar and two other frames. The red frame is the tool bar. And the blue frames are the two main windows, which can be toggled between using the "MainPage" and "PageOne" buttons respectively.

As you can probably tell, my problem is that the tool bar frame(the red part)is not fully expanding to fill the reaming yellow space. No matter how much space I allocate for the tool bar frame, it does not expand.

My understanding was that if I put the tool bar frame in the zeroth column, and the
two main windows in the first, and I did container.grid_rowconfigure(0, weight=1) and container.grid_rowconfigure(1, weight=4) that would meet my needs. I made this assumption based on this excerpt from here:

To make a column or row stretchable, use this option and supply a value that  gives the relative weight of this column or row when distributing the extra  space. For example, if a widget w contains a grid layout, these lines will distribute three-fourths of the extra space to the first column and one-fourth  to the second column:

   w.columnconfigure(0, weight=3)
   w.columnconfigure(1, weight=1)

If this option is not used, the column or row will not stretch.

Was I wrong to assume this? Is there something I'm missing? How can I make my tool bar frame expand to fill the extra space?

Body:
You just need to tell your toolbar to stick to the south side of the available space as well:

self.toolbar.grid(row=0, column=0, sticky='nesw')


问:
ExtJs: how to disable fieldset on button click event
I have a fieldset defined on my page. Now I want to enable or disable this field set on button click event. But it is not working properly. Below is the code I have written:

To Disable:

```<code>this.mySettings.query('[name="fieldsetName"]').forEach(function (field) {
    field.disable();
});
</code>```

To Enable:

```<code>this.mySettings.query('[name="fieldsetName"]').forEach(function (field) {
    field.enable();
});
</code>```

Issue-1 : When I disable fieldset, it seems to be disabled visually. But still I can access controls inside it.

Issue-2 : Once it is disabled, I cannot re-enable it.

I need a working sample with these two issues resolved.

Currently I am using version 4.2 of ExtJs

答:
Paste this into a Sencha fiddle and hit Run:

```<code>Ext.application({
    name : 'Fiddle',

    launch : function() {
        Ext.Msg.alert('Fiddle', 'Welcome to Sencha Fiddle!');

        Ext.create('Ext.window.Window', {
            height: '100%',
            width: '100%',
            autoShow:true,
            bodyPadding: 25,
            title:'win',
            items: [{
                xtype: 'fieldset',
                items: [{
                    xtype: 'checkbox',
                    fieldLabel: 'field1'
                },{
                    xtype: 'checkbox',
                    fieldLabel: 'field2'
                },{
                    fieldLabel: 'field3',
                    xtype: 'combo',
                    store: ['asdf','zzasdf','dfdf']
                }]
            }, {
                xtype: 'button',
                text: 'Enable/Disable entire fieldset',
                handler: function(btn){
                    var fset = btn.up('window').down('fieldset');
                    fset.setDisabled(!fset.disabled);
                }
            }, {
                margin: '0 0 0 10',
                xtype: 'button',
                text: 'Enable/Disable each field in fieldset individually',
                handler: function(btn){
                    var fset = btn.up('window').down('fieldset');
                    fset.items.each(function(i){
                        i.setDisabled(!i.disabled);
                    });
                }
            }]
        });
    }
});
</code>```

Body:
I have a fieldset defined on my page. Now I want to enable or disable this field set on button click event. But it is not working properly. Below is the code I have written:

To Disable:

this.mySettings.query('[name="fieldsetName"]').forEach(function (field) {
    field.disable();
});

To Enable:

this.mySettings.query('[name="fieldsetName"]').forEach(function (field) {
    field.enable();
});

Issue-1 : When I disable fieldset, it seems to be disabled visually. But still I can access controls inside it.

Issue-2 : Once it is disabled, I cannot re-enable it.

I need a working sample with these two issues resolved.

Currently I am using version 4.2 of ExtJs

Body:
Paste this into a Sencha fiddle and hit Run:

Ext.application({
    name : 'Fiddle',

    launch : function() {
        Ext.Msg.alert('Fiddle', 'Welcome to Sencha Fiddle!');

        Ext.create('Ext.window.Window', {
            height: '100%',
            width: '100%',
            autoShow:true,
            bodyPadding: 25,
            title:'win',
            items: [{
                xtype: 'fieldset',
                items: [{
                    xtype: 'checkbox',
                    fieldLabel: 'field1'
                },{
                    xtype: 'checkbox',
                    fieldLabel: 'field2'
                },{
                    fieldLabel: 'field3',
                    xtype: 'combo',
                    store: ['asdf','zzasdf','dfdf']
                }]
            }, {
                xtype: 'button',
                text: 'Enable/Disable entire fieldset',
                handler: function(btn){
                    var fset = btn.up('window').down('fieldset');
                    fset.setDisabled(!fset.disabled);
                }
            }, {
                margin: '0 0 0 10',
                xtype: 'button',
                text: 'Enable/Disable each field in fieldset individually',
                handler: function(btn){
                    var fset = btn.up('window').down('fieldset');
                    fset.items.each(function(i){
                        i.setDisabled(!i.disabled);
                    });
                }
            }]
        });
    }
});


问:
How to convert the values of a Map of List to a single List
How is the best (efficient and simple) way to convert the values of a Map<Object1, List<Object2>> to a List<Object2>. Should I simply iterate over all entries and adAll the items to a list?

答:
One option using addAll.</p>

```<code>List<Object2> list = new ArrayList<>();
myMap.values().forEach(list::addAll);
</code>```

Body:
One option using addAll.

List<Object2> list = new ArrayList<>();
myMap.values().forEach(list::addAll);


问:
numpy min and max functions return nan
I have a two dimentional array full of floats representing the difference between two other 2D arrays.  I need to create a contour and map it, but when I try to map the contour I recieve an error stating that my contour needs at least 2 levels.

ValueError: Filled contours require at least 2 levels.
Error begins at a = np.min(tsEndAvg) and b = np.max(tsEndAvg)

```<code> k = int(raw_input("Enter the iteration amount: "))*12
    x = 0
    # Appending Arrays to cover last 360th slot of lon
    lon2 = np.empty(len(lon)+1)
    for l in range(0, len(lon)):
        lon2[l] = lon[l]
    lon2[len(lon2) - 1] = 360.
    # Creating temp arrays for manipulation later
    tssum = np.empty([len(lat), len(lon)+1])
    tsEndSum = np.empty([len(lat), len(lon) + 1])
    ts2 = np.empty([len(lat), len(lon2)])
    time2 = np.empty(len(time))
    tsEndAvg = np.empty([len(lat), len(lon) + 1])

#START WHILE FOR BEGINNING DATA
    while x < k:
        print str(x)
        # x iterates through a slice of time, k is the iteration amount
        # Attempting to grab global sum of surface temperatures over k iterations
        ts = tempts[x, :, :]
        for i in range(0, len(lat)):
            for j in range(0, len(lon)):
                ts2[i][j] = ts[i][j]
        for i in range(0, 192):
            ts2[i][len(lon2) - 1] = ts[i][0]

        tssum = tssum + ts2# Running sum of the global data
        newDate = beginDate + datetime.timedelta(time[x])
        print newDate
        x = x + 1
    # Dividing each data point in tssum by k for the average amount
#END WHILE
    tssum = tssum / k

#START WHILE FOR END DATA
    x = len(time) -1
    while x > (len(time) - 1) - k:
        # x iterates through a slice of time, k is the iteration amount
        # Attempting to grab global sum of surface temperatures over k iterations
        print x
        ts = tempts[x, :, :]
        for i in range(0, len(lat)):
            for j in range(0, len(lon)):
                ts2[i][j] = ts[i][j]
        for i in range(0, 192):
            ts2[i][len(lon2) - 1] = ts[i][0]
        tsEndSum = tsEndSum + ts2
        x = x - 1
#END WHILE

# AVERAGING ALL GLOBAL DATA
    tsEndSum = tsEndSum / k
    tsEndAvg = tsEndSum - tssum
#END AVG
    a = np.min(tsEndAvg)
    b = np.max(tsEndAvg)

    plt.figure()
    ax = plt.axes(projection=c.PlateCarree())
    ax.coastlines(resolution='50m', linewidth=.25)
    ax.outline_patch.set_visible(False)
    lon2, lat2 = np.meshgrid(lon2, lat)
    plt.contourf(lon2, lat2, tsEndAvg, levels=np.arange(a,b,1)) #ERROR POINTS TO THIS LINE
    name = "SurfaceTempAnom-"+str(k/12)+".png"
    plt.savefig("/Users/Robert/PycharmProjects/CESM/anoms/"+name, dpi=750, bbox_inches='tight', pad_inches=0)
    print('saved: '+name)
</code>```

答:
Well, please show us your input data because it should work. See for example the minimal example:

import numpy as np
a=[[1,2],[3,4]]
print np.max(a)

It will return 4. THus the most likely problems are:

the input cant be interpreted as np-array

its not a list/array of floats

...

Title: numpy min and max functions return nan

Body:
I have a two dimentional array full of floats representing the difference between two other 2D arrays.  I need to create a contour and map it, but when I try to map the contour I recieve an error stating that my contour needs at least 2 levels.

ValueError: Filled contours require at least 2 levels.
Error begins at a = np.min(tsEndAvg) and b = np.max(tsEndAvg)

 k = int(raw_input("Enter the iteration amount: "))*12
    x = 0
    # Appending Arrays to cover last 360th slot of lon
    lon2 = np.empty(len(lon)+1)
    for l in range(0, len(lon)):
        lon2[l] = lon[l]
    lon2[len(lon2) - 1] = 360.
    # Creating temp arrays for manipulation later
    tssum = np.empty([len(lat), len(lon)+1])
    tsEndSum = np.empty([len(lat), len(lon) + 1])
    ts2 = np.empty([len(lat), len(lon2)])
    time2 = np.empty(len(time))
    tsEndAvg = np.empty([len(lat), len(lon) + 1])

#START WHILE FOR BEGINNING DATA
    while x < k:
        print str(x)
        # x iterates through a slice of time, k is the iteration amount
        # Attempting to grab global sum of surface temperatures over k iterations
        ts = tempts[x, :, :]
        for i in range(0, len(lat)):
            for j in range(0, len(lon)):
                ts2[i][j] = ts[i][j]
        for i in range(0, 192):
            ts2[i][len(lon2) - 1] = ts[i][0]

        tssum = tssum + ts2# Running sum of the global data
        newDate = beginDate + datetime.timedelta(time[x])
        print newDate
        x = x + 1
    # Dividing each data point in tssum by k for the average amount
#END WHILE
    tssum = tssum / k

#START WHILE FOR END DATA
    x = len(time) -1
    while x > (len(time) - 1) - k:
        # x iterates through a slice of time, k is the iteration amount
        # Attempting to grab global sum of surface temperatures over k iterations
        print x
        ts = tempts[x, :, :]
        for i in range(0, len(lat)):
            for j in range(0, len(lon)):
                ts2[i][j] = ts[i][j]
        for i in range(0, 192):
            ts2[i][len(lon2) - 1] = ts[i][0]
        tsEndSum = tsEndSum + ts2
        x = x - 1
#END WHILE

# AVERAGING ALL GLOBAL DATA
    tsEndSum = tsEndSum / k
    tsEndAvg = tsEndSum - tssum
#END AVG
    a = np.min(tsEndAvg)
    b = np.max(tsEndAvg)

    plt.figure()
    ax = plt.axes(projection=c.PlateCarree())
    ax.coastlines(resolution='50m', linewidth=.25)
    ax.outline_patch.set_visible(False)
    lon2, lat2 = np.meshgrid(lon2, lat)
    plt.contourf(lon2, lat2, tsEndAvg, levels=np.arange(a,b,1)) #ERROR POINTS TO THIS LINE
    name = "SurfaceTempAnom-"+str(k/12)+".png"
    plt.savefig("/Users/Robert/PycharmProjects/CESM/anoms/"+name, dpi=750, bbox_inches='tight', pad_inches=0)
    print('saved: '+name)


问:
Google Guice MethodInterceptor under Tomcat 8.5
We wan't to use aop methodinterceptors using guice as provider under tomcat 8.5. We are currently already using interceptors and guice in our Java-FX applications without any problems.

Trying to do the same under Tomcat does not work. Objects are injected into servlets via guice, but the annotated methods of those objects are not bound to the interceptor. It looks as if guice might think that cglib/asm are not available and revert to none-aop.

Are there any special preconditions the servlet containers needs to fullfil in order to use guice's aop? As stated above the same configuration of guice/cglib/asm works for us in none webapp projects.

```<code>@Singleton
public class TestServlet extends HttpServlet {

    @Inject
    X                           x;

    public TestServlet() {
        System.out.println("constructor");
        try {
            throw new IOException();
        } catch (final Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
        testMethod(resp);
    }

    protected void testMethod(final HttpServletResponse resp) throws IOException {
        x.test(resp);
    }
}
</code>```

We wan't X in our servlet to contain methods that are intercepted.
By putting the throw/catch thing in the constructor we verified that the constructor is called through guice.

```<code>public class X {
    @Y
    public int test(final ServletResponse res) throws IOException {
        res.getWriter().write("123");
        return 1;
    }
}

public class TestInterceptor implements MethodInterceptor {
    @Override
    public Object invoke(final MethodInvocation arg0) throws Throwable {
        System.out.println("METHOD INTERCEPTOR " + arg0);
        return arg0.proceed();
    }
}

public class Module extends AbstractModule {
    @Override
    protected void configure() {
        System.out.println("TestInterceptor configuration");
        bindInterceptor(Matchers.any(), Matchers.annotatedWith(Y.class), new TestInterceptor());
    }
}

@WebListener
public class BootStrap extends GuiceServletContextListener {

...

    @Override
    protected Injector getInjector() {
    final Injector inject = Guice.injector(new Module(), new ServletModule() {
            @Override
            protected void configureServlets() {
                super.configureServlets();
                System.out.println("Injector");
                serve("/test2/*").with(TestServlet.class);
            }
        });
        return inject;
    }
}
</code>```

The servlet is reachable and X is none-null but looking at it in the debugger it is clear no binary code modifications were done.

Are we missing somethings here? Can anyone link an example of a working guice (4+)/tomcat (8+)/aop example?

Edit

It turned out to be unrelated to the servlet container. The trouble was with guice itself. Sorry for the confusion, this problem was very hard to fence in.
For those interested we opened an issue
https://github.com/google/guice/issues/1094

Note that at the time of writing this is not accepted as a bug. It could also be that we missinterpreted the javadoc.

答:
I've used Guice AOP with Tomcat before (though it was an older version of Tomcat) and AOP worked. (I can't link because it was proprietary code).

One thing I notice looking at your posted code is that you are not using the GuiceFilter, which I believe is required.

As stated here you need to configure it at the top of your web.xml like so:

```<code><filter>
    <filter-name>guiceFilter</filter-name>
    <filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>guiceFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
</code>```

Edit based on comments:
You shouldn't have to modify/hack the classloader to use Guice interceptors in a servlet container. They should work out of the box with no additional changes.

Body:
We wan't to use aop methodinterceptors using guice as provider under tomcat 8.5. We are currently already using interceptors and guice in our Java-FX applications without any problems.

Trying to do the same under Tomcat does not work. Objects are injected into servlets via guice, but the annotated methods of those objects are not bound to the interceptor. It looks as if guice might think that cglib/asm are not available and revert to none-aop.

Are there any special preconditions the servlet containers needs to fullfil in order to use guice's aop? As stated above the same configuration of guice/cglib/asm works for us in none webapp projects.

@Singleton
public class TestServlet extends HttpServlet {

    @Inject
    X                           x;

    public TestServlet() {
        System.out.println("constructor");
        try {
            throw new IOException();
        } catch (final Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
        testMethod(resp);
    }

    protected void testMethod(final HttpServletResponse resp) throws IOException {
        x.test(resp);
    }
}

We wan't X in our servlet to contain methods that are intercepted.
By putting the throw/catch thing in the constructor we verified that the constructor is called through guice.

public class X {
    @Y
    public int test(final ServletResponse res) throws IOException {
        res.getWriter().write("123");
        return 1;
    }
}

public class TestInterceptor implements MethodInterceptor {
    @Override
    public Object invoke(final MethodInvocation arg0) throws Throwable {
        System.out.println("METHOD INTERCEPTOR " + arg0);
        return arg0.proceed();
    }
}

public class Module extends AbstractModule {
    @Override
    protected void configure() {
        System.out.println("TestInterceptor configuration");
        bindInterceptor(Matchers.any(), Matchers.annotatedWith(Y.class), new TestInterceptor());
    }
}

@WebListener
public class BootStrap extends GuiceServletContextListener {

...

    @Override
    protected Injector getInjector() {
    final Injector inject = Guice.injector(new Module(), new ServletModule() {
            @Override
            protected void configureServlets() {
                super.configureServlets();
                System.out.println("Injector");
                serve("/test2/*").with(TestServlet.class);
            }
        });
        return inject;
    }
}

The servlet is reachable and X is none-null but looking at it in the debugger it is clear no binary code modifications were done.

Are we missing somethings here? Can anyone link an example of a working guice (4+)/tomcat (8+)/aop example?

Edit

It turned out to be unrelated to the servlet container. The trouble was with guice itself. Sorry for the confusion, this problem was very hard to fence in.
For those interested we opened an issue
https://github.com/google/guice/issues/1094

Note that at the time of writing this is not accepted as a bug. It could also be that we missinterpreted the javadoc.

Body:
I've used Guice AOP with Tomcat before (though it was an older version of Tomcat) and AOP worked. (I can't link because it was proprietary code).

One thing I notice looking at your posted code is that you are not using the GuiceFilter, which I believe is required.

As stated here you need to configure it at the top of your web.xml like so:

<filter>
    <filter-name>guiceFilter</filter-name>
    <filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>guiceFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Edit based on comments:
You shouldn't have to modify/hack the classloader to use Guice interceptors in a servlet container. They should work out of the box with no additional changes.


问:
jquery select any dom element on page
Does anyone know how to select any element (possibly on click) on page like body is selected, div is selected, div#foo etc... so i can place it to some variable and edit it later on.

i've tried

```<code>$("*", document.body).click(function (e) {
 e.stopPropagation();
 var domEl = $(this).get(0);
 alert("Clicked on - " + domEl.tagName);
});
</code>```

but it's not working for all elements

答:
You want to get the target property of the event:

```<code>$(document).click(function(e) {
   e.stopPropagation();
   var domEl = e.target; // or $(e.target) to jQuerytize it
   alert("Clicked on - " + domEl.tagName);
});
</code>```

See: http://www.quirksmode.org/js/events_properties.html

Demo: http://jsfiddle.net/karim79/dyHEA/

Title: jquery select any dom element on page

Body:
Does anyone know how to select any element (possibly on click) on page like body is selected, div is selected, div#foo etc... so i can place it to some variable and edit it later on.

i've tried

$("*", document.body).click(function (e) {
 e.stopPropagation();
 var domEl = $(this).get(0);
 alert("Clicked on - " + domEl.tagName);
});

but it's not working for all elements

Body:
You want to get the target property of the event:

$(document).click(function(e) {
   e.stopPropagation();
   var domEl = e.target; // or $(e.target) to jQuerytize it
   alert("Clicked on - " + domEl.tagName);
});

See: http://www.quirksmode.org/js/events_properties.html

Demo: http://jsfiddle.net/karim79/dyHEA/


问:
How do you set a JLabel to take all the available width space?
I'm trying to center the JLabel text and to change the background and foreground color. I tried to use HTML:

```<code>JLabel listHeader = new JLabel("<html><span style='background-color:#555;color:White;text-align:center;'>Tables</span></html>");
</code>```

But it doesn't seem to work as you can see in the image below.

Image of the components

The label is inside a panel that has the layout manager set to grid bag layout with the following constraints:

```<code>c.gridy=0;
c.gridx=0;
c.weighty=0;
c.weightx=1;
c.fill=GridBagConstraints.NONE;
c.anchor = GridBagConstraints.LINE_START;
</code>```

I tried with fill BOTH as well, same result.

How can I make the label take all the width space?

答:
I tried to use HTML:

Don't use HTML.

I'm trying to center the JLabel text

To center the text in the space available to the label you can use:

```<code>label.setHorizontalAlignment(JLabel.CENTER);
</code>```

and to change the background and foreground color.

You need to make the label opaque:

```<code>label.setOpaque( true ):
label.setBackground( Color.RED );
</code>```

I tried with fill BOTH as well, same result.

Well, I don't think you want "BOTH" since you are only concerned with the width. You may also need to use the weightx constraint. Read the section from the Swing tutorial on How to Use GridBagLayout for more information on using the constraints.

Without your MCVE/SSCCE we can't see exactly what you are doing.

Body:
I'm trying to center the JLabel text and to change the background and foreground color. I tried to use HTML:

JLabel listHeader = new JLabel("Tables");

But it doesn't seem to work as you can see in the image below.

Image of the components

The label is inside a panel that has the layout manager set to grid bag layout with the following constraints:

c.gridy=0;
c.gridx=0;
c.weighty=0;
c.weightx=1;
c.fill=GridBagConstraints.NONE;
c.anchor = GridBagConstraints.LINE_START;

I tried with fill BOTH as well, same result.

How can I make the label take all the width space?

Body:
I tried to use HTML:

Don't use HTML.

I'm trying to center the JLabel text

To center the text in the space available to the label you can use:

label.setHorizontalAlignment(JLabel.CENTER);

and to change the background and foreground color.

You need to make the label opaque:

label.setOpaque( true ):
label.setBackground( Color.RED );

I tried with fill BOTH as well, same result.

Well, I don't think you want "BOTH" since you are only concerned with the width. You may also need to use the weightx constraint. Read the section from the Swing tutorial on How to Use GridBagLayout for more information on using the constraints.

Without your MCVE/SSCCE we can't see exactly what you are doing.


问:
Splitting the unit segment into two parts recursively (2-D case)
Recently I have asked a question about how to generate a simple multifractal (Binomial Measure) in 1-D and I received a nice answer. Now, I would like to generate 2-D Binomial Measure but I have faced difficulties in implementing this.

A 1-D case can be generated as follows:

The binomial measure is a probability measure which is defined conveniently via a recursive construction. Start by splitting $ I := [0, 1] $ into two subintervals $ I_0 $ and $ I_1 $ of equal length and assign the masses $ m_0 $ and $ m_1 = 1 - m_0 $ to them. With the two subintervals one proceeds in the same manner and so forth: at stage two, e.g. the four subintervals $ I_{00}, I_{01}, I_{10}, I_{11} $ have masses $ m_0m_0, m_0m_1 m_1m_0 m_1m_1 $ respectively.

Rudolf H. Riedi. Introduction to Multifractals

Intuitively the generalization in 2-D seems easy. Instead of intervals on a unit segment, in 2-D we have a unit square, that recursively splits into four subsquares with masses m0, m1, m2, m3 given m0 + m1 + m2 + m3 = 1, then into 16 subintervals, 64, etc.

MWE (1-D case):

```<code>import matplotlib.pyplot as plt
from sympy import var

def binom_measuare(iterations, p=0.4, current_layer=None):

    var('m0 m1')

    if current_layer is None:
        current_layer = [1]

    next_layer = []

    for item in current_layer:
        next_layer.append(m0*item)
        next_layer.append(m1*item)

    if iterations != 0:
        return binom_measuare(iterations - 1, current_layer=next_layer)

    else:
        return [i.subs(m0, p).subs(m1, 1 - p) for i in next_layer]
</code>```

Let's plot the output

```<code>y = binom_measuare(iterations=12)
x = [(i+1) / len(y) for i in range(len(y))]

x = [0] + x
y = [0] + y

plt.plot(x, y)
</code>```

MWE for 2-D case:

```<code>def binom_measuare_2D(iterations, p1=0.4, p2=0.2, p3=0.3, p4=0.1, current_layer=None):

    var('mx0 mx1 my0 my1')

    if current_layer is None:
        current_layer = [1]

    next_layer = []

    for item in current_layer:
        next_layer.append(mx0*item)
        next_layer.append(mx1*item)
        next_layer.append(my0*item)
        next_layer.append(my1*item)

    if iterations != 0:
        return binom_measuare_2D(iterations-1, p1, p2, p3, p4, next_layer)

    else:
        return [i.subs(mx0, p1).subs(mx1, p2).subs(my0, p3).subs(my1, p4) for i in next_layer]
</code>```

And example of use:

```<code>import numpy as np

iterat = 1
z = binom_measuare_2D(iterations=iterat, p1=0.1, p2=0.2, p3=0.3, p4=0.4)
z = np.array(z)
z = z.reshape(2**(1 + iterat), 2**(1 + iterat))
print(z)
</code>```

It seems to have right values in the output but I have no idea how to assign values from the list for each coordinate x and y. It returns the values for subsquare, but not for the row of the general square so it can be easily visualized. Let me illustrate what I mean. Let (row index; col index) be the indices of the output array in the example provided above.

It fills according to this pattern:

However, I expect it to be filled like this one:

答:
In analogy to what I wrote in a previous answer I would suggest, rather than thinking in terms of splitting cells consider replacing each cell with four new cells, a kind of double mitosis. The values in the new cells can be calculated like this except that the result would be reshaped to form a 4x4 matrix. The next generation layer would be calculated from the current layer by iterating through the cells of the current layer and placing the 4x4 results into the next generation layer.

```<code>>>> from sympy import *
>>> var('m0 m1 m2 m3')
(m0, m1, m2, m3)
>>> def mitosis(aCell):
...     return ((m0**3, m0**2*m1, m0*m1**2, m1**3), (m0**2*m2, m0*m1*m2, m0*m1*m3, m1**2*m3), (m0*m2**2, m0*m2*m3, m1*m2*m3, m1*m3**2), (m0**3, m2**2*m3, m2*m3**2, m3**3))
...
>>> first = (m0,m1,m2,m3)
>>> mitosis(first)
((m0**3, m0**2*m1, m0*m1**2, m1**3), (m0**2*m2, m0*m1*m2, m0*m1*m3, m1**2*m3), (m0*m2**2, m0*m2*m3, m1*m2*m3, m1*m3**2), (m0**3, m2**2*m3, m2*m3**2, m3**3))
</code>```

Body:
Recently I have asked a question about how to generate a simple multifractal (Binomial Measure) in 1-D and I received a nice answer. Now, I would like to generate 2-D Binomial Measure but I have faced difficulties in implementing this.

A 1-D case can be generated as follows:

The binomial measure is a probability measure which is defined conveniently via a recursive construction. Start by splitting $ I := [0, 1] $ into two subintervals $ I_0 $ and $ I_1 $ of equal length and assign the masses $ m_0 $ and $ m_1 = 1 - m_0 $ to them. With the two subintervals one proceeds in the same manner and so forth: at stage two, e.g. the four subintervals $ I_{00}, I_{01}, I_{10}, I_{11} $ have masses $ m_0m_0, m_0m_1 m_1m_0 m_1m_1 $ respectively.

Rudolf H. Riedi. Introduction to Multifractals

Intuitively the generalization in 2-D seems easy. Instead of intervals on a unit segment, in 2-D we have a unit square, that recursively splits into four subsquares with masses m0, m1, m2, m3 given m0 + m1 + m2 + m3 = 1, then into 16 subintervals, 64, etc.

MWE (1-D case):

import matplotlib.pyplot as plt
from sympy import var

def binom_measuare(iterations, p=0.4, current_layer=None):

    var('m0 m1')

    if current_layer is None:
        current_layer = [1]

    next_layer = []

    for item in current_layer:
        next_layer.append(m0*item)
        next_layer.append(m1*item)

    if iterations != 0:
        return binom_measuare(iterations - 1, current_layer=next_layer)

    else:
        return [i.subs(m0, p).subs(m1, 1 - p) for i in next_layer]

Let's plot the output

y = binom_measuare(iterations=12)
x = [(i+1) / len(y) for i in range(len(y))]

x = [0] + x
y = [0] + y

plt.plot(x, y)

MWE for 2-D case:

def binom_measuare_2D(iterations, p1=0.4, p2=0.2, p3=0.3, p4=0.1, current_layer=None):

    var('mx0 mx1 my0 my1')

    if current_layer is None:
        current_layer = [1]

    next_layer = []

    for item in current_layer:
        next_layer.append(mx0*item)
        next_layer.append(mx1*item)
        next_layer.append(my0*item)
        next_layer.append(my1*item)

    if iterations != 0:
        return binom_measuare_2D(iterations-1, p1, p2, p3, p4, next_layer)

    else:
        return [i.subs(mx0, p1).subs(mx1, p2).subs(my0, p3).subs(my1, p4) for i in next_layer]

And example of use:

import numpy as np

iterat = 1
z = binom_measuare_2D(iterations=iterat, p1=0.1, p2=0.2, p3=0.3, p4=0.4)
z = np.array(z)
z = z.reshape(2**(1 + iterat), 2**(1 + iterat))
print(z)

It seems to have right values in the output but I have no idea how to assign values from the list for each coordinate x and y. It returns the values for subsquare, but not for the row of the general square so it can be easily visualized. Let me illustrate what I mean. Let (row index; col index) be the indices of the output array in the example provided above.

It fills according to this pattern:

However, I expect it to be filled like this one:

Body:
In analogy to what I wrote in a previous answer I would suggest, rather than thinking in terms of splitting cells consider replacing each cell with four new cells, a kind of double mitosis. The values in the new cells can be calculated like this except that the result would be reshaped to form a 4x4 matrix. The next generation layer would be calculated from the current layer by iterating through the cells of the current layer and placing the 4x4 results into the next generation layer.

>>> from sympy import *
>>> var('m0 m1 m2 m3')
(m0, m1, m2, m3)
>>> def mitosis(aCell):
...     return ((m0**3, m0**2*m1, m0*m1**2, m1**3), (m0**2*m2, m0*m1*m2, m0*m1*m3, m1**2*m3), (m0*m2**2, m0*m2*m3, m1*m2*m3, m1*m3**2), (m0**3, m2**2*m3, m2*m3**2, m3**3))
...
>>> first = (m0,m1,m2,m3)
>>> mitosis(first)
((m0**3, m0**2*m1, m0*m1**2, m1**3), (m0**2*m2, m0*m1*m2, m0*m1*m3, m1**2*m3), (m0*m2**2, m0*m2*m3, m1*m2*m3, m1*m3**2), (m0**3, m2**2*m3, m2*m3**2, m3**3))


问:
What is the type of the exception "Exception: Prelude.read: no parse"
I'm trying catch the exception that happens when the user writes something different from than expected.

I'm doing this:

```<code>main = do
    {catch (take_number) fix_error;}
    where
        take_number = do
        {
            take_number "Give me a number";
            n <- readLn;
        }
        fix_error e = if Exception e then do
            {
                putStrLn "Invalid number! Try again";
                main;
            }
            else ioError e
</code>```

I don't the exception type that I need catch in Execption

答:
The type of exception you get when doing readLn is IOError which is just an alias for IOException.

Here is how you could handle the error, I've added a type to readLn to enforce it to be read as an Int.

import           Control.Exception

main :: IO ()
main = catch takeNumber handleError

takeNumber :: IO ()
takeNumber = do
  putStrLn "Give me a number:"
  n <- readLn :: IO Int
  putStrLn ("Success, your number is: " ++ show n)

handleError :: IOError -> IO ()
handleError e = do
  putStrLn ("Invalid number! Try again. The error was: " ++ show e)
  main
```

Body:
I'm trying catch the exception that happens when the user writes something different from than expected.

I'm doing this:

main = do
    {catch (take_number) fix_error;}
    where
        take_number = do
        {
            take_number "Give me a number";
            n <- readLn;
        }
        fix_error e = if Exception e then do
            {
                putStrLn "Invalid number! Try again";
                main;
            }
            else ioError e

I don't the exception type that I need catch in Execption


问:
Java AWT 1.3 to Codename One
I want to know if it is at all possible to take an old java 1.3 application and wrap the java.awt components with the CodenameOne components. Is this possible?

The reason for this is a client... like always wants a rushed solution to use before we do a full rewrite.

Thanks

答:
Since the Codename One API is similar to AWT/Swing, it probably wouldn't be that hard to just change a few imports, and then touch up as necessary where the API differs.  Of course some concepts are very different between desktop and mobile (e.g. multiple windows, menus, etc..) so those might be harder to massage.

E.g.  You would change java.awt.Label to com.codename1.ui.Label, and java.awt.Button to com.codename1.ui.Button, etc...

This article, wrtitten by a member of the Codename One community, describes the process he used to port a fairly complex set of AWT/Swing Apps into Codename One.  You might find it helpful.

Title: Java AWT 1.3 to Codename One


问:
How can I format a cell into a number within a Google Query?
I have a cell that is formatted as Time. However when I use that cell within a query and try to use an aggregator on it, it will tell me it can't be done because it's not a number. When I manually format the cell as a number it has no problems. Is there a way to tell the Google Query that it can use that column as a number?</p>

答:
I have run into this before. I am not sure exactly what you are trying to do, but I can share on solution I have used to aggregate time. Maybe it will give you an idea. Break the time into hrs, min, and sec and then those can be aggregated. Like this:</p>

```<code>=query(query(A2:B8,"select hour(A), minute(A),second(A)"),"select sum(Col1),sum(Col2),sum(Col3)")
</code>```

Body:
I have run into this before. I am not sure exactly what you are trying to do, but I can share on solution I have used to aggregate time. Maybe it will give you an idea. Break the time into hrs, min, and sec and then those can be aggregated. Like this:

=query(query(A2:B8,"select hour(A), minute(A),second(A)"),"select sum(Col1),sum(Col2),sum(Col3)")


问:
tensorflow import error in python 2.7.6
I have installed tensor flow from tensorflow website. While trying to import tensor flow its showing following error

```<code>>>>import tensorflow as tf
</code>```

```<code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/tensorflow/__init__.py", line  24, in <module>
from tensorflow.python import *
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/__init__.py", line 75, in <module>
from tensorflow.core.framework.graph_pb2 import *
File "/usr/local/lib/python2.7/dist-packages/tensorflow/core/framework/graph_pb2.py", line 6, in <module>
from google.protobuf import descriptor as _descriptor
File "/usr/local/lib/python2.7/dist-packages/google/protobuf/__init__.py",   line 37, in <module>
__import__('pkg_resources').declare_namespace(__name__)
File "/usr/local/lib/python2.7/dist-packages/pkg_resources/__init__.py",   line 36, in <module>
import email.parser
File "/usr/lib/python2.7/email/parser.py", line 12, in <module>
from email.feedparser import FeedParser
File "/usr/lib/python2.7/email/feedparser.py", line 27, in <module>
from email import message
File "/usr/lib/python2.7/email/message.py", line 16, in <module>
import email.charset
File "/usr/lib/python2.7/email/charset.py", line 13, in <module>
import email.base64mime
File "/usr/lib/python2.7/email/base64mime.py", line 40, in <module>
from email.utils import fix_eols
File "/usr/lib/python2.7/email/utils.py", line 28, in <module>
import socket
File "/home/tamarind/socket.py", line 5, in <module>
This module provides socket operations and some related functions.
TypeError: 'module' object is not callable
</code>```

I think its problem with socket please suggest. Please suggest.

答: It looks like /home/tamarind/socket.py is taking precedence over the python socket module. Just rename/remove that (or import TensorFlow from a different directory) and it should work. You may need to remove socket.pyc too.

Title: tensorflow import error in python 2.7.6

Body:
I have installed tensor flow from tensorflow website. While trying to import tensor flow its showing following error

>>>import tensorflow as tf

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/tensorflow/__init__.py", line  24, in <module>
from tensorflow.python import *
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/__init__.py", line 75, in <module>
from tensorflow.core.framework.graph_pb2 import *
File "/usr/local/lib/python2.7/dist-packages/tensorflow/core/framework/graph_pb2.py", line 6, in <module>
from google.protobuf import descriptor as _descriptor
File "/usr/local/lib/python2.7/dist-packages/google/protobuf/__init__.py",   line 37, in <module>
__import__('pkg_resources').declare_namespace(__name__)
File "/usr/local/lib/python2.7/dist-packages/pkg_resources/__init__.py",   line 36, in <module>
import email.parser
File "/usr/lib/python2.7/email/parser.py", line 12, in <module>
from email.feedparser import FeedParser
File "/usr/lib/python2.7/email/feedparser.py", line 27, in <module>
from email import message
File "/usr/lib/python2.7/email/message.py", line 16, in <module>
import email.charset
File "/usr/lib/python2.7/email/charset.py", line 13, in <module>
import email.base64mime
File "/usr/lib/python2.7/email/base64mime.py", line 40, in <module>
from email.utils import fix_eols
File "/usr/lib/python2.7/email/utils.py", line 28, in <module>
import socket
File "/home/tamarind/socket.py", line 5, in <module>
This module provides socket operations and some related functions.
TypeError: 'module' object is not callable

I think its problem with socket please suggest. Please suggest.