问:
Display a specific property from an array
I have an array of cars with different attributes. I have been trying to make a function that will display just the minivans when I press a button. I can't get anything to display when the button is pressed. I don't get any errors when I run the full program. Any tips on what I am doing wrong would be very helpful! </p>

```<code>// Define  car object using a constructor function
function Car(id, car_make, car_model, car_year, car_type, car_color,
car_price, car_mileage) {
    this.stockid = id;
    this.make = car_make;
    this.model = car_model;
    this.year = car_year;
    this.type = car_type;
    this.color = car_color;
    this.price = car_price;
    this.mileage = car_mileage;
}

// Declare an array of Car objects
var car_list = [];

// Create an instance of the Car object and add it to the car_list array
   car_list.push(new Car(1001, "Toyota", "Camry", 2011, "Sedan", "Gray",
      17555, 55060));
   car_list.push(new Car(1002, "Volvo", "s40", 2013, "Sedan", "Black",
      15575, 20350));
   car_list.push(new Car(1251, "Toyota", "Sienna", 2008, "Minivan", "Gray",
      15775, 70000));
   car_list.push(new Car(1321, "Porsche", "Panamera", 2012, "Hatchback",
      "Red", 104250, 10567));
   car_list.push(new Car(1904, "Honda", "Accord", 2009, "Sedan", "White",
      13370, 35000));
   car_list.push(new Car(1855, "Toyota", "Highlander", 2008, "SUV",
      "Silver", 18555, 55060));
   car_list.push(new Car(1543, "Ford", "Fusion", 2011, "Sedan", "Black",
      13575, 90350));
   car_list.push(new Car(1345, "Toyota", "Sienna", 2011, "Minivan", "Gray",
      25775, 70000));
   car_list.push(new Car(2133, "Dodge", "Caravan", 2012, "Minivan", "Red",
      30250, 17567));
   car_list.push(new Car(2999, "Lexus", "LFA", 2012, "coupe", "Red", 381370,
      3500));
   car_list.push(new Car(3001, "Ferrari", "Rubino", 2012, "coupe", "Red",
      354370, 5500));
   car_list.push(new Car(4002, "Audi", "R8", 2012, "convertible", "Black",
      181370, 4500));
// Display car list

for (var i=0; i<car_list.length; i++){
    var this_element = "<tr class='car-item' id='l-"+i+"' >" ;
    this_element += "<td>" + car_list[i].stockid + "</td><td>" +
car_list[i].make + "</td>";
    this_element += "<td>" + car_list[i].model + "</td><td>" +
car_list[i].year + "</td><td>" + car_list[i].type + "</td>";
    this_element += "<td>" + car_list[i].color + "</td><td> $" +
car_list[i].price + "</td>";
    this_element += "<td>" + car_list[i].mileage + "</td>";
    this_element += "<td><button type='button'  data-index='"+i+"'
class='addme btn btn-primary' ";
    this_element +=  "data-stockid='"+ car_list[i].stockid + "'>Add</button>
</td></tr>";

    $("#car-list").append(this_element);
}

//display minivans
$('#p3').on('click', function(){

  if(type = "Minivan"){

     var thisButton = $(this);
     var index = thisButton.data('index');
     var thisCar = car_list[index];

  var newRow = "<tr><td>"+ thisCar.stockid + "</td><td>" + thisCar.make + "
  </td><td>" + thisCar.model + "</td><td>" + thisCar.year +
    "</td><td>" + thisCar.type + "</td><td>" + thisCar.color + "</td><td>" +
     thisCar.price + "</td><td>" + thisCar.mileage + "</td></tr>";

  $('#minivan-list').append(newRow);
 }

});
</code>```

答:
If you want to get the list of type 'Minivan', you have to loop thru your car_list  array.

```<code>for ( var key in car_list ) {
    if ( car_list[ key ].type == "Minivan" ) console.log( car_list[ key ] );
}
</code>```

If you want to append all the minivans to #minivan-list

```<code>var html = ""

for ( var key in car_list ) {
    if ( car_list[ key ].type == "Minivan" ) {
        html += "<tr><td>"+ car_list[ key ].stockid + "</td><td>" + car_list[ key ].make + "</td><td>" + car_list[ key ].model + "</td><td>" + car_list[ key ].year + "</td><td>" + car_list[ key ].type + "</td><td>" + car_list[ key ].color + "</td><td>" + car_list[ key ].price + "</td><td>" + car_list[ key ].mileage + "</td></tr>";
    }
}

$('#minivan-list').append( html );
</code>```

Body:
I have an array of cars with different attributes. I have been trying to make a function that will display just the minivans when I press a button. I can't get anything to display when the button is pressed. I don't get any errors when I run the full program. Any tips on what I am doing wrong would be very helpful!

// Define  car object using a constructor function
function Car(id, car_make, car_model, car_year, car_type, car_color,
car_price, car_mileage) {
    this.stockid = id;
    this.make = car_make;
    this.model = car_model;
    this.year = car_year;
    this.type = car_type;
    this.color = car_color;
    this.price = car_price;
    this.mileage = car_mileage;
}

// Declare an array of Car objects
var car_list = [];

// Create an instance of the Car object and add it to the car_list array
   car_list.push(new Car(1001, "Toyota", "Camry", 2011, "Sedan", "Gray",
      17555, 55060));
   car_list.push(new Car(1002, "Volvo", "s40", 2013, "Sedan", "Black",
      15575, 20350));
   car_list.push(new Car(1251, "Toyota", "Sienna", 2008, "Minivan", "Gray",
      15775, 70000));
   car_list.push(new Car(1321, "Porsche", "Panamera", 2012, "Hatchback",
      "Red", 104250, 10567));
   car_list.push(new Car(1904, "Honda", "Accord", 2009, "Sedan", "White",
      13370, 35000));
   car_list.push(new Car(1855, "Toyota", "Highlander", 2008, "SUV",
      "Silver", 18555, 55060));
   car_list.push(new Car(1543, "Ford", "Fusion", 2011, "Sedan", "Black",
      13575, 90350));
   car_list.push(new Car(1345, "Toyota", "Sienna", 2011, "Minivan", "Gray",
      25775, 70000));
   car_list.push(new Car(2133, "Dodge", "Caravan", 2012, "Minivan", "Red",
      30250, 17567));
   car_list.push(new Car(2999, "Lexus", "LFA", 2012, "coupe", "Red", 381370,
      3500));
   car_list.push(new Car(3001, "Ferrari", "Rubino", 2012, "coupe", "Red",
      354370, 5500));
   car_list.push(new Car(4002, "Audi", "R8", 2012, "convertible", "Black",
      181370, 4500));
// Display car list

for (var i=0; i<car_list.length; i++){
    var this_element = "
" ;
    this_element += "" + car_list[i].stockid + "	" +
car_list[i].make + "	";
    this_element += "" + car_list[i].model + "	" +
car_list[i].year + "	" + car_list[i].type + "	";
    this_element += "" + car_list[i].color + "	 $" +
car_list[i].price + "	";
    this_element += "" + car_list[i].mileage + "	";
    this_element += "<button type='button'  data-index='"+i+"'
class='addme btn btn-primary' ";
    this_element +=  "data-stockid='"+ car_list[i].stockid + "'>Add</button>

";

    $("#car-list").append(this_element);
}

//display minivans
$('#p3').on('click', function(){

  if(type = "Minivan"){

     var thisButton = $(this);
     var index = thisButton.data('index');
     var thisCar = car_list[index];

  var newRow = "
"+ thisCar.stockid + "	" + thisCar.make + "
  	" + thisCar.model + "	" + thisCar.year +
    "	" + thisCar.type + "	" + thisCar.color + "	" +
     thisCar.price + "	" + thisCar.mileage + "
";

  $('#minivan-list').append(newRow);
 }

});

Body:
If you want to get the list of type 'Minivan', you have to loop thru your car_list  array.

for ( var key in car_list ) {
    if ( car_list[ key ].type == "Minivan" ) console.log( car_list[ key ] );
}

If you want to append all the minivans to #minivan-list

var html = ""

for ( var key in car_list ) {
    if ( car_list[ key ].type == "Minivan" ) {
        html += "<tr><td>"+ car_list[ key ].stockid + "</td><td>" + car_list[ key ].make + "</td><td>" + car_list[ key ].model + "</td><td>" + car_list[ key ].year + "</td><td>" + car_list[ key ].type + "</td><td>" + car_list[ key ].color + "</td><td>" + car_list[ key ].price + "</td><td>" + car_list[ key ].mileage + "</td></tr>";
    }
}

$('#minivan-list').append( html );


来源: stackexchange

问:
Check multiple columns for value, replace with NA if not found in R
I have a data.frame like this:

```<code>#df1
ID     a1      a2     a3      b1      b2      b3     Date    Name
3xy    NA      NA     NA     Ben      Bob     Alex   12/3    Bob
4lm    John    Bill   Sue    NA       NA      NA     12/5    Mark
</code>```

I want those in the "name" column to be replaced by NA if they don't appear in any of the a1 through b3 columns in their row, like this:

```<code>ID     a1      a2     a3      b1      b2      b3     Date    Name
3xy    NA      NA     NA     Ben      Bob     Alex   12/3    Bob
4lm    John    Bill   Sue    NA       NA      NA     12/5    NA
</code>```

I can't figure out why what's below doesn't work:

```<code>df1$Name <- with(df1, ifelse(Name %in% df1[2:7], Name, NA))
</code>```

or

```<code>df1$Name[!(df1$Name %in% df1[2:7])] <- NA
</code>```

Both statements replace the entire "Name" column with NA, failing to preserve the names that appear in columns a1 through b3.

答:
We can use rowSums to assign the value of 'Name' column to NA if there is no TRUE elements in any of the columns for each row

```<code>df1$Name[!rowSums(t(t(df1[2:7] ) == df1$Name), na.rm = TRUE)] <- NA
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a data.frame like this:

#df1
ID     a1      a2     a3      b1      b2      b3     Date    Name
3xy    NA      NA     NA     Ben      Bob     Alex   12/3    Bob
4lm    John    Bill   Sue    NA       NA      NA     12/5    Mark

I want those in the "name" column to be replaced by NA if they don't appear in any of the a1 through b3 columns in their row, like this:

ID     a1      a2     a3      b1      b2      b3     Date    Name
3xy    NA      NA     NA     Ben      Bob     Alex   12/3    Bob
4lm    John    Bill   Sue    NA       NA      NA     12/5    NA

I can't figure out why what's below doesn't work:

df1$Name <- with(df1, ifelse(Name %in% df1[2:7], Name, NA))

or

df1$Name[!(df1$Name %in% df1[2:7])] <- NA

Both statements replace the entire "Name" column with NA, failing to preserve the names that appear in columns a1 through b3.

Body:
We can use rowSums to assign the value of 'Name' column to NA if there is no TRUE elements in any of the columns for each row

df1$Name[!rowSums(t(t(df1[2:7] ) == df1$Name), na.rm = TRUE)] <- NA


问:
why we cannot use "=" to shared_ptr or unique_ptr?
I fount the syntax got compile error.

```<code>std::shared_ptr<int> p = new int(5);

31 41 E:\temprory (delete it if u like)\1208.cpp [Error] conversion from 'int*' to non-scalar type 'std::shared_ptr<int>' requested
</code>```

But it is O.K

```<code>std::shared_ptr<int> p(new int(5));
</code>```

The same as unique_ptr;

But I don't know why it is prohibited.

答:
The constructor of std::shared_ptr and std::unique_ptr taking raw pointer are explicit; std::shared_ptr<int> p = new int(5); is copy initialization, which doesn't consider explicit constructors.

Copy-initialization is less permissive than direct-initialization: explicit constructors are not converting constructors and are not considered for copy-initialization.

For direct initialization, explicit constructors are considered then std::shared_ptr<int> p(new int(5)); works fine.

Why the constructor is explicit?

To prevent unintentional implicit conversion and ownership transfer. e.g.

```<code>void foo(std::unique_ptr<int> p) { ... }
</code>```

then

```<code>int* pi = new int(5);
foo(pi); // if implicit conversion is allowed, the ownership will be transfered to the parameter p
// then when get out of foo pi is destroyed, and can't be used again
</code>```

Body:
I fount the syntax got compile error.

std::shared_ptr<int> p = new int(5);

31 41 E:\temprory (delete it if u like)\1208.cpp [Error] conversion from 'int*' to non-scalar type 'std::shared_ptr<int>' requested

But it is O.K

std::shared_ptr<int> p(new int(5));

The same as unique_ptr;

But I don't know why it is prohibited.

Body:
The constructor of std::shared_ptr and std::unique_ptr taking raw pointer are explicit; std::shared_ptr<int> p = new int(5); is copy initialization, which doesn't consider explicit constructors.

Copy-initialization is less permissive than direct-initialization: explicit constructors are not converting constructors and are not considered for copy-initialization.

For direct initialization, explicit constructors are considered then std::shared_ptr<int> p(new int(5)); works fine.

Why the constructor is explicit?

To prevent unintentional implicit conversion and ownership transfer. e.g.

void foo(std::unique_ptr<int> p) { ... }

then

int* pi = new int(5);
foo(pi); // if implicit conversion is allowed, the ownership will be transfered to the parameter p
// then when get out of foo pi is destroyed, and can't be used again


问:
match(join) two dataframe using regular expression in r
I need to match two dataframe, but there id is not exactly the same. id2 maybe longer, but contains all characters in id1. how do I left_join two table without losing information. for example 182219556 and 485182219556 are deemed as the same.

```<code>library(tidyverse)
data1 <- tibble(id = c(175642619,172881781,182219556,41925997,201404118),
            case_id=c(2746306,2746823,2749855,2749933,2750222))

data2 <- tibble(id = c(175642619,172881781568,485182219556,41925997,201404118),
            case_id2=c(2746306,2746823,2749855,2749933,2750222))

left_join(data1, data2)
</code>```

答:
You can do this using fuzzyjoin library. There is stringdist_left_join which is a left join based on a distance between two strings. In your case, I put max_dist equal to 3. Meaning that, two strings are deemed as same allowing maximum distance up to 3 characters between two strings which is your case.

```<code>library(fuzzyjoin)
stringdist_left_join(data1, data2, by ="id", max_dist = 3)

#       id.x  case_id         id.y  case_id2
#1 175642619  2746306    175642619   2746306
#2 172881781  2746823 172881781568   2746823
#3 182219556  2749855 485182219556   2749855
#4 41925997   2749933     41925997   2749933
#5 201404118  2750222    201404118   2750222
</code>```

Body:
I need to match two dataframe, but there id is not exactly the same. id2 maybe longer, but contains all characters in id1. how do I left_join two table without losing information. for example 182219556 and 485182219556 are deemed as the same.

library(tidyverse)
data1 <- tibble(id = c(175642619,172881781,182219556,41925997,201404118),
            case_id=c(2746306,2746823,2749855,2749933,2750222))

data2 <- tibble(id = c(175642619,172881781568,485182219556,41925997,201404118),
            case_id2=c(2746306,2746823,2749855,2749933,2750222))

left_join(data1, data2)

Body:
You can do this using fuzzyjoin library. There is stringdist_left_join which is a left join based on a distance between two strings. In your case, I put max_dist equal to 3. Meaning that, two strings are deemed as same allowing maximum distance up to 3 characters between two strings which is your case.

library(fuzzyjoin)
stringdist_left_join(data1, data2, by ="id", max_dist = 3)

#       id.x  case_id         id.y  case_id2
#1 175642619  2746306    175642619   2746306
#2 172881781  2746823 172881781568   2746823
#3 182219556  2749855 485182219556   2749855
#4 41925997   2749933     41925997   2749933
#5 201404118  2750222    201404118   2750222


问:
Conf files and static files in a deb package
I'm using dh_help to build a package template and trying to follow the ubuntu and debian packaging guides for creating a binary package.

How do I tell debuild which file is a conf file and should go for example to /etc/mypkg.conf ?
I've tried to put it under mypkg-0.1/etc/mypkg/fname.conf but debuild ignores it.
The debian guide says all files under etc/ are treated automatically as conf files but it doesn't work for me (http://www.debian.org/doc/maint-guid...ml#s-conffiles).
I've tried putting the conf file under mypkg-1.0/etc/mypkg.conf and under mypkg-1.0/debain/etc/mypkg.conf but it is not included. I also tried to list the file in conffiles but I'm getting an error that it can't be found when building the package.

I also don't understand how to include static files in the package.
Do I have to use the install file to list all the files and folders?
I thought that putting everything with the full path under the mypkgs-0.1 folder should work like it does when using dpkg manually.

Thanks

答:
You don't have to include the package version if you install files via the standard debhelper / debian/rules file. Instead, in the install step do:

```<code>install -cm 644 fname.conf $(CURDIR)/debian/mypkg/etc/mypkg/fname.conf
</code>```

And it should be included properly.

ContentLicense: CC BY-SA 2.5

Body:
You don't have to include the package version if you install files via the standard debhelper / debian/rules file. Instead, in the install step do:

install -cm 644 fname.conf $(CURDIR)/debian/mypkg/etc/mypkg/fname.conf

And it should be included properly.


问:
MariaDB: ERROR 2013 (HY000): Lost connection persists only for one database
I have several databases:

   - curr

   - curr_add

and many others on the same MariaDB instance. When I submit an sql to curr_add I get connection and the results. When I send the query to curr I get the error:

MariaDB: ERROR 2013 (HY000): Lost connection to MySQL server during query

and the service stops. When I restart the service each time I want to access the database curr the serivice stops. This is not the case for all other databases of the same instance. The instance and databases exists since one year and I had never such problems. Is there a way to find out what is the problem and how to solve it?

Working environment:

Windows 7

MariaDB 10.2.6

I entered as root: mysql -uroot -h localhost -p

Update (1):

I have access to database information_schema. For example, I can count the rows of table system_variables: SELECT COUNT(*) FROM system_variables. But if I try the same with table columns: SELECT COUNT(*) FROM columns, the connection will be lost (see figure).

I submit:

SELECT COUNT(*) FROM tables

or

SELECT table_schema, table_name FROM tables

I get results.

But if I submit

SELECT * FROM tables

or

SELECT table_schema, table_name, engine, table_rows FROM tables LIMIT 10

the connection will be lost.

Summary: some database disconnect the mysql-server and also some columns of tables.

Update (2): error informations from file .err

```<code>The manual page at http://dev.mysql.com/doc/mysql/en/crashing.html contains
information that should help you find out what is causing the crash.
2017-11-28 19:42:43 7820 [Note] InnoDB: Mutexes and rw_locks use Windows interlocked functions
2017-11-28 19:42:43 7820 [Note] InnoDB: Uses event mutexes
2017-11-28 19:42:43 7820 [Note] InnoDB: Compressed tables use zlib 1.2.3
2017-11-28 19:42:43 7820 [Note] InnoDB: Number of pools: 1
2017-11-28 19:42:43 7820 [Note] InnoDB: Using generic crc32 instructions
2017-11-28 19:42:43 7820 [Note] InnoDB: Initializing buffer pool, total size = 14G, instances = 8, chunk size = 128M
2017-11-28 19:42:44 7820 [Note] InnoDB: Completed initialization of buffer pool
2017-11-28 19:42:44 7820 [Note] InnoDB: Highest supported file format is Barracuda.
2017-11-28 19:42:44 7820 [Note] InnoDB: Starting crash recovery from checkpoint LSN=556718604758
2017-11-28 19:42:52 7820 [Note] InnoDB: 128 out of 128 rollback segments are active.
2017-11-28 19:42:52 7820 [Note] InnoDB: Removed temporary tablespace data file: "ibtmp1"
2017-11-28 19:42:52 7820 [Note] InnoDB: Creating shared tablespace for temporary tables
2017-11-28 19:42:52 7820 [Note] InnoDB: Setting file '.\ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
2017-11-28 19:42:52 7820 [Note] InnoDB: File '.\ibtmp1' size is now 12 MB.
2017-11-28 19:42:52 7820 [Note] InnoDB: 5.7.14 started; log sequence number 556718604767
2017-11-28 19:42:52 4868 [Note] InnoDB: page_cleaner: 1000ms intended loop took 7784ms. The settings might not be optimal. (flushed=0 and evicted=0, during the time.)
2017-11-28 19:42:52 7380 [Note] InnoDB: Loading buffer pool(s) from C:\Program Files\MariaDB 10.2\data\ib_buffer_pool
2017-11-28 19:42:52 7820 [Note] Server socket created on IP: '::'.
2017-11-28 19:42:52 7820 [Note] Reading of all Master_info entries succeded
2017-11-28 19:42:52 7820 [Note] Added new Master_info '' to hash table
2017-11-28 19:42:52 7820 [Note] C:\Program Files\MariaDB 10.2\bin\mysqld.exe: ready for connections.
Version: '10.2.6-MariaDB'  socket: ''  port: 3306  mariadb.org binary distribution
2017-11-28 19:44:08 7380 [Note] InnoDB: Buffer pool(s) load completed at 171128 19:44:08
2017-11-28 19:44:20 9820 [Warning] InnoDB: Retry attempts for reading partial data failed.
2017-11-28 19:44:20 9820 [ERROR] InnoDB: Tried to read 16384 bytes at offset 4947968, but was only able to read 0
2017-11-28 19:44:20 9820 [ERROR] InnoDB: File (unknown): 'read' returned OS error 0. Cannot continue operation
171128 19:44:20 [ERROR] mysqld got exception 0x80000003 ;
This could be because you hit a bug. It is also possible that this binary
or one of the libraries it was linked against is corrupt, improperly built,
or misconfigured. This error can also be caused by malfunctioning hardware.

To report this bug, see https://mariadb.com/kb/en/reporting-bugs

We will try our best to scrape up some info that will hopefully help
diagnose the problem, but since we have already crashed,
something is definitely wrong and this may fail.

Server version: 10.2.6-MariaDB
key_buffer_size=134217728
read_buffer_size=131072
max_used_connections=1
max_threads=65537
thread_count=7
It is possible that mysqld could use up to
key_buffer_size + (read_buffer_size + sort_buffer_size)*max_threads = 136026 K  bytes of memory
Hope that's ok; if not, decrease some variables in the equation.

Thread pointer: 0x7d1b9fd8
Attempting backtrace. You can use the following information to find out
where mysqld died. If you see no messages after this, something went
terribly wrong...
mysqld.exe!my_parameter_handler()[my_init.c:259]
mysqld.exe!raise()[signal.cpp:516]
mysqld.exe!abort()[abort.cpp:71]
mysqld.exe!os_file_handle_error_cond_exit()[os0file.cc:5209]
mysqld.exe!os_file_read_page()[os0file.cc:5091]
mysqld.exe!os_file_read_func()[os0file.cc:5433]
mysqld.exe!fil_io()[fil0fil.cc:5436]
mysqld.exe!buf_read_page_low()[buf0rea.cc:179]
mysqld.exe!buf_read_page()[buf0rea.cc:436]
mysqld.exe!buf_page_get_gen()[buf0buf.cc:4267]
mysqld.exe!btr_cur_search_to_nth_level()[btr0cur.cc:1115]
mysqld.exe!btr_pcur_open_low()[btr0pcur.ic:457]
mysqld.exe!btr_pcur_open_on_user_rec_func()[btr0pcur.cc:597]
mysqld.exe!dict_load_foreign()[dict0load.cc:3334]
mysqld.exe!dict_load_foreigns()[dict0load.cc:3587]
mysqld.exe!dict_load_table_one()[dict0load.cc:2958]
mysqld.exe!dict_load_table()[dict0load.cc:2670]
mysqld.exe!dict_table_open_on_name()[dict0dict.cc:1174]
mysqld.exe!ha_innobase::open_dict_table()[ha_innodb.cc:6976]
mysqld.exe!ha_innobase::open()[ha_innodb.cc:6618]
mysqld.exe!handler::ha_open()[handler.cc:2507]
mysqld.exe!open_table_from_share()[table.cc:3278]
mysqld.exe!open_table()[sql_base.cc:1874]
mysqld.exe!open_and_process_table()[sql_base.cc:3409]
mysqld.exe!open_tables()[sql_base.cc:3926]
mysqld.exe!open_and_lock_tables()[sql_base.cc:4682]
mysqld.exe!execute_sqlcom_select()[sql_parse.cc:6352]
mysqld.exe!mysql_execute_command()[sql_parse.cc:3448]
mysqld.exe!mysql_parse()[sql_parse.cc:7879]
mysqld.exe!dispatch_command()[sql_parse.cc:1814]
mysqld.exe!do_command()[sql_parse.cc:1361]
mysqld.exe!threadpool_process_request()[threadpool_common.cc:346]
mysqld.exe!tp_callback()[threadpool_common.cc:192]
ntdll.dll!TpPostWork()
ntdll.dll!RtlRealSuccessor()
kernel32.dll!BaseThreadInitThunk()
ntdll.dll!RtlUserThreadStart()

Trying to get some variables.
Some pointers may be invalid and cause the dump to abort.
Query (0x78b38ff0): SELECT COUNT(*) FROM curr.patient
Connection ID (thread ID): 9
Status: NOT_KILLED

Optimizer switch: index_merge=on,index_merge_union=on,index_merge_sort_union=on,index_merge_intersection=on,index_merge_sort_intersection=off,engine_condition_pushdown=off,index_condition_pushdown=on,derived_merge=on,derived_with_keys=on,firstmatch=on,loosescan=on,materialization=on,in_to_exists=on,semijoin=on,partial_match_rowid_merge=on,partial_match_table_scan=on,subquery_cache=on,mrr=off,mrr_cost_based=off,mrr_sort_keys=off,outer_join_with_cache=on,semijoin_with_cache=on,join_cache_incremental=on,join_cache_hashed=on,join_cache_bka=on,optimize_join_buffer_size=off,table_elimination=on,extended_keys=on,exists_to_in=on,orderby_uses_equalities=on,condition_pushdown_for_derived=on

The manual page at http://dev.mysql.com/doc/mysql/en/crashing.html contains
information that should help you find out what is causing the crash.
</code>```

答:
I wanted to reinstall MariaDB. When I started deinstall/change of MaridaDB through the application wizard of Window 7 it asked if I wanted to Change/Repair/Remove. I decided to repair. After that MariaDB worked as usual. That is I could submit queries without losing connection.

Upgrade from MariaDB from 10.2.6 to 10.2.11 didn't help. Repair allowed me to be successful.

Lesson learned: Before asking SO do repair MariaDB.

Body:
I have several databases:

   - curr

   - curr_add

and many others on the same MariaDB instance. When I submit an sql to curr_add I get connection and the results. When I send the query to curr I get the error:

MariaDB: ERROR 2013 (HY000): Lost connection to MySQL server during query

and the service stops. When I restart the service each time I want to access the database curr the serivice stops. This is not the case for all other databases of the same instance. The instance and databases exists since one year and I had never such problems. Is there a way to find out what is the problem and how to solve it?

Working environment:

Windows 7

MariaDB 10.2.6

I entered as root: mysql -uroot -h localhost -p

Update (1):

I have access to database information_schema. For example, I can count the rows of table system_variables: SELECT COUNT(*) FROM system_variables. But if I try the same with table columns: SELECT COUNT(*) FROM columns, the connection will be lost (see figure).

I submit:

SELECT COUNT(*) FROM tables

or

SELECT table_schema, table_name FROM tables

I get results.

But if I submit

SELECT * FROM tables

or

SELECT table_schema, table_name, engine, table_rows FROM tables LIMIT 10

the connection will be lost.

Summary: some database disconnect the mysql-server and also some columns of tables.

Update (2): error informations from file .err

The manual page at http://dev.mysql.com/doc/mysql/en/crashing.html contains
information that should help you find out what is causing the crash.
2017-11-28 19:42:43 7820 [Note] InnoDB: Mutexes and rw_locks use Windows interlocked functions
2017-11-28 19:42:43 7820 [Note] InnoDB: Uses event mutexes
2017-11-28 19:42:43 7820 [Note] InnoDB: Compressed tables use zlib 1.2.3
2017-11-28 19:42:43 7820 [Note] InnoDB: Number of pools: 1
2017-11-28 19:42:43 7820 [Note] InnoDB: Using generic crc32 instructions
2017-11-28 19:42:43 7820 [Note] InnoDB: Initializing buffer pool, total size = 14G, instances = 8, chunk size = 128M
2017-11-28 19:42:44 7820 [Note] InnoDB: Completed initialization of buffer pool
2017-11-28 19:42:44 7820 [Note] InnoDB: Highest supported file format is Barracuda.
2017-11-28 19:42:44 7820 [Note] InnoDB: Starting crash recovery from checkpoint LSN=556718604758
2017-11-28 19:42:52 7820 [Note] InnoDB: 128 out of 128 rollback segments are active.
2017-11-28 19:42:52 7820 [Note] InnoDB: Removed temporary tablespace data file: "ibtmp1"
2017-11-28 19:42:52 7820 [Note] InnoDB: Creating shared tablespace for temporary tables
2017-11-28 19:42:52 7820 [Note] InnoDB: Setting file '.\ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
2017-11-28 19:42:52 7820 [Note] InnoDB: File '.\ibtmp1' size is now 12 MB.
2017-11-28 19:42:52 7820 [Note] InnoDB: 5.7.14 started; log sequence number 556718604767
2017-11-28 19:42:52 4868 [Note] InnoDB: page_cleaner: 1000ms intended loop took 7784ms. The settings might not be optimal. (flushed=0 and evicted=0, during the time.)
2017-11-28 19:42:52 7380 [Note] InnoDB: Loading buffer pool(s) from C:\Program Files\MariaDB 10.2\data\ib_buffer_pool
2017-11-28 19:42:52 7820 [Note] Server socket created on IP: '::'.
2017-11-28 19:42:52 7820 [Note] Reading of all Master_info entries succeded
2017-11-28 19:42:52 7820 [Note] Added new Master_info '' to hash table
2017-11-28 19:42:52 7820 [Note] C:\Program Files\MariaDB 10.2\bin\mysqld.exe: ready for connections.
Version: '10.2.6-MariaDB'  socket: ''  port: 3306  mariadb.org binary distribution
2017-11-28 19:44:08 7380 [Note] InnoDB: Buffer pool(s) load completed at 171128 19:44:08
2017-11-28 19:44:20 9820 [Warning] InnoDB: Retry attempts for reading partial data failed.
2017-11-28 19:44:20 9820 [ERROR] InnoDB: Tried to read 16384 bytes at offset 4947968, but was only able to read 0
2017-11-28 19:44:20 9820 [ERROR] InnoDB: File (unknown): 'read' returned OS error 0. Cannot continue operation
171128 19:44:20 [ERROR] mysqld got exception 0x80000003 ;
This could be because you hit a bug. It is also possible that this binary
or one of the libraries it was linked against is corrupt, improperly built,
or misconfigured. This error can also be caused by malfunctioning hardware.

To report this bug, see https://mariadb.com/kb/en/reporting-bugs

We will try our best to scrape up some info that will hopefully help
diagnose the problem, but since we have already crashed,
something is definitely wrong and this may fail.

Server version: 10.2.6-MariaDB
key_buffer_size=134217728
read_buffer_size=131072
max_used_connections=1
max_threads=65537
thread_count=7
It is possible that mysqld could use up to
key_buffer_size + (read_buffer_size + sort_buffer_size)*max_threads = 136026 K  bytes of memory
Hope that's ok; if not, decrease some variables in the equation.

Thread pointer: 0x7d1b9fd8
Attempting backtrace. You can use the following information to find out
where mysqld died. If you see no messages after this, something went
terribly wrong...
mysqld.exe!my_parameter_handler()[my_init.c:259]
mysqld.exe!raise()[signal.cpp:516]
mysqld.exe!abort()[abort.cpp:71]
mysqld.exe!os_file_handle_error_cond_exit()[os0file.cc:5209]
mysqld.exe!os_file_read_page()[os0file.cc:5091]
mysqld.exe!os_file_read_func()[os0file.cc:5433]
mysqld.exe!fil_io()[fil0fil.cc:5436]
mysqld.exe!buf_read_page_low()[buf0rea.cc:179]
mysqld.exe!buf_read_page()[buf0rea.cc:436]
mysqld.exe!buf_page_get_gen()[buf0buf.cc:4267]
mysqld.exe!btr_cur_search_to_nth_level()[btr0cur.cc:1115]
mysqld.exe!btr_pcur_open_low()[btr0pcur.ic:457]
mysqld.exe!btr_pcur_open_on_user_rec_func()[btr0pcur.cc:597]
mysqld.exe!dict_load_foreign()[dict0load.cc:3334]
mysqld.exe!dict_load_foreigns()[dict0load.cc:3587]
mysqld.exe!dict_load_table_one()[dict0load.cc:2958]
mysqld.exe!dict_load_table()[dict0load.cc:2670]
mysqld.exe!dict_table_open_on_name()[dict0dict.cc:1174]
mysqld.exe!ha_innobase::open_dict_table()[ha_innodb.cc:6976]
mysqld.exe!ha_innobase::open()[ha_innodb.cc:6618]
mysqld.exe!handler::ha_open()[handler.cc:2507]
mysqld.exe!open_table_from_share()[table.cc:3278]
mysqld.exe!open_table()[sql_base.cc:1874]
mysqld.exe!open_and_process_table()[sql_base.cc:3409]
mysqld.exe!open_tables()[sql_base.cc:3926]
mysqld.exe!open_and_lock_tables()[sql_base.cc:4682]
mysqld.exe!execute_sqlcom_select()[sql_parse.cc:6352]
mysqld.exe!mysql_execute_command()[sql_parse.cc:3448]
mysqld.exe!mysql_parse()[sql_parse.cc:7879]
mysqld.exe!dispatch_command()[sql_parse.cc:1814]
mysqld.exe!do_command()[sql_parse.cc:1361]
mysqld.exe!threadpool_process_request()[threadpool_common.cc:346]
mysqld.exe!tp_callback()[threadpool_common.cc:192]
ntdll.dll!TpPostWork()
ntdll.dll!RtlRealSuccessor()
kernel32.dll!BaseThreadInitThunk()
ntdll.dll!RtlUserThreadStart()

Trying to get some variables.
Some pointers may be invalid and cause the dump to abort.
Query (0x78b38ff0): SELECT COUNT(*) FROM curr.patient
Connection ID (thread ID): 9
Status: NOT_KILLED

Optimizer switch: index_merge=on,index_merge_union=on,index_merge_sort_union=on,index_merge_intersection=on,index_merge_sort_intersection=off,engine_condition_pushdown=off,index_condition_pushdown=on,derived_merge=on,derived_with_keys=on,firstmatch=on,loosescan=on,materialization=on,in_to_exists=on,semijoin=on,partial_match_rowid_merge=on,partial_match_table_scan=on,subquery_cache=on,mrr=off,mrr_cost_based=off,mrr_sort_keys=off,outer_join_with_cache=on,semijoin_with_cache=on,join_cache_incremental=on,join_cache_hashed=on,join_cache_bka=on,optimize_join_buffer_size=off,table_elimination=on,extended_keys=on,exists_to_in=on,orderby_uses_equalities=on,condition_pushdown_for_derived=on

The manual page at http://dev.mysql.com/doc/mysql/en/crashing.html contains
information that should help you find out what is causing the crash.


问:
How split a string in java and assign a hyperlink to each separated value
I am getting the following from DB with the respective id's as shown in the below picture:

I need to separate the location_names with their respective location id's so that I can update each location individually.
Finally I need something like this:

```<code> <a href="updateLocation/1">loc1</a>
 <a href="updateLocation/2">loc2</a>
</code>```

答:
If location id  size and  location  name size both are equal then you can try following code snippet </p>

```<code>    String ids = "1,2,3,4,5";
    String locations = "loc1,loc2,loc3,loc4,loc5";

    String[] idArr = ids.split(",");
    String[] locationArr = locations.split(",");

    Map<String, String> data = new HashMap<>();

    for (int i = 0; i <= locationArr.length - 1; i++) {
        data.put(idArr[i], locationArr[i]);

        System.out.println("<a href=" + "updateLocation/" + idArr[i] + ">" + locationArr[i] + "</a>");

    }
    System.out.println("-----map data--------" + data);
</code>```

Body:
I am getting the following from DB with the respective id's as shown in the below picture:

I need to separate the location_names with their respective location id's so that I can update each location individually.
Finally I need something like this:

 loc1
 loc2

Body:
If location id  size and  location  name size both are equal then you can try following code snippet

    String ids = "1,2,3,4,5";
    String locations = "loc1,loc2,loc3,loc4,loc5";

    String[] idArr = ids.split(",");
    String[] locationArr = locations.split(",");

    Map<String, String> data = new HashMap<>();

    for (int i = 0; i <= locationArr.length - 1; i++) {
        data.put(idArr[i], locationArr[i]);

        System.out.println("<a href=" + "updateLocation/" + idArr[i] + ">" + locationArr[i] + "</a>");

    }
    System.out.println("-----map data--------" + data);


问:
Automatic Versioning in TFS Build
I am not sure whether i can the problem good explaning. Well we use TFS for our building. And in our VS solution, there is also an installshield setup project.

Well, sometimes our team members forget the increase products' versions that why we want to give the version number automatically generated like 3.7.1.*
so when we build the project, the version of our product dll/exe will be 3.7.1.5655

and let say we've created the following versions

```<code>3.7.1.1234
3.7.1.5678
3.7.1.9134
</code>```

and we gave the product Version 3.7.1.5678 to our customer. And after a while, the customer said that there is a bug in this version and the version number is 3.7.1.5678.

So, as I said earlier, we made the version number format like 3.7.1.* and we commit always like that so the assemblyinfo.cs file will not be changed. and when the customer said that the  version 3.7.1.5678 has problem. how can we find the related version what the customer has, in tfs commit. Let say we committed several time in the same day and we cannot see (or i dont know it) where the version number 3.7.1.5678 has been stored.

Well, I need to find the realted commit and work on this time project but i dont cannot know which commit it was.

My question is that how you solve this problem?

I hope i could explain it.

We have TFS Version 16.122.26918.3 and we use mostly Visual Studio 2017

答:
You could find the corresponding build of version number which is 3.7.1.5678.

For a particular build, it's easy to get related changeset/commit.

Then you could pull down that changeset/commit from TFS to your local workspace, and work on the bugs.

Not sure what your build number looks like, it's better to make a part of build number the same as the last version number(5678), like the usage of $(BuildID).

$(BuildID) is an internal immutable ID.

Title: Automatic Versioning in TFS Build

Body:
I am not sure whether i can the problem good explaning. Well we use TFS for our building. And in our VS solution, there is also an installshield setup project.

Well, sometimes our team members forget the increase products' versions that why we want to give the version number automatically generated like 3.7.1.*
so when we build the project, the version of our product dll/exe will be 3.7.1.5655

and let say we've created the following versions

3.7.1.1234
3.7.1.5678
3.7.1.9134

and we gave the product Version 3.7.1.5678 to our customer. And after a while, the customer said that there is a bug in this version and the version number is 3.7.1.5678.

So, as I said earlier, we made the version number format like 3.7.1.* and we commit always like that so the assemblyinfo.cs file will not be changed. and when the customer said that the  version 3.7.1.5678 has problem. how can we find the related version what the customer has, in tfs commit. Let say we committed several time in the same day and we cannot see (or i dont know it) where the version number 3.7.1.5678 has been stored.

Well, I need to find the realted commit and work on this time project but i dont cannot know which commit it was.

My question is that how you solve this problem?

I hope i could explain it.

We have TFS Version 16.122.26918.3 and we use mostly Visual Studio 2017


问:
HTTPS Volley Invalid header issue
Before all : if you don't know the exact answer so just give me advice how to check. Thanks

I have alreary tried a lot of different way how to implement ssl to my volley request but without success.

I can not understand way I get this error

ResponseJsonString = <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
                                                                  <TITLE>Bad Request</TITLE>
                                                                  <META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii">

Bad Request - Invalid Header

HTTP Error 400. The request has an invalid header name.

So step by step my code implementation

This is how I get the volley queue

```<code>mRequestQueue = Volley.newRequestQueue(this, new SslHurlStuck(SslUtils.KEYSTORE, SslUtils.PASSWORD_SSL, this));
</code>```

there is my SslHurlStuck

```<code>package utils.ssl;

import android.content.Context;
import android.util.Log;

import com.android.volley.toolbox.HurlStack;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import utils.global.AppUtils;

public class SslHurlStuck extends HurlStack
{
private final static String TAG = SslHurlStuck.class.getSimpleName();

private String mTrustStoreAssetName;
private String mTrustStorePassword;
private Context mContext;

public SslHurlStuck(final String iTrustStoreAssetName, final String iTrustStorePassword, Context iContext)
{
    super();

    mTrustStoreAssetName = iTrustStoreAssetName;
    mTrustStorePassword = iTrustStorePassword;
    mContext = iContext;
}

@Override
protected HttpURLConnection createConnection(URL url) throws IOException
{
    HttpsURLConnection urlConnection = null;

    try
    {
        urlConnection = new PinnedCertificateHttpsURLConnectionFactory(mContext).createHttpsURLConnection(url.toString(), mTrustStoreAssetName, mTrustStorePassword);
    }
    catch (Throwable iThrowable)
    {
        AppUtils.printLog(Log.ERROR, TAG, iThrowable.getMessage());
    }

    return urlConnection;
}
}
</code>```

And eventually there is my PinnedCertificateHttpsURLConnectionFactory

```<code>package utils.ssl;

import android.content.Context;
import android.util.Log;

import java.net.URL;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

 import javax.net.ssl.HostnameVerifier;
javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import utils.global.AppUtils;
import webServices.global.RequestStringBuilder;

public class PinnedCertificateHttpsURLConnectionFactory
{
private final static String TAG = PinnedCertificateHttpsURLConnectionFactory.class.getSimpleName();

private final Context mContext;

public PinnedCertificateHttpsURLConnectionFactory(Context iContext)
{
    mContext = iContext;
}

HttpsURLConnection createHttpsURLConnection(String urlString, final String iTrustStoreAssetName, final String iTrustStorePassword) throws Throwable
{
    // Initialize the trust manager factory instance with our trust store
    // as source of certificate authorities and trust material.
    KeyStore trustStore = new TrustStoreFactory(iTrustStoreAssetName, iTrustStorePassword, mContext).createTrustStore();
    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(tmfAlgorithm);
    trustManagerFactory.init(trustStore);

    // Initialize the SSL context.
    TrustManager[] wrappedTrustManagers = getWrappedTrustManagers(trustManagerFactory.getTrustManagers());
    SSLContext sslContext = SSLContext.getInstance(SslUtils.PROTOCOL_TLS);
    sslContext.init(null, wrappedTrustManagers, null);

    // Create the https URL connection.
    URL url = new URL(urlString);
    HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
    urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());
    urlConnection.setHostnameVerifier(getHostnameVerifier());

    return urlConnection;
}

// Let's assume your server app is hosting inside a server machine
// which has a server certificate in which "Issued to" is "localhost",for example.
// Then, inside verify method you can verify "localhost".
// If not, you can temporarily return true
private HostnameVerifier getHostnameVerifier()
{
    return new HostnameVerifier()
    {
        @Override
        public boolean verify(String hostname, SSLSession session)
        {
            HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();

            String localHost = SslUtils.SSL_LOCAL_HOST_DEV;

            if (RequestStringBuilder.isEnvironmentProd())
            {
                localHost = SslUtils.SSL_LOCAL_HOST_PROD;
            }

            return hv.verify(localHost, session);
            //              return hv.verify("localhost", session);
            //              return true;
        }
    };
}

private TrustManager[] getWrappedTrustManagers(TrustManager[] trustManagers)
{
    final X509TrustManager originalTrustManager = (X509TrustManager) trustManagers[0];

    final X509TrustManager x509TrustManager = new X509TrustManager()
    {
        public X509Certificate[] getAcceptedIssuers()
        {
            return originalTrustManager.getAcceptedIssuers();
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType)
        {
            try
            {
                if (certs != null && certs.length > 0)
                {
                    for (X509Certificate cer : certs)
                    {
                        cer.checkValidity();
                    }
                }
                else
                {
                    originalTrustManager.checkClientTrusted(certs, authType);
                }
            }
            catch (CertificateException e)
            {
                AppUtils.printLog(Log.ERROR, TAG, "checkClientTrusted" + e.toString());
            }
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType)
        {
            try
            {
                if (certs != null && certs.length > 0)
                {
                    for (X509Certificate cer : certs)
                    {
                        cer.checkValidity();
                    }
                }
                else
                {
                    originalTrustManager.checkServerTrusted(certs, authType);
                }
            }
            catch (CertificateException e)
            {
                AppUtils.printLog(Log.ERROR, TAG, "checkServerTrusted" + e.toString());
            }
        }
    };

    return new TrustManager[] {x509TrustManager};
}
}
</code>```

And last one TrustStoreFactory

```<code>public class TrustStoreFactory
{
private String mTrustStoreAssetName;
private String mTrustStorePassword;

private Context mContext;

public TrustStoreFactory(final String iTrustStoreAssetName, final String iTrustStorePassword, final Context iContext)
{
    mTrustStoreAssetName = iTrustStoreAssetName;
    mTrustStorePassword = iTrustStorePassword;
    mContext = iContext;
}

KeyStore createTrustStore() throws Throwable
{
    // Retrieve the trust store file from the assets.
    InputStream inputStream = mContext.getAssets().open(mTrustStoreAssetName);

    try
    {
        // Create a key store with the retrieved input stream.
        KeyStore trustStore = KeyStore.getInstance(SslUtils.KEYSTORE_EXTENSION_BKS);

        trustStore.load(inputStream, mTrustStorePassword.toCharArray());

        return trustStore;
    }
    finally
    {
            inputStream.close();
    }
}
}
</code>```

So, question is , what am I doing wrong?

My keystore consist 2 cer files, I tried different combinations to add the cer to the keystore... but nothing was changed.

Actually I don't think that there is a problems with a code, I think some issue with certificates , but I can not understand what exactly, and how to fix it

And also what is intresting that in iOS the same ssl checking work in another way, we just need to get certificate from response and then getPublicKey() on it, and compare if public key from response certificate equal to certificate public key that consist within app... But in android it is much more difficult...

Feel free to ask

答: The Content-Type header is not treated the same way as other headers by Volley. In particular, overriding getHeaders() to change the content type does not always work. Check this ans for more information </p>

Title: HTTPS Volley Invalid header issue

Body:
Before all : if you don't know the exact answer so just give me advice how to check. Thanks

I have alreary tried a lot of different way how to implement ssl to my volley request but without success.

I can not understand way I get this error

ResponseJsonString = <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
                                                                  <TITLE>Bad Request</TITLE>
                                                                  <META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii">

Bad Request - Invalid Header

HTTP Error 400. The request has an invalid header name.

So step by step my code implementation

This is how I get the volley queue

mRequestQueue = Volley.newRequestQueue(this, new SslHurlStuck(SslUtils.KEYSTORE, SslUtils.PASSWORD_SSL, this));

there is my SslHurlStuck

package utils.ssl;

import android.content.Context;
import android.util.Log;

import com.android.volley.toolbox.HurlStack;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import utils.global.AppUtils;

public class SslHurlStuck extends HurlStack
{
private final static String TAG = SslHurlStuck.class.getSimpleName();

private String mTrustStoreAssetName;
private String mTrustStorePassword;
private Context mContext;

public SslHurlStuck(final String iTrustStoreAssetName, final String iTrustStorePassword, Context iContext)
{
    super();

    mTrustStoreAssetName = iTrustStoreAssetName;
    mTrustStorePassword = iTrustStorePassword;
    mContext = iContext;
}

@Override
protected HttpURLConnection createConnection(URL url) throws IOException
{
    HttpsURLConnection urlConnection = null;

    try
    {
        urlConnection = new PinnedCertificateHttpsURLConnectionFactory(mContext).createHttpsURLConnection(url.toString(), mTrustStoreAssetName, mTrustStorePassword);
    }
    catch (Throwable iThrowable)
    {
        AppUtils.printLog(Log.ERROR, TAG, iThrowable.getMessage());
    }

    return urlConnection;
}
}

And eventually there is my PinnedCertificateHttpsURLConnectionFactory

package utils.ssl;

import android.content.Context;
import android.util.Log;

import java.net.URL;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

 import javax.net.ssl.HostnameVerifier;
javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import utils.global.AppUtils;
import webServices.global.RequestStringBuilder;

public class PinnedCertificateHttpsURLConnectionFactory
{
private final static String TAG = PinnedCertificateHttpsURLConnectionFactory.class.getSimpleName();

private final Context mContext;

public PinnedCertificateHttpsURLConnectionFactory(Context iContext)
{
    mContext = iContext;
}

HttpsURLConnection createHttpsURLConnection(String urlString, final String iTrustStoreAssetName, final String iTrustStorePassword) throws Throwable
{
    // Initialize the trust manager factory instance with our trust store
    // as source of certificate authorities and trust material.
    KeyStore trustStore = new TrustStoreFactory(iTrustStoreAssetName, iTrustStorePassword, mContext).createTrustStore();
    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(tmfAlgorithm);
    trustManagerFactory.init(trustStore);

    // Initialize the SSL context.
    TrustManager[] wrappedTrustManagers = getWrappedTrustManagers(trustManagerFactory.getTrustManagers());
    SSLContext sslContext = SSLContext.getInstance(SslUtils.PROTOCOL_TLS);
    sslContext.init(null, wrappedTrustManagers, null);

    // Create the https URL connection.
    URL url = new URL(urlString);
    HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
    urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());
    urlConnection.setHostnameVerifier(getHostnameVerifier());

    return urlConnection;
}

// Let's assume your server app is hosting inside a server machine
// which has a server certificate in which "Issued to" is "localhost",for example.
// Then, inside verify method you can verify "localhost".
// If not, you can temporarily return true
private HostnameVerifier getHostnameVerifier()
{
    return new HostnameVerifier()
    {
        @Override
        public boolean verify(String hostname, SSLSession session)
        {
            HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();

            String localHost = SslUtils.SSL_LOCAL_HOST_DEV;

            if (RequestStringBuilder.isEnvironmentProd())
            {
                localHost = SslUtils.SSL_LOCAL_HOST_PROD;
            }

            return hv.verify(localHost, session);
            //              return hv.verify("localhost", session);
            //              return true;
        }
    };
}

private TrustManager[] getWrappedTrustManagers(TrustManager[] trustManagers)
{
    final X509TrustManager originalTrustManager = (X509TrustManager) trustManagers[0];

    final X509TrustManager x509TrustManager = new X509TrustManager()
    {
        public X509Certificate[] getAcceptedIssuers()
        {
            return originalTrustManager.getAcceptedIssuers();
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType)
        {
            try
            {
                if (certs != null && certs.length > 0)
                {
                    for (X509Certificate cer : certs)
                    {
                        cer.checkValidity();
                    }
                }
                else
                {
                    originalTrustManager.checkClientTrusted(certs, authType);
                }
            }
            catch (CertificateException e)
            {
                AppUtils.printLog(Log.ERROR, TAG, "checkClientTrusted" + e.toString());
            }
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType)
        {
            try
            {
                if (certs != null && certs.length > 0)
                {
                    for (X509Certificate cer : certs)
                    {
                        cer.checkValidity();
                    }
                }
                else
                {
                    originalTrustManager.checkServerTrusted(certs, authType);
                }
            }
            catch (CertificateException e)
            {
                AppUtils.printLog(Log.ERROR, TAG, "checkServerTrusted" + e.toString());
            }
        }
    };

    return new TrustManager[] {x509TrustManager};
}
}

And last one TrustStoreFactory

public class TrustStoreFactory
{
private String mTrustStoreAssetName;
private String mTrustStorePassword;

private Context mContext;

public TrustStoreFactory(final String iTrustStoreAssetName, final String iTrustStorePassword, final Context iContext)
{
    mTrustStoreAssetName = iTrustStoreAssetName;
    mTrustStorePassword = iTrustStorePassword;
    mContext = iContext;
}

KeyStore createTrustStore() throws Throwable
{
    // Retrieve the trust store file from the assets.
    InputStream inputStream = mContext.getAssets().open(mTrustStoreAssetName);

    try
    {
        // Create a key store with the retrieved input stream.
        KeyStore trustStore = KeyStore.getInstance(SslUtils.KEYSTORE_EXTENSION_BKS);

        trustStore.load(inputStream, mTrustStorePassword.toCharArray());

        return trustStore;
    }
    finally
    {
            inputStream.close();
    }
}
}

So, question is , what am I doing wrong?

My keystore consist 2 cer files, I tried different combinations to add the cer to the keystore... but nothing was changed.

Actually I don't think that there is a problems with a code, I think some issue with certificates , but I can not understand what exactly, and how to fix it

And also what is intresting that in iOS the same ssl checking work in another way, we just need to get certificate from response and then getPublicKey() on it, and compare if public key from response certificate equal to certificate public key that consist within app... But in android it is much more difficult...

Feel free to ask


问:
Difference between web service and website
What is the difference between web service and website ? I know the difference between Webapplication and website .  If possible please explain with example. Thank you,Any help is greatly appreciated. </p>

答:
Website : It is a combination of user interfaces and services or only user interface. User doesn't require any coding to consume websites. Mostly website use for static and dynamic content. It uses by end-user who is not a coder.

Webservices: It is a service and consumes by any application ( like web, native, windows etc). A consumer needs to do coding to use these services. Mostly webservice mostly use by the coder for their application.


问:
Do we log duplicate data in tables or keep joining on all future reads?
Say a user activity table. At a minimum you would need stuff like user_id, datetime, activity_id, object_id, etc. I can join up with object table to find the object owner. I can join with activity table to find the activity group, type, etc.

OR

I can copy those details at runtime into the activity table also. This only means duplicate data but in the future whenever i need to read i do not have to keep joining. I have all my data now in the activity table for all possible pieces of data.

If i do duplicate data, do i duplicate it with FK or standalone?

答:
What you are talking about is called database normalization (or in your case de-normalization).

Since a relational database is pretty much designed to perform joins, there is usually VERY little reason to de-normalize and store duplicate data in one big wide table (there are some edge cases and tradeoffs, but in the example you used they don't really apply, so I recommend sticking with 3-table approach you listed (activity, user_activity, object).


问:
Trying to implement Minecraft Server List Ping in Swift
I am trying to query the status of a Minecraft server in Swift. I have looked here for help, but I can't figure out what to do. I have found, and analyzed a Java class that can query an mc server (find it here), but I don't know how to implement it in Swift. How would I go about sending the packets, and then receiving packets from the server, in Swift?</p>

```<code>import UIKit

var str = "Hello, playground"

var inputStream: NSInputStream?
var outputStream: NSOutputStream?

NSStream.getStreamsToHostWithName("0.0.0.0", port: 25577, inputStream: &inputStream, outputStream: &outputStream)
outputStream?.open()
inputStream?.open()
//while(true){
//get input
//}
let bytes : [CChar] = [0x01]
let data = NSData(bytes: bytes, length: 1)
//let data: NSData = "this is a test string".dataUsingEncoding(NSUTF8StringEncoding)!
outputStream?.write(UnsafePointer<UInt8>(data.bytes), maxLength: data.length)

NSLog("asdfasdf")
var buffer = [UInt8](count: 4096, repeatedValue: 0)
inputStream?.read(&buffer, maxLength: buffer.count)
inputStream?.read(&buffer, maxLength: buffer.count)
inputStream?.read(&buffer, maxLength: buffer.count)
</code>```

答:
A bit late, but... I happened to write this exact code once, in Swift. I wrote it awhile ago, so I'm not completely certain if it still works fine, but it should. Also, this will need the Sockets library from https://github.com/vapor/sockets. It definitely isn't the prettiest code I've ever written, but I really just threw it together in a hurry, so... Here it is:</p>

```<code>import Foundation
import Sockets
import Dispatch

public class MinecraftQuery {
    let STATISTIC: UInt8 = 0x00
    let HANDSHAKE: UInt8 = 0x09

    private let socket: UDPInternetSocket
    private var challenge: [UInt8]? = nil
    private var challengeNumber: Int32 = 0
    private var last_connect_time = Date(timeIntervalSinceReferenceDate: 0)

    private var response_received = false

    private var update_queued = false

    //toggle to prevent multple active connections
    private var connection_active = false

    public var serverInfo: [String: String] = [:]
    public var playerList: [String] = []

    init? (hostname: String, port: Port = 19132) {
    do {
        socket = try UDPInternetSocket(address: InternetAddress(hostname: hostname, port: port))
    } catch (let error) {
        debugPrint(error)
        return nil
    }

    print("query_init working")
    }

    func connect() {
    do {
        try socket.sendto(data: [0xFE, 0xFD, self.HANDSHAKE, 0x01, 0x02, 0x03, 0x04 ])

        // Should receive challenge
        let temp_recv = try socket.recvfrom(maxBytes: 20)

        guard temp_recv.sender == socket.address else {
        print("Received query challenge from unknown source. Ignoring.")
        return
        }

        guard temp_recv.data.starts(with: [self.HANDSHAKE, 1, 2, 3, 4]) else {
        print("Received invalid challenge data. Ignoring.")
        return
        }

        self.challenge = temp_recv.data

        if let challengeString = String(utf8String: Array(challenge![5...].map({ (byte) -> Int8 in
        Int8(byte)
        }))) {

        guard let challengeNumber = Int32(challengeString)?.byteSwapped else {
            print("Could not convert challenge to number. Ignoring.")
            return
        }

        self.challengeNumber = challengeNumber
        }
    } catch (let error) {
        debugPrint(error)
    }
    }

    func query() {
    let queryData = Data([0xFE, 0xFD, self.STATISTIC, 1, 2, 3, 4]) + Data(bytes: &self.challengeNumber, count: 4) + [0, 0, 0, 0]
    do {
        try self.socket.sendto(data: Array(queryData))
        let statisticRecv = try self.socket.recvfrom()

        guard statisticRecv.sender == socket.address else {
        print("Received statistics from unknown source. Ignoring.")
        return
        }

        guard statisticRecv.data.starts(with: [0, 1, 2, 3, 4]) else {
        print("Received invalid statistics data. Ignoring")
        return
        }

        var resultsDict: [String: String] = [:]

        let binStrings = statisticRecv.data[5...].split(separator: 0)

        var playerHeaderIDX = 0

        for index in 0..<binStrings.count {
        if index % 2 == 0 {
            if String(bytes: binStrings[index], encoding: .ascii) == "\u{01}player_" {
            playerHeaderIDX = index
            break
            }
            resultsDict[String(bytes: binStrings[index], encoding: .ascii)!] = String(bytes: binStrings[index + 1], encoding: .ascii)!
        }
        }

        self.serverInfo = resultsDict
        self.playerList = binStrings[(playerHeaderIDX + 1)...].map({ (binString) -> String in
        if let returnString = String(bytes: binString, encoding: .ascii) {
            return returnString
        } else {
            return ""
        }
        })

    } catch (let error) {
        debugPrint(error)
    }
    }
}
</code>```

Body:
I am trying to query the status of a Minecraft server in Swift. I have looked here for help, but I can't figure out what to do. I have found, and analyzed a Java class that can query an mc server (find it here), but I don't know how to implement it in Swift. How would I go about sending the packets, and then receiving packets from the server, in Swift?

import UIKit

var str = "Hello, playground"

var inputStream: NSInputStream?
var outputStream: NSOutputStream?

NSStream.getStreamsToHostWithName("0.0.0.0", port: 25577, inputStream: &inputStream, outputStream: &outputStream)
outputStream?.open()
inputStream?.open()
//while(true){
//get input
//}
let bytes : [CChar] = [0x01]
let data = NSData(bytes: bytes, length: 1)
//let data: NSData = "this is a test string".dataUsingEncoding(NSUTF8StringEncoding)!
outputStream?.write(UnsafePointer<UInt8>(data.bytes), maxLength: data.length)

NSLog("asdfasdf")
var buffer = [UInt8](count: 4096, repeatedValue: 0)
inputStream?.read(&buffer, maxLength: buffer.count)
inputStream?.read(&buffer, maxLength: buffer.count)
inputStream?.read(&buffer, maxLength: buffer.count)

Body:
A bit late, but... I happened to write this exact code once, in Swift. I wrote it awhile ago, so I'm not completely certain if it still works fine, but it should. Also, this will need the Sockets library from https://github.com/vapor/sockets. It definitely isn't the prettiest code I've ever written, but I really just threw it together in a hurry, so... Here it is:

import Foundation
import Sockets
import Dispatch

public class MinecraftQuery {
    let STATISTIC: UInt8 = 0x00
    let HANDSHAKE: UInt8 = 0x09

    private let socket: UDPInternetSocket
    private var challenge: [UInt8]? = nil
    private var challengeNumber: Int32 = 0
    private var last_connect_time = Date(timeIntervalSinceReferenceDate: 0)

    private var response_received = false

    private var update_queued = false

    //toggle to prevent multple active connections
    private var connection_active = false

    public var serverInfo: [String: String] = [:]
    public var playerList: [String] = []

    init? (hostname: String, port: Port = 19132) {
    do {
        socket = try UDPInternetSocket(address: InternetAddress(hostname: hostname, port: port))
    } catch (let error) {
        debugPrint(error)
        return nil
    }

    print("query_init working")
    }

    func connect() {
    do {
        try socket.sendto(data: [0xFE, 0xFD, self.HANDSHAKE, 0x01, 0x02, 0x03, 0x04 ])

        // Should receive challenge
        let temp_recv = try socket.recvfrom(maxBytes: 20)

        guard temp_recv.sender == socket.address else {
        print("Received query challenge from unknown source. Ignoring.")
        return
        }

        guard temp_recv.data.starts(with: [self.HANDSHAKE, 1, 2, 3, 4]) else {
        print("Received invalid challenge data. Ignoring.")
        return
        }

        self.challenge = temp_recv.data

        if let challengeString = String(utf8String: Array(challenge![5...].map({ (byte) -> Int8 in
        Int8(byte)
        }))) {

        guard let challengeNumber = Int32(challengeString)?.byteSwapped else {
            print("Could not convert challenge to number. Ignoring.")
            return
        }

        self.challengeNumber = challengeNumber
        }
    } catch (let error) {
        debugPrint(error)
    }
    }

    func query() {
    let queryData = Data([0xFE, 0xFD, self.STATISTIC, 1, 2, 3, 4]) + Data(bytes: &self.challengeNumber, count: 4) + [0, 0, 0, 0]
    do {
        try self.socket.sendto(data: Array(queryData))
        let statisticRecv = try self.socket.recvfrom()

        guard statisticRecv.sender == socket.address else {
        print("Received statistics from unknown source. Ignoring.")
        return
        }

        guard statisticRecv.data.starts(with: [0, 1, 2, 3, 4]) else {
        print("Received invalid statistics data. Ignoring")
        return
        }

        var resultsDict: [String: String] = [:]

        let binStrings = statisticRecv.data[5...].split(separator: 0)

        var playerHeaderIDX = 0

        for index in 0..<binStrings.count {
        if index % 2 == 0 {
            if String(bytes: binStrings[index], encoding: .ascii) == "\u{01}player_" {
            playerHeaderIDX = index
            break
            }
            resultsDict[String(bytes: binStrings[index], encoding: .ascii)!] = String(bytes: binStrings[index + 1], encoding: .ascii)!
        }
        }

        self.serverInfo = resultsDict
        self.playerList = binStrings[(playerHeaderIDX + 1)...].map({ (binString) -> String in
        if let returnString = String(bytes: binString, encoding: .ascii) {
            return returnString
        } else {
            return ""
        }
        })

    } catch (let error) {
        debugPrint(error)
    }
    }
}


问:
Testing phases, where is the smoke testing?
So I was looking to a book and I dont really understand their classification:

```<code>Unit tests
Integration tests
Smoke and Sanity tests
System tests
Acceptance tests
</code>```

I thought smoke test would be right after integration one? Also I thought that sanity means quick check of the application when new part is deployed.

Also the question: is this correct or should the smoke and sanity tests be in different order. If so, why?

答:
Smoke Testing is the first & foremost Testing done by any QA personnel. This is done once the unit testing is completed by the developer.

The main agenda to perform Smoke testings is to believe your application can handle the positive flow at the Least. Once this done QA gradually proceeds with the following
1.Functional Testing
2.Link & Download Options
3.UI
4.System Testing
5.Regression for better results from previous builds.

Happy Testing :)

Body:
So I was looking to a book and I dont really understand their classification:

Unit tests
Integration tests
Smoke and Sanity tests
System tests
Acceptance tests

I thought smoke test would be right after integration one? Also I thought that sanity means quick check of the application when new part is deployed.

Also the question: is this correct or should the smoke and sanity tests be in different order. If so, why?


问:
Scraping a page + click on its href and takes hrefs data
I'm trying to scrap a page and take it's hrefs data which are in  tag, but i can't get result. This is an assignment for my school.
May someone help me please to resolve this issue?

This is my code:

```<code>from bs4 import BeautifulSoup
import re
import requests

for i in range (1,5):
    base_url = 'https://www.leboncoin.fr/locations'
    url = 'https://www.leboncoin.fr/locations/1152669519.htm?ca=22_s'
    res = requests.get(url)
    soup = BeautifulSoup(res.text)

    locations = []

    links = soup.find_all(['li','a'], href=re.compile('.*\/locations\/+(i)+'))

    for l in links:
        full_link = base_url + l['href']
        titre = l[['li', 'section', 'h2']].strip()
        res = requests.get(full_link)
        soup = BeautifulSoup(res.text)
        loyer = soup.find(['h2','span'], attrs={"class": "value\^((?![A-Z]).)*$"})
        loyers = loyer.text
        ville = soup.find(['h2','span'], attrs={"class": "value", "itemprop": "adresse"})
        villes = ville.text
        surface = soup.find(['h2','span'], attrs={"class": "clearfix", "calss": "value"})
        surfaces = surface.text
        description = soup.find('p', attrs={"class": "value", "itemprop": "description"})
        descriptions = description.text
        shops.append(titre, loyers, villes, surfaces, descriptions)

    print(locations)
</code>```

I got this like result:

```<code>[]
[]
[]
[]
</code>```

Thanks in advance for your answers.

答:
You haven't defines shops anywhere, I am assuming that you want a dictionary. So for that do this:</p>

```<code>for l in links:
    shops = {}
    full_link = base_url + l['href']
    shops['titre'] = l[['li', 'section', 'h2']].strip()
    res = requests.get(full_link)
    soup = BeautifulSoup(res.text)
    loyer = soup.find(['h2','span'], attrs={"class": "value\^((?![A-Z]).)*$"})
    shops['loyers'] = loyer.text
    ville = soup.find(['h2','span'], attrs={"class": "value", "itemprop": "adresse"})
    shops['villes'] = ville.text
    surface = soup.find(['h2','span'], attrs={"class": "clearfix", "calss": "value"})
    shops['surfaces'] = surface.text
    description = soup.find('p', attrs={"class": "value", "itemprop": "description"})
    shops['descriptions'] = description.text
    locations.append(shops)

print(locations)
</code>```

Body:
I'm trying to scrap a page and take it's hrefs data which are in  tag, but i can't get result. This is an assignment for my school.
May someone help me please to resolve this issue?

This is my code:

from bs4 import BeautifulSoup
import re
import requests

for i in range (1,5):
    base_url = 'https://www.leboncoin.fr/locations'
    url = 'https://www.leboncoin.fr/locations/1152669519.htm?ca=22_s'
    res = requests.get(url)
    soup = BeautifulSoup(res.text)

    locations = []

    links = soup.find_all(['li','a'], href=re.compile('.*\/locations\/+(i)+'))

    for l in links:
        full_link = base_url + l['href']
        titre = l[['li', 'section', 'h2']].strip()
        res = requests.get(full_link)
        soup = BeautifulSoup(res.text)
        loyer = soup.find(['h2','span'], attrs={"class": "value\^((?![A-Z]).)*$"})
        loyers = loyer.text
        ville = soup.find(['h2','span'], attrs={"class": "value", "itemprop": "adresse"})
        villes = ville.text
        surface = soup.find(['h2','span'], attrs={"class": "clearfix", "calss": "value"})
        surfaces = surface.text
        description = soup.find('p', attrs={"class": "value", "itemprop": "description"})
        descriptions = description.text
        shops.append(titre, loyers, villes, surfaces, descriptions)

    print(locations)

I got this like result:

[]
[]
[]
[]

Thanks in advance for your answers.

Body:
You haven't defines shops anywhere, I am assuming that you want a dictionary. So for that do this:

for l in links:
    shops = {}
    full_link = base_url + l['href']
    shops['titre'] = l[['li', 'section', 'h2']].strip()
    res = requests.get(full_link)
    soup = BeautifulSoup(res.text)
    loyer = soup.find(['h2','span'], attrs={"class": "value\^((?![A-Z]).)*$"})
    shops['loyers'] = loyer.text
    ville = soup.find(['h2','span'], attrs={"class": "value", "itemprop": "adresse"})
    shops['villes'] = ville.text
    surface = soup.find(['h2','span'], attrs={"class": "clearfix", "calss": "value"})
    shops['surfaces'] = surface.text
    description = soup.find('p', attrs={"class": "value", "itemprop": "description"})
    shops['descriptions'] = description.text
    locations.append(shops)

print(locations)


问:
Effective way of pattern matching on multiple Options Scala
I have below function which returns a flag based on some conditions.

Trying to see if there is a better Scala way to achieve the same?

Basically based on the status of the person there are different rules to be applied finally to derive on the pass_ind flag.

If person status is Student or Unemployment there are some rules on income and if the person status is not in Student or Unemployment there are different rules to be applied on score & income

```<code>def IncomeScreenStatus(status_cd: Option[String],
                                   score: Option[Int],
                                 income: Option[Double]) : String  = {

 var pass_ind : String = "F"

 if (score.isDefined && income.isDefined && status_cd.isDefined) {

        val score : Int = score.get
        val income : Double = income.get
        val status_cd : String = status_cd.get

        if (status_cd == "STUDENT" || status_cd == "UNEMPLOYMENT") {
          pass_ind = (status_cd, income) match {
            case ("UNEMPLOYMENT", income) if income <= 7000 => "P"
            case ("STUDENT", income) if income <= 18000 => "P"
            case _ => "F"
          }
        }
        else {
          pass_ind = (income, score) match {
            case (income, score) if (score < 100 || score > 150) && income <= 8500 => "P"
            case (income, score) if (score <= 167 && score >= 100) && income <= 10500 => "P"
            case _ => "F"
          }
        }

      }

    pass_ind

}
</code>```

答:
Here's a first crack at it.

```<code>def IncomeScreenStatus(status_cd: Option[String]
                      ,score    : Option[Int]
                      ,income   : Option[Double]) : String  = {
  for {
    stat <- status_cd
    scr  <- score
    incm <- income
  } yield stat match {
    case "UNEMPLOYMENT" => if (incm <=  7000) "P" else "F"
    case "STUDENT"      => if (incm <= 18000) "P" else "F"
    case _ => if ((scr <  100 || scr >  150) && incm <=  8500 ||
                  (scr <= 167 && scr >= 100) && incm <= 10500) "P" else "F"
  }
}.getOrElse("F")
</code>```

Creating local variables with the same name as the passed in parameters really confuses the compiler.

Body:
I have below function which returns a flag based on some conditions.

Trying to see if there is a better Scala way to achieve the same?

Basically based on the status of the person there are different rules to be applied finally to derive on the pass_ind flag.

If person status is Student or Unemployment there are some rules on income and if the person status is not in Student or Unemployment there are different rules to be applied on score & income

def IncomeScreenStatus(status_cd: Option[String],
                                   score: Option[Int],
                                 income: Option[Double]) : String  = {

 var pass_ind : String = "F"

 if (score.isDefined && income.isDefined && status_cd.isDefined) {

        val score : Int = score.get
        val income : Double = income.get
        val status_cd : String = status_cd.get

        if (status_cd == "STUDENT" || status_cd == "UNEMPLOYMENT") {
          pass_ind = (status_cd, income) match {
            case ("UNEMPLOYMENT", income) if income <= 7000 => "P"
            case ("STUDENT", income) if income <= 18000 => "P"
            case _ => "F"
          }
        }
        else {
          pass_ind = (income, score) match {
            case (income, score) if (score < 100 || score > 150) && income <= 8500 => "P"
            case (income, score) if (score <= 167 && score >= 100) && income <= 10500 => "P"
            case _ => "F"
          }
        }

      }

    pass_ind

}

Body:
Here's a first crack at it.

def IncomeScreenStatus(status_cd: Option[String]
                      ,score    : Option[Int]
                      ,income   : Option[Double]) : String  = {
  for {
    stat <- status_cd
    scr  <- score
    incm <- income
  } yield stat match {
    case "UNEMPLOYMENT" => if (incm <=  7000) "P" else "F"
    case "STUDENT"      => if (incm <= 18000) "P" else "F"
    case _ => if ((scr <  100 || scr >  150) && incm <=  8500 ||
                  (scr <= 167 && scr >= 100) && incm <= 10500) "P" else "F"
  }
}.getOrElse("F")

Creating local variables with the same name as the passed in parameters really confuses the compiler.


答:
First of all, I have few comments about recommended code-style adopted by Scala,

variable/function/def names are supposed to be camelCase

incomeScreenStatus instead of IncomeScreenStatus.

statusCd instead of status_cd

passInd instead of pass_ind

Now,

```<code>def incomeScreenStatus(statusCd: Option[String],
                       score: Option[Int],
                       income: Option[Double]) : String  = {
  (score, income, statusCd) match {
    case (Some(scoreV), Some(incomeV), Some(statusCdV)) => {
      (statusCdV, incomeV, scoreV) match {
        case ("UNEMPLOYMENT", _, _) if incomeV <= 7000 => "p"
        case ("STUDENT", _, _) if incomeV <= 18000 => "p"
        case _ if (scoreV < 100 || scoreV > 150) && incomeV <= 8500 => "P"
        case _ if (scoreV <= 167 && scoreV >= 100) && incomeV <= 10500 => "P"
        case _ => "F"
      }
    }
    case _ => "F"
  }

}
</code>```

Title: Effective way of pattern matching on multiple Options Scala

Body:
First of all, I have few comments about recommended code-style adopted by Scala,

variable/function/def names are supposed to be camelCase

incomeScreenStatus instead of IncomeScreenStatus.

statusCd instead of status_cd

passInd instead of pass_ind

Now,

def incomeScreenStatus(statusCd: Option[String],
                       score: Option[Int],
                       income: Option[Double]) : String  = {
  (score, income, statusCd) match {
    case (Some(scoreV), Some(incomeV), Some(statusCdV)) => {
      (statusCdV, incomeV, scoreV) match {
        case ("UNEMPLOYMENT", _, _) if incomeV <= 7000 => "p"
        case ("STUDENT", _, _) if incomeV <= 18000 => "p"
        case _ if (scoreV < 100 || scoreV > 150) && incomeV <= 8500 => "P"
        case _ if (scoreV <= 167 && scoreV >= 100) && incomeV <= 10500 => "P"
        case _ => "F"
      }
    }
    case _ => "F"
  }

}


问:
get face skin tone color from image
i have tried below code that is returning me color of specific pixel which i have pass in argument

```<code>int x = (int)event.getX();
int y = (int)event.getY();
int pixel = bitmap.getPixel(x,y);

int redValue = Color.red(pixel);
int blueValue = Color.blue(pixel);
int greenValue = Color.green(pixel);

int[] color={redValue ,blueValue ,greenValue };
btn.setBackgroundColor(getHexColor(color));

public static int getHexColor(int[] color) {
return android.graphics.Color.rgb(color[0], color[1], color[2]);
}
</code>```

i have also try color palette following link is reference link that is also not returning perfect skin tone color of face

this is i have also tried

anyone have idea how to extract or get face skin tone color ??

答:
Use this code for getting colors from images.
You can follow this tutorial for further information.

https://medium.com/david-developer/extracting-colors-from-images-integrating-picasso-and-palette-b9ba45c9c418

```<code> Palette.from(bitmap)
            .generate(new Palette.PaletteAsyncListener() {
                @Override
                public void onGenerated(Palette palette) {
                    Palette.Swatch textSwatch = palette.getVibrantSwatch();
                    if (textSwatch == null) {
                        Toast.makeText(MainActivity.this, "Null swatch :(", Toast.LENGTH_SHORT).show();
                        return;
                }
                backgroundGroup.setBackgroundColor(textSwatch.getRgb());
                titleColorText.setTextColor(textSwatch.getTitleTextColor());
                bodyColorText.setTextColor(textSwatch.getBodyTextColor());
            }
        });
</code>```

Title: get face skin tone color from image

Body:
i have tried below code that is returning me color of specific pixel which i have pass in argument

int x = (int)event.getX();
int y = (int)event.getY();
int pixel = bitmap.getPixel(x,y);

int redValue = Color.red(pixel);
int blueValue = Color.blue(pixel);
int greenValue = Color.green(pixel);

int[] color={redValue ,blueValue ,greenValue };
btn.setBackgroundColor(getHexColor(color));

public static int getHexColor(int[] color) {
return android.graphics.Color.rgb(color[0], color[1], color[2]);
}

i have also try color palette following link is reference link that is also not returning perfect skin tone color of face

this is i have also tried

anyone have idea how to extract or get face skin tone color ??

Body:
Use this code for getting colors from images.
You can follow this tutorial for further information.

https://medium.com/david-developer/extracting-colors-from-images-integrating-picasso-and-palette-b9ba45c9c418

 Palette.from(bitmap)
            .generate(new Palette.PaletteAsyncListener() {
                @Override
                public void onGenerated(Palette palette) {
                    Palette.Swatch textSwatch = palette.getVibrantSwatch();
                    if (textSwatch == null) {
                        Toast.makeText(MainActivity.this, "Null swatch :(", Toast.LENGTH_SHORT).show();
                        return;
                }
                backgroundGroup.setBackgroundColor(textSwatch.getRgb());
                titleColorText.setTextColor(textSwatch.getTitleTextColor());
                bodyColorText.setTextColor(textSwatch.getBodyTextColor());
            }
        });


问:
WordPress add_image_size not working. Images uploaded after thumbnail size is defined
I have looked around here and other forums for a solution of my problem. Almost everywhere the solution is to install Regenerate Thumbnail plugin, because images uploaded before thumbnail size is defined will not work.

For me, the issue is all my images were uploaded after I defined the thumbnail size: add_image_size('home_grid_thumbnail', 200, 150, true); But they are rendering with 1px * 1px dimensions.

Any suggestion would be helpful.

答:
Through the discussions/comments OP found out that he needed /image.php to be included.

Normally these files need to be included as dependencies when handling images on the frontend

```<code>include_once( ABSPATH . 'wp-admin/includes/image.php' );
include_once( ABSPATH . 'wp-admin/includes/file.php' );
include_once( ABSPATH . 'wp-admin/includes/media.php' );
</code>```

This does not need to be included/required when building a plugin etc for the control panel, since the functions in them are already loaded when in the admin section

Body:
Through the discussions/comments OP found out that he needed /image.php to be included.

Normally these files need to be included as dependencies when handling images on the frontend

include_once( ABSPATH . 'wp-admin/includes/image.php' );
include_once( ABSPATH . 'wp-admin/includes/file.php' );
include_once( ABSPATH . 'wp-admin/includes/media.php' );

This does not need to be included/required when building a plugin etc for the control panel, since the functions in them are already loaded when in the admin section


问:
How to set onChildAdded called when an child is added
```<code>public class ChatsFragment extends Fragment {

FirebaseDatabase database;
DatabaseReference myRef;
List<ListData> list;
RecyclerView recyclerview;
TextView badge;
String name, message, nameCaps;
int id, user_id;
DatabaseHelper databaseHelper;

public View onCreateView(LayoutInflater inflater, ViewGroup group, Bundle b) {
    View view = inflater.inflate(R.layout.fragment_chats, group, false);
    recyclerview = view.findViewById(R.id.rview);
    badge = view.findViewById(R.id.badge);
    database = FirebaseDatabase.getInstance();
    myRef = database.getReference("message");
    list = new ArrayList<>();
    databaseHelper = new DatabaseHelper(getContext());
    myRef.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            UserDetails userdetails = dataSnapshot.getValue(UserDetails.class);
            name = userdetails.getName();
            message = userdetails.getMessage();
            id = userdetails.getId();
            user_id = userdetails.getUser_id();
            nameCaps = name.substring(0, 1).toUpperCase() + name.substring(1);
            if (databaseHelper.checkUserID(user_id)) {
                databaseHelper.updateMsg(nameCaps, message, user_id);
            } else {
                databaseHelper.insertData(nameCaps, message, id, user_id);
            }
            list = databaseHelper.getData();
            RecyclerViewAdapter recycler = new RecyclerViewAdapter(list);
            RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
            recyclerview.setLayoutManager(layoutManager);
            recyclerview.setItemAnimator(new DefaultItemAnimator());
            recyclerview.setAdapter(recycler);
        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {
            UserDetails userdetails = dataSnapshot.getValue(UserDetails.class);
            name = userdetails.getName();
            message = userdetails.getMessage();
            id = userdetails.getId();
            nameCaps = name.substring(0, 1).toUpperCase() + name.substring(1);
            databaseHelper.updateData(nameCaps, message, id);

        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {
            UserDetails userdetails = dataSnapshot.getValue(UserDetails.class);
            id = userdetails.getId();
            databaseHelper.deleteData(id);
        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
    return view;
}
</code>```

This is my code. When a child is added i saved it in sqlite database and fetch the data from database and load into recyclerview but onChildAdded() method calls on every time i open the app.How to set when i added a child then onChildAdded() calls otherwise it don't call onChildAdded()

答:
There is no such way to find, because it always return you with all relevant data that are present on Firebase. There is no solution to restrict it as per my research and knowledge.

There is a way to do that:

For me the logic was is to have value -"status" for example- which needs to be validated before deciding whether it is really new or was an old record then I set the "status" to a different value so I don't get it next time:

```<code>@Override
    public void onChildAdded(DataSnapshot dataSnapshot, String previousChildKey) {

            if(dataSnapshot.hasChildren()) {

                String Id = (String) dataSnapshot.child("user_id").getValue();
                String status = (String) dataSnapshot.child("status").getValue();

                if (Id != null && Id.equals(storedId) && status != null && status.equals("created")) {
                    Log.d("INCOMING_REQUEST", "This is for you!");
                    sessionsRef.child(dataSnapshot.getKey()).child("status").setValue("received");
                }

            }

    }
</code>```

Thanks and let me know if need more !!

Body:
public class ChatsFragment extends Fragment {

FirebaseDatabase database;
DatabaseReference myRef;
List<ListData> list;
RecyclerView recyclerview;
TextView badge;
String name, message, nameCaps;
int id, user_id;
DatabaseHelper databaseHelper;

public View onCreateView(LayoutInflater inflater, ViewGroup group, Bundle b) {
    View view = inflater.inflate(R.layout.fragment_chats, group, false);
    recyclerview = view.findViewById(R.id.rview);
    badge = view.findViewById(R.id.badge);
    database = FirebaseDatabase.getInstance();
    myRef = database.getReference("message");
    list = new ArrayList<>();
    databaseHelper = new DatabaseHelper(getContext());
    myRef.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            UserDetails userdetails = dataSnapshot.getValue(UserDetails.class);
            name = userdetails.getName();
            message = userdetails.getMessage();
            id = userdetails.getId();
            user_id = userdetails.getUser_id();
            nameCaps = name.substring(0, 1).toUpperCase() + name.substring(1);
            if (databaseHelper.checkUserID(user_id)) {
                databaseHelper.updateMsg(nameCaps, message, user_id);
            } else {
                databaseHelper.insertData(nameCaps, message, id, user_id);
            }
            list = databaseHelper.getData();
            RecyclerViewAdapter recycler = new RecyclerViewAdapter(list);
            RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
            recyclerview.setLayoutManager(layoutManager);
            recyclerview.setItemAnimator(new DefaultItemAnimator());
            recyclerview.setAdapter(recycler);
        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {
            UserDetails userdetails = dataSnapshot.getValue(UserDetails.class);
            name = userdetails.getName();
            message = userdetails.getMessage();
            id = userdetails.getId();
            nameCaps = name.substring(0, 1).toUpperCase() + name.substring(1);
            databaseHelper.updateData(nameCaps, message, id);

        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {
            UserDetails userdetails = dataSnapshot.getValue(UserDetails.class);
            id = userdetails.getId();
            databaseHelper.deleteData(id);
        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
    return view;
}

This is my code. When a child is added i saved it in sqlite database and fetch the data from database and load into recyclerview but onChildAdded() method calls on every time i open the app.How to set when i added a child then onChildAdded() calls otherwise it don't call onChildAdded()

Body:
There is no such way to find, because it always return you with all relevant data that are present on Firebase. There is no solution to restrict it as per my research and knowledge.

There is a way to do that:

For me the logic was is to have value -"status" for example- which needs to be validated before deciding whether it is really new or was an old record then I set the "status" to a different value so I don't get it next time:

@Override
    public void onChildAdded(DataSnapshot dataSnapshot, String previousChildKey) {

            if(dataSnapshot.hasChildren()) {

                String Id = (String) dataSnapshot.child("user_id").getValue();
                String status = (String) dataSnapshot.child("status").getValue();

                if (Id != null && Id.equals(storedId) && status != null && status.equals("created")) {
                    Log.d("INCOMING_REQUEST", "This is for you!");
                    sessionsRef.child(dataSnapshot.getKey()).child("status").setValue("received");
                }

            }

    }

Thanks and let me know if need more !!


问:
Getting a dialog on click of Edit Button on admin-on-rest
I am working on an application using admin-on-rest framework. For editing an entry on a Resource we provide XXXEdit, XXXShow, XXXCreate props to it. My requirement is that when I click on an Edit button in List view on any entry I should get a Dialog box with the parameters in XXXEdit instead of going to a new page. I tried doing this by using a Dialog in XXXEdit component

```<code> <Edit title={<RoleTitle />} {...props}>
      <SimpleForm>
        <Dialog
          title="Dialog With Actions"
          actions={actions}
          modal={false}
          open={true}
        >
          <TextInput source="id" />
          <TextInput source="name" validate={required} />
          .
          .//some more fields
        </Dialog>
      </SimpleForm>
    </Edit>
</code>```

I get errors like The TextInput component wasn't called within a redux-form
If I use a DisabledInput then I get an error cannot read value of undefined

How do I go on with this?

答:
I tried to resolve this using HOC and react-router.

I created a button using AOR button and provided a containerElement

```<code>containerElement={
          <Link
            key={record.id}
            to={{
              ...{
                pathname: `${basePath}/${encodeURIComponent(record.id)}`
              },
              ...{ state: { modal: true } }
            }}
          />
        }
</code>```

I created a route like this where DialogRoleEdit is an AOR edit component wrapped with a dialog HOC below .

```<code><Route
    exact
    path="/roles/:id"
    render={routeProps => {
      return !!(
        routeProps.location.state && routeProps.location.state.modal
      ) ? (
        <Restricted authClient={authClient} location={routeProps.location}>
          <div>
            <RoleList resource={"roles"} {...routeProps} />
            <DialogRoleEdit resource={"roles"} {...routeProps} />
          </div>
        </Restricted>
      ) : (
        <Restricted authClient={authClient} location={routeProps.location}>
          <RoleEdit resource={"roles"} {...routeProps} />
        </Restricted>
      );
    }}
  />
</code>```

Finally an HOC

```<code>handleClose = () => {
  this.props.history.goBack();
};
render() {
  const actions = [
    <FlatButton label="Cancel" primary={true} onClick={this.handleClose} />
  ];
  return (
    <Dialog>
      <WrappedComponent/>
    </Dialog>
  )
</code>```

}

We need to provide edit prop for this resource in App.js

```<code>edit={DialogUserEdit}
</code>```

Body:
I am working on an application using admin-on-rest framework. For editing an entry on a Resource we provide XXXEdit, XXXShow, XXXCreate props to it. My requirement is that when I click on an Edit button in List view on any entry I should get a Dialog box with the parameters in XXXEdit instead of going to a new page. I tried doing this by using a Dialog in XXXEdit component

 <Edit title={<RoleTitle />} {...props}>
      <SimpleForm>
        <Dialog
          title="Dialog With Actions"
          actions={actions}
          modal={false}
          open={true}
        >
          <TextInput source="id" />
          <TextInput source="name" validate={required} />
          .
          .//some more fields
        </Dialog>
      </SimpleForm>
    </Edit>

I get errors like The TextInput component wasn't called within a redux-form
If I use a DisabledInput then I get an error cannot read value of undefined

How do I go on with this?

Body:
I tried to resolve this using HOC and react-router.

I created a button using AOR button and provided a containerElement

containerElement={
          <Link
            key={record.id}
            to={{
              ...{
                pathname: `${basePath}/${encodeURIComponent(record.id)}`
              },
              ...{ state: { modal: true } }
            }}
          />
        }

I created a route like this where DialogRoleEdit is an AOR edit component wrapped with a dialog HOC below .

<Route
    exact
    path="/roles/:id"
    render={routeProps => {
      return !!(
        routeProps.location.state && routeProps.location.state.modal
      ) ? (
        <Restricted authClient={authClient} location={routeProps.location}>
          <div>
            <RoleList resource={"roles"} {...routeProps} />
            <DialogRoleEdit resource={"roles"} {...routeProps} />
          </div>
        </Restricted>
      ) : (
        <Restricted authClient={authClient} location={routeProps.location}>
          <RoleEdit resource={"roles"} {...routeProps} />
        </Restricted>
      );
    }}
  />

Finally an HOC

handleClose = () => {
  this.props.history.goBack();
};
render() {
  const actions = [
    <FlatButton label="Cancel" primary={true} onClick={this.handleClose} />
  ];
  return (
    <Dialog>
      <WrappedComponent/>
    </Dialog>
  )

}

We need to provide edit prop for this resource in App.js

edit={DialogUserEdit}


问:
How to remove special characters from a string?
I want to remove special characters like:

```<code>- + ^ . : ,
</code>```

from an String using Java.

答:
This will replace all the  characters except alphanumeric </p>

```<code>replaceAll("[^A-Za-z0-9]","");
</code>```

Body:
I want to remove special characters like:

- + ^ . : ,

from an String using Java.

Body:
This will replace all the  characters except alphanumeric

replaceAll("[^A-Za-z0-9]","");