问:
I have 28 errors, this is my first program, h elp out if you can
I'm trying to make some sort of a primitive form on what I'd optimize to be an interactive BMI calculator I guess.
So this is my code.

CODE:

import java.util.Scanner;

class bmi{

public static void main(String args[]) {

```<code>Scanner userinput = new Scanner(System.in);

double weight, height, bmi;
String sex;

System.out.println("Hello there!");

System.out.println("I am your Body-Mass index calculator!");

System.out.println("Would you please be so kind and tell me your weight? In kilograms if possible, I'm from Europe xD.");
weight = userinput.nextDouble();

System.out.println("Alrighty, now tell me, how tall are you? In meters this time.");
height = userinput.nextDouble();

System.out.println("Finally, can you tell me wether you are a boy or a girl, if that isn't too intrusive... *wink*");
sex = userinput.nextLine();

bmi = weight / (height * height);

if (sex = "boy")  {
    System.out.println("Thank you for providing me this information, bro!");
    System.out.println("                                    ");
    System.out.println("Hmm, it looks like your results came...");
}
else {
    System.out.println("Thanks for the indormation, sys! ;)");
    System.out.println("                                    ");
    System.out.println("Hmm, it looks like your results came...");
}

   System.out.println("                                           ");

   if (bmi <= 18.5 && sex = "boy")  {
       System.out.println("Looking just at your height and weight, I can tell you are a skinny guy, in fact the data (your BMI is "bmi") shows that you are underweight. You might consider gaining some wight, it would be best for your health.");

   }
   else if (bmi <= 25 && sex = "boy")  {
       System.out.println("Damn son, you're looking good (in numbers xD)! With a BMI of "bmi", you are just about average, nothing to worry about here!);

   }
   else if (bmi <= 18.5 && sex = "girl")  {
       System.out.println("Looking at the numbers you gave me, it seems that you are underweight :/, in fact with a bmi of "bmi",your weight is below that of an average girl. Not having considered your age, there is no way I can tell you wether the condition is critical or not, but you should really consider gaining some weight.");

   }
   else if (bmi <= 25 && sex = "girl")  {
       System.out.println("Damn giiiirl, you rock! Having a BMI of "bmi", you are an ideal specimen of a healthy female figure. Keep it up!);

   }
   else if (bmi > 25 && sex = "girl")  {
       System.out.println("First of all, let me say it's not critical, but with a BMI of "bmi", you are considered overweight, try working out or going for a run from time to time, it sure will help your health.);

   }
   else if (bmi > 25 && sex = "boy")  {
       System.out.println("First of all, let me say it's not critical, but with a BMI of "bmi", you are considered overweight, try working out or going for a run from time to time, it sure will help your health.);

   }
   else if (bmi > 30) then {
       System.out.println("I am so sorry to be the one to inform you, but with a BMI of "bmi",you are consiered obese by the National Health Orgnaization, at this point, your weight might be seriously affecting your health, and I strongly suggest you to take on a diet, start working out or if the case is extreme, seek professional help. Do it for yourself, I believe in you! <3");
   }

   System.out.println("                                           ");
   System.out.println("Thank you for letting me help!");
</code>```

}

}

OK, and now here is the report:

javac JavaTutorial.java

JavaTutorial.java:39: error: ')' expected

```<code>       System.out.println("Looking just at your height and weight, I can tell you are a skinny guy, in fact the data (your BMI is "bmi") shows that you are underweight. You might consider gaining some wight, it would be best for your health.");

                                                                                ^
</code>```

JavaTutorial.java:39: error: not a statement

```<code>       System.out.println("Looking just at your height and weight, I can tell you are a skinny guy, in fact the data (your BMI is "bmi") shows that you are underweight. You might consider gaining some wight, it would be best for your health.");

                                                                                ^
</code>```

JavaTutorial.java:39: error: ';' expected

```<code>       System.out.println("Looking just at your height and weight, I can tell you are a skinny guy, in fact the data (your BMI is "bmi") shows that you are underweight. You might consider gaining some wight, it would be best for your health.");

                                                                                ^
</code>```

JavaTutorial.java:43: error: ')' expected

```<code>       System.out.println("Damn son, you're looking good (in numbers xD)! With a BMI of "bmi", you are just about average, nothing to worry about here!);

                                                        ^
</code>```

JavaTutorial.java:43: error: unclosed string literal

```<code>       System.out.println("Damn son, you're looking good (in numbers xD)! With a BMI of "bmi", you are just about average, nothing to worry about here!);

                                                                                ^
</code>```

JavaTutorial.java:43: error: ';' expected

System.out.println("Damn son, you're looking good (in numbers xD)! With a BMI of "bmi", you are just about average, nothing to worry about here!);

```<code>                                                                                ^
</code>```

JavaTutorial.java:47: error: ')' expected

System.out.println("Looking at the numbers you gave me, it seems that you are underweight :/, in fact with a bmi of "bmi",your weight is below that of an average girl. Not having considered your age, there is no way I can tell you wether the condition is critical or not, but you should really consider gaining some weight.");

```<code>                                                                                ^
</code>```

JavaTutorial.java:47: error: not a statement

System.out.println("Looking at the numbers you gave me, it seems that you are underweight :/, in fact with a bmi of "bmi",your weight is below that of an average girl. Not having considered your age, there is no way I can tell you wether the condition is critical or not, but you should really consider gaining some weight.");

```<code>                                                                                ^
</code>```

JavaTutorial.java:47: error: ';' expected

System.out.println("Looking at the numbers you gave me, it seems that you are underweight :/, in fact with a bmi of "bmi",your weight is below that of an average girl. Not having considered your age, there is no way I can tell you wether the condition is critical or not, but you should really consider gaining some weight.");

```<code>                                                                                ^
</code>```

JavaTutorial.java:51: error: ')' expected

System.out.println("Damn giiiirl, you rock! Having a BMI of "bmi", you are an ideal specimen of a healthy female figure. Keep it up!);

```<code>                                                                    ^
</code>```

JavaTutorial.java:51: error: unclosed string literal

System.out.println("Damn giiiirl, you rock! Having a BMI of "bmi", you are an ideal specimen of a healthy female figure. Keep it up!);
                                                                           ^
JavaTutorial.java:51: error: ';' expected

System.out.println("Damn giiiirl, you rock! Having a BMI of "bmi", you are an ideal specimen of a healthy female figure. Keep it up!);
                                                                                ^
JavaTutorial.java:55: error: ')' expected

System.out.println("First of all, let me say it's not critical, but with a BMI of "bmi", you are considered overweight, try working out or going for a run from time to time, it sure will help your health.);

```<code>                                                                                ^
</code>```

JavaTutorial.java:55: error: unclosed string literal

System.out.println("First of all, let me say it's not critical, but with a BMI of "bmi", you are considered overweight, try working out or going for a run from time to time, it sure will help your health.);
                                                                                ^
JavaTutorial.java:55: error: ';' expected

System.out.println("First of all, let me say it's not critical, but with a BMI of "bmi", you are considered overweight, try working out or going for a run from time to time, it sure will help your health.);
                                                                                ^
JavaTutorial.java:59: error: ')' expected

System.out.println("First of all, let me say it's not critical, but with a BMI of "bmi", you are considered overweight, try working out or going for a run from time to time, it sure will help your health.);
                                                                                ^
JavaTutorial.java:59: error: unclosed string literal

System.out.println("First of all, let me say it's not critical, but with a BMI of "bmi", you are considered overweight, try working out or going for a run from time to time, it sure will help your health.);
                                                                                ^
JavaTutorial.java:59: error: ';' expected

System.out.println("First of all, let me say it's not critical, but with a BMI of "bmi", you are considered overweight, try working out or going for a run from time to time, it sure will help your health.);

```<code>                                                                                ^
</code>```

JavaTutorial.java:62: error: not a statement

```<code>   else if (bmi > 30) then {

                      ^
</code>```

JavaTutorial.java:62: error: ';' expected

else if (bmi > 30) then {
                              ^
JavaTutorial.java:62: error: 'else' without 'if'

else if (bmi > 30) then {
       ^

JavaTutorial.java:63: error: ')' expected

System.out.println("I am so sorry to be the one to inform you, but with a BMI of "bmi",you are consiered obese by the National Health Orgnaization, at this point, your weight might be seriously affecting your health, and I strongly suggest you to take on a diet, start working out or if the case is extreme, seek professional help. Do it for yourself, I believe in you! <3");
                                                                                ^
JavaTutorial.java:63: error: not a statement

System.out.println("I am so sorry to be the one to inform you, but with a BMI of "bmi",you are consiered obese by the National Health Orgnaization, at this point, your weight might be seriously affecting your health, and I strongly suggest you to take on a diet, start working out or if the case is extreme, seek professional help. Do it for yourself, I believe in you! <3");

```<code>                                                                                ^
</code>```

JavaTutorial.java:63: error: ';' expected

System.out.println("I am so sorry to be the one to inform you, but with a BMI of "bmi",you are consiered obese by the National Health Orgnaization, at this point, your weight might be seriously affecting your health, and I strongly suggest you to take on a diet, start working out or if the case is extreme, seek professional help. Do it for yourself, I believe in you! <3");
                                                                                ^
JavaTutorial.java:58: error: 'else' without 'if'

```<code>   else if (bmi > 25 && sex = "boy")  {

   ^
</code>```

JavaTutorial.java:54: error: 'else' without 'if'

```<code>   else if (bmi > 25 && sex = "girl")  {

   ^
</code>```

JavaTutorial.java:46: error: reached end of file while parsing

```<code>   else if (bmi <= 18.5 && sex = "girl")  {

   ^
</code>```

JavaTutorial.java:72: error: reached end of file while parsing

}

^

28 errors

答:
I fixed it for you. There were several mistakes.

if comparisons always need two equal signs like this: if(a == b){...}

There is no then in if clauses in java

Always comare Strings with the String.equals method. A String is saved as an object in java. Comparing two objects with == never returns true, unless they are two variables pointing at the same instance. In this case you are comparing the content of an object, which is why you should use string1.equals(string2)

Idk why, but scanner.nextLine() didn't work, but scanner.next() did. Since you are asking for a single word, this shouldn't cause any problems. I'm not too familiar with scanner but it worked for me ;)

when trying to insert a variable into a String you need to use plus signs like this: "something written here " + someVariable + "something written over there".

Here is the fixed code:

```<code>    public static void main(String[] args) {

        Scanner userinput = new Scanner(System.in);

        double weight, height, bmi;
        String sex;

        System.out.println("Hello there!");

        System.out.println("I am your Body-Mass index calculator!");

        System.out.println(
            "Would you please be so kind and tell me your weight? In kilograms if possible, I'm from Europe xD.");
        weight = userinput.nextDouble();

        System.out.println("Alrighty, now tell me, how tall are you? In meters this time.");
        height = userinput.nextDouble();

        System.out.println(
            "Finally, can you tell me wether you are a boy or a girl, if that isn't too intrusive... *wink*");
        sex = userinput.nextLine();

        bmi = weight / (height * height);
        if ( sex.equals("boy")) {
            System.out.println("Thank you for providing me this information, bro!");
            System.out.println("                                    ");
            System.out.println("Hmm, it looks like your results came...");
        } else {
            System.out.println("Thanks for the information, sys! ;)");
            System.out.println("                                    ");
            System.out.println("Hmm, it looks like your results came...");
        }

        System.out.println("                                           ");

        if (bmi <= 18.5 && sex.equals("boy")) {
            System.out.println(
                "Looking just at your height and weight, I can tell you are a skinny guy, in fact the data (your BMI is "
                + bmi
                + ") shows that you are underweight. You might consider gaining some wight, it would be best for your health.");

        } else if (bmi <= 25 && sex.equals("boy")) {
            System.out.println("Damn son, you're looking good (in numbers xD)! With a BMI of " + bmi
                + ", you are just about average, nothing to worry about here!");

        } else if (bmi <= 18.5 && sex.equals("girl")) {
            System.out.println(
                "Looking at the numbers you gave me, it seems that you are underweight :/, in fact with a bmi of "
                + bmi
                + ",your weight is below that of an average girl. Not having considered your age, there is no way I can tell you wether the condition is critical or not, but you should really consider gaining some weight.");

        } else if (bmi <= 25 && sex.equals("girl")) {
            System.out.println("Damn giiiirl, you rock! Having a BMI of " + bmi
                + ", you are an ideal specimen of a healthy female figure. Keep it up!");

        } else if (bmi > 25 && sex.equals("girl")) {
            System.out.println("First of all, let me say it's not critical, but with a BMI of " + bmi
                + ", you are considered overweight, try working out or going for a run from time to time, it sure will help your health.");

        } else if (bmi > 25 && sex.equals("boy")) {
            System.out.println("First of all, let me say it's not critical, but with a BMI of " + bmi
                + ", you are considered overweight, try working out or going for a run from time to time, it sure will help your health.");

        } else if (bmi > 30) {
            System.out.println("I am so sorry to be the one to inform you, but with a BMI of " + bmi
                + ",you are consiered obese by the National Health Orgnaization, at this point, your weight might be seriously affecting your health, and I strongly suggest you to take on a diet, start working out or if the case is extreme, seek professional help. Do it for yourself, I believe in you! <3");
        }

        System.out.println("                                           ");
        System.out.println("Thank you for letting me help!");

    }
</code>```

Body:
I'm trying to make some sort of a primitive form on what I'd optimize to be an interactive BMI calculator I guess.
So this is my code.

CODE:

import java.util.Scanner;

class bmi{

public static void main(String args[]) {

Scanner userinput = new Scanner(System.in);

double weight, height, bmi;
String sex;

System.out.println("Hello there!");

System.out.println("I am your Body-Mass index calculator!");

System.out.println("Would you please be so kind and tell me your weight? In kilograms if possible, I'm from Europe xD.");
weight = userinput.nextDouble();

System.out.println("Alrighty, now tell me, how tall are you? In meters this time.");
height = userinput.nextDouble();

System.out.println("Finally, can you tell me wether you are a boy or a girl, if that isn't too intrusive... *wink*");
sex = userinput.nextLine();

bmi = weight / (height * height);

if (sex = "boy")  {
    System.out.println("Thank you for providing me this information, bro!");
    System.out.println("                                    ");
    System.out.println("Hmm, it looks like your results came...");
}
else {
    System.out.println("Thanks for the indormation, sys! ;)");
    System.out.println("                                    ");
    System.out.println("Hmm, it looks like your results came...");
}

   System.out.println("                                           ");

   if (bmi <= 18.5 && sex = "boy")  {
       System.out.println("Looking just at your height and weight, I can tell you are a skinny guy, in fact the data (your BMI is "bmi") shows that you are underweight. You might consider gaining some wight, it would be best for your health.");

   }
   else if (bmi <= 25 && sex = "boy")  {
       System.out.println("Damn son, you're looking good (in numbers xD)! With a BMI of "bmi", you are just about average, nothing to worry about here!);

   }
   else if (bmi <= 18.5 && sex = "girl")  {
       System.out.println("Looking at the numbers you gave me, it seems that you are underweight :/, in fact with a bmi of "bmi",your weight is below that of an average girl. Not having considered your age, there is no way I can tell you wether the condition is critical or not, but you should really consider gaining some weight.");

   }
   else if (bmi <= 25 && sex = "girl")  {
       System.out.println("Damn giiiirl, you rock! Having a BMI of "bmi", you are an ideal specimen of a healthy female figure. Keep it up!);

   }
   else if (bmi > 25 && sex = "girl")  {
       System.out.println("First of all, let me say it's not critical, but with a BMI of "bmi", you are considered overweight, try working out or going for a run from time to time, it sure will help your health.);

   }
   else if (bmi > 25 && sex = "boy")  {
       System.out.println("First of all, let me say it's not critical, but with a BMI of "bmi", you are considered overweight, try working out or going for a run from time to time, it sure will help your health.);

   }
   else if (bmi > 30) then {
       System.out.println("I am so sorry to be the one to inform you, but with a BMI of "bmi",you are consiered obese by the National Health Orgnaization, at this point, your weight might be seriously affecting your health, and I strongly suggest you to take on a diet, start working out or if the case is extreme, seek professional help. Do it for yourself, I believe in you! <3");
   }

   System.out.println("                                           ");
   System.out.println("Thank you for letting me help!");

}

}

OK, and now here is the report:

javac JavaTutorial.java

JavaTutorial.java:39: error: ')' expected

       System.out.println("Looking just at your height and weight, I can tell you are a skinny guy, in fact the data (your BMI is "bmi") shows that you are underweight. You might consider gaining some wight, it would be best for your health.");

                                                                                ^

JavaTutorial.java:39: error: not a statement

       System.out.println("Looking just at your height and weight, I can tell you are a skinny guy, in fact the data (your BMI is "bmi") shows that you are underweight. You might consider gaining some wight, it would be best for your health.");

                                                                                ^

JavaTutorial.java:39: error: ';' expected

       System.out.println("Looking just at your height and weight, I can tell you are a skinny guy, in fact the data (your BMI is "bmi") shows that you are underweight. You might consider gaining some wight, it would be best for your health.");

                                                                                ^

JavaTutorial.java:43: error: ')' expected

       System.out.println("Damn son, you're looking good (in numbers xD)! With a BMI of "bmi", you are just about average, nothing to worry about here!);

                                                        ^

JavaTutorial.java:43: error: unclosed string literal

       System.out.println("Damn son, you're looking good (in numbers xD)! With a BMI of "bmi", you are just about average, nothing to worry about here!);

                                                                                ^

JavaTutorial.java:43: error: ';' expected

System.out.println("Damn son, you're looking good (in numbers xD)! With a BMI of "bmi", you are just about average, nothing to worry about here!);

                                                                                ^

JavaTutorial.java:47: error: ')' expected

System.out.println("Looking at the numbers you gave me, it seems that you are underweight :/, in fact with a bmi of "bmi",your weight is below that of an average girl. Not having considered your age, there is no way I can tell you wether the condition is critical or not, but you should really consider gaining some weight.");

                                                                                ^

JavaTutorial.java:47: error: not a statement

System.out.println("Looking at the numbers you gave me, it seems that you are underweight :/, in fact with a bmi of "bmi",your weight is below that of an average girl. Not having considered your age, there is no way I can tell you wether the condition is critical or not, but you should really consider gaining some weight.");

                                                                                ^

JavaTutorial.java:47: error: ';' expected

System.out.println("Looking at the numbers you gave me, it seems that you are underweight :/, in fact with a bmi of "bmi",your weight is below that of an average girl. Not having considered your age, there is no way I can tell you wether the condition is critical or not, but you should really consider gaining some weight.");

                                                                                ^

JavaTutorial.java:51: error: ')' expected

System.out.println("Damn giiiirl, you rock! Having a BMI of "bmi", you are an ideal specimen of a healthy female figure. Keep it up!);

                                                                    ^

JavaTutorial.java:51: error: unclosed string literal

System.out.println("Damn giiiirl, you rock! Having a BMI of "bmi", you are an ideal specimen of a healthy female figure. Keep it up!);
                                                                           ^
JavaTutorial.java:51: error: ';' expected

System.out.println("Damn giiiirl, you rock! Having a BMI of "bmi", you are an ideal specimen of a healthy female figure. Keep it up!);
                                                                                ^
JavaTutorial.java:55: error: ')' expected

System.out.println("First of all, let me say it's not critical, but with a BMI of "bmi", you are considered overweight, try working out or going for a run from time to time, it sure will help your health.);

                                                                                ^

JavaTutorial.java:55: error: unclosed string literal

System.out.println("First of all, let me say it's not critical, but with a BMI of "bmi", you are considered overweight, try working out or going for a run from time to time, it sure will help your health.);
                                                                                ^
JavaTutorial.java:55: error: ';' expected

System.out.println("First of all, let me say it's not critical, but with a BMI of "bmi", you are considered overweight, try working out or going for a run from time to time, it sure will help your health.);
                                                                                ^
JavaTutorial.java:59: error: ')' expected

System.out.println("First of all, let me say it's not critical, but with a BMI of "bmi", you are considered overweight, try working out or going for a run from time to time, it sure will help your health.);
                                                                                ^
JavaTutorial.java:59: error: unclosed string literal

System.out.println("First of all, let me say it's not critical, but with a BMI of "bmi", you are considered overweight, try working out or going for a run from time to time, it sure will help your health.);
                                                                                ^
JavaTutorial.java:59: error: ';' expected

System.out.println("First of all, let me say it's not critical, but with a BMI of "bmi", you are considered overweight, try working out or going for a run from time to time, it sure will help your health.);

                                                                                ^

JavaTutorial.java:62: error: not a statement

   else if (bmi > 30) then {

                      ^

JavaTutorial.java:62: error: ';' expected

else if (bmi > 30) then {
                              ^
JavaTutorial.java:62: error: 'else' without 'if'

else if (bmi > 30) then {
       ^

JavaTutorial.java:63: error: ')' expected

System.out.println("I am so sorry to be the one to inform you, but with a BMI of "bmi",you are consiered obese by the National Health Orgnaization, at this point, your weight might be seriously affecting your health, and I strongly suggest you to take on a diet, start working out or if the case is extreme, seek professional help. Do it for yourself, I believe in you! <3");
                                                                                ^
JavaTutorial.java:63: error: not a statement

System.out.println("I am so sorry to be the one to inform you, but with a BMI of "bmi",you are consiered obese by the National Health Orgnaization, at this point, your weight might be seriously affecting your health, and I strongly suggest you to take on a diet, start working out or if the case is extreme, seek professional help. Do it for yourself, I believe in you! <3");

                                                                                ^

JavaTutorial.java:63: error: ';' expected

System.out.println("I am so sorry to be the one to inform you, but with a BMI of "bmi",you are consiered obese by the National Health Orgnaization, at this point, your weight might be seriously affecting your health, and I strongly suggest you to take on a diet, start working out or if the case is extreme, seek professional help. Do it for yourself, I believe in you! <3");
                                                                                ^
JavaTutorial.java:58: error: 'else' without 'if'

   else if (bmi > 25 && sex = "boy")  {

   ^

JavaTutorial.java:54: error: 'else' without 'if'

   else if (bmi > 25 && sex = "girl")  {

   ^

JavaTutorial.java:46: error: reached end of file while parsing

   else if (bmi <= 18.5 && sex = "girl")  {

   ^

JavaTutorial.java:72: error: reached end of file while parsing

}

^

28 errors

Body:
I fixed it for you. There were several mistakes.

if comparisons always need two equal signs like this: if(a == b){...}

There is no then in if clauses in java

Always comare Strings with the String.equals method. A String is saved as an object in java. Comparing two objects with == never returns true, unless they are two variables pointing at the same instance. In this case you are comparing the content of an object, which is why you should use string1.equals(string2)

Idk why, but scanner.nextLine() didn't work, but scanner.next() did. Since you are asking for a single word, this shouldn't cause any problems. I'm not too familiar with scanner but it worked for me ;)

when trying to insert a variable into a String you need to use plus signs like this: "something written here " + someVariable + "something written over there".

Here is the fixed code:

    public static void main(String[] args) {

        Scanner userinput = new Scanner(System.in);

        double weight, height, bmi;
        String sex;

        System.out.println("Hello there!");

        System.out.println("I am your Body-Mass index calculator!");

        System.out.println(
            "Would you please be so kind and tell me your weight? In kilograms if possible, I'm from Europe xD.");
        weight = userinput.nextDouble();

        System.out.println("Alrighty, now tell me, how tall are you? In meters this time.");
        height = userinput.nextDouble();

        System.out.println(
            "Finally, can you tell me wether you are a boy or a girl, if that isn't too intrusive... *wink*");
        sex = userinput.nextLine();

        bmi = weight / (height * height);
        if ( sex.equals("boy")) {
            System.out.println("Thank you for providing me this information, bro!");
            System.out.println("                                    ");
            System.out.println("Hmm, it looks like your results came...");
        } else {
            System.out.println("Thanks for the information, sys! ;)");
            System.out.println("                                    ");
            System.out.println("Hmm, it looks like your results came...");
        }

        System.out.println("                                           ");

        if (bmi <= 18.5 && sex.equals("boy")) {
            System.out.println(
                "Looking just at your height and weight, I can tell you are a skinny guy, in fact the data (your BMI is "
                + bmi
                + ") shows that you are underweight. You might consider gaining some wight, it would be best for your health.");

        } else if (bmi <= 25 && sex.equals("boy")) {
            System.out.println("Damn son, you're looking good (in numbers xD)! With a BMI of " + bmi
                + ", you are just about average, nothing to worry about here!");

        } else if (bmi <= 18.5 && sex.equals("girl")) {
            System.out.println(
                "Looking at the numbers you gave me, it seems that you are underweight :/, in fact with a bmi of "
                + bmi
                + ",your weight is below that of an average girl. Not having considered your age, there is no way I can tell you wether the condition is critical or not, but you should really consider gaining some weight.");

        } else if (bmi <= 25 && sex.equals("girl")) {
            System.out.println("Damn giiiirl, you rock! Having a BMI of " + bmi
                + ", you are an ideal specimen of a healthy female figure. Keep it up!");

        } else if (bmi > 25 && sex.equals("girl")) {
            System.out.println("First of all, let me say it's not critical, but with a BMI of " + bmi
                + ", you are considered overweight, try working out or going for a run from time to time, it sure will help your health.");

        } else if (bmi > 25 && sex.equals("boy")) {
            System.out.println("First of all, let me say it's not critical, but with a BMI of " + bmi
                + ", you are considered overweight, try working out or going for a run from time to time, it sure will help your health.");

        } else if (bmi > 30) {
            System.out.println("I am so sorry to be the one to inform you, but with a BMI of " + bmi
                + ",you are consiered obese by the National Health Orgnaization, at this point, your weight might be seriously affecting your health, and I strongly suggest you to take on a diet, start working out or if the case is extreme, seek professional help. Do it for yourself, I believe in you! <3");
        }

        System.out.println("                                           ");
        System.out.println("Thank you for letting me help!");

    }


来源: stackexchange

问:
Display pixel-perfect canvas on all devices
I have some canvases that I want to be displayed pixel-perfect in every (modern) browser. By default, devices with high-DPI screens are scaling my page so that everything looks the right size, but it's breaking* the appearance of my canvases.

How can I ensure that one pixel in my canvas = one pixel on the screen? Preferably this wouldn't affect other elements on the page, since I still want e.g. text to be scaled appropriately for the device.

I already tried styling the canvas dimensions based on window.devicePixelRatio. That makes the canvases the right size but the contents look even worse. I'm guessing that just scales them down after they're already scaled up incorrectly.

*If you care, because the canvases use dithering and the browsers are doing some kind of lerp rather than nearest-neighbor

答:
The simplest approximation is this:

```<code>canvas {
    image-rendering: pixelated;
    image-rendering: crisp-edges;
}
</code>```

Browser support isn't great. I've tested this with Chrome, Firefox, and Safari on Windows, Mac, Linux, iOS, and Android: it gives you a canvas made up of individually controllable squares, which will correspond to pixels if the canvas is not zoomed in and the device has an integer display scale factor.

This has no effect on normal DPI devices as long as your canvases are being displayed at their normal size. Also, depending on the screen, you get interesting artifacts on high DPI devices, but I think that's unavoidable due to how those displays work. They're still better than the artifacts you get without the style.

I also tried upscaling all of my canvases 200% with nearest-neighbor in javascript and then setting them as background images of normal-sized divs. This is how Apple recommends displaying images for retina devices, so I thought it would give a great result. But you still end up with artifacts and they aren't fixed by zooming in the page so it's actually worse that the simple solution above.

ContentLicense: CC BY-SA 3.0

Body:
The simplest approximation is this:

canvas {
    image-rendering: pixelated;
    image-rendering: crisp-edges;
}

Browser support isn't great. I've tested this with Chrome, Firefox, and Safari on Windows, Mac, Linux, iOS, and Android: it gives you a canvas made up of individually controllable squares, which will correspond to pixels if the canvas is not zoomed in and the device has an integer display scale factor.

This has no effect on normal DPI devices as long as your canvases are being displayed at their normal size. Also, depending on the screen, you get interesting artifacts on high DPI devices, but I think that's unavoidable due to how those displays work. They're still better than the artifacts you get without the style.

I also tried upscaling all of my canvases 200% with nearest-neighbor in javascript and then setting them as background images of normal-sized divs. This is how Apple recommends displaying images for retina devices, so I thought it would give a great result. But you still end up with artifacts and they aren't fixed by zooming in the page so it's actually worse that the simple solution above.

ContentLicense: CC BY-SA 4.0


问:
AWS API Gateway make single endpoint publicly available
I have successfully set up multiple API Gateways on AWS and they work perfectly with client API Keys.

Is it possible to make a specific endpoint in an API publicly available, but all other endpoints protected with the client API key required?

答:
You can use AWS CloudFront to forward the request to API Gateway for the public endpoint and define the Client API Key in CloudFront headers forwarded to the Origin.

Note: When including API Gateway as a origin to CloudFront you need to do the following.

Whitelist header (Except Host Header)

Make HTTPS only

Make TTL values 0


问:
awk split question
I wrote a small script, using awk 'split' command to get the current directory name.

echo $PWD

I need to replace '8' with the number of tokens as a result of the split operation.
// If PWD = /home/username/bin. I am trying to get "bin" into package.

```<code>package="`echo $PWD | awk '{split($0,a,"/"); print a[8] }'`"
echo $package
</code>```

Can you please tell me what do I substitute in place of 'print a[8]'  to get the script working for any directory path ?

-Sachin

答:
The other answers are better replacements to perform the function you're trying to accomplish. However, here is the specific answer to your question:

```<code>package=$(echo $PWD | awk '{n = split($0,a,"/"); print a[n] }')
echo "$package"
</code>```

split() returns the number of resulting elements.

ContentLicense: CC BY-SA 2.5

Title: awk split question

Body:
I wrote a small script, using awk 'split' command to get the current directory name.

echo $PWD

I need to replace '8' with the number of tokens as a result of the split operation.
// If PWD = /home/username/bin. I am trying to get "bin" into package.

package="`echo $PWD | awk '{split($0,a,"/"); print a[8] }'`"
echo $package

Can you please tell me what do I substitute in place of 'print a[8]'  to get the script working for any directory path ?

-Sachin

Body:
The other answers are better replacements to perform the function you're trying to accomplish. However, here is the specific answer to your question:

package=$(echo $PWD | awk '{n = split($0,a,"/"); print a[n] }')
echo "$package"

split() returns the number of resulting elements.


问:
jQuery toggle function doesn't work on first click
i want to create a simple toggle function which toggles a div show() or hide() with a cookie to remember in which state the div is. So far so good. Well, it works kind of. When i toggle the div hide() it hides, but when i reload the page an want to toggle the div show() i have to click the button twice ! I've read the anwers here in but they didn't help. Also i've tried to make it with a click function but that doesn't work at all.

Here ist the code:

```<code>  jQuery().ready(function () {

        var footeroff = jQuery.cookie('footeroff');
        var toggle_footer = jQuery(".toggle_footer_switch");

        if (footeroff == "off") {
        jQuery("div#footer").hide();
        jQuery("div#wkfooter_switch").hide();
        toggle_footer.html("<img src='../images/other/zuklappen.png' border='0'>");
        };

        if (footeroff == "on") {
        jQuery("div#footer").show();
        jQuery("div#wkfooter_switch").show();
        toggle_footer.html("<img src='../images/other/aufklappen.png' border='0'>");
        };

        var footer_switch = jQuery("div#footer");
        var toggle_footer = jQuery(".toggle_footer_switch");
        var toggle_switch_div = jQuery("div#toggle_switch_div");

        jQuery("a.toggle_footer_switch").toggle(
            function () {
                toggle_footer.html("<img src='../images/other/zuklappen.png' border='0'>");
                jQuery("div#footer").fadeOut("slow");
                jQuery("div#wkfooter_switch").hide();
                jQuery.cookie("footeroff" , "off");
            },
            function () {
                toggle_footer.html("<img src='../images/other/aufklappen.png' border='0'>");
                jQuery("div#footer").fadeIn("slow");
                jQuery("div#wkfooter_switch").show();
                jQuery.cookie("footeroff" , "on");
            }
        );

    });
</code>```

And there is the code with a click function:

```<code>      jQuery().ready(function () {

        var footeroff = jQuery.cookie('footeroff');
        var toggle_footer = jQuery(".toggle_footer_switch");

        if (footeroff == "off") {
        jQuery("div#footer").hide();
        jQuery("div#wkfooter_switch").hide();
        toggle_footer.html("<img src='../images/other/zuklappen.png' border='0'>");
        };

        if (footeroff == "on") {
        jQuery("div#footer").show();
        jQuery("div#wkfooter_switch").show();
        toggle_footer.html("<img src='../images/other/aufklappen.png' border='0'>");
        };

        var footer_switch = jQuery("div#footer");
        var toggle_footer = jQuery(".toggle_footer_switch");
        var toggle_switch_div = jQuery("div#toggle_switch_div");

        jQuery("a.toggle_footer_switch").click(function() {

            if (footer_switch.is(":visible")) {
                toggle_footer.html("<img src='../images/other/zuklappen.png' border='0'>");
                jQuery("div#footer").hide();
                jQuery("div#wkfooter_switch").hide();
                jQuery.cookie("footeroff" , "off");
            }
            else if (footer_switch.is(":hidden")) {
                toggle_footer.html("<img src='../images/other/aufklappen.png' border='0'>");
                jQuery("div#footer").show();
                jQuery("div#wkfooter_switch").show();
                jQuery.cookie("footeroff" , "on");
            }

        });

    });
</code>```

Thank you very much!

Best regards

答:
I know this is a really old question, but just for people that are looking for a quick fix, this worked for me:

a. in the PHP/HTML file:

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/.../jquery.min.js"></script>
    <script>
    $(document).ready(function(){
        $("#pClick").click(function(){
            $("#pText").toggle();
            $("#pText").text("...");
        });
    });
    </script>
</code>```

b. in the CSS file:

```<code>#pText {display: none;}
</code>```

It now works even on the first click. It's a simple, quick answer that I hope will be useful to somebody.

Body:
i want to create a simple toggle function which toggles a div show() or hide() with a cookie to remember in which state the div is. So far so good. Well, it works kind of. When i toggle the div hide() it hides, but when i reload the page an want to toggle the div show() i have to click the button twice ! I've read the anwers here in but they didn't help. Also i've tried to make it with a click function but that doesn't work at all.

Here ist the code:

  jQuery().ready(function () {

        var footeroff = jQuery.cookie('footeroff');
        var toggle_footer = jQuery(".toggle_footer_switch");

        if (footeroff == "off") {
        jQuery("div#footer").hide();
        jQuery("div#wkfooter_switch").hide();
        toggle_footer.html("");
        };

        if (footeroff == "on") {
        jQuery("div#footer").show();
        jQuery("div#wkfooter_switch").show();
        toggle_footer.html("");
        };

        var footer_switch = jQuery("div#footer");
        var toggle_footer = jQuery(".toggle_footer_switch");
        var toggle_switch_div = jQuery("div#toggle_switch_div");

        jQuery("a.toggle_footer_switch").toggle(
            function () {
                toggle_footer.html("");
                jQuery("div#footer").fadeOut("slow");
                jQuery("div#wkfooter_switch").hide();
                jQuery.cookie("footeroff" , "off");
            },
            function () {
                toggle_footer.html("");
                jQuery("div#footer").fadeIn("slow");
                jQuery("div#wkfooter_switch").show();
                jQuery.cookie("footeroff" , "on");
            }
        );

    });

And there is the code with a click function:

      jQuery().ready(function () {

        var footeroff = jQuery.cookie('footeroff');
        var toggle_footer = jQuery(".toggle_footer_switch");

        if (footeroff == "off") {
        jQuery("div#footer").hide();
        jQuery("div#wkfooter_switch").hide();
        toggle_footer.html("");
        };

        if (footeroff == "on") {
        jQuery("div#footer").show();
        jQuery("div#wkfooter_switch").show();
        toggle_footer.html("");
        };

        var footer_switch = jQuery("div#footer");
        var toggle_footer = jQuery(".toggle_footer_switch");
        var toggle_switch_div = jQuery("div#toggle_switch_div");

        jQuery("a.toggle_footer_switch").click(function() {

            if (footer_switch.is(":visible")) {
                toggle_footer.html("");
                jQuery("div#footer").hide();
                jQuery("div#wkfooter_switch").hide();
                jQuery.cookie("footeroff" , "off");
            }
            else if (footer_switch.is(":hidden")) {
                toggle_footer.html("");
                jQuery("div#footer").show();
                jQuery("div#wkfooter_switch").show();
                jQuery.cookie("footeroff" , "on");
            }

        });

    });

Thank you very much!

Best regards

Body:
I know this is a really old question, but just for people that are looking for a quick fix, this worked for me:

a. in the PHP/HTML file:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/.../jquery.min.js"></script>
    <script>
    $(document).ready(function(){
        $("#pClick").click(function(){
            $("#pText").toggle();
            $("#pText").text("...");
        });
    });
    </script>

b. in the CSS file:

#pText {display: none;}

It now works even on the first click. It's a simple, quick answer that I hope will be useful to somebody.


问:
Search and replace a word in directory and its subdirectories
I need to find and replace a word in all the files across a directory and its subdirectories.

I used this line of code:

```<code>perl -pi -w -e 's/foo/bar/g;' *.*
</code>```

But it changes the words only in files in the current directory and doesn't affect the subdirectories.

How can I change the word on every directory and subdirectory?

答:
You could do a pure Perl solution that recursively traverses your directory structure, but that'd require a lot more code to write.

The easier solution is to use the find command which can be told to find all files and run a command against them.

```<code>find . -type f -exec perl -pi -w -e 's/foo/bar/g;' \{\} \;
</code>```

(I've escaped the {} and ; just in case but you might not need this)

Body:
I need to find and replace a word in all the files across a directory and its subdirectories.

I used this line of code:

perl -pi -w -e 's/foo/bar/g;' *.*

But it changes the words only in files in the current directory and doesn't affect the subdirectories.

How can I change the word on every directory and subdirectory?

Body:
You could do a pure Perl solution that recursively traverses your directory structure, but that'd require a lot more code to write.

The easier solution is to use the find command which can be told to find all files and run a command against them.

find . -type f -exec perl -pi -w -e 's/foo/bar/g;' \{\} \;

(I've escaped the {} and ; just in case but you might not need this)


问:
How to check if a table exists in a MySQL database using shell script?
i am trying to check whether a table is empty or not using shell script
the code that i have is

```<code>#!/bin/bash

if [ "mysql -u user -ppassword -hserver dbname -e 'select count(*) from test_dec;'" != 0 ];
then
        echo "table not empty"
else
        echo "table empty"
fi
</code>```

but when i run this it always displays "table not empty" even if the output of the query is 0.

```<code>user@server$ ./table_check.sh
table not empty
</code>```

what is wrong here?

答:
This is my version of the script and it will first check if table exists and if yes will check if the table is empty.

BASH

```<code>#!/bin/bash

# Prepare variables
TABLE=$1
SQL_EXISTS=$(printf 'SHOW TABLES LIKE "%s"' "$TABLE")
SQL_IS_EMPTY=$(printf 'SELECT 1 FROM %s LIMIT 1' "$TABLE")

# Credentials
USERNAME=YOUR_USERNAME
PASSWORD=YOUR_PASSWORD
DATABASE=YOUR_DATABASE_NAME

echo "Checking if table <$TABLE> exists ..."

# Check if table exists
if [[ $(mysql -u $USERNAME -p$PASSWORD -e "$SQL_EXISTS" $DATABASE) ]]
then
    echo "Table exists ..."

    # Check if table has records
    if [[ $(mysql -u $USERNAME -p$PASSWORD -e "$SQL_IS_EMPTY" $DATABASE) ]]
    then
        echo "Table has records ..."
    else
        echo "Table is empty ..."
    fi
else
    echo "Table not exists ..."
fi
</code>```

USAGE

First before using this script you need to replace YOUR_USERNAME, YOUR_PASSWORD and YOUR_DATABASE_NAME with the corresponding values. Then:

```<code># bash SCRIPT_NAME TABLE_TO_CHECK
  bash my_script my_table
</code>```

where SCRIPT_NAME( my_script ) is the name of the file holding the above script content and TABLE_TO_CHECK( my_table ) is the name of the table that you want to check for.

EXPECTED OUTPUT

```<code>Checking if table <my_table> exists ...
Table exists ...
Table is empty ...
</code>```

COUPLE OF WORDS ABOUT THE CODE

Store the first argument from the command line in variable TABLE

```<code>TABLE=$1
</code>```

Prepare two variables that will hold the SQL queries used to check.
Note that printf is used to insert the table name in the variables, because $('SHOW TABLES LIKE "$TABLE"') is not going to work.

```<code>SQL_EXISTS=$(printf 'SHOW TABLES LIKE "%s"' "$TABLE")
SQL_IS_EMPTY=$(printf 'SELECT COUNT(*) as records FROM %s' "$TABLE")
</code>```

Check if table exists. SHOW TABLES LIKE "table_name" will return empty string if the table does not exist and the if statement will fail. Usage of the $ like $(echo 1 + 2) means - evaluate whatever is inside the parentheses and return that as a value.

```<code>if [[ $(mysql -u $USERNAME -p$PASSWORD -e "$SQL_EXISTS" $DATABASE) ]]
</code>```

Finally we check if table is empty. Using the previous approach. Basically we check if MySQL will return empty string (for empty tables), otherwise the query will return some text as a result and we can consider the table not empty.

```<code>if [[ $(mysql -u $USERNAME -p$PASSWORD -e "$SQL_IS_EMPTY" $DATABASE) ]]
</code>```

Body:
i am trying to check whether a table is empty or not using shell script
the code that i have is

#!/bin/bash

if [ "mysql -u user -ppassword -hserver dbname -e 'select count(*) from test_dec;'" != 0 ];
then
        echo "table not empty"
else
        echo "table empty"
fi

but when i run this it always displays "table not empty" even if the output of the query is 0.

user@server$ ./table_check.sh
table not empty

what is wrong here?

Body:
This is my version of the script and it will first check if table exists and if yes will check if the table is empty.

BASH

#!/bin/bash

# Prepare variables
TABLE=$1
SQL_EXISTS=$(printf 'SHOW TABLES LIKE "%s"' "$TABLE")
SQL_IS_EMPTY=$(printf 'SELECT 1 FROM %s LIMIT 1' "$TABLE")

# Credentials
USERNAME=YOUR_USERNAME
PASSWORD=YOUR_PASSWORD
DATABASE=YOUR_DATABASE_NAME

echo "Checking if table <$TABLE> exists ..."

# Check if table exists
if [[ $(mysql -u $USERNAME -p$PASSWORD -e "$SQL_EXISTS" $DATABASE) ]]
then
    echo "Table exists ..."

    # Check if table has records
    if [[ $(mysql -u $USERNAME -p$PASSWORD -e "$SQL_IS_EMPTY" $DATABASE) ]]
    then
        echo "Table has records ..."
    else
        echo "Table is empty ..."
    fi
else
    echo "Table not exists ..."
fi

USAGE

First before using this script you need to replace YOUR_USERNAME, YOUR_PASSWORD and YOUR_DATABASE_NAME with the corresponding values. Then:

# bash SCRIPT_NAME TABLE_TO_CHECK
  bash my_script my_table

where SCRIPT_NAME( my_script ) is the name of the file holding the above script content and TABLE_TO_CHECK( my_table ) is the name of the table that you want to check for.

EXPECTED OUTPUT

Checking if table <my_table> exists ...
Table exists ...
Table is empty ...

COUPLE OF WORDS ABOUT THE CODE

Store the first argument from the command line in variable TABLE

TABLE=$1

Prepare two variables that will hold the SQL queries used to check.
Note that printf is used to insert the table name in the variables, because $('SHOW TABLES LIKE "$TABLE"') is not going to work.

SQL_EXISTS=$(printf 'SHOW TABLES LIKE "%s"' "$TABLE")
SQL_IS_EMPTY=$(printf 'SELECT COUNT(*) as records FROM %s' "$TABLE")

Check if table exists. SHOW TABLES LIKE "table_name" will return empty string if the table does not exist and the if statement will fail. Usage of the $ like $(echo 1 + 2) means - evaluate whatever is inside the parentheses and return that as a value.

if [[ $(mysql -u $USERNAME -p$PASSWORD -e "$SQL_EXISTS" $DATABASE) ]]

Finally we check if table is empty. Using the previous approach. Basically we check if MySQL will return empty string (for empty tables), otherwise the query will return some text as a result and we can consider the table not empty.

if [[ $(mysql -u $USERNAME -p$PASSWORD -e "$SQL_IS_EMPTY" $DATABASE) ]]


问:
Adding MANY variables in Tensorflow
If tf.add only takes 2 to 3 positional arguments how do I add half a dozen or more values together (hoping you won't say do lots of sub-totals first!). I'd like to specify something like:

```<code>tf.AddTheseTogether(value1,value2,value3,value4,value5) etc.
</code>```

Tried tf.add_n and had same result. It errors with #tf.add or add_n takes 2 to 3 positional arguments no more. Also tried tf.add([value1,value2],[value3,value4]) etc. Guessing there must be another function? tf.sum not known.

答:
tf.add_n takes a list of inputs, like this (note the []):

```<code>tf.add_n([value1,value2,value3,value4,value5])
</code>```

Title: Adding MANY variables in Tensorflow

Body:
If tf.add only takes 2 to 3 positional arguments how do I add half a dozen or more values together (hoping you won't say do lots of sub-totals first!). I'd like to specify something like:

tf.AddTheseTogether(value1,value2,value3,value4,value5) etc.

Tried tf.add_n and had same result. It errors with #tf.add or add_n takes 2 to 3 positional arguments no more. Also tried tf.add([value1,value2],[value3,value4]) etc. Guessing there must be another function? tf.sum not known.

Body:
tf.add_n takes a list of inputs, like this (note the []):

tf.add_n([value1,value2,value3,value4,value5])


问:
Check if router-outlet is in use
All,

I would like to use *ngIf to remove a section of a page if a specific router-outlet has a component.

I've tried searching through ActivatedRoute and Router, but I can't seem to figure it out. How do you check if a specific router-outlet is in use?

答:
I figured this out. You need to use the events for router outlets. However, you can't use ngIf because events won't be fired unless the outlet is in the dom.

ts

```<code>showOutlet: boolean;

onActivate(event : any) {
  this.showOutlet = true;
}

onDeactivate(event : any) {
  this.showOutlet = false;
}
</code>```

html

```<code><div [hidden]="!showOutlet">
  <router-outlet name="my-outlet"
      (activate)="onActivate($event)"
      (deactivate)="onDeactivate($event)"></router-outlet>
</div>
</code>```

Title: Check if router-outlet is in use

Body:
I figured this out. You need to use the events for router outlets. However, you can't use ngIf because events won't be fired unless the outlet is in the dom.

ts

showOutlet: boolean;

onActivate(event : any) {
  this.showOutlet = true;
}

onDeactivate(event : any) {
  this.showOutlet = false;
}

html

<div [hidden]="!showOutlet">
  <router-outlet name="my-outlet"
      (activate)="onActivate($event)"
      (deactivate)="onDeactivate($event)"></router-outlet>
</div>


问:
Problems getting inputted values from forms in jQuery
Hey guys, this is my first time using jQuery. I'm working on a simple Twitter app that checks whether a user is following another user, but I'm having trouble picking up on the inputted values in my form.

I've got this form on my page:

```<code><form id="form_friendship">
  Is <input type='text' name='user_a' value='username'/> following <input type='text' name='user_b' value='username'/> on Twitter? <input type="submit" value="Check">
</form>
</code>```

And using the form plugin, here's my JS:

```<code>var value = $('#form_friendship *').fieldValue( );
$('#form_friendship *').submit(alert(value));
</code>```

The only thing that's being alerted is "username, username" and it's not registered text inputted into the fields at all. Any ideas on what's wrong here? Thanks

答:
i think that your javascript should look more like this

```<code>var userA = $('input[name:user_a]').val(),
userB = $('input[name:user_b]').val( );

$('#form_friendship').submit(function(){
    alert(userA +', '+userB);
});
</code>```

if you want to collect all the values from the form with out specifying the actual input you can try something like

```<code>$('#form_friendship').submit(function(){

    //creating array to put values
    var inputs = [];

    //loop to catch all inputs type=text
    $(this).find('input[type=text]').each(function(){
        //pushing values into array
        inputs.push($(this).val());
    })

    //joining alerting values in array
    alert(inputs.join(', '));

});
</code>```

Body:
Hey guys, this is my first time using jQuery. I'm working on a simple Twitter app that checks whether a user is following another user, but I'm having trouble picking up on the inputted values in my form.

I've got this form on my page:

<form id="form_friendship">
  Is <input type='text' name='user_a' value='username'/> following <input type='text' name='user_b' value='username'/> on Twitter? <input type="submit" value="Check">
</form>

And using the form plugin, here's my JS:

var value = $('#form_friendship *').fieldValue( );
$('#form_friendship *').submit(alert(value));

The only thing that's being alerted is "username, username" and it's not registered text inputted into the fields at all. Any ideas on what's wrong here? Thanks

Body:
i think that your javascript should look more like this

var userA = $('input[name:user_a]').val(),
userB = $('input[name:user_b]').val( );

$('#form_friendship').submit(function(){
    alert(userA +', '+userB);
});

if you want to collect all the values from the form with out specifying the actual input you can try something like

$('#form_friendship').submit(function(){

    //creating array to put values
    var inputs = [];

    //loop to catch all inputs type=text
    $(this).find('input[type=text]').each(function(){
        //pushing values into array
        inputs.push($(this).val());
    })

    //joining alerting values in array
    alert(inputs.join(', '));

});


问:
CSS Flex Column Layout without Specified Height
Just discovered flex today and I'm hoping it'll solve a small visual challenge.

I have a list of items already alphabetically sorted. They all have the same width and, up until now, I've had them floating left. This results in a left-to-right order with wrapping when horizontal space runs out.

What I was hoping to do is have top-down sorting with as many columns as possible with the available width. Seeing as this list is dynamic, the height would be variable. And the height would have to increase as horizontal space is lost (resizing) preventing as many columns.

Given the apparent nature of what flex is trying to accomplish I'd think this would be supported, but thus far I can't figure it out. "display: flex" and "flex-flow: column wrap" seem correct, but it requires a specific height to work, which I can't provide.

Am I missing something?

Edit:
I've created a JSFiddle to play with here: https://jsfiddle.net/7ae3xz2x/

```<code>ul {
    display: flex;
    flex-flow: column wrap;
    height: 100px;
}
ul li {
    width: 150px;
    list-style-type: none;
    border: 1px solid black;
    text-align: center;
}
</code>```

If you take the height off the ul, nothing wraps.

It seems the conceptual problem is that "column" flow is all tied to the height of the container instead of to the width, which is what I want. I don't care how tall the area has to be. I care about having as many columns as possible in the available width. Maybe this is just an annoying shortcoming of the flex convention.

答:
This seems like a job for CSS columns: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Columns

Instead of flex, give the ul a column-width CSS rule:

```<code>ul {
  column-width: 150px;
}
</code>```

Here's a JSFiddle.

Body:
Just discovered flex today and I'm hoping it'll solve a small visual challenge.

I have a list of items already alphabetically sorted. They all have the same width and, up until now, I've had them floating left. This results in a left-to-right order with wrapping when horizontal space runs out.

What I was hoping to do is have top-down sorting with as many columns as possible with the available width. Seeing as this list is dynamic, the height would be variable. And the height would have to increase as horizontal space is lost (resizing) preventing as many columns.

Given the apparent nature of what flex is trying to accomplish I'd think this would be supported, but thus far I can't figure it out. "display: flex" and "flex-flow: column wrap" seem correct, but it requires a specific height to work, which I can't provide.

Am I missing something?

Edit:
I've created a JSFiddle to play with here: https://jsfiddle.net/7ae3xz2x/

ul {
    display: flex;
    flex-flow: column wrap;
    height: 100px;
}
ul li {
    width: 150px;
    list-style-type: none;
    border: 1px solid black;
    text-align: center;
}

If you take the height off the ul, nothing wraps.

It seems the conceptual problem is that "column" flow is all tied to the height of the container instead of to the width, which is what I want. I don't care how tall the area has to be. I care about having as many columns as possible in the available width. Maybe this is just an annoying shortcoming of the flex convention.

Body:
This seems like a job for CSS columns: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Columns

Instead of flex, give the ul a column-width CSS rule:

ul {
  column-width: 150px;
}

Here's a JSFiddle.


问:
is this a valid class variable ? $this->$variablename
I am referencing to a variable like this

```<code>$this->variablename
</code>```

but I have seen accessing variable like this:

```<code>$this->$variablename
</code>```

for example in a google script

```<code>public function __get($key)
{
    $keyTypeName = $this->keyType($key);
    $keyDataType = $this->dataType($key);
    if (isset($this->$keyTypeName) && !isset($this->processed[$key])) {
      if (isset($this->modelData[$key])) {
        $val = $this->modelData[$key];
      } else if (isset($this->$keyDataType) &&
          ($this->$keyDataType == 'array' || $this->$keyDataType == 'map')) {
        $val = array();
      } else {
        $val = null;
      }
   }
}
</code>```

in this example it is $this->$keyTypeName, is this an error or valid code?. In php 7 it is giving error.

答:
See Example

What is $this->$var simple means that the php interpreter converter the $var and parse it together with the object $this.

If $var = "string";

and you say $this->$var, it simply means $this->string.

Check the example link attached.

Body:
I am referencing to a variable like this

$this->variablename

but I have seen accessing variable like this:

$this->$variablename

for example in a google script

public function __get($key)
{
    $keyTypeName = $this->keyType($key);
    $keyDataType = $this->dataType($key);
    if (isset($this->$keyTypeName) && !isset($this->processed[$key])) {
      if (isset($this->modelData[$key])) {
        $val = $this->modelData[$key];
      } else if (isset($this->$keyDataType) &&
          ($this->$keyDataType == 'array' || $this->$keyDataType == 'map')) {
        $val = array();
      } else {
        $val = null;
      }
   }
}

in this example it is $this->$keyTypeName, is this an error or valid code?. In php 7 it is giving error.


问:
Unable to load the "Symfony\Bridge\Twig\Form\TwigRenderer" runtime
I've been working through various hurtles toward migrating an existing Symfony3 web app from a local LAMP host up to Goggle's App Engine Standard PHP Environment.  I've taken hints from the appengine-symfony-starter-project to use Memcache for sessions, pre-cache the application code, and connect to a Cloud SQL MySQL database. In have the core pieces working fine.

I added a login form at /login using a TWIG template with a form in it that goes like so:

```<code><form class="form" action="{{ path('security_login') }}" method="post">
  <input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}" />
  <div class="form-group">
    <input class="form-control" id="email" type="text" name="_email" placeholder="Email" value="{{ last_username }}"/>
  </div>
  <div class="form-group">
    <input class="form-control" id="password" type="password" name="_password" placeholder="Password"/>
  </div>
  <div class="form-group">
    <input type="checkbox" id="remember_me" name="_remember_me" checked>
    <label for "remember_me">Remember Me</label>
  </div>
  <div class="form-group">
    <button class="btn btn-round btn-b">Login</button>
  </div>
  <div class="form-group"><a href="{{ path('security_reset') }}">Forgot Password?</a></div>
</form>
</code>```

This works fine in the local DEV and TEST environments but when I push this up to GAE, I'm getting the error below:

```<code>Unable to load the "Symfony\Bridge\Twig\Form\TwigRenderer" runtime.
</code>```

I've been digging for a couple hours now and haven't found a hit as to what's wrong here.  Anyone have any ideas where to look?

Thanks in advance,

答:
We encountered the same error this morning at work, in a Silex app.

This helped us: https://github.com/silexphp/Silex/pull/1571

It worked for us to change in our composer.json the version of symfony/form from ~2.8|^3.0 to ~2.8|3.3 as it appears TwigRenderer is deprecated in 3.4.

Hope this helps.

Body:
I've been working through various hurtles toward migrating an existing Symfony3 web app from a local LAMP host up to Goggle's App Engine Standard PHP Environment.  I've taken hints from the appengine-symfony-starter-project to use Memcache for sessions, pre-cache the application code, and connect to a Cloud SQL MySQL database. In have the core pieces working fine.

I added a login form at /login using a TWIG template with a form in it that goes like so:

<form class="form" action="{{ path('security_login') }}" method="post">
  <input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}" />

    <input class="form-control" id="email" type="text" name="_email" placeholder="Email" value="{{ last_username }}"/>

    <input class="form-control" id="password" type="password" name="_password" placeholder="Password"/>

    <input type="checkbox" id="remember_me" name="_remember_me" checked>
    Remember Me

    <button class="btn btn-round btn-b">Login</button>

Forgot Password?

</form>

This works fine in the local DEV and TEST environments but when I push this up to GAE, I'm getting the error below:

Unable to load the "Symfony\Bridge\Twig\Form\TwigRenderer" runtime.

I've been digging for a couple hours now and haven't found a hit as to what's wrong here.  Anyone have any ideas where to look?

Thanks in advance,


问:
Any plans for "do"/Action LINQ operator?
Here's a simple method with a foreach loop:

```<code>IEnumerable<XElement> FieldsToXElements(object instance)
{
    var fieldElements = new List<XElement>();

    foreach (var field in instance.GetType().GetFields(instance))
    {
        fieldElements.Add(new XElement(field.Name, field.GetValue(instance)));
    }

    return fieldElements;
}
</code>```

Kind of ugly. If there were some operator in LINQ that mean "do something" (e.g. perform an Action for each selected in the LINQ statement), it would look nicer, more terse:

```<code>IEnumerable<XElement> FieldsToXElements(object instance)
{
    var fieldElements = new List<XElement>();

    from field in instance.GetType().GetFields(instance))
    let name = field.Name
    let value = field.GetValue(instance)
    do fieldElements.Add(new XElement(name, value));

    return fieldElements;
}
</code>```

I realize that's subjective, and just my opinion. For a foreach loop that has one line that simply invokes a method, a "do" operator makes sense, in my opinion. But I'm wondering if anyone at MS has thought the same thing. Is such LINQ operator planned in any upcoming releases (e.g. alongside the C# 4.0 debut)?

Here's another example, with a predicate, where the fictitious do operator would really make the code look cleaner. This:

```<code>IEnumerable<XElement> FieldsToXElements
    (object instance, Func<FieldInfo, bool> predicate)
{
    var fieldElements = new List<XElement>();

    foreach (var field in instance.GetType().GetFields(instance).Where(predicate))
    {
        fieldElements.Add(new XElement(field.Name, field.GetValue(instance)));
    }

    return fieldElements;
}
</code>```

vs. this:

```<code>IEnumerable<XElement> FieldsToXElements
    (object instance, Func<FieldInfo, bool> predicate)
{
    var fieldElements = new List<XElement>();

    from field in instance.GetType().GetFields(instance))
    let name = field.Name
    let value = field.GetValue(instance)
    where predicate(field)
    do fieldElements.Add(new XElement(name, value));

    return fieldElements;
}
</code>```

答:
For your specific example (populating a List<XElement>), I'd do it this way.

```<code>IEnumerable<XElement> FieldsToXElements(object instance)
{
  List<XElement> fieldElements =
  (
    from field in instance.GetType().GetFields(instance))
    let name = field.Name
    let value = field.GetValue(instance)
    select new XElement(name, value)
  ).ToList();  //Another Option is List<T>.AddRange()
  return fieldElements;
}
</code>```

Also: Don't forget that List<T> already implements .ForEach<T>(), so to use it against any Enumerable<T>, this is all the code you need.

```<code>myEnumerable.ToList().ForEach( x => myAction(x) );
</code>```

OwnerDisplayName: Chris

Body:
Here's a simple method with a foreach loop:

IEnumerable<XElement> FieldsToXElements(object instance)
{
    var fieldElements = new List<XElement>();

    foreach (var field in instance.GetType().GetFields(instance))
    {
        fieldElements.Add(new XElement(field.Name, field.GetValue(instance)));
    }

    return fieldElements;
}

Kind of ugly. If there were some operator in LINQ that mean "do something" (e.g. perform an Action for each selected in the LINQ statement), it would look nicer, more terse:

IEnumerable<XElement> FieldsToXElements(object instance)
{
    var fieldElements = new List<XElement>();

    from field in instance.GetType().GetFields(instance))
    let name = field.Name
    let value = field.GetValue(instance)
    do fieldElements.Add(new XElement(name, value));

    return fieldElements;
}

I realize that's subjective, and just my opinion. For a foreach loop that has one line that simply invokes a method, a "do" operator makes sense, in my opinion. But I'm wondering if anyone at MS has thought the same thing. Is such LINQ operator planned in any upcoming releases (e.g. alongside the C# 4.0 debut)?

Here's another example, with a predicate, where the fictitious do operator would really make the code look cleaner. This:

IEnumerable<XElement> FieldsToXElements
    (object instance, Func<FieldInfo, bool> predicate)
{
    var fieldElements = new List<XElement>();

    foreach (var field in instance.GetType().GetFields(instance).Where(predicate))
    {
        fieldElements.Add(new XElement(field.Name, field.GetValue(instance)));
    }

    return fieldElements;
}

vs. this:

IEnumerable<XElement> FieldsToXElements
    (object instance, Func<FieldInfo, bool> predicate)
{
    var fieldElements = new List<XElement>();

    from field in instance.GetType().GetFields(instance))
    let name = field.Name
    let value = field.GetValue(instance)
    where predicate(field)
    do fieldElements.Add(new XElement(name, value));

    return fieldElements;
}

Body:
For your specific example (populating a List<XElement>), I'd do it this way.

IEnumerable<XElement> FieldsToXElements(object instance)
{
  List<XElement> fieldElements =
  (
    from field in instance.GetType().GetFields(instance))
    let name = field.Name
    let value = field.GetValue(instance)
    select new XElement(name, value)
  ).ToList();  //Another Option is List<T>.AddRange()
  return fieldElements;
}

Also: Don't forget that List<T> already implements .ForEach<T>(), so to use it against any Enumerable<T>, this is all the code you need.

myEnumerable.ToList().ForEach( x => myAction(x) );

OwnerDisplayName: David B


问:
CS0012: The type 'System.Data.Linq.DataContext' is defined in an assembly that is not referenced
Helllo, I get this error:

CS0246: The type or namespace name 'DataClasses1DataContext' could not be found (are you missing a using directive or an assembly reference?)

For this .aspx file:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class WebApplication1_admin_Places : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        DataClasses1DataContext db = new DataClasses1DataContext();
        var query = (from m in db.Places orderby m.Name select m);
        PlacesList.DataSource = query;
        PlacesList.DataBind();
    }
}
</code>```

The thing is, on / folder I can access DB, but on /admin folder i get this error.

What am I doing wrong?

EDIT

CS0012: The type 'System.Data.Linq.DataContext' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Data.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.

What does that mean?

答:
Navigate to the web project's References node Find the reference to
  System.Data.Linq Open the VS Properties Window In the properties
  window, change Copy Local: False to True Before this, the
  System.Data.Linq.dll was not being copied into the bin directory.
  (Copying it manually into the bin directory also resolved the error)

From: https://stackoverflow.com/a/34356930/125938

Body:
Helllo, I get this error:

CS0246: The type or namespace name 'DataClasses1DataContext' could not be found (are you missing a using directive or an assembly reference?)

For this .aspx file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class WebApplication1_admin_Places : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        DataClasses1DataContext db = new DataClasses1DataContext();
        var query = (from m in db.Places orderby m.Name select m);
        PlacesList.DataSource = query;
        PlacesList.DataBind();
    }
}

The thing is, on / folder I can access DB, but on /admin folder i get this error.

What am I doing wrong?

EDIT

CS0012: The type 'System.Data.Linq.DataContext' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Data.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.

What does that mean?


问:
Converting JSON to XML in Java
I am new to json. I am having a program to generate xml from json object.

```<code>String str = "{'name':'JSON','integer':1,'double':2.0,'boolean':true,'nested':{'id':42},'array':[1,2,3]}";
    JSON json = JSONSerializer.toJSON( str );
    XMLSerializer xmlSerializer = new XMLSerializer();
    xmlSerializer.setTypeHintsCompatibility( false );
    String xml = xmlSerializer.write( json );
    System.out.println(xml);
</code>```

the output is:

```<code><?xml version="1.0" encoding="UTF-8"?>
<o><array json_class="array"><e json_type="number">1</e><e json_type="number">2</e><e json_type="number">3</e></array><boolean json_type="boolean">true</boolean><double json_type="number">2.0</double><integer json_type="number">1</integer><name json_type="string">JSON</name><nested json_class="object"><id json_type="number">42</id></nested></o>
</code>```

my biggest problem is how to write my own attributes instead of json_type="number" and also writing my own sub elements like .

答:
Transforming with XSLT 3.0 is the only proper way to do it, as far as I can tell. It is guaranteed to produce valid XML, and a nice structure at that.
https://www.w3.org/TR/xslt/#json</p>

Title: Converting JSON to XML in Java

Body:
I am new to json. I am having a program to generate xml from json object.

String str = "{'name':'JSON','integer':1,'double':2.0,'boolean':true,'nested':{'id':42},'array':[1,2,3]}";
    JSON json = JSONSerializer.toJSON( str );
    XMLSerializer xmlSerializer = new XMLSerializer();
    xmlSerializer.setTypeHintsCompatibility( false );
    String xml = xmlSerializer.write( json );
    System.out.println(xml);

the output is:

<?xml version="1.0" encoding="UTF-8"?>
<o><array json_class="array"><e json_type="number">1</e><e json_type="number">2</e><e json_type="number">3</e></array><boolean json_type="boolean">true</boolean><double json_type="number">2.0</double><integer json_type="number">1</integer><name json_type="string">JSON</name><nested json_class="object"><id json_type="number">42</id></nested></o>

my biggest problem is how to write my own attributes instead of json_type="number" and also writing my own sub elements like .


问:
importing a library only for debugging, not for release
I am using OkHttp in my Application and add OkHttp interceptor to print log. As you see, I only want to import OkHttp interceptor for debug apk not for release.

```<code>    if (BuildConfig.DEBUG) {
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.i(TAG, message);
            }
        });
        logging.setLevel(HttpLoggingInterceptor.Level.HEADERS);
        mOkHttpClient = new OkHttpClient.Builder().addInterceptor(logging).build();
    }else {
        mOkHttpClient = new OkHttpClient();
    }
</code>```

I have used debugImplementation 'com.squareup.okhttp3:logging-interceptor:3.9.1' however when I invoke ./gradlew assembleRelease it failed because import import okhttp3.logging.HttpLoggingInterceptor;

Is there any way to do that? Thanks in advance.

Edit

The question Import library only for debugging does not work for me.

答:
In your gradle replace

```<code>compile 'library'
</code>```

for

```<code>compileDebug 'library'
</code>```

In Gradle 3.0 not sure but think it is implementationDebug/apiDebug

But on release the code will not compile.

A solution that may work if it doesnt conflict is to create a interface in 'main/java' that will delegate what you want without being library specific, then create a folder 'debug/java' and create a File that implements the interface with the Library, call it from your code instead this debug will be specific for the flavor debug compile. Here to compile as release without errors you may specify a class with the same name in 'release/java' with a empty implementation (if this doesnt works you will have to lookup with Class#forName and it will only work on debug)

Body:
I am using OkHttp in my Application and add OkHttp interceptor to print log. As you see, I only want to import OkHttp interceptor for debug apk not for release.

    if (BuildConfig.DEBUG) {
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.i(TAG, message);
            }
        });
        logging.setLevel(HttpLoggingInterceptor.Level.HEADERS);
        mOkHttpClient = new OkHttpClient.Builder().addInterceptor(logging).build();
    }else {
        mOkHttpClient = new OkHttpClient();
    }

I have used debugImplementation 'com.squareup.okhttp3:logging-interceptor:3.9.1' however when I invoke ./gradlew assembleRelease it failed because import import okhttp3.logging.HttpLoggingInterceptor;

Is there any way to do that? Thanks in advance.

Edit

The question Import library only for debugging does not work for me.

Body:
In your gradle replace

compile 'library'

for

compileDebug 'library'

In Gradle 3.0 not sure but think it is implementationDebug/apiDebug

But on release the code will not compile.

A solution that may work if it doesnt conflict is to create a interface in 'main/java' that will delegate what you want without being library specific, then create a folder 'debug/java' and create a File that implements the interface with the Library, call it from your code instead this debug will be specific for the flavor debug compile. Here to compile as release without errors you may specify a class with the same name in 'release/java' with a empty implementation (if this doesnt works you will have to lookup with Class#forName and it will only work on debug)


问:
What do two question marks together mean in C#?
Ran across this line of code:

```<code>FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();
</code>```

What do the two question marks mean, is it some kind of ternary operator?
It's hard to look up in Google.

答:
It's a null coalescing operator that works similarly to a ternary operator.

```<code>    a ?? b  => a !=null ? a : b
</code>```

Another interesting point for this is,
"A nullable type can contain a value, or it can be undefined".
So if you try to assign a nullable value type to a non-nullable value type
you will get a compile-time error.

```<code>int? x = null; // x is nullable value type
int z = 0; // z is non-nullable value type
z = x; // compile error will be there.
</code>```

So to do that using ?? operator:

```<code>z = x ?? 1; // with ?? operator there are no issues
</code>```

OwnerDisplayName: Edward Tanguay

Body:
Ran across this line of code:

FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();

What do the two question marks mean, is it some kind of ternary operator?
It's hard to look up in Google.

LastEditorDisplayName: OrbMan

Body:
It's a null coalescing operator that works similarly to a ternary operator.

    a ?? b  => a !=null ? a : b

Another interesting point for this is,
"A nullable type can contain a value, or it can be undefined".
So if you try to assign a nullable value type to a non-nullable value type
you will get a compile-time error.

int? x = null; // x is nullable value type
int z = 0; // z is non-nullable value type
z = x; // compile error will be there.

So to do that using ?? operator:

z = x ?? 1; // with ?? operator there are no issues


问:
How to show different Views on different Drupal Themes
Say I have a default theme for my drupal site. Here I have created views, blocks, etc and styled everything the way I want for the public. Now, as the admin I would like to have an entirely separate theme. No problem, I create a second theme in the themes directory and switch my admin user theme configuration to the second theme. But, what if in my second theme I want to show entirely different content (i.e. Views, blocks, etc).
Let's use my front page as an example (front).
Right now my front page has a slideshow using Views. This view obviously shows up on the front page no matter what theme I'm using. So for my front page, how could I show an entirely different View (say a list of blog posts) for the second theme than the slideshow View I'm using for the first theme?</p>

答:
The easiest way is to put your views in a block, as blocks are configured per theme. Different themes can have completely different block configurations. A potential issue with this approach is that it does take some more work to get things like arguments to play nicely with views that are hosted in blocks.

Another option which may work for you is to just have the same view themed different ways. Views plays very nicely with the theme layer of Drupal and you can create template files for a particular view or view display. Check out the theme info link in the views admin page to see all the possible overrides for a view. Of course this is assuming that there are some common elements between what you want to show.

A third option might be to display multiple views on the one page, and use the permissions system to ensure only one is shown at any one time. I have used this approach in the past but it did get somewhat unwieldy to manage because as requirements changed I had to replicate the changes across multiple views.


问:
Retrieve exchange rate from website with Excel
I want to write a date in Excel and get the rate on this date .

I search solutions but not found something that can help me.

I am using Excel 2016.

My code:

```<code>Function CryptoQuote(enteredDate As String)
    If IsDate(enteredDate) Then
        enteredDate = Format(Date, "yyyy-mm-dd")
        Dim strURL As String: strURL = "http://www.x-rates.com/historical/?from=USD&amount=1&date=" & enteredDate
        MsgBox strURL
        Dim http As Object: Set http = CreateObject("msxml2.xmlhttp")
        http.Open "GET", strURL, False
        http.Send
        Dim strCSV As String
        Found = InStr(http.responseText, "/graph/?from=USD&to=ILS") 'find this in the HTML
        If Found <> 0 Then
            Length = Len(http.responseText) - Found 'check the length of the HTML
            strCSV = Right(http.responseText, Length) 'Trim the begining of the String until we get to our value
            strCSV = Left(strCSV, Len(strCSV) - (Len(strCSV) - 36)) 'Trim the end of the string to leave only the value we are looking for
            strCSV = Replace(strCSV, "graph/?from=USD&to=ILS'>", "") 'replace the original search string with nothing so we are left with numbers only
        Else
        CryptoQuote = "Could not find the data!"
        End If
    Else
        MsgBox "Please enter a correct date as yyyy-mm-dd"
    End If
    CryptoQuote = Val(strCSV)
    MsgBox strCSV
End Function
</code>```

答:
If what you want is USD to EUR then this will do the job (not the most elegant way of doing things but it will do the task at hand):</p>

```<code>Public Sub CryptoQuote()
    enteredDate = InputBox("Please enter the search date: ", "Enter Date")
    If IsDate(enteredDate) Then
        enteredDate = Format(enteredDate, "yyyy-mm-dd")
        Dim strURL As String: strURL = "http://www.x-rates.com/historical/?from=USD&amount=1&date=" & enteredDate
        Dim http As Object: Set http = CreateObject("msxml2.xmlhttp")
        http.Open "GET", strURL, False
        http.send
        Dim strCSV As String
        Found = InStr(http.responsetext, "/graph/?from=USD&to=EUR") 'find this in the HTML
        If Found <> 0 Then
            Length = Len(http.responsetext) - Found 'check the length of the HTML
            strCSV = Right(http.responsetext, Length) 'Trim the begining of the String until we get to our value
            strCSV = Left(strCSV, Len(strCSV) - (Len(strCSV) - 36)) 'Trim the end of the string to leave only the value we are looking for
            strCSV = Replace(strCSV, "graph/?from=USD&to=EUR'>", "") 'replace the original search string with nothing so we are left with numbers only
        Else
            MsgBox "Could not find the data!"
        End If
    Else
    MsgBox "Please enter a correct date as yyyy-mm-dd"
    End If
    MsgBox "The rate for 1 USD in EURO is " & strCSV
End Sub
</code>```

Body:
I want to write a date in Excel and get the rate on this date .

I search solutions but not found something that can help me.

I am using Excel 2016.

My code:

Function CryptoQuote(enteredDate As String)
    If IsDate(enteredDate) Then
        enteredDate = Format(Date, "yyyy-mm-dd")
        Dim strURL As String: strURL = "http://www.x-rates.com/historical/?from=USD&amount=1&date=" & enteredDate
        MsgBox strURL
        Dim http As Object: Set http = CreateObject("msxml2.xmlhttp")
        http.Open "GET", strURL, False
        http.Send
        Dim strCSV As String
        Found = InStr(http.responseText, "/graph/?from=USD&to=ILS") 'find this in the HTML
        If Found <> 0 Then
            Length = Len(http.responseText) - Found 'check the length of the HTML
            strCSV = Right(http.responseText, Length) 'Trim the begining of the String until we get to our value
            strCSV = Left(strCSV, Len(strCSV) - (Len(strCSV) - 36)) 'Trim the end of the string to leave only the value we are looking for
            strCSV = Replace(strCSV, "graph/?from=USD&to=ILS'>", "") 'replace the original search string with nothing so we are left with numbers only
        Else
        CryptoQuote = "Could not find the data!"
        End If
    Else
        MsgBox "Please enter a correct date as yyyy-mm-dd"
    End If
    CryptoQuote = Val(strCSV)
    MsgBox strCSV
End Function

Body:
If what you want is USD to EUR then this will do the job (not the most elegant way of doing things but it will do the task at hand):

Public Sub CryptoQuote()
    enteredDate = InputBox("Please enter the search date: ", "Enter Date")
    If IsDate(enteredDate) Then
        enteredDate = Format(enteredDate, "yyyy-mm-dd")
        Dim strURL As String: strURL = "http://www.x-rates.com/historical/?from=USD&amount=1&date=" & enteredDate
        Dim http As Object: Set http = CreateObject("msxml2.xmlhttp")
        http.Open "GET", strURL, False
        http.send
        Dim strCSV As String
        Found = InStr(http.responsetext, "/graph/?from=USD&amp;to=EUR") 'find this in the HTML
        If Found <> 0 Then
            Length = Len(http.responsetext) - Found 'check the length of the HTML
            strCSV = Right(http.responsetext, Length) 'Trim the begining of the String until we get to our value
            strCSV = Left(strCSV, Len(strCSV) - (Len(strCSV) - 36)) 'Trim the end of the string to leave only the value we are looking for
            strCSV = Replace(strCSV, "graph/?from=USD&amp;to=EUR'>", "") 'replace the original search string with nothing so we are left with numbers only
        Else
            MsgBox "Could not find the data!"
        End If
    Else
    MsgBox "Please enter a correct date as yyyy-mm-dd"
    End If
    MsgBox "The rate for 1 USD in EURO is " & strCSV
End Sub


问:
Reading txt in to an array
So I have a txt file formatted like this

Name

Height Litres

Height Litres

Height Litres

Height Litres

Height Litres

Prize

And I have two structures called kennlinie and pumpe

```<code>struct kennlinie {

        int liter;
        int hoehe;

    };

    struct pumpe {

        char name[20];
        kennlinie pkt[5];
        float preis;

    };
</code>```

I have also a variable pumpe pump[9].

pump[i].name should contain the name, pump[i].pkt[j].hoehe the height, pump[i].pkt[j].literthe litres and pump[i].prize the price.

What's the best way to import the data from the txt to an array?

答:
The best method, IMHO, is to have the classes read in their members.  The classes know the member type and quantity.  Research "data hiding" and "encapsulation".

This is accomplished by overloading operator>>.

```<code>class Height_Liters
{
  public:
    friend std::istream& operator>>(std::istream& input, Height_Liters& hl);
  private:
    unsigned int height;
    unsigned int liters;
};
std::istream& operator>>(std::istream& input, Height_Liters& hl)
{
   input >> hl.height;
   input >> hl.liters;
};
</code>```

Now you can do something like this to read a Height Liters row:

```<code>Height_Liters hl;
std::vector<Height_Liters> database;
//...
  my_data_file >> hl;
  database.push_back(hl);
//...
</code>```

However, since there is no indication of how many rows there are, you may want to read it differently:

```<code>std::string name;
unsigned int height;
unsigned int liters;
unsigned int prize;
std::getline(my_data_file, name); // read first row
while (my_data_file >> height)
{
  prize = height; // Just in case
  if (my_data_file >> liters)
  {
    Height_Liters hl(height, liters);
    database.push_back(hl);
  }
}
</code>```

Title: Reading txt in to an array

Body:
So I have a txt file formatted like this

Name

Height Litres

Height Litres

Height Litres

Height Litres

Height Litres

Prize

And I have two structures called kennlinie and pumpe

struct kennlinie {

        int liter;
        int hoehe;

    };

    struct pumpe {

        char name[20];
        kennlinie pkt[5];
        float preis;

    };

I have also a variable pumpe pump[9].

pump[i].name should contain the name, pump[i].pkt[j].hoehe the height, pump[i].pkt[j].literthe litres and pump[i].prize the price.

What's the best way to import the data from the txt to an array?

Body:
The best method, IMHO, is to have the classes read in their members.  The classes know the member type and quantity.  Research "data hiding" and "encapsulation".

This is accomplished by overloading operator>>.

class Height_Liters
{
  public:
    friend std::istream& operator>>(std::istream& input, Height_Liters& hl);
  private:
    unsigned int height;
    unsigned int liters;
};
std::istream& operator>>(std::istream& input, Height_Liters& hl)
{
   input >> hl.height;
   input >> hl.liters;
};

Now you can do something like this to read a Height Liters row:

Height_Liters hl;
std::vector<Height_Liters> database;
//...
  my_data_file >> hl;
  database.push_back(hl);
//...

However, since there is no indication of how many rows there are, you may want to read it differently:

std::string name;
unsigned int height;
unsigned int liters;
unsigned int prize;
std::getline(my_data_file, name); // read first row
while (my_data_file >> height)
{
  prize = height; // Just in case
  if (my_data_file >> liters)
  {
    Height_Liters hl(height, liters);
    database.push_back(hl);
  }
}


问:
Hibernate - can a Java8 Function Object be persisted in database?
I am working on an abstract model to represent a variety of complex business processes based on event registration. For that purpose, I want to be able to persist Java8 Function objects using the newest version of Hibernate, such as

```<code>@Entity
public class Foo {
    private Runnable onUpdate = () -> System.out.println("worked");
    private java.util.function.Function<String, String> identity = s -> s;
    // imagine bean-compliant getter and setter
}
</code>```

Persisting method references is not an option, since partial method application during runtime before setting a callback is a requirement.

Just trying above code leads to the following exception:

    org.hibernate.MappingException: Could not determine type for: java.lang.Runnable ...

Is there any way to persist function objects that match a fixed functional interface such as Runnable? And if not, what alternative strategies are available?

EDIT concerning the XY-problem:

I want to be able to associate methods in an object with some hibernate entity's
PostUpdate callback during runtime, while letting the user supply all arguments which the hibernate callback can not supply. For example, I have an entity @Entity public class Bar and another controller class with a  method void foo(Bar new, int i). Now, every time a specific instance of Bar is updated in the database, I want it to call foo with the updated object and a parameter i, which is specified by the user during current or some previous runtime while associating the foo-Event with the Bar instance.

Most importantly, I want to persist this runtime association using Hibernate, keeping a reference to the method, the object the method belongs to and all parameters supplied during association. Then, on server startup, as soon as the controller object is loaded it listens to changes made to the entity instance.

答:
No

Unfortunately in current versions of Hibernate it is impossible to store Java 8 functions in a database. Lambdas do not implement Serializable and there is no way to make them do so.

Body:
I am working on an abstract model to represent a variety of complex business processes based on event registration. For that purpose, I want to be able to persist Java8 Function objects using the newest version of Hibernate, such as

@Entity
public class Foo {
    private Runnable onUpdate = () -> System.out.println("worked");
    private java.util.function.Function<String, String> identity = s -> s;
    // imagine bean-compliant getter and setter
}

Persisting method references is not an option, since partial method application during runtime before setting a callback is a requirement.

Just trying above code leads to the following exception:

    org.hibernate.MappingException: Could not determine type for: java.lang.Runnable ...

Is there any way to persist function objects that match a fixed functional interface such as Runnable? And if not, what alternative strategies are available?

EDIT concerning the XY-problem:

I want to be able to associate methods in an object with some hibernate entity's
PostUpdate callback during runtime, while letting the user supply all arguments which the hibernate callback can not supply. For example, I have an entity @Entity public class Bar and another controller class with a  method void foo(Bar new, int i). Now, every time a specific instance of Bar is updated in the database, I want it to call foo with the updated object and a parameter i, which is specified by the user during current or some previous runtime while associating the foo-Event with the Bar instance.

Most importantly, I want to persist this runtime association using Hibernate, keeping a reference to the method, the object the method belongs to and all parameters supplied during association. Then, on server startup, as soon as the controller object is loaded it listens to changes made to the entity instance.