问:
Math Class, Methods, and random Numbers (Java)
I am in desperate need for help with a Java Program I need to compete for school! I have been working on this for at least 3 hours for the past 3 days and I can not figure it out.... =( Here are the directions:

Write a program that calls each of the methods of the Math class from the list below and provides output showing the method called, values sent to the method, and the returned results. Each listed method will tell you which values to use. For example:

Listed method:

```<code>double pow(double a, double b): use 2.0 and 3.0.
</code>```

Your program would display:

```<code>Math.pow(2.0, 3.0) = 8.0.
</code>```

When calling a method that accepts doubles, use numbers with at least one decimal digit like the example above, even if it's a zero. Remember that numbers with decimals are double literals. Try to use values that will produce easily verifiable results.

Here is the list:

```<code>double pow(double a, double b): Use 3.0 and 2.0

double sqrt(double x): Use 25.0

int max(int a, int b): Use 6 and 2

double max(double a, double b): Use -50.0 and 7.0

static double random()
</code>```

Sample output:

```<code>Math.pow(3.0, 2.0) = 9.0

Math.sqrt(25.0)=5.0

Math.max(6,2)=6

Math.max(-50.0,7.0)=7.0

Math.random()= /*-random value-*/
</code>```

Test your program with the values shown in the examples, fix any errors.
Add a method to your program called randomStudy that has no parameters and returns no value. In this method, do the following:

a. Declare three int variables: total, min, and max. Set total to 0, min to 11, andmax to -1.

b. Create a loop that will run 1,000 times. In the body of the loop, generate a random int value between 1 and 10, inclusive. Add this number to your total. If this number is less than min, update min with the new number. If it is greater than max, update max with the new number.

c. After the loop, display the following:

Min value: x
Max value: y
Average: z
Replace x and y with your min and max values. Calculate z by dividing your total by 1000d.
Call your new randomStudy method from the main method.
Highlight and copy the output shown in Eclipse. Paste the output at the bottom of your source code file. Add the text Results:above your output, and then comment out the text your just dded plus the output text. Your commented results should look something like this:

```<code>/*

Results:

Math.pow(3.0, 2.0)= 9.0

Math.sqrt(25.0) = 5.0

Math.max(6, 2) = 6

Math.max(-50.0, 7.0) = 7.0

Math.random() = -random number-

Min value: 1

Max value: 10

Average: 5.553

*/
</code>```

So, the problem I am having is with the last part about running the loop 1,000 times and then displaying the largest and smallest number out of the 1,000 numbers. And also displaying the mean of the 1,000 numbers. Here is My code:

```<code> class MathMethodsProgram {

public static void main(String[] args) {
    //      Prints the pow method.

    System.out.println("Math.pow(2.0, 3.0) = " + Math.pow(2.0, 3.0));

   //       Prints the sqrt method

    System.out.println("Math.sqrt(25) = " + Math.sqrt(25));

    //      Prints the max number

    System.out.println("Math.max( 6, 3) = " + Math.max(6, 3));

   //       Prints the max number

    System.out.println("Math.max(-50.0,7.0) = " + Math.max(-50.0, 7.0));

   //       Prints a random number
    System.out.println("Math.random(); = " + Math.random());

    randomStudy();

    }

public static void randomStudy(){
    int total = 0;
    int min = 11;
    int max = -1;
    int newtotal = 0;
    int i;
    int randomInt = 0;

        for( i = 0; i < 1000; i++){
             randomInt = 1 + (int)( Math.random() * 11);

             newtotal = (randomInt + total);

            }
        if (randomInt < min) {
            min = 1 + (int) Math.random();
        } else {
            System.out.println("Min: " + min);
        }

        if (randomInt > max) {
            max = 1 + (int) Math.random();
        } else {
            System.out.println("Max: " + max);
         }

         System.out.println("Min value:" + min);
         System.out.println("Max Value:" + max);
         System.out.println("Average:"+ newtotal / 1000d);
    }

}
</code>```

And when I run the code in Eclipse this is the output:

```<code> Math.pow(2.0, 3.0) = 8.0
Math.sqrt(25) = 5.0
Math.max( 6, 3) = 6
Math.max(-50.0,7.0) = 7.0
Math.random(); = 0.1824716748725944
Min value:1
Max Value:1
Average:0.008
</code>```

Thanks in advance

答:
Here I am going to provide a code that I created. My purpose is to provide you the idea how to create multiple functions equivalent to the ones that we obtain from the Math class. I included comments that help these classes to be self explanatory, I hope this help you. I also include dialog boxes to display data, so it is a good resource if someone is looking for help how to use javax.swing class.

The first class MyMath.java contains the methods used perform all calculations.

```<code>package com.exercise.lecture2;

/**
 * Create a class call "MyMath" that has the following class methods:
 * static boolean isEven(int x) --> returns true is number is even
 * static long absolute(long x) --> returns the absolute value of x
 * static double hypotenuse (double x, double y) --> returns sqrt(x^2 + y^2)
 * static double max (double a, double b) --> returns max of a or b
 * static double min (double a, double b ) --> returns min of a or b
 *
 * @author Samuel
 *
 */
public class MyMath {

    /**
     * An even number is an integer which is "evenly divisible" by two.
     * This means that if the integer is divided by 2, it yields no remainder.
     * Zero is an even number because zero divided by two equals zero, which despite not being a natural number, is an integer.
     * Even numbers can be either positive or negative.
     *
     * @param x
     * @return
     */
    static boolean isEven(int x){
        if (x % 2 == 0)
            return true;
        else
            return false;
    }

    /**
     * In mathematics, the absolute value or modulus of a real number is the number without the sign.
     * The absolute value of 2 is 2, the absolute value of -2 is also 2.
     *
     * @param x
     * @return
     */
    static long absolute(long x) {
        if (x >= 0)
            return x;
        else
            return (-1*x);
    }

    /**
     * The hypotenuse is the side opposite the 90 degrees angle in a right triangle. It is always the longest side.
     *
     * @param x
     * @param y
     * @return
     */
    static double hypotenuse (double x, double y) {
        return Math.sqrt((x * x) + (y * y));
    }

    /**
     * Maximum of two values
     * @param a
     * @param b
     * @return
     */
    static double max (double a, double b) {
        if (a >= b)
            return a;
        else
            return b;
    }

    /**
     * Minimum of two values
     * @param a
     * @param b
     * @return
     */
    static double min (double a, double b ) {
        if (a < b)
            return a;
        else
            return b;
    }

}
</code>```

The second class MathClassTest.java contains javax.swing class in order to display using dialog boxes.

```<code>package com.exercise.lecture2;

import javax.swing.JOptionPane; // importing the javax.swing class in order to use dialog box in my code

/**
 * static boolean isEven(int x) --> returns true is number is even
 * static long absolute(long x) --> returns the absolute value of x
 * static double hypotenuse (double x, double y) --> returns sqrt(x^2 + y^2)
 * static double max (double a, double b) --> returns max of a or b
 * static double min (double a, double b ) --> returns min of a or b
 *
 * Write an application that allows the user to select between the above methods and
 * returns the response to the user.
 *
 * @author Samuel
 *
 */
public class MathClassTest {

    public static void main(String[] args) {

        /* used to test the functions on MyMath.java class, here is how all of this begin
         * then I change it to make this tester use javax.swing class in order to display using
         * dialog boxes.
         *
         // is Even
        System.out.println(MyMath.isEven(-100));

        // Absolute value of an integer
        System.out.println(MyMath.absolute(-10));

        // Hypotenuse of two values
        System.out.println(MyMath.hypotenuse(3, 4));

        // Max of two values
        System.out.println(MyMath.max(3, -4));

        // Min of two values
        System.out.println(MyMath.min(3, -4));

        */

        boolean repeat;
        do {
            //String name = JOptionPane.showInputDialog(null, "Enter your name", "Enter name", JOptionPane.PLAIN_MESSAGE);
            String option = JOptionPane.showInputDialog(null,"Choose 'a' or 'A' to determine if a number is EVEN or not. \n" // options
                    + "Choose 'b' or 'B' to determine the ABSOLUTE value of a number. \n" // the (+) sign concatenate the all of the followings Strings as one
                    + "Choose 'c' or 'C' to determine the HYPOTENUSE of two values. \n"
                    + "Choose 'd' or 'D' to determine the MAXIMUM of two values. \n"
                    + "Choose 'e' or 'E' to determine the MINIMUM of two values. \n"
                    + "Choose 'q' or 'Q' to quit this simple application. \n\n"
                    , "My Math class, by S. Mayol", JOptionPane.QUESTION_MESSAGE); // title bar of the dialog box
            repeat = true;

            if (option.equals("Q") || option.equals("q")) {
                JOptionPane.showMessageDialog(null, "Thank you for participating...", "by Samuel Mayol", JOptionPane.INFORMATION_MESSAGE);
                repeat = false;
                System.exit(0);
            } else {
                if (option.equals("A")||option.equals("a")){
                    try { // to prevent that the value inserted is an integer and not a letter
                        String val = JOptionPane.showInputDialog("Enter a number to deternine if the number is even");
                        JOptionPane.showMessageDialog(null, "Is the number " + val + " even? " + MyMath.isEven(Integer.valueOf(val)),
                                "Even", JOptionPane.INFORMATION_MESSAGE); // add a title message on a dialog box
                        repeat = true;
                    } catch(Exception e){
                        JOptionPane.showMessageDialog(null, "The input " + option + " is not valid integer, please try again", "WARNING!!!",
                                JOptionPane.WARNING_MESSAGE);
                    }
                }
                else if (option.equals("B")||option.equals("b")){
                    try {
                        String val = JOptionPane.showInputDialog("Enter a number to calculate absolute value of that number");
                        JOptionPane.showMessageDialog(null, "The absolute value of " + val + " is: " + MyMath.absolute(Long.valueOf(val)),
                                "Absolute", JOptionPane.INFORMATION_MESSAGE);
                        repeat = true;
                    } catch(Exception e){
                        JOptionPane.showMessageDialog(null, "The input " + option + " is not valid integer, please try again", "WARNING!!!",
                                JOptionPane.WARNING_MESSAGE);
                    }
                }
                else if (option.equals("C")||option.equals("c")){
                    try {
                        String val = JOptionPane.showInputDialog("Enter the first side to calculate the hypotenuse");
                        String val2 = JOptionPane.showInputDialog("Enter the second side to calculate the hypotenuse");
                        JOptionPane.showMessageDialog(null, "The hypotenuse of " + val + " and " + val2 + " is: " + MyMath.hypotenuse(Double.valueOf(val), Double.valueOf(val2)),
                                "Hypotenuse", JOptionPane.INFORMATION_MESSAGE);
                        repeat = true;
                    } catch(Exception e){
                        JOptionPane.showMessageDialog(null, "The any of the inputs " + option + " are not valid integer, please try again", "WARNING!!!",
                                JOptionPane.WARNING_MESSAGE);
                    }
                }
                else if (option.equals("D")||option.equals("d")){
                    try {
                        String val = JOptionPane.showInputDialog("Enter the first number to calculate the max value");
                        String val2 = JOptionPane.showInputDialog("Enter the second number to calculate the max value");
                        JOptionPane.showMessageDialog(null, "The max of " + val + " and " + val2 + " is: " + MyMath.max(Double.valueOf(val), Double.valueOf(val2)),
                                "Maximum", JOptionPane.INFORMATION_MESSAGE);
                        repeat = true;
                    } catch(Exception e){
                        JOptionPane.showMessageDialog(null, "The any of the inputs " + option + " are not valid integer, please try again", "WARNING!!!",
                                JOptionPane.WARNING_MESSAGE);
                    }
                }
                else if (option.equals("E")||option.equals("e")){
                    try {
                        String val = JOptionPane.showInputDialog("Enter the first number to calculate the min value");
                        String val2 = JOptionPane.showInputDialog("Enter the second number to calculate the min value");
                        JOptionPane.showMessageDialog(null, "The min of " + val + " and " + val2 + " is: " + MyMath.min(Double.valueOf(val), Double.valueOf(val2)),
                                "Minimum", JOptionPane.INFORMATION_MESSAGE);
                        repeat = true;
                    } catch(Exception e){
                        JOptionPane.showMessageDialog(null, "The any of the inputs " + option + " are not valid integer, please try again", "WARNING!!!",
                                JOptionPane.WARNING_MESSAGE);
                    }
                }
                else
                    JOptionPane.showMessageDialog(null, "The input " + option + " is not valid, please try again", "A, B, C, D, E, or Q",
                        JOptionPane.WARNING_MESSAGE);
            }
        } while(repeat);
    }

}
</code>```

Body:
I am in desperate need for help with a Java Program I need to compete for school! I have been working on this for at least 3 hours for the past 3 days and I can not figure it out.... =( Here are the directions:

Write a program that calls each of the methods of the Math class from the list below and provides output showing the method called, values sent to the method, and the returned results. Each listed method will tell you which values to use. For example:

Listed method:

double pow(double a, double b): use 2.0 and 3.0.

Your program would display:

Math.pow(2.0, 3.0) = 8.0.

When calling a method that accepts doubles, use numbers with at least one decimal digit like the example above, even if it's a zero. Remember that numbers with decimals are double literals. Try to use values that will produce easily verifiable results.

Here is the list:

double pow(double a, double b): Use 3.0 and 2.0

double sqrt(double x): Use 25.0

int max(int a, int b): Use 6 and 2

double max(double a, double b): Use -50.0 and 7.0

static double random()

Sample output:

Math.pow(3.0, 2.0) = 9.0

Math.sqrt(25.0)=5.0

Math.max(6,2)=6

Math.max(-50.0,7.0)=7.0

Math.random()= /*-random value-*/

Test your program with the values shown in the examples, fix any errors.
Add a method to your program called randomStudy that has no parameters and returns no value. In this method, do the following:

a. Declare three int variables: total, min, and max. Set total to 0, min to 11, andmax to -1.

b. Create a loop that will run 1,000 times. In the body of the loop, generate a random int value between 1 and 10, inclusive. Add this number to your total. If this number is less than min, update min with the new number. If it is greater than max, update max with the new number.

c. After the loop, display the following:

Min value: x
Max value: y
Average: z
Replace x and y with your min and max values. Calculate z by dividing your total by 1000d.
Call your new randomStudy method from the main method.
Highlight and copy the output shown in Eclipse. Paste the output at the bottom of your source code file. Add the text Results:above your output, and then comment out the text your just dded plus the output text. Your commented results should look something like this:

/*

Results:

Math.pow(3.0, 2.0)= 9.0

Math.sqrt(25.0) = 5.0

Math.max(6, 2) = 6

Math.max(-50.0, 7.0) = 7.0

Math.random() = -random number-

Min value: 1

Max value: 10

Average: 5.553

*/

So, the problem I am having is with the last part about running the loop 1,000 times and then displaying the largest and smallest number out of the 1,000 numbers. And also displaying the mean of the 1,000 numbers. Here is My code:

 class MathMethodsProgram {

public static void main(String[] args) {
    //      Prints the pow method.

    System.out.println("Math.pow(2.0, 3.0) = " + Math.pow(2.0, 3.0));

   //       Prints the sqrt method

    System.out.println("Math.sqrt(25) = " + Math.sqrt(25));

    //      Prints the max number

    System.out.println("Math.max( 6, 3) = " + Math.max(6, 3));

   //       Prints the max number

    System.out.println("Math.max(-50.0,7.0) = " + Math.max(-50.0, 7.0));

   //       Prints a random number
    System.out.println("Math.random(); = " + Math.random());

    randomStudy();

    }

public static void randomStudy(){
    int total = 0;
    int min = 11;
    int max = -1;
    int newtotal = 0;
    int i;
    int randomInt = 0;

        for( i = 0; i < 1000; i++){
             randomInt = 1 + (int)( Math.random() * 11);

             newtotal = (randomInt + total);

            }
        if (randomInt < min) {
            min = 1 + (int) Math.random();
        } else {
            System.out.println("Min: " + min);
        }

        if (randomInt > max) {
            max = 1 + (int) Math.random();
        } else {
            System.out.println("Max: " + max);
         }

         System.out.println("Min value:" + min);
         System.out.println("Max Value:" + max);
         System.out.println("Average:"+ newtotal / 1000d);
    }

}

And when I run the code in Eclipse this is the output:

 Math.pow(2.0, 3.0) = 8.0
Math.sqrt(25) = 5.0
Math.max( 6, 3) = 6
Math.max(-50.0,7.0) = 7.0
Math.random(); = 0.1824716748725944
Min value:1
Max Value:1
Average:0.008

Thanks in advance

Body:
Here I am going to provide a code that I created. My purpose is to provide you the idea how to create multiple functions equivalent to the ones that we obtain from the Math class. I included comments that help these classes to be self explanatory, I hope this help you. I also include dialog boxes to display data, so it is a good resource if someone is looking for help how to use javax.swing class.

The first class MyMath.java contains the methods used perform all calculations.

package com.exercise.lecture2;

/**
 * Create a class call "MyMath" that has the following class methods:
 * static boolean isEven(int x) --> returns true is number is even
 * static long absolute(long x) --> returns the absolute value of x
 * static double hypotenuse (double x, double y) --> returns sqrt(x^2 + y^2)
 * static double max (double a, double b) --> returns max of a or b
 * static double min (double a, double b ) --> returns min of a or b
 *
 * @author Samuel
 *
 */
public class MyMath {

    /**
     * An even number is an integer which is "evenly divisible" by two.
     * This means that if the integer is divided by 2, it yields no remainder.
     * Zero is an even number because zero divided by two equals zero, which despite not being a natural number, is an integer.
     * Even numbers can be either positive or negative.
     *
     * @param x
     * @return
     */
    static boolean isEven(int x){
        if (x % 2 == 0)
            return true;
        else
            return false;
    }

    /**
     * In mathematics, the absolute value or modulus of a real number is the number without the sign.
     * The absolute value of 2 is 2, the absolute value of -2 is also 2.
     *
     * @param x
     * @return
     */
    static long absolute(long x) {
        if (x >= 0)
            return x;
        else
            return (-1*x);
    }

    /**
     * The hypotenuse is the side opposite the 90 degrees angle in a right triangle. It is always the longest side.
     *
     * @param x
     * @param y
     * @return
     */
    static double hypotenuse (double x, double y) {
        return Math.sqrt((x * x) + (y * y));
    }

    /**
     * Maximum of two values
     * @param a
     * @param b
     * @return
     */
    static double max (double a, double b) {
        if (a >= b)
            return a;
        else
            return b;
    }

    /**
     * Minimum of two values
     * @param a
     * @param b
     * @return
     */
    static double min (double a, double b ) {
        if (a < b)
            return a;
        else
            return b;
    }

}

The second class MathClassTest.java contains javax.swing class in order to display using dialog boxes.

package com.exercise.lecture2;

import javax.swing.JOptionPane; // importing the javax.swing class in order to use dialog box in my code

/**
 * static boolean isEven(int x) --> returns true is number is even
 * static long absolute(long x) --> returns the absolute value of x
 * static double hypotenuse (double x, double y) --> returns sqrt(x^2 + y^2)
 * static double max (double a, double b) --> returns max of a or b
 * static double min (double a, double b ) --> returns min of a or b
 *
 * Write an application that allows the user to select between the above methods and
 * returns the response to the user.
 *
 * @author Samuel
 *
 */
public class MathClassTest {

    public static void main(String[] args) {

        /* used to test the functions on MyMath.java class, here is how all of this begin
         * then I change it to make this tester use javax.swing class in order to display using
         * dialog boxes.
         *
         // is Even
        System.out.println(MyMath.isEven(-100));

        // Absolute value of an integer
        System.out.println(MyMath.absolute(-10));

        // Hypotenuse of two values
        System.out.println(MyMath.hypotenuse(3, 4));

        // Max of two values
        System.out.println(MyMath.max(3, -4));

        // Min of two values
        System.out.println(MyMath.min(3, -4));

        */

        boolean repeat;
        do {
            //String name = JOptionPane.showInputDialog(null, "Enter your name", "Enter name", JOptionPane.PLAIN_MESSAGE);
            String option = JOptionPane.showInputDialog(null,"Choose 'a' or 'A' to determine if a number is EVEN or not. \n" // options
                    + "Choose 'b' or 'B' to determine the ABSOLUTE value of a number. \n" // the (+) sign concatenate the all of the followings Strings as one
                    + "Choose 'c' or 'C' to determine the HYPOTENUSE of two values. \n"
                    + "Choose 'd' or 'D' to determine the MAXIMUM of two values. \n"
                    + "Choose 'e' or 'E' to determine the MINIMUM of two values. \n"
                    + "Choose 'q' or 'Q' to quit this simple application. \n\n"
                    , "My Math class, by S. Mayol", JOptionPane.QUESTION_MESSAGE); // title bar of the dialog box
            repeat = true;

            if (option.equals("Q") || option.equals("q")) {
                JOptionPane.showMessageDialog(null, "Thank you for participating...", "by Samuel Mayol", JOptionPane.INFORMATION_MESSAGE);
                repeat = false;
                System.exit(0);
            } else {
                if (option.equals("A")||option.equals("a")){
                    try { // to prevent that the value inserted is an integer and not a letter
                        String val = JOptionPane.showInputDialog("Enter a number to deternine if the number is even");
                        JOptionPane.showMessageDialog(null, "Is the number " + val + " even? " + MyMath.isEven(Integer.valueOf(val)),
                                "Even", JOptionPane.INFORMATION_MESSAGE); // add a title message on a dialog box
                        repeat = true;
                    } catch(Exception e){
                        JOptionPane.showMessageDialog(null, "The input " + option + " is not valid integer, please try again", "WARNING!!!",
                                JOptionPane.WARNING_MESSAGE);
                    }
                }
                else if (option.equals("B")||option.equals("b")){
                    try {
                        String val = JOptionPane.showInputDialog("Enter a number to calculate absolute value of that number");
                        JOptionPane.showMessageDialog(null, "The absolute value of " + val + " is: " + MyMath.absolute(Long.valueOf(val)),
                                "Absolute", JOptionPane.INFORMATION_MESSAGE);
                        repeat = true;
                    } catch(Exception e){
                        JOptionPane.showMessageDialog(null, "The input " + option + " is not valid integer, please try again", "WARNING!!!",
                                JOptionPane.WARNING_MESSAGE);
                    }
                }
                else if (option.equals("C")||option.equals("c")){
                    try {
                        String val = JOptionPane.showInputDialog("Enter the first side to calculate the hypotenuse");
                        String val2 = JOptionPane.showInputDialog("Enter the second side to calculate the hypotenuse");
                        JOptionPane.showMessageDialog(null, "The hypotenuse of " + val + " and " + val2 + " is: " + MyMath.hypotenuse(Double.valueOf(val), Double.valueOf(val2)),
                                "Hypotenuse", JOptionPane.INFORMATION_MESSAGE);
                        repeat = true;
                    } catch(Exception e){
                        JOptionPane.showMessageDialog(null, "The any of the inputs " + option + " are not valid integer, please try again", "WARNING!!!",
                                JOptionPane.WARNING_MESSAGE);
                    }
                }
                else if (option.equals("D")||option.equals("d")){
                    try {
                        String val = JOptionPane.showInputDialog("Enter the first number to calculate the max value");
                        String val2 = JOptionPane.showInputDialog("Enter the second number to calculate the max value");
                        JOptionPane.showMessageDialog(null, "The max of " + val + " and " + val2 + " is: " + MyMath.max(Double.valueOf(val), Double.valueOf(val2)),
                                "Maximum", JOptionPane.INFORMATION_MESSAGE);
                        repeat = true;
                    } catch(Exception e){
                        JOptionPane.showMessageDialog(null, "The any of the inputs " + option + " are not valid integer, please try again", "WARNING!!!",
                                JOptionPane.WARNING_MESSAGE);
                    }
                }
                else if (option.equals("E")||option.equals("e")){
                    try {
                        String val = JOptionPane.showInputDialog("Enter the first number to calculate the min value");
                        String val2 = JOptionPane.showInputDialog("Enter the second number to calculate the min value");
                        JOptionPane.showMessageDialog(null, "The min of " + val + " and " + val2 + " is: " + MyMath.min(Double.valueOf(val), Double.valueOf(val2)),
                                "Minimum", JOptionPane.INFORMATION_MESSAGE);
                        repeat = true;
                    } catch(Exception e){
                        JOptionPane.showMessageDialog(null, "The any of the inputs " + option + " are not valid integer, please try again", "WARNING!!!",
                                JOptionPane.WARNING_MESSAGE);
                    }
                }
                else
                    JOptionPane.showMessageDialog(null, "The input " + option + " is not valid, please try again", "A, B, C, D, E, or Q",
                        JOptionPane.WARNING_MESSAGE);
            }
        } while(repeat);
    }

}


来源: stackexchange

问:
Regex to Match Hashtags in string that contain no more than 1 space
What I'm looking to do is match hashtags in a string, but the hashtag may have a space in it: #brown fox. Most hashtags are single words, #brown, #fox, but some were improperly formatted and resulted in spaces being entered.

The hashtags that have spaces are only allowed to be two words, so #space suit is allowed, but #brown fox jumps is not allowed.

The quick #brown #fox #jumps over the lazy dog.

brown, fox, jumps

The quick #brown fox #jumps over the lazy dog.

brown fox, jumps

The quick #brown fox #jumps over the lazy #dog.

brown fox, jumps, dog

If there is a hashtag, followed by one word, then followed by a hashtag, then we can assume the word is for that hashtag. Otherwise, we shouldn't capture it in the group.

Here is what I've tried so far, but clearly it's nowhere close to what I need:
https://regex101.com/r/vHOCaf/1

```<code>(\#+\w{2,})|(\#([\w]){2,}\s{0,1}([\w]){2,})
</code>```

答:
I think this is what you want: /#(?:\w+\b)(?: ?\w*\b)/g, it will match at most 2 words after # or only one if the second word has a # also.

See it working here: https://regex101.com/r/Bq0qNM/2

[EDIT] change regex to not match a second word if there is no # after it:

/#(?:(?:\w+\b \w+\b)(?= #|$)|\w+\b)/g

See result here: https://regex101.com/r/Bq0qNM/3

[EDIT] a shorter one
/#(?:\w+ ?\w+(?= #|$)|\w+\b)/g, https://regex101.com/r/Bq0qNM/4

ContentLicense: CC BY-SA 3.0

Body:
What I'm looking to do is match hashtags in a string, but the hashtag may have a space in it: #brown fox. Most hashtags are single words, #brown, #fox, but some were improperly formatted and resulted in spaces being entered.

The hashtags that have spaces are only allowed to be two words, so #space suit is allowed, but #brown fox jumps is not allowed.

The quick #brown #fox #jumps over the lazy dog.

brown, fox, jumps

The quick #brown fox #jumps over the lazy dog.

brown fox, jumps

The quick #brown fox #jumps over the lazy #dog.

brown fox, jumps, dog

If there is a hashtag, followed by one word, then followed by a hashtag, then we can assume the word is for that hashtag. Otherwise, we shouldn't capture it in the group.

Here is what I've tried so far, but clearly it's nowhere close to what I need:
https://regex101.com/r/vHOCaf/1

(\#+\w{2,})|(\#([\w]){2,}\s{0,1}([\w]){2,})


问:
Table-valued function refresh
I have a table-valued function (TVF) in SQL Server that looks like this:

```<code>CREATE FUNCTION TVF_xyz(@AuditKey INT)
RETURNS TABLE
AS
    RETURN
        SELECT *
        FROM xyz
        WHERE AUDIT_KEY = @AuditKey
GO
</code>```

Now, I added a new column to the xyz table.

When I query using TVF_xyz, it doesn't show me the new column (shows all other columns except newly added).

Query:

```<code>SELECT TOP 10 *
FROM TVF_xyz (1543)
</code>```

I would like to know, how to refresh TVF to show new column.

PS: Select * used in TVF to fetch all columns.

答:
https://msdn.microsoft.com/en-us/library/bb386954(v=vs.110).aspx

The following SQL function explicitly states that it returns a TABLE. Therefore, the returned rowset structure is implicitly defined.

sample

```<code>CREATE FUNCTION ProductsCostingMoreThan(@cost money)
RETURNS TABLE
AS
RETURN
    SELECT ProductID, UnitPrice
    FROM Products
    WHERE UnitPrice > @cost
</code>```

Title: Table-valued function refresh

Body:
I have a table-valued function (TVF) in SQL Server that looks like this:

CREATE FUNCTION TVF_xyz(@AuditKey INT)
RETURNS TABLE
AS
    RETURN
        SELECT *
        FROM xyz
        WHERE AUDIT_KEY = @AuditKey
GO

Now, I added a new column to the xyz table.

When I query using TVF_xyz, it doesn't show me the new column (shows all other columns except newly added).

Query:

SELECT TOP 10 *
FROM TVF_xyz (1543)

I would like to know, how to refresh TVF to show new column.

PS: Select * used in TVF to fetch all columns.

Body:
https://msdn.microsoft.com/en-us/library/bb386954(v=vs.110).aspx

The following SQL function explicitly states that it returns a TABLE. Therefore, the returned rowset structure is implicitly defined.

sample

CREATE FUNCTION ProductsCostingMoreThan(@cost money)
RETURNS TABLE
AS
RETURN
    SELECT ProductID, UnitPrice
    FROM Products
    WHERE UnitPrice > @cost


问:
TypeError: ufunc 'subtract' did not contain a loop with signature matching types dtype('<U1') dtype('<U1') dtype('<U1')
Strange error from numpy via matplotlib when trying to get a histogram of a tiny toy dataset. I'm just not sure how to interpret the error, which makes it hard to see what to do next.

Didn't find much related, though this nltk question and this gdsCAD question are superficially similar.

I intend the debugging info at bottom to be more helpful than the driver code, but if I've missed something, please ask. This is reproducible as part of an existing test suite.

```<code>        if n > 1:
            return diff(a[slice1]-a[slice2], n-1, axis=axis)
        else:
>           return a[slice1]-a[slice2]
E           TypeError: ufunc 'subtract' did not contain a loop with signature matching types dtype('<U1') dtype('<U1') dtype('<U1')

../py2.7.11-venv/lib/python2.7/site-packages/numpy/lib/function_base.py:1567: TypeError
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> entering PDB >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
> py2.7.11-venv/lib/python2.7/site-packages/numpy/lib/function_base.py(1567)diff()
-> return a[slice1]-a[slice2]
(Pdb) bt
[...]
py2.7.11-venv/lib/python2.7/site-packages/matplotlib/axes/_axes.py(5678)hist()
-> m, bins = np.histogram(x[i], bins, weights=w[i], **hist_kwargs)
  py2.7.11-venv/lib/python2.7/site-packages/numpy/lib/function_base.py(606)histogram()
-> if (np.diff(bins) < 0).any():
> py2.7.11-venv/lib/python2.7/site-packages/numpy/lib/function_base.py(1567)diff()
-> return a[slice1]-a[slice2]
(Pdb) p numpy.__version__
'1.11.0'
(Pdb) p matplotlib.__version__
'1.4.3'
(Pdb) a
a = [u'A' u'B' u'C' u'D' u'E']
n = 1
axis = -1
(Pdb) p slice1
(slice(1, None, None),)
(Pdb) p slice2
(slice(None, -1, None),)
(Pdb)
</code>```

答:
I had a similar issue where an integer in a row of a DataFrame I was iterating over was of type numpy.int64.  I got the

TypeError: ufunc 'subtract' did not contain a loop with signature matching types dtype('<U1') dtype('<U1') dtype('<U1')

error when trying to subtract a float from it.

The easiest fix for me was to convert the row using pd.to_numeric(row).

Body:
Strange error from numpy via matplotlib when trying to get a histogram of a tiny toy dataset. I'm just not sure how to interpret the error, which makes it hard to see what to do next.

Didn't find much related, though this nltk question and this gdsCAD question are superficially similar.

I intend the debugging info at bottom to be more helpful than the driver code, but if I've missed something, please ask. This is reproducible as part of an existing test suite.

        if n > 1:
            return diff(a[slice1]-a[slice2], n-1, axis=axis)
        else:
>           return a[slice1]-a[slice2]
E           TypeError: ufunc 'subtract' did not contain a loop with signature matching types dtype('<U1') dtype('<U1') dtype('<U1')

../py2.7.11-venv/lib/python2.7/site-packages/numpy/lib/function_base.py:1567: TypeError
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> entering PDB >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
> py2.7.11-venv/lib/python2.7/site-packages/numpy/lib/function_base.py(1567)diff()
-> return a[slice1]-a[slice2]
(Pdb) bt
[...]
py2.7.11-venv/lib/python2.7/site-packages/matplotlib/axes/_axes.py(5678)hist()
-> m, bins = np.histogram(x[i], bins, weights=w[i], **hist_kwargs)
  py2.7.11-venv/lib/python2.7/site-packages/numpy/lib/function_base.py(606)histogram()
-> if (np.diff(bins) < 0).any():
> py2.7.11-venv/lib/python2.7/site-packages/numpy/lib/function_base.py(1567)diff()
-> return a[slice1]-a[slice2]
(Pdb) p numpy.__version__
'1.11.0'
(Pdb) p matplotlib.__version__
'1.4.3'
(Pdb) a
a = [u'A' u'B' u'C' u'D' u'E']
n = 1
axis = -1
(Pdb) p slice1
(slice(1, None, None),)
(Pdb) p slice2
(slice(None, -1, None),)
(Pdb)

ContentLicense: CC BY-SA 4.0


问:
Merging two json (deep nested)
I tried to merge two json both with $.extend and $.merge but no success. I also tried to attach it like this:

```<code>data: JSON.stringify({"data" : [
    {term: request.term},
    jsontag
]}),
</code>```

Here's my setup:

```<code>autocomplete: ({
    source: function (request, response) {
        var tags = $('#input-newsearch-2').val();
        var jsonfied = {
            tags: tags.replace(/,$/, "").split(",").map(function (tag) {
                return { tag: tag };
            })
        };
        var jsontag = JSON.stringify(jsonfied);
        var jsonterm = JSON.stringify({ term: request.term });
    //console.log(jsontag);
    //console.log(jsonterm);
    //var mergedObj = $.extend(jsontag, jsonterm);
    //console.log(mergedObj);
    $.ajax({
        url: "/source",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: [jsontag, jsonterm],
        success: function (data) {
            response(data);
        }
    });
},
});
</code>```

Console:

```<code>{"tags":[{"tag":"value01"},{"tag":"value02"},{"tag":"value03"}]}
{"term":"value04"}
</code>```

I was hoping to get sth like:

```<code>[{"term":"value04"},{"tags":[{"tag":"value01"},{"tag":"value02"},{"tag":"value03"}]}]
</code>```

Or even better:

```<code>{"data":[{"term":"value04"},{"tags":[{"tag":"value01"},{"tag":"value02"},{"tag":"value03"}]}]}
</code>```

答:
You can simply do this, and achieve what you desire.

```<code>const mergedJSON = {data: []};

mergedJSON.data.push(jsonterm);
mergedJSON.data.push(jsontag);

console.log(JSON.stringify(mergedJSON));
</code>```

And output will be

```<code>{"data":[{"term":"value04"},{"tags":[{"tag":"value01"},{"tag":"value02"},{"tag":"value03"}]}]}
</code>```

Which fits your even better scenario. Check this jsFiddle for demo.

Title: Merging two json (deep nested)

Body:
I tried to merge two json both with $.extend and $.merge but no success. I also tried to attach it like this:

data: JSON.stringify({"data" : [
    {term: request.term},
    jsontag
]}),

Here's my setup:

autocomplete: ({
    source: function (request, response) {
        var tags = $('#input-newsearch-2').val();
        var jsonfied = {
            tags: tags.replace(/,$/, "").split(",").map(function (tag) {
                return { tag: tag };
            })
        };
        var jsontag = JSON.stringify(jsonfied);
        var jsonterm = JSON.stringify({ term: request.term });
    //console.log(jsontag);
    //console.log(jsonterm);
    //var mergedObj = $.extend(jsontag, jsonterm);
    //console.log(mergedObj);
    $.ajax({
        url: "/source",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: [jsontag, jsonterm],
        success: function (data) {
            response(data);
        }
    });
},
});

Console:

{"tags":[{"tag":"value01"},{"tag":"value02"},{"tag":"value03"}]}
{"term":"value04"}

I was hoping to get sth like:

[{"term":"value04"},{"tags":[{"tag":"value01"},{"tag":"value02"},{"tag":"value03"}]}]

Or even better:

{"data":[{"term":"value04"},{"tags":[{"tag":"value01"},{"tag":"value02"},{"tag":"value03"}]}]}

Body:
You can simply do this, and achieve what you desire.

const mergedJSON = {data: []};

mergedJSON.data.push(jsonterm);
mergedJSON.data.push(jsontag);

console.log(JSON.stringify(mergedJSON));

And output will be

{"data":[{"term":"value04"},{"tags":[{"tag":"value01"},{"tag":"value02"},{"tag":"value03"}]}]}

Which fits your even better scenario. Check this jsFiddle for demo.


问:
R: Apply to slices of an array and return an array
I want to find the simplest way to apply a function across slices of an array, where each application of the function returns a matrix, and receive a sensible array object as the final answer.

I feel like there should be a simple way to do this with apply function, but I feel like I need a simplify = 'array' option, which would be super convenient. The closest I get is this:

```<code>dims = c(2,3,10,4,5)
arr = array(runif(prod(dims)),dim = dims, dimnames =
          list(
            paste0('a',1:dims[1]),
            paste0('b',1:dims[2]),
            paste0('c',1:dims[3]),
            paste0('d',1:dims[4]),
            paste0('e',1:dims[5])
          ))

result = apply(arr, c(4,5), function(x) apply(x, c(3), function(y) (y - y[,1])^2 ) )
</code>```

The result should be an array with dimension c(2,3,10,4,5) or some permutation thereof.

I could get to the right form by calling as.array on result with the appropriate dimensions, but there should be an easier way that preserves the dimnames automatically.

答:
This can be done with the aaply function in plyr package. This is one of several apply functions in this package, where the naming convention is that aa in aaply stands for array to array.

```<code>dims = c(2,3,10,4,5)
arr = array(runif(prod(dims)),dim = dims, dimnames =
          list(
            paste0('a',1:dims[1]),
            paste0('b',1:dims[2]),
            paste0('c',1:dims[3]),
            paste0('d',1:dims[4]),
            paste0('e',1:dims[5])
          ))

aresult = (aaply(arr, c(4,5), function(x) aaply(x, c(3), function(y) (y - y[,1])^2 ) ) )
result = aperm(abind(aresult), c(4,5,3,1,2))
</code>```

Body:
I want to find the simplest way to apply a function across slices of an array, where each application of the function returns a matrix, and receive a sensible array object as the final answer.

I feel like there should be a simple way to do this with apply function, but I feel like I need a simplify = 'array' option, which would be super convenient. The closest I get is this:

dims = c(2,3,10,4,5)
arr = array(runif(prod(dims)),dim = dims, dimnames =
          list(
            paste0('a',1:dims[1]),
            paste0('b',1:dims[2]),
            paste0('c',1:dims[3]),
            paste0('d',1:dims[4]),
            paste0('e',1:dims[5])
          ))

result = apply(arr, c(4,5), function(x) apply(x, c(3), function(y) (y - y[,1])^2 ) )

The result should be an array with dimension c(2,3,10,4,5) or some permutation thereof.

I could get to the right form by calling as.array on result with the appropriate dimensions, but there should be an easier way that preserves the dimnames automatically.

Body:
This can be done with the aaply function in plyr package. This is one of several apply functions in this package, where the naming convention is that aa in aaply stands for array to array.

dims = c(2,3,10,4,5)
arr = array(runif(prod(dims)),dim = dims, dimnames =
          list(
            paste0('a',1:dims[1]),
            paste0('b',1:dims[2]),
            paste0('c',1:dims[3]),
            paste0('d',1:dims[4]),
            paste0('e',1:dims[5])
          ))

aresult = (aaply(arr, c(4,5), function(x) aaply(x, c(3), function(y) (y - y[,1])^2 ) ) )
result = aperm(abind(aresult), c(4,5,3,1,2))


问:
Array in Controller laravel
Can anyone help me to fix my code ? i've the concept but dont know how to write them into code in controller

```<code>$temp=DB::table('temporary')->get();

    //dd($temp);
    if($temp['tahun'] < 'current year'){
        $temp['tahun'] = 'current year';
        $temp['nomor'] = 'nomor+1';
        $keluhan->no_laporan = $temp['nomor'];
    } else {
        $temp['nomor']++;
    }
</code>```

Condition :
my table temporary has 2 attribute tahun(value=2017 int) and nomor (value=1 int)
i want to check if my tahun < this current year (real time year, idk the code so i write current year) then my tahun become = this curent year AND my nomor++ (+1 from its value first) how do i wrte them into laravel code ? please kindly help, thank you buddy

答:
$temp=DB::table('temporary')->get(); will get a collection. so you have to  loop. and Use Carbon to get the date.

```<code>foreach($temp as $temp)
{
  if($temp->tahun < Carbon\Carbon::now()->year){
    {
      $temp->tahun=Carbon\Carbon::now()->year;
      $temp->nomor=$temp->nomor+1;
      $temp->update();
     }
   else
    {
       $temp->nomor=$temp->nomor+1;
       $temp->update();
    }
}
</code>```

Title: Array in Controller laravel

Body:
Can anyone help me to fix my code ? i've the concept but dont know how to write them into code in controller

$temp=DB::table('temporary')->get();

    //dd($temp);
    if($temp['tahun'] < 'current year'){
        $temp['tahun'] = 'current year';
        $temp['nomor'] = 'nomor+1';
        $keluhan->no_laporan = $temp['nomor'];
    } else {
        $temp['nomor']++;
    }

Condition :
my table temporary has 2 attribute tahun(value=2017 int) and nomor (value=1 int)
i want to check if my tahun < this current year (real time year, idk the code so i write current year) then my tahun become = this curent year AND my nomor++ (+1 from its value first) how do i wrte them into laravel code ? please kindly help, thank you buddy

Body:
$temp=DB::table('temporary')->get(); will get a collection. so you have to  loop. and Use Carbon to get the date.

foreach($temp as $temp)
{
  if($temp->tahun < Carbon\Carbon::now()->year){
    {
      $temp->tahun=Carbon\Carbon::now()->year;
      $temp->nomor=$temp->nomor+1;
      $temp->update();
     }
   else
    {
       $temp->nomor=$temp->nomor+1;
       $temp->update();
    }
}


问:
Converting Excel formula into Python script for ArcGIS
I have some fields that I need to bring together, average and then recategorize them so that I can rate them. I'm be doing this in ArcGIS.

I know how to do this in Excel in a two-step process:

1.

```<code>=(Field1 + Field2 + Field3)/3
</code>```

2.

```<code>=IF([@[Field4]]>=10,3,IF([@[Field4]]>=5,2,IF([@[Field4]]>=0,1,IF([@[Field4]]=#N/A*,Null))))
</code>```

There are fields that will have Null values.

The other formula needs to convert string (ranges) to a number, i.e. 0-5 = 1, then 6-10 = 2, etc.

Then I would use the previous to calculate what I need to do for those objects.

答:
First I would suggest to use pandas library to do the data handling with read_csv function.

For the first step you can do it with the mean function.

For the second step :

```<code>df['field 4'].loc[df['field 4']>=10]=3
df['field 4'].loc[(df['field 4']>=5) & (df['fiel 4']<10)]=2
df['field 4'].loc[(df['field 4']>=0) & (df['field 4']<5)]=1
df['field 4'].fillna(None)
</code>```

Body:
I have some fields that I need to bring together, average and then recategorize them so that I can rate them. I'm be doing this in ArcGIS.

I know how to do this in Excel in a two-step process:

1.

=(Field1 + Field2 + Field3)/3

2.

=IF([@[Field4]]>=10,3,IF([@[Field4]]>=5,2,IF([@[Field4]]>=0,1,IF([@[Field4]]=#N/A*,Null))))

There are fields that will have Null values.

The other formula needs to convert string (ranges) to a number, i.e. 0-5 = 1, then 6-10 = 2, etc.

Then I would use the previous to calculate what I need to do for those objects.

Body:
First I would suggest to use pandas library to do the data handling with read_csv function.

For the first step you can do it with the mean function.

For the second step :

df['field 4'].loc[df['field 4']>=10]=3
df['field 4'].loc[(df['field 4']>=5) & (df['fiel 4']<10)]=2
df['field 4'].loc[(df['field 4']>=0) & (df['field 4']<5)]=1
df['field 4'].fillna(None)


问:
Receiving Invalid number of Arguments - SQL ORACLE
I need to create a view named A9T5 that will use the A9 table to display the non-null States, the number of people in the state, the number of different JobTitles held by the people in the state, and the average number of people per JobTitle in the state.

The state abbreviations should be displayed in upper case. The average should be rounded to one digit after the decimal point. The four column headings should be State, People, Different_Jobs and People_Per_Job. The rows should be sorted by State.

Note: The average in column 4 is just the value in column 2 divided by the value in column 3. For instance, there are 369 people from California. Collectively, the 369 people hold 14 different JobTitles. This results in an average of 369/14=26.3571 which rounds to 26.4.

THIS IS WHAT I HAVE SO FAR:

```<code>SELECT Upper(State) as State,
       Count(*) as People, Count(DISTINCT JobTitle) as Different_Jobs,
       Round((Count(*) / Count(DISTINCT InitCap(JobTitle),1)) as People_Per_Job
FROM A9
WHERE State is NOT NULL
GROUP BY Upper(State)
ORDER BY Upper(State);
</code>```

I keep getting the error, invalid number of arguments.

What do i need to do in order to fix this?

答:
missing 1 ')' in

```<code>Round((Count(*) / Count(DISTINCT InitCap(JobTitle),1)) as
</code>```

should be

```<code> Round(( Count(*) / Count(DISTINCT InitCap(JobTitle)) ),1)
</code>```

Body:
I need to create a view named A9T5 that will use the A9 table to display the non-null States, the number of people in the state, the number of different JobTitles held by the people in the state, and the average number of people per JobTitle in the state.

The state abbreviations should be displayed in upper case. The average should be rounded to one digit after the decimal point. The four column headings should be State, People, Different_Jobs and People_Per_Job. The rows should be sorted by State.

Note: The average in column 4 is just the value in column 2 divided by the value in column 3. For instance, there are 369 people from California. Collectively, the 369 people hold 14 different JobTitles. This results in an average of 369/14=26.3571 which rounds to 26.4.

THIS IS WHAT I HAVE SO FAR:

SELECT Upper(State) as State,
       Count(*) as People, Count(DISTINCT JobTitle) as Different_Jobs,
       Round((Count(*) / Count(DISTINCT InitCap(JobTitle),1)) as People_Per_Job
FROM A9
WHERE State is NOT NULL
GROUP BY Upper(State)
ORDER BY Upper(State);

I keep getting the error, invalid number of arguments.

What do i need to do in order to fix this?

Body:
missing 1 ')' in

Round((Count(*) / Count(DISTINCT InitCap(JobTitle),1)) as

should be

 Round(( Count(*) / Count(DISTINCT InitCap(JobTitle)) ),1)


问:
JS expression for a function with a property
Is it possible to write a single expression in ES6 for a function that also has a property?

i.e. is there a simpler way to write the expression after f= without the wrapper?

```<code>f = (function(){
  const f = function(x) { return 2*x; };
  f.foo = 'bar';
  return f;
})();
</code>```

答:
As nnnnnn's comment suggests, the IIFE wrapper doesn't seem to be accomplishing anything.

```<code>const f = (function(){
  const f = function(x) { return 2*x; };
  f.foo = 'bar';
  return f;
})();
</code>```

is the same as

```<code>const f = function(x) { return 2*x; };
f.foo = 'bar';
</code>```

and I think using Object.assign just obfuscates what is going on above.

Body:
Is it possible to write a single expression in ES6 for a function that also has a property?

i.e. is there a simpler way to write the expression after f= without the wrapper?

f = (function(){
  const f = function(x) { return 2*x; };
  f.foo = 'bar';
  return f;
})();

Body:
As nnnnnn's comment suggests, the IIFE wrapper doesn't seem to be accomplishing anything.

const f = (function(){
  const f = function(x) { return 2*x; };
  f.foo = 'bar';
  return f;
})();

is the same as

const f = function(x) { return 2*x; };
f.foo = 'bar';

and I think using Object.assign just obfuscates what is going on above.


问:
wrong tempreture value when using arduino software i2c for SHT21 sensor
I run this code for reading temperature and humidity using SHT21 sensor:

#include <Wire.h>
#include <Ports.h>
#include "PortsSHT21.h"
#include <SHT2x.h>

//Define soft i2c channels for a sensor
  SHT21 hsensor2 (2); // pins A1 and D5 - Sensor 2

//define variables for temp data
  float h, t;

void setup()
{
    Wire.begin();
   Serial.begin(9600);
}

void loop()
{
  // Get data from  sensor soft I2C
  hsensor2.measure(SHT21::HUMI);
  hsensor2.measure(SHT21::TEMP);
  hsensor2.calculate(h, t);
    float hum2 = (h);
   float temp2 = (t);
    Serial.println("temp2");
    Serial.println(temp2);

    delay(500);
}
```

<p>But always it returns -46.85 degree. here is  PortsSHT21.cpp code and source code of PortsSHT21.h can be found here</p>

<p>It seems that this part of PortsSHT21.cpp file (line 114)  has always a zero value for "meas[TEMP]" variable.</p>

```t_C = (175.72 / 16384.0) * meas[TEMP] - 46.85; //T= -46.85 + 175.72 * ST/2^16
```

Would you please help me about fixing this?

答:
This sensor looks to be pretty identical to the HTU21D and Si7021 units. The addresses and conversion constants are identical. After confirming the hardware setup I would suggest, as a debugging step, trying one of those libraries. I have had success with using the Si7021 as a drop in replacement (no software change) for a burnt up HTU21D. Looks like the SHT21 chip uses the same I2C interface as well.

HTU21D Tutorial

SHT21 Datasheet

HTU21D Datasheet

Body:
I run this code for reading temperature and humidity using SHT21 sensor:

#include <Wire.h>
#include <Ports.h>
#include "PortsSHT21.h"
#include <SHT2x.h>

//Define soft i2c channels for a sensor
  SHT21 hsensor2 (2); // pins A1 and D5 - Sensor 2

//define variables for temp data
  float h, t;

void setup()
{
    Wire.begin();
   Serial.begin(9600);
}

void loop()
{
  // Get data from  sensor soft I2C
  hsensor2.measure(SHT21::HUMI);
  hsensor2.measure(SHT21::TEMP);
  hsensor2.calculate(h, t);
    float hum2 = (h);
   float temp2 = (t);
    Serial.println("temp2");
    Serial.println(temp2);

    delay(500);
}

But always it returns -46.85 degree. here is  PortsSHT21.cpp code and source code of PortsSHT21.h can be found here

It seems that this part of PortsSHT21.cpp file (line 114)  has always a zero value for "meas[TEMP]" variable.

t_C = (175.72 / 16384.0) * meas[TEMP] - 46.85; //T= -46.85 + 175.72 * ST/2^16

Would you please help me about fixing this?


问:
Keep-alive on a single route instaead of all routes in router-view
if keep-alive is specified to router-view as below

```<code><keep-alive>
    <router-view></router-view>
</keep-alive>
</code>```

then all routes are effectively cached and reloaded when that route is revisited.

I'd like to be able to specify a keep-alive option on individual routes.

With many  routes and only 1 or 2 that need to be kept alive wihout re-rendering caching all routes is useless

is there any method of doing so or any workaround available

答:
https://jsfiddle.net/Linusborg/L613xva0/4/

New in Vue version 2.1.0, the include and exclude props for conditionally caching components. Note the use of the name option.

```<code>const Foo = {
    name: 'foo',
  template: '<div><p v-for="n in numbers">{{ n }}</p></div>',
  data: function() {
    return {
        numbers: [Math.round(Math.random() * 10), Math.round(Math.random() * 10)]
    }
  }
}

const Bar = {
    name: 'bar',
    template: '<div><p v-for="n in numbers"><strong>{{ n }}</strong></p></div>',
  data: function() {
    return {
        numbers: [Math.round(Math.random() * 10), Math.round(Math.random() * 10)]
    }
  }
}
</code>```

Body:
if keep-alive is specified to router-view as below

<keep-alive>
    <router-view></router-view>
</keep-alive>

then all routes are effectively cached and reloaded when that route is revisited.

I'd like to be able to specify a keep-alive option on individual routes.

With many  routes and only 1 or 2 that need to be kept alive wihout re-rendering caching all routes is useless

is there any method of doing so or any workaround available

Body:
https://jsfiddle.net/Linusborg/L613xva0/4/

New in Vue version 2.1.0, the include and exclude props for conditionally caching components. Note the use of the name option.

const Foo = {
    name: 'foo',
  template: '<div><p v-for="n in numbers">{{ n }}</p></div>',
  data: function() {
    return {
        numbers: [Math.round(Math.random() * 10), Math.round(Math.random() * 10)]
    }
  }
}

const Bar = {
    name: 'bar',
    template: '<div><p v-for="n in numbers"><strong>{{ n }}</strong></p></div>',
  data: function() {
    return {
        numbers: [Math.round(Math.random() * 10), Math.round(Math.random() * 10)]
    }
  }
}


问:
php remove duplicate subarray from array and count them
I have array of arrays that hold 4 fields, i want to remove all subarrays that have same first 3 values and sum their 4th value. Please help.

```<code>$a = [
       ["123", "XL", "blue", 1],
       ["345", "L", "black", 1],
       ["534", "S", "white", 2],
       ["345", "L", "black", 4]
     ]
$a = fixArray($a);
</code>```

after

```<code>$a = [
       ["123", "XL", "blue", 1],
       ["345", "L", "black", 5],
       ["534", "S", "white", 2]
     ]
</code>```

答:
try this :

```<code>function FixArray($arr)
{
    // create a copy to work with
    $ca = $arr;

    // we're gonna fill this one and return it
    $cr = array();

    for($i=0; $i<count($arr); $i++){

        $tmp = $arr[$i];

        for($j=0; $j<count($arr); $j++){

            // empty the same element in the copy so we don't double count it.
            if($i == $j){
                $ca[$j][0] = "";
                $ca[$j][1] = "";
                $ca[$j][2] = "";
                $ca[$j][3] = "";
            }

            if($tmp[0] == $ca[$j][0] && $tmp[1] == $ca[$j][1] && $tmp[2] == $ca[$j][2]){
                // if matched, add then push into the return array then empty the element from the copy
                array_push($cr, [$ca[$j][0], $ca[$j][1], $ca[$j][2], ($ca[$j][3] + $tmp[3])]);
                $ca[$j][0] = "";
                $ca[$j][1] = "";
                $ca[$j][2] = "";
                $ca[$j][3] = "";
            }
        }
    }

    return $cr;
}
</code>```

Body:
I have array of arrays that hold 4 fields, i want to remove all subarrays that have same first 3 values and sum their 4th value. Please help.

$a = [
       ["123", "XL", "blue", 1],
       ["345", "L", "black", 1],
       ["534", "S", "white", 2],
       ["345", "L", "black", 4]
     ]
$a = fixArray($a);

after

$a = [
       ["123", "XL", "blue", 1],
       ["345", "L", "black", 5],
       ["534", "S", "white", 2]
     ]

Body:
try this :

function FixArray($arr)
{
    // create a copy to work with
    $ca = $arr;

    // we're gonna fill this one and return it
    $cr = array();

    for($i=0; $i<count($arr); $i++){

        $tmp = $arr[$i];

        for($j=0; $j<count($arr); $j++){

            // empty the same element in the copy so we don't double count it.
            if($i == $j){
                $ca[$j][0] = "";
                $ca[$j][1] = "";
                $ca[$j][2] = "";
                $ca[$j][3] = "";
            }

            if($tmp[0] == $ca[$j][0] && $tmp[1] == $ca[$j][1] && $tmp[2] == $ca[$j][2]){
                // if matched, add then push into the return array then empty the element from the copy
                array_push($cr, [$ca[$j][0], $ca[$j][1], $ca[$j][2], ($ca[$j][3] + $tmp[3])]);
                $ca[$j][0] = "";
                $ca[$j][1] = "";
                $ca[$j][2] = "";
                $ca[$j][3] = "";
            }
        }
    }

    return $cr;
}


问:
How can I loop through the JSON response object to remove the property labels?
```<code>// GET - Get login settings
router.route('/login/settings').get((req, res) => {
  let settings =[];
  pool.connect((err, client, done) => {
    client.query('SELECT * FROM public.settings', (err, result) => {
      settings = result.rows;
      res.json({
          settings,
      });
    });
  });
});
</code>```

I have this code in my API routing that returns the following JSON object:

```<code>{
  "settings": [
    {
      "key": "TwoFactorAuth",
      "value": "false"
    },
    {
      "key": "sessionTimeout",
      "value": "200"
    }
  ]
}
</code>```

How can I write a loop in the routing code to change the JSON response object to look like this:

```<code>{
  "settings": [
    {
      "TwoFactorAuth": "false"
    },
    {
      "sessionTimeout": "200"
    }
  ]
}
</code>```

答:
Loop through the settings array and create a new object with one property. The name of the property comes from the key element of the original element, and the value of the property comes from the value element. Then replace the array element with this.

```<code>var settings = response.settings;
for (var i = 0; i < settings.length; i++) {
    var obj = {};
    obj[settings[i].key] = settings[i].value;
    settings[i] = obj;
}
</code>```

Body:
// GET - Get login settings
router.route('/login/settings').get((req, res) => {
  let settings =[];
  pool.connect((err, client, done) => {
    client.query('SELECT * FROM public.settings', (err, result) => {
      settings = result.rows;
      res.json({
          settings,
      });
    });
  });
});

I have this code in my API routing that returns the following JSON object:

{
  "settings": [
    {
      "key": "TwoFactorAuth",
      "value": "false"
    },
    {
      "key": "sessionTimeout",
      "value": "200"
    }
  ]
}

How can I write a loop in the routing code to change the JSON response object to look like this:

{
  "settings": [
    {
      "TwoFactorAuth": "false"
    },
    {
      "sessionTimeout": "200"
    }
  ]
}

Body:
Loop through the settings array and create a new object with one property. The name of the property comes from the key element of the original element, and the value of the property comes from the value element. Then replace the array element with this.

var settings = response.settings;
for (var i = 0; i < settings.length; i++) {
    var obj = {};
    obj[settings[i].key] = settings[i].value;
    settings[i] = obj;
}


问:
Accessing result of map/reduce within Ionic2 app using PouchDB
I am using PouchDB on an Ionic 2 app that syncs with my CouchDB that is on AWS.

I have created a design document in futon and this works well if I go to http://my-ip-address:5984/wardround_jobs/_design/teams/_view/teams - I can see the JSON that is output by the map/reduce used in my design.

I am now trying to figure out how to access this in my app.

I start with this - it gives me all documents:

```<code>return new Promise(resolve => {

    this.db.allDocs({
    include_docs: true

    }).then((result) => {
        console.log(result);
    }).catch((error) => {
        console.log(error);
    });

});
</code>```

I can then amend this to get back one specific document:

```<code>return new Promise(resolve => {

    this.db.get('0448071807c0f37f53e06aab54034a42').then((result) => {
        console.log(result);
    }).catch((error) => {
        console.log(error);
    });

});
</code>```

But if I try and get back my design view using this code then I get back an error:

```<code>return new Promise(resolve => {

    this.db.get('_design/teams/_view/teams').then((result) => {
        console.log(result);
    }).catch((error) => {
        console.log(error);
    });

});
</code>```

The error is:

```<code>CustomPouchError {
    status: 404,
    name: "not_found",
    message: "missing",
    error: true,
    reason: "missing"
}
</code>```

How can I access the result from my map/reduce within my app?

EDIT - with the help of Alexis I got this working ...

```<code>return new Promise(resolve => {

    this.db.get('teams/teams').then((result) => {
        console.log(result);
    }).catch((error) => {
        console.log(error);
    });

});
</code>```

答: To get the result from any map/reduce design document, you need to use the query() function.

Body:
I am using PouchDB on an Ionic 2 app that syncs with my CouchDB that is on AWS.

I have created a design document in futon and this works well if I go to http://my-ip-address:5984/wardround_jobs/_design/teams/_view/teams - I can see the JSON that is output by the map/reduce used in my design.

I am now trying to figure out how to access this in my app.

I start with this - it gives me all documents:

return new Promise(resolve => {

    this.db.allDocs({
    include_docs: true

    }).then((result) => {
        console.log(result);
    }).catch((error) => {
        console.log(error);
    });

});

I can then amend this to get back one specific document:

return new Promise(resolve => {

    this.db.get('0448071807c0f37f53e06aab54034a42').then((result) => {
        console.log(result);
    }).catch((error) => {
        console.log(error);
    });

});

But if I try and get back my design view using this code then I get back an error:

return new Promise(resolve => {

    this.db.get('_design/teams/_view/teams').then((result) => {
        console.log(result);
    }).catch((error) => {
        console.log(error);
    });

});

The error is:

CustomPouchError {
    status: 404,
    name: "not_found",
    message: "missing",
    error: true,
    reason: "missing"
}

How can I access the result from my map/reduce within my app?

EDIT - with the help of Alexis I got this working ...

return new Promise(resolve => {

    this.db.get('teams/teams').then((result) => {
        console.log(result);
    }).catch((error) => {
        console.log(error);
    });

});


问:
How do you use the MDL color classes when the color name has two words?
In Material Design Lite, you can add CSS classes to a component to change either the background color or the text color:

```<code>mdl-color--{color-name}-{shade}
mdl-color-text--{color-name}-{shade}
</code>```

To set a div's background color to orange you could do this:

```<code><div class="mdl-color--orange">...</div>
</code>```

Does anyone know how to do it when the color name has two words, such as Light Blue, Light Green, etc? I've tried just about every combination of dashes and underscores I could think of with no luck.

答:
You separate them with one dash. Examples:

mdl-color--light-blue-100

mdl-color--light-green-A100

mdl-color-text--deep-orange

mdl-color-text--blue-grey-700

Don't forget you need to include them in your theme.

Body:
In Material Design Lite, you can add CSS classes to a component to change either the background color or the text color:

mdl-color--{color-name}-{shade}
mdl-color-text--{color-name}-{shade}

To set a div's background color to orange you could do this:

...

Does anyone know how to do it when the color name has two words, such as Light Blue, Light Green, etc? I've tried just about every combination of dashes and underscores I could think of with no luck.


答:
For adding variable as key to some object you can use [key] notation.
try this for setting object to update :</p>

```<code>settings  = settings.map((data) => {
    var object = {};
    object[data.key] = data.value;
    return object;
});
</code>```

Title: How can I loop through the JSON response object to remove the property labels?

Body:
For adding variable as key to some object you can use [key] notation.
try this for setting object to update :

settings  = settings.map((data) => {
    var object = {};
    object[data.key] = data.value;
    return object;
});


问:
.htaccess serving other files if specific files are not found
If I have /index.html and the user goes to domain.tld or domain.tld/index.html I want them to get that page. (Default behavior)

If I don't have /index.html but I do have /content.txt I'd like to serve the page /makeindex.php but not change the url.

If I don't have /index.html or /content.txt I'd like to serve /nocontent.php but not change the url.

So far I have:

```<code>RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /makeindex.php [L]
</code>```

But I don't know how to limit this to domain.tld or domain.tld/index.html and I also don't know how I would create that two step process first checking for content.txt if I serve /makeindex.php or falling back to /nocontent.php if both those files don't exist.

答:
You can use the following rule, put this at the top of your htaccess :</p>

```<code>RewriteEngine on

#if /index.html exists serve it as a directory index and main page
RewriteCond %{DOCUMENT_ROOT}/index.html -f
RewriteCond %{REQUEST_URI} ^/$
RewriteRule ^ /index.html [L]
#if content.txt exists , use makeindex.php as directory index
RewriteCond %{DOCUMENT_ROOT}/content.txt -f
RewriteRule ^$ /makeindex.php [L]
#else set /nocontent.php as directory index
 RewriteRule ^$ /nocontent.php [L]
</code>```

Body:
If I have /index.html and the user goes to domain.tld or domain.tld/index.html I want them to get that page. (Default behavior)

If I don't have /index.html but I do have /content.txt I'd like to serve the page /makeindex.php but not change the url.

If I don't have /index.html or /content.txt I'd like to serve /nocontent.php but not change the url.

So far I have:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /makeindex.php [L]

But I don't know how to limit this to domain.tld or domain.tld/index.html and I also don't know how I would create that two step process first checking for content.txt if I serve /makeindex.php or falling back to /nocontent.php if both those files don't exist.

Body:
You can use the following rule, put this at the top of your htaccess :

RewriteEngine on

#if /index.html exists serve it as a directory index and main page
RewriteCond %{DOCUMENT_ROOT}/index.html -f
RewriteCond %{REQUEST_URI} ^/$
RewriteRule ^ /index.html [L]
#if content.txt exists , use makeindex.php as directory index
RewriteCond %{DOCUMENT_ROOT}/content.txt -f
RewriteRule ^$ /makeindex.php [L]
#else set /nocontent.php as directory index
 RewriteRule ^$ /nocontent.php [L]


问:
Json; CamelCase to underscore in JSON serialisation
I encountered a situation in  deserialising json to POJO and serialising it back to json

Deserialising:
Here the json is received with camel cased params and the pojo has an appropriate JsonCreator and this works

eg- received json - {"userId":"id"}

Serialisation:
Here I have to serialise this POJO into JSON again to send to another service. and the parameter should be SNAKE cased with underscore

eg - variable userId should be changed to user_id while serialising

has anyone faced this situation before? has some tips to proceed ?

thanks!

答: Please try adding @JsonProperty("user_id") annotation in your pojo class. I hope it should solve the issue.</p>


问:
HAProxy path_beg not redirecting
I'm testing a simple haproxy rule to make http://localhost/haproxy-dconv take me to http://cbonte.github.io/haproxy-dconv but it isn't working. 404 response seems to be from the site but the path isn't resolving.</p>

```<code>frontend HTTP
  mode http
  bind *:80

  acl url_dconv path_beg /haproxy-dconv
  use_backend dconv-backend if url_dconv

backend dconv-backend
  mode http
  server dconv cbonte.github.io
</code>```

答:
Try this -

```<code>frontend HTTP
    mode http
    bind *:80
    use_backend dconv-backend if { path_beg /haproxy-dconv/ }

backend dconv-backend
    mode http
    server dconv cbonte.github.io
</code>```

Source: https://cbonte.github.io/haproxy-dconv/1.7/configuration.html#use_backend

Title: HAProxy path_beg not redirecting

Body:
I'm testing a simple haproxy rule to make http://localhost/haproxy-dconv take me to http://cbonte.github.io/haproxy-dconv but it isn't working. 404 response seems to be from the site but the path isn't resolving.

frontend HTTP
  mode http
  bind *:80

  acl url_dconv path_beg /haproxy-dconv
  use_backend dconv-backend if url_dconv

backend dconv-backend
  mode http
  server dconv cbonte.github.io

Body:
Try this -

frontend HTTP
    mode http
    bind *:80
    use_backend dconv-backend if { path_beg /haproxy-dconv/ }

backend dconv-backend
    mode http
    server dconv cbonte.github.io

Source: https://cbonte.github.io/haproxy-dconv/1.7/configuration.html#use_backend


问:
500 error on localhost when submitting form using AJAX and PHP
I'm fairly new to PHP and I'm having trouble sending test emails out from my local host.

I have a 3 field form where I'm hoping that I can have a user submit the form & be able to see a success message without the page refreshing. I get the error message that I have set in the code but for some reason, I'm unable to actually get the emails to send/have a success message appear.

Here's my code:

js

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

    var form = $('#ajax-contact');

    var formMessages = $('#form-messages');

    $(form).submit(function(e) {
        e.preventDefault();

        var formData = $(form).serialize();

        $.ajax({
            type: 'POST',
            url: $(form).attr('action'),
            data: formData
        })
        .done(function(response) {

            $(formMessages).removeClass('error');
            $(formMessages).addClass('success');

            $(formMessages).text(response);

            $('#name, #email, #number').val('');
        })
        .fail(function(data) {

            $(formMessages).removeClass('success');
            $(formMessages).addClass('error');

            if (data.responseText !== '') {
                $(formMessages).text(data.responseText);
            } else {
                $(formMessages).text('Oops! An error occured and your message could not be sent.');
            }
        });

    });

});
</code>```

mailer.php

```<code><?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = strip_tags(trim($_POST["name"]));
            $name = str_replace(array("\r","\n"),array(" "," "),$name);
    $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
    $number = trim($_POST["number"]);

    if ( empty($name) OR empty($number) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        http_response_code(400);
        echo "Sorry, there seems to be a problem submitting your details, please try again or contacts us";
        exit;
    }
    $recipient = "example@example.co.uk";
    $subject = "$name has given you their details to call them back";
    $email_content = "
    <html>
    <style>
    body {
        background-color: white;
    }

    .email-container{
        background-color:#c1c1c1;
        max-width:400px;
        margin:0 auto;
        padding:30px 10px;
        border-radius:10px;
        border: 2px solid #515151;
    }

    </style>
    <body>
    <div class="email-container">

    Dear example, <br />
     <br />
    A potential client has requested a call back. Their details are as follows: <br />
     <br />
    Name: $name\n <br />
    Email: $email\n\n <br />
    Telephone: \n$numer\n
    </div>

    </body>
    </html>"
    $email_headers = "From: $name <$email>";
    if (mail($recipient, $subject, $email_content, $email_headers)) {
        http_response_code(200);
        echo "Thank You! Your message has been sent.";
    } else {
        http_response_code(500);
        echo "Sorry, there seems to be a problem submitting your details, please try again or contacts us";
    }

} else {
    http_response_code(403);
    echo "There was a problem with your submission, please try again.";
}

?>
</code>```

HTML

```<code><form class="requestcall-form" id="ajax-contact" method="post" action="mailer.php">
  <input type="text" id="name" name="name" placeholder="Full Name" required>
  <input type="text" id="email" name="email" placeholder="Email Address" required>
  <input type="text" id="number" name="number" placeholder="Contact number" required>
  <input class="submit" type="submit" name="submit" value="Submit">
</form>
<div id="form-messages"></div>
</code>```

答:
The other answer is correct, I thought I'd offer a better solution for dealing with large blocks of text, heredoc strings. No worrying about unescaped quotes ruining your day. Using this, your code would look like this:

...
$recipient = "example@example.co.uk";
$subject = "$name has given you their details to call them back";
$email_content = <<< HTML

Dear example,

A potential client has requested a call back. Their details are as follows:

Name: $name

Email: $email

Telephone: $numer

HTML;
$email_headers = "From: $name <$email>";
...
```

Body:
I'm fairly new to PHP and I'm having trouble sending test emails out from my local host.

I have a 3 field form where I'm hoping that I can have a user submit the form & be able to see a success message without the page refreshing. I get the error message that I have set in the code but for some reason, I'm unable to actually get the emails to send/have a success message appear.

Here's my code:

js

jQuery( document ).ready( function( $ ) {

    var form = $('#ajax-contact');

    var formMessages = $('#form-messages');

    $(form).submit(function(e) {
        e.preventDefault();

        var formData = $(form).serialize();

        $.ajax({
            type: 'POST',
            url: $(form).attr('action'),
            data: formData
        })
        .done(function(response) {

            $(formMessages).removeClass('error');
            $(formMessages).addClass('success');

            $(formMessages).text(response);

            $('#name, #email, #number').val('');
        })
        .fail(function(data) {

            $(formMessages).removeClass('success');
            $(formMessages).addClass('error');

            if (data.responseText !== '') {
                $(formMessages).text(data.responseText);
            } else {
                $(formMessages).text('Oops! An error occured and your message could not be sent.');
            }
        });

    });

});

mailer.php

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = strip_tags(trim($_POST["name"]));
            $name = str_replace(array("\r","\n"),array(" "," "),$name);
    $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
    $number = trim($_POST["number"]);

    if ( empty($name) OR empty($number) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        http_response_code(400);
        echo "Sorry, there seems to be a problem submitting your details, please try again or contacts us";
        exit;
    }
    $recipient = "example@example.co.uk";
    $subject = "$name has given you their details to call them back";
    $email_content = "

    Dear example,

    A potential client has requested a call back. Their details are as follows:

    Name: $name\n

    Email: $email\n\n

    Telephone: \n$numer\n

    "
    $email_headers = "From: $name <$email>";
    if (mail($recipient, $subject, $email_content, $email_headers)) {
        http_response_code(200);
        echo "Thank You! Your message has been sent.";
    } else {
        http_response_code(500);
        echo "Sorry, there seems to be a problem submitting your details, please try again or contacts us";
    }

} else {
    http_response_code(403);
    echo "There was a problem with your submission, please try again.";
}

?>

HTML

<form class="requestcall-form" id="ajax-contact" method="post" action="mailer.php">
  <input type="text" id="name" name="name" placeholder="Full Name" required>
  <input type="text" id="email" name="email" placeholder="Email Address" required>
  <input type="text" id="number" name="number" placeholder="Contact number" required>
  <input class="submit" type="submit" name="submit" value="Submit">
</form>

Body:
The other answer is correct, I thought I'd offer a better solution for dealing with large blocks of text, heredoc strings. No worrying about unescaped quotes ruining your day. Using this, your code would look like this:

...
$recipient = "example@example.co.uk";
$subject = "$name has given you their details to call them back";
$email_content = <<< HTML
<html>
<style>
body {
    background-color: white;
}

.email-container{
    background-color:#c1c1c1;
    max-width:400px;
    margin:0 auto;
    padding:30px 10px;
    border-radius:10px;
    border: 2px solid #515151;
}

</style>
<body>
<div class="email-container">

Dear example, <br />
 <br />
A potential client has requested a call back. Their details are as follows: <br />
 <br />
Name: $name <br />
Email: $email <br />
Telephone: $numer
</div>

</body>
</html>

HTML;
$email_headers = "From: $name <$email>";
...


问:
How do I compile openSSL in 32 bit mode on a 64bit system?
I have a program that currently has to be compiled in 32 bit mode (for now) and needs to be linked against a version of openSSL with the experimental ciphers included.  Therefore I need to compile a 32 bit openSSL.  Using

```<code>./config -m32
</code>```

results in both -m32 and -m64 being included in the compiler flags.

答:
May be will can modify "config" file in openssl,because it will first check the OS 64 bit or  32 bit ,and the prepare the configure for OS,for example,the OS is 64bit,and we can modify the term in config as below
repace x86_64--linux?) OUT="linux-x86_64";;
with x86_64--linux?) OUT="linux-generic32";;

Body:
I have a program that currently has to be compiled in 32 bit mode (for now) and needs to be linked against a version of openSSL with the experimental ciphers included.  Therefore I need to compile a 32 bit openSSL.  Using

./config -m32

results in both -m32 and -m64 being included in the compiler flags.


问:
How can currying be done in C++?
What is currying?

How can currying be done in C++?

Please Explain binders in STL container?

答:
Some great answers here. I thought I would add my own because it was fun to play around with the concept.

Partial function application: The process of "binding" a function with only some of its parameters, deferring the rest to be filled in later. The result is another function with fewer parameters.

Currying: Is a special form of partial function application where you can only "bind" a single argument at a time. The result is another function with exactly 1 fewer parameter.

The code I'm about to present is partial function application from which currying is possible, but not the only possibility. It offers a few benefits over the above currying implementations (mainly because it's partial function application and not currying, heh).

Applying over an empty function:

```<code>auto sum0 = [](){return 0;};
std::cout << partial_apply(sum0)() << std::endl;
</code>```

Applying multiple arguments at a time:

```<code>auto sum10 = [](int a, int b, int c, int d, int e, int f, int g, int h, int i, int j){return a+b+c+d+e+f+g+h+i+j;};
std::cout << partial_apply(sum10)(1)(1,1)(1,1,1)(1,1,1,1) << std::endl; // 10
</code>```

constexpr support that allows for compile-time static_assert:

```<code>static_assert(partial_apply(sum0)() == 0);
</code>```

A useful error message if you accidentally go too far in providing arguments:

```<code>auto sum1 = [](int x){ return x;};
partial_apply(sum1)(1)(1);
</code>```

error: static_assert failed "Attempting to apply too many arguments!"

Other answers above return lambdas that bind an argument and then return further lambdas. This approach wraps that essential functionality into a callable object. Definitions for operator() allow the internal lambda to be called. Variadic templates allow us to check for someone going too far, and an implicit conversion function to the result type of the function call allows us to print the result or compare the object to a primitive.

Code:

```<code>namespace detail{
template<class F>
using is_zero_callable = decltype(std::declval<F>()());

template<class F>
constexpr bool is_zero_callable_v = std::experimental::is_detected_v<is_zero_callable, F>;
}

template<class F>
struct partial_apply_t
{
    template<class... Args>
    constexpr auto operator()(Args... args)
    {
        static_assert(sizeof...(args) == 0 || !is_zero_callable, "Attempting to apply too many arguments!");
        auto bind_some = [=](auto... rest) -> decltype(myFun(args..., rest...))
        {
           return myFun(args..., rest...);
        };
        using bind_t = decltype(bind_some);

        return partial_apply_t<bind_t>{bind_some};
    }
    explicit constexpr partial_apply_t(F fun) : myFun(fun){}

    constexpr operator auto()
    {
        if constexpr (is_zero_callable)
            return myFun();
        else
            return *this; // a callable
    }
    static constexpr bool is_zero_callable = detail::is_zero_callable_v<F>;
    F myFun;
};
</code>```

Live Demo

A few more notes:

I chose to use is_detected mainly for enjoyment and practice; it serves the same as a normal type trait would here.

There could definitely be more work done to support perfect forwarding for performance reasons

The code is C++17 because it requires for constexpr lambda support in C++17

And it seems that GCC 7.0.1 is not quite there yet, either, so I used Clang 5.0.0

Some tests:

```<code>auto sum0 = [](){return 0;};
auto sum1 = [](int x){ return x;};
auto sum2 = [](int x, int y){ return x + y;};
auto sum3 = [](int x, int y, int z){ return x + y + z; };
auto sum10 = [](int a, int b, int c, int d, int e, int f, int g, int h, int i, int j){return a+b+c+d+e+f+g+h+i+j;};

std::cout << partial_apply(sum0)() << std::endl; //0
static_assert(partial_apply(sum0)() == 0, "sum0 should return 0");
std::cout << partial_apply(sum1)(1) << std::endl; // 1
std::cout << partial_apply(sum2)(1)(1) << std::endl; // 2
std::cout << partial_apply(sum3)(1)(1)(1) << std::endl; // 3
static_assert(partial_apply(sum3)(1)(1)(1) == 3, "sum3 should return 3");
std::cout << partial_apply(sum10)(1)(1,1)(1,1,1)(1,1,1,1) << std::endl; // 10
//partial_apply(sum1)(1)(1); // fails static assert
auto partiallyApplied = partial_apply(sum3)(1)(1);
std::function<int(int)> finish_applying = partiallyApplied;
std::cout << std::boolalpha << (finish_applying(1) == 3) << std::endl; // true

auto plus2 = partial_apply(sum3)(1)(1);
std::cout << std::boolalpha << (plus2(1) == 3) << std::endl; // true
std::cout << std::boolalpha << (plus2(3) == 5) << std::endl; // true
</code>```

Title: How can currying be done in C++?

Body:
Some great answers here. I thought I would add my own because it was fun to play around with the concept.

Partial function application: The process of "binding" a function with only some of its parameters, deferring the rest to be filled in later. The result is another function with fewer parameters.

Currying: Is a special form of partial function application where you can only "bind" a single argument at a time. The result is another function with exactly 1 fewer parameter.

The code I'm about to present is partial function application from which currying is possible, but not the only possibility. It offers a few benefits over the above currying implementations (mainly because it's partial function application and not currying, heh).

Applying over an empty function:

auto sum0 = [](){return 0;};
std::cout << partial_apply(sum0)() << std::endl;

Applying multiple arguments at a time:

auto sum10 = [](int a, int b, int c, int d, int e, int f, int g, int h, int i, int j){return a+b+c+d+e+f+g+h+i+j;};
std::cout << partial_apply(sum10)(1)(1,1)(1,1,1)(1,1,1,1) << std::endl; // 10

constexpr support that allows for compile-time static_assert:

static_assert(partial_apply(sum0)() == 0);

A useful error message if you accidentally go too far in providing arguments:

auto sum1 = [](int x){ return x;};
partial_apply(sum1)(1)(1);

error: static_assert failed "Attempting to apply too many arguments!"

Other answers above return lambdas that bind an argument and then return further lambdas. This approach wraps that essential functionality into a callable object. Definitions for operator() allow the internal lambda to be called. Variadic templates allow us to check for someone going too far, and an implicit conversion function to the result type of the function call allows us to print the result or compare the object to a primitive.

Code:

namespace detail{
template<class F>
using is_zero_callable = decltype(std::declval<F>()());

template<class F>
constexpr bool is_zero_callable_v = std::experimental::is_detected_v<is_zero_callable, F>;
}

template<class F>
struct partial_apply_t
{
    template<class... Args>
    constexpr auto operator()(Args... args)
    {
        static_assert(sizeof...(args) == 0 || !is_zero_callable, "Attempting to apply too many arguments!");
        auto bind_some = [=](auto... rest) -> decltype(myFun(args..., rest...))
        {
           return myFun(args..., rest...);
        };
        using bind_t = decltype(bind_some);

        return partial_apply_t<bind_t>{bind_some};
    }
    explicit constexpr partial_apply_t(F fun) : myFun(fun){}

    constexpr operator auto()
    {
        if constexpr (is_zero_callable)
            return myFun();
        else
            return *this; // a callable
    }
    static constexpr bool is_zero_callable = detail::is_zero_callable_v<F>;
    F myFun;
};

Live Demo

A few more notes:

I chose to use is_detected mainly for enjoyment and practice; it serves the same as a normal type trait would here.

There could definitely be more work done to support perfect forwarding for performance reasons

The code is C++17 because it requires for constexpr lambda support in C++17

And it seems that GCC 7.0.1 is not quite there yet, either, so I used Clang 5.0.0

Some tests:

auto sum0 = [](){return 0;};
auto sum1 = [](int x){ return x;};
auto sum2 = [](int x, int y){ return x + y;};
auto sum3 = [](int x, int y, int z){ return x + y + z; };
auto sum10 = [](int a, int b, int c, int d, int e, int f, int g, int h, int i, int j){return a+b+c+d+e+f+g+h+i+j;};

std::cout << partial_apply(sum0)() << std::endl; //0
static_assert(partial_apply(sum0)() == 0, "sum0 should return 0");
std::cout << partial_apply(sum1)(1) << std::endl; // 1
std::cout << partial_apply(sum2)(1)(1) << std::endl; // 2
std::cout << partial_apply(sum3)(1)(1)(1) << std::endl; // 3
static_assert(partial_apply(sum3)(1)(1)(1) == 3, "sum3 should return 3");
std::cout << partial_apply(sum10)(1)(1,1)(1,1,1)(1,1,1,1) << std::endl; // 10
//partial_apply(sum1)(1)(1); // fails static assert
auto partiallyApplied = partial_apply(sum3)(1)(1);
std::function<int(int)> finish_applying = partiallyApplied;
std::cout << std::boolalpha << (finish_applying(1) == 3) << std::endl; // true

auto plus2 = partial_apply(sum3)(1)(1);
std::cout << std::boolalpha << (plus2(1) == 3) << std::endl; // true
std::cout << std::boolalpha << (plus2(3) == 5) << std::endl; // true


问:
Pythonic way to check if: all elements evaluate to False -OR- all elements evaluate to True
I want the results of the function to be:

All values evaluate to False (None, 0, empty string) -> True

All values evaluate to True -> True

Every other case -> False

This is my try at it:

```<code>>>> def consistent(x):
...  x_filtered = filter(None, x)
...  return len(x_filtered) in (0, len(x))
...
>>> consistent((0,1))
False
>>> consistent((1,1))
True
>>> consistent((0,0))
True
</code>```

[Bonus]

What should this function be named?

答:
Piggybacking on Ignacio Vasquez-Abram's method, but will stop after first mismatch:

```<code>def unanimous(s):
  it1, it2 = itertools.tee(iter(s))
  it1.next()
  return not any(bool(a)^bool(b) for a,b in itertools.izip(it1,it2))
</code>```

While using not reduce(operators.xor, s) would be simpler, it does no short-circuiting.

ContentLicense: CC BY-SA 2.5

Body:
I want the results of the function to be:

All values evaluate to False (None, 0, empty string) -> True

All values evaluate to True -> True

Every other case -> False

This is my try at it:

>>> def consistent(x):
...  x_filtered = filter(None, x)
...  return len(x_filtered) in (0, len(x))
...
>>> consistent((0,1))
False
>>> consistent((1,1))
True
>>> consistent((0,0))
True

[Bonus]

What should this function be named?

Body:
Piggybacking on Ignacio Vasquez-Abram's method, but will stop after first mismatch:

def unanimous(s):
  it1, it2 = itertools.tee(iter(s))
  it1.next()
  return not any(bool(a)^bool(b) for a,b in itertools.izip(it1,it2))

While using not reduce(operators.xor, s) would be simpler, it does no short-circuiting.


问:
Regex to Match Hashtags in string that contain no more than 1 space
What I'm looking to do is match hashtags in a string, but the hashtag may have a space in it: #brown fox. Most hashtags are single words, #brown, #fox, but some were improperly formatted and resulted in spaces being entered.

The hashtags that have spaces are only allowed to be two words, so #space suit is allowed, but #brown fox jumps is not allowed.

The quick #brown #fox #jumps over the lazy dog.

brown, fox, jumps

The quick #brown fox #jumps over the lazy dog.

brown fox, jumps

The quick #brown fox #jumps over the lazy #dog.

brown fox, jumps, dog

If there is a hashtag, followed by one word, then followed by a hashtag, then we can assume the word is for that hashtag. Otherwise, we shouldn't capture it in the group.

Here is what I've tried so far, but clearly it's nowhere close to what I need:
https://regex101.com/r/vHOCaf/1

```<code>(\#+\w{2,})|(\#([\w]){2,}\s{0,1}([\w]){2,})
</code>```

答:
The regex you need must have a positive lookahead to not match a hashtag followed by a word without followed by another hashtag:

```<code>#\w+\b(?:\s\w+\b(?=\s#\w+))?
</code>```

Debuggex Demo

Body:
What I'm looking to do is match hashtags in a string, but the hashtag may have a space in it: #brown fox. Most hashtags are single words, #brown, #fox, but some were improperly formatted and resulted in spaces being entered.

The hashtags that have spaces are only allowed to be two words, so #space suit is allowed, but #brown fox jumps is not allowed.

The quick #brown #fox #jumps over the lazy dog.

brown, fox, jumps

The quick #brown fox #jumps over the lazy dog.

brown fox, jumps

The quick #brown fox #jumps over the lazy #dog.

brown fox, jumps, dog

If there is a hashtag, followed by one word, then followed by a hashtag, then we can assume the word is for that hashtag. Otherwise, we shouldn't capture it in the group.

Here is what I've tried so far, but clearly it's nowhere close to what I need:
https://regex101.com/r/vHOCaf/1

(\#+\w{2,})|(\#([\w]){2,}\s{0,1}([\w]){2,})

Body:
The regex you need must have a positive lookahead to not match a hashtag followed by a word without followed by another hashtag:

#\w+\b(?:\s\w+\b(?=\s#\w+))?

Debuggex Demo


问:
Why showing Null Pointer Exception While using JFrame in Eclipse?
Error******************************************************************

```<code>Exception in thread "main" java.lang.NullPointerException
at java.awt.Window.init(Unknown Source)
at java.awt.Window.<init>(Unknown Source)
at java.awt.Frame.<init>(Unknown Source)
at java.awt.Frame.<init>(Unknown Source)
at javax.swing.JFrame.<init>(Unknown Source)
at Main.main(Main.java:12)
</code>```

Code********************************************************************

```<code>import javax.swing.JFrame;
import javax.swing.JSlider;

import com.fazecast.jSerialComm.*;

public class Main {

    /**
     * @param args
     */
    public static void main(String[] args) {
        JFrame w = new JFrame();
        JSlider slider = new JSlider();
        slider.setMinimum(1023);
        w.add(slider);
        w.pack();
        w.setVisible(true);
    }
}
</code>```

答: Thank you Jonathan Sterling, Japu_D_Cret and chetan mehra. It worked well. I downloaded the exact version of Eclipse (Luna) prescribed in that video [ youtu.be/8B6j_yr9H8g ] and new JDK, Nothing else. The problem was with the IDE.</p>

Body:
Error******************************************************************

Exception in thread "main" java.lang.NullPointerException
at java.awt.Window.init(Unknown Source)
at java.awt.Window.<init>(Unknown Source)
at java.awt.Frame.<init>(Unknown Source)
at java.awt.Frame.<init>(Unknown Source)
at javax.swing.JFrame.<init>(Unknown Source)
at Main.main(Main.java:12)

Code********************************************************************

import javax.swing.JFrame;
import javax.swing.JSlider;

import com.fazecast.jSerialComm.*;

public class Main {

    /**
     * @param args
     */
    public static void main(String[] args) {
        JFrame w = new JFrame();
        JSlider slider = new JSlider();
        slider.setMinimum(1023);
        w.add(slider);
        w.pack();
        w.setVisible(true);
    }
}