问:
PHP Function pt_register
I'm a beginner with PHP, I was exposed to processed HTML forms and I'm learning how to use it to do more and more...

I'm using this function (and based on Google so are a lot of people) but I really want to understand what it's doing....

```<code>function pt_register()
{
  $num_args = func_num_args();
   $vars = array();

   if ($num_args >= 2) {
       $method = strtoupper(func_get_arg(0));

       if (($method != 'SESSION') && ($method != 'GET') && ($method != 'POST') && ($method != 'SERVER') && ($method != 'COOKIE') && ($method != 'ENV')) {
           die('The first argument of pt_register must be one of the following: GET, POST, SESSION, SERVER, COOKIE, or ENV');
     }

       $varname = "HTTP_{$method}_VARS";
      global ${$varname};

       for ($i = 1; $i < $num_args; $i++) {
           $parameter = func_get_arg($i);

           if (isset(${$varname}[$parameter])) {
               global $$parameter;
               $$parameter = ${$varname}[$parameter];
          }

       }

   } else {
       die('You must specify at least two arguments');
   }

}
</code>```

Can anyone walk through this in English for me?

答:
```<code>function pt_register()
{
  $num_args = func_num_args(); // Get the number of arguments passed to this function
   $vars = array();

   if ($num_args >= 2) {
       $method = strtoupper(func_get_arg(0));
       // if the number of arguments is larger than or equal to 2, get the first one and make it uppercase, assign it to the varible $method

       if (($method != 'SESSION') && ($method != 'GET') && ($method != 'POST') && ($method != 'SERVER') && ($method != 'COOKIE') && ($method != 'ENV')) {
           die('The first argument of pt_register must be one of the following: GET, POST, SESSION, SERVER, COOKIE, or ENV');
     }
       // check if $method = GET, POST, SESSION, SERVER, COOKIE, or ENV' if not, die and kill the script

       $varname = "HTTP_{$method}_VARS";
       /* assign the method to the var name
       * i.e. HTTP_GET_VARS, HTTP_POST_VARS etc
       */

      global ${$varname};
       // put the varible into the global varibles

       for ($i = 1; $i < $num_args; $i++) { // iterate through the arguments
           $parameter = func_get_arg($i);   // assign to parameter

           if (isset(${$varname}[$parameter])) {
               // check if a parameter is set in the HTTP var array
               // i.e HTTP_GET_VARS[$parameter]
               global $$parameter;
               //assign the varible name of parameter to the varible name
               // say parameter was 'content', create a varible named 'content' and make it global
               $$parameter = ${$varname}[$parameter];
               // update the parameter to match its value in the HTTP vars array
               // i.e $content = HTTP_GET_VARS['content'];
          }

       }

   } else {
       die('You must specify at least two arguments');
   }

}
</code>```

OwnerDisplayName: HaArD

Title: PHP Function pt_register

Body:
I'm a beginner with PHP, I was exposed to processed HTML forms and I'm learning how to use it to do more and more...

I'm using this function (and based on Google so are a lot of people) but I really want to understand what it's doing....

function pt_register()
{
  $num_args = func_num_args();
   $vars = array();

   if ($num_args >= 2) {
       $method = strtoupper(func_get_arg(0));

       if (($method != 'SESSION') && ($method != 'GET') && ($method != 'POST') && ($method != 'SERVER') && ($method != 'COOKIE') && ($method != 'ENV')) {
           die('The first argument of pt_register must be one of the following: GET, POST, SESSION, SERVER, COOKIE, or ENV');
     }

       $varname = "HTTP_{$method}_VARS";
      global ${$varname};

       for ($i = 1; $i < $num_args; $i++) {
           $parameter = func_get_arg($i);

           if (isset(${$varname}[$parameter])) {
               global $$parameter;
               $$parameter = ${$varname}[$parameter];
          }

       }

   } else {
       die('You must specify at least two arguments');
   }

}

Can anyone walk through this in English for me?

LastEditorDisplayName: RoBorg

OwnerDisplayName: Jayrox


来源: stackexchange

问:
Making a calculator but I am receiving compiling errors
I am teaching myself Java and started to make a calculator but I'm running into two errors when I try and run the code.

I was thinking about implementing a WHILE loop with the characters to create a loop but it did not seem to work. Really burnt out and I thought this was a good place to ask.

```<code>import java.lang.Math;
import java.util.Scanner;

public class Calculator
{

    public static void main(String[] args)
    {
        double numberOne = 0;
        double numberTwo = 0;
        String operatorInput;
        Scanner myInput = new Scanner(System.in);

       System.out.print("Enter first number: ");
       numberOne = myInput.nextDouble();

       System.out.print("Enter second number: ");
       numberTwo = myInput.nextDouble();

       System.out.print("Enter the operation you wish to perform (/, *, -, +): ");
       operatorInput = myInput.nextLine();

       double result = calculate(numberOne, numberTwo, operatorInput, myInput);

       System.out.printf("The result is: %.2f%n", result);

       myInput.close();
    }

    public static double calculate(double numberOne, double numberTwo, String operatorInput, Scanner myInput)
    {
        while(true)
        {
            switch (operatorInput)
            {
                case("/"):
                {
                    myInput.close();
                    return divideNumbers(numberOne, numberTwo);
                }
                case("*"):
                {
                    myInput.close();
                    return multiplyNumbers(numberOne, numberTwo);
                }
                case("+"):
                {
                    myInput.close();
                    return addNumbers(numberOne, numberTwo);
                }
                case("-"):
                {
                    myInput.close();
                    return subtractNumbers(numberOne, numberTwo);
                }
                default:
                {
                    System.out.println("Invalid Input");
                    System.out.print("Enter the operation you wish to perform (/, *, -, +): ");
                    operatorInput = myInput.nextLine();
                }
            }
        }
    }

    public static double divideNumbers(double numberOne, double numberTwo)
    {
        return numberOne / numberTwo;
    }
    public static double multiplyNumbers(double numberOne, double numberTwo)
    {
        return numberOne * numberTwo;
    }
    public static double addNumbers(double numberOne, double numberTwo)
    {
        return numberOne + numberTwo;
    }
    public static double subtractNumbers(double numberOne, double numberTwo)
    {
        return numberOne - numberTwo;
    }
}
</code>```

```<code>Calculator.java:27: error: cannot find symbol
       operatorInput = input.nextChar();
                            ^
  symbol:   method nextChar()
  location: variable input of type Scanner
Calculator.java:55: error: incompatible types: <null> cannot be converted to double
                return null;
                       ^
</code>```

答:
you can change double primitive type to Double object to be able to return null value.
also you can convert operatorInput to string and read it as input.next()
here's example for what changes I suggest: </p>

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

public class Calculator
{
public static void main(String[] args)
{
    double numberOne = 0;
    double numberTwo = 0;
    String operatorInput;

Scanner input = new Scanner(System.in);

   System.out.print("Enter first number: ");
   numberOne = input.nextDouble();

   System.out.print("Enter second number: ");
   numberTwo = input.nextDouble();

   System.out.print("Enter the operation you wish to perform (/, *, -, +): ");
   operatorInput = input.next();
   System.out.println(calculate(numberOne, numberTwo,operatorInput));

}

public static Double calculate(double numberOne, double numberTwo, String operatorInput)
{
    switch (operatorInput)
    {
        case("/"):
        {
            return divideNumbers(numberOne, numberTwo);
        }
        case("*"):
        {
            return multiplyNumbers(numberOne, numberTwo);
        }
        case("+"):
        {
            return addNumbers(numberOne, numberTwo);
        }
        case("-"):
        {
            return subtractNumbers(numberOne, numberTwo);
        }
        default:
        {
            System.out.println("Invalid Input");
            return null;
        }
    }

}

public static double divideNumbers(double numberOne, double numberTwo)
{
    return numberOne / numberTwo;
}
public static double multiplyNumbers(double numberOne, double numberTwo)
{
    return numberOne * numberTwo;
}
public static double addNumbers(double numberOne, double numberTwo)
{
    return numberOne + numberTwo;
}
public static double subtractNumbers(double numberOne, double numberTwo)
{
    return numberOne - numberTwo;
}
</code>```

<p>}</p>

ContentLicense: CC BY-SA 4.0

Body:
I am teaching myself Java and started to make a calculator but I'm running into two errors when I try and run the code.

I was thinking about implementing a WHILE loop with the characters to create a loop but it did not seem to work. Really burnt out and I thought this was a good place to ask.

import java.lang.Math;
import java.util.Scanner;

public class Calculator
{

    public static void main(String[] args)
    {
        double numberOne = 0;
        double numberTwo = 0;
        String operatorInput;
        Scanner myInput = new Scanner(System.in);

       System.out.print("Enter first number: ");
       numberOne = myInput.nextDouble();

       System.out.print("Enter second number: ");
       numberTwo = myInput.nextDouble();

       System.out.print("Enter the operation you wish to perform (/, *, -, +): ");
       operatorInput = myInput.nextLine();

       double result = calculate(numberOne, numberTwo, operatorInput, myInput);

       System.out.printf("The result is: %.2f%n", result);

       myInput.close();
    }

    public static double calculate(double numberOne, double numberTwo, String operatorInput, Scanner myInput)
    {
        while(true)
        {
            switch (operatorInput)
            {
                case("/"):
                {
                    myInput.close();
                    return divideNumbers(numberOne, numberTwo);
                }
                case("*"):
                {
                    myInput.close();
                    return multiplyNumbers(numberOne, numberTwo);
                }
                case("+"):
                {
                    myInput.close();
                    return addNumbers(numberOne, numberTwo);
                }
                case("-"):
                {
                    myInput.close();
                    return subtractNumbers(numberOne, numberTwo);
                }
                default:
                {
                    System.out.println("Invalid Input");
                    System.out.print("Enter the operation you wish to perform (/, *, -, +): ");
                    operatorInput = myInput.nextLine();
                }
            }
        }
    }

    public static double divideNumbers(double numberOne, double numberTwo)
    {
        return numberOne / numberTwo;
    }
    public static double multiplyNumbers(double numberOne, double numberTwo)
    {
        return numberOne * numberTwo;
    }
    public static double addNumbers(double numberOne, double numberTwo)
    {
        return numberOne + numberTwo;
    }
    public static double subtractNumbers(double numberOne, double numberTwo)
    {
        return numberOne - numberTwo;
    }
}

Calculator.java:27: error: cannot find symbol
       operatorInput = input.nextChar();
                            ^
  symbol:   method nextChar()
  location: variable input of type Scanner
Calculator.java:55: error: incompatible types: <null> cannot be converted to double
                return null;
                       ^

Body:
you can change double primitive type to Double object to be able to return null value.
also you can convert operatorInput to string and read it as input.next()
here's example for what changes I suggest:

import java.util.Scanner;

public class Calculator
{
public static void main(String[] args)
{
    double numberOne = 0;
    double numberTwo = 0;
    String operatorInput;

Scanner input = new Scanner(System.in);

   System.out.print("Enter first number: ");
   numberOne = input.nextDouble();

   System.out.print("Enter second number: ");
   numberTwo = input.nextDouble();

   System.out.print("Enter the operation you wish to perform (/, *, -, +): ");
   operatorInput = input.next();
   System.out.println(calculate(numberOne, numberTwo,operatorInput));

}

public static Double calculate(double numberOne, double numberTwo, String operatorInput)
{
    switch (operatorInput)
    {
        case("/"):
        {
            return divideNumbers(numberOne, numberTwo);
        }
        case("*"):
        {
            return multiplyNumbers(numberOne, numberTwo);
        }
        case("+"):
        {
            return addNumbers(numberOne, numberTwo);
        }
        case("-"):
        {
            return subtractNumbers(numberOne, numberTwo);
        }
        default:
        {
            System.out.println("Invalid Input");
            return null;
        }
    }

}

public static double divideNumbers(double numberOne, double numberTwo)
{
    return numberOne / numberTwo;
}
public static double multiplyNumbers(double numberOne, double numberTwo)
{
    return numberOne * numberTwo;
}
public static double addNumbers(double numberOne, double numberTwo)
{
    return numberOne + numberTwo;
}
public static double subtractNumbers(double numberOne, double numberTwo)
{
    return numberOne - numberTwo;
}

}


问:
Module not found: Can't resolve './reducers/index'
Module not found: Can't resolve './reducers/index' in'C:\Users\Dibba\Desktop\rdx\src'
This error occurred during the build time and cannot be dismissed.

node version is
v9.11.2
npm version is
6.9.1-next.0

structure:

error message :

code:

答: Your app is not able to find your root reducer since the file name on disk doesn't match the file name in the code. There appears to be a trailing space in the filename of ./reducers/index.js, from what I can see in your first screenshot. Remove the space and your app should be able to find the file without problem.


问:
How to fix 'list index out of range' error in ZigZag problem?
I have a list index out of range error on Line 6 upon using a list of list approach to solve the ZigZag problem (https://leetcode.com/problems/zigzag-conversion/). Why is there such an error?</p>

```<code>def convert(self, s, numRows):
        row=0
        down=True
        rows=[[] for i in range(numRows)]
        for i in range(len(s)):
            rows[row].extend(s[i])
            #print(rows)
            if(row==0):
                down=True
            elif(row==len(s)-1):
                down=False
            if down:
                row+=1
            else:
                row-=1
        st=[]
        for k in rows:
            st+=k
        return ''.join(st)
</code>```

答:
The error is due to the fact that you compare (row==len(s)-1). Now s is the string, not the number of rows, so for a string that is larger than the number of rows, eventually row will be that large that it goes out of bounds.

That being said, we can improve the code effectively. We know that the row ri on which we assign the i-th element is a sequence 0, 1, ..., n-1, n-2, ..., 0, 1, .... So we can define a function for this like:

```<code>def pingpong(n):
    while True:
        yield from range(n)
        yield from range(n-2, 0, -1)
</code>```

For example:

```<code>>>> list(islice(pingpong(3), 14))
[0, 1, 2, 1, 0, 1, 2, 1, 0, 1, 2, 1, 0, 1]
>>> list(islice(pingpong(4), 14))
[0, 1, 2, 3, 2, 1, 0, 1, 2, 3, 2, 1, 0, 1]
</code>```

Then we can thus append each row of the pingpong function with the corresponding character:

```<code>def zigzag(text, numRows):
    rows = [[] for _ in range(numRows)]
    for ri, c in zip(pingpong(numRows), text):
        rows[ri].append(c)
    return ''.join(map(''.join, rows))
</code>```

Which gives us:

```<code>>>> zigzag('PAYPALISHIRING', 3)
'PAHNAPLSIIGYIR'
>>> zigzag('PAYPALISHIRING', 4)
'PINALSIGYAHRPI'
</code>```

I submitted the above approach to the LeetCode puzzle, and it got accepted (all test cases succeeded).

Body:
I have a list index out of range error on Line 6 upon using a list of list approach to solve the ZigZag problem (https://leetcode.com/problems/zigzag-conversion/). Why is there such an error?

def convert(self, s, numRows):
        row=0
        down=True
        rows=[[] for i in range(numRows)]
        for i in range(len(s)):
            rows[row].extend(s[i])
            #print(rows)
            if(row==0):
                down=True
            elif(row==len(s)-1):
                down=False
            if down:
                row+=1
            else:
                row-=1
        st=[]
        for k in rows:
            st+=k
        return ''.join(st)

Body:
The error is due to the fact that you compare (row==len(s)-1). Now s is the string, not the number of rows, so for a string that is larger than the number of rows, eventually row will be that large that it goes out of bounds.

That being said, we can improve the code effectively. We know that the row ri on which we assign the i-th element is a sequence 0, 1, ..., n-1, n-2, ..., 0, 1, .... So we can define a function for this like:

def pingpong(n):
    while True:
        yield from range(n)
        yield from range(n-2, 0, -1)

For example:

>>> list(islice(pingpong(3), 14))
[0, 1, 2, 1, 0, 1, 2, 1, 0, 1, 2, 1, 0, 1]
>>> list(islice(pingpong(4), 14))
[0, 1, 2, 3, 2, 1, 0, 1, 2, 3, 2, 1, 0, 1]

Then we can thus append each row of the pingpong function with the corresponding character:

def zigzag(text, numRows):
    rows = [[] for _ in range(numRows)]
    for ri, c in zip(pingpong(numRows), text):
        rows[ri].append(c)
    return ''.join(map(''.join, rows))

Which gives us:

>>> zigzag('PAYPALISHIRING', 3)
'PAHNAPLSIIGYIR'
>>> zigzag('PAYPALISHIRING', 4)
'PINALSIGYAHRPI'

I submitted the above approach to the LeetCode puzzle, and it got accepted (all test cases succeeded).


问:
RegEx for capturing a pattern with new lines
I have the following string

```<code>1h 30min: Title
- Description Line 1
1h 30min: Title
- Description Line 1
- Description Line 2
- Description Line 3
</code>```

And I would like to get the following results using regex.

```<code>Match 1:
  "1h 30min: Title
  - Description Line 1"

      Group 1: "1h"
      Group 2: "30min"
      Group 3: "Title
               - Description Line 1"
</code>```

```<code>Match 2:
  "1h 30min: Title
  - Description Line 1
  - Description Line 2
  - Description Line 3"

      Group 1: "1h"
      Group 2: "30min"
      Group 3: "Title
               - Description Line 1
               - Description Line 2
               - Description Line 3"
</code>```

I have the following regex https://regex101.com/r/dp5zKq/1

```<code>(([0-9]{1,2}h)\s*([0-9]{1,2}min)*\:)+?((.*\n*)*)
</code>```

However I can't figure out how to make the any character / new line regex stop when it hits a new match for the hours & minutes. Any ideas?

答:
You could match the h and min parts in group 1 and 2.

Then use a repeating pattern that matches the whole line if it does not start with the hour pattern (or include the minute afterwards as well.

```<code>([0-9]{1,2}h)[ ]*([0-9]{1,2}min):[ ]*(.*(?:\n(?![0-9]{1,2}h).*)*)
</code>```

Explanation

([0-9]{1,2}h)[ ]* Capturing group 1, the h format

([0-9]{1,2}min) Capturing group 2, the min format

:[ ]* Match : and 1+ spaces (the space does not have to be in a character class, this is only for clarity)

( Capturing group 3

.* Match any char except a newline 0+ times

(?: Non capturing group

\n(?![0-9]{1,2}h).* Match a newline, assert what is on the right is not the h pattern. If it is not, match any char except a newline 0+ times

) Close non capturing group and repeat 0+ times

) Close group 3

Regex demo

Body:
I have the following string

1h 30min: Title
- Description Line 1
1h 30min: Title
- Description Line 1
- Description Line 2
- Description Line 3

And I would like to get the following results using regex.

Match 1:
  "1h 30min: Title
  - Description Line 1"

      Group 1: "1h"
      Group 2: "30min"
      Group 3: "Title
               - Description Line 1"

Match 2:
  "1h 30min: Title
  - Description Line 1
  - Description Line 2
  - Description Line 3"

      Group 1: "1h"
      Group 2: "30min"
      Group 3: "Title
               - Description Line 1
               - Description Line 2
               - Description Line 3"

I have the following regex https://regex101.com/r/dp5zKq/1

(([0-9]{1,2}h)\s*([0-9]{1,2}min)*\:)+?((.*\n*)*)

However I can't figure out how to make the any character / new line regex stop when it hits a new match for the hours & minutes. Any ideas?

Body:
You could match the h and min parts in group 1 and 2.

Then use a repeating pattern that matches the whole line if it does not start with the hour pattern (or include the minute afterwards as well.

([0-9]{1,2}h)[ ]*([0-9]{1,2}min):[ ]*(.*(?:\n(?![0-9]{1,2}h).*)*)

Explanation

([0-9]{1,2}h)[ ]* Capturing group 1, the h format

([0-9]{1,2}min) Capturing group 2, the min format

:[ ]* Match : and 1+ spaces (the space does not have to be in a character class, this is only for clarity)

( Capturing group 3

.* Match any char except a newline 0+ times

(?: Non capturing group

\n(?![0-9]{1,2}h).* Match a newline, assert what is on the right is not the h pattern. If it is not, match any char except a newline 0+ times

) Close non capturing group and repeat 0+ times

) Close group 3

Regex demo


问:
A way of skipping tests in a GWTTestCase
Is there something similar to jUnit's @Ignore annotation for the GWTTestCase?</p>

答:
I haven't used this API, but it looks like GWTTestCase extends junit.framework.TestCase.
Hence annotations wont be available and you'll have to manually rename your testXX methods to something that doesn't start with 'test'

ContentLicense: CC BY-SA 3.0


问:
how to show videos and images with react-native-image-picker in react native
```<code>import ImagePicker from 'react-native-image-picker';
   const options = {
      title: 'Select Image',
      takePhotoButtonTitle:'take a photo',
      chooseFromlibraryButtonTitle:'choose from gallery',
      quality:1
    };

    class Upload extends Component <{}>{
        static navigationOptions = { header: null }

        constructor(){
            super()
            this.state ={
                ImageSource:null
            }
        }
        selectPhoto(){
                    ImagePicker.showImagePicker(options, (response) => {
                console.log('Response = ', response);

                if (response.didCancel) {
                console.log('User cancelled image picker');
                } else if (response.error) {
                console.log('ImagePicker Error: ', response.error);
                } else {
                let source = { uri: response.uri };
                this.setState({
                  ImageSource: source,
                });
                }
                });
        }
</code>```

how to show videos with image in react native and by using video soucr uri state still only shows the image
2.and if using mediatypes all still is shows the image how to fix this

答:
Here you go</p>

```<code>   ImagePicker.showImagePicker({
        title: 'Choose Image or Video',
        customButtons: [{ name: 'image', title: 'Take a Photo' },{ name: 'video', title: 'Take a Video' }],
        chooseFromLibraryButtonTitle: null,
        takePhotoButtonTitle: null,
    }, (res) => {
        if(res.customButton ){
            ImagePicker.launchCamera({
                mediaType: res.customButton,
                videoQuality: 'high',
                quality: 1,
            }, (response) => {
                // Same code as in above section!
            });
        }
    });
</code>```

Body:
import ImagePicker from 'react-native-image-picker';
   const options = {
      title: 'Select Image',
      takePhotoButtonTitle:'take a photo',
      chooseFromlibraryButtonTitle:'choose from gallery',
      quality:1
    };

    class Upload extends Component <{}>{
        static navigationOptions = { header: null }

        constructor(){
            super()
            this.state ={
                ImageSource:null
            }
        }
        selectPhoto(){
                    ImagePicker.showImagePicker(options, (response) => {
                console.log('Response = ', response);

                if (response.didCancel) {
                console.log('User cancelled image picker');
                } else if (response.error) {
                console.log('ImagePicker Error: ', response.error);
                } else {
                let source = { uri: response.uri };
                this.setState({
                  ImageSource: source,
                });
                }
                });
        }

how to show videos with image in react native and by using video soucr uri state still only shows the image
2.and if using mediatypes all still is shows the image how to fix this

Body:
Here you go

   ImagePicker.showImagePicker({
        title: 'Choose Image or Video',
        customButtons: [{ name: 'image', title: 'Take a Photo' },{ name: 'video', title: 'Take a Video' }],
        chooseFromLibraryButtonTitle: null,
        takePhotoButtonTitle: null,
    }, (res) => {
        if(res.customButton ){
            ImagePicker.launchCamera({
                mediaType: res.customButton,
                videoQuality: 'high',
                quality: 1,
            }, (response) => {
                // Same code as in above section!
            });
        }
    });


问:
Using an existing function, how to define a new function with different default optional arguments?
Given a function fxn1()

def fxn1(a,b=1):
    return a*b
```

<p>I would like to do something like:</p>

<pre class="lang-py prettyprint-override"><code>fxn2=fxn1(.,b=2)
</code>```

In words, I would like to make a new function fxn2() which is identical to fxn1() but with different default values of optional arguments. I have not been able to find an answer/direction on web.

答:
You can use partial function:</p>

```<code>from functools import partial
fxn2 = partial(fxn1, b=2)

fxn2(1)
</code>```

Body:
Given a function fxn1()

def fxn1(a,b=1):
    return a*b

I would like to do something like:

fxn2=fxn1(.,b=2)

In words, I would like to make a new function fxn2() which is identical to fxn1() but with different default values of optional arguments. I have not been able to find an answer/direction on web.

Body:
You can use partial function:

from functools import partial
fxn2 = partial(fxn1, b=2)

fxn2(1)


答:
You can use functools.partial (official doc):

```<code>from functools import partial

def fxn1(a,b=1):
    return a*b

fxn2 = partial(fxn1, b=2)

print(fxn2(4))
</code>```

Prints:

```<code>8
</code>```

Title: Using an existing function, how to define a new function with different default optional arguments?

Body:
You can use functools.partial (official doc):

from functools import partial

def fxn1(a,b=1):
    return a*b

fxn2 = partial(fxn1, b=2)

print(fxn2(4))

Prints:

8


问:
Spaces not registered when using onChange on <input>
Upon pressing of space onChange event is not getting called on my html input element.

Here's what I tried.

```<code>class FilterDropDown extends React.PureComponent {
state = {
      query: '',
    };

handleKeyPress = (evt) => {
      this.setState({ query: evt.target.value });
    };

render() {
      const { placeholder, items, id } = this.props;
      return (
        <DropDown
          placeholder={placeholder}
          open={this.state.show}
          onToggle={this.disableAppScrollAndToggleShowState}
          onSelect={this.onSelect}
          value={this.props[id]}
        >
          {
            this.props.filterable
            && (
            // eslint-disable-next-line react/jsx-no-undef
            <DropDown.Item disabled className="filters__option-text-filter">
              <div className="wrapper">
                <Label className="filter-dropdown__search-icon" />
                <input
                  type="text"
                  onChange={this.handleKeyPress}
                  size="sm"
                  placeholder={this.props.filterPlaceholder}
                  aria-label="filter-dropdown"
                  value={this.state.query}
                />
                <Button className="filter-dropdown__clear" onClick={this.resetQuery} />
              </div>
            </DropDown.Item>
            )
          }

          {
            items
              .filter(item => item.value.length > 0
                && item.value.toLowerCase().includes(this.state.query.toLowerCase()))
              .map(item => (
                <DropDown.Item
                  active={item.value === this.props[id]}
                  key={item.value}
                  eventKey={item.value}
                >
                  <span className="filter-options">{`${item.value} (${item.count})`}</span>
                </DropDown.Item>
              ))
          }
        </DropDown>
      );
    }
}
</code>```

I am not posting the whole code but just enough to understand the use.
Also this input field is within the React Bootstraps Dropdown element, which is not allowing the input to accept spaces.

Heres a link of the documentation of react Dropdown https://react-bootstrap.github.io/components/dropdowns/. If we look at the Custom Dropdown Components example the input box implemented there also doesn't allow spaces.

Is there a way I can deal with that?
Thanks.

答:
The code even is fine, is not optimal (specially for learning porpuses).

What it might what you are looking for is to visualize the value in the imput at the time the user is typing:

```<code>import React from 'react';

class MyComponent extends React.Component {
    state = {
        query: '',
    }

    handleKeyPress = (evt) => {
        this.setState({ query: evt.target.value }, () => {
            console.log("query: " + this.state.query) // this is for debugging
        });
    };

    render() {
        return (
            <div>
                <input type="text"
                onChange={this.handleKeyPress}
                size="sm"
                placeholder={this.props.filterPlaceholder}
                aria-label="filter-dropdown"
                value={this.state.query}
                />
                <h1>query: {this.state.query}</h1>
                {/* this is for visualing the changes in the component*/}
            </div>
        );
    }
}
</code>```

Body:
Upon pressing of space onChange event is not getting called on my html input element.

Here's what I tried.

class FilterDropDown extends React.PureComponent {
state = {
      query: '',
    };

handleKeyPress = (evt) => {
      this.setState({ query: evt.target.value });
    };

render() {
      const { placeholder, items, id } = this.props;
      return (
        <DropDown
          placeholder={placeholder}
          open={this.state.show}
          onToggle={this.disableAppScrollAndToggleShowState}
          onSelect={this.onSelect}
          value={this.props[id]}
        >
          {
            this.props.filterable
            && (
            // eslint-disable-next-line react/jsx-no-undef
            <DropDown.Item disabled className="filters__option-text-filter">

                <input
                  type="text"
                  onChange={this.handleKeyPress}
                  size="sm"
                  placeholder={this.props.filterPlaceholder}
                  aria-label="filter-dropdown"
                  value={this.state.query}
                />
                <Button className="filter-dropdown__clear" onClick={this.resetQuery} />

            </DropDown.Item>
            )
          }

          {
            items
              .filter(item => item.value.length > 0
                && item.value.toLowerCase().includes(this.state.query.toLowerCase()))
              .map(item => (
                <DropDown.Item
                  active={item.value === this.props[id]}
                  key={item.value}
                  eventKey={item.value}
                >
                  {`${item.value} (${item.count})`}
                </DropDown.Item>
              ))
          }
        </DropDown>
      );
    }
}

I am not posting the whole code but just enough to understand the use.
Also this input field is within the React Bootstraps Dropdown element, which is not allowing the input to accept spaces.

Heres a link of the documentation of react Dropdown https://react-bootstrap.github.io/components/dropdowns/. If we look at the Custom Dropdown Components example the input box implemented there also doesn't allow spaces.

Is there a way I can deal with that?
Thanks.

Body:
The code even is fine, is not optimal (specially for learning porpuses).

What it might what you are looking for is to visualize the value in the imput at the time the user is typing:

import React from 'react';

class MyComponent extends React.Component {
    state = {
        query: '',
    }

    handleKeyPress = (evt) => {
        this.setState({ query: evt.target.value }, () => {
            console.log("query: " + this.state.query) // this is for debugging
        });
    };

    render() {
        return (
            <div>
                <input type="text"
                onChange={this.handleKeyPress}
                size="sm"
                placeholder={this.props.filterPlaceholder}
                aria-label="filter-dropdown"
                value={this.state.query}
                />
                <h1>query: {this.state.query}</h1>
                {/* this is for visualing the changes in the component*/}
            </div>
        );
    }
}


问:
Magento 2 Default RSS Generator only part of products
I am using Magento 2 Community 2.1.9, I am also set the default RSS feeds. I reviewed the content of the XML generated, it shows only some of the eligible products.

For example, I set to generate XML for a category of 'shoes', only some of the shoes inside this category are included in the XML. Most are not included.

I am confused, do you have any idea? Is there a bug? How I can modify the code to make it include everything under the said category.

Thanks.

答:
Please check if the products are visible/in stock/enable

Also compare any one of the product that is not seen in the feed with the product that is seen to check all the attribute values are set properly.

Hope this helps


问:
If Loop to find the latest value from multiple textboxes from one form to populate another textbox is another form
I have a form called "Label" and another form called "Sheeter".
Sheeter form has 12 textboxes (Pallet1), (Pallet2), (Pallet3)...

The user will enter other details in the "Sheeter" form, but they will stay on the page till all the 12 boxes are filled up. Pallet textboxes basically captures the time at which the different pallets are made (which is for used as tracking numbers). As soon as one Pallet is made User will double click the textbox "Pallet1" and it will be populated with current time. Next the user wants to use this value in textbox Pallet1 to print a label. I have made a button which will fetch the value of Pallet1 textbox in a textbox in Label Form.
The user doesn't want to close the Sheeter form at this point, and will wait on the form till the next Pallet is produced, again double click on the textbox "Pallet2" to get the time and expect that once the Print button is clicked it takes the new value to populate the textbox label on form label.

I have tried if loops of two different types, however I am unsure of the syntax.

First logic is to see if a textbox is empty and if its true fetch the value from the previous textbox for the label.

Second logic is to compare the value of the textboxes and which is higher, fetch that value.

```<code>If Me.Pallet2.Value = "" Then

Forms![LabelSHEETER1].Pallet = Me.Pallet1
Me.JOB.SetFocus

Else
If Me.Pallet3.Value = Null Then

Forms![LabelSHEETER1].Pallet = Me.Pallet2
Me.JOB.SetFocus

Else

If Me.Pallet4.Value = Null Then

Forms![LabelSHEETER1].Pallet = Me.Pallet3
Me.JOB.SetFocus

End If
End If
End If
</code>```

```<code>If Me.Pallet2.Value ="" Then

Forms![LabelSHEETER1].Pallet = Me.Pallet1
Me.JOB.SetFocus

Else
If Me.Pallet2.Value >Me.Pallet1.value Then

Forms![LabelSHEETER1].Pallet = Me.Pallet2
Me.JOB.SetFocus

Else

If Me.Pallet3.Value >Me.Pallet2.value Then

Forms![LabelSHEETER1].Pallet = Me.Pallet3
Me.JOB.SetFocus

End If
End If
End If
</code>```

I am unsure if I should write "" or Null, have tried both, none of them work.

Also neither of the logic seem to be working (dont know if syntax is incorrect or logic itself is flawed)

答:
Oh wait, I found the solution:

```<code>If IsNull(Me.Pallet2.Value) Then
</code>```

Forms![LabelSHEETER1].Pallet = Me.Pallet1
Me.JOB.SetFocus

Else

If IsNull(Me.Pallet3.Value) Then

Forms![LabelSHEETER1].Pallet = Me.Pallet2
Me.JOB.SetFocus

Else

If IsNull(Me.Pallet4.Value) Then

Forms![LabelSHEETER1].Pallet = Me.Pallet3
Me.JOB.SetFocus

End If
End If
End If

Body:
I have a form called "Label" and another form called "Sheeter".
Sheeter form has 12 textboxes (Pallet1), (Pallet2), (Pallet3)...

The user will enter other details in the "Sheeter" form, but they will stay on the page till all the 12 boxes are filled up. Pallet textboxes basically captures the time at which the different pallets are made (which is for used as tracking numbers). As soon as one Pallet is made User will double click the textbox "Pallet1" and it will be populated with current time. Next the user wants to use this value in textbox Pallet1 to print a label. I have made a button which will fetch the value of Pallet1 textbox in a textbox in Label Form.
The user doesn't want to close the Sheeter form at this point, and will wait on the form till the next Pallet is produced, again double click on the textbox "Pallet2" to get the time and expect that once the Print button is clicked it takes the new value to populate the textbox label on form label.

I have tried if loops of two different types, however I am unsure of the syntax.

First logic is to see if a textbox is empty and if its true fetch the value from the previous textbox for the label.

Second logic is to compare the value of the textboxes and which is higher, fetch that value.

If Me.Pallet2.Value = "" Then

Forms![LabelSHEETER1].Pallet = Me.Pallet1
Me.JOB.SetFocus

Else
If Me.Pallet3.Value = Null Then

Forms![LabelSHEETER1].Pallet = Me.Pallet2
Me.JOB.SetFocus

Else

If Me.Pallet4.Value = Null Then

Forms![LabelSHEETER1].Pallet = Me.Pallet3
Me.JOB.SetFocus

End If
End If
End If

If Me.Pallet2.Value ="" Then

Forms![LabelSHEETER1].Pallet = Me.Pallet1
Me.JOB.SetFocus

Else
If Me.Pallet2.Value >Me.Pallet1.value Then

Forms![LabelSHEETER1].Pallet = Me.Pallet2
Me.JOB.SetFocus

Else

If Me.Pallet3.Value >Me.Pallet2.value Then

Forms![LabelSHEETER1].Pallet = Me.Pallet3
Me.JOB.SetFocus

End If
End If
End If

I am unsure if I should write "" or Null, have tried both, none of them work.

Also neither of the logic seem to be working (dont know if syntax is incorrect or logic itself is flawed)

Body:
Oh wait, I found the solution:

If IsNull(Me.Pallet2.Value) Then

Forms![LabelSHEETER1].Pallet = Me.Pallet1
Me.JOB.SetFocus

Else

If IsNull(Me.Pallet3.Value) Then

Forms![LabelSHEETER1].Pallet = Me.Pallet2
Me.JOB.SetFocus

Else

If IsNull(Me.Pallet4.Value) Then

Forms![LabelSHEETER1].Pallet = Me.Pallet3
Me.JOB.SetFocus

End If
End If
End If


问:
Why print_r() still exists?
```<code>print_r(array('name'=> 'bob', 'age' => 20, 'sex' => 'man'));
</code>```

Then :

```<code>Array {
    [name] => bob,
    [age] => 20,
    [sex] => man }

var_dump(array('name' => 'bob', 'age' => 20));
</code>```

will display:

```<code>array(2) {
    ['name'] => string(3) 'bob'
    ['age'] => int(20) }
</code>```

var_dump is perfect to debug  and  much better than print_r. But why print_r still exists? or print_r has some advantage i don't know

答:
If you output print_r between to ```</code> tags then it gives you a much more readable output than var_dump. That is my main reason for using while debugging.</p>

```Array
(
    [name] => bob,
    [age] => 20,
    [sex] => man
)
```

Basically it gives you a formatted output that var_dump doesn't. Although it doesn't give you quite as detailed type information.

Title: Why print_r() still exists?

Body:
print_r(array('name'=> 'bob', 'age' => 20, 'sex' => 'man'));

Then :

Array {
    [name] => bob,
    [age] => 20,
    [sex] => man }

var_dump(array('name' => 'bob', 'age' => 20));

will display:

array(2) {
    ['name'] => string(3) 'bob'
    ['age'] => int(20) }

var_dump is perfect to debug  and  much better than print_r. But why print_r still exists? or print_r has some advantage i don't know

Body:
If you output print_r between to <pre> tags then it gives you a much more readable output than var_dump. That is my main reason for using while debugging.

Array
(
    [name] => bob,
    [age] => 20,
    [sex] => man
)

Basically it gives you a formatted output that var_dump doesn't. Although it doesn't give you quite as detailed type information.


问:
Pyrebase cannot find an email
I was following the Pyrebase tutorial and I got it up and running for one user account. I added another user account to the code and now I'm getting an error saying email address isn't found. The user account has been added to the Firebase User, and given the same access as the first account.

I've confirmed that the account has been added to Firebase with the correct email and password.

user = auth.sign_in_with_email_and_password("someEmailAddress@gmail.com", "Secret Password")

I'm expecting a return code of 0, stating it's connected successfully. However, I'm getting the error below:

raise HTTPError(e, request_object.text)
requests.exceptions.HTTPError: [Errno 400 Client Error: Bad Request for url: https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key=AIzaSyDgn6aURRvEDP-M738sy7oo0ubbNqqLXzY] {
  "error": {
    "code": 400,
    "message": "EMAIL_NOT_FOUND",
    "errors": [
      {
        "message": "EMAIL_NOT_FOUND",
        "domain": "global",
        "reason": "invalid"

答: I have found my error. After adding the account under the Project Overview -> Project settings -> Users and Permissions tab, I forgot to add the account under the Authentication tab on the left hand side. Once that's added, the code works as expected. </p>

Title: Pyrebase cannot find an email


问:
wkhtmltopdf - limit table of content child nodes
I am using wkhtmltodpf along with knp-snappy and I am trying to limit TOC to max 3 childrens. I have defined custom xsl file which looks like this:

```<code><xsl:template match="outline:outline">
    <html>
        <head>
        </head>
        <body>
            <h1>Table of Contents</h1>
            <ul><xsl:apply-templates select="outline:item/outline:item"/></ul>
        </body>
    </html>
</xsl:template>
<xsl:template match="outline:item">
    <li class="level-{count(ancestor::*) - 1}">
        <xsl:if test="((@title!='') and (@title!='Table of Contents'))">
            <div>
                <a>
                    <xsl:if test="@link">
                        <xsl:attribute name="href"><xsl:value-of select="@link"/></xsl:attribute>
                    </xsl:if>
                    <xsl:if test="@backLink">
                        <xsl:attribute name="name"><xsl:value-of select="@backLink"/></xsl:attribute>
                    </xsl:if>
                    <xsl:value-of select="@title" />
                </a>
                <span> <xsl:value-of select="@page" /> </span>
            </div>
        </xsl:if>
        <ul class="level-{count(ancestor::*) - 1}">
            <xsl:comment>added to prevent self-closing tags in QtXmlPatterns</xsl:comment>
            <xsl:apply-templates select="outline:item"/>
        </ul>
    </li>
</xsl:template>
</code>```

and with output:

What I need to show only 1,2,3 levels
I'm not good into XML and I really don't know how could I limit it :/
I am using these tags to create my table of content:

1 - h4 tag
2 - h3 tag
3 - h2 tag
...

答:
solved by myself

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:outline="http://wkhtmltopdf.org/outline"
                xmlns="http://www.w3.org/1999/xhtml">
    <xsl:output doctype-public="-//W3C//DTD XHTML 1.0 Strict//EN"
                doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitiona
l.dtd"
                indent="yes" />
    <xsl:template match="outline:outline">
        <html>
            <head>
                <title>Table of Contents</title>
                <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
                <style>
                    * {
                    padding: 0;
                    margin: 0;
                    font-family: Arial, Helvetica, sans-seriff;
                    }

                    .book-toc-title {
                        margin-bottom: .5em;
                    }

                    .book-toc-list {

                    }

                    .book-toc-list .book-toc-list {

                    }

                    .book-toc-item {
                        list-style-type: none;
                    }

                    .book-toc-item .book-toc-item {
                        list-style-type: none;
                        list-style-position: outside;
                        font-size: 14px;
                        margin: 0.2em 0 0 2em;
                        padding-top: 0.2em;
                    }

                    .book-toc-item.level_1 {
                        padding-top: 0.5em;
                        margin-bottom: 0.2em
                    }
                    .book-toc-item.level_1:first-child {display: none;}
                    .book-toc-item.level_2 {padding-bottom: 0.2em;}
                    .book-toc-item.level_3 {}

                    .book-toc-item-inner {
                    }

                    .book-toc-item-title {
                    display: block;
                    padding-bottom: 5px;
                    font-size: 16px;
                    font-weight: bold;
                    }

                    .book-toc-item-title .text {
                    display: block;
                    border-bottom: 1px dotted #000;
                    height: 19px;
                    }

                    .book-toc-item-title .text-inner {
                    background-color: #fff;
                    line-height: 30px;
                    padding-right: 7px;
                    }

                    .book-toc-item .book-toc-item .book-toc-item-title {
                    font-weight: normal;
                    }

                    .book-toc-item-pagenum {
                    position: relative;
                    float: right;
                    top: 5px;
                    paddig-bottom: 0;
                    padding-left: 5px;
                    font-size: 14px;
                    line-height: 20px;
                    text-align: right;
                    background-color: #fff;
                    }

                </style>
            </head>
            <body>
                <h1>Table of Contents</h1>
                <ul><xsl:apply-templates select="outline:item/outline:item"/></ul>
            </body>
        </html>
    </xsl:template>

    <xsl:template match="outline:item[count(ancestor::outline:item)<=3]">
        <li class="book-toc-item level_{count(ancestor::outline:item)}">
            <xsl:if test="@title!=''">
                <div class="book-toc-item-inner">

                    <span class="book-toc-item-pagenum">
                        <xsl:value-of select="@page"/>
                    </span>

                    <a class="book-toc-item-title">
                        <xsl:if test="@link">
                            <xsl:attribute name="href">
                                <xsl:value-of select="@link"/>
                            </xsl:attribute>
                        </xsl:if>

                        <xsl:if test="@backLink">
                            <xsl:attribute name="name">
                                <xsl:value-of select="@backLink"/>
                            </xsl:attribute>
                        </xsl:if>

                        <span class="text">
                            <span class="text-inner">
                                <xsl:value-of select="@title"/>
                            </span>
                        </span>
                    </a>

                </div>
            </xsl:if>

            <ol class="book-toc-list">
                <xsl:comment>added to prevent self-closing tags in QtXmlPatterns</xsl:comment>
                <xsl:apply-templates select="outline:item"/>
            </ol>
        </li>
    </xsl:template>
</xsl:stylesheet>
</code>```

Body:
I am using wkhtmltodpf along with knp-snappy and I am trying to limit TOC to max 3 childrens. I have defined custom xsl file which looks like this:

<xsl:template match="outline:outline">

Table of Contents

<xsl:apply-templates select="outline:item/outline:item"/>

</xsl:template>
<xsl:template match="outline:item">

        <xsl:if test="((@title!='') and (@title!='Table of Contents'))">

                    <xsl:if test="@link">
                        <xsl:attribute name="href"><xsl:value-of select="@link"/></xsl:attribute>
                    </xsl:if>
                    <xsl:if test="@backLink">
                        <xsl:attribute name="name"><xsl:value-of select="@backLink"/></xsl:attribute>
                    </xsl:if>
                    <xsl:value-of select="@title" />

                 <xsl:value-of select="@page" />

        </xsl:if>

            <xsl:comment>added to prevent self-closing tags in QtXmlPatterns</xsl:comment>
            <xsl:apply-templates select="outline:item"/>

</xsl:template>

and with output:

What I need to show only 1,2,3 levels
I'm not good into XML and I really don't know how could I limit it :/
I am using these tags to create my table of content:

1 - h4 tag
2 - h3 tag
3 - h2 tag
...

Body:
solved by myself

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:outline="http://wkhtmltopdf.org/outline"
                xmlns="http://www.w3.org/1999/xhtml">
    <xsl:output doctype-public="-//W3C//DTD XHTML 1.0 Strict//EN"
                doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitiona
l.dtd"
                indent="yes" />
    <xsl:template match="outline:outline">
        <html>
            <head>
                <title>Table of Contents</title>
                <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
                <style>
                    * {
                    padding: 0;
                    margin: 0;
                    font-family: Arial, Helvetica, sans-seriff;
                    }

                    .book-toc-title {
                        margin-bottom: .5em;
                    }

                    .book-toc-list {

                    }

                    .book-toc-list .book-toc-list {

                    }

                    .book-toc-item {
                        list-style-type: none;
                    }

                    .book-toc-item .book-toc-item {
                        list-style-type: none;
                        list-style-position: outside;
                        font-size: 14px;
                        margin: 0.2em 0 0 2em;
                        padding-top: 0.2em;
                    }

                    .book-toc-item.level_1 {
                        padding-top: 0.5em;
                        margin-bottom: 0.2em
                    }
                    .book-toc-item.level_1:first-child {display: none;}
                    .book-toc-item.level_2 {padding-bottom: 0.2em;}
                    .book-toc-item.level_3 {}

                    .book-toc-item-inner {
                    }

                    .book-toc-item-title {
                    display: block;
                    padding-bottom: 5px;
                    font-size: 16px;
                    font-weight: bold;
                    }

                    .book-toc-item-title .text {
                    display: block;
                    border-bottom: 1px dotted #000;
                    height: 19px;
                    }

                    .book-toc-item-title .text-inner {
                    background-color: #fff;
                    line-height: 30px;
                    padding-right: 7px;
                    }

                    .book-toc-item .book-toc-item .book-toc-item-title {
                    font-weight: normal;
                    }

                    .book-toc-item-pagenum {
                    position: relative;
                    float: right;
                    top: 5px;
                    paddig-bottom: 0;
                    padding-left: 5px;
                    font-size: 14px;
                    line-height: 20px;
                    text-align: right;
                    background-color: #fff;
                    }

                </style>
            </head>
            <body>
                <h1>Table of Contents</h1>
                <ul><xsl:apply-templates select="outline:item/outline:item"/></ul>
            </body>
        </html>
    </xsl:template>

    <xsl:template match="outline:item[count(ancestor::outline:item)&lt;=3]">
        <li class="book-toc-item level_{count(ancestor::outline:item)}">
            <xsl:if test="@title!=''">
                <div class="book-toc-item-inner">

                    <span class="book-toc-item-pagenum">
                        <xsl:value-of select="@page"/>
                    </span>

                    <a class="book-toc-item-title">
                        <xsl:if test="@link">
                            <xsl:attribute name="href">
                                <xsl:value-of select="@link"/>
                            </xsl:attribute>
                        </xsl:if>

                        <xsl:if test="@backLink">
                            <xsl:attribute name="name">
                                <xsl:value-of select="@backLink"/>
                            </xsl:attribute>
                        </xsl:if>

                        <span class="text">
                            <span class="text-inner">
                                <xsl:value-of select="@title"/>
                            </span>
                        </span>
                    </a>

                </div>
            </xsl:if>

            <ol class="book-toc-list">
                <xsl:comment>added to prevent self-closing tags in QtXmlPatterns</xsl:comment>
                <xsl:apply-templates select="outline:item"/>
            </ol>
        </li>
    </xsl:template>
</xsl:stylesheet>


问:
Printing generator objects in python
I created my own iterator (to learn how they work) as follows

```<code>class Reverse():
    def __init__(self, word):
        self.word = word
        self.index = len(word)
    def __iter__(self):
        return self
    def __next__(self):
        self.index -=1
        if self.index < 0:
            raise StopIteration
        return self.word[self.index]

print (char for char in Reverse("word"),end="")
</code>```

I know I can say:

```<code>rev = Reverse("word")
for char in rev:
    print(char, end="")
</code>```

but I was hoping to be able to do it in a single line

```<code>print (char for char in Reverse("word"),end="")
</code>```

This doesn't work and raises an error. If I remove the end="" it prints out a generator object. Surely by including a for loop in the print statement it should iterate through my generator object and print each item?
Why does this not happen

答:
Surely by including a for loop in the print statement it should iterate through my generator object and print each item?

No, it will print the string representation of a generator object.

If you want to output what this object generates, you can use a starred expression:

```<code>print(*(char for char in Reverse("word")),end="")
</code>```

This is because the for loop in a generator expression isn't actually executed at the instantiation of the generator object, and that's the whole point of generators: you can have an infinite generator and still be able to pass it around as a regular value and consume finite chunks of it, all that without having infinite amounts of memory.

Title: Printing generator objects in python

Body:
I created my own iterator (to learn how they work) as follows

class Reverse():
    def __init__(self, word):
        self.word = word
        self.index = len(word)
    def __iter__(self):
        return self
    def __next__(self):
        self.index -=1
        if self.index < 0:
            raise StopIteration
        return self.word[self.index]

print (char for char in Reverse("word"),end="")

I know I can say:

rev = Reverse("word")
for char in rev:
    print(char, end="")

but I was hoping to be able to do it in a single line

print (char for char in Reverse("word"),end="")

This doesn't work and raises an error. If I remove the end="" it prints out a generator object. Surely by including a for loop in the print statement it should iterate through my generator object and print each item?
Why does this not happen

Body:
Surely by including a for loop in the print statement it should iterate through my generator object and print each item?

No, it will print the string representation of a generator object.

If you want to output what this object generates, you can use a starred expression:

print(*(char for char in Reverse("word")),end="")

This is because the for loop in a generator expression isn't actually executed at the instantiation of the generator object, and that's the whole point of generators: you can have an infinite generator and still be able to pass it around as a regular value and consume finite chunks of it, all that without having infinite amounts of memory.


问:
Encode text into WPARAM for win32api.SendMessage()
I'm trying to call win32api.SendMessage() via my Python application (i.e. the sending app).

The receiving app's API states that the format of the message is: ::SendMessage(<app_name>, <msg_name>, (WPARAM) <value>)

However, value is actually a string of between 3 to 4 characters (no spaces).

My Question

What is the correct way of using win32api.SendMessage, especially with regard to value?

Can I simply put the string, as in:
win32api.SendMessage(<app_name>, <msg_name>, "ABC")?

Or do I need to convert the string to WPARAM type (and if so, how do I do that)?

I've been developing in Linux Python and have very little experience with Windows and C++. Would appreciate any assistance.

Thanks in advance!

P.s. In response to comments, the receiving app is actually AmiBroker and the actual message format given in the API documentation is:
::SendMessage( g_hAmiBrokerWnd, WM_USER_STREAMING_UPDATE, (WPARAM) Ticker, (LPARAM) &recentInfoStructureForGivenTicker );
The 'string' I mentioned earlier is 'Ticker', which the author says is a string (char*). I didn't include that initially as I thought the actual message format is not important.

RESEARCH: I read from this that WPARAM is essentially an integer type, and this led me to win32api. Among the many articles I read; none of them helped to answer my questions above (or at least so I think).

答:
If you are sending a custom message then it is perfectly ok to send data in the WPARAM. If you are sending a standard window message then WPARAM should really be set to a value that is correct for the message sent.

Note WPARAM is a 32 bit integer so if you cannot fit your string into 32 bits (AKA 4 bytes) then no you cannot do this. Note if you are sending ASCII this means you can only pass 4 characters (one per byte). I don't know python, but I would imagine you could bit shift the 4 bytes and ADD or OR them into a single 32 bit integer to send as the WPARAM, maybe something like this?

Pseudo code follows

```<code>Int32 wparam = 0
wparam = wparam | ((Int32)chr[0] << (32 - (8 * 1)))
wparam = wparam | ((Int32)chr[1] << (32 - (8 * 2)))
wparam = wparam | ((Int32)chr[2] << (32 - (8 * 3)))
wparam = wparam | ((Int32)chr[3] << (32 - (8 * 4)))
</code>```

See the SendMessage function on the Micorsoft website.

https://learn.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-sendmessage

See a large number of other questions about sending a custom message.

Sending a Custom windows message...custom data marshalling

Body:
If you are sending a custom message then it is perfectly ok to send data in the WPARAM. If you are sending a standard window message then WPARAM should really be set to a value that is correct for the message sent.

Note WPARAM is a 32 bit integer so if you cannot fit your string into 32 bits (AKA 4 bytes) then no you cannot do this. Note if you are sending ASCII this means you can only pass 4 characters (one per byte). I don't know python, but I would imagine you could bit shift the 4 bytes and ADD or OR them into a single 32 bit integer to send as the WPARAM, maybe something like this?

Pseudo code follows

Int32 wparam = 0
wparam = wparam | ((Int32)chr[0] << (32 - (8 * 1)))
wparam = wparam | ((Int32)chr[1] << (32 - (8 * 2)))
wparam = wparam | ((Int32)chr[2] << (32 - (8 * 3)))
wparam = wparam | ((Int32)chr[3] << (32 - (8 * 4)))

See the SendMessage function on the Micorsoft website.

https://learn.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-sendmessage

See a large number of other questions about sending a custom message.

Sending a Custom windows message...custom data marshalling


Title: Print rows from output1 based on output2 values

Body:
df1

slot              Time     Location  User
56  2017-10-26 22:15:00     89        1
2   2017-10-27 00:30:00     54        1
20  2017-10-28 05:00:00     64        1
24  2017-10-29 06:00:00     2         1
91  2017-11-01 22:45:00     78        1
62  2017-11-02 15:30:00     99        1
91  2017-11-02 22:45:00     34        1
47  2017-10-26 20:15:00     465       2
1   2017-10-27 00:10:00     67        2
20  2017-10-28 05:00:00     5746      2
28  2017-10-29 07:00:00     36        2
91  2017-11-01 22:45:00     786       2
58  2017-11-02 14:30:00     477       2
95  2017-11-02 23:45:00     7322      2

df2

slot
2
91
62
58

I need the output df3 as

slot              Time    Location  User
2   2017-10-27 00:30:00     54        1
91  2017-11-01 22:45:00     78        1
91  2017-11-02 22:45:00     34        1
91  2017-11-01 22:45:00     786       2
62  2017-11-02 15:30:00     99        1
58  2017-11-02 14:30:00     477       2

if those are csv file then we can join them

join File1 file2 > file3

But how can we do the same for the outputs in Jupyter notebook

Body:
Try isin:

df1[df1.slot.isin(df2.slot)]

Output:

    slot               Time     Location    User
1   2   2017-10-27 00:30:00     54          1
4   91  2017-11-01 22:45:00     78          1
5   62  2017-11-02 15:30:00     99          1
6   91  2017-11-02 22:45:00     34          1
11  91  2017-11-01 22:45:00     786         2
12  58  2017-11-02 14:30:00     477         2


问:
Output arbitrary tag element in Facelets?
I want to output a tag with dynamic attributes like:

```<code><foo attr1="val1"
     attr2="val1"
     attr3="val1">
    Contents
</foo>
</code>```

Where attribute names is unknown in compile time.

It's obviously c:forEach or ui:repeat doesn't work here:

```<code><foo <c:forEach ... /> >
</code>```

So, is there something like this?

```<code><x:element name='foo'>
    <forEach>
        <x:attribute name='#{"attr" + index}'>
            #{"val" + index}
        </x:attribute>
    </forEach>
</x:element>
</code>```

Thanks.

答:
You can do it with f:attribute (xmlns:f=http://java.sun.com/jsf/core), which would associates an attribute with the nearest parent UIComponent.

See:

http://download.oracle.com/docs/cd/E17802_01/j2ee/j2ee/javaserverfaces/1.2/docs/tlddocs/

http://myfaces.apache.org/core11/myfaces-impl/tlddoc/f/attribute.html

Body:
I want to output a tag with dynamic attributes like:

<foo attr1="val1"
     attr2="val1"
     attr3="val1">
    Contents
</foo>

Where attribute names is unknown in compile time.

It's obviously c:forEach or ui:repeat doesn't work here:

<foo <c:forEach ... /> >

So, is there something like this?

<x:element name='foo'>
    <forEach>
        <x:attribute name='#{"attr" + index}'>
            #{"val" + index}
        </x:attribute>
    </forEach>
</x:element>

Thanks.


答:
A generator is a lazy iterator. When you use a for loop, you are manually exhausting the generator. When you print it out in a single line, you are not exhausting it by iterating.

You can unpack the generator to exhaust it and get all of the values:

```<code>print(*(char for char in Reverse('word')), sep='')
</code>```

I’ve changed end for sep as you are doing everything in 1 print call so want to separate each ‘argument’ (character) with no space.

You can also do the following:

```<code>print(*Reverse('word'), sep='')
</code>```

As Reverse is already an iterator, you are able to exhaust it.

Title: Printing generator objects in python

Body:
A generator is a lazy iterator. When you use a for loop, you are manually exhausting the generator. When you print it out in a single line, you are not exhausting it by iterating.

You can unpack the generator to exhaust it and get all of the values:

print(*(char for char in Reverse('word')), sep='')

I’ve changed end for sep as you are doing everything in 1 print call so want to separate each ‘argument’ (character) with no space.

You can also do the following:

print(*Reverse('word'), sep='')

As Reverse is already an iterator, you are able to exhaust it.


问:
I need to join rows in a query (pivot)
I have some troubles with my query pivot:

SELECT *
FROM
(
    SELECT [usuario],
           [codtrab],
           [tna],
           [hora],
           [tipo],
           [fecha]
    FROM prueba
) AS SourceTable PIVOT(AVG([tna]) FOR [tipo] IN([entrada], [salida])) AS PivotTable
```

<p>This return a table </p>

```usuario | codtrab | hora                fecha       entrada salida
name1   | 600     | 08:02:00.0000000    2019-05-17  0       NULL
name1   | 600     | 16:02:00.0000000    2019-05-17  NULL    1
name2   | 200     | 08:10:00.0000000    2019-05-17  0       NULL
name2   | 200     | 16:10:00.0000000    2019-05-17  NULL    1
name3   | 400     | 08:20:00.0000000    2019-05-17  0       NULL
name3   | 400     | 16:20:00.0000000    2019-05-17  NULL    1
```

<p>I want to show the data into a table like this:</p>

```usuario codtrab hora                fecha       entrada salida
name1   600     08:02:00.0000000    2019-05-17  0       1
name2   200     08:10:00.0000000    2019-05-17  0       1
name3   400     08:20:00.0000000    2019-05-17  0       1
```

答:
Can you try after removing column [hora] from the selection? As this column has multiple value for a name like- 'Name1', i think this creating the double rows.</p>

```<code>SELECT *
FROM
(
    SELECT [usuario],
       [codtrab],
       [tna],
       --[hora],
       [tipo],
       [fecha]
FROM prueba
) AS SourceTable
PIVOT(AVG([tna]) FOR [tipo] IN([entrada], [salida])) AS PivotTable
</code>```

Title: I need to join rows in a query (pivot)

Body:
I have some troubles with my query pivot:

SELECT *
FROM
(
    SELECT [usuario],
           [codtrab],
           [tna],
           [hora],
           [tipo],
           [fecha]
    FROM prueba
) AS SourceTable PIVOT(AVG([tna]) FOR [tipo] IN([entrada], [salida])) AS PivotTable

This return a table

usuario | codtrab | hora                fecha       entrada salida
name1   | 600     | 08:02:00.0000000    2019-05-17  0       NULL
name1   | 600     | 16:02:00.0000000    2019-05-17  NULL    1
name2   | 200     | 08:10:00.0000000    2019-05-17  0       NULL
name2   | 200     | 16:10:00.0000000    2019-05-17  NULL    1
name3   | 400     | 08:20:00.0000000    2019-05-17  0       NULL
name3   | 400     | 16:20:00.0000000    2019-05-17  NULL    1

I want to show the data into a table like this:

usuario codtrab hora                fecha       entrada salida
name1   600     08:02:00.0000000    2019-05-17  0       1
name2   200     08:10:00.0000000    2019-05-17  0       1
name3   400     08:20:00.0000000    2019-05-17  0       1

Body:
Can you try after removing column [hora] from the selection? As this column has multiple value for a name like- 'Name1', i think this creating the double rows.

SELECT *
FROM
(
    SELECT [usuario],
       [codtrab],
       [tna],
       --[hora],
       [tipo],
       [fecha]
FROM prueba
) AS SourceTable
PIVOT(AVG([tna]) FOR [tipo] IN([entrada], [salida])) AS PivotTable


问:
Making a calculator but I am receiving compiling errors
I am teaching myself Java and started to make a calculator but I'm running into two errors when I try and run the code.

I was thinking about implementing a WHILE loop with the characters to create a loop but it did not seem to work. Really burnt out and I thought this was a good place to ask.

```<code>import java.lang.Math;
import java.util.Scanner;

public class Calculator
{

    public static void main(String[] args)
    {
        double numberOne = 0;
        double numberTwo = 0;
        String operatorInput;
        Scanner myInput = new Scanner(System.in);

       System.out.print("Enter first number: ");
       numberOne = myInput.nextDouble();

       System.out.print("Enter second number: ");
       numberTwo = myInput.nextDouble();

       System.out.print("Enter the operation you wish to perform (/, *, -, +): ");
       operatorInput = myInput.nextLine();

       double result = calculate(numberOne, numberTwo, operatorInput, myInput);

       System.out.printf("The result is: %.2f%n", result);

       myInput.close();
    }

    public static double calculate(double numberOne, double numberTwo, String operatorInput, Scanner myInput)
    {
        while(true)
        {
            switch (operatorInput)
            {
                case("/"):
                {
                    myInput.close();
                    return divideNumbers(numberOne, numberTwo);
                }
                case("*"):
                {
                    myInput.close();
                    return multiplyNumbers(numberOne, numberTwo);
                }
                case("+"):
                {
                    myInput.close();
                    return addNumbers(numberOne, numberTwo);
                }
                case("-"):
                {
                    myInput.close();
                    return subtractNumbers(numberOne, numberTwo);
                }
                default:
                {
                    System.out.println("Invalid Input");
                    System.out.print("Enter the operation you wish to perform (/, *, -, +): ");
                    operatorInput = myInput.nextLine();
                }
            }
        }
    }

    public static double divideNumbers(double numberOne, double numberTwo)
    {
        return numberOne / numberTwo;
    }
    public static double multiplyNumbers(double numberOne, double numberTwo)
    {
        return numberOne * numberTwo;
    }
    public static double addNumbers(double numberOne, double numberTwo)
    {
        return numberOne + numberTwo;
    }
    public static double subtractNumbers(double numberOne, double numberTwo)
    {
        return numberOne - numberTwo;
    }
}
</code>```

```<code>Calculator.java:27: error: cannot find symbol
       operatorInput = input.nextChar();
                            ^
  symbol:   method nextChar()
  location: variable input of type Scanner
Calculator.java:55: error: incompatible types: <null> cannot be converted to double
                return null;
                       ^
</code>```

答:
I managed to solve the issue by using a while(true) on top of the switch. Also, I could not use the nextChar() because it wasn't supported by the scanner. I was able to fix this by creating a scanner called myInput. This allowed me to continue on passed me character selection. Once that was done I was able to break the loop with that scanner myInput.close(); refer to updated code above. Thanks again, everyone!

```<code> double numberOne = 0;
        double numberTwo = 0;
        String operatorInput;
        Scanner myInput = new Scanner(System.in);

       System.out.print("Enter first number: ");
       numberOne = myInput.nextDouble();

       System.out.print("Enter second number: ");
       numberTwo = myInput.nextDouble();

       System.out.print("Enter the operation you wish to perform (/, *, -, +): ");
       operatorInput = myInput.nextLine();

       double result = calculate(numberOne, numberTwo, operatorInput, myInput);

       System.out.printf("The result is: %.2f%n", result);

       myInput.close();
    }

    public static double calculate(double numberOne, double numberTwo, String operatorInput, Scanner myInput)
    {
        while(true)
        {
            switch (operatorInput)
            {
                case("/"):
                {
                    myInput.close();
                    return divideNumbers(numberOne, numberTwo);
                }
                case("*"):
                {
                    myInput.close();
                    return multiplyNumbers(numberOne, numberTwo);
                }
                case("+"):
                {
                    myInput.close();
                    return addNumbers(numberOne, numberTwo);
                }
                case("-"):
                {
                    myInput.close();
                    return subtractNumbers(numberOne, numberTwo);
                }
                default:
                {
                    System.out.println("Invalid Input");
                    System.out.print("Enter the operation you wish to perform (/, *, -, +): ");
                    operatorInput = myInput.nextLine();
                }
            }
        }
    }
</code>```

Body:
I am teaching myself Java and started to make a calculator but I'm running into two errors when I try and run the code.

I was thinking about implementing a WHILE loop with the characters to create a loop but it did not seem to work. Really burnt out and I thought this was a good place to ask.

import java.lang.Math;
import java.util.Scanner;

public class Calculator
{

    public static void main(String[] args)
    {
        double numberOne = 0;
        double numberTwo = 0;
        String operatorInput;
        Scanner myInput = new Scanner(System.in);

       System.out.print("Enter first number: ");
       numberOne = myInput.nextDouble();

       System.out.print("Enter second number: ");
       numberTwo = myInput.nextDouble();

       System.out.print("Enter the operation you wish to perform (/, *, -, +): ");
       operatorInput = myInput.nextLine();

       double result = calculate(numberOne, numberTwo, operatorInput, myInput);

       System.out.printf("The result is: %.2f%n", result);

       myInput.close();
    }

    public static double calculate(double numberOne, double numberTwo, String operatorInput, Scanner myInput)
    {
        while(true)
        {
            switch (operatorInput)
            {
                case("/"):
                {
                    myInput.close();
                    return divideNumbers(numberOne, numberTwo);
                }
                case("*"):
                {
                    myInput.close();
                    return multiplyNumbers(numberOne, numberTwo);
                }
                case("+"):
                {
                    myInput.close();
                    return addNumbers(numberOne, numberTwo);
                }
                case("-"):
                {
                    myInput.close();
                    return subtractNumbers(numberOne, numberTwo);
                }
                default:
                {
                    System.out.println("Invalid Input");
                    System.out.print("Enter the operation you wish to perform (/, *, -, +): ");
                    operatorInput = myInput.nextLine();
                }
            }
        }
    }

    public static double divideNumbers(double numberOne, double numberTwo)
    {
        return numberOne / numberTwo;
    }
    public static double multiplyNumbers(double numberOne, double numberTwo)
    {
        return numberOne * numberTwo;
    }
    public static double addNumbers(double numberOne, double numberTwo)
    {
        return numberOne + numberTwo;
    }
    public static double subtractNumbers(double numberOne, double numberTwo)
    {
        return numberOne - numberTwo;
    }
}

Calculator.java:27: error: cannot find symbol
       operatorInput = input.nextChar();
                            ^
  symbol:   method nextChar()
  location: variable input of type Scanner
Calculator.java:55: error: incompatible types: <null> cannot be converted to double
                return null;
                       ^

Body:
I managed to solve the issue by using a while(true) on top of the switch. Also, I could not use the nextChar() because it wasn't supported by the scanner. I was able to fix this by creating a scanner called myInput. This allowed me to continue on passed me character selection. Once that was done I was able to break the loop with that scanner myInput.close(); refer to updated code above. Thanks again, everyone!

 double numberOne = 0;
        double numberTwo = 0;
        String operatorInput;
        Scanner myInput = new Scanner(System.in);

       System.out.print("Enter first number: ");
       numberOne = myInput.nextDouble();

       System.out.print("Enter second number: ");
       numberTwo = myInput.nextDouble();

       System.out.print("Enter the operation you wish to perform (/, *, -, +): ");
       operatorInput = myInput.nextLine();

       double result = calculate(numberOne, numberTwo, operatorInput, myInput);

       System.out.printf("The result is: %.2f%n", result);

       myInput.close();
    }

    public static double calculate(double numberOne, double numberTwo, String operatorInput, Scanner myInput)
    {
        while(true)
        {
            switch (operatorInput)
            {
                case("/"):
                {
                    myInput.close();
                    return divideNumbers(numberOne, numberTwo);
                }
                case("*"):
                {
                    myInput.close();
                    return multiplyNumbers(numberOne, numberTwo);
                }
                case("+"):
                {
                    myInput.close();
                    return addNumbers(numberOne, numberTwo);
                }
                case("-"):
                {
                    myInput.close();
                    return subtractNumbers(numberOne, numberTwo);
                }
                default:
                {
                    System.out.println("Invalid Input");
                    System.out.print("Enter the operation you wish to perform (/, *, -, +): ");
                    operatorInput = myInput.nextLine();
                }
            }
        }
    }


问:
Fullscreen bootstrap 4 card with highcharts
I have several (bootstrap) cards where I would like to have the opportunity to show this fullscreen. Highcharts charts are present in these cards. The problem is that the height of the highcharts does not adapt when you are going in full screen mode.

A while ago I asked the same question with bootstrap panels and then "daniel_s" made this example for panels. Only now I have added a number of columns at the bottom and it has been converted from panels to cards. Unfortunately the example is not working anymore. Again "daniel_s" made an example but the height is still not 100%.

Is there a possibility to automatically adjust the scaling of the highcharts so that the ratio (columns at the bottom and header) remains the same as in this example?

In addition, I would also like to know how I get the header the text and icons on one line. So that the text is on the left and the icons are on the right.

HTML

```<code><link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.13/css/all.css">
<script type="text/javascript" src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
<!------ Include the above in your HEAD tag ---------->

<div class="container">
  <div class="row">
    <div class="col-md-6 col-lg-3">
      <div class="card with-margin card_shadow card_border rounded">
        <div class="container-fluid" id="mainContainer">
          <div class="row border-bottom-0 card_border2" style="background: linear-gradient(to right, #eea849, #fa7921); justify-content: space-between">
            <h3>Panel 1</h3>
            <li class="list-inline-item"><a href="#" id="panel-fullscreen" class="fullscreen-btn" role="button" title="Toggle fullscreen"><i class="fas fa-expand"></i></a></li>
          </div>
          <div class="row">
            <div class="card-body border-top-0 border-bottom-0 card_border2 row-200">
              <div id="container"></div>
            </div>
          </div>
          <div class="row bg-white justify-content-center card_border">
            <div class="col-sm text-center card_border2">
              <br> text 1
            </div>
            <div class="col-sm text-center card_border2">
              <br> text 2
            </div>
            <div class="col-sm text-center card_border2">
              <br> text 3
            </div>
            <div class="col-sm text-center card_border2">
              <br> text 4
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="col-md-6 col-lg-3">
      <div class="card with-margin card_shadow card_border rounded">
        <div class="container-fluid" id="mainContainer">
          <div class="row border-bottom-0 card_border2" style="background: linear-gradient(to right, #eea849, #fa7921); justify-content: space-between">
            <h3>Panel 2</h3>
            <li class="list-inline-item"><a href="#" id="panel-fullscreen2" class="fullscreen-btn" role="button" title="Toggle fullscreen"><i class="fas fa-expand"></i></a></li>
          </div>
          <div class="row">
            <div class="card-body border-top-0 border-bottom-0 card_border2 row-200">
              <div id="container2"></div>
            </div>
          </div>
          <div class="row bg-white justify-content-center card_border">
            <div class="col-sm text-center card_border2">
              <br> text 1
            </div>
            <div class="col-sm text-center card_border2">
              <br> text 2
            </div>
            <div class="col-sm text-center card_border2">
              <br> text 3
            </div>
            <div class="col-sm text-center card_border2">
              <br> text 4
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
</code>```

CSS

```<code>.panel-actions {
  margin-bottom: 0;
  text-align: right;
}

.panel-actions a {
  color: #333;
}
#mainContainer {
  height: 50%;
}
.panel-fullscreen {
  display: block;
  z-index: 9999;
  position: fixed !important;
  width: 100%;
  height: 100%;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  overflow: auto;
}
.full-height-row {
  height: 100%;
  width: 100%;
}
#container {
  height: 100%;
}
#container2 {
  height: 100%;
}
.row-200 {
  height: 220px;
}

.card_border {
  border: solid 0.75px #fa7921;
}

.card_border2 {
  border: solid 2px #fa7921;
}
</code>```

JavaScript

```<code>$(document).ready(function() {
  var charts = [];
  var chart1Info = {
    containerId: "container",
    definition: {
      title: {
        text: "Chart1 Title"
      },
      subtitle: {
        text: "Source: thesolarfoundation.com"
      },
      yAxis: {
        title: {
          text: "Number of Employees"
        }
      },
      legend: {
        layout: "vertical",
        align: "right",
        verticalAlign: "middle"
      },
      plotOptions: {
        series: {
          label: {
            connectorAllowed: false
          },
          pointStart: 2010
        }
      },
      series: [
        {
          name: "Installation",
          data: [43934, 52503, 57177, 69658, 97031, 119931, 137133, 154175]
        },
        {
          name: "Manufacturing",
          data: [24916, 24064, 29742, 29851, 32490, 30282, 38121, 40434]
        },
        {
          name: "Sales & Distribution",
          data: [11744, 17722, 16005, 19771, 20185, 24377, 32147, 39387]
        },
        {
          name: "Project Development",
          data: [null, null, 7988, 12169, 15112, 22452, 34400, 34227]
        },
        {
          name: "Other",
          data: [12908, 5948, 8105, 11248, 8989, 11816, 18274, 18111]
        }
      ]
    }
  };
  var chart2Info = {
    containerId: "container2",
    definition: {
      title: {
        text: "Chart2 Title"
      },
      subtitle: {
        text: "Source: thesolarfoundation.com"
      },
      yAxis: {
        title: {
          text: "Number of Employees"
        }
      },
      legend: {
        layout: "vertical",
        align: "right",
        verticalAlign: "middle"
      },
      plotOptions: {
        series: {
          label: {
            connectorAllowed: false
          },
          pointStart: 2010
        }
      },
      series: [
        {
          name: "Installation",
          data: [43934, 52503, 57177, 69658, 97031, 119931, 137133, 154175]
        },
        {
          name: "Manufacturing",
          data: [24916, 24064, 29742, 29851, 32490, 30282, 38121, 40434]
        },
        {
          name: "Sales & Distribution",
          data: [11744, 17722, 16005, 19771, 20185, 24377, 32147, 39387]
        },
        {
          name: "Project Development",
          data: [null, null, 7988, 12169, 15112, 22452, 34400, 34227]
        },
        {
          name: "Other",
          data: [12908, 5948, 8105, 11248, 8989, 11816, 18274, 18111]
        }
      ]
    }
  };

  function drawChart(chartInfo) {
    // Properties that vary by chart should be defined in chartInfo
    // Any properties that are the same for all charts are added here
    chartInfo.responsive = {
      rules: [
        {
          condition: {
            maxWidth: 500
          },
          chartOptions: {
            legend: {
              layout: "horizontal",
              align: "center",
              verticalAlign: "bottom"
            }
          }
        }
      ]
    };

    if (chartInfo == chart1Info) {
      charts[0] = Highcharts.chart(chartInfo.containerId, chartInfo.definition);
    } else {
      charts[1] = Highcharts.chart(chartInfo.containerId, chartInfo.definition);
    }
  }
  //Toggle fullscreen
  $(".fullscreen-btn").click(function(e) {
    e.preventDefault();

    var $this = $(this);
    $this
      .children("i")
      .toggleClass("fa-expand")
      .toggleClass("fa-arrows-alt");
    $(this)
      .closest(".card")
      .toggleClass("panel-fullscreen");
    $($(this).parents()[3])
      .find(".card-body")
      .toggleClass("row-200");

    var chartInfo =
      $this.attr("id") === "panel-fullscreen" ? chart1Info : chart2Info;
    drawChart(chartInfo);
  });

  drawChart(chart1Info);
  drawChart(chart2Info);
});
</code>```

As can be seen in this example, the height is not 100%, while in this example the height is 100%. How do I manage that in the first example the height is always 100%.

答:
I've examined both examples and probably found the solution.

In your working example, all the elements are located in one container panel which has a height set to 100% and child panel-heading of height 94%.

In your example with the issue, there is a 'card' with height set to 100% and child container-fluid with rows inside without a fixed height set.

So as you can see rows doesn't know how to share the space on the screen. To fix it you have to set the CSS styles so that container-fluid is 100% height and rows for example 10% top row, 80% middle row, 10% bottom row. Then all the elements are rendered correctly as you can see below:

Body:
I have several (bootstrap) cards where I would like to have the opportunity to show this fullscreen. Highcharts charts are present in these cards. The problem is that the height of the highcharts does not adapt when you are going in full screen mode.

A while ago I asked the same question with bootstrap panels and then "daniel_s" made this example for panels. Only now I have added a number of columns at the bottom and it has been converted from panels to cards. Unfortunately the example is not working anymore. Again "daniel_s" made an example but the height is still not 100%.

Is there a possibility to automatically adjust the scaling of the highcharts so that the ratio (columns at the bottom and header) remains the same as in this example?

In addition, I would also like to know how I get the header the text and icons on one line. So that the text is on the left and the icons are on the right.

HTML

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.13/css/all.css">

Panel 1

 text 1

 text 2

 text 3

 text 4

Panel 2

 text 1

 text 2

 text 3

 text 4

CSS

.panel-actions {
  margin-bottom: 0;
  text-align: right;
}

.panel-actions a {
  color: #333;
}
#mainContainer {
  height: 50%;
}
.panel-fullscreen {
  display: block;
  z-index: 9999;
  position: fixed !important;
  width: 100%;
  height: 100%;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  overflow: auto;
}
.full-height-row {
  height: 100%;
  width: 100%;
}
#container {
  height: 100%;
}
#container2 {
  height: 100%;
}
.row-200 {
  height: 220px;
}

.card_border {
  border: solid 0.75px #fa7921;
}

.card_border2 {
  border: solid 2px #fa7921;
}

JavaScript

$(document).ready(function() {
  var charts = [];
  var chart1Info = {
    containerId: "container",
    definition: {
      title: {
        text: "Chart1 Title"
      },
      subtitle: {
        text: "Source: thesolarfoundation.com"
      },
      yAxis: {
        title: {
          text: "Number of Employees"
        }
      },
      legend: {
        layout: "vertical",
        align: "right",
        verticalAlign: "middle"
      },
      plotOptions: {
        series: {
          label: {
            connectorAllowed: false
          },
          pointStart: 2010
        }
      },
      series: [
        {
          name: "Installation",
          data: [43934, 52503, 57177, 69658, 97031, 119931, 137133, 154175]
        },
        {
          name: "Manufacturing",
          data: [24916, 24064, 29742, 29851, 32490, 30282, 38121, 40434]
        },
        {
          name: "Sales & Distribution",
          data: [11744, 17722, 16005, 19771, 20185, 24377, 32147, 39387]
        },
        {
          name: "Project Development",
          data: [null, null, 7988, 12169, 15112, 22452, 34400, 34227]
        },
        {
          name: "Other",
          data: [12908, 5948, 8105, 11248, 8989, 11816, 18274, 18111]
        }
      ]
    }
  };
  var chart2Info = {
    containerId: "container2",
    definition: {
      title: {
        text: "Chart2 Title"
      },
      subtitle: {
        text: "Source: thesolarfoundation.com"
      },
      yAxis: {
        title: {
          text: "Number of Employees"
        }
      },
      legend: {
        layout: "vertical",
        align: "right",
        verticalAlign: "middle"
      },
      plotOptions: {
        series: {
          label: {
            connectorAllowed: false
          },
          pointStart: 2010
        }
      },
      series: [
        {
          name: "Installation",
          data: [43934, 52503, 57177, 69658, 97031, 119931, 137133, 154175]
        },
        {
          name: "Manufacturing",
          data: [24916, 24064, 29742, 29851, 32490, 30282, 38121, 40434]
        },
        {
          name: "Sales & Distribution",
          data: [11744, 17722, 16005, 19771, 20185, 24377, 32147, 39387]
        },
        {
          name: "Project Development",
          data: [null, null, 7988, 12169, 15112, 22452, 34400, 34227]
        },
        {
          name: "Other",
          data: [12908, 5948, 8105, 11248, 8989, 11816, 18274, 18111]
        }
      ]
    }
  };

  function drawChart(chartInfo) {
    // Properties that vary by chart should be defined in chartInfo
    // Any properties that are the same for all charts are added here
    chartInfo.responsive = {
      rules: [
        {
          condition: {
            maxWidth: 500
          },
          chartOptions: {
            legend: {
              layout: "horizontal",
              align: "center",
              verticalAlign: "bottom"
            }
          }
        }
      ]
    };

    if (chartInfo == chart1Info) {
      charts[0] = Highcharts.chart(chartInfo.containerId, chartInfo.definition);
    } else {
      charts[1] = Highcharts.chart(chartInfo.containerId, chartInfo.definition);
    }
  }
  //Toggle fullscreen
  $(".fullscreen-btn").click(function(e) {
    e.preventDefault();

    var $this = $(this);
    $this
      .children("i")
      .toggleClass("fa-expand")
      .toggleClass("fa-arrows-alt");
    $(this)
      .closest(".card")
      .toggleClass("panel-fullscreen");
    $($(this).parents()[3])
      .find(".card-body")
      .toggleClass("row-200");

    var chartInfo =
      $this.attr("id") === "panel-fullscreen" ? chart1Info : chart2Info;
    drawChart(chartInfo);
  });

  drawChart(chart1Info);
  drawChart(chart2Info);
});

As can be seen in this example, the height is not 100%, while in this example the height is 100%. How do I manage that in the first example the height is always 100%.


问:
How to modify the value of $request in Nginx?
In Nginx, currently we are logging $request. But we want to change value for one request param in it.
We need to log hashed id instead of actual id.
Could you please tell me how can I achieve that ?

Current value of $request :

```<code>POST /test/userRegistration?id=1234&name=John&address=UK
</code>```

Expected value:

```<code>POST /test/userRegistration?id=8c77ec99436a23d2c05a6bd36c64de856&name=John&address=UK
</code>```

Nginx Log Format :

```<code>log_format  main '$request $status $request_time';
</code>```

I have written follwoing ruby code to meet my requirement. But I am not sure  how to integrate it in ERB file. That log_format is declared in
a ERB file.

Code:

```<code>str = "POST /test/userRegistration?name=John&id=1234&address=UK"
str1 = str.scan(/&id=.+&/)[0]
str1 = str1.chomp('&')
str1 = str1.split("=").last
str1 = Digest::SHA256.hexdigest str1
str2 = "&id="+str1+"&"
str3 = str.sub(/&name=.+&/, str2)
puts str3
</code>```

Please help me writing similar logic in ERB file. Also, please let me know if there is any better way to handle it as I am new to Ruby.

Thanks

答:
To me you need to check openresty project or install LUA extension for Nginx. Its ok to replace nginx with openresty to get LUA out of the box.

With LUA script you can parse this certain part of the request - similar to your ruby code and record modified request uri in Nginx access log.

Here are some examples how you can modify request parameters with LUA

Body:
In Nginx, currently we are logging $request. But we want to change value for one request param in it.
We need to log hashed id instead of actual id.
Could you please tell me how can I achieve that ?

Current value of $request :

POST /test/userRegistration?id=1234&name=John&address=UK

Expected value:

POST /test/userRegistration?id=8c77ec99436a23d2c05a6bd36c64de856&name=John&address=UK

Nginx Log Format :

log_format  main '$request $status $request_time';

I have written follwoing ruby code to meet my requirement. But I am not sure  how to integrate it in ERB file. That log_format is declared in
a ERB file.

Code:

str = "POST /test/userRegistration?name=John&id=1234&address=UK"
str1 = str.scan(/&id=.+&/)[0]
str1 = str1.chomp('&')
str1 = str1.split("=").last
str1 = Digest::SHA256.hexdigest str1
str2 = "&id="+str1+"&"
str3 = str.sub(/&name=.+&/, str2)
puts str3

Please help me writing similar logic in ERB file. Also, please let me know if there is any better way to handle it as I am new to Ruby.

Thanks