问:
How to fix this?
How do I fix this? I know that the error is in line 8 (g = f/5) but how do i fix the error?   </p>

```<code>a = input("Enter a number: ")
b = input("Enter a second number: ")
c = input("Enter a third number: ")
d = input("Enter a fourth number: ")
e = input("Enter a fifth number: ")

f = a+b+c+d+e
g = f/5

print  ("The average of these numbers is "+str(g))
</code>```

答:
```<code>a = int(input("Enter a number: ")) #if you want user to allow non-integer number tan use float instead of int
b = int(input("Enter a second number: "))
c = int(input("Enter a third number: "))
d = int(input("Enter a fourth number: "))
e = int(input("Enter a fifth number: "))

f = a+b+c+d+e
g = f/5

print  ("The average of these numbers is "+str(g))
</code>```

In python by default input is taken as string and when you add two string 56and 4 it will just give you another string 564 which is concatenate but you can not divide string hence you got error on that line.

Title: How to fix this?

Body:
How do I fix this? I know that the error is in line 8 (g = f/5) but how do i fix the error?

a = input("Enter a number: ")
b = input("Enter a second number: ")
c = input("Enter a third number: ")
d = input("Enter a fourth number: ")
e = input("Enter a fifth number: ")

f = a+b+c+d+e
g = f/5

print  ("The average of these numbers is "+str(g))

Body:
a = int(input("Enter a number: ")) #if you want user to allow non-integer number tan use float instead of int
b = int(input("Enter a second number: "))
c = int(input("Enter a third number: "))
d = int(input("Enter a fourth number: "))
e = int(input("Enter a fifth number: "))

f = a+b+c+d+e
g = f/5

print  ("The average of these numbers is "+str(g))

In python by default input is taken as string and when you add two string 56and 4 it will just give you another string 564 which is concatenate but you can not divide string hence you got error on that line.


来源: stackexchange

问:
How to debug cgi program written in C and running in Apache2?
I have a complex cgi executable written in C, I configured in Apache2 and now it is running succesfully. How can I debug this program in the source code, such as set break points and inspect variables? Any tools like gdb or eclipse? Any tutorial of how to set up the debugging environment?

Thanks in advance!!

答:
Unless FastCGI or SCGI is used, the CGI process is short-lived and you need to delay its exit to have enough time to attach the debugger while the process is still running. For casual debugging the easiest option is to simply use sleep() in an endless loop at the breakpoint location and exit the loop with the debugger once it is attached to the program.

Here's a small example CGI program:

```<code>#include <stdio.h>
#include <unistd.h>

void wait_for_gdb_to_attach() {
  int is_waiting = 1;
  while (is_waiting) {
    sleep(1); // sleep for 1 second
  }
}

int main(void) {
  wait_for_gdb_to_attach();
  printf("Content-Type: text/plain;charset=us-ascii\n\n");
  printf("Hello!");
  return 0;
}
</code>```

Suppose it is compiled into cgi-debugging-example, this is how you would attach the debugger once the application enters the endless loop:

```<code>sudo cgdb cgi-debugging-example $(pgrep cgi-debugging)
</code>```

Next you need to exit the infinite loop and wait_for_gdb_to_attach() function to reach the "breakpoint" in your application. The trick here is to step out of sleep functions until you reach wait_for_gdb_to_attach() and set the value of the variable is_waiting with the debugger so that while (is_waiting) exits:

```<code>(gdb) finish
Run till exit from 0x8a0920 __nanosleep_nocancel () at syscall-template.S:81
0x8a07d4 in __sleep (seconds=0) at sleep.c:137
(gdb) finish
Run till exit from 0x8a07d4 in __sleep (seconds=0) at sleep.c:137
wait_for_gdb_to_attach () at cgi-debugging-example.c:6
Value returned is $1 = 0
(gdb) set is_waiting = 0 # <<<<<< to exit while
(gdb) finish
Run till exit from wait_for_gdb_to_attach () cgi-debugging-example.c:6
main () at cgi-debugging-example.c:13
</code>```

Once you are out of wait_for_gdb_to_attach(), you can continue debugging the program or let it run to completion.

Full example with detailed instructions here.

ContentLicense: CC BY-SA 3.0

Body:
Unless FastCGI or SCGI is used, the CGI process is short-lived and you need to delay its exit to have enough time to attach the debugger while the process is still running. For casual debugging the easiest option is to simply use sleep() in an endless loop at the breakpoint location and exit the loop with the debugger once it is attached to the program.

Here's a small example CGI program:

#include <stdio.h>
#include <unistd.h>

void wait_for_gdb_to_attach() {
  int is_waiting = 1;
  while (is_waiting) {
    sleep(1); // sleep for 1 second
  }
}

int main(void) {
  wait_for_gdb_to_attach();
  printf("Content-Type: text/plain;charset=us-ascii\n\n");
  printf("Hello!");
  return 0;
}

Suppose it is compiled into cgi-debugging-example, this is how you would attach the debugger once the application enters the endless loop:

sudo cgdb cgi-debugging-example $(pgrep cgi-debugging)

Next you need to exit the infinite loop and wait_for_gdb_to_attach() function to reach the "breakpoint" in your application. The trick here is to step out of sleep functions until you reach wait_for_gdb_to_attach() and set the value of the variable is_waiting with the debugger so that while (is_waiting) exits:

(gdb) finish
Run till exit from 0x8a0920 __nanosleep_nocancel () at syscall-template.S:81
0x8a07d4 in __sleep (seconds=0) at sleep.c:137
(gdb) finish
Run till exit from 0x8a07d4 in __sleep (seconds=0) at sleep.c:137
wait_for_gdb_to_attach () at cgi-debugging-example.c:6
Value returned is $1 = 0
(gdb) set is_waiting = 0 # <<<<<< to exit while
(gdb) finish
Run till exit from wait_for_gdb_to_attach () cgi-debugging-example.c:6
main () at cgi-debugging-example.c:13

Once you are out of wait_for_gdb_to_attach(), you can continue debugging the program or let it run to completion.

Full example with detailed instructions here.


问:
With URI gem in Ruby, how do I actually parse this cookie that has paths, etc?
When I get some cookies back from the server, I'm needing to only pass the key=value parameters in the next request. I don't need the path information, expiration, etc. However, when I inspect the hash, I get all of that back and find no real way to only parse and keep the important information.

For example, here's the cookie returned from my HTTP POST request:

```<code>[1] pry(main)> headers['Cookie']
=> "ds_user=testuser; expires=Fri, 01-Sep-2017 22:20:55 GMT; Max-Age=7776000; Path=/, rur=ATN; Path=/, csrftoken=V6pcoCJdHJLb7BGu2BV8TwE5ZoA5fm; expires=Sat, 02-Jun-2018 22:20:55 GMT; Max-Age=31449600; Path=/; Secure, mid=WTM2RwABAAHw09zRkX55hIbjqszz; expires=Fri, 29-May-2037 22:20:55 GMT; Max-Age=630720000; Path=/, uid=554580241; expires=Fri, 01-Sep-2017 22:20:55 GMT; Max-Age=7776000; Path=/, sessionid=4be2b3d03caf0f3073ce8f1215a2d723a23981a52b0c%3AZ0Y0P0yRXSvpy2gBwZguWo4zoOpGajRA%3A%7B%22_auth_user_id%22%3A5545802841%2C%22_auth_user_backend%22%3A%22accounts.backends.CaseInsensitiveModelBackend%22%2C%22_auth_user_hash%22%3A%22%22%2C%22_token_ver%22%3A2%2C%22_token%22%3A%225545802841%3Ai2MlZYtSByn9IVBMuL8AHkCq0fX4HI7N%3A480fd4a05bfcdd081c70d0c4c4391883064a35cdd43402506937e611590d92a2%22%2C%22_platform%22%3A1%2C%22last_refreshed%22%3A1496528455.4560296535%7D; expires=Fri, 01-Sep-2017 22:20:55 GMT; HttpOnly; Max-Age=7776000; Path=/; Secure"
</code>```

I can't do something like headers['Cookie'].split("; ") because the semicolon (;) appears at random parts of the cookie returned in the header.

So for example, when I submit the next request using the cookies returned from that request, it needs to look something like:

```<code>Cookie: csrftoken=hgsdco49G6E1EOyR48ofKhtG0P; ds_user=testuser; uid=55458041; mid=WTIRigABAAFjQJOKtJ3jaWGbi70P; rur=ATN; sessionid=a9c568a15f567fb8bf9752a3%3AIMAaCgikVRROWcqGu6aoBhJTx5VGutKh%3A%7B%22_auth_user_id%22%3A5545802841%2C%22_auth_user_backend%22%3A%22accounts.backends.CaseInsensitiveModelBackend%22%2C%22_auth_user_hash%22%3A%22%22%2C%22_token_ver%22%3A2%2C%22_token%22%3A%225545802841%3AyvzFW559ItJDPMOY9CyBja4NfW049qxy%3A4c5e7c48a20d3c8a1cbc4d0f9a0631449ff24c9b1dbc35a0f80f50568d0a3365%22%2C%22_platform%22%3A1%2C%22last_refreshed%22%3A1496453514.4971137047%7D
</code>```

Any idea what the easiest way to achieve this would be?

答:
Considerer that the cookie is separed by ";" and under the Path is separated by commas you can proceed working as follow:

```<code>pry(main)> cookie = headers['Cookie']
=> "ds_user=testuser; expires=Fri, 01-Sep-2017 22:20:55 GMT; Max-Age=7776000; Path=/, rur=ATN; Path=/, csrftoken=V6pcoCJdHJLb7BGu2BV8TwE5ZoA5fm; expires=Sat, 02-Jun-2018 22:20:55 GMT; Max-Age=31449600; Path=/; Secure, mid=WTM2RwABAAHw09zRkX55hIbjqszz; expires=Fri, 29-May-2037 22:20:55 GMT; Max-Age=630720000; Path=/, uid=554580241; expires=Fri, 01-Sep-2017 22:20:55 GMT; Max-Age=7776000; Path=/, sessionid=4be2b3d03caf0f3073ce8f1215a2d723a23981a52b0c%3AZ0Y0P0yRXSvpy2gBwZguWo4zoOpGajRA%3A%7B%22_auth_user_id%22%3A5545802841%2C%22_auth_user_backend%22%3A%22accounts.backends.CaseInsensitiveModelBackend%22%2C%22_auth_user_hash%22%3A%22%22%2C%22_token_ver%22%3A2%2C%22_token%22%3A%225545802841%3Ai2MlZYtSByn9IVBMuL8AHkCq0fX4HI7N%3A480fd4a05bfcdd081c70d0c4c4391883064a35cdd43402506937e611590d92a2%22%2C%22_platform%22%3A1%2C%22last_refreshed%22%3A1496528455.4560296535%7D; expires=Fri, 01-Sep-2017 22:20:55 GMT; HttpOnly; Max-Age=7776000; Path=/; Secure"

pry(main)> cookie.split(";").each do |f|
        f =~ /^(.*?)=(.*?)$/
      if $1 == " Path" then
        puts "There is a #{$1} that contains #{$2}"
      else
       puts "#{$1} = #{$2}"
      end
    end

pry(main)* ds_user = testuser
 expires = Fri, 01-Sep-2017 22:20:55 GMT
 Max-Age = 7776000
There is a  Path that contains /, rur=ATN
There is a  Path that contains /, csrftoken=V6pcoCJdHJLb7BGu2BV8TwE5ZoA5fm
 expires = Sat, 02-Jun-2018 22:20:55 GMT
 Max-Age = 31449600
There is a  Path that contains /
 Secure, mid = WTM2RwABAAHw09zRkX55hIbjqszz
 expires = Fri, 29-May-2037 22:20:55 GMT
 Max-Age = 630720000
There is a  Path that contains /, uid=554580241
 expires = Fri, 01-Sep-2017 22:20:55 GMT
 Max-Age = 7776000
There is a  Path that contains /, sessionid=4be2b3d03caf0f3073ce8f1215a2d723a23981a52b0c%3AZ0Y0P0yRXSvpy2gBwZguWo4zoOpGajRA%3A%7B%22_auth_user_id%22%3A5545802841%2C%22_auth_user_backend%22%3A%22accounts.backends.CaseInsensitiveModelBackend%22%2C%22_auth_user_hash%22%3A%22%22%2C%22_token_ver%22%3A2%2C%22_token%22%3A%225545802841%3Ai2MlZYtSByn9IVBMuL8AHkCq0fX4HI7N%3A480fd4a05bfcdd081c70d0c4c4391883064a35cdd43402506937e611590d92a2%22%2C%22_platform%22%3A1%2C%22last_refreshed%22%3A1496528455.4560296535%7D
 expires = Fri, 01-Sep-2017 22:20:55 GMT
 =
 Max-Age = 7776000
There is a  Path that contains /
 =

=> ["ds_user=testuser",
 " expires=Fri, 01-Sep-2017 22:20:55 GMT",
 " Max-Age=7776000",
 " Path=/, rur=ATN",
 " Path=/, csrftoken=V6pcoCJdHJLb7BGu2BV8TwE5ZoA5fm",
 " expires=Sat, 02-Jun-2018 22:20:55 GMT",
 " Max-Age=31449600",
 " Path=/",
 " Secure, mid=WTM2RwABAAHw09zRkX55hIbjqszz",
 " expires=Fri, 29-May-2037 22:20:55 GMT",
 " Max-Age=630720000",
 " Path=/, uid=554580241",
 " expires=Fri, 01-Sep-2017 22:20:55 GMT",
 " Max-Age=7776000",
 " Path=/, sessionid=4be2b3d03caf0f3073ce8f1215a2d723a23981a52b0c%3AZ0Y0P0yRXSvpy2gBwZguWo4zoOpGajRA%3A%7B%22_auth_user_id%22%3A5545802841%2C%22_auth_user_backend%22%3A%22accounts.backends.CaseInsensitiveModelBackend%22%2C%22_auth_user_hash%22%3A%22%22%2C%22_token_ver%22%3A2%2C%22_token%22%3A%225545802841%3Ai2MlZYtSByn9IVBMuL8AHkCq0fX4HI7N%3A480fd4a05bfcdd081c70d0c4c4391883064a35cdd43402506937e611590d92a2%22%2C%22_platform%22%3A1%2C%22last_refreshed%22%3A1496528455.4560296535%7D",
 " expires=Fri, 01-Sep-2017 22:20:55 GMT",
 " HttpOnly",
 " Max-Age=7776000",
 " Path=/",
 " Secure"]
</code>```

Be careful with the space after ; and proceed with whath you wnat inside the path

Body:
When I get some cookies back from the server, I'm needing to only pass the key=value parameters in the next request. I don't need the path information, expiration, etc. However, when I inspect the hash, I get all of that back and find no real way to only parse and keep the important information.

For example, here's the cookie returned from my HTTP POST request:

[1] pry(main)> headers['Cookie']
=> "ds_user=testuser; expires=Fri, 01-Sep-2017 22:20:55 GMT; Max-Age=7776000; Path=/, rur=ATN; Path=/, csrftoken=V6pcoCJdHJLb7BGu2BV8TwE5ZoA5fm; expires=Sat, 02-Jun-2018 22:20:55 GMT; Max-Age=31449600; Path=/; Secure, mid=WTM2RwABAAHw09zRkX55hIbjqszz; expires=Fri, 29-May-2037 22:20:55 GMT; Max-Age=630720000; Path=/, uid=554580241; expires=Fri, 01-Sep-2017 22:20:55 GMT; Max-Age=7776000; Path=/, sessionid=4be2b3d03caf0f3073ce8f1215a2d723a23981a52b0c%3AZ0Y0P0yRXSvpy2gBwZguWo4zoOpGajRA%3A%7B%22_auth_user_id%22%3A5545802841%2C%22_auth_user_backend%22%3A%22accounts.backends.CaseInsensitiveModelBackend%22%2C%22_auth_user_hash%22%3A%22%22%2C%22_token_ver%22%3A2%2C%22_token%22%3A%225545802841%3Ai2MlZYtSByn9IVBMuL8AHkCq0fX4HI7N%3A480fd4a05bfcdd081c70d0c4c4391883064a35cdd43402506937e611590d92a2%22%2C%22_platform%22%3A1%2C%22last_refreshed%22%3A1496528455.4560296535%7D; expires=Fri, 01-Sep-2017 22:20:55 GMT; HttpOnly; Max-Age=7776000; Path=/; Secure"

I can't do something like headers['Cookie'].split("; ") because the semicolon (;) appears at random parts of the cookie returned in the header.

So for example, when I submit the next request using the cookies returned from that request, it needs to look something like:

Cookie: csrftoken=hgsdco49G6E1EOyR48ofKhtG0P; ds_user=testuser; uid=55458041; mid=WTIRigABAAFjQJOKtJ3jaWGbi70P; rur=ATN; sessionid=a9c568a15f567fb8bf9752a3%3AIMAaCgikVRROWcqGu6aoBhJTx5VGutKh%3A%7B%22_auth_user_id%22%3A5545802841%2C%22_auth_user_backend%22%3A%22accounts.backends.CaseInsensitiveModelBackend%22%2C%22_auth_user_hash%22%3A%22%22%2C%22_token_ver%22%3A2%2C%22_token%22%3A%225545802841%3AyvzFW559ItJDPMOY9CyBja4NfW049qxy%3A4c5e7c48a20d3c8a1cbc4d0f9a0631449ff24c9b1dbc35a0f80f50568d0a3365%22%2C%22_platform%22%3A1%2C%22last_refreshed%22%3A1496453514.4971137047%7D

Any idea what the easiest way to achieve this would be?

Body:
Considerer that the cookie is separed by ";" and under the Path is separated by commas you can proceed working as follow:

pry(main)> cookie = headers['Cookie']
=> "ds_user=testuser; expires=Fri, 01-Sep-2017 22:20:55 GMT; Max-Age=7776000; Path=/, rur=ATN; Path=/, csrftoken=V6pcoCJdHJLb7BGu2BV8TwE5ZoA5fm; expires=Sat, 02-Jun-2018 22:20:55 GMT; Max-Age=31449600; Path=/; Secure, mid=WTM2RwABAAHw09zRkX55hIbjqszz; expires=Fri, 29-May-2037 22:20:55 GMT; Max-Age=630720000; Path=/, uid=554580241; expires=Fri, 01-Sep-2017 22:20:55 GMT; Max-Age=7776000; Path=/, sessionid=4be2b3d03caf0f3073ce8f1215a2d723a23981a52b0c%3AZ0Y0P0yRXSvpy2gBwZguWo4zoOpGajRA%3A%7B%22_auth_user_id%22%3A5545802841%2C%22_auth_user_backend%22%3A%22accounts.backends.CaseInsensitiveModelBackend%22%2C%22_auth_user_hash%22%3A%22%22%2C%22_token_ver%22%3A2%2C%22_token%22%3A%225545802841%3Ai2MlZYtSByn9IVBMuL8AHkCq0fX4HI7N%3A480fd4a05bfcdd081c70d0c4c4391883064a35cdd43402506937e611590d92a2%22%2C%22_platform%22%3A1%2C%22last_refreshed%22%3A1496528455.4560296535%7D; expires=Fri, 01-Sep-2017 22:20:55 GMT; HttpOnly; Max-Age=7776000; Path=/; Secure"

pry(main)> cookie.split(";").each do |f|
        f =~ /^(.*?)=(.*?)$/
      if $1 == " Path" then
        puts "There is a #{$1} that contains #{$2}"
      else
       puts "#{$1} = #{$2}"
      end
    end

pry(main)* ds_user = testuser
 expires = Fri, 01-Sep-2017 22:20:55 GMT
 Max-Age = 7776000
There is a  Path that contains /, rur=ATN
There is a  Path that contains /, csrftoken=V6pcoCJdHJLb7BGu2BV8TwE5ZoA5fm
 expires = Sat, 02-Jun-2018 22:20:55 GMT
 Max-Age = 31449600
There is a  Path that contains /
 Secure, mid = WTM2RwABAAHw09zRkX55hIbjqszz
 expires = Fri, 29-May-2037 22:20:55 GMT
 Max-Age = 630720000
There is a  Path that contains /, uid=554580241
 expires = Fri, 01-Sep-2017 22:20:55 GMT
 Max-Age = 7776000
There is a  Path that contains /, sessionid=4be2b3d03caf0f3073ce8f1215a2d723a23981a52b0c%3AZ0Y0P0yRXSvpy2gBwZguWo4zoOpGajRA%3A%7B%22_auth_user_id%22%3A5545802841%2C%22_auth_user_backend%22%3A%22accounts.backends.CaseInsensitiveModelBackend%22%2C%22_auth_user_hash%22%3A%22%22%2C%22_token_ver%22%3A2%2C%22_token%22%3A%225545802841%3Ai2MlZYtSByn9IVBMuL8AHkCq0fX4HI7N%3A480fd4a05bfcdd081c70d0c4c4391883064a35cdd43402506937e611590d92a2%22%2C%22_platform%22%3A1%2C%22last_refreshed%22%3A1496528455.4560296535%7D
 expires = Fri, 01-Sep-2017 22:20:55 GMT
 =
 Max-Age = 7776000
There is a  Path that contains /
 =

=> ["ds_user=testuser",
 " expires=Fri, 01-Sep-2017 22:20:55 GMT",
 " Max-Age=7776000",
 " Path=/, rur=ATN",
 " Path=/, csrftoken=V6pcoCJdHJLb7BGu2BV8TwE5ZoA5fm",
 " expires=Sat, 02-Jun-2018 22:20:55 GMT",
 " Max-Age=31449600",
 " Path=/",
 " Secure, mid=WTM2RwABAAHw09zRkX55hIbjqszz",
 " expires=Fri, 29-May-2037 22:20:55 GMT",
 " Max-Age=630720000",
 " Path=/, uid=554580241",
 " expires=Fri, 01-Sep-2017 22:20:55 GMT",
 " Max-Age=7776000",
 " Path=/, sessionid=4be2b3d03caf0f3073ce8f1215a2d723a23981a52b0c%3AZ0Y0P0yRXSvpy2gBwZguWo4zoOpGajRA%3A%7B%22_auth_user_id%22%3A5545802841%2C%22_auth_user_backend%22%3A%22accounts.backends.CaseInsensitiveModelBackend%22%2C%22_auth_user_hash%22%3A%22%22%2C%22_token_ver%22%3A2%2C%22_token%22%3A%225545802841%3Ai2MlZYtSByn9IVBMuL8AHkCq0fX4HI7N%3A480fd4a05bfcdd081c70d0c4c4391883064a35cdd43402506937e611590d92a2%22%2C%22_platform%22%3A1%2C%22last_refreshed%22%3A1496528455.4560296535%7D",
 " expires=Fri, 01-Sep-2017 22:20:55 GMT",
 " HttpOnly",
 " Max-Age=7776000",
 " Path=/",
 " Secure"]

Be careful with the space after ; and proceed with whath you wnat inside the path


问:
Using a database to store configuration rather than a configuration file
Unfortunately searching for this kind of material produces a lot of noise for me so I was wondering if anyone here knew of a good resource for anyone wishing to learn how to use a database to store site configuration info rather than a file.

I guess some points I'm interested in are:
1) How to store the data. One array like e107? Separate row for each configurable?
2) How to get the configuration data. Global array?

答:
Something like this should work for you:

```<code>CREATE TABLE `config` (
  `prop` varchar(100) DEFAULT NULL,
  `value` mediumtext,
  UNIQUE KEY `lookup` (`lookup`)
) ENGINE=InnoDB
</code>```

Put your keys into prop, and the config values into value.

ContentLicense: CC BY-SA 2.5

Body:
Something like this should work for you:

CREATE TABLE `config` (
  `prop` varchar(100) DEFAULT NULL,
  `value` mediumtext,
  UNIQUE KEY `lookup` (`lookup`)
) ENGINE=InnoDB

Put your keys into prop, and the config values into value.


问:
excel data validation select from table
How can I create a datavalidation list that lets the user pick values from a table and based on that selection show another value from the same table. For example I have this table..

```<code>PlaceName       MapCoordinate
New York        https://xxxxxxxx/axQX7SfmbB72
Washington      https://xxxxxxx/vc7bhJY3Gxr
</code>```

I want the user to select from the PlaceName column in a list, but the value that should be displayed should be the MapCoordinate value. Is this possible?

Currently I only have this formula in a list
    =INDIRECT("PlaceNameTable[PlaceName]")

Or should I use vLookup in some way instead?

答:
If you have your datavalidation(list of names) in cell B1, then you can use in cell C1 for example vlookup(B1,PlaceNameTable,2,0)
which works on my test sheet.

Title: excel data validation select from table

Body:
How can I create a datavalidation list that lets the user pick values from a table and based on that selection show another value from the same table. For example I have this table..

PlaceName       MapCoordinate
New York        https://xxxxxxxx/axQX7SfmbB72
Washington      https://xxxxxxx/vc7bhJY3Gxr

I want the user to select from the PlaceName column in a list, but the value that should be displayed should be the MapCoordinate value. Is this possible?

Currently I only have this formula in a list
    =INDIRECT("PlaceNameTable[PlaceName]")

Or should I use vLookup in some way instead?


问:
How to make particular Li tag active on click on anchor tag inside of that li tag?
I want to make my Li tag active when particular anchor tag inside li tag is clicked.

This is my Code:

```<code><ul class="list-unstyled detail-sidemenu mrb15">
    <li>
        <a onclick="Display1()" href="#"><span class="glyphicon glyphicon-link"></span> ABC</a>
    </li>
    <li>
        <a href="#" onclick="Display2()"><span class="glyphicon glyphicon-link"></span>PQR</a>
    </li>
</ul>

.detail-sidemenu li a:hover {
    background-color: #ed1b23;
    color: #ffffff;
}
</code>```

Now i want to apply this hover class css on Li tag:

```<code> function Display1()
    {
        //active ABC
    }

 function Display2()
    {
         //Active PQR and remove active from ABC
    }
</code>```

答:
To make particular
 tag active or inactive refer this answer on stackoverflow.

Answer

Body:
I want to make my Li tag active when particular anchor tag inside li tag is clicked.

This is my Code:

         ABC

        PQR

.detail-sidemenu li a:hover {
    background-color: #ed1b23;
    color: #ffffff;
}

Now i want to apply this hover class css on Li tag:

 function Display1()
    {
        //active ABC
    }

 function Display2()
    {
         //Active PQR and remove active from ABC
    }

Body:
To make particular <li> tag active or inactive refer this answer on stackoverflow.

Answer


问:
Prevent fieldset from resizing contents
I tried to resize my <fieldset> element, but it automatically made its contents smaller. Then, I added display:inline-block in my CSS file (as suggested by many answers on a similar topic). However, this doesn't help at all, everything stays the same. What should I do? I'd like a noob-friendly solution, since I'm not that good at CSS, as you may have noticed. Cheers!

fieldset {
  display: inline-block;
  border: 1px solid blue;
  background-color: white;
  width: 40%;
}

legend {
  display: inline-block;
  padding: 4px 8px;
  border: 1px solid blue;
  font-size: 15px;
  color: white;
  background-color: blue;
  text-align: left;
}

label {
  width: 100px;
  margin-right: 30px;
  display: inline-block;
  text-align: left;
}

input[type=text] {
  width: 25%;
  padding: 10px 20px;
  margin: 0px 0;
  display: inline-block;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><fieldset>
  <legend>XXX</legend>
  <label for="username">Username:</label>
  <input type="text" name="username">
</fieldset></code>```

答:
If you use percentage on the content's width, it will will change according to the width of the container(fieldset).

Just remove the percentage value.

fieldset {
  display: inline-block;
  border: 1px solid blue;
  background-color: white;

}

legend {
  display: inline-block;
  padding: 4px 8px;
  border: 1px solid blue;
  font-size: 15px;
  color: white;
  background-color: blue;
  text-align: left;
}

label {
  width: 100px;
  display: inline-block;
  text-align: left;
}

input[type=text] {

  padding: 10px 20px;
  margin: 0px 0;
  display: inline-block;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><fieldset>
  <legend>XXX</legend>
  <label for="username">Username:</label>
  <input type="text" name="username">
</fieldset></code>```

Title: Prevent fieldset from resizing contents

Body:
I tried to resize my <fieldset> element, but it automatically made its contents smaller. Then, I added display:inline-block in my CSS file (as suggested by many answers on a similar topic). However, this doesn't help at all, everything stays the same. What should I do? I'd like a noob-friendly solution, since I'm not that good at CSS, as you may have noticed. Cheers!

fieldset {
  display: inline-block;
  border: 1px solid blue;
  background-color: white;
  width: 40%;
}

legend {
  display: inline-block;
  padding: 4px 8px;
  border: 1px solid blue;
  font-size: 15px;
  color: white;
  background-color: blue;
  text-align: left;
}

label {
  width: 100px;
  margin-right: 30px;
  display: inline-block;
  text-align: left;
}

input[type=text] {
  width: 25%;
  padding: 10px 20px;
  margin: 0px 0;
  display: inline-block;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
}

<fieldset>
  <legend>XXX</legend>
  Username:
  <input type="text" name="username">
</fieldset>

Body:
If you use percentage on the content's width, it will will change according to the width of the container(fieldset).

Just remove the percentage value.

fieldset {
  display: inline-block;
  border: 1px solid blue;
  background-color: white;

}

legend {
  display: inline-block;
  padding: 4px 8px;
  border: 1px solid blue;
  font-size: 15px;
  color: white;
  background-color: blue;
  text-align: left;
}

label {
  width: 100px;
  display: inline-block;
  text-align: left;
}

input[type=text] {

  padding: 10px 20px;
  margin: 0px 0;
  display: inline-block;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
}

<fieldset>
  <legend>XXX</legend>
  <label for="username">Username:</label>
  <input type="text" name="username">
</fieldset>


问:
How "perfect" does a database have to be?
I'm designing a website to track weight lifting and calories. I've never designed my own database before and I figured I should get is as spot on as possible before I start coding. Every time I think I'm done, I get antsy that it's not perfect. I've mostly fleshed it out in MySQL Workbench but I still have a few questions.

How important is it to make the
database "perfect" before hand? How
hard is it to re-factor a database
later?

What does the engine option do? Right
now all tables are defaulting to
InnoDB engine? Any issues with this?

Are dataypes changeable after data
entry? Maybe not going from VARCHAR
to INT, but what about VARCHAR(45) to
VARCHAR(255)?

What are basic database rules that HAVE to
be followed for a successful design?

I've also attached my ERM diagram. If anyone could point out any obvious irregularities it would be greatly appreciated.

答:
I doubt that any database is perfect; don't let the perfect be the enemy of the good.

InnoDB enforces referential integrity to foreign keys.

Any ALTER can be done, but you might have to modify data in addition to tables.

Normalization rules, good indexing practices (e.g., one per WHERE clause), etc should be followed.


问:
Passing Variable From A Java Class to Another
I'm trying to pass username variable obtained from the JTextField named username from the below Class, I tried many things and I keep failing :(

The first Class:

```<code>    package com.cashdrw;
// GUI Login interface

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;

public class ldapLoginPost implements ActionListener {
    public ldapLoginPost() {
    }

    JFrame frmCashdrawerTool;
    JPanel panel;
    JButton button;
    JTextField username;
    JPasswordField password;
    JLabel usernameLbl;
    JLabel passwordLbl;
    JLabel resultLbl;
    int result;
    private JLabel label;
    private JLabel label_1;
    private JLabel label_2;
    private JLabel lblNewLabel;

    public static void main (String[] args){
          ldapLoginPost gui = new ldapLoginPost();

            gui.go();
        }
        public void go(){
            frmCashdrawerTool = new JFrame();
            frmCashdrawerTool.setTitle("Cashdrawer Tool");
            frmCashdrawerTool.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/images/photo.jpg")));
            frmCashdrawerTool.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frmCashdrawerTool.setResizable(false);

            button = new JButton("Login");
            button.setFont(new Font("Tahoma", Font.BOLD, 14));
            button.setBounds(153, 165, 92, 25);
            button.addActionListener(this);
            username = new JTextField(20);
            username.setBounds(152, 95, 151, 22);
            username.setText("");
            password = new JPasswordField(20);
            password.setBounds(152, 130, 151, 22);
            password.setText("");
            resultLbl = new JLabel(" ");
            resultLbl.setFont(new Font("Tahoma", Font.PLAIN, 14));
            resultLbl.setBounds(129, 203, 174, 22);
            usernameLbl = new JLabel("Username");
            usernameLbl.setFont(new Font("Tahoma", Font.BOLD, 14));
            usernameLbl.setBounds(65, 97, 75, 16);
            passwordLbl = new JLabel("Password");
            passwordLbl.setFont(new Font("Tahoma", Font.BOLD, 14));
            passwordLbl.setBounds(65, 132, 75, 16);
            panel = new JPanel();
            panel.setBackground(Color.WHITE);
            frmCashdrawerTool.getContentPane().add(BorderLayout.CENTER, panel);
            panel.setLayout(null);
            panel.add(usernameLbl);
            panel.add(username);
            username.requestFocusInWindow();

            label = new JLabel("");
            label.setBounds(353, 16, 0, 0);
            panel.add(label);
            panel.add(passwordLbl);
            panel.add(password);

            label_1 = new JLabel("");
            label_1.setBounds(349, 43, 0, 0);
            panel.add(label_1);

            label_2 = new JLabel("");
            label_2.setBounds(354, 43, 0, 0);
            panel.add(label_2);
            panel.add(button);
            panel.add(resultLbl);

            lblNewLabel = new JLabel("");
            lblNewLabel.setIcon(new ImageIcon(getClass().getResource("/images/rsz_vf.jpg")));
            lblNewLabel.setBounds(0, 0, 391, 73);
            panel.add(lblNewLabel);
            frmCashdrawerTool.setSize(397,273);
            frmCashdrawerTool.setVisible(true);
        }

         public void actionPerformed(ActionEvent event) {
                char[] passwordVar = password.getPassword();
                String passString = new String (passwordVar);
                String currentUser = (username.getText());
            if (currentUser.isEmpty() || passString.isEmpty()) {
               result = 2;
            }else if (currentUser.equalsIgnoreCase("xxx")){
                String[] inputLine;
                inputLine = new String[2];
                inputLine[0] = currentUser;
                inputLine[1] = passString;
                ldapConnPost connect = new ldapConnPost();
                result = connect.setUpConnection(inputLine);
            }else {
                result = 3;
            }

             if (result ==1) {
                username.setText("");
                password.setText("");
                resultLbl.setForeground(Color.GREEN);
                resultLbl.setText("Authenticated Successfully");
                frmCashdrawerTool.setVisible(false);
                frmCashdrawerTool.dispose();
                String[] inputLine;
                inputLine = new String[1];
                inputLine[0] = "INFO  --- " + currentUser + "  Was Granted Access!";
                logger obj= new logger();
                obj.writer(inputLine);
                cashDrw gui = new cashDrw();
                gui.go();
             }
             if (result == 2){
                 JOptionPane.showMessageDialog(null, "Please Enter Your Data!","ERROR",JOptionPane.ERROR_MESSAGE);
                 System.out.println("Connection Class not called");
             }
             if (result == 3){
                 username.setText("");
                 password.setText("");
                 JOptionPane.showMessageDialog(null, "You Are not allowed to use this tool!","ERROR",JOptionPane.ERROR_MESSAGE);
                 System.out.println("Connection Class not called");
                 String[] inputLine;
                 inputLine = new String[1];
                 inputLine[0] = "ERROR --- " + currentUser + "  Was Denied Access!";
                 logger obj= new logger();
                 obj.writer(inputLine);
             }

             if (result == 0) {
                 JOptionPane.showMessageDialog(null, "Authentication Failed!","ERROR",JOptionPane.ERROR_MESSAGE);
                 password.setText("");
                 String[] inputLine;
                 inputLine = new String[1];
                 inputLine[0] = "ERROR --- " + currentUser + "  LDAP Authentication Failed!";
                 logger obj= new logger();
                 obj.writer(inputLine);
         }
        }
}
</code>```

To the below Class, so that I can use it there:

```<code>package com.cashdrw;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class cashDrw extends JFrame implements ActionListener {
    public cashDrw() {
    }

    JFrame frmCashdrawerTool;
    JPanel panel;
    JButton btnUpdate;
    JTextField userid;
    JTextField storeid;
    JLabel useridLbl;
    JLabel storeidLbl;
    JLabel resultLbl;
    int cashdrwresult;
    private JLabel label;
    private JLabel label_1;
    private JLabel label_2;
    private JLabel lblNewLabel;

    public static void main (String[] args) {

       }
        public void go() {
            frmCashdrawerTool = new JFrame();
            frmCashdrawerTool.setTitle("Cashdrawer Tool");
            frmCashdrawerTool.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/images/photo.jpg")));
            frmCashdrawerTool.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frmCashdrawerTool.setResizable(false);

            btnUpdate = new JButton("Update");
            btnUpdate.setFont(new Font("Tahoma", Font.BOLD, 14));
            btnUpdate.setBounds(153, 165, 92, 25);
            btnUpdate.addActionListener(this);
            userid = new JTextField(20);
            userid.setBounds(152, 95, 151, 22);
            userid.setText("");
            storeid = new JTextField(20);
            storeid.setBounds(152, 130, 151, 22);
            storeid.setText("");
            resultLbl = new JLabel(" ");
            resultLbl.setFont(new Font("Tahoma", Font.PLAIN, 14));
            resultLbl.setBounds(129, 203, 174, 22);
            useridLbl = new JLabel("User ID");
            useridLbl.setFont(new Font("Tahoma", Font.BOLD, 14));
            useridLbl.setBounds(65, 97, 75, 16);
            storeidLbl = new JLabel("Store ID");
            storeidLbl.setFont(new Font("Tahoma", Font.BOLD, 14));
            storeidLbl.setBounds(65, 132, 75, 16);
            panel = new JPanel();
            panel.setBackground(Color.WHITE);
            frmCashdrawerTool.getContentPane().add(BorderLayout.CENTER, panel);
            panel.setLayout(null);
            panel.add(useridLbl);
            panel.add(userid);
            userid.requestFocusInWindow();

            label = new JLabel("");
            label.setBounds(353, 16, 0, 0);
            panel.add(label);
            panel.add(storeidLbl);
            panel.add(storeid);

            label_1 = new JLabel("");
            label_1.setBounds(349, 43, 0, 0);
            panel.add(label_1);

            label_2 = new JLabel("");
            label_2.setBounds(354, 43, 0, 0);
            panel.add(label_2);
            panel.add(btnUpdate);
            panel.add(resultLbl);
            frmCashdrawerTool.setSize(397,273);
            frmCashdrawerTool.setVisible(true);

            lblNewLabel = new JLabel("");
            lblNewLabel.setIcon(new ImageIcon(getClass().getResource("/images/rsz_vf.jpg")));
            lblNewLabel.setBounds(0, 0, 391, 73);
            panel.add(lblNewLabel);
            frmCashdrawerTool.setSize(397,273);
            frmCashdrawerTool.setVisible(true);

        }

         public void actionPerformed(ActionEvent event) {
                String currentStore = (storeid.getText());
                String currentUser = (userid.getText());
            if (currentUser.isEmpty() || currentStore.isEmpty()) {
                cashdrwresult = 2;
            }else{
              String[] inputLine;
              inputLine = new String[2];
              inputLine[0] = currentUser;
              inputLine[1] = currentStore;
              cashDrwsql join = new cashDrwsql();
              cashdrwresult = join.cashDrwAtion(inputLine);
            }
             if (cashdrwresult ==1) {
                 JOptionPane.showMessageDialog(null, "Action Was Performed Successfully","INFO",JOptionPane.PLAIN_MESSAGE);
                 userid.setText("");
                 storeid.setText("");
                 String[] inputLine;
                 inputLine = new String[1];
                 inputLine[0] = "INFO  --- Drawer: " + currentUser + " of Store: " + currentStore + " was unlocked!";
                 logger obj= new logger();
                 obj.writer(inputLine);
               //resultLbl.setForeground(Color.GREEN);
               //resultLbl.setText("Done!");

             }
             if (cashdrwresult == 2){
                 resultLbl.setForeground(Color.RED);
                // resultLbl.setText("Please Enter Required Data");
                 userid.setText("");
                 storeid.setText("");
                 JOptionPane.showMessageDialog(null, "Please Enter Required Data!","ERROR",JOptionPane.ERROR_MESSAGE);
              System.out.println("Connection Class not called");
              String[] inputLine;
              inputLine = new String[1];
              inputLine[0] = "ERROR  --- No Action Was taken, Please Enter Required Data!";
              logger obj= new logger();
              obj.writer(inputLine);
             }

             if (cashdrwresult == 0) {
            //   resultLbl.setForeground(Color.RED);
            //  resultLbl.setText("Action Was Not Performed");
                 JOptionPane.showMessageDialog(null, "Action Was not performed, Refer Back to Support Team!","ERROR",JOptionPane.ERROR_MESSAGE);
                 userid.setText("");
                 storeid.setText("");
                 String[] inputLine;
                 inputLine = new String[1];
                 inputLine[0] = "ERROR  --- No Action Was taken for User: " + currentUser + " of Store: " + currentStore;
                 logger obj= new logger();
                 obj.writer(inputLine);
         }
        }
}
</code>```

Can you please help me know how to do so ?

答:
You need to go to the 2nd Class "cashDrw". Create a JTextField variable called username. Then create a function and call it "setUsername" for example. And make it public so other classes can access it. And give the function one param. JTextField username; for example. Then type in it:
this.username = username;
Then go to the first class and call the "setUsername" function. And pass the username to it!!</p>

Body:
I'm trying to pass username variable obtained from the JTextField named username from the below Class, I tried many things and I keep failing :(

The first Class:

    package com.cashdrw;
// GUI Login interface

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;

public class ldapLoginPost implements ActionListener {
    public ldapLoginPost() {
    }

    JFrame frmCashdrawerTool;
    JPanel panel;
    JButton button;
    JTextField username;
    JPasswordField password;
    JLabel usernameLbl;
    JLabel passwordLbl;
    JLabel resultLbl;
    int result;
    private JLabel label;
    private JLabel label_1;
    private JLabel label_2;
    private JLabel lblNewLabel;

    public static void main (String[] args){
          ldapLoginPost gui = new ldapLoginPost();

            gui.go();
        }
        public void go(){
            frmCashdrawerTool = new JFrame();
            frmCashdrawerTool.setTitle("Cashdrawer Tool");
            frmCashdrawerTool.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/images/photo.jpg")));
            frmCashdrawerTool.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frmCashdrawerTool.setResizable(false);

            button = new JButton("Login");
            button.setFont(new Font("Tahoma", Font.BOLD, 14));
            button.setBounds(153, 165, 92, 25);
            button.addActionListener(this);
            username = new JTextField(20);
            username.setBounds(152, 95, 151, 22);
            username.setText("");
            password = new JPasswordField(20);
            password.setBounds(152, 130, 151, 22);
            password.setText("");
            resultLbl = new JLabel(" ");
            resultLbl.setFont(new Font("Tahoma", Font.PLAIN, 14));
            resultLbl.setBounds(129, 203, 174, 22);
            usernameLbl = new JLabel("Username");
            usernameLbl.setFont(new Font("Tahoma", Font.BOLD, 14));
            usernameLbl.setBounds(65, 97, 75, 16);
            passwordLbl = new JLabel("Password");
            passwordLbl.setFont(new Font("Tahoma", Font.BOLD, 14));
            passwordLbl.setBounds(65, 132, 75, 16);
            panel = new JPanel();
            panel.setBackground(Color.WHITE);
            frmCashdrawerTool.getContentPane().add(BorderLayout.CENTER, panel);
            panel.setLayout(null);
            panel.add(usernameLbl);
            panel.add(username);
            username.requestFocusInWindow();

            label = new JLabel("");
            label.setBounds(353, 16, 0, 0);
            panel.add(label);
            panel.add(passwordLbl);
            panel.add(password);

            label_1 = new JLabel("");
            label_1.setBounds(349, 43, 0, 0);
            panel.add(label_1);

            label_2 = new JLabel("");
            label_2.setBounds(354, 43, 0, 0);
            panel.add(label_2);
            panel.add(button);
            panel.add(resultLbl);

            lblNewLabel = new JLabel("");
            lblNewLabel.setIcon(new ImageIcon(getClass().getResource("/images/rsz_vf.jpg")));
            lblNewLabel.setBounds(0, 0, 391, 73);
            panel.add(lblNewLabel);
            frmCashdrawerTool.setSize(397,273);
            frmCashdrawerTool.setVisible(true);
        }

         public void actionPerformed(ActionEvent event) {
                char[] passwordVar = password.getPassword();
                String passString = new String (passwordVar);
                String currentUser = (username.getText());
            if (currentUser.isEmpty() || passString.isEmpty()) {
               result = 2;
            }else if (currentUser.equalsIgnoreCase("xxx")){
                String[] inputLine;
                inputLine = new String[2];
                inputLine[0] = currentUser;
                inputLine[1] = passString;
                ldapConnPost connect = new ldapConnPost();
                result = connect.setUpConnection(inputLine);
            }else {
                result = 3;
            }

             if (result ==1) {
                username.setText("");
                password.setText("");
                resultLbl.setForeground(Color.GREEN);
                resultLbl.setText("Authenticated Successfully");
                frmCashdrawerTool.setVisible(false);
                frmCashdrawerTool.dispose();
                String[] inputLine;
                inputLine = new String[1];
                inputLine[0] = "INFO  --- " + currentUser + "  Was Granted Access!";
                logger obj= new logger();
                obj.writer(inputLine);
                cashDrw gui = new cashDrw();
                gui.go();
             }
             if (result == 2){
                 JOptionPane.showMessageDialog(null, "Please Enter Your Data!","ERROR",JOptionPane.ERROR_MESSAGE);
                 System.out.println("Connection Class not called");
             }
             if (result == 3){
                 username.setText("");
                 password.setText("");
                 JOptionPane.showMessageDialog(null, "You Are not allowed to use this tool!","ERROR",JOptionPane.ERROR_MESSAGE);
                 System.out.println("Connection Class not called");
                 String[] inputLine;
                 inputLine = new String[1];
                 inputLine[0] = "ERROR --- " + currentUser + "  Was Denied Access!";
                 logger obj= new logger();
                 obj.writer(inputLine);
             }

             if (result == 0) {
                 JOptionPane.showMessageDialog(null, "Authentication Failed!","ERROR",JOptionPane.ERROR_MESSAGE);
                 password.setText("");
                 String[] inputLine;
                 inputLine = new String[1];
                 inputLine[0] = "ERROR --- " + currentUser + "  LDAP Authentication Failed!";
                 logger obj= new logger();
                 obj.writer(inputLine);
         }
        }
}

To the below Class, so that I can use it there:

package com.cashdrw;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class cashDrw extends JFrame implements ActionListener {
    public cashDrw() {
    }

    JFrame frmCashdrawerTool;
    JPanel panel;
    JButton btnUpdate;
    JTextField userid;
    JTextField storeid;
    JLabel useridLbl;
    JLabel storeidLbl;
    JLabel resultLbl;
    int cashdrwresult;
    private JLabel label;
    private JLabel label_1;
    private JLabel label_2;
    private JLabel lblNewLabel;

    public static void main (String[] args) {

       }
        public void go() {
            frmCashdrawerTool = new JFrame();
            frmCashdrawerTool.setTitle("Cashdrawer Tool");
            frmCashdrawerTool.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/images/photo.jpg")));
            frmCashdrawerTool.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frmCashdrawerTool.setResizable(false);

            btnUpdate = new JButton("Update");
            btnUpdate.setFont(new Font("Tahoma", Font.BOLD, 14));
            btnUpdate.setBounds(153, 165, 92, 25);
            btnUpdate.addActionListener(this);
            userid = new JTextField(20);
            userid.setBounds(152, 95, 151, 22);
            userid.setText("");
            storeid = new JTextField(20);
            storeid.setBounds(152, 130, 151, 22);
            storeid.setText("");
            resultLbl = new JLabel(" ");
            resultLbl.setFont(new Font("Tahoma", Font.PLAIN, 14));
            resultLbl.setBounds(129, 203, 174, 22);
            useridLbl = new JLabel("User ID");
            useridLbl.setFont(new Font("Tahoma", Font.BOLD, 14));
            useridLbl.setBounds(65, 97, 75, 16);
            storeidLbl = new JLabel("Store ID");
            storeidLbl.setFont(new Font("Tahoma", Font.BOLD, 14));
            storeidLbl.setBounds(65, 132, 75, 16);
            panel = new JPanel();
            panel.setBackground(Color.WHITE);
            frmCashdrawerTool.getContentPane().add(BorderLayout.CENTER, panel);
            panel.setLayout(null);
            panel.add(useridLbl);
            panel.add(userid);
            userid.requestFocusInWindow();

            label = new JLabel("");
            label.setBounds(353, 16, 0, 0);
            panel.add(label);
            panel.add(storeidLbl);
            panel.add(storeid);

            label_1 = new JLabel("");
            label_1.setBounds(349, 43, 0, 0);
            panel.add(label_1);

            label_2 = new JLabel("");
            label_2.setBounds(354, 43, 0, 0);
            panel.add(label_2);
            panel.add(btnUpdate);
            panel.add(resultLbl);
            frmCashdrawerTool.setSize(397,273);
            frmCashdrawerTool.setVisible(true);

            lblNewLabel = new JLabel("");
            lblNewLabel.setIcon(new ImageIcon(getClass().getResource("/images/rsz_vf.jpg")));
            lblNewLabel.setBounds(0, 0, 391, 73);
            panel.add(lblNewLabel);
            frmCashdrawerTool.setSize(397,273);
            frmCashdrawerTool.setVisible(true);

        }

         public void actionPerformed(ActionEvent event) {
                String currentStore = (storeid.getText());
                String currentUser = (userid.getText());
            if (currentUser.isEmpty() || currentStore.isEmpty()) {
                cashdrwresult = 2;
            }else{
              String[] inputLine;
              inputLine = new String[2];
              inputLine[0] = currentUser;
              inputLine[1] = currentStore;
              cashDrwsql join = new cashDrwsql();
              cashdrwresult = join.cashDrwAtion(inputLine);
            }
             if (cashdrwresult ==1) {
                 JOptionPane.showMessageDialog(null, "Action Was Performed Successfully","INFO",JOptionPane.PLAIN_MESSAGE);
                 userid.setText("");
                 storeid.setText("");
                 String[] inputLine;
                 inputLine = new String[1];
                 inputLine[0] = "INFO  --- Drawer: " + currentUser + " of Store: " + currentStore + " was unlocked!";
                 logger obj= new logger();
                 obj.writer(inputLine);
               //resultLbl.setForeground(Color.GREEN);
               //resultLbl.setText("Done!");

             }
             if (cashdrwresult == 2){
                 resultLbl.setForeground(Color.RED);
                // resultLbl.setText("Please Enter Required Data");
                 userid.setText("");
                 storeid.setText("");
                 JOptionPane.showMessageDialog(null, "Please Enter Required Data!","ERROR",JOptionPane.ERROR_MESSAGE);
              System.out.println("Connection Class not called");
              String[] inputLine;
              inputLine = new String[1];
              inputLine[0] = "ERROR  --- No Action Was taken, Please Enter Required Data!";
              logger obj= new logger();
              obj.writer(inputLine);
             }

             if (cashdrwresult == 0) {
            //   resultLbl.setForeground(Color.RED);
            //  resultLbl.setText("Action Was Not Performed");
                 JOptionPane.showMessageDialog(null, "Action Was not performed, Refer Back to Support Team!","ERROR",JOptionPane.ERROR_MESSAGE);
                 userid.setText("");
                 storeid.setText("");
                 String[] inputLine;
                 inputLine = new String[1];
                 inputLine[0] = "ERROR  --- No Action Was taken for User: " + currentUser + " of Store: " + currentStore;
                 logger obj= new logger();
                 obj.writer(inputLine);
         }
        }
}

Can you please help me know how to do so ?


问:
Getting undefined step definition warning in Cucumber Protractor setup
I have installed the npm modules locally (find the dependencies details in below package.json) and try to execute the below cucumber feature file and SD but getting Undefined. Implement.. message.

I have prepared my feature file as below: Stored in: test/features/sample.feature

```<code> Feature: Running Cucumber with Protractor
 @test
 Scenario: To verify the Search result
  Given I am on home page
</code>```

And implemented the SD as below: Stored in: test/step_definitions/sample.steps.js

```<code> module.exports = function() {
  this.Given(/^I am on home page$/, function () {
    return browser.get("http://www.google.com");
   });
 }
</code>```

And my specs & cucumberOpts in conf.js as below:

```<code> specs: [
 './../features/*.feature'
 ],

 cucumberOpts: {
  require: ['./step_definitions/*.steps.js'],
  tags: '@test',
  strict: true,
  format: 'pretty'
 }
</code>```

Installed package.json dependencies details:

```<code> "dependencies": {
  "chai": "^4.0.1",
  "chai-as-promised": "^6.0.0",
  "cucumber": "^2.3.0",
  "protractor": "^5.1.2",
  "protractor-cucumber-framework": "^3.1.1"
 }
</code>```

But in execution getting the message as :

```<code> 1 scenario (1 undefined)
 1 step (1 undefined)
 0m00.000s
</code>```

can anyone help me to come out...

答:
Your problem seems to be with the step definitions themselves.

You seem to be using the old CucumberJS 1.x syntax for the 2.x framework.

Here's the update to the step definition provided using 2.x syntax:

```<code>var {defineSupportCode} = require('cucumber');

defineSupportCode(({Given, When, Then}) => {

  Given(/^I am on home page$/, function () {
    return browser.get("http://www.google.com");
  });

});
</code>```

Body:
I have installed the npm modules locally (find the dependencies details in below package.json) and try to execute the below cucumber feature file and SD but getting Undefined. Implement.. message.

I have prepared my feature file as below: Stored in: test/features/sample.feature

 Feature: Running Cucumber with Protractor
 @test
 Scenario: To verify the Search result
  Given I am on home page

And implemented the SD as below: Stored in: test/step_definitions/sample.steps.js

 module.exports = function() {
  this.Given(/^I am on home page$/, function () {
    return browser.get("http://www.google.com");
   });
 }

And my specs & cucumberOpts in conf.js as below:

 specs: [
 './../features/*.feature'
 ],

 cucumberOpts: {
  require: ['./step_definitions/*.steps.js'],
  tags: '@test',
  strict: true,
  format: 'pretty'
 }

Installed package.json dependencies details:

 "dependencies": {
  "chai": "^4.0.1",
  "chai-as-promised": "^6.0.0",
  "cucumber": "^2.3.0",
  "protractor": "^5.1.2",
  "protractor-cucumber-framework": "^3.1.1"
 }

But in execution getting the message as :

 1 scenario (1 undefined)
 1 step (1 undefined)
 0m00.000s

can anyone help me to come out...

Body:
Your problem seems to be with the step definitions themselves.

You seem to be using the old CucumberJS 1.x syntax for the 2.x framework.

Here's the update to the step definition provided using 2.x syntax:

var {defineSupportCode} = require('cucumber');

defineSupportCode(({Given, When, Then}) => {

  Given(/^I am on home page$/, function () {
    return browser.get("http://www.google.com");
  });

});


问:
Unable to remove white space from data frame and hence was not able to find mean
I need to find the mean of this value where
class(newtemp)
is character .The data was original 10.6 °C like this. i removed °C but space is there due to which as.numeric is not working.

```<code>newtemp

 [1] "-10.6 " "-10.6 " "-11.0 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 "

[12] "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-11.0 "

[23] "-10.6 " "-10.6 " "-10.6 " "-11.0 " "-10.6 " "-10.0 " "-10.0 " "-10.0 " "-10.0 " "-10.0 " "-9.4 "

[34] "-8.9 "  "-8.3 "  "-7.2 "  "-7.2 "  "-5.6 "  "-5.0 "  "-3.9 "  "-3.9 "  "-3.9 "  "-3.3 "  "-3.3 "

[45] "-3.9 "  "-6.1 "  "-8.3 "  "-7.8 "  "-8.9 "  "-10.0 " "-11.7 " "-12.8 "

#Tried this
library(stringr)
try=str_replace_all(newtemp, fixed(" "), "") but not able to remove
#Tried this also
trim <- function (x) gsub("^\\s+|\\s+$", "", x)
trim(x =newtemp)
# STill not removed

as.numeric(try)

 [1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA

[36] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
#Warning message:
#NAs introduced by coercion
#Sill no output.
</code>```

The code i m using is :

```<code>    library(rvest)
linkurl="https://www.wunderground.com/history/airport/KVAY/2015/2/17/DailyHistory.html?req_city=Cherry+Hill&req_state=NJ&req_statename=New+Jersey&reqdb.zip=08002&reqdb.magic=1&reqdb.wmo=99999&MR=1"
weathertable=read_html(linkurl)%>%html_node("#obsTable")%>%html_table()
weathertable
newtemp=weathertable$Temp.

abc=(gsub("°C", "", newtemp))
abc
abc_new=(gsub("[[:space:]]", "", abc))
as.numeric(abc_new)
trimws(x=abc)
as.numeric(trimws(x=abc))
</code>```

Update

```<code>        > newtemp
     [1] "-10.6 °C" "-10.6 °C" "-11.0 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C"
    [10] "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C"
    [19] "-10.6 °C" "-10.6 °C" "-10.6 °C" "-11.0 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-11.0 °C" "-10.6 °C"
    [28] "-10.0 °C" "-10.0 °C" "-10.0 °C" "-10.0 °C" "-10.0 °C" "-9.4 °C"  "-8.9 °C"  "-8.3 °C"  "-7.2 °C"
    [37] "-7.2 °C"  "-5.6 °C"  "-5.0 °C"  "-3.9 °C"  "-3.9 °C"  "-3.9 °C"  "-3.3 °C"  "-3.3 °C"  "-3.9 °C"
    [46] "-6.1 °C"  "-8.3 °C"  "-7.8 °C"  "-8.9 °C"  "-10.0 °C" "-11.7 °C" "-12.8 °C"
    > abc=(gsub(" °C", "", newtemp))
    > abc
     [1] "-10.6 °C" "-10.6 °C" "-11.0 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C"
    [10] "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C"
    [19] "-10.6 °C" "-10.6 °C" "-10.6 °C" "-11.0 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-11.0 °C" "-10.6 °C"
    [28] "-10.0 °C" "-10.0 °C" "-10.0 °C" "-10.0 °C" "-10.0 °C" "-9.4 °C"  "-8.9 °C"  "-8.3 °C"  "-7.2 °C"
    [37] "-7.2 °C"  "-5.6 °C"  "-5.0 °C"  "-3.9 °C"  "-3.9 °C"  "-3.9 °C"  "-3.3 °C"  "-3.3 °C"  "-3.9 °C"
    [46] "-6.1 °C"  "-8.3 °C"  "-7.8 °C"  "-8.9 °C"  "-10.0 °C" "-11.7 °C" "-12.8 °C"
    > abc=(gsub("°C", "", newtemp))
> abc
 [1] "-10.6 " "-10.6 " "-11.0 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 "
[12] "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-11.0 "
[23] "-10.6 " "-10.6 " "-10.6 " "-11.0 " "-10.6 " "-10.0 " "-10.0 " "-10.0 " "-10.0 " "-10.0 " "-9.4 "
[34] "-8.9 "  "-8.3 "  "-7.2 "  "-7.2 "  "-5.6 "  "-5.0 "  "-3.9 "  "-3.9 "  "-3.9 "  "-3.3 "  "-3.3 "
[45] "-3.9 "  "-6.1 "  "-8.3 "  "-7.8 "  "-8.9 "  "-10.0 " "-11.7 " "-12.8 "
>
</code>```

答:
Your strings contain a whitespace other than a regular ASCII space (decimal value 32). Thus, you need a regex that will match any Unicode whitespace. It is curious that a simple gsub("[[:space:]]*°C", "", newtemp) does not work in all R environments.

What usually works is a PCRE regex:

```<code>gsub("(*UCP)\\s*°C", "", newtemp, perl=TRUE)
</code>```

Here, (*UCP) is a PCRE verb making the shorthand character classes Unicode-aware and \s can match any Unicode whitespaces. The perl=TRUE argument makes R use a PCRE regex engine rather than the default TRE regex engine.

Body:
I need to find the mean of this value where
class(newtemp)
is character .The data was original 10.6 °C like this. i removed °C but space is there due to which as.numeric is not working.

newtemp

 [1] "-10.6 " "-10.6 " "-11.0 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 "

[12] "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-11.0 "

[23] "-10.6 " "-10.6 " "-10.6 " "-11.0 " "-10.6 " "-10.0 " "-10.0 " "-10.0 " "-10.0 " "-10.0 " "-9.4 "

[34] "-8.9 "  "-8.3 "  "-7.2 "  "-7.2 "  "-5.6 "  "-5.0 "  "-3.9 "  "-3.9 "  "-3.9 "  "-3.3 "  "-3.3 "

[45] "-3.9 "  "-6.1 "  "-8.3 "  "-7.8 "  "-8.9 "  "-10.0 " "-11.7 " "-12.8 "

#Tried this
library(stringr)
try=str_replace_all(newtemp, fixed(" "), "") but not able to remove
#Tried this also
trim <- function (x) gsub("^\\s+|\\s+$", "", x)
trim(x =newtemp)
# STill not removed

as.numeric(try)

 [1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA

[36] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
#Warning message:
#NAs introduced by coercion
#Sill no output.

The code i m using is :

    library(rvest)
linkurl="https://www.wunderground.com/history/airport/KVAY/2015/2/17/DailyHistory.html?req_city=Cherry+Hill&req_state=NJ&req_statename=New+Jersey&reqdb.zip=08002&reqdb.magic=1&reqdb.wmo=99999&MR=1"
weathertable=read_html(linkurl)%>%html_node("#obsTable")%>%html_table()
weathertable
newtemp=weathertable$Temp.

abc=(gsub("°C", "", newtemp))
abc
abc_new=(gsub("[[:space:]]", "", abc))
as.numeric(abc_new)
trimws(x=abc)
as.numeric(trimws(x=abc))

Update

        > newtemp
     [1] "-10.6 °C" "-10.6 °C" "-11.0 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C"
    [10] "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C"
    [19] "-10.6 °C" "-10.6 °C" "-10.6 °C" "-11.0 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-11.0 °C" "-10.6 °C"
    [28] "-10.0 °C" "-10.0 °C" "-10.0 °C" "-10.0 °C" "-10.0 °C" "-9.4 °C"  "-8.9 °C"  "-8.3 °C"  "-7.2 °C"
    [37] "-7.2 °C"  "-5.6 °C"  "-5.0 °C"  "-3.9 °C"  "-3.9 °C"  "-3.9 °C"  "-3.3 °C"  "-3.3 °C"  "-3.9 °C"
    [46] "-6.1 °C"  "-8.3 °C"  "-7.8 °C"  "-8.9 °C"  "-10.0 °C" "-11.7 °C" "-12.8 °C"
    > abc=(gsub(" °C", "", newtemp))
    > abc
     [1] "-10.6 °C" "-10.6 °C" "-11.0 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C"
    [10] "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C"
    [19] "-10.6 °C" "-10.6 °C" "-10.6 °C" "-11.0 °C" "-10.6 °C" "-10.6 °C" "-10.6 °C" "-11.0 °C" "-10.6 °C"
    [28] "-10.0 °C" "-10.0 °C" "-10.0 °C" "-10.0 °C" "-10.0 °C" "-9.4 °C"  "-8.9 °C"  "-8.3 °C"  "-7.2 °C"
    [37] "-7.2 °C"  "-5.6 °C"  "-5.0 °C"  "-3.9 °C"  "-3.9 °C"  "-3.9 °C"  "-3.3 °C"  "-3.3 °C"  "-3.9 °C"
    [46] "-6.1 °C"  "-8.3 °C"  "-7.8 °C"  "-8.9 °C"  "-10.0 °C" "-11.7 °C" "-12.8 °C"
    > abc=(gsub("°C", "", newtemp))
> abc
 [1] "-10.6 " "-10.6 " "-11.0 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 "
[12] "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-10.6 " "-11.0 "
[23] "-10.6 " "-10.6 " "-10.6 " "-11.0 " "-10.6 " "-10.0 " "-10.0 " "-10.0 " "-10.0 " "-10.0 " "-9.4 "
[34] "-8.9 "  "-8.3 "  "-7.2 "  "-7.2 "  "-5.6 "  "-5.0 "  "-3.9 "  "-3.9 "  "-3.9 "  "-3.3 "  "-3.3 "
[45] "-3.9 "  "-6.1 "  "-8.3 "  "-7.8 "  "-8.9 "  "-10.0 " "-11.7 " "-12.8 "
>

Body:
Your strings contain a whitespace other than a regular ASCII space (decimal value 32). Thus, you need a regex that will match any Unicode whitespace. It is curious that a simple gsub("[[:space:]]*°C", "", newtemp) does not work in all R environments.

What usually works is a PCRE regex:

gsub("(*UCP)\\s*°C", "", newtemp, perl=TRUE)

Here, (*UCP) is a PCRE verb making the shorthand character classes Unicode-aware and \s can match any Unicode whitespaces. The perl=TRUE argument makes R use a PCRE regex engine rather than the default TRE regex engine.


问:
Using Scrapy ItemLoader, parse first n characters of text from multiple elements
Using Scrapy's ItemLoader, I'd like to parse the first n characters from an HTML element (which will have multiple embedded HTML elements, each of which may or may not contain text which constitutes part of the text that is to be retained).

Here's an example setup:

Sample HTML:

```<code><div class="about-copy">
<p>Developers trust Stack Overflow to help solve coding problems
  and use Stack Overflow Jobs to find job opportunities. We’re
  committed to making the internet a better place, and our products
  aim to enrich the lives of developers as they grow and mature in
  their careers.
</p>
<a href='...'></a>
<p>Founded in 2008, Stack Overflow sees 40 million visitors each month
  and is the flagship site of the Stack Exchange network, home to 150+
  Q&A sites dedicated to niche topics.
</p>
</div>
</code>```

Parser code:

```<code>def parse_details(self, response):
   ...
   l = ItemLoader(item=Entry(), response=response)
   # this is presumably the portion of the code that is to be modified
   l.add_css('f_brief_summary', 'div.about-copy::text')
   ...
</code>```

Desired result:

```<code>  Developers trust Stack Overflow to help solve coding problems
  and use Stack Overflow Jobs to find job opportunities. We’re
  committed to making the internet a better place, and our products
  aim to enrich the lives of developers as they grow and mature in
  their careers. Founded in 2008, Stack Overflow
</code>```

Is there a one-step way to do this using an ItemLoader, or should the parsing be done manually, with the text then added to the ItemLoaded object with the 'add_value' method?

答:
Instead of using the generic ItemLoader, create your own Loader class. You can then apply pre and post processing to each of the field, or define processors for them all. See: Scrapy Item Loaders Guide

In your module which defines the Entry item, add the following. Notice that in the example below I am using the "remove_tags" method instead of "::text" in your selector.

```<code>import scrapy
from scrapy.loader import ItemLoader

from scrapy.loader.processors import MapCompose, Join
from w3lib.html import remove_tags

# You can do so much better here!
def format_me(x):
    return x.replace('\n', ' ').replace('  ', ' ').strip()

# Here is the Loader you need to add; mine only covers one field.
class EntryLoader(ItemLoader):
    f_brief_summary_in = MapCompose(remove_tags, format_me)
    f_brief_summary_out = Join()

# You already have this; mine only covers one field.
class Entry(scrapy.Item):
    f_brief_summary = scrapy.Field()
</code>```

This gives you the result you wanted. To test:

Save your example snippet into a file, e.g. example.html

Run the scrapy shell

```<code>scrapy shell './example.html'
</code>```

In the shell import your Item and Loader:

```<code>from scrapyproj.entry_module import EntryLoader, Entry
</code>```

Test the parser:

```<code>entry_loader = EntryLoader(item=Entry(), response=response)
entry_loader.add_css('f_brief_summary', 'div.about-copy')
entry_loader.load_item()
</code>```

Outputs:

```<code>{'f_brief_summary': 'Developers trust Stack Overflow to help solve coding '
                    'problems  and use Stack Overflow Jobs to find job '
                    'opportunities. We’re  committed to making the internet a '
                    'better place, and our products  aim to enrich the lives '
                    'of developers as they grow and mature in  their '
                    'careers.   Founded in 2008, Stack Overflow sees 40 '
                    'million visitors each month  and is the flagship site of '
                    'the Stack Exchange network, home to 150+  Q&A sites '
                    'dedicated to niche topics.'}
</code>```

Body:
Using Scrapy's ItemLoader, I'd like to parse the first n characters from an HTML element (which will have multiple embedded HTML elements, each of which may or may not contain text which constitutes part of the text that is to be retained).

Here's an example setup:

Sample HTML:

Developers trust Stack Overflow to help solve coding problems
  and use Stack Overflow Jobs to find job opportunities. We’re
  committed to making the internet a better place, and our products
  aim to enrich the lives of developers as they grow and mature in
  their careers.

Founded in 2008, Stack Overflow sees 40 million visitors each month
  and is the flagship site of the Stack Exchange network, home to 150+
  Q&A sites dedicated to niche topics.

Parser code:

def parse_details(self, response):
   ...
   l = ItemLoader(item=Entry(), response=response)
   # this is presumably the portion of the code that is to be modified
   l.add_css('f_brief_summary', 'div.about-copy::text')
   ...

Desired result:

  Developers trust Stack Overflow to help solve coding problems
  and use Stack Overflow Jobs to find job opportunities. We’re
  committed to making the internet a better place, and our products
  aim to enrich the lives of developers as they grow and mature in
  their careers. Founded in 2008, Stack Overflow

Is there a one-step way to do this using an ItemLoader, or should the parsing be done manually, with the text then added to the ItemLoaded object with the 'add_value' method?

Body:
Instead of using the generic ItemLoader, create your own Loader class. You can then apply pre and post processing to each of the field, or define processors for them all. See: Scrapy Item Loaders Guide

In your module which defines the Entry item, add the following. Notice that in the example below I am using the "remove_tags" method instead of "::text" in your selector.

import scrapy
from scrapy.loader import ItemLoader

from scrapy.loader.processors import MapCompose, Join
from w3lib.html import remove_tags

# You can do so much better here!
def format_me(x):
    return x.replace('\n', ' ').replace('  ', ' ').strip()

# Here is the Loader you need to add; mine only covers one field.
class EntryLoader(ItemLoader):
    f_brief_summary_in = MapCompose(remove_tags, format_me)
    f_brief_summary_out = Join()

# You already have this; mine only covers one field.
class Entry(scrapy.Item):
    f_brief_summary = scrapy.Field()

This gives you the result you wanted. To test:

Save your example snippet into a file, e.g. example.html

Run the scrapy shell

scrapy shell './example.html'

In the shell import your Item and Loader:

from scrapyproj.entry_module import EntryLoader, Entry

Test the parser:

entry_loader = EntryLoader(item=Entry(), response=response)
entry_loader.add_css('f_brief_summary', 'div.about-copy')
entry_loader.load_item()

Outputs:

{'f_brief_summary': 'Developers trust Stack Overflow to help solve coding '
                    'problems  and use Stack Overflow Jobs to find job '
                    'opportunities. We’re  committed to making the internet a '
                    'better place, and our products  aim to enrich the lives '
                    'of developers as they grow and mature in  their '
                    'careers.   Founded in 2008, Stack Overflow sees 40 '
                    'million visitors each month  and is the flagship site of '
                    'the Stack Exchange network, home to 150+  Q&amp;A sites '
                    'dedicated to niche topics.'}


问:
personal version control system to recommend
For personal use. Anyone can recommend the version control system for Windows</p>

答: Git. You won't regret it. </p>

Body: Git. You won't regret it.


问:
running angular app before e-2-e tests
I have written a few protractor tests against an angular 2 app. Both of them reside in the same repository (app and the tests). I need to run the app (npm start) on localhost before I can run those tests. whats the best way to achieve this?</p>

答:
There are a number of build tools that can accomplish this (eg. Grunt, Gulp, etc...). Personally, I like to use npm scripts, as they are simple, and already part of your project. For example, in your package.json, you could add something like:

```<code>  "scripts": {
    "pretest": "npm install",
    "test": "protractor conf.js"
  },
</code>```

And then if you run your tests via npm test, npm install should get run before your tests run.

Title: running angular app before e-2-e tests

Body:
There are a number of build tools that can accomplish this (eg. Grunt, Gulp, etc...). Personally, I like to use npm scripts, as they are simple, and already part of your project. For example, in your package.json, you could add something like:

  "scripts": {
    "pretest": "npm install",
    "test": "protractor conf.js"
  },

And then if you run your tests via npm test, npm install should get run before your tests run.


问:
Initialize active class on Materialize form when form is prepopulated
I'm using materialise with reactjs. When I populate a form with data from the database the value is set however the label transition javascript which adds the active class isn't triggered. This means the value of the form is ontop of the label.  Materialize docs suggests using some jquery to get it to trigger, however, putting this jquery in componentWillReceiveProps after this.setState doesn't seem to work. I'm new to Reactjs so help is appreciated.

```<code>componentWillReceiveProps(nextProps) {
  var profileCandidate = nextProps.profileCandidate;
  var firstName = profileCandidate && profileCandidate.name && profileCandidate.name.first;

  this.setState({
    'name.first': firstName,
  });

  $(document).ready(function() {
    Materialize.updateTextFields();
  });
}
</code>```

答:
Are you using react materialize ?
I do not think you will be needing such jquery logic to get fired on update if you are using react version of materialize.
Thanks</p>

Body:
I'm using materialise with reactjs. When I populate a form with data from the database the value is set however the label transition javascript which adds the active class isn't triggered. This means the value of the form is ontop of the label.  Materialize docs suggests using some jquery to get it to trigger, however, putting this jquery in componentWillReceiveProps after this.setState doesn't seem to work. I'm new to Reactjs so help is appreciated.

componentWillReceiveProps(nextProps) {
  var profileCandidate = nextProps.profileCandidate;
  var firstName = profileCandidate && profileCandidate.name && profileCandidate.name.first;

  this.setState({
    'name.first': firstName,
  });

  $(document).ready(function() {
    Materialize.updateTextFields();
  });
}


问:
How to exchange code for token in Spotify using Poco Net Library
So all of a sudden they decide I need an authorization header for Spotify Search API.

My application runs in C++ using Poco Net libraries and I can't get it to work.

I went through all that process of getting the "code" that I am supposed to exchange for the token. I assume this code is valid, even though I used just a totally unrelated domain then copied it of the variable that was sent to that page.

See https://developer.spotify.com/web-api/authorization-guide/

This is my code that isn't working:

```<code>bool getToken()
{
    Poco::URI loginURI( "https://accounts.spotify.com" );
    Poco::Net::HTTPSClientSession loginSession( loginURI.getHost(), loginURI.getPort(), context );
//      Poco::Net::HTTPBasicCredentials credentials( clientId, clientSecret );

    std::ostringstream requestOStr;
    requestOStr << "https://accounts.spotify.com/api/token?grant_type=authorization_code&code="
            << (m_refreshToken.empty() ? code : m_refreshToken)
            << "&redirect_uri=" << redirectURI
            << "&client_id=" << clientId << "&client_secret=" << clientSecret;

    std::string requestStr( requestOStr.str() );
    Poco::Net::HTTPRequest loginRequest( Poco::Net::HTTPRequest::HTTP_POST, requestStr,
            Poco::Net::HTTPMessage::HTTP_1_1 );

//      credentials.authenticate( loginRequest );

    loginSession.sendRequest( loginRequest );
    Poco::Net::HTTPResponse response;

    std::istream& rs = loginSession.receiveResponse( response );
    std::cout << "Login request " << requestStr << std::endl;
    std::cout << "Login response status " << static_cast<int>(response.getStatus()) << ", "
            << response.getReason() << std::endl;

    std::string rsStr(std::istreambuf_iterator<char>(rs), {});
    if( rsStr.empty() )
    {
        std::cout << "No results" << std::endl;
        return false;
    }
    else
    {
        std::cout << "Logon response:\n" << rsStr << std::endl;
    }
    Parser parser;
    Var result;
    result = parser.parse(rsStr);
    Object::Ptr obj = result.extract<Object::Ptr>();
    try
    {
        Var tokenVar = obj->get( "access_token ");
        if( tokenVar.isString() )
        {
            m_token = tokenVar.convert< std::string >();
        }
        else
        {
            std::cerr << "Could not get access token" << std::endl;
            return false;
        }
        Var refreshTokenVar = obj->get( "refresh_token" );
        if( refreshTokenVar.isString() )
        {
            m_refreshToken = refreshTokenVar.convert< std::string >();
        }
        return true;
    }
    catch( const std::exception& err )
    {
        std::cerr << "Error getting login token" << err.what() << std::endl;
        return false;
    }
}
</code>```

I tried the BasicCredentials instead of putting client id and clientSecret into the request but that got the same result.

This is how the HTTP request looks with the values modified:

```<code>https://accounts.spotify.com/api/token?grant_type=authorization_code&code=THE_CODE&redirect_uri=THE_REDIRECT_URI&client_id=THE_CLIENT_ID&client_secret=THE_CLIENT_SECRET
</code>```

The response I am getting is:

```<code>Login response status 400, Bad Request
  {"error":"server_error","error_description":"Unexpected status: 400"}
</code>```

答:
Ok I will answer my own question now having found out the answer. My error was mis-use of POST.

This works, once I have the original authorization_code. The code will no longer be valid once "swapped" but that's a different issue.

```<code>bool getToken()
{
    Poco::URI loginURI( "https://accounts.spotify.com" );
    Poco::Net::HTTPSClientSession loginSession( loginURI.getHost(), loginURI.getPort(), context );
    Poco::Net::HTTPBasicCredentials credentials( clientId, clientSecret );

    loginSession.setKeepAlive( true );
    std::string requestStr( "https://accounts.spotify.com/api/token" );
    Poco::Net::HTTPRequest loginRequest( Poco::Net::HTTPRequest::HTTP_POST,
            requestStr,
            Poco::Net::HTTPMessage::HTTP_1_1 );
    loginRequest.setContentType("application/x-www-form-urlencoded");
    loginRequest.setKeepAlive( true );

    std::string grantType;
    std::string authCode;

    if( m_refreshToken.empty() )
    {
        grantType = "authorization_code";
        authCode = code;
    }
    else
    {
        grantType = "refresh_token";
        authCode = m_refreshToken;
    }
    std::ostringstream contentOStr;
    contentOStr << "grant_type=" << grantType <<
        "&code=" << authCode
        << "&redirect_uri=" << redirectURI;

    std::string contentStr = contentOStr.str();
    loginRequest.setContentLength( contentStr.size() );
    credentials.authenticate( loginRequest );

    std::ostream& requestOStr = loginSession.sendRequest( loginRequest );
    requestOStr << contentStr;
    requestOStr.flush();
    Poco::Net::HTTPResponse response;

    std::istream& rs = loginSession.receiveResponse( response );
    std::cout << "Login request ";
    loginRequest.write(std::cout);
    std::cout << std::endl;
    std::cout << "Login response status " << static_cast<int>(response.getStatus()) << ", "
            << response.getReason() << std::endl;

    std::string rsStr(std::istreambuf_iterator<char>(rs), {});
    if( rsStr.empty() )
    {
        std::cout << "No results" << std::endl;
        return false;
    }
    else
    {
        std::cout << "Logon response:\n" << rsStr << std::endl;
    }
    Parser parser;
    Var result;
    result = parser.parse(rsStr);
    Object::Ptr obj = result.extract<Object::Ptr>();
    try
    {
        Var tokenVar = obj->get( "access_token" );
        if( tokenVar.isString() )
        {
            m_token = tokenVar.convert< std::string >();
        }
        else
        {
            std::cerr << "Could not get access token" << std::endl;
            return false;
        }
        Var refreshTokenVar = obj->get( "refresh_token" );
        if( refreshTokenVar.isString() )
        {
            m_refreshToken = refreshTokenVar.convert< std::string >();
        }
        return true;
    }
    catch( const std::exception& err )
    {
        std::cerr << "Error getting login token" << err.what() << std::endl;
        return false;
    }
}
</code>```

Body:
So all of a sudden they decide I need an authorization header for Spotify Search API.

My application runs in C++ using Poco Net libraries and I can't get it to work.

I went through all that process of getting the "code" that I am supposed to exchange for the token. I assume this code is valid, even though I used just a totally unrelated domain then copied it of the variable that was sent to that page.

See https://developer.spotify.com/web-api/authorization-guide/

This is my code that isn't working:

bool getToken()
{
    Poco::URI loginURI( "https://accounts.spotify.com" );
    Poco::Net::HTTPSClientSession loginSession( loginURI.getHost(), loginURI.getPort(), context );
//      Poco::Net::HTTPBasicCredentials credentials( clientId, clientSecret );

    std::ostringstream requestOStr;
    requestOStr << "https://accounts.spotify.com/api/token?grant_type=authorization_code&code="
            << (m_refreshToken.empty() ? code : m_refreshToken)
            << "&redirect_uri=" << redirectURI
            << "&client_id=" << clientId << "&client_secret=" << clientSecret;

    std::string requestStr( requestOStr.str() );
    Poco::Net::HTTPRequest loginRequest( Poco::Net::HTTPRequest::HTTP_POST, requestStr,
            Poco::Net::HTTPMessage::HTTP_1_1 );

//      credentials.authenticate( loginRequest );

    loginSession.sendRequest( loginRequest );
    Poco::Net::HTTPResponse response;

    std::istream& rs = loginSession.receiveResponse( response );
    std::cout << "Login request " << requestStr << std::endl;
    std::cout << "Login response status " << static_cast<int>(response.getStatus()) << ", "
            << response.getReason() << std::endl;

    std::string rsStr(std::istreambuf_iterator<char>(rs), {});
    if( rsStr.empty() )
    {
        std::cout << "No results" << std::endl;
        return false;
    }
    else
    {
        std::cout << "Logon response:\n" << rsStr << std::endl;
    }
    Parser parser;
    Var result;
    result = parser.parse(rsStr);
    Object::Ptr obj = result.extract<Object::Ptr>();
    try
    {
        Var tokenVar = obj->get( "access_token ");
        if( tokenVar.isString() )
        {
            m_token = tokenVar.convert< std::string >();
        }
        else
        {
            std::cerr << "Could not get access token" << std::endl;
            return false;
        }
        Var refreshTokenVar = obj->get( "refresh_token" );
        if( refreshTokenVar.isString() )
        {
            m_refreshToken = refreshTokenVar.convert< std::string >();
        }
        return true;
    }
    catch( const std::exception& err )
    {
        std::cerr << "Error getting login token" << err.what() << std::endl;
        return false;
    }
}

I tried the BasicCredentials instead of putting client id and clientSecret into the request but that got the same result.

This is how the HTTP request looks with the values modified:

https://accounts.spotify.com/api/token?grant_type=authorization_code&code=THE_CODE&redirect_uri=THE_REDIRECT_URI&client_id=THE_CLIENT_ID&client_secret=THE_CLIENT_SECRET

The response I am getting is:

Login response status 400, Bad Request
  {"error":"server_error","error_description":"Unexpected status: 400"}

Body:
Ok I will answer my own question now having found out the answer. My error was mis-use of POST.

This works, once I have the original authorization_code. The code will no longer be valid once "swapped" but that's a different issue.

bool getToken()
{
    Poco::URI loginURI( "https://accounts.spotify.com" );
    Poco::Net::HTTPSClientSession loginSession( loginURI.getHost(), loginURI.getPort(), context );
    Poco::Net::HTTPBasicCredentials credentials( clientId, clientSecret );

    loginSession.setKeepAlive( true );
    std::string requestStr( "https://accounts.spotify.com/api/token" );
    Poco::Net::HTTPRequest loginRequest( Poco::Net::HTTPRequest::HTTP_POST,
            requestStr,
            Poco::Net::HTTPMessage::HTTP_1_1 );
    loginRequest.setContentType("application/x-www-form-urlencoded");
    loginRequest.setKeepAlive( true );

    std::string grantType;
    std::string authCode;

    if( m_refreshToken.empty() )
    {
        grantType = "authorization_code";
        authCode = code;
    }
    else
    {
        grantType = "refresh_token";
        authCode = m_refreshToken;
    }
    std::ostringstream contentOStr;
    contentOStr << "grant_type=" << grantType <<
        "&code=" << authCode
        << "&redirect_uri=" << redirectURI;

    std::string contentStr = contentOStr.str();
    loginRequest.setContentLength( contentStr.size() );
    credentials.authenticate( loginRequest );

    std::ostream& requestOStr = loginSession.sendRequest( loginRequest );
    requestOStr << contentStr;
    requestOStr.flush();
    Poco::Net::HTTPResponse response;

    std::istream& rs = loginSession.receiveResponse( response );
    std::cout << "Login request ";
    loginRequest.write(std::cout);
    std::cout << std::endl;
    std::cout << "Login response status " << static_cast<int>(response.getStatus()) << ", "
            << response.getReason() << std::endl;

    std::string rsStr(std::istreambuf_iterator<char>(rs), {});
    if( rsStr.empty() )
    {
        std::cout << "No results" << std::endl;
        return false;
    }
    else
    {
        std::cout << "Logon response:\n" << rsStr << std::endl;
    }
    Parser parser;
    Var result;
    result = parser.parse(rsStr);
    Object::Ptr obj = result.extract<Object::Ptr>();
    try
    {
        Var tokenVar = obj->get( "access_token" );
        if( tokenVar.isString() )
        {
            m_token = tokenVar.convert< std::string >();
        }
        else
        {
            std::cerr << "Could not get access token" << std::endl;
            return false;
        }
        Var refreshTokenVar = obj->get( "refresh_token" );
        if( refreshTokenVar.isString() )
        {
            m_refreshToken = refreshTokenVar.convert< std::string >();
        }
        return true;
    }
    catch( const std::exception& err )
    {
        std::cerr << "Error getting login token" << err.what() << std::endl;
        return false;
    }
}


问:
TensorFlow not found using pip
I'm trying to install TensorFlow using pip:

$ pip install tensorflow --user
Collecting tensorflow
Could not find a version that satisfies the requirement tensorflow (from versions: )
No matching distribution found for tensorflow
```

What am I doing wrong? So far I've used Python and pip with no issues.

答:
Start Command Prompt with Administrative Permission

Enter following command     python -m pip install --upgrade pip

Next Enter command pip install tensorflow

ContentLicense: CC BY-SA 4.0

Title: TensorFlow not found using pip

Body:
I'm trying to install TensorFlow using pip:

$ pip install tensorflow --user
Collecting tensorflow
Could not find a version that satisfies the requirement tensorflow (from versions: )
No matching distribution found for tensorflow

What am I doing wrong? So far I've used Python and pip with no issues.


问:
Align Buttons with videoView using Constraint layout
I've been trying to make a similar login screen like Snapchat where the two buttons are at the bottom and theres a small video playing on the background layer. When I did everything the buttons do not position themselves where they are rather they go all over the emulator, and the video player is also misaligned.

The code for the login page is given below

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.test.test.Login">

<Button
    android:id="@+id/btnSignUp"
    android:layout_width="414dp"
    android:layout_height="89dp"
    android:text="SIGN UP"
    android:textSize="40sp"
    android:textStyle="bold"
    android:background="#FFD54F"
    android:textColor="#FAFAFA"
    tools:layout_editor_absoluteX="-24dp"
    tools:layout_editor_absoluteY="397dp" />

<Button
    android:id="@+id/btnLogin"
    android:layout_width="414dp"
    android:layout_height="89dp"
    android:fontFamily="sans-serif"
    android:lineSpacingExtra="10sp"
    android:text="Login"
    android:textSize="40sp"
    android:textStyle="bold"
    android:background="#80DEEA"
    android:textColor="#FAFAFA"
    tools:layout_editor_absoluteX="-15dp"
    tools:layout_editor_absoluteY="486dp" />

<VideoView
    android:id="@+id/bgVideoView"
    android:layout_width="394dp"
    android:layout_height="410dp"
    tools:layout_editor_absoluteX="-5dp"
    tools:layout_editor_absoluteY="0dp" />
</android.support.constraint.ConstraintLayout>
</code>```

What I want it to look like

Emulator Capture

答:
You are using ConstraintLayout as root element but you have given no constraints for your subviews. When you use ConstraintLayout try something like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/btnSignUp"
        android:layout_width="0dp"
        android:layout_height="89dp"
        android:background="#FFD54F"
        android:text="SIGN UP"
        android:textColor="#FAFAFA"
        android:textSize="40sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toTopOf="@+id/btnLogin"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        tools:ignore="HardcodedText"
        tools:layout_editor_absoluteX="-24dp"
        tools:layout_editor_absoluteY="397dp" />

    <Button
        android:id="@+id/btnLogin"
        android:layout_width="414dp"
        android:layout_height="89dp"
        android:background="#80DEEA"
        android:lineSpacingExtra="10sp"
        android:text="Login"
        android:textColor="#FAFAFA"
        android:textSize="40sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        tools:ignore="HardcodedText"
        tools:layout_editor_absoluteX="-15dp"
        tools:layout_editor_absoluteY="486dp" />

    <VideoView
        android:id="@+id/bgVideoView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:visibility="visible"
        app:layout_constraintBottom_toTopOf="@+id/btnSignUp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
</code>```

ConstraintLayout is more advance and flexable from RelativeLayout. Try learn more about it from here:

Build a Responsive UI with ConstraintLayout

Body:
I've been trying to make a similar login screen like Snapchat where the two buttons are at the bottom and theres a small video playing on the background layer. When I did everything the buttons do not position themselves where they are rather they go all over the emulator, and the video player is also misaligned.

The code for the login page is given below

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.test.test.Login">

<Button
    android:id="@+id/btnSignUp"
    android:layout_width="414dp"
    android:layout_height="89dp"
    android:text="SIGN UP"
    android:textSize="40sp"
    android:textStyle="bold"
    android:background="#FFD54F"
    android:textColor="#FAFAFA"
    tools:layout_editor_absoluteX="-24dp"
    tools:layout_editor_absoluteY="397dp" />

<Button
    android:id="@+id/btnLogin"
    android:layout_width="414dp"
    android:layout_height="89dp"
    android:fontFamily="sans-serif"
    android:lineSpacingExtra="10sp"
    android:text="Login"
    android:textSize="40sp"
    android:textStyle="bold"
    android:background="#80DEEA"
    android:textColor="#FAFAFA"
    tools:layout_editor_absoluteX="-15dp"
    tools:layout_editor_absoluteY="486dp" />

<VideoView
    android:id="@+id/bgVideoView"
    android:layout_width="394dp"
    android:layout_height="410dp"
    tools:layout_editor_absoluteX="-5dp"
    tools:layout_editor_absoluteY="0dp" />
</android.support.constraint.ConstraintLayout>

What I want it to look like

Emulator Capture

Body:
You are using ConstraintLayout as root element but you have given no constraints for your subviews. When you use ConstraintLayout try something like this:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/btnSignUp"
        android:layout_width="0dp"
        android:layout_height="89dp"
        android:background="#FFD54F"
        android:text="SIGN UP"
        android:textColor="#FAFAFA"
        android:textSize="40sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toTopOf="@+id/btnLogin"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        tools:ignore="HardcodedText"
        tools:layout_editor_absoluteX="-24dp"
        tools:layout_editor_absoluteY="397dp" />

    <Button
        android:id="@+id/btnLogin"
        android:layout_width="414dp"
        android:layout_height="89dp"
        android:background="#80DEEA"
        android:lineSpacingExtra="10sp"
        android:text="Login"
        android:textColor="#FAFAFA"
        android:textSize="40sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        tools:ignore="HardcodedText"
        tools:layout_editor_absoluteX="-15dp"
        tools:layout_editor_absoluteY="486dp" />

    <VideoView
        android:id="@+id/bgVideoView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:visibility="visible"
        app:layout_constraintBottom_toTopOf="@+id/btnSignUp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

ConstraintLayout is more advance and flexable from RelativeLayout. Try learn more about it from here:

Build a Responsive UI with ConstraintLayout


问:
C# Group by list by specific element to result a list of lists
I have a list of objects. Every object has these components: index, countNr, descA, descB.

How I can group by (maybe LINQ) this list by countNr value?

Like:

List = {(1,3,a1,b1), (2,2,a2,b2), (3,2,a3,b3), (4,1,a4,b4), (5,1,a5,b5), (6,1,a6,b6), (7,1,a7,b7)}

I want now to have another newList of lists, where the position in this list is indicating the countNr number, like:

```<code>newList = {{(7,1,a7,b7), (6,1,a6,b6), (5,1,a5,b5), (4,1,a4,b4)},  {(3,2,a3,b3), (2,2,a2,b2)},  {(1,3,a1,b1)}}
</code>```

答:
If your class, looks like this:

```<code>public class MyClass
{

    public MyClass(int index, int countNr, string descA, string descB)
    {
        Index = index;
        CountNr = countNr;
        DescA = descA;
        DescB = descB;
    }
    public int Index { get; set; }
    public int CountNr { get; set; }
    public string DescA { get; set; }
    public string DescB { get; set; }
}
</code>```

And this input:

```<code>var list = new List<MyClass> {
    new MyClass(1, 3, "a1", "b1"),
    new MyClass(2, 2, "a2", "b2"),
    new MyClass (3, 2, "a3", "b3"),
    new MyClass(4, 1, "a4", "b4"),
    new MyClass(5, 1, "a5", "b5"),
    new MyClass(6, 1, "a6", "b6"),
    new MyClass(7, 1, "a7", "b7") };
</code>```

You can try it:

```<code>var query = from r in list
    group r by new { r.CountNr } into grp
    orderby grp.Key.CountNr ascending
    select new
    {
        grp.Key.CountNr,
        grp
    };
</code>```

Then you have this :

```<code>foreach (var item in query)
{
    System.Diagnostics.Debug.WriteLine($"CountNr: {item.CountNr}"); //Key  or group
    //All rows of group
    foreach (var g in item.grp)
    {
        System.Diagnostics.Debug.WriteLine($"{g.Index} - {g.CountNr} - {g.DescA} - {g.DescB}");
    }
}
</code>```

And this result:

```<code>CountNr: 1
4 - 1 - a4 - b4
5 - 1 - a5 - b5
6 - 1 - a6 - b6
7 - 1 - a7 - b7
CountNr: 2
2 - 2 - a2 - b2
3 - 2 - a3 - b3
CountNr: 3
1 - 3 - a1 - b1
</code>```

If you need to order by index too. Try this:

```<code>var query = from r in list
    group r by new { r.CountNr } into grp
    orderby grp.Key.CountNr ascending
    select new
    {
        grp.Key.CountNr,
        grp =grp.OrderByDescending( c=> c.Index)
    };
</code>```

And you have this result:

```<code>CountNr: 1
7 - 1 - a7 - b7
6 - 1 - a6 - b6
5 - 1 - a5 - b5
4 - 1 - a4 - b4
CountNr: 2
3 - 2 - a3 - b3
2 - 2 - a2 - b2
CountNr: 3
1 - 3 - a1 - b1
</code>```

Att.

Body:
I have a list of objects. Every object has these components: index, countNr, descA, descB.

How I can group by (maybe LINQ) this list by countNr value?

Like:

List = {(1,3,a1,b1), (2,2,a2,b2), (3,2,a3,b3), (4,1,a4,b4), (5,1,a5,b5), (6,1,a6,b6), (7,1,a7,b7)}

I want now to have another newList of lists, where the position in this list is indicating the countNr number, like:

newList = {{(7,1,a7,b7), (6,1,a6,b6), (5,1,a5,b5), (4,1,a4,b4)},  {(3,2,a3,b3), (2,2,a2,b2)},  {(1,3,a1,b1)}}

Body:
If your class, looks like this:

public class MyClass
{

    public MyClass(int index, int countNr, string descA, string descB)
    {
        Index = index;
        CountNr = countNr;
        DescA = descA;
        DescB = descB;
    }
    public int Index { get; set; }
    public int CountNr { get; set; }
    public string DescA { get; set; }
    public string DescB { get; set; }
}

And this input:

var list = new List<MyClass> {
    new MyClass(1, 3, "a1", "b1"),
    new MyClass(2, 2, "a2", "b2"),
    new MyClass (3, 2, "a3", "b3"),
    new MyClass(4, 1, "a4", "b4"),
    new MyClass(5, 1, "a5", "b5"),
    new MyClass(6, 1, "a6", "b6"),
    new MyClass(7, 1, "a7", "b7") };

You can try it:

var query = from r in list
    group r by new { r.CountNr } into grp
    orderby grp.Key.CountNr ascending
    select new
    {
        grp.Key.CountNr,
        grp
    };

Then you have this :

foreach (var item in query)
{
    System.Diagnostics.Debug.WriteLine($"CountNr: {item.CountNr}"); //Key  or group
    //All rows of group
    foreach (var g in item.grp)
    {
        System.Diagnostics.Debug.WriteLine($"{g.Index} - {g.CountNr} - {g.DescA} - {g.DescB}");
    }
}

And this result:

CountNr: 1
4 - 1 - a4 - b4
5 - 1 - a5 - b5
6 - 1 - a6 - b6
7 - 1 - a7 - b7
CountNr: 2
2 - 2 - a2 - b2
3 - 2 - a3 - b3
CountNr: 3
1 - 3 - a1 - b1

If you need to order by index too. Try this:

var query = from r in list
    group r by new { r.CountNr } into grp
    orderby grp.Key.CountNr ascending
    select new
    {
        grp.Key.CountNr,
        grp =grp.OrderByDescending( c=> c.Index)
    };

And you have this result:

CountNr: 1
7 - 1 - a7 - b7
6 - 1 - a6 - b6
5 - 1 - a5 - b5
4 - 1 - a4 - b4
CountNr: 2
3 - 2 - a3 - b3
2 - 2 - a2 - b2
CountNr: 3
1 - 3 - a1 - b1

Att.