问:
Creating a 2d numpy array to hold characters
I have the following numpy array and previous set up that has a word queue and a temporary variable 'temp' to store a word. This word needs to be "put", letter by letter, into the numpy 2d array:

```<code>from collections import deque
import numpy as np
message=input("Write a message:")
wordqueue=message.split()
queue=deque(wordqueue)
print(wordqueue)

for i in range(1):
  temp=wordqueue.pop(0) #store the removed item in the temporary variable 'temp'
print(wordqueue)
print(temp)
display = np.zeros((4,10)) #create a 2d array that is to store the words from the queue
print(display)
display[0, 0] = temp #add the word from the temp variable to fill the array (each character in each sequential position in the array)
print(display)
</code>```

Unfortunately, the output is as follows:

```<code>Write a message: This is a message for the display array
['This', 'is', 'a', 'message', 'for', 'the', 'display', 'array']
['is', 'a', 'message', 'for', 'the', 'display', 'array']
This
[[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]]
Traceback (most recent call last):
  File "python", line 20, in <module>
ValueError: could not convert string to float: 'This'
</code>```

I did try to define the 2d array and define the data type, but that too wasn't very obvious and I kept getting various errors.

What I would like help with is the following:
1. Ideally, I would like the numpy array to be set up with "*"s instead of zeros/ones (the documentation didn't help with this setup).
2. Replace the *s in the array with the temp variable. One letter for each *

EXAMPLE:

Display array:
 (4 x 20)

```<code>* * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *
</code>```

Enter Message: This is a test message
temp: This

Updated display would show:

```<code>t h i s * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *
</code>```

for subsequent words, it would then populate the array (truncating if the word was too big and going to the next line if necessary)

So far:
https://repl.it/IcJ3/7

I tried this, for instance, to create the char array:

```<code>display = np.chararray((4,10)) #create a 2d array that is to store the letters in the words from the queue
display[:]="*"
</code>```

but it produced this, with the erroneous "b" inserted. Cannot see why ...

```<code>[[b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*']
 [b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*']
 [b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*']
 [b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*']]
</code>```

Updated (working on )repl.it here:
https://repl.it/IcJ3/8

答:
First thing is first, if you want a "character" array, you have to be careful with what exactly you expect. In Python 3, strings are now sequences of unicode code points. In Python 2, strings were the classic "sequence of bytes" strings from languages like C. This means, that from a memory pov, unicode types can be much more memory intensive:

```<code>In [1]: import numpy as np

In [2]: chararray = np.zeros((4,10), dtype='S1')

In [3]: unicodearray =  np.zeros((4,10), dtype='U1')

In [4]: chararray.itemsize, unicodearray.itemsize
Out[4]: (1, 4)

In [5]: chararray.nbytes
Out[5]: 40

In [6]: unicodearray.nbytes
Out[6]: 160
</code>```

So if you know you want to work only with ascii-characters, you can use the S1 dtype cut your memory use to 1/4th. Also note, that since S1 in Python 3 actually corresponds to the bytes data type (which is equilvaent to Python 2 str), the representation is prepended by a b, so b'this is a bytes object':

```<code>In [7]: chararray
Out[7]:
array([[b'', b'', b'', b'', b'', b'', b'', b'', b'', b''],
       [b'', b'', b'', b'', b'', b'', b'', b'', b'', b''],
       [b'', b'', b'', b'', b'', b'', b'', b'', b'', b''],
       [b'', b'', b'', b'', b'', b'', b'', b'', b'', b'']],
      dtype='|S1')

In [8]: unicodearray
Out[8]:
array([['', '', '', '', '', '', '', '', '', ''],
       ['', '', '', '', '', '', '', '', '', ''],
       ['', '', '', '', '', '', '', '', '', ''],
       ['', '', '', '', '', '', '', '', '', '']],
      dtype='<U1')
</code>```

Now, suppose you have some payload you want to assign a message to your array. If your message consists of characters that are representable as ascii, then you can play fast and loose with the dtype:

```<code>In [15]: message = 'This'

In [16]: unicodearray.reshape(-1)[:len(message)] = list(message)

In [17]: unicodearray
Out[17]:
array(['T', 'h', 'i', 's', '', '', '', '', '', '', '', '', '', '', '', '',
       '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
       '', '', '', '', '', '', ''],
      dtype='<U1')

In [18]: chararray.reshape(-1)[:len(message)] = list(message)

In [19]: chararray
Out[19]:
array([[b'T', b'h', b'i', b's', b'', b'', b'', b'', b'', b''],
       [b'', b'', b'', b'', b'', b'', b'', b'', b'', b''],
       [b'', b'', b'', b'', b'', b'', b'', b'', b'', b''],
       [b'', b'', b'', b'', b'', b'', b'', b'', b'', b'']],
      dtype='|S1')
</code>```

However, if that is not the case:

```<code>In [22]: message = "กขฃคฅฆงจฉ"

In [23]: len(message)
Out[23]: 9

In [24]: unicodearray.reshape(-1)[:len(message)] = list(message)

In [25]: unicodearray
Out[25]:
array(['ก', 'ข', 'ฃ', 'ค', 'ฅ', 'ฆ', 'ง', 'จ', 'ฉ', '', '', '', '', '', '',
       '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
       '', '', '', '', '', '', '', ''],
      dtype='<U1')

In [26]: chararray.reshape(-1)[:len(message)] = list(message)
---------------------------------------------------------------------------
UnicodeEncodeError                        Traceback (most recent call last)
<ipython-input-26-7d7cdb93de1f> in <module>()
----> 1 chararray.reshape(-1)[:len(message)] = list(message)

UnicodeEncodeError: 'ascii' codec can't encode character '\u0e01' in position 0: ordinal not in range(128)

In [27]:
</code>```

Note, if you want to initialize the array with an element other than what it defaults to with np.zeros you can use np.full:

```<code>In [27]: chararray = np.full((4,10), '*', dtype='S1')

In [28]: chararray
Out[28]:
array([[b'*', b'*', b'*', b'*', b'*', b'*', b'*', b'*', b'*', b'*'],
       [b'*', b'*', b'*', b'*', b'*', b'*', b'*', b'*', b'*', b'*'],
       [b'*', b'*', b'*', b'*', b'*', b'*', b'*', b'*', b'*', b'*'],
       [b'*', b'*', b'*', b'*', b'*', b'*', b'*', b'*', b'*', b'*']],
      dtype='|S1')
</code>```

Finally, to do this long-form with for-loops:

```<code>In [17]: temp = "a test"

In [18]: display = np.full((4,10), '*', dtype='U1')

In [19]: display
Out[19]:
array([['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'],
       ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'],
       ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'],
       ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*']],
      dtype='<U1')

In [20]: it = iter(temp) # give us a single-pass iterator
    ...: for i in range(display.shape[0]):
    ...:     for j, c in zip(range(display.shape[1]), it):
    ...:         display[i, j] = c
    ...:

In [21]: display
Out[21]:
array([['a', ' ', 't', 'e', 's', 't', '*', '*', '*', '*'],
       ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'],
       ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'],
       ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*']],
      dtype='<U1')
</code>```

An another test for good measure, that spans rows:

```<code>In [36]: temp = "this is a test, a test this is"

In [37]: display = np.full((4,10), '*', dtype='U1')

In [38]: it = iter(temp) # give us a single-pass iterator
    ...: for i in range(display.shape[0]):
    ...:     for j, c in zip(range(display.shape[1]), it):
    ...:         display[i, j] = c
    ...:

In [39]: display
Out[39]:
array([['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' '],
       ['t', 'e', 's', 't', ',', ' ', 'a', ' ', 't', 'e'],
       ['s', 't', ' ', 't', 'h', 'i', 's', ' ', 'i', 's'],
       ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*']],
      dtype='<U1')
</code>```

Warning The order of the arguments passed to zip matters, since it is a single-pass iterator:

```<code>zip(range(display.shape[1]), it)
</code>```

It should be the last argument, or else it will skip characters between rows!

Finally, note that numpy provides a convenience function for iterating over arrays sequentially:

```<code>In [49]: temp = "this is yet another test"

In [50]: display = np.full((4,10), '*', dtype='U1')

In [51]: for c, x in zip(temp, np.nditer(display, op_flags=['readwrite'])):
    ...:     x[...] = c
    ...:

In [52]: display
Out[52]:
array([['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'y', 'e'],
       ['t', ' ', 'a', 'n', 'o', 't', 'h', 'e', 'r', ' '],
       ['t', 'e', 's', 't', '*', '*', '*', '*', '*', '*'],
       ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*']],
      dtype='<U1')
</code>```

There is a minor complication of having to pass a op_flags=['readwrite'] to the function to make sure that the iterator that is returned allows modification to the underlying array, but it greatly simplifies the code and we don't need to use a single-pass iterator. I still prefer slice assignment, though.

Body:
I have the following numpy array and previous set up that has a word queue and a temporary variable 'temp' to store a word. This word needs to be "put", letter by letter, into the numpy 2d array:

from collections import deque
import numpy as np
message=input("Write a message:")
wordqueue=message.split()
queue=deque(wordqueue)
print(wordqueue)

for i in range(1):
  temp=wordqueue.pop(0) #store the removed item in the temporary variable 'temp'
print(wordqueue)
print(temp)
display = np.zeros((4,10)) #create a 2d array that is to store the words from the queue
print(display)
display[0, 0] = temp #add the word from the temp variable to fill the array (each character in each sequential position in the array)
print(display)

Unfortunately, the output is as follows:

Write a message: This is a message for the display array
['This', 'is', 'a', 'message', 'for', 'the', 'display', 'array']
['is', 'a', 'message', 'for', 'the', 'display', 'array']
This
[[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]]
Traceback (most recent call last):
  File "python", line 20, in <module>
ValueError: could not convert string to float: 'This'

I did try to define the 2d array and define the data type, but that too wasn't very obvious and I kept getting various errors.

What I would like help with is the following:
1. Ideally, I would like the numpy array to be set up with "*"s instead of zeros/ones (the documentation didn't help with this setup).
2. Replace the *s in the array with the temp variable. One letter for each *

EXAMPLE:

Display array:
 (4 x 20)

* * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *

Enter Message: This is a test message
temp: This

Updated display would show:

t h i s * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *

for subsequent words, it would then populate the array (truncating if the word was too big and going to the next line if necessary)

So far:
https://repl.it/IcJ3/7

I tried this, for instance, to create the char array:

display = np.chararray((4,10)) #create a 2d array that is to store the letters in the words from the queue
display[:]="*"

but it produced this, with the erroneous "b" inserted. Cannot see why ...

[[b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*']
 [b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*']
 [b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*']
 [b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*']]

Updated (working on )repl.it here:
https://repl.it/IcJ3/8

Body:
First thing is first, if you want a "character" array, you have to be careful with what exactly you expect. In Python 3, strings are now sequences of unicode code points. In Python 2, strings were the classic "sequence of bytes" strings from languages like C. This means, that from a memory pov, unicode types can be much more memory intensive:

In [1]: import numpy as np

In [2]: chararray = np.zeros((4,10), dtype='S1')

In [3]: unicodearray =  np.zeros((4,10), dtype='U1')

In [4]: chararray.itemsize, unicodearray.itemsize
Out[4]: (1, 4)

In [5]: chararray.nbytes
Out[5]: 40

In [6]: unicodearray.nbytes
Out[6]: 160

So if you know you want to work only with ascii-characters, you can use the S1 dtype cut your memory use to 1/4th. Also note, that since S1 in Python 3 actually corresponds to the bytes data type (which is equilvaent to Python 2 str), the representation is prepended by a b, so b'this is a bytes object':

In [7]: chararray
Out[7]:
array([[b'', b'', b'', b'', b'', b'', b'', b'', b'', b''],
       [b'', b'', b'', b'', b'', b'', b'', b'', b'', b''],
       [b'', b'', b'', b'', b'', b'', b'', b'', b'', b''],
       [b'', b'', b'', b'', b'', b'', b'', b'', b'', b'']],
      dtype='|S1')

In [8]: unicodearray
Out[8]:
array([['', '', '', '', '', '', '', '', '', ''],
       ['', '', '', '', '', '', '', '', '', ''],
       ['', '', '', '', '', '', '', '', '', ''],
       ['', '', '', '', '', '', '', '', '', '']],
      dtype='<U1')

Now, suppose you have some payload you want to assign a message to your array. If your message consists of characters that are representable as ascii, then you can play fast and loose with the dtype:

In [15]: message = 'This'

In [16]: unicodearray.reshape(-1)[:len(message)] = list(message)

In [17]: unicodearray
Out[17]:
array(['T', 'h', 'i', 's', '', '', '', '', '', '', '', '', '', '', '', '',
       '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
       '', '', '', '', '', '', ''],
      dtype='<U1')

In [18]: chararray.reshape(-1)[:len(message)] = list(message)

In [19]: chararray
Out[19]:
array([[b'T', b'h', b'i', b's', b'', b'', b'', b'', b'', b''],
       [b'', b'', b'', b'', b'', b'', b'', b'', b'', b''],
       [b'', b'', b'', b'', b'', b'', b'', b'', b'', b''],
       [b'', b'', b'', b'', b'', b'', b'', b'', b'', b'']],
      dtype='|S1')

However, if that is not the case:

In [22]: message = "กขฃคฅฆงจฉ"

In [23]: len(message)
Out[23]: 9

In [24]: unicodearray.reshape(-1)[:len(message)] = list(message)

In [25]: unicodearray
Out[25]:
array(['ก', 'ข', 'ฃ', 'ค', 'ฅ', 'ฆ', 'ง', 'จ', 'ฉ', '', '', '', '', '', '',
       '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
       '', '', '', '', '', '', '', ''],
      dtype='<U1')

In [26]: chararray.reshape(-1)[:len(message)] = list(message)
---------------------------------------------------------------------------
UnicodeEncodeError                        Traceback (most recent call last)
<ipython-input-26-7d7cdb93de1f> in <module>()
----> 1 chararray.reshape(-1)[:len(message)] = list(message)

UnicodeEncodeError: 'ascii' codec can't encode character '\u0e01' in position 0: ordinal not in range(128)

In [27]:

Note, if you want to initialize the array with an element other than what it defaults to with np.zeros you can use np.full:

In [27]: chararray = np.full((4,10), '*', dtype='S1')

In [28]: chararray
Out[28]:
array([[b'*', b'*', b'*', b'*', b'*', b'*', b'*', b'*', b'*', b'*'],
       [b'*', b'*', b'*', b'*', b'*', b'*', b'*', b'*', b'*', b'*'],
       [b'*', b'*', b'*', b'*', b'*', b'*', b'*', b'*', b'*', b'*'],
       [b'*', b'*', b'*', b'*', b'*', b'*', b'*', b'*', b'*', b'*']],
      dtype='|S1')

Finally, to do this long-form with for-loops:

In [17]: temp = "a test"

In [18]: display = np.full((4,10), '*', dtype='U1')

In [19]: display
Out[19]:
array([['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'],
       ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'],
       ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'],
       ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*']],
      dtype='<U1')

In [20]: it = iter(temp) # give us a single-pass iterator
    ...: for i in range(display.shape[0]):
    ...:     for j, c in zip(range(display.shape[1]), it):
    ...:         display[i, j] = c
    ...:

In [21]: display
Out[21]:
array([['a', ' ', 't', 'e', 's', 't', '*', '*', '*', '*'],
       ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'],
       ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'],
       ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*']],
      dtype='<U1')

An another test for good measure, that spans rows:

In [36]: temp = "this is a test, a test this is"

In [37]: display = np.full((4,10), '*', dtype='U1')

In [38]: it = iter(temp) # give us a single-pass iterator
    ...: for i in range(display.shape[0]):
    ...:     for j, c in zip(range(display.shape[1]), it):
    ...:         display[i, j] = c
    ...:

In [39]: display
Out[39]:
array([['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' '],
       ['t', 'e', 's', 't', ',', ' ', 'a', ' ', 't', 'e'],
       ['s', 't', ' ', 't', 'h', 'i', 's', ' ', 'i', 's'],
       ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*']],
      dtype='<U1')

Warning The order of the arguments passed to zip matters, since it is a single-pass iterator:

zip(range(display.shape[1]), it)

It should be the last argument, or else it will skip characters between rows!

Finally, note that numpy provides a convenience function for iterating over arrays sequentially:

In [49]: temp = "this is yet another test"

In [50]: display = np.full((4,10), '*', dtype='U1')

In [51]: for c, x in zip(temp, np.nditer(display, op_flags=['readwrite'])):
    ...:     x[...] = c
    ...:

In [52]: display
Out[52]:
array([['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'y', 'e'],
       ['t', ' ', 'a', 'n', 'o', 't', 'h', 'e', 'r', ' '],
       ['t', 'e', 's', 't', '*', '*', '*', '*', '*', '*'],
       ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*']],
      dtype='<U1')

There is a minor complication of having to pass a op_flags=['readwrite'] to the function to make sure that the iterator that is returned allows modification to the underlying array, but it greatly simplifies the code and we don't need to use a single-pass iterator. I still prefer slice assignment, though.


来源: stackexchange

问:
FILTER_SANITIZE vs FILTER VALIDATE, whats the difference - and which to use?
Currently I'm making sort of calculator-like app in PHP with form as method of input. To secure input i'm using filter_input() function. As filter this function take one of elements from two groups: FILTER_SANITIZE and FILTER_VALIDATE, which one should i use to filter input from form?

```<code>$number1 = trim(filter_input(INPUT_GET, 'number1', FILTER_VALIDATE_FLOAT));
</code>```

or

```<code>$number1 = trim(filter_input(INPUT_GET, 'number1', FILTER_SANITIZE_FLOAT));
</code>```

答:
It depends on what you need or is suitable for your application, really. One would validate it, and say "Yes, this is (or isn't) a valid float", while the other would clean it for any non-acceptable value and return that, and not say anything if the original input was valid or not to begin with.

The same applies for the other FILTER_SANITIZE_* and FILTER_VALIDATE_*constants, but in this example we'll look at floating-point validation and sanitation, as asked in the original question.

Let's take a look!

```<code>$float = 0.032;
$not_float = "0.03b2";

var_dump(filter_var($float, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION));
var_dump(filter_var($not_float, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION));

var_dump(filter_var($float, FILTER_VALIDATE_FLOAT));
var_dump(filter_var($not_float, FILTER_VALIDATE_FLOAT));
</code>```

The return from the above dumps would be

```<code>string(5) "0.032"  // $float          FILTER_SANITIZE_NUMBER_FLOAT
string(5) "0.032"  // $not_float      FILTER_SANITIZE_NUMBER_FLOAT
float(0.032)       // $float          FILTER_VALIDATE_FLOAT
bool(false)        // $not_float      FILTER_VALIDATE_FLOAT
</code>```

FILTER_SANITIZE_NUMBER_FLOAT would return a string of the sanitized value (PHP isn't a strongly typed language, so "0.032" == 0.032).

You should also note the FILTER_FLAG_ALLOW_FRACTION flag, which keeps the decimal in place (without that flag it would return 0032).

As you can see, any FILTER_VALIDATE_FLOAT would return a boolean false if it isn't a valid float, and the actual floating value if it was valid (which is a "truthy" value). Keep in mind that 0.00 would be a "falsy" value, so if you wish to check if the validation failed, you should use strict comparison, in case the input was zero, but still valid.

```<code>if (filter_var($input, FILTER_VALIDATE_FLOAT) === false) {
    // Oh noes! $input wasn't a valid float!
}
</code>```

You can see it for yourself in this live demo.

To conclude

If you want to use it in calculations, you might want to validate it, and let the user know that its invalid format, but you could sanitize it, and use it anyway.

Other filters

The examle here shows the usage of FILTER_SANITIZE_FLOAT, but there are other validation and santation filters. See the below links for a full description.

List of validation filters

List of sanitation filters

ContentLicense: CC BY-SA 3.0

Body:
Currently I'm making sort of calculator-like app in PHP with form as method of input. To secure input i'm using filter_input() function. As filter this function take one of elements from two groups: FILTER_SANITIZE and FILTER_VALIDATE, which one should i use to filter input from form?

$number1 = trim(filter_input(INPUT_GET, 'number1', FILTER_VALIDATE_FLOAT));

or

$number1 = trim(filter_input(INPUT_GET, 'number1', FILTER_SANITIZE_FLOAT));

Body:
It depends on what you need or is suitable for your application, really. One would validate it, and say "Yes, this is (or isn't) a valid float", while the other would clean it for any non-acceptable value and return that, and not say anything if the original input was valid or not to begin with.

The same applies for the other FILTER_SANITIZE_* and FILTER_VALIDATE_*constants, but in this example we'll look at floating-point validation and sanitation, as asked in the original question.

Let's take a look!

$float = 0.032;
$not_float = "0.03b2";

var_dump(filter_var($float, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION));
var_dump(filter_var($not_float, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION));

var_dump(filter_var($float, FILTER_VALIDATE_FLOAT));
var_dump(filter_var($not_float, FILTER_VALIDATE_FLOAT));

The return from the above dumps would be

string(5) "0.032"  // $float          FILTER_SANITIZE_NUMBER_FLOAT
string(5) "0.032"  // $not_float      FILTER_SANITIZE_NUMBER_FLOAT
float(0.032)       // $float          FILTER_VALIDATE_FLOAT
bool(false)        // $not_float      FILTER_VALIDATE_FLOAT

FILTER_SANITIZE_NUMBER_FLOAT would return a string of the sanitized value (PHP isn't a strongly typed language, so "0.032" == 0.032).

You should also note the FILTER_FLAG_ALLOW_FRACTION flag, which keeps the decimal in place (without that flag it would return 0032).

As you can see, any FILTER_VALIDATE_FLOAT would return a boolean false if it isn't a valid float, and the actual floating value if it was valid (which is a "truthy" value). Keep in mind that 0.00 would be a "falsy" value, so if you wish to check if the validation failed, you should use strict comparison, in case the input was zero, but still valid.

if (filter_var($input, FILTER_VALIDATE_FLOAT) === false) {
    // Oh noes! $input wasn't a valid float!
}

You can see it for yourself in this live demo.

To conclude

If you want to use it in calculations, you might want to validate it, and let the user know that its invalid format, but you could sanitize it, and use it anyway.

Other filters

The examle here shows the usage of FILTER_SANITIZE_FLOAT, but there are other validation and santation filters. See the below links for a full description.

List of validation filters

List of sanitation filters

ContentLicense: CC BY-SA 4.0


问:
Database only saves last iteration , laravel 5.4
please why is the code below only saves last iteration ？

```<code>foreach($videos as $video)
    {
       $filename=$video->getClientOriginalName();
        $vidWay=public_path('videos');
        $lessons->video=$filename;
       // echo $filename;
        $video->move($vidWay,$filename);
        $lessons->title=$lesson_titles[$upload_count];
        $lessons->course_id=$Course->id;
        $lessons->save();
        $upload_count++;
            // echo $filename;
    }
</code>```

Any idea ？

答:
i think code must be something like this</p>

```<code>foreach($videos as $video)
    {
       $lessons=new App\Lessons()
       $filename=$video->getClientOriginalName();
        $vidWay=public_path('videos');
        $lessons->video=$filename;
       // echo $filename;
        $video->move($vidWay,$filename);
        $lessons->title=$lesson_titles[$upload_count];
        $lessons->course_id=$Course->id;
        $lessons->save();
        $upload_count++;
            // echo $filename;
    }
</code>```

Body:
please why is the code below only saves last iteration ？

foreach($videos as $video)
    {
       $filename=$video->getClientOriginalName();
        $vidWay=public_path('videos');
        $lessons->video=$filename;
       // echo $filename;
        $video->move($vidWay,$filename);
        $lessons->title=$lesson_titles[$upload_count];
        $lessons->course_id=$Course->id;
        $lessons->save();
        $upload_count++;
            // echo $filename;
    }

Any idea ？

Body:
i think code must be something like this

foreach($videos as $video)
    {
       $lessons=new App\Lessons()
       $filename=$video->getClientOriginalName();
        $vidWay=public_path('videos');
        $lessons->video=$filename;
       // echo $filename;
        $video->move($vidWay,$filename);
        $lessons->title=$lesson_titles[$upload_count];
        $lessons->course_id=$Course->id;
        $lessons->save();
        $upload_count++;
            // echo $filename;
    }


问:
How to write data to a graphics card without using BIOS?
I want to make an (extremely simple) operating system. I am currently learning about graphics cards.

This is what I know so far (please correct me if I am wrong):

A graphics card has two modes: a text mode, and a graphics mode.

You can write data to a graphics cards using BIOS (instead of accessing the graphics card directly).

What I want to do is to write directly to the graphics card's video memory without using BIOS (because I want to understand how things work). So I have the following questions:

How do I know what is the base address of the video memory of the graphics card, is this
done by probing the PCI bus to get the base address, or is the base address fixed (just like the COM ports base addresses is fixed for example)?

Are all graphics cards accessed in the same way, or do I have to create device drivers for all available graphics cards?

Edit: I am using x86.

答:
Introduction

Graphics cards are a very complex topic, I'm confident in saying that they are the most complex subsystem you'll find on a PC.

If you ever found yourself lost programming an XHCI (USB 3.0) or an old RTL8239A network interface card then be prepared because this is much more complex.

Graphics controllers are the products of a very competitive marketing - rarely a vendor opens the specifications and when it does, it gives an intentionally poor support.

If you add that the hardware itself deals with: codecs, audio (yes, audio streams too), 3D programmable pipelines, video signals and video outputs, surface formats, media formats, DMA and memory remapping then you can see that it is not an easy task to program a video card.

The better approach, in my opinion, is to "retrace the history" of the video cards.
Start from the MDA then move to CGA then EGA and finally to VGA.

The VGA legacy is still supported, the specifications can be found here or in the first part of this PDF from Intel.

You can program the VGA without the BIOS "easily" - meaning that it is an already well-known and documented hardware architecture (but not necessarily easy to configure).

I don't remember if the previous adapters were subsets of the VGA or not, if not they aren't supported anymore probably.

You can try with a virtual machine or an emulator.

When you are satisfied with the VGA you can move to the SVGA.

Here come the troubles: as Wikipedia confirms, the VGA was the last truly standardised video card/adapter interface:

Unlike VGA—a purely IBM-defined standard—Super VGA was never formally defined.

The organisation VESA standardised a BIOS API called Video BIOS Extensions to allow the use of SVGA cards to driverless OSes but that's not what you were looking for.

You can try reverse engineering a VBE BIOS but I think it will be a nightmare - a senseless stream of writes to IO ports and MMIOs.

Making sense of tenths of configuration registers without any reference is almost impossible.

Note that we are still talking about 1998 technology up to this point.

After the VESA VBE effort, no more standard interfaces have been published - the only reliable way to program a video card with less than 20 years is by signing an NDA with its vendor.

Luckily, recently (actually, not anymore), Intel entered the market with its Intel GFX (a.k.a. Intel HD Graphics) cards.

Intel never aimed to manufacture top-of-the-notch video cards, not even closely - so they can be open about their architecture since that's not their core business.

The result is this marvellous set of Programming Reference Manuals that describe the functionality of their video cards.

Complete with (traditionalistic) minimal information to program them.

In general, hobbyists stops before this point (at the SVGA checkpoint), because the hardware has become very complex and the efforts very huge.

For example, my Haswell integrated video card is documented with 17 PDFs of about 250 pages each (on average).

The display part is documented in a PDF on its own, the framebuffer has disappeared in favour of Display surface and the display part alone of the hardware is this:

While this may not be very comprehensible, it should suffice to get an idea of the numerous technology that a programmer must understand before programming a modern video card.

You can surely take a look at the Linux source code but beware that the Linux kernel is no usually of immediate understanding even for simple controllers - it is not a toy OS, it is a real OS with its own API and interface that must fit the hardware interface (actually the other way around).

Furthermore, only the Intel and AMD video drivers are really open source, the others are either proprietary or just a bunch of undocumented code.

Brief outline of common VGA modes programming

If you just want to program the VGA (a very respectable task indeed!) you can start by setting the video modes 03h (text mode) or 13h (graphics mode).

Video mode 03h

The frame buffer is at 0b8000h (physical address), usually accessed as 0b800h:0000h as it is handy to have a zero offset.

The screen is made up of 80x25 characters, each characters occupy a word (16-bit) in the frame buffer.

The low byte is the character code - the character map used will associate a glyph to a code (e.g. 41h to A).

The high order byte is the attribute byte - the low nibble is the foreground colour, the high nibble is the background colour.

More information can be found in the EGA/CGA/VGA links above.

Video mode 13h

It is a graphical mode with 320x200 pixel, the frame buffer is at 0a0000h (physical address) usually accessed as 0a000h:0000h for the same reason of above.

Each pixel is a single byte, the value of the byte selects the colour of the pixel.

The default palette can be changed by programming the DAC registers (3c7h, 3c8h, 3c9h for the VGA adapter).

Answers

A graphics card has two modes: a text mode, and a graphics mode.

Not necessarily, today this distinction may not exist anymore.

The MDA had only a text mode.

EGA, CGA and VGA and SVGA had both.

The modern approach is to draw the text, however during boot or during particular situations (e.g. BSOD) a basic video driver in text mode is used.

This driver probably uses a BIOS service since the video driver may not be available/reliable.

You can write data to a graphics cards using BIOS

Up to the SVGA era, then BIOS support was discontinued.

How do I know what is the base address of the video memory of the graphics card, is this done by probing the PCI bus to get the base address, or is the base address fixed (just like the COM ports base addresses is fixed for example)?

Video cards have been connected through the history to the ISA, PCI, AGP and PCIe buses.

Only the ISA bus wasn't configurable (at least not from the beginning), the others had configurable BARs (Base Address Registers) per function (the smallest addressable entity in the PCI bus).

In order to get the base address of the MMIO registers of a video card the PCI or PCIe bus must be enumerated and the standard registers in the configuration space must be read/set.

Dealing with PCIe is not as easy as dealing with PCI.

Note that not even the UARTs have a fixed address, they are configured by default to map to the legacy (3f8h, 2f8h, 3e8h and 2e8h) addresses but the hardware was (is?) in a SuperIO chip behind a PCI-to-LPC bridge that emulated a PCI-to-ISA bridge.

With the advent of the Intel platform hub architecture (i.e. the death of the north and south bridge) the SuperIO chip eventually made it into the PCH or moved behind the SPI controller.

Are all graphics cards accessed in the same way, or do I have to create device drivers for all available graphics cards?

Each graphic card is a beautiful vicious creature on its own.

A device driver is needed for each model.

Some driver can be reused for a whole family of models but this is not true in general.


问:
SEO URL # vs. #!

Possible Duplicate:

  What's the shebang (#!) in Facebook and new Twitter URLs for?

Hello!

What is the difference between this URL: mysite.com/images.php#img-1 and this URL: mysite.com/images.php#!img-1, please?

I have a simple photo gallery, nothing fancy, that changes images from a JavaScript array of files and instead of refreshing the page for every image it does it "on the spot" using jQuery.

Thank you.

答:
As soon as you use the hashbang in a
  URL, Google will spot that you're
  following their protocol, and
  interpret your URLs in a special way -
  they'll take everything after the
  hashbang, and pass it to the site as a
  URL parameter instead. The name they
  use for the parameter is:
  _escaped_fragment_

reference: http://www.seomoz.org/blog/how-to-allow-google-to-crawl-ajax-content

ContentLicense: CC BY-SA 2.5

Title: SEO URL # vs. #!


问:
AES-256 best practices implementation
I'm reversing an app but I'm not very expert of the AES algorithm.
The application gives the user the opportunity to make an offline login.

The user is asked to provide his username and password

This is the function that is used to store the info of the user

```<code>    public void EncryptLoginInfo(string username, byte[] secretShared, byte[] salt)
{
  byte[] random = calc.GenerateRandomBytes();
  byte[] array = aes.Encrypt(secretShared, random);
  OfflineLogin loginInfo = new OfflineLogin()
  {
    Username = username,
    SecretShared = array,
    Iv = random,
    Salt = salt
  };
  this._userCredentials.StoreOfflineLoginData(username, loginInfo);
}
</code>```

And this are the info that are stored inside an internal config file of the app. In the example below, the password passed to the encryptLoginInfo is 123

```<code>Username: not_important
SecretShared: 4KVrjy1cQVWYpWF7aolpMS0HzhKyFf+9VXauQrXoXVUbf0bGXIDOLDJuSVhYoFo2
Iv:yil4nn02IoKsOnX5KXVsDg==
Salt: 5kJio2VQEqjomHRdQMqRVJ0zkBsmqi8K3NypC2VWJk4
</code>```

If the user want to make an offline login, he is asked to provide username and his password.

Question: Is this algo safe? If an attacker is able to obtain SecretShared+Iv+Salt is he able to recover the password of the user (that in this specific example is 123)

This is the decrypt function

```<code>public void DencryptLoginInfo(OfflineLogin loginInfo)
{
  byte[] array = aes.Decrypt(loginInfo.SecretShared, loginInfo.Iv);
  loginInfo.SecretShared = array;
  loginInfo.Iv = (byte[]) null;
}
</code>```

Are you able to spot any security issues in this implementation? The algo used should be AES-256.. Are you able to implement a POC in python to decrypt the PASSWORD given SecretShared+Iv+Salt?

答:
According to your comment, your goal is to authenticate the user.  For that we use password base key derivation functions on the password.  Often people refer to this as "hashing passwords", which is unfortunate terminology because "hashing" can mean anything.  But the main point is that we do not encrypt passwords, instead we send them through a one-way function that is designed to be slow.  The slow speed deters brute force attacks.

You do not need an IV to do this.  Instead, your app should be deriving a salt and and using a password based key derivation function (sometimes referred to as a "password hashing" algorithm: you will have to excuse that the industry has made a mess out of the terminology on this topic).  You can find guidance on this all over the web.  But I suggest you have a read of point 4 in Top 10 Developer Crypto Mistakes to see common pitfalls in implementing this.

Don't use openssl to convert a password into a key (or password hash)!  The algorithm in openssl is weak.  Openssl's EVP_BytesToKey() fails to meet the requirements of slow speed, meaning that it is easy to brute force your key from your password.

The proper solution to this problem is to use an algorithm such as bcrypt or pbkdf2 (Java implementations can be found without much effort) to derive a "hash" from the password.  You then verify that the user typed in the password correctly by re-doing the same computation with the user entered password and the salt that was stored for this password.  If they match, access is granted, otherwise access is denied.

Note that if this app interacts with a server, normally you do password verification on the server side.  If your app does not interact with a server, then you may have a good reason to do it on the device.  I don't know what your app does, so I cannot tell you what is right or wrong for you.

A great reference for doing this properly is How to Safely Store Your Users' Passwords in 2016 .

Title: AES-256 best practices implementation

Body:
I'm reversing an app but I'm not very expert of the AES algorithm.
The application gives the user the opportunity to make an offline login.

The user is asked to provide his username and password

This is the function that is used to store the info of the user

    public void EncryptLoginInfo(string username, byte[] secretShared, byte[] salt)
{
  byte[] random = calc.GenerateRandomBytes();
  byte[] array = aes.Encrypt(secretShared, random);
  OfflineLogin loginInfo = new OfflineLogin()
  {
    Username = username,
    SecretShared = array,
    Iv = random,
    Salt = salt
  };
  this._userCredentials.StoreOfflineLoginData(username, loginInfo);
}

And this are the info that are stored inside an internal config file of the app. In the example below, the password passed to the encryptLoginInfo is 123

Username: not_important
SecretShared: 4KVrjy1cQVWYpWF7aolpMS0HzhKyFf+9VXauQrXoXVUbf0bGXIDOLDJuSVhYoFo2
Iv:yil4nn02IoKsOnX5KXVsDg==
Salt: 5kJio2VQEqjomHRdQMqRVJ0zkBsmqi8K3NypC2VWJk4

If the user want to make an offline login, he is asked to provide username and his password.

Question: Is this algo safe? If an attacker is able to obtain SecretShared+Iv+Salt is he able to recover the password of the user (that in this specific example is 123)

This is the decrypt function

public void DencryptLoginInfo(OfflineLogin loginInfo)
{
  byte[] array = aes.Decrypt(loginInfo.SecretShared, loginInfo.Iv);
  loginInfo.SecretShared = array;
  loginInfo.Iv = (byte[]) null;
}

Are you able to spot any security issues in this implementation? The algo used should be AES-256.. Are you able to implement a POC in python to decrypt the PASSWORD given SecretShared+Iv+Salt?


问:
Going mad with Android Fragment Transaction
I can not comprehend this behavior of my fragment transactions. Can someone please intervent before I go crazy. In my MainActivity I set it up correctly:

```<code>    private final GuideFragment guideFragment = new GuideFragment();
    private final MapFragment mapFragment = new MapFragment();
    private final MoreFragment moreFragment = new MoreFragment();

    Fragment active;

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
                = new BottomNavigationView.OnNavigationItemSelectedListener() {

            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                FragmentTransaction transaction = getFragmentManager().beginTransaction();
                switch (item.getItemId()) {
                    case R.id.navigation_guide:
                        if (!guideFragment.isAdded()) {
                            transaction.add(R.id.content,guideFragment).commit();
                            active = guideFragment;
                            Log.d(TAG, "add Fragment1");
                            break;
                        } else {
                            transaction.hide(active).show(guideFragment).commit();
                            active = guideFragment;
                            Log.d(TAG, "show Fragment1");
                            break;
                        }
                    case R.id.navigation_map:
                        if (!mapFragment.isAdded()) {
                            transaction.add(R.id.content, mapFragment).commit();
                            active = mapFragment;
                            Log.d(TAG,"add Fragment2");
                            break;
                        } else {
                            transaction.hide(active).show(mapFragment).commit();
                            active = mapFragment;
                            Log.d(TAG,"show Fragment2");
                            break;
                        }
                    case R.id.navigation_more:
                        if (!moreFragment.isAdded()) {
                            transaction.add(R.id.content,moreFragment).commit();
                            active = moreFragment;
                            Log.d(TAG,"add Fragment3");
                            break;
                        } else {
                            transaction.hide(active).show(moreFragment).commit();
                            active = moreFragment;
                            Log.d(TAG,"show Fragment3");
                            break;
                        }
                }

                return true;
            }

        };

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);

        //start with guide view/fragment
        switchTabView(R.id.navigation_guide);

    }

    //method to start or switch a tab
    private void switchTabView(int itemId) {
        navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
        navigation.setSelectedItemId(itemId);

    }
</code>```

My App has 3 Tabs as you can see above: Tab1 (Guide) Tab2 (Map) Tab3 (More).

When the app launches, the first Tab (Guide) is added and shown correctly.
Then I tap on Map (next Fragment), this is added and shown correctly.
Finally on the More Tab (my 3rd Tab) all works great.

But when the activity launches and I tap 1-3 (Guide to Map) so far correct -
then 3-2 (More Tab to Map Tab) all good - but then back from 2-1 (Map to Guide) there is suddenly the 3rd tab Fragment (More) shown where the Guide Fragment should be.

Someone has an idea on what is wrong?
Would appreciate some help.

Solution thanks to Mateus

```<code>transaction.hide(fragment3).hide(fragment2).show(fragment1).commit();
</code>```

I am not sure if calling two times hide fragment is that clean but I think with 3 tabs it is still okay. With more tabs I would consider to handle this in a different way like remove() or replace() fragments.

Update - Solution is more tricky as expected:

```<code>           switch (item.getItemId()) {
                case R.id.navigation_guide:
                    if (!guideFragment.isAdded()) {
                        transaction.add(R.id.content,guideFragment).commit();
                        Log.d(TAG, "add Fragment1");
                        break;
                    } else {
                        if (!moreFragment.isAdded() && mapFragment.isAdded()) {
                            transaction.hide(mapFragment).show(guideFragment).commit();
                        }
                        if (moreFragment.isAdded() && !mapFragment.isAdded()) {
                            transaction.hide(moreFragment).show(guideFragment).commit();
                        }
                        if (moreFragment.isAdded() && mapFragment.isAdded()) {
                            transaction.hide(moreFragment).hide(mapFragment).show(guideFragment).commit();
                        }

                        Log.d(TAG, "show Fragment1");
                        break;
                    }
                case R.id.navigation_map:
                    if (!mapFragment.isAdded()) {
                        transaction.add(R.id.content, mapFragment).commit();
                        Log.d(TAG,"add Fragment2");
                        break;
                    } else {
                        if (!moreFragment.isAdded()) {
                            transaction.hide(guideFragment).show(mapFragment).commit();
                        } else {
                            transaction.hide(guideFragment).hide(moreFragment).show(mapFragment).commit();
                        }
                        Log.d(TAG,"show Fragment2");
                        break;
                    }
                case R.id.navigation_more:
                    if (!moreFragment.isAdded()) {
                        transaction.add(R.id.content,moreFragment).commit();
                        Log.d(TAG,"add Fragment3");
                        break;
                    } else {
                        if (!mapFragment.isAdded()) {
                            transaction.hide(guideFragment).show(moreFragment).commit();
                        } else {
                            transaction.hide(guideFragment).hide(mapFragment).show(moreFragment).commit();
                        }
                        Log.d(TAG,"show Fragment3");
                        break;
                    }
            }
</code>```

Finally bug free, you have to check if other fragments are added!

答:
When I want to go to another fragment in the same activity I use this:

```<code>FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

transaction.replace(R.id.container,yourFragment);
transaction.commit();
</code>```

Container is a layout in your activity. Use it to show your fragment.
Also you have to init in each case of bottomNavigationView the FragmentTransaction object!

I believe that this is what you are looking for!

Body:
I can not comprehend this behavior of my fragment transactions. Can someone please intervent before I go crazy. In my MainActivity I set it up correctly:

    private final GuideFragment guideFragment = new GuideFragment();
    private final MapFragment mapFragment = new MapFragment();
    private final MoreFragment moreFragment = new MoreFragment();

    Fragment active;

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
                = new BottomNavigationView.OnNavigationItemSelectedListener() {

            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                FragmentTransaction transaction = getFragmentManager().beginTransaction();
                switch (item.getItemId()) {
                    case R.id.navigation_guide:
                        if (!guideFragment.isAdded()) {
                            transaction.add(R.id.content,guideFragment).commit();
                            active = guideFragment;
                            Log.d(TAG, "add Fragment1");
                            break;
                        } else {
                            transaction.hide(active).show(guideFragment).commit();
                            active = guideFragment;
                            Log.d(TAG, "show Fragment1");
                            break;
                        }
                    case R.id.navigation_map:
                        if (!mapFragment.isAdded()) {
                            transaction.add(R.id.content, mapFragment).commit();
                            active = mapFragment;
                            Log.d(TAG,"add Fragment2");
                            break;
                        } else {
                            transaction.hide(active).show(mapFragment).commit();
                            active = mapFragment;
                            Log.d(TAG,"show Fragment2");
                            break;
                        }
                    case R.id.navigation_more:
                        if (!moreFragment.isAdded()) {
                            transaction.add(R.id.content,moreFragment).commit();
                            active = moreFragment;
                            Log.d(TAG,"add Fragment3");
                            break;
                        } else {
                            transaction.hide(active).show(moreFragment).commit();
                            active = moreFragment;
                            Log.d(TAG,"show Fragment3");
                            break;
                        }
                }

                return true;
            }

        };

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);

        //start with guide view/fragment
        switchTabView(R.id.navigation_guide);

    }

    //method to start or switch a tab
    private void switchTabView(int itemId) {
        navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
        navigation.setSelectedItemId(itemId);

    }

My App has 3 Tabs as you can see above: Tab1 (Guide) Tab2 (Map) Tab3 (More).

When the app launches, the first Tab (Guide) is added and shown correctly.
Then I tap on Map (next Fragment), this is added and shown correctly.
Finally on the More Tab (my 3rd Tab) all works great.

But when the activity launches and I tap 1-3 (Guide to Map) so far correct -
then 3-2 (More Tab to Map Tab) all good - but then back from 2-1 (Map to Guide) there is suddenly the 3rd tab Fragment (More) shown where the Guide Fragment should be.

Someone has an idea on what is wrong?
Would appreciate some help.

Solution thanks to Mateus

transaction.hide(fragment3).hide(fragment2).show(fragment1).commit();

I am not sure if calling two times hide fragment is that clean but I think with 3 tabs it is still okay. With more tabs I would consider to handle this in a different way like remove() or replace() fragments.

Update - Solution is more tricky as expected:

           switch (item.getItemId()) {
                case R.id.navigation_guide:
                    if (!guideFragment.isAdded()) {
                        transaction.add(R.id.content,guideFragment).commit();
                        Log.d(TAG, "add Fragment1");
                        break;
                    } else {
                        if (!moreFragment.isAdded() && mapFragment.isAdded()) {
                            transaction.hide(mapFragment).show(guideFragment).commit();
                        }
                        if (moreFragment.isAdded() && !mapFragment.isAdded()) {
                            transaction.hide(moreFragment).show(guideFragment).commit();
                        }
                        if (moreFragment.isAdded() && mapFragment.isAdded()) {
                            transaction.hide(moreFragment).hide(mapFragment).show(guideFragment).commit();
                        }

                        Log.d(TAG, "show Fragment1");
                        break;
                    }
                case R.id.navigation_map:
                    if (!mapFragment.isAdded()) {
                        transaction.add(R.id.content, mapFragment).commit();
                        Log.d(TAG,"add Fragment2");
                        break;
                    } else {
                        if (!moreFragment.isAdded()) {
                            transaction.hide(guideFragment).show(mapFragment).commit();
                        } else {
                            transaction.hide(guideFragment).hide(moreFragment).show(mapFragment).commit();
                        }
                        Log.d(TAG,"show Fragment2");
                        break;
                    }
                case R.id.navigation_more:
                    if (!moreFragment.isAdded()) {
                        transaction.add(R.id.content,moreFragment).commit();
                        Log.d(TAG,"add Fragment3");
                        break;
                    } else {
                        if (!mapFragment.isAdded()) {
                            transaction.hide(guideFragment).show(moreFragment).commit();
                        } else {
                            transaction.hide(guideFragment).hide(mapFragment).show(moreFragment).commit();
                        }
                        Log.d(TAG,"show Fragment3");
                        break;
                    }
            }

Finally bug free, you have to check if other fragments are added!

Body:
When I want to go to another fragment in the same activity I use this:

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

transaction.replace(R.id.container,yourFragment);
transaction.commit();

Container is a layout in your activity. Use it to show your fragment.
Also you have to init in each case of bottomNavigationView the FragmentTransaction object!

I believe that this is what you are looking for!


问:
What are my options for interpolation of such data
Having dramatically different step sizes, and not much data. We have data like >--4-6----3-9----4-7----9-3----4-1----> ( - is step here ) and in real life this data is looped in a circle. What polynomials/formulas can help me with interpolation of such data? Will Bezier work?

答: Fit Cublic Splines on each set. A single BeZier curve is not accurate enough (unless you know otherwise). Another option is Chebyschev Polynomials.</p>


问:
Formatting Excel in VB.NET
I am exporting DataGridViews to Excel using ClipboardCopyMode. However, I want to format the header and the cell width/height, because the cells aren't adjusting normally.

Also, I want to add some data in it apart of the data from the DataGridView.

This is the code of the sub I have:

```<code>     Dim appExcel As Excel.Application
     Dim wbExcel As Excel.Workbook

            System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("es-US")

            If Combo.SelectedValue.ToString().Trim() = "Something" Then

                dgv.SelectAll()
                dgv.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText
                Clipboard.SetDataObject(dgv.GetClipboardContent())

            End If

      appExcel = New Excel.Application
      appExcel.SheetsInNewWorkbook = 1
      wbExcel = appExcel.Workbooks.Add
      appExcel.Visible = True

      wbExcel.Worksheets(1).Range("A3").Select()
      wbExcel.Worksheets(1).Paste()
</code>```

How can I do these things and beautify my exported Excel?

Thanks in advance

答:
To style the cells, you can create an Excel.Style and apply it to a range. First, you need to get a reference to the worksheet like:

```<code>Dim xlWorksheet As Excel.Worksheet = wbExcel.Worksheets(1)
</code>```

Then Create the style:

```<code>Dim RptHeader As Excel.Style = xlWorksheet.Application.ActiveWorkbook.Styles.Add("RptHeader")
RptHeader.Font.Bold = True
RptHeader.Font.Size = 14
RptHeader.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightSteelBlue)
RptHeader.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter
</code>```

Then set a range/cell's style (For a range, just use something like  xlWorksheet.Range("A1:A2").Style):

```<code>xlWorksheet.Cells(1, 1).Style = "RptHeader"
</code>```

...As for cell width/height, the basic syntax looks like:

```<code>xlWorksheet.Columns(1).EntireColumn.ColumnWidth = 25
xlWorksheet.Rows(1).RowHeight = 25
</code>```

When you say the columns aren't "adjusting normally" though, I get the sense you're talking about autofit, which can also be accomplished like so:

```<code>xlWorksheet.Range("A:XFD").EntireColumn.AutoFit()
</code>```

To add data that is not part of your copy from the datagridview, simply set a cell's value to whatever you want like:

```<code>xlWorkSheet.Cells(1, 2) = "1234" '1 being the row-index, 2 the column-index
</code>```

Title: Formatting Excel in VB.NET

Body:
I am exporting DataGridViews to Excel using ClipboardCopyMode. However, I want to format the header and the cell width/height, because the cells aren't adjusting normally.

Also, I want to add some data in it apart of the data from the DataGridView.

This is the code of the sub I have:

     Dim appExcel As Excel.Application
     Dim wbExcel As Excel.Workbook

            System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("es-US")

            If Combo.SelectedValue.ToString().Trim() = "Something" Then

                dgv.SelectAll()
                dgv.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText
                Clipboard.SetDataObject(dgv.GetClipboardContent())

            End If

      appExcel = New Excel.Application
      appExcel.SheetsInNewWorkbook = 1
      wbExcel = appExcel.Workbooks.Add
      appExcel.Visible = True

      wbExcel.Worksheets(1).Range("A3").Select()
      wbExcel.Worksheets(1).Paste()

How can I do these things and beautify my exported Excel?

Thanks in advance

Body:
To style the cells, you can create an Excel.Style and apply it to a range. First, you need to get a reference to the worksheet like:

Dim xlWorksheet As Excel.Worksheet = wbExcel.Worksheets(1)

Then Create the style:

Dim RptHeader As Excel.Style = xlWorksheet.Application.ActiveWorkbook.Styles.Add("RptHeader")
RptHeader.Font.Bold = True
RptHeader.Font.Size = 14
RptHeader.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightSteelBlue)
RptHeader.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter

Then set a range/cell's style (For a range, just use something like  xlWorksheet.Range("A1:A2").Style):

xlWorksheet.Cells(1, 1).Style = "RptHeader"

...As for cell width/height, the basic syntax looks like:

xlWorksheet.Columns(1).EntireColumn.ColumnWidth = 25
xlWorksheet.Rows(1).RowHeight = 25

When you say the columns aren't "adjusting normally" though, I get the sense you're talking about autofit, which can also be accomplished like so:

xlWorksheet.Range("A:XFD").EntireColumn.AutoFit()

To add data that is not part of your copy from the datagridview, simply set a cell's value to whatever you want like:

xlWorkSheet.Cells(1, 2) = "1234" '1 being the row-index, 2 the column-index


问:
When element is updated twice JQ is not working
I'm using socket.io to send some data, but JQ animation/slideToggle etc. works only on last element (data1 and data2 won't toggle for example).

After reverse engineering/cut all non-related code/ modify it so it's simpler and better for understand, I got:

HTML:

```<code>                <div class="wrapper1">
                <div class="wrapper1_name">WRAPPER1</div>
                    <ul class="wrapper1_ul">
                        <li>
                            <div class="container1_name">container1</div>
                            <div class="container1"></div>
                            <div class="container2_name">container2</div>
                            <div class="container2"></div>
                            <div class="container3_name">container3</div>
                            <div class="container3"></div>
                        </li>
                    </ul>
                </div>
<script src="jquery.min_v3.1.1.js"></script>
</code>```

SOCKET.IO - server:

```<code>            socketio_data1_html = '<div class="data1">Data1</div>'
            req.io.emit('socketio data1', {socketio_data1_html : data1});

            socketio_data2_html = '<div class="data2">Data2</div>'
            req.io.emit('socketio data2', {socketio_data2_html : data2});

            socketio_data3_html = '<div class="data3">Data3</div>'
            req.io.emit('socketio data3', {socketio_data3_html : data3});
</code>```

SOCKET.IO - client:

```<code>            /* DATA1 */
                socket.on('socketio data1', function(data1)
                {
                    document.getElementsByClassName('container1')[0].innerHTML +=
                    '<ul class="data1_ul"><u>Data1:</u>'
                        + '<li>'
                            + '<ul class="ul_data1_content">'
                                + '<li class="data1_li_content">' + data1.socketio_data1_html + '</li>'
                            + '</ul>'
                        + '</li>'
                        + '<li>'
                            + '<ul class="ul_data1_info">Slide text (CLICK ME - why this is not working?):'
                                + '<li class="data1_li_info">'
                                    + 'Data1 slideToogle text.'
                                + '</li>'
                            + '</ul>'
                        + '</li>'
                    + '</ul>';

                    if (document.getElementsByClassName('.data1_ul') !== null)
                    {
                        $('.data1_li_info').hide(); // optional - to hide INFO by default
                        $('.ul_data1_info').click(function()
                        {
                            $('.data1_li_info').slideToggle();
                        });
                    }
                });
            /* / DATA1 */

            /*  DATA2 */
                socket.on('socketio data2', function(data2)
                {
                    document.getElementsByClassName('container1')[0].innerHTML +=
                    '<ul class="data2_ul"><u>Data2:</u>'
                        + '<li>'
                            + '<ul class="ul_data2_content">'
                                + '<li class="data2_li_content">' + data2.socketio_data2_html + '</li>'
                            + '</ul>'
                        + '</li>'
                        + '<li>'
                            + '<ul class="ul_data2_info">Slide text (CLICK ME - why this is not working?):'
                                + '<li class="data2_li_info">'
                                    + 'Data2 slideToogle text.'
                                + '</li>'
                            + '</ul>'
                        + '</li>'
                    + '</ul>';

                    if (document.getElementsByClassName('.data2_ul') !== null)
                    {
                        $('.data2_li_info').hide(); // optional - to hide INFO by default
                        $('.ul_data2_info').click(function()
                        {
                            $('.data2_li_info').slideToggle();
                        });
                    }
                });
            /* / DATA2 */

            /* DATA3 */
                socket.on('socketio data3', function(data3)
                {
                    document.getElementsByClassName('container1')[0].innerHTML +=
                    '<ul class="data3_ul"><u>Data3:</u>'
                        + '<li>'
                            + '<ul class="ul_data3_content">'
                                + '<li class="data3_li_content">' + data3.socketio_data3_html + '</li>'
                            + '</ul>'
                        + '</li>'
                        + '<li>'
                            + '<ul class="ul_data3_info">Slide text (CLICK ME - why only this works?):'
                                + '<li class="data3_li_info">'
                                    + 'Data3 slideToogle text.'
                                + '</li>'
                            + '</ul>'
                        + '</li>'
                    + '</ul>';

                    if (document.getElementsByClassName('.data3_ul') !== null)
                    {
                        $('.data3_li_info').hide(); // optional - to hide INFO by default
                        $('.ul_data3_info').click(function()
                        {
                            $('.data3_li_info').slideToggle();
                        });
                    }
                });
            /* / DATA3 */
</code>```

CSS:

```<code>.wrapper1
{padding:10px;
background:red;}

.wrapper1_name
{padding:10px;
background:brown;}

.container1_name
{padding:10px;
background:green;}

.container1
{padding:20px;
background:blue;}

.data1
{padding:10px;
background:orange;}

.data2
{padding:10px;
background:pink;}

.data3
{padding:10px;
background:aqua;}

.container2
{padding:20px;
background:violet;}

.container3
{padding:20px;
background:gray;}
</code>```

Any idea WHY?

答:
It's cause of flow of JS. By the time your third data socket.on pass, rest is outdated (cause you change html structure).

A simple working example is put all related JQ (your animation, slidetoggle and so on) in latest socket on data. Here:

```<code>socket.on('socketio data3', function(data3)
                {
                    document.getElementsByClassName('container1')[0].innerHTML +=
                    '<ul class="data3_ul"><u>Data3:</u>'
                        + '<li>'
                            + '<ul class="ul_data3_content">'
                                + '<li class="data3_li_content">' + data3.socketio_data3_html + '</li>'
                            + '</ul>'
                        + '</li>'
                        + '<li>'
                            + '<ul class="ul_data3_info">Slide text (CLICK ME - why only this works?):'
                                + '<li class="data3_li_info">'
                                    + 'Data3 slideToogle text.'
                                + '</li>'
                            + '</ul>'
                        + '</li>'
                    + '</ul>';

                    if (document.getElementsByClassName('.data3_ul') !== null)
                    {
                        $('.data3_li_info').hide(); // optional - to hide INFO by default
                        $('.ul_data3_info').click(function()
                        {
                            $('.data3_li_info').slideToggle();
                        });
                    }

                    if (document.getElementsByClassName('.data2_ul') !== null)
                    {
                        $('.data2_li_info').hide(); // optional - to hide INFO by default
                        $('.ul_data2_info').click(function()
                        {
                            $('.data2_li_info').slideToggle();
                        });
                    }

                    if (document.getElementsByClassName('.data1_ul') !== null)
                    {
                        $('.data1_li_info').hide(); // optional - to hide INFO by default
                        $('.ul_data1_info').click(function()
                        {
                            $('.data1_li_info').slideToggle();
                        });
                    }

                });
</code>```

This should work. Or you can put all JS/JQ related code in additional file and load it after all socket data is passed. The thing is, you need update html structure at first, THEN add JQ effects that makes use of it (html).

Body:
I'm using socket.io to send some data, but JQ animation/slideToggle etc. works only on last element (data1 and data2 won't toggle for example).

After reverse engineering/cut all non-related code/ modify it so it's simpler and better for understand, I got:

HTML:

WRAPPER1

container1

container2

container3

SOCKET.IO - server:

            socketio_data1_html = '
Data1
'
            req.io.emit('socketio data1', {socketio_data1_html : data1});

            socketio_data2_html = '
Data2
'
            req.io.emit('socketio data2', {socketio_data2_html : data2});

            socketio_data3_html = '
Data3
'
            req.io.emit('socketio data3', {socketio_data3_html : data3});

SOCKET.IO - client:

            /* DATA1 */
                socket.on('socketio data1', function(data1)
                {
                    document.getElementsByClassName('container1')[0].innerHTML +=
                    '
Data1:'
                        + '
'
                            + '
'
                                + '
' + data1.socketio_data1_html + '
'
                            + '
'
                        + '
'
                        + '
'
                            + '
Slide text (CLICK ME - why this is not working?):'
                                + '
'
                                    + 'Data1 slideToogle text.'
                                + '
'
                            + '
'
                        + '
'
                    + '
';

                    if (document.getElementsByClassName('.data1_ul') !== null)
                    {
                        $('.data1_li_info').hide(); // optional - to hide INFO by default
                        $('.ul_data1_info').click(function()
                        {
                            $('.data1_li_info').slideToggle();
                        });
                    }
                });
            /* / DATA1 */

            /*  DATA2 */
                socket.on('socketio data2', function(data2)
                {
                    document.getElementsByClassName('container1')[0].innerHTML +=
                    '
Data2:'
                        + '
'
                            + '
'
                                + '
' + data2.socketio_data2_html + '
'
                            + '
'
                        + '
'
                        + '
'
                            + '
Slide text (CLICK ME - why this is not working?):'
                                + '
'
                                    + 'Data2 slideToogle text.'
                                + '
'
                            + '
'
                        + '
'
                    + '
';

                    if (document.getElementsByClassName('.data2_ul') !== null)
                    {
                        $('.data2_li_info').hide(); // optional - to hide INFO by default
                        $('.ul_data2_info').click(function()
                        {
                            $('.data2_li_info').slideToggle();
                        });
                    }
                });
            /* / DATA2 */

            /* DATA3 */
                socket.on('socketio data3', function(data3)
                {
                    document.getElementsByClassName('container1')[0].innerHTML +=
                    '
Data3:'
                        + '
'
                            + '
'
                                + '
' + data3.socketio_data3_html + '
'
                            + '
'
                        + '
'
                        + '
'
                            + '
Slide text (CLICK ME - why only this works?):'
                                + '
'
                                    + 'Data3 slideToogle text.'
                                + '
'
                            + '
'
                        + '
'
                    + '
';

                    if (document.getElementsByClassName('.data3_ul') !== null)
                    {
                        $('.data3_li_info').hide(); // optional - to hide INFO by default
                        $('.ul_data3_info').click(function()
                        {
                            $('.data3_li_info').slideToggle();
                        });
                    }
                });
            /* / DATA3 */

CSS:

.wrapper1
{padding:10px;
background:red;}

.wrapper1_name
{padding:10px;
background:brown;}

.container1_name
{padding:10px;
background:green;}

.container1
{padding:20px;
background:blue;}

.data1
{padding:10px;
background:orange;}

.data2
{padding:10px;
background:pink;}

.data3
{padding:10px;
background:aqua;}

.container2
{padding:20px;
background:violet;}

.container3
{padding:20px;
background:gray;}

Any idea WHY?

Body:
It's cause of flow of JS. By the time your third data socket.on pass, rest is outdated (cause you change html structure).

A simple working example is put all related JQ (your animation, slidetoggle and so on) in latest socket on data. Here:

socket.on('socketio data3', function(data3)
                {
                    document.getElementsByClassName('container1')[0].innerHTML +=
                    '<ul class="data3_ul"><u>Data3:</u>'
                        + '<li>'
                            + '<ul class="ul_data3_content">'
                                + '<li class="data3_li_content">' + data3.socketio_data3_html + '</li>'
                            + '</ul>'
                        + '</li>'
                        + '<li>'
                            + '<ul class="ul_data3_info">Slide text (CLICK ME - why only this works?):'
                                + '<li class="data3_li_info">'
                                    + 'Data3 slideToogle text.'
                                + '</li>'
                            + '</ul>'
                        + '</li>'
                    + '</ul>';

                    if (document.getElementsByClassName('.data3_ul') !== null)
                    {
                        $('.data3_li_info').hide(); // optional - to hide INFO by default
                        $('.ul_data3_info').click(function()
                        {
                            $('.data3_li_info').slideToggle();
                        });
                    }

                    if (document.getElementsByClassName('.data2_ul') !== null)
                    {
                        $('.data2_li_info').hide(); // optional - to hide INFO by default
                        $('.ul_data2_info').click(function()
                        {
                            $('.data2_li_info').slideToggle();
                        });
                    }

                    if (document.getElementsByClassName('.data1_ul') !== null)
                    {
                        $('.data1_li_info').hide(); // optional - to hide INFO by default
                        $('.ul_data1_info').click(function()
                        {
                            $('.data1_li_info').slideToggle();
                        });
                    }

                });

This should work. Or you can put all JS/JQ related code in additional file and load it after all socket data is passed. The thing is, you need update html structure at first, THEN add JQ effects that makes use of it (html).


问:
Angular 2 http.post not working with web api
My Web Api Core Controller Method looks like this

```<code>public void Post(Sample sample) {
         _sampleService.CreateSample(sample);
    }
</code>```

Sample POCO looks like this

```<code>  public class Sample : BaseEntity
{
    public string BarCode { get; set; }
    public DateTime CreatedAt { get; set; }
    public virtual User CreatedBy { get; set; }
    public virtual Status Status { get; set; }
}
</code>```

on the client side sample object is only sending 2 properties for now and looks like this.

```<code>{barcode:"1234"createdAt:"2017-06-07"}
</code>```

and the http post looks like this

```<code>createSample(sample: Sample) {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.post(AppConstants.createSample, JSON.stringify(sample), { headers: headers })
  .map((res: Response) => res.json());  }
</code>```

so if i user headers i get  No 'Access-Control-Allow-Origin' header is present

if i not use headers i get (Unsupported Media Type)

any idea whats going on here.
UPDATE
so I followed instructions as in first answer and looks like CORS is not set property but now JSON is not being converted to C# Object

答:
You need to use headers to tell the API method what you're sending.

You need to enable CORS in your .Net Core app Startup.cs so that your API allows requests coming from another origin (accepts calls from your client app url, basically) - and set CORS to AllowAnyMethod()

You do this with the following code in your ConfigureServices() method:

```<code>var corsUrls = new List<string>(){"http://localhost:4200", "https://mylivesite.com"};

services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
{
    builder
      .AllowAnyMethod() //<--this allows preflight headers required for POST
      .AllowAnyHeader() //<--accepts headers
      .AllowCredentials() //<--lets your app send auth credentials
      .WithOrigins(corsUrls.ToArray()); //<--this is the important line
}));

services.Configure<MvcOptions>(
    options => { options.Filters.Add(new CorsAuthorizationFilterFactory("CorsPolicy")); });
</code>```

and then finally in your Configure() method:

```<code>app.UseCors("CorsPolicy");
</code>```

Note that the policy name "CorsPolicy" that I've used is just an example, you can call it whatever you like.

Body:
My Web Api Core Controller Method looks like this

public void Post(Sample sample) {
         _sampleService.CreateSample(sample);
    }

Sample POCO looks like this

  public class Sample : BaseEntity
{
    public string BarCode { get; set; }
    public DateTime CreatedAt { get; set; }
    public virtual User CreatedBy { get; set; }
    public virtual Status Status { get; set; }
}

on the client side sample object is only sending 2 properties for now and looks like this.

{barcode:"1234"createdAt:"2017-06-07"}

and the http post looks like this

createSample(sample: Sample) {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.post(AppConstants.createSample, JSON.stringify(sample), { headers: headers })
  .map((res: Response) => res.json());  }

so if i user headers i get  No 'Access-Control-Allow-Origin' header is present

if i not use headers i get (Unsupported Media Type)

any idea whats going on here.
UPDATE
so I followed instructions as in first answer and looks like CORS is not set property but now JSON is not being converted to C# Object

Body:
You need to use headers to tell the API method what you're sending.

You need to enable CORS in your .Net Core app Startup.cs so that your API allows requests coming from another origin (accepts calls from your client app url, basically) - and set CORS to AllowAnyMethod()

You do this with the following code in your ConfigureServices() method:

var corsUrls = new List<string>(){"http://localhost:4200", "https://mylivesite.com"};

services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
{
    builder
      .AllowAnyMethod() //<--this allows preflight headers required for POST
      .AllowAnyHeader() //<--accepts headers
      .AllowCredentials() //<--lets your app send auth credentials
      .WithOrigins(corsUrls.ToArray()); //<--this is the important line
}));

services.Configure<MvcOptions>(
    options => { options.Filters.Add(new CorsAuthorizationFilterFactory("CorsPolicy")); });

and then finally in your Configure() method:

app.UseCors("CorsPolicy");

Note that the policy name "CorsPolicy" that I've used is just an example, you can call it whatever you like.


问:
Copying a varchar(max) field in a DTS Package
i am using DTS to export data to text file. but some fields are of type varchar(max) and the max size i can specify is varchar(8000). Hence text is getting truncated how can i avoid this.</p>

答:
I would try and convert it to a Text column.  A text column can hold up to 2147483647 bytes of binary data.

Thanks, Andrew


问:
python used sshtunnel can't connect to mysql
I'm trying to use sshtunnel and MySQLdb in python2.7 to tunnel my connection and facing following problem:

I used Sequel Pro to connect mysql was OK, but the python code did not work!

Sequel Pro is like this:

connect info

and code is like this:

```<code>`from sshtunnel import SSHTunnelForwarder
import MySQLdb
with SSHTunnelForwarder(
        ('2.2.2.2', 22),
        ssh_username='name2',
        ssh_password='mypassword',
        remote_bind_address=('127.0.0.1', 3306)
) as tunnel:
    connection = MySQLdb.connect(
    user='name1',
    password='mypassword',
    host='1.1.1.1',
    database='mydata',
    port=3306)
</code>```

I searched some example code like:

```<code>from sshtunnel import SSHTunnelForwarder
import MySQLdb

with SSHTunnelForwarder(
        (_host, _ssh_port),
        ssh_username=_username,
        ssh_password=_password,
        remote_bind_address=(_remote_bind_address, _remote_mysql_port),
        local_bind_address=(_local_bind_address, _local_mysql_port)
) as tunnel:
    connection = MySQLdb.connect(
    user=_db_user,
    password=_db_password,
    host=_local_bind_address,
    database=_db_name,
    port=_local_mysql_port)
</code>```

I want to know that did I do the right way to built ssh or connect to mysql? Thanks for help!

update:
the error message:

```<code>2017-06-15 17:52:58,415| ERROR   | Could not connect to gateway 1.1.1.1:22 : 110
Traceback (most recent call last):
  File "<stdin>", line 6, in <module>
  File "build/bdist.linux-x86_64/egg/sshtunnel.py", line 1483, in __enter__
  File "build/bdist.linux-x86_64/egg/sshtunnel.py", line 1225, in start
  File "build/bdist.linux-x86_64/egg/sshtunnel.py", line 1037, in _raise
sshtunnel.BaseSSHTunnelForwarderError: Could not establish session to SSH gateway
</code>```

答:
Update your code to add the local_bind_address:

```<code>from sshtunnel import SSHTunnelForwarder
import MySQLdb
with SSHTunnelForwarder(
        ('2.2.2.2', 22),
        ssh_username='name2',
        ssh_password='mypassword',
        remote_bind_address=('127.0.0.1', 3306),
        local_bind_address = ('1.1.1.1', 3306)
) as tunnel:
    connection = MySQLdb.connect(
    user='name1',
    password='mypassword',
    host='1.1.1.1',
    database='mydata',
    port=3306)
</code>```

Unless you specify your Localhost (as '1.1.1.1' in your case) & Port; MYSQL service will not be available for the localhost.
I Hope this helps.

Body:
I'm trying to use sshtunnel and MySQLdb in python2.7 to tunnel my connection and facing following problem:

I used Sequel Pro to connect mysql was OK, but the python code did not work!

Sequel Pro is like this:

connect info

and code is like this:

`from sshtunnel import SSHTunnelForwarder
import MySQLdb
with SSHTunnelForwarder(
        ('2.2.2.2', 22),
        ssh_username='name2',
        ssh_password='mypassword',
        remote_bind_address=('127.0.0.1', 3306)
) as tunnel:
    connection = MySQLdb.connect(
    user='name1',
    password='mypassword',
    host='1.1.1.1',
    database='mydata',
    port=3306)

I searched some example code like:

from sshtunnel import SSHTunnelForwarder
import MySQLdb

with SSHTunnelForwarder(
        (_host, _ssh_port),
        ssh_username=_username,
        ssh_password=_password,
        remote_bind_address=(_remote_bind_address, _remote_mysql_port),
        local_bind_address=(_local_bind_address, _local_mysql_port)
) as tunnel:
    connection = MySQLdb.connect(
    user=_db_user,
    password=_db_password,
    host=_local_bind_address,
    database=_db_name,
    port=_local_mysql_port)

I want to know that did I do the right way to built ssh or connect to mysql? Thanks for help!

update:
the error message:

2017-06-15 17:52:58,415| ERROR   | Could not connect to gateway 1.1.1.1:22 : 110
Traceback (most recent call last):
  File "<stdin>", line 6, in <module>
  File "build/bdist.linux-x86_64/egg/sshtunnel.py", line 1483, in __enter__
  File "build/bdist.linux-x86_64/egg/sshtunnel.py", line 1225, in start
  File "build/bdist.linux-x86_64/egg/sshtunnel.py", line 1037, in _raise
sshtunnel.BaseSSHTunnelForwarderError: Could not establish session to SSH gateway

Body:
Update your code to add the local_bind_address:

from sshtunnel import SSHTunnelForwarder
import MySQLdb
with SSHTunnelForwarder(
        ('2.2.2.2', 22),
        ssh_username='name2',
        ssh_password='mypassword',
        remote_bind_address=('127.0.0.1', 3306),
        local_bind_address = ('1.1.1.1', 3306)
) as tunnel:
    connection = MySQLdb.connect(
    user='name1',
    password='mypassword',
    host='1.1.1.1',
    database='mydata',
    port=3306)

Unless you specify your Localhost (as '1.1.1.1' in your case) & Port; MYSQL service will not be available for the localhost.
I Hope this helps.


问:
What's wrong with my dfs implementation?
I have implemented a dfs search for an 8 puzzle game but for some reason I can't manage to get it work as it should, my stack keeps adding and adding possible movements for my 8 puzzle game but it never decreases for an answer, I don't know if it is normal or not but here is my code in case someone can help me.

The code is not fully optimized I know, I just want to know why it is not working as a dfs should be, thank you.

```<code>function depthFirstSearch(currentState, finalState)
{
  var stack = [];
  var visited = [];
  delete currentState["prev"];
  stack.push(currentState);
  while(stack.length)
  {
    var node = stack.pop();
    visited.push(node);
    if(compare(node, finalState))
    {
      return visited;
    }
    else
    {
      var successors = getSuccessors(node);
      for(var i = 0; i < successors.length; i++)
      {
        delete successors[i]["prev"];
      }
      var realSuccessors = [];
      for(var i = 0; i < visited.length; i++)
      {
        for(var j = 0; j < successors.length; j++)
        {
          if(compare(successors[j], visited[i]))
          {
            continue;
          }
          else
          {
            realSuccessors.push(successors[j]);
          }
        }
      }
      for(var i = 0; i < realSuccessors.length; i++)
      {
        stack.push(realSuccessors[i]);
      }
      console.log(stack.length);
    }
  }
}
</code>```

答: I'm going to answer myself since I realized that the number of combinations considering that im traversing my graph in depth could lead me to an infinite or long number of combinations and never reach the solution since I'm going just in one direction, therefore I thought about doing an iterative DFS which traverses each children by levels. </p>

Body:
I have implemented a dfs search for an 8 puzzle game but for some reason I can't manage to get it work as it should, my stack keeps adding and adding possible movements for my 8 puzzle game but it never decreases for an answer, I don't know if it is normal or not but here is my code in case someone can help me.

The code is not fully optimized I know, I just want to know why it is not working as a dfs should be, thank you.

function depthFirstSearch(currentState, finalState)
{
  var stack = [];
  var visited = [];
  delete currentState["prev"];
  stack.push(currentState);
  while(stack.length)
  {
    var node = stack.pop();
    visited.push(node);
    if(compare(node, finalState))
    {
      return visited;
    }
    else
    {
      var successors = getSuccessors(node);
      for(var i = 0; i < successors.length; i++)
      {
        delete successors[i]["prev"];
      }
      var realSuccessors = [];
      for(var i = 0; i < visited.length; i++)
      {
        for(var j = 0; j < successors.length; j++)
        {
          if(compare(successors[j], visited[i]))
          {
            continue;
          }
          else
          {
            realSuccessors.push(successors[j]);
          }
        }
      }
      for(var i = 0; i < realSuccessors.length; i++)
      {
        stack.push(realSuccessors[i]);
      }
      console.log(stack.length);
    }
  }
}


问:
SSL/TLS with Websockets Server - go lang
I am using collider (https://github.com/webrtc/apprtc/tree/master/src/collider -a websockets server in go) and I am trying to add SSL/TLS support. For which I generated self-signed certificates:

```<code>openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365

Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:
Country Name (2 letter code) [AU]:US
State or Province Name (full name) [Some-State]:CA
Locality Name (eg, city) []:
Organization Name (eg, company) [Internet Widgits Pty Ltd]:testwebsite.com
Organizational Unit Name (eg, section) []:Engineering
Common Name (e.g. server FQDN or YOUR name) []:www.testwebsite.com
Email Address []:testwebsite@gmail.com
</code>```

When I run the collider, I see this error:

```<code>2017/06/05 21:25:50 Error Run: crypto/tls: failed to parse private key
</code>```

When I generate using (based on http://www.kaihag.com/https-and-go/):

```<code>openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout key.pem -out cert.pem
</code>```

I get this error:

```<code>2017/06/05 22:11:31 http: TLS handshake error from <some-ip>:1082: remote error: unknown certificate
</code>```

How to fix this?

Note: collider uses golang.org/x/net/websocket

答:
I ended up obtaining the certs from: https://certbot.eff.org/#ubuntuxenial-other

```<code>certbot certonly --standalone -d example.com -d www.example.com
</code>```

I had to use fullchain.pem instead of cert.pem for this collider to work:

https://github.com/webrtc/apprtc/issues/442

Body:
I am using collider (https://github.com/webrtc/apprtc/tree/master/src/collider -a websockets server in go) and I am trying to add SSL/TLS support. For which I generated self-signed certificates:

openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365

Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:
Country Name (2 letter code) [AU]:US
State or Province Name (full name) [Some-State]:CA
Locality Name (eg, city) []:
Organization Name (eg, company) [Internet Widgits Pty Ltd]:testwebsite.com
Organizational Unit Name (eg, section) []:Engineering
Common Name (e.g. server FQDN or YOUR name) []:www.testwebsite.com
Email Address []:testwebsite@gmail.com

When I run the collider, I see this error:

2017/06/05 21:25:50 Error Run: crypto/tls: failed to parse private key

When I generate using (based on http://www.kaihag.com/https-and-go/):

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout key.pem -out cert.pem

I get this error:

2017/06/05 22:11:31 http: TLS handshake error from <some-ip>:1082: remote error: unknown certificate

How to fix this?

Note: collider uses golang.org/x/net/websocket

Body:
I ended up obtaining the certs from: https://certbot.eff.org/#ubuntuxenial-other

certbot certonly --standalone -d example.com -d www.example.com

I had to use fullchain.pem instead of cert.pem for this collider to work:

https://github.com/webrtc/apprtc/issues/442


问:
How to pass authorization parameters?
I try to use framework that was created by swagger-codegen but I don't understand how to pass authorization token to my API methods.

E.g. we can use sample Petstore: https://github.com/swagger-api/swagger-codegen/blob/master/samples/client/petstore/android/httpclient/docs/UserApi.md#updateUser

How can I add authorisation token to my request header (that token I will receive from my previous request to AuthorizationAPI)?

Maybe I don't understand authorisation flow for swagger-codegen for Android.

```<code>UserApi apiInstance = new UserApi();
User body = new User(); // User | Created user object
try {
    apiInstance.createUser(body); // here I will receive error unauhorized
} catch (ApiException e) {
    System.err.println("Exception when calling UserApi#createUser");
    e.printStackTrace();
}
</code>```

答:
By briefly looking at the code it looks like you can pass arbitrary http headers by invoking addHeaderon UserApi https://github.com/swagger-api/swagger-codegen/blob/master/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/UserApi.java#L36

Also it looks like swagger-codegen cli has support for generating the authorization headers

```<code>    -a <authorization>, --auth <authorization>
        adds authorization headers when fetching the swagger definitions
        remotely. Pass in a URL-encoded string of name:header with a comma
        separating multiple values
</code>```

Title: How to pass authorization parameters?

Body:
I try to use framework that was created by swagger-codegen but I don't understand how to pass authorization token to my API methods.

E.g. we can use sample Petstore: https://github.com/swagger-api/swagger-codegen/blob/master/samples/client/petstore/android/httpclient/docs/UserApi.md#updateUser

How can I add authorisation token to my request header (that token I will receive from my previous request to AuthorizationAPI)?

Maybe I don't understand authorisation flow for swagger-codegen for Android.

UserApi apiInstance = new UserApi();
User body = new User(); // User | Created user object
try {
    apiInstance.createUser(body); // here I will receive error unauhorized
} catch (ApiException e) {
    System.err.println("Exception when calling UserApi#createUser");
    e.printStackTrace();
}

Body:
By briefly looking at the code it looks like you can pass arbitrary http headers by invoking addHeaderon UserApi https://github.com/swagger-api/swagger-codegen/blob/master/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/UserApi.java#L36

Also it looks like swagger-codegen cli has support for generating the authorization headers

    -a <authorization>, --auth <authorization>
        adds authorization headers when fetching the swagger definitions
        remotely. Pass in a URL-encoded string of name:header with a comma
        separating multiple values


问:
Enable only four line in text Input in Kivy
I am new in Kivy programming.
I want to enable only 4 lines in text Input in Kivy.
I can use either only one line either multi lines, but I want a text field which has enabled only 4 lines.
In short I want a text field where i can enter anything till to four rows </p>

答:
You could set a counter for the line breaks and/or characters and block any new line break/character.

Kivy TextInput documentation

You can use the row value. This could be managed by the filtering function of TextInput.

Edit:

A little example class:

```<code>class TInput(TextInput):

    def __init__(self,**kwargs):
        super(TInput,self).__init__(**kwargs)
        self.__lineBreak__=0

    def insert_text(self, substring, from_undo=False):
        if "\n" in substring and self.__lineBreak__ <= 4:
            self.__lineBreak__ += 1
            self.__s__ = substring
        elif self.__lineBreak__ > 4 and "\n" in substring:
            self.__s__ = ""
        return super(TInput, self).insert_text(s, from_undo=from_undo)
</code>```

I think that should do the job

Body:
You could set a counter for the line breaks and/or characters and block any new line break/character.

Kivy TextInput documentation

You can use the row value. This could be managed by the filtering function of TextInput.

Edit:

A little example class:

class TInput(TextInput):

    def __init__(self,**kwargs):
        super(TInput,self).__init__(**kwargs)
        self.__lineBreak__=0

    def insert_text(self, substring, from_undo=False):
        if "\n" in substring and self.__lineBreak__ <= 4:
            self.__lineBreak__ += 1
            self.__s__ = substring
        elif self.__lineBreak__ > 4 and "\n" in substring:
            self.__s__ = ""
        return super(TInput, self).insert_text(s, from_undo=from_undo)

I think that should do the job