问:
MySQL: InnoDb: Semaphore wait has lasted > 600 seconds. We intentionally crash the server
MySQL 5.7.16 server on Windows Server 2012R2 with 32GB RAM is now restarting itself every 18minutes or so with the following in the error log:

```<code>InnoDB: ###### Diagnostic info printed to the standard error stream 2017-11-
16T13:18:39.650036Z 0 [ERROR] [FATAL] InnoDB: Semaphore wait has lasted >
600 seconds. We intentionally crash the server because it appears to be
hung.
2017-11-16 13:18:39 0x1bcc  InnoDB: Assertion failure in thread 7116 in file
ut0ut.cc line 916
InnoDB: We intentionally generate a memory trap.
InnoDB: Submit a detailed bug report to http://bugs.mysql.com.
InnoDB: If you get repeated assertion failures or crashes, even
InnoDB: immediately after the mysqld startup, there may be
InnoDB: corruption in the InnoDB tablespace. Please refer to
InnoDB: http://dev.mysql.com/doc/refman/5.7/en/forcing-innodb-recovery.html
InnoDB: about forcing recovery.
13:18:39 UTC - 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.
Attempting to collect some information that could help diagnose the problem.
As this is a crash and something is definitely wrong, the information
collection process might fail.

key_buffer_size=8388608
read_buffer_size=131072
max_used_connections=34
max_threads=151
thread_count=6
connection_count=6
It is possible that mysqld could use up to
key_buffer_size + (read_buffer_size + sort_buffer_size)*max_threads = 68011K bytes of memory
Hope that's ok; if not, decrease some variables in the equation.

Thread pointer: 0x0
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...
7ff7eeb7e262    mysqld.exe!my_sigabrt_handler()[my_thr_init.c:449]
7ff7eef28489    mysqld.exe!raise()[winsig.c:587]
7ff7eef27380    mysqld.exe!abort()[abort.c:82]
7ff7eec8f178    mysqld.exe!ut_dbg_assertion_failed()[ut0dbg.cc:67]
7ff7eec8f391    mysqld.exe!ib::fatal::~fatal()[ut0ut.cc:916]
7ff7eebfd43d    mysqld.exe!srv_error_monitor_thread()[srv0srv.cc:1724]
7ffc55d613d2    KERNEL32.DLL!BaseThreadInitThunk()
7ffc57d854e4    ntdll.dll!RtlUserThreadStart()
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>```

There appears to be a transaction which is being rolled back when the server restarts. The following can be found in the information_schema.innodb_trx\G

```<code>trx_id: 309725166
trx_state: ROLLING BACK
trx_started: 2017-11-16 13:30:18
trx_requested_lock_id: NULL
trx_wait_started: NULL
trx_weight: 17856930
trx_mysql_thread_id: 0
trx_query: NULL
trx_operation_state: NULL
trx_tables_in_use: 0
trx_tables_locked: 1
trx_lock_structs: 1
trx_lock_memory_bytes: 1136
trx_rows_locked: 0
trx_rows_modified: 17856929
trx_concurrency_tickets: 0
trx_isolation_level: REPEATABLE READ
trx_unique_checks: 1
trx_foreign_key_checks: 1
trx_last_foreign_key_error: NULL
trx_adaptive_hash_latched: 0
trx_adaptive_hash_timeout: 0
trx_is_read_only: 0
trx_autocommit_non_locking: 0
</code>```

Is it possible to stop this transaction being rolled back?

Results from SHOW GLOBAL STATUS:

```<code>Aborted_clients                               | 0
Aborted_connects                              | 0
Binlog_cache_disk_use                         | 0
Binlog_cache_use                              | 0
Binlog_stmt_cache_disk_use                    | 0
Binlog_stmt_cache_use                         | 0
Bytes_received                                | 79456733
Bytes_sent                                    | 132918726
Com_admin_commands                            | 53
Com_assign_to_keycache                        | 0
Com_alter_db                                  | 0
Com_alter_db_upgrade                          | 0
Com_alter_event                               | 0
Com_alter_function                            | 0
Com_alter_instance                            | 0
Com_alter_procedure                           | 0
Com_alter_server                              | 0
Com_alter_table                               | 0
Com_alter_tablespace                          | 0
Com_alter_user                                | 0
Com_analyze                                   | 0
Com_begin                                     | 0
Com_binlog                                    | 0
Com_call_procedure                            | 0
Com_change_db                                 | 890
Com_change_master                             | 0
Com_change_repl_filter                        | 0
Com_check                                     | 0
Com_checksum                                  | 0
Com_commit                                    | 0
Com_create_db                                 | 0
Com_create_event                              | 0
Com_create_function                           | 0
Com_create_index                              | 0
Com_create_procedure                          | 0
Com_create_server                             | 0
Com_create_table                              | 0
Com_create_trigger                            | 0
Com_create_udf                                | 0
Com_create_user                               | 0
Com_create_view                               | 0
Com_dealloc_sql                               | 0
Com_delete                                    | 2
Com_delete_multi                              | 0
Com_do                                        | 0
Com_drop_db                                   | 0
Com_drop_event                                | 0
Com_drop_function                             | 0
Com_drop_index                                | 0
Com_drop_procedure                            | 0
Com_drop_server                               | 0
Com_drop_table                                | 0
Com_drop_trigger                              | 0
Com_drop_user                                 | 0
Com_drop_view                                 | 0
Com_empty_query                               | 0
Com_execute_sql                               | 0
Com_explain_other                             | 0
Com_flush                                     | 0
Com_get_diagnostics                           | 0
Com_grant                                     | 0
Com_ha_close                                  | 0
Com_ha_open                                   | 0
Com_ha_read                                   | 0
Com_help                                      | 0
Com_insert                                    | 542
Com_insert_select                             | 1
Com_install_plugin                            | 0
Com_kill                                      | 0
Com_load                                      | 0
Com_lock_tables                               | 0
Com_optimize                                  | 0
Com_preload_keys                              | 0
Com_prepare_sql                               | 0
Com_purge                                     | 0
Com_purge_before_date                         | 0
Com_release_savepoint                         | 0
Com_rename_table                              | 0
Com_rename_user                               | 0
Com_repair                                    | 0
Com_replace                                   | 0
Com_replace_select                            | 0
Com_reset                                     | 0
Com_resignal                                  | 0
Com_revoke                                    | 0
Com_revoke_all                                | 0
Com_rollback                                  | 0
Com_rollback_to_savepoint                     | 0
Com_savepoint                                 | 0
Com_select                                    | 30656
Com_set_option                                | 532
Com_signal                                    | 0
Com_show_binlog_events                        | 0
Com_show_binlogs                              | 0
Com_show_charsets                             | 0
Com_show_collations                           | 16
Com_show_create_db                            | 0
Com_show_create_event                         | 0
Com_show_create_func                          | 0
Com_show_create_proc                          | 0
Com_show_create_table                         | 0
Com_show_create_trigger                       | 0
Com_show_databases                            | 0
Com_show_engine_logs                          | 0
Com_show_engine_mutex                         | 0
Com_show_engine_status                        | 0
Com_show_events                               | 0
Com_show_errors                               | 0
Com_show_fields                               | 0
Com_show_function_code                        | 0
Com_show_function_status                      | 0
Com_show_grants                               | 0
Com_show_keys                                 | 0
Com_show_master_status                        | 0
Com_show_open_tables                          | 0
Com_show_plugins                              | 0
Com_show_privileges                           | 0
Com_show_procedure_code                       | 0
Com_show_procedure_status                     | 0
Com_show_processlist                          | 0
Com_show_profile                              | 0
Com_show_profiles                             | 0
Com_show_relaylog_events                      | 0
Com_show_slave_hosts                          | 0
Com_show_slave_status                         | 0
Com_show_status                               | 1
Com_show_storage_engines                      | 0
Com_show_table_status                         | 0
Com_show_tables                               | 0
Com_show_triggers                             | 0
Com_show_variables                            | 17
Com_show_warnings                             | 375
Com_show_create_user                          | 0
Com_shutdown                                  | 0
Com_slave_start                               | 0
Com_slave_stop                                | 0
Com_group_replication_start                   | 0
Com_group_replication_stop                    | 0
Com_stmt_execute                              | 2264
Com_stmt_close                                | 2264
Com_stmt_fetch                                | 0
Com_stmt_prepare                              | 2264
Com_stmt_reset                                | 0
Com_stmt_send_long_data                       | 0
Com_truncate                                  | 0
Com_uninstall_plugin                          | 0
Com_unlock_tables                             | 0
Com_update                                    | 1204
Com_update_multi                              | 0
Com_xa_commit                                 | 0
Com_xa_end                                    | 0
Com_xa_prepare                                | 0
Com_xa_recover                                | 0
Com_xa_rollback                               | 0
Com_xa_start                                  | 0
Com_stmt_reprepare                            | 0
Connection_errors_accept                      | 0
Connection_errors_internal                    | 0
Connection_errors_max_connections             | 0
Connection_errors_peer_address                | 0
Connection_errors_select                      | 0
Connection_errors_tcpwrap                     | 0
Connections                                   | 342
Created_tmp_disk_tables                       | 0
Created_tmp_files                             | 11
Created_tmp_tables                            | 147767
Delayed_errors                                | 0
Delayed_insert_threads                        | 0
Delayed_writes                                | 0
Flush_commands                                | 1
Handler_commit                                | 32388
Handler_delete                                | 1
Handler_discover                              | 0
Handler_external_lock                         | 564581
Handler_mrr_init                              | 0
Handler_prepare                               | 0
Handler_read_first                            | 1565
Handler_read_key                              | 414968
Handler_read_last                             | 360
Handler_read_next                             | 4100377
Handler_read_prev                             | 207212
Handler_read_rnd                              | 15703
Handler_read_rnd_next                         | 4149804
Handler_rollback                              | 0
Handler_savepoint                             | 0
Handler_savepoint_rollback                    | 0
Handler_update                                | 17817
Handler_write                                 | 3996718
Innodb_buffer_pool_dump_status                | Dumping of buffer pool not     started
Innodb_buffer_pool_load_status                | Buffer pool(s) load     completed at 171117  9:20:31
Innodb_buffer_pool_resize_status              |
Innodb_buffer_pool_pages_data                 | 7204
Innodb_buffer_pool_bytes_data                 | 118030336
Innodb_buffer_pool_pages_dirty                | 105
Innodb_buffer_pool_bytes_dirty                | 1720320
Innodb_buffer_pool_pages_flushed              | 8781
Innodb_buffer_pool_pages_free                 | 988
Innodb_buffer_pool_pages_misc                 | 0
Innodb_buffer_pool_pages_total                | 8192
Innodb_buffer_pool_read_ahead_rnd             | 0
Innodb_buffer_pool_read_ahead                 | 2287
Innodb_buffer_pool_read_ahead_evicted         | 39
Innodb_buffer_pool_read_requests              | 8577383
Innodb_buffer_pool_reads                      | 217476
Innodb_buffer_pool_wait_free                  | 0
Innodb_buffer_pool_write_requests             | 162181
Innodb_data_fsyncs                            | 2971
Innodb_data_pending_fsyncs                    | 0
Innodb_data_pending_reads                     | 0
Innodb_data_pending_writes                    | 0
Innodb_data_read                              | 3691057664
Innodb_data_reads                             | 225979
Innodb_data_writes                            | 11884
Innodb_data_written                           | 316987904
Innodb_dblwr_pages_written                    | 9286
Innodb_dblwr_writes                           | 682
Innodb_log_waits                              | 0
Innodb_log_write_requests                     | 24032
Innodb_log_writes                             | 1816
Innodb_os_log_fsyncs                          | 230
Innodb_os_log_pending_fsyncs                  | 0
Innodb_os_log_pending_writes                  | 0
Innodb_os_log_written                         | 12146688
Innodb_page_size                              | 16384
Innodb_pages_created                          | 327
Innodb_pages_read                             | 224226
Innodb_pages_written                          | 9320
Innodb_row_lock_current_waits                 | 0
Innodb_row_lock_time                          | 12564
Innodb_row_lock_time_avg                      | 546
Innodb_row_lock_time_max                      | 2359
Innodb_row_lock_waits                         | 23
Innodb_rows_deleted                           | 1
Innodb_rows_inserted                          | 11063
Innodb_rows_read                              | 6571175
Innodb_rows_updated                           | 17817
Innodb_num_open_files                         | 398
Innodb_truncated_status_writes                | 0
Innodb_available_undo_logs                    | 128
Key_blocks_not_flushed                        | 0
Key_blocks_unused                             | 6698
Key_blocks_used                               | 3
Key_read_requests                             | 6
Key_reads                                     | 3
Key_write_requests                            | 0
Key_writes                                    | 0
Locked_connects                               | 0
Max_execution_time_exceeded                   | 0
Max_execution_time_set                        | 0
Max_execution_time_set_failed                 | 0
Max_used_connections                          | 40
Max_used_connections_time                     | 2017-11-17 09:30:04
Not_flushed_delayed_rows                      | 0
Ongoing_anonymous_transaction_count           | 0
Open_files                                    | 0
Open_streams                                  | 0
Open_table_definitions                        | 319
Open_tables                                   | 916
Opened_files                                  | 360
Opened_table_definitions                      | 319
Opened_tables                                 | 1066
Performance_schema_accounts_lost              | 0
Performance_schema_cond_classes_lost          | 0
Performance_schema_cond_instances_lost        | 0
Performance_schema_digest_lost                | 0
Performance_schema_file_classes_lost          | 0
Performance_schema_file_handles_lost          | 0
Performance_schema_file_instances_lost        | 0
Performance_schema_hosts_lost                 | 0
Performance_schema_index_stat_lost            | 0
Performance_schema_locker_lost                | 0
Performance_schema_memory_classes_lost        | 0
Performance_schema_metadata_lock_lost         | 0
Performance_schema_mutex_classes_lost         | 0
Performance_schema_mutex_instances_lost       | 0
Performance_schema_nested_statement_lost      | 0
Performance_schema_prepared_statements_lost   | 0
Performance_schema_program_lost               | 0
Performance_schema_rwlock_classes_lost        | 0
Performance_schema_rwlock_instances_lost      | 0
Performance_schema_session_connect_attrs_lost | 0
Performance_schema_socket_classes_lost        | 0
Performance_schema_socket_instances_lost      | 0
Performance_schema_stage_classes_lost         | 0
Performance_schema_statement_classes_lost     | 0
Performance_schema_table_handles_lost         | 0
Performance_schema_table_instances_lost       | 0
Performance_schema_table_lock_stat_lost       | 0
Performance_schema_thread_classes_lost        | 0
Performance_schema_thread_instances_lost      | 0
Performance_schema_users_lost                 | 0
Prepared_stmt_count                           | 0
Qcache_free_blocks                            | 0
Qcache_free_memory                            | 0
Qcache_hits                                   | 0
Qcache_inserts                                | 0
Qcache_lowmem_prunes                          | 0
Qcache_not_cached                             | 0
Qcache_queries_in_cache                       | 0
Qcache_total_blocks                           | 0
Queries                                       | 39149
Questions                                     | 34567
Select_full_join                              | 439
Select_full_range_join                        | 1
Select_range                                  | 1572
Select_range_check                            | 0
Select_scan                                   | 197553
Slave_open_temp_tables                        | 0
Slow_launch_threads                           | 0
Slow_queries                                  | 0
Sort_merge_passes                             | 7
Sort_range                                    | 428
Sort_rows                                     | 14902
Sort_scan                                     | 27
Ssl_accept_renegotiates                       | 0
Ssl_accepts                                   | 0
Ssl_callback_cache_hits                       | 0
Ssl_cipher                                    |
Ssl_cipher_list                               |
Ssl_client_connects                           | 0
Ssl_connect_renegotiates                      | 0
Ssl_ctx_verify_depth                          | 0
Ssl_ctx_verify_mode                           | 0
Ssl_default_timeout                           | 0
Ssl_finished_accepts                          | 0
Ssl_finished_connects                         | 0
Ssl_server_not_after                          |
Ssl_server_not_before                         |
Ssl_session_cache_hits                        | 0
Ssl_session_cache_misses                      | 0
Ssl_session_cache_mode                        | NONE
Ssl_session_cache_overflows                   | 0
Ssl_session_cache_size                        | 0
Ssl_session_cache_timeouts                    | 0
Ssl_sessions_reused                           | 0
Ssl_used_session_cache_entries                | 0
Ssl_verify_depth                              | 0
Ssl_verify_mode                               | 0
Ssl_version                                   |
Table_locks_immediate                         | 116
Table_locks_waited                            | 0
Table_open_cache_hits                         | 286526
Table_open_cache_misses                       | 1066
Table_open_cache_overflows                    | 143
Tc_log_max_pages_used                         | 0
Tc_log_page_size                              | 0
Tc_log_page_waits                             | 0
Threads_cached                                | 8
Threads_connected                             | 9
Threads_created                               | 83
Threads_running                               | 5
Uptime                                        | 1022
Uptime_since_flush_status                     | 1022
</code>```

答:
From your UPTIME of 1022 seconds GLOBAL STATUS report, research and consider these my.cnf/ini  add/change/disable with leading # or REMOVE to avoid clutter.  Normally only 1 change is made per day and monitor.  In your case, with 18 minute crashes, let's make them all in one shutdown/restart.

```<code>thread_cache_size=100 # from default because 83 threads created already, V8 CAP is 100 to avoid OOM
innodb_buffer_pool_size=6G # from default of 128M, was full in 17 minutes
table_open_cache=10000 # 1066 already opened in 17 minutes.
</code>```

Desperately need your SHOW GLOBAL VARIABLES; and SHOW ENGINE INNODB STATUS; and complete my.cnf/ini to avoid GUESSING for additional suggestions.  dropbox.com or pastebin.com are reasonable places to share data if you are reaching storage limits here.

Search for '[MySQL] Semaphore wait has lasted' to find earlier solutions in stackoverflow.com  dba.stackexchange.com or serverfault.com  (our pw are shared by these 3 sites, so you do not need 3 accounts).

The rollback was dealing with 17,856,929 rows.  In a single transaction, that is a load that needs analysis for breaking it up into more manageable row counts for a single transaction.

update 2017-11-18 about 09 UTC  wh
In my.cnf/ini [mysqld] section you NEED

```<code>innodb_log_buffer_size=48M # from 256M
innodb_log_file_size=256M # from default of 48M
</code>```

Today, they are backwards and are a significant part of the cause of your 17 minute restarts.
Shutdown/restart required neither value can be dynamically changed.

Body:
MySQL 5.7.16 server on Windows Server 2012R2 with 32GB RAM is now restarting itself every 18minutes or so with the following in the error log:

InnoDB: ###### Diagnostic info printed to the standard error stream 2017-11-
16T13:18:39.650036Z 0 [ERROR] [FATAL] InnoDB: Semaphore wait has lasted >
600 seconds. We intentionally crash the server because it appears to be
hung.
2017-11-16 13:18:39 0x1bcc  InnoDB: Assertion failure in thread 7116 in file
ut0ut.cc line 916
InnoDB: We intentionally generate a memory trap.
InnoDB: Submit a detailed bug report to http://bugs.mysql.com.
InnoDB: If you get repeated assertion failures or crashes, even
InnoDB: immediately after the mysqld startup, there may be
InnoDB: corruption in the InnoDB tablespace. Please refer to
InnoDB: http://dev.mysql.com/doc/refman/5.7/en/forcing-innodb-recovery.html
InnoDB: about forcing recovery.
13:18:39 UTC - 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.
Attempting to collect some information that could help diagnose the problem.
As this is a crash and something is definitely wrong, the information
collection process might fail.

key_buffer_size=8388608
read_buffer_size=131072
max_used_connections=34
max_threads=151
thread_count=6
connection_count=6
It is possible that mysqld could use up to
key_buffer_size + (read_buffer_size + sort_buffer_size)*max_threads = 68011K bytes of memory
Hope that's ok; if not, decrease some variables in the equation.

Thread pointer: 0x0
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...
7ff7eeb7e262    mysqld.exe!my_sigabrt_handler()[my_thr_init.c:449]
7ff7eef28489    mysqld.exe!raise()[winsig.c:587]
7ff7eef27380    mysqld.exe!abort()[abort.c:82]
7ff7eec8f178    mysqld.exe!ut_dbg_assertion_failed()[ut0dbg.cc:67]
7ff7eec8f391    mysqld.exe!ib::fatal::~fatal()[ut0ut.cc:916]
7ff7eebfd43d    mysqld.exe!srv_error_monitor_thread()[srv0srv.cc:1724]
7ffc55d613d2    KERNEL32.DLL!BaseThreadInitThunk()
7ffc57d854e4    ntdll.dll!RtlUserThreadStart()
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.

There appears to be a transaction which is being rolled back when the server restarts. The following can be found in the information_schema.innodb_trx\G

trx_id: 309725166
trx_state: ROLLING BACK
trx_started: 2017-11-16 13:30:18
trx_requested_lock_id: NULL
trx_wait_started: NULL
trx_weight: 17856930
trx_mysql_thread_id: 0
trx_query: NULL
trx_operation_state: NULL
trx_tables_in_use: 0
trx_tables_locked: 1
trx_lock_structs: 1
trx_lock_memory_bytes: 1136
trx_rows_locked: 0
trx_rows_modified: 17856929
trx_concurrency_tickets: 0
trx_isolation_level: REPEATABLE READ
trx_unique_checks: 1
trx_foreign_key_checks: 1
trx_last_foreign_key_error: NULL
trx_adaptive_hash_latched: 0
trx_adaptive_hash_timeout: 0
trx_is_read_only: 0
trx_autocommit_non_locking: 0

Is it possible to stop this transaction being rolled back?

Results from SHOW GLOBAL STATUS:

Aborted_clients                               | 0
Aborted_connects                              | 0
Binlog_cache_disk_use                         | 0
Binlog_cache_use                              | 0
Binlog_stmt_cache_disk_use                    | 0
Binlog_stmt_cache_use                         | 0
Bytes_received                                | 79456733
Bytes_sent                                    | 132918726
Com_admin_commands                            | 53
Com_assign_to_keycache                        | 0
Com_alter_db                                  | 0
Com_alter_db_upgrade                          | 0
Com_alter_event                               | 0
Com_alter_function                            | 0
Com_alter_instance                            | 0
Com_alter_procedure                           | 0
Com_alter_server                              | 0
Com_alter_table                               | 0
Com_alter_tablespace                          | 0
Com_alter_user                                | 0
Com_analyze                                   | 0
Com_begin                                     | 0
Com_binlog                                    | 0
Com_call_procedure                            | 0
Com_change_db                                 | 890
Com_change_master                             | 0
Com_change_repl_filter                        | 0
Com_check                                     | 0
Com_checksum                                  | 0
Com_commit                                    | 0
Com_create_db                                 | 0
Com_create_event                              | 0
Com_create_function                           | 0
Com_create_index                              | 0
Com_create_procedure                          | 0
Com_create_server                             | 0
Com_create_table                              | 0
Com_create_trigger                            | 0
Com_create_udf                                | 0
Com_create_user                               | 0
Com_create_view                               | 0
Com_dealloc_sql                               | 0
Com_delete                                    | 2
Com_delete_multi                              | 0
Com_do                                        | 0
Com_drop_db                                   | 0
Com_drop_event                                | 0
Com_drop_function                             | 0
Com_drop_index                                | 0
Com_drop_procedure                            | 0
Com_drop_server                               | 0
Com_drop_table                                | 0
Com_drop_trigger                              | 0
Com_drop_user                                 | 0
Com_drop_view                                 | 0
Com_empty_query                               | 0
Com_execute_sql                               | 0
Com_explain_other                             | 0
Com_flush                                     | 0
Com_get_diagnostics                           | 0
Com_grant                                     | 0
Com_ha_close                                  | 0
Com_ha_open                                   | 0
Com_ha_read                                   | 0
Com_help                                      | 0
Com_insert                                    | 542
Com_insert_select                             | 1
Com_install_plugin                            | 0
Com_kill                                      | 0
Com_load                                      | 0
Com_lock_tables                               | 0
Com_optimize                                  | 0
Com_preload_keys                              | 0
Com_prepare_sql                               | 0
Com_purge                                     | 0
Com_purge_before_date                         | 0
Com_release_savepoint                         | 0
Com_rename_table                              | 0
Com_rename_user                               | 0
Com_repair                                    | 0
Com_replace                                   | 0
Com_replace_select                            | 0
Com_reset                                     | 0
Com_resignal                                  | 0
Com_revoke                                    | 0
Com_revoke_all                                | 0
Com_rollback                                  | 0
Com_rollback_to_savepoint                     | 0
Com_savepoint                                 | 0
Com_select                                    | 30656
Com_set_option                                | 532
Com_signal                                    | 0
Com_show_binlog_events                        | 0
Com_show_binlogs                              | 0
Com_show_charsets                             | 0
Com_show_collations                           | 16
Com_show_create_db                            | 0
Com_show_create_event                         | 0
Com_show_create_func                          | 0
Com_show_create_proc                          | 0
Com_show_create_table                         | 0
Com_show_create_trigger                       | 0
Com_show_databases                            | 0
Com_show_engine_logs                          | 0
Com_show_engine_mutex                         | 0
Com_show_engine_status                        | 0
Com_show_events                               | 0
Com_show_errors                               | 0
Com_show_fields                               | 0
Com_show_function_code                        | 0
Com_show_function_status                      | 0
Com_show_grants                               | 0
Com_show_keys                                 | 0
Com_show_master_status                        | 0
Com_show_open_tables                          | 0
Com_show_plugins                              | 0
Com_show_privileges                           | 0
Com_show_procedure_code                       | 0
Com_show_procedure_status                     | 0
Com_show_processlist                          | 0
Com_show_profile                              | 0
Com_show_profiles                             | 0
Com_show_relaylog_events                      | 0
Com_show_slave_hosts                          | 0
Com_show_slave_status                         | 0
Com_show_status                               | 1
Com_show_storage_engines                      | 0
Com_show_table_status                         | 0
Com_show_tables                               | 0
Com_show_triggers                             | 0
Com_show_variables                            | 17
Com_show_warnings                             | 375
Com_show_create_user                          | 0
Com_shutdown                                  | 0
Com_slave_start                               | 0
Com_slave_stop                                | 0
Com_group_replication_start                   | 0
Com_group_replication_stop                    | 0
Com_stmt_execute                              | 2264
Com_stmt_close                                | 2264
Com_stmt_fetch                                | 0
Com_stmt_prepare                              | 2264
Com_stmt_reset                                | 0
Com_stmt_send_long_data                       | 0
Com_truncate                                  | 0
Com_uninstall_plugin                          | 0
Com_unlock_tables                             | 0
Com_update                                    | 1204
Com_update_multi                              | 0
Com_xa_commit                                 | 0
Com_xa_end                                    | 0
Com_xa_prepare                                | 0
Com_xa_recover                                | 0
Com_xa_rollback                               | 0
Com_xa_start                                  | 0
Com_stmt_reprepare                            | 0
Connection_errors_accept                      | 0
Connection_errors_internal                    | 0
Connection_errors_max_connections             | 0
Connection_errors_peer_address                | 0
Connection_errors_select                      | 0
Connection_errors_tcpwrap                     | 0
Connections                                   | 342
Created_tmp_disk_tables                       | 0
Created_tmp_files                             | 11
Created_tmp_tables                            | 147767
Delayed_errors                                | 0
Delayed_insert_threads                        | 0
Delayed_writes                                | 0
Flush_commands                                | 1
Handler_commit                                | 32388
Handler_delete                                | 1
Handler_discover                              | 0
Handler_external_lock                         | 564581
Handler_mrr_init                              | 0
Handler_prepare                               | 0
Handler_read_first                            | 1565
Handler_read_key                              | 414968
Handler_read_last                             | 360
Handler_read_next                             | 4100377
Handler_read_prev                             | 207212
Handler_read_rnd                              | 15703
Handler_read_rnd_next                         | 4149804
Handler_rollback                              | 0
Handler_savepoint                             | 0
Handler_savepoint_rollback                    | 0
Handler_update                                | 17817
Handler_write                                 | 3996718
Innodb_buffer_pool_dump_status                | Dumping of buffer pool not     started
Innodb_buffer_pool_load_status                | Buffer pool(s) load     completed at 171117  9:20:31
Innodb_buffer_pool_resize_status              |
Innodb_buffer_pool_pages_data                 | 7204
Innodb_buffer_pool_bytes_data                 | 118030336
Innodb_buffer_pool_pages_dirty                | 105
Innodb_buffer_pool_bytes_dirty                | 1720320
Innodb_buffer_pool_pages_flushed              | 8781
Innodb_buffer_pool_pages_free                 | 988
Innodb_buffer_pool_pages_misc                 | 0
Innodb_buffer_pool_pages_total                | 8192
Innodb_buffer_pool_read_ahead_rnd             | 0
Innodb_buffer_pool_read_ahead                 | 2287
Innodb_buffer_pool_read_ahead_evicted         | 39
Innodb_buffer_pool_read_requests              | 8577383
Innodb_buffer_pool_reads                      | 217476
Innodb_buffer_pool_wait_free                  | 0
Innodb_buffer_pool_write_requests             | 162181
Innodb_data_fsyncs                            | 2971
Innodb_data_pending_fsyncs                    | 0
Innodb_data_pending_reads                     | 0
Innodb_data_pending_writes                    | 0
Innodb_data_read                              | 3691057664
Innodb_data_reads                             | 225979
Innodb_data_writes                            | 11884
Innodb_data_written                           | 316987904
Innodb_dblwr_pages_written                    | 9286
Innodb_dblwr_writes                           | 682
Innodb_log_waits                              | 0
Innodb_log_write_requests                     | 24032
Innodb_log_writes                             | 1816
Innodb_os_log_fsyncs                          | 230
Innodb_os_log_pending_fsyncs                  | 0
Innodb_os_log_pending_writes                  | 0
Innodb_os_log_written                         | 12146688
Innodb_page_size                              | 16384
Innodb_pages_created                          | 327
Innodb_pages_read                             | 224226
Innodb_pages_written                          | 9320
Innodb_row_lock_current_waits                 | 0
Innodb_row_lock_time                          | 12564
Innodb_row_lock_time_avg                      | 546
Innodb_row_lock_time_max                      | 2359
Innodb_row_lock_waits                         | 23
Innodb_rows_deleted                           | 1
Innodb_rows_inserted                          | 11063
Innodb_rows_read                              | 6571175
Innodb_rows_updated                           | 17817
Innodb_num_open_files                         | 398
Innodb_truncated_status_writes                | 0
Innodb_available_undo_logs                    | 128
Key_blocks_not_flushed                        | 0
Key_blocks_unused                             | 6698
Key_blocks_used                               | 3
Key_read_requests                             | 6
Key_reads                                     | 3
Key_write_requests                            | 0
Key_writes                                    | 0
Locked_connects                               | 0
Max_execution_time_exceeded                   | 0
Max_execution_time_set                        | 0
Max_execution_time_set_failed                 | 0
Max_used_connections                          | 40
Max_used_connections_time                     | 2017-11-17 09:30:04
Not_flushed_delayed_rows                      | 0
Ongoing_anonymous_transaction_count           | 0
Open_files                                    | 0
Open_streams                                  | 0
Open_table_definitions                        | 319
Open_tables                                   | 916
Opened_files                                  | 360
Opened_table_definitions                      | 319
Opened_tables                                 | 1066
Performance_schema_accounts_lost              | 0
Performance_schema_cond_classes_lost          | 0
Performance_schema_cond_instances_lost        | 0
Performance_schema_digest_lost                | 0
Performance_schema_file_classes_lost          | 0
Performance_schema_file_handles_lost          | 0
Performance_schema_file_instances_lost        | 0
Performance_schema_hosts_lost                 | 0
Performance_schema_index_stat_lost            | 0
Performance_schema_locker_lost                | 0
Performance_schema_memory_classes_lost        | 0
Performance_schema_metadata_lock_lost         | 0
Performance_schema_mutex_classes_lost         | 0
Performance_schema_mutex_instances_lost       | 0
Performance_schema_nested_statement_lost      | 0
Performance_schema_prepared_statements_lost   | 0
Performance_schema_program_lost               | 0
Performance_schema_rwlock_classes_lost        | 0
Performance_schema_rwlock_instances_lost      | 0
Performance_schema_session_connect_attrs_lost | 0
Performance_schema_socket_classes_lost        | 0
Performance_schema_socket_instances_lost      | 0
Performance_schema_stage_classes_lost         | 0
Performance_schema_statement_classes_lost     | 0
Performance_schema_table_handles_lost         | 0
Performance_schema_table_instances_lost       | 0
Performance_schema_table_lock_stat_lost       | 0
Performance_schema_thread_classes_lost        | 0
Performance_schema_thread_instances_lost      | 0
Performance_schema_users_lost                 | 0
Prepared_stmt_count                           | 0
Qcache_free_blocks                            | 0
Qcache_free_memory                            | 0
Qcache_hits                                   | 0
Qcache_inserts                                | 0
Qcache_lowmem_prunes                          | 0
Qcache_not_cached                             | 0
Qcache_queries_in_cache                       | 0
Qcache_total_blocks                           | 0
Queries                                       | 39149
Questions                                     | 34567
Select_full_join                              | 439
Select_full_range_join                        | 1
Select_range                                  | 1572
Select_range_check                            | 0
Select_scan                                   | 197553
Slave_open_temp_tables                        | 0
Slow_launch_threads                           | 0
Slow_queries                                  | 0
Sort_merge_passes                             | 7
Sort_range                                    | 428
Sort_rows                                     | 14902
Sort_scan                                     | 27
Ssl_accept_renegotiates                       | 0
Ssl_accepts                                   | 0
Ssl_callback_cache_hits                       | 0
Ssl_cipher                                    |
Ssl_cipher_list                               |
Ssl_client_connects                           | 0
Ssl_connect_renegotiates                      | 0
Ssl_ctx_verify_depth                          | 0
Ssl_ctx_verify_mode                           | 0
Ssl_default_timeout                           | 0
Ssl_finished_accepts                          | 0
Ssl_finished_connects                         | 0
Ssl_server_not_after                          |
Ssl_server_not_before                         |
Ssl_session_cache_hits                        | 0
Ssl_session_cache_misses                      | 0
Ssl_session_cache_mode                        | NONE
Ssl_session_cache_overflows                   | 0
Ssl_session_cache_size                        | 0
Ssl_session_cache_timeouts                    | 0
Ssl_sessions_reused                           | 0
Ssl_used_session_cache_entries                | 0
Ssl_verify_depth                              | 0
Ssl_verify_mode                               | 0
Ssl_version                                   |
Table_locks_immediate                         | 116
Table_locks_waited                            | 0
Table_open_cache_hits                         | 286526
Table_open_cache_misses                       | 1066
Table_open_cache_overflows                    | 143
Tc_log_max_pages_used                         | 0
Tc_log_page_size                              | 0
Tc_log_page_waits                             | 0
Threads_cached                                | 8
Threads_connected                             | 9
Threads_created                               | 83
Threads_running                               | 5
Uptime                                        | 1022
Uptime_since_flush_status                     | 1022

Body:
From your UPTIME of 1022 seconds GLOBAL STATUS report, research and consider these my.cnf/ini  add/change/disable with leading # or REMOVE to avoid clutter.  Normally only 1 change is made per day and monitor.  In your case, with 18 minute crashes, let's make them all in one shutdown/restart.

thread_cache_size=100 # from default because 83 threads created already, V8 CAP is 100 to avoid OOM
innodb_buffer_pool_size=6G # from default of 128M, was full in 17 minutes
table_open_cache=10000 # 1066 already opened in 17 minutes.

Desperately need your SHOW GLOBAL VARIABLES; and SHOW ENGINE INNODB STATUS; and complete my.cnf/ini to avoid GUESSING for additional suggestions.  dropbox.com or pastebin.com are reasonable places to share data if you are reaching storage limits here.

Search for '[MySQL] Semaphore wait has lasted' to find earlier solutions in stackoverflow.com  dba.stackexchange.com or serverfault.com  (our pw are shared by these 3 sites, so you do not need 3 accounts).

The rollback was dealing with 17,856,929 rows.  In a single transaction, that is a load that needs analysis for breaking it up into more manageable row counts for a single transaction.

update 2017-11-18 about 09 UTC  wh
In my.cnf/ini [mysqld] section you NEED

innodb_log_buffer_size=48M # from 256M
innodb_log_file_size=256M # from default of 48M

Today, they are backwards and are a significant part of the cause of your 17 minute restarts.
Shutdown/restart required neither value can be dynamically changed.


来源: stackexchange

问:
WordPress wp_count_terms() number of tags
I want to count the number of terms in my own Custom Post Type. I use the following code:

```<code>$posttags = the_terms( get_the_ID(), 'yacht-detail');
$count = wp_count_terms($posttags);
echo $count;
</code>```

The code is working, but it counts every word, not every term. I have two- or three-word-terms. And wp_count_terms counts every word.

How can I achieve the right counting?

答:
I guess the yacht-detail is your taxonomy

```<code>$count = wp_count_terms('yacht-detail');
echo $count;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to count the number of terms in my own Custom Post Type. I use the following code:

$posttags = the_terms( get_the_ID(), 'yacht-detail');
$count = wp_count_terms($posttags);
echo $count;

The code is working, but it counts every word, not every term. I have two- or three-word-terms. And wp_count_terms counts every word.

How can I achieve the right counting?

Body:
I guess the yacht-detail is your taxonomy

$count = wp_count_terms('yacht-detail');
echo $count;


问:
VBScript to run a file from desktop (any user)
I've created a VBScript to run a macro from excel without opening the file.

```<code>Set objExcel = CreateObject("Excel.Application")
objExcel.Application.Run "'C:\Users\MyUser\Desktop\RM.xlsm'!Module4.Email"
objExcel.DisplayAlerts = False
objExcel.Application.Quit
Set objExcel = Nothing
</code>```

I want to use this VBScript & XLSM file on different computers, so how can i change this script to work without editing the path every time?

(Maybe a code to run from current folder or a code to run from any user desktop)

答:
If the file will always be on the desktop of every user then you can use environment variables to determine the location.

```<code>Set wshShell = CreateObject( "WScript.Shell" )
userName = wshShell.ExpandEnvironmentStrings( "%UserName%" )

path = "'C:\Users\" + userName + "\Desktop\RM.xlsm'!Module4.Email"
Set objExcel = CreateObject("Excel.Application")
objExcel.Application.Run path
objExcel.DisplayAlerts = False
objExcel.Application.Quit
Set objExcel = Nothing
</code>```

(Untested code)

If the file is not on each user's desktop then you'll need to store it in a common location on the network and have each user access it from there, e.g. in .

```<code>\\YourFileSever\SharedFiles\RM.xlsm
</code>```

In practical terms the latter is preferable as it means the workbook is in only one place and when it comes to releasing a new version you only have to update one copy

Body:
I've created a VBScript to run a macro from excel without opening the file.

Set objExcel = CreateObject("Excel.Application")
objExcel.Application.Run "'C:\Users\MyUser\Desktop\RM.xlsm'!Module4.Email"
objExcel.DisplayAlerts = False
objExcel.Application.Quit
Set objExcel = Nothing

I want to use this VBScript & XLSM file on different computers, so how can i change this script to work without editing the path every time?

(Maybe a code to run from current folder or a code to run from any user desktop)

Body:
If the file will always be on the desktop of every user then you can use environment variables to determine the location.

Set wshShell = CreateObject( "WScript.Shell" )
userName = wshShell.ExpandEnvironmentStrings( "%UserName%" )

path = "'C:\Users\" + userName + "\Desktop\RM.xlsm'!Module4.Email"
Set objExcel = CreateObject("Excel.Application")
objExcel.Application.Run path
objExcel.DisplayAlerts = False
objExcel.Application.Quit
Set objExcel = Nothing

(Untested code)

If the file is not on each user's desktop then you'll need to store it in a common location on the network and have each user access it from there, e.g. in .

\\YourFileSever\SharedFiles\RM.xlsm

In practical terms the latter is preferable as it means the workbook is in only one place and when it comes to releasing a new version you only have to update one copy


问:
Analyze Heap usage in Java 8 Release 144 - feature removed? how to analyze heap then?
I am trying to use the heap and jstat commands to analyze heap usage by the different IDE and programs using Java, as my machine is incredibly slow.

I have 16 GIG Ram, my min Heap is 252MB, my max Heap is 3,9 Gig. Now I want to know the heap usage by different programs.

jmap was experimental and removed in Release 60, can you kindly tell me if there is

1) a way to use jmap in Release 144 using Java Advanced Management Console? If so, how?

2) An alternative program / command line manager by a third party to analyze Java heap usage?

3) Would Java Usage Tracker be an alternative? If so, what would I need to consider?

Thank you.

BR,
SN

答:
You can do a thread dump in linux - kill -3 [java-process-number],
the thread dump will appear in the log file of the process.
In the end of the thread dump you will see some statistic about the heap usage.
example:

```<code>Heap
 garbage-first heap   total 524288K, used 14336K [0x00000007a0000000, 0x00000007a0101000, 0x00000007c0000000)
  region size 1024K, 15 young (15360K), 0 survivors (0K)
 Metaspace       used 8584K, capacity 8688K, committed 8832K, reserved 1056768K
 class space    used 1022K, capacity 1080K, committed 1152K, reserved 1048576K
</code>```

Body:
You can do a thread dump in linux - kill -3 [java-process-number],
the thread dump will appear in the log file of the process.
In the end of the thread dump you will see some statistic about the heap usage.
example:

Heap
 garbage-first heap   total 524288K, used 14336K [0x00000007a0000000, 0x00000007a0101000, 0x00000007c0000000)
  region size 1024K, 15 young (15360K), 0 survivors (0K)
 Metaspace       used 8584K, capacity 8688K, committed 8832K, reserved 1056768K
 class space    used 1022K, capacity 1080K, committed 1152K, reserved 1048576K


问:
How to show Woo Category (clothing) and WP Category (php) at a time in wordpress php
I want to show only two categories one from wp categories (category name - php) and one from woo categories (category name - clothing) and hide remaining woo and wp categories except php and clothing. How can i do this?</p>

```<code>function custom_pre_get_posts_query( $q ) {
  $tax_query = (array) $q->get( 'tax_query' );

  $tax_query[] = array(
       'taxonomy' => 'product_cat',
       'field' => 'slug',
       'terms' => array( 'clothing' ), // clothing is woo category name
       'operator' => 'IN'
  );

  $tax_query[] = array(
       'taxonomy' => 'category',
       'field' => 'slug',
       'terms' => array( 'php' ), // php is wp category name
       'operator' => 'IN'
  );

  $q->set( 'tax_query', $tax_query );
}

add_action( 'pre_get_posts', 'custom_pre_get_posts_query' );
</code>```

答:
Finally i got the solution guys...</p>

```<code>           `$tax_query[] = array(
                'relation' => 'OR',
                array(
                    'taxonomy' => 'category',
                    'field' => 'term_id',
                    'terms' => array('php'),
                    'operator' => 'IN'
                ),
                array(
                    'taxonomy' => 'product_cat',
                    'field' => 'term_id',
                    'terms' => array('clothing'),
                    'operator' => 'IN'
                )
            );`
</code>```

Body:
I want to show only two categories one from wp categories (category name - php) and one from woo categories (category name - clothing) and hide remaining woo and wp categories except php and clothing. How can i do this?

function custom_pre_get_posts_query( $q ) {
  $tax_query = (array) $q->get( 'tax_query' );

  $tax_query[] = array(
       'taxonomy' => 'product_cat',
       'field' => 'slug',
       'terms' => array( 'clothing' ), // clothing is woo category name
       'operator' => 'IN'
  );

  $tax_query[] = array(
       'taxonomy' => 'category',
       'field' => 'slug',
       'terms' => array( 'php' ), // php is wp category name
       'operator' => 'IN'
  );

  $q->set( 'tax_query', $tax_query );
}

add_action( 'pre_get_posts', 'custom_pre_get_posts_query' );

Body:
Finally i got the solution guys...

           `$tax_query[] = array(
                'relation' => 'OR',
                array(
                    'taxonomy' => 'category',
                    'field' => 'term_id',
                    'terms' => array('php'),
                    'operator' => 'IN'
                ),
                array(
                    'taxonomy' => 'product_cat',
                    'field' => 'term_id',
                    'terms' => array('clothing'),
                    'operator' => 'IN'
                )
            );`


问:
Why is unsigned 4 not considered greater than signed -2?
```<code>unsigned int x = 4;
int y = -2;
int z = x > y;
</code>```

When realizing this operation the value for the variable Z is 0, but why it is 0 and not 1?.

答:
Believe it or not, if a C expression is formed from two arguments, one with an int type and the other with an unsigned type, then the int value is promoted to an unsigned type prior to the comparison taking place.

So in your case, y is promoted to an unsigned type. Because it's negative, it will be converted by having UINT_MAX + 1 added to it, and it will assume a value UINT_MAX - 1.

Therefore x > y will be 0.

Yes, this is the cause of very many bugs. Even professional programmers fall for this from time to time. Some compilers can warn you: for example, with gcc, if you compile with -Wextra you will get a warning.

Body:
unsigned int x = 4;
int y = -2;
int z = x > y;

When realizing this operation the value for the variable Z is 0, but why it is 0 and not 1?.


问:
Get the next lowest ID or the greatest?
This is the SQL I have so far:

```<code>  SELECT  `cimg`.*,
          `pimg`.`id` as `prev`,
          `nimg`.`id` as `next`
  FROM    `images` as `cimg`,
          `images` as `pimg`,
          `images` as `nimg`
  WHERE   `cimg`.`id` = :id AND
          `pimg`.`id` = (
            SELECT  max(`id`)
            FROM    `images`
            WHERE   `id` < :id
          ) AND
          `nimg`.`id` = (
            SELECT  min(`id`)
            FROM    `images`
            WHERE   `id` > :id
          )
</code>```

It basically selects all of the data from a row, then selects the id of the row above it and below it.

However when the current row is one of the extremes, I need it to then get the id of the other extreme for its prev (if it is the lowest) or next (if it is the greatest).

Kind of like a carousel or loop. E.g. we have a table with id's 2, 5, 10, 20 and 53.

If it was the lowest row as current row, we would return all of the data for the row with id 2 and additionally two more columns; 53 as prev and 5 as next.

答:
Basically what you'd want to do is check if there is a value or not. When there is no value in your subquery it should return the MAX() or MIN() value of id.

Not sure whether this is the best option but it should do the trick.

```<code>SELECT
    `cimg`.*, `pimg`.`id` AS `prev`, `nimg`.`id` AS `next`
FROM
    `images` AS `cimg`,
    `images` AS `pimg`,
    `images` AS `nimg`
WHERE
    `cimg`.`id` = :id
AND `pimg`.`id` =
    CASE WHEN (SELECT MAX(`id`) FROM `images` WHERE `id` < :id) IS NOT NULL
        THEN (SELECT MAX(`id`) FROM `images` WHERE `id` < :id)
        ELSE (SELECT MAX(`id`) FROM `images`)
    END
AND `nimg`.`id` =
    CASE  WHEN (SELECT  MIN(`id`) FROM `images` WHERE `id` > :id) IS NOT NULL
        THEN (SELECT  MIN(`id`) FROM `images` WHERE `id` > :id)
        ELSE (SELECT  MIN(`id`) FROM `images`)
    END
;
</code>```

Title: Get the next lowest ID or the greatest?

Body:
This is the SQL I have so far:

  SELECT  `cimg`.*,
          `pimg`.`id` as `prev`,
          `nimg`.`id` as `next`
  FROM    `images` as `cimg`,
          `images` as `pimg`,
          `images` as `nimg`
  WHERE   `cimg`.`id` = :id AND
          `pimg`.`id` = (
            SELECT  max(`id`)
            FROM    `images`
            WHERE   `id` < :id
          ) AND
          `nimg`.`id` = (
            SELECT  min(`id`)
            FROM    `images`
            WHERE   `id` > :id
          )

It basically selects all of the data from a row, then selects the id of the row above it and below it.

However when the current row is one of the extremes, I need it to then get the id of the other extreme for its prev (if it is the lowest) or next (if it is the greatest).

Kind of like a carousel or loop. E.g. we have a table with id's 2, 5, 10, 20 and 53.

If it was the lowest row as current row, we would return all of the data for the row with id 2 and additionally two more columns; 53 as prev and 5 as next.

Body:
Basically what you'd want to do is check if there is a value or not. When there is no value in your subquery it should return the MAX() or MIN() value of id.

Not sure whether this is the best option but it should do the trick.

SELECT
    `cimg`.*, `pimg`.`id` AS `prev`, `nimg`.`id` AS `next`
FROM
    `images` AS `cimg`,
    `images` AS `pimg`,
    `images` AS `nimg`
WHERE
    `cimg`.`id` = :id
AND `pimg`.`id` =
    CASE WHEN (SELECT MAX(`id`) FROM `images` WHERE `id` < :id) IS NOT NULL
        THEN (SELECT MAX(`id`) FROM `images` WHERE `id` < :id)
        ELSE (SELECT MAX(`id`) FROM `images`)
    END
AND `nimg`.`id` =
    CASE  WHEN (SELECT  MIN(`id`) FROM `images` WHERE `id` > :id) IS NOT NULL
        THEN (SELECT  MIN(`id`) FROM `images` WHERE `id` > :id)
        ELSE (SELECT  MIN(`id`) FROM `images`)
    END
;


问:
ASP.Net: Call an async method in Page_Load
I have this API client which has a send method used to post my object to a Web API service and return an object of type ReturnedResults.
Now I need to run this post method in an ASP.net page_load event.
I have seen similar examples here, however what I need is to get my return object from my async method.

I know that I am supposed to use

```<code>PageAsyncTask t = new PageAsyncTask(APIService.Send("test"));
</code>```

However I have two problems, first PageAsyncTask doesn't accept my Send method as a valid Task type, I guess that's because my method returns a Task of Task type  so it complains that it can't convert Task to System.Func

Also how can I get my object of ReturnedResults out of this once it is successfully executed?

答:
Just because you can't await the result of a PageAsyncTask doesn't mean that the task itself can't kick off more functions that you can then await. You can take advantage of this to have an async page load.

```<code>public void Page_Load(object sender, EventArgs e)
{
    RegisterAsyncTask(new PageAsyncTask(PageLoadAsync));
}

public async Task PageLoadAsync()
{
    //perform your actions here, including calling async methods and awaiting their results

    Task<string> downloadTask = new WebClient().DownloadStringTaskAsync("http://www.example.com");

    TextBox1.Title = "We can do some actions while waiting for the task to complete";

    TextBox2.Title = await downloadTask;
}
</code>```

Make sure your page is marked as async.

```<code><%@ Page Language="C#" CodeBehind="Default.aspx.cs" Inherits="Default" Async="true" %>
</code>```

Keep in mind that the above code is slightly misleading. ASP.NET Web Forms is still based on the HTTP request/response model. It can't actually update a textbox's title on the client side while waiting for some file to download. Instead, it updates the textbox's title in the HTTP response, and once all server side processing is done (including your asynchronous tasks) it will then send the response to the client, at which point they'll see the updated textbox's title.

Body:
I have this API client which has a send method used to post my object to a Web API service and return an object of type ReturnedResults.
Now I need to run this post method in an ASP.net page_load event.
I have seen similar examples here, however what I need is to get my return object from my async method.

I know that I am supposed to use

PageAsyncTask t = new PageAsyncTask(APIService.Send("test"));

However I have two problems, first PageAsyncTask doesn't accept my Send method as a valid Task type, I guess that's because my method returns a Task of Task type  so it complains that it can't convert Task to System.Func

Also how can I get my object of ReturnedResults out of this once it is successfully executed?

Body:
Just because you can't await the result of a PageAsyncTask doesn't mean that the task itself can't kick off more functions that you can then await. You can take advantage of this to have an async page load.

public void Page_Load(object sender, EventArgs e)
{
    RegisterAsyncTask(new PageAsyncTask(PageLoadAsync));
}

public async Task PageLoadAsync()
{
    //perform your actions here, including calling async methods and awaiting their results

    Task<string> downloadTask = new WebClient().DownloadStringTaskAsync("http://www.example.com");

    TextBox1.Title = "We can do some actions while waiting for the task to complete";

    TextBox2.Title = await downloadTask;
}

Make sure your page is marked as async.

<%@ Page Language="C#" CodeBehind="Default.aspx.cs" Inherits="Default" Async="true" %>

Keep in mind that the above code is slightly misleading. ASP.NET Web Forms is still based on the HTTP request/response model. It can't actually update a textbox's title on the client side while waiting for some file to download. Instead, it updates the textbox's title in the HTTP response, and once all server side processing is done (including your asynchronous tasks) it will then send the response to the client, at which point they'll see the updated textbox's title.

ContentLicense: CC BY-SA 4.0


问:
What is the difference between enum and object in typescript
I am trying to access values of a map via enum and also make a translation ready app for all the strings in it.
Both concerns overlap and I have to decide between using enums or just object in JSON format.

So what exactly is the difference and useage between an enum and an object?

For example:

I can use enums to access arrays as well as inserting labels and other stuff like

const enum FieldNames {
  FirstField: "Field One",
  SecondField: "Field Two"
};

someFieldArray[FieldNames.FirstField].label = FieldNames.FirstField;
someFieldArray[FieldNames.SecondField].label = FieldNames.SecondField;```
</div>
</div>
</p>

<ul>
<li>Or I can achieve the same behaviour via object</li>
</ul>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const FieldNames = {
  FirstField: "Field One",
  SecondField: "Field Two"
};

someFieldArray[FieldNames.FirstField].label = FieldNames.FirstField;
someFieldArray[FieldNames.SecondField].label = FieldNames.SecondField;</code>```

I really do not get the benefit choosing enums over simple objects. In my opinion an object has much more benefits without any downsides.

答:
Enum

An enum may give you additional benefits, if you want the features:

```<code>const enum FieldNamesEnum {
  FirstField = "Field One",
  SecondField = "Field Two"
};

let x: FieldNamesEnum;

x = FieldNamesEnum.FirstField;
x = FieldNamesEnum.SecondField;

// Error - not assignable to FieldNames
x = 'str';

// Cannot assign
FieldNamesEnum.FirstField = 'str';
</code>```

Importantly, you can't assign to the enum members and types are checked to the enum members, rather than string.

Additionally, because you have used a const enum in your example, the enum won't exist at runtime and all the references will be substituted for the literal values (if you used a plain enum the enum would exist at runtime).

Object

Compare this to the object example:

```<code>const FieldNames = {
  FirstField: "Field One",
  SecondField: "Field Two"
};

let y: string;

y = FieldNames.FirstField;
y = FieldNames.SecondField;

// Oops it works
y = 'str';

// Oops it works

FieldNames.FirstField = 'str';
</code>```

Union

If you don't need the full enum, but want to limit the values, you can use a union of literal values:

```<code>type FieldNames = "Field One" | "Field Two";

let x: FieldNames;

x = "Field One";
x = "Field Two";

// Error - not allowed
x = "Field Three";
</code>```

Body:
I am trying to access values of a map via enum and also make a translation ready app for all the strings in it.
Both concerns overlap and I have to decide between using enums or just object in JSON format.

So what exactly is the difference and useage between an enum and an object?

For example:

I can use enums to access arrays as well as inserting labels and other stuff like

const enum FieldNames {
  FirstField: "Field One",
  SecondField: "Field Two"
};

someFieldArray[FieldNames.FirstField].label = FieldNames.FirstField;
someFieldArray[FieldNames.SecondField].label = FieldNames.SecondField;

Or I can achieve the same behaviour via object

const FieldNames = {
  FirstField: "Field One",
  SecondField: "Field Two"
};

someFieldArray[FieldNames.FirstField].label = FieldNames.FirstField;
someFieldArray[FieldNames.SecondField].label = FieldNames.SecondField;

I really do not get the benefit choosing enums over simple objects. In my opinion an object has much more benefits without any downsides.

Body:
Enum

An enum may give you additional benefits, if you want the features:

const enum FieldNamesEnum {
  FirstField = "Field One",
  SecondField = "Field Two"
};

let x: FieldNamesEnum;

x = FieldNamesEnum.FirstField;
x = FieldNamesEnum.SecondField;

// Error - not assignable to FieldNames
x = 'str';

// Cannot assign
FieldNamesEnum.FirstField = 'str';

Importantly, you can't assign to the enum members and types are checked to the enum members, rather than string.

Additionally, because you have used a const enum in your example, the enum won't exist at runtime and all the references will be substituted for the literal values (if you used a plain enum the enum would exist at runtime).

Object

Compare this to the object example:

const FieldNames = {
  FirstField: "Field One",
  SecondField: "Field Two"
};

let y: string;

y = FieldNames.FirstField;
y = FieldNames.SecondField;

// Oops it works
y = 'str';

// Oops it works

FieldNames.FirstField = 'str';

Union

If you don't need the full enum, but want to limit the values, you can use a union of literal values:

type FieldNames = "Field One" | "Field Two";

let x: FieldNames;

x = "Field One";
x = "Field Two";

// Error - not allowed
x = "Field Three";


问:
this._subscribe is not a function
I try to subscribe my Observable "TemplateName" and I have this error,

I don't know what :

```<code>templateName: Observable<string>;
this.templateName = this.requestDetail.request.templateName;
</code>```

It sends me this back to the console :

Observable {_isScalar: false, _subscribe: Array(1)}
  _isScalar
  :
  false
  _subscribe
  :
  ["deploy"]
  proto
  :
  Object

I try to subscribe :

```<code>this.subscriptions.push(this.templateName.subscribe.bind(this.templateName)(templateName => {
                this.store.dispatch(new requestActions.LoadTemplateAction(templateName))
            }))
</code>```

And I have this error :

this._subscribe is not a function

答:
this.requestDetail.request.templateName must be an Observable for you to subscribe.

this.templateName is declared as an Observable so .request.templateName must be of the same type. Maybe this help you:

```<code>templateName = new Subject<string>();
request.templateName: Observable<string> = this.templateName.asObservable();
</code>```

here the varaible .request.template is your this.requestDetail.request.templateName
so  when you call this.requestDetail.request.templateName it should return an Observable. Then in your service or place where you declared templateName if you do templateName.next('some string') when you subscribe to this.requestDetail.request.templateName or this.tamplatename after this.tamplatename = this.requestDetail.request.templateName your data must be 'some string'

Other way without Subject is this:

```<code>request.templateName: Observable<string> = new Observable((observer) => {
    // observable execution
    observer.next("bla bla bla")
    observer.complete()
})
</code>```

Check this and this for more information.

Title: this._subscribe is not a function

Body:
I try to subscribe my Observable "TemplateName" and I have this error,

I don't know what :

templateName: Observable<string>;
this.templateName = this.requestDetail.request.templateName;

It sends me this back to the console :

Observable {_isScalar: false, _subscribe: Array(1)}
  _isScalar
  :
  false
  _subscribe
  :
  ["deploy"]
  proto
  :
  Object

I try to subscribe :

this.subscriptions.push(this.templateName.subscribe.bind(this.templateName)(templateName => {
                this.store.dispatch(new requestActions.LoadTemplateAction(templateName))
            }))

And I have this error :

this._subscribe is not a function

Body:
this.requestDetail.request.templateName must be an Observable for you to subscribe.

this.templateName is declared as an Observable so .request.templateName must be of the same type. Maybe this help you:

templateName = new Subject<string>();
request.templateName: Observable<string> = this.templateName.asObservable();

here the varaible .request.template is your this.requestDetail.request.templateName
so  when you call this.requestDetail.request.templateName it should return an Observable. Then in your service or place where you declared templateName if you do templateName.next('some string') when you subscribe to this.requestDetail.request.templateName or this.tamplatename after this.tamplatename = this.requestDetail.request.templateName your data must be 'some string'

Other way without Subject is this:

request.templateName: Observable<string> = new Observable((observer) => {
    // observable execution
    observer.next("bla bla bla")
    observer.complete()
})

Check this and this for more information.


问:
Location of images for Xamarin Forms projects
I've a Xamarin Forms project - with the 3 projects for UWP, iOS and Android.
Now I want to use images in my Xamarin Pages. As intended by Xamarin I want to use the same code for all three targets ... e.g.:

```<code><Image Source="Assets/appIcon-256.png"/>
</code>```

This works for iOS and UWP - both have a folder "Assets" where I placed the image. Ok, I've to maintain the image twice, but I've the same XAML code for both project.

But for Android, that doesn't seems to work. The image is not displayed in Android, if I put the png in the Assets folder of the Anroid project.

What can I do to use the same location for all images for all the three projects?

答:
Why the path starting with "Assets/"? For Android Place your image to MyProject.Android/Resources/drawable. For iOS myProject.iOS/Resources/
 and in xaml

```<code><Image Source="appIcon-256.png"/>
</code>```

It will work.
In addition for iOS if you have same picture with different sizes, you should rename them like "appIcon-256.png" "appIcon-256@2x.png" "appIcon-256@3x.png"

Body:
I've a Xamarin Forms project - with the 3 projects for UWP, iOS and Android.
Now I want to use images in my Xamarin Pages. As intended by Xamarin I want to use the same code for all three targets ... e.g.:

<Image Source="Assets/appIcon-256.png"/>

This works for iOS and UWP - both have a folder "Assets" where I placed the image. Ok, I've to maintain the image twice, but I've the same XAML code for both project.

But for Android, that doesn't seems to work. The image is not displayed in Android, if I put the png in the Assets folder of the Anroid project.

What can I do to use the same location for all images for all the three projects?

Body:
Why the path starting with "Assets/"? For Android Place your image to MyProject.Android/Resources/drawable. For iOS myProject.iOS/Resources/
 and in xaml

<Image Source="appIcon-256.png"/>

It will work.
In addition for iOS if you have same picture with different sizes, you should rename them like "appIcon-256.png" "appIcon-256@2x.png" "appIcon-256@3x.png"


问:
add a substring in Python
I am beginner in python i wanna add a substring in my python code. Here is my code

```<code>def gen_qr_text(acc_id,amount):
pp_acc_id = ""
pp_amount = ""
pp_chksum = ""

if len(acc_id) == 15:
  pp_acc_id = "0315" + acc_id
elif len(acc_id) == 13:
  pp_acc_id = "0213" + acc_id
elif len(acc_id) == 10:
  pp_acc_id = "01130066" + acc_id.substring(1)
else:
  return "null"

if not amount:
  pp_amount = str.format("54%02d%s", len(amount), amount)

pp_str = "00020101021129370016A000000677010111" + pp_acc_id + "5303764" +          pp_amount + "5802TH" + "6304"

pp_chksum = str(crc(pp_str))
pp_str += pp_chksum
return pp_str
</code>```

It makes some error in my code. Here is the line:

```<code>pp_acc_id = "01130066" + acc_id.substring(1)
</code>```

i wanna update to add substring. I converted this code from java. What should i do to convert this line in python.

答:
This is what you're looking for:

```<code>def gen_qr_text(acc_id,amount):
    pp_acc_id = ""
    pp_amount = ""
    pp_chksum = ""

    if len(acc_id) == 15:
        pp_acc_id = "0315" + acc_id
    elif len(acc_id) == 13:
        pp_acc_id = "0213" + acc_id
    elif len(acc_id) == 10:
        pp_acc_id = "01130066" + acc_id[1]
    else:
        return None

    if not amount:
        pp_amount = "54{:2d}{}".format(len(amount), amount))

    pp_str = "00020101021129370016A000000677010111" + pp_acc_id + "5303764" +          pp_amount + "5802TH" + "6304"

    pp_chksum = str(crc(pp_str))
    pp_str += pp_chksum
    return pp_str
</code>```

Also note that there's nothing called null in Python, return None.

Title: add a substring in Python

Body:
I am beginner in python i wanna add a substring in my python code. Here is my code

def gen_qr_text(acc_id,amount):
pp_acc_id = ""
pp_amount = ""
pp_chksum = ""

if len(acc_id) == 15:
  pp_acc_id = "0315" + acc_id
elif len(acc_id) == 13:
  pp_acc_id = "0213" + acc_id
elif len(acc_id) == 10:
  pp_acc_id = "01130066" + acc_id.substring(1)
else:
  return "null"

if not amount:
  pp_amount = str.format("54%02d%s", len(amount), amount)

pp_str = "00020101021129370016A000000677010111" + pp_acc_id + "5303764" +          pp_amount + "5802TH" + "6304"

pp_chksum = str(crc(pp_str))
pp_str += pp_chksum
return pp_str

It makes some error in my code. Here is the line:

pp_acc_id = "01130066" + acc_id.substring(1)

i wanna update to add substring. I converted this code from java. What should i do to convert this line in python.

Body:
This is what you're looking for:

def gen_qr_text(acc_id,amount):
    pp_acc_id = ""
    pp_amount = ""
    pp_chksum = ""

    if len(acc_id) == 15:
        pp_acc_id = "0315" + acc_id
    elif len(acc_id) == 13:
        pp_acc_id = "0213" + acc_id
    elif len(acc_id) == 10:
        pp_acc_id = "01130066" + acc_id[1]
    else:
        return None

    if not amount:
        pp_amount = "54{:2d}{}".format(len(amount), amount))

    pp_str = "00020101021129370016A000000677010111" + pp_acc_id + "5303764" +          pp_amount + "5802TH" + "6304"

    pp_chksum = str(crc(pp_str))
    pp_str += pp_chksum
    return pp_str

Also note that there's nothing called null in Python, return None.


答:
It is called integer promotion.

```<code>int z = x > y;
</code>```

In this example, the comparison(>) operator operates on a signed int and an unsigned int. By the conversion rules, y is converted to an unsigned int. Because -2 cannot be represented as an unsigned int value, the -2 is converted to -2 + UINT_MAX+1.

C11 6.3.1.3, paragraph 2:

Otherwise, if the new type is unsigned, the value is converted by
  repeatedly adding or subtracting one more than the maximum value that
  can be represented in the new type until the value is in the range of
  the new type.

So, the program prints 0 because UINT_MAX is not less than 4.

Or

If you want to print 1, then do explicit type case. like:

```<code>int z =  (int)x >y;
</code>```

Title: Why is unsigned 4 not considered greater than signed -2?

Body:
It is called integer promotion.

int z = x > y;

In this example, the comparison(>) operator operates on a signed int and an unsigned int. By the conversion rules, y is converted to an unsigned int. Because -2 cannot be represented as an unsigned int value, the -2 is converted to -2 + UINT_MAX+1.

C11 6.3.1.3, paragraph 2:

Otherwise, if the new type is unsigned, the value is converted by
  repeatedly adding or subtracting one more than the maximum value that
  can be represented in the new type until the value is in the range of
  the new type.

So, the program prints 0 because UINT_MAX is not less than 4.

Or

If you want to print 1, then do explicit type case. like:

int z =  (int)x >y;


问:
How to set table schema at table name with Cake?
PostgreSQL, Oracle and many other DBMS's use SCHEMA, so, the table name is

```<code>schema_name.table_name
</code>```

But CakePHP manuals not say anithing about this. What about Model, View and Controller names in the CakePHP defaults?  I can use a solution like prefix, that is, where the same schema name will be used at all database operations.

PS1: please not to be confused with method Modelschema, and questions about accessing this method.

PS2: the Bill's 2006 solution is not the better one, because is not updated (I am using CakePHP2) and is not a "official cakePHP solution".

PS3: database.php have some schema attribute? What the link to CakePHP documentation?

答:
In CakePHP you must define more database config.

In CakePHP 2:

set the 'schema' param to your config

create new configs for all of your schema

use the right schema in your models

For example, database conf:

```<code>public $default = array(
        'datasource' => 'Database/Postgres',
        'persistent' => false,
        'host'       => 'localhost',
        'login'      => 'my_db_user',
        'password'   => 'my_db_passw',
        'database'   => 'my_project_db',
        'prefix'     => '',
        'encoding'   => 'utf8',
        'schema'     => 'postgres'
    );
public $other_schema = array(
        'datasource' => 'Database/Postgres',
        'persistent' => false,
        'host'       => 'localhost',
        'login'      => 'my_db_user',
        'password'   => 'my_db_passw',
        'database'   => 'my_project_db',
        'prefix'     => '',
        'encoding'   => 'utf8',
        'schema'     => 'other_schema'
    );
</code>```

If you want to use it in a model:

```<code>class AppModel extends AppModel {
    public $useDbConfig = 'other_schema';
}
</code>```

In CakePHP3 is the same way, just there the database is config/app.php and you must use

```<code>use Cake\Datasource\ConnectionManager;
$connection = ConnectionManager::get('default');
</code>```

Body:
PostgreSQL, Oracle and many other DBMS's use SCHEMA, so, the table name is

schema_name.table_name

But CakePHP manuals not say anithing about this. What about Model, View and Controller names in the CakePHP defaults?  I can use a solution like prefix, that is, where the same schema name will be used at all database operations.

PS1: please not to be confused with method Modelschema, and questions about accessing this method.

PS2: the Bill's 2006 solution is not the better one, because is not updated (I am using CakePHP2) and is not a "official cakePHP solution".

PS3: database.php have some schema attribute? What the link to CakePHP documentation?

Body:
In CakePHP you must define more database config.

In CakePHP 2:

set the 'schema' param to your config

create new configs for all of your schema

use the right schema in your models

For example, database conf:

public $default = array(
        'datasource' => 'Database/Postgres',
        'persistent' => false,
        'host'       => 'localhost',
        'login'      => 'my_db_user',
        'password'   => 'my_db_passw',
        'database'   => 'my_project_db',
        'prefix'     => '',
        'encoding'   => 'utf8',
        'schema'     => 'postgres'
    );
public $other_schema = array(
        'datasource' => 'Database/Postgres',
        'persistent' => false,
        'host'       => 'localhost',
        'login'      => 'my_db_user',
        'password'   => 'my_db_passw',
        'database'   => 'my_project_db',
        'prefix'     => '',
        'encoding'   => 'utf8',
        'schema'     => 'other_schema'
    );

If you want to use it in a model:

class AppModel extends AppModel {
    public $useDbConfig = 'other_schema';
}

In CakePHP3 is the same way, just there the database is config/app.php and you must use

use Cake\Datasource\ConnectionManager;
$connection = ConnectionManager::get('default');


问:
Element-UI el-select validation
I'm using Vue with Element-Ui and I'm having issues with the validation trigger on my <el-select> element. Essentially this is what the HTML looks like

```<code><el-form-item label="Partner" prop="partner">
  <el-select class="dialog-select" v-model="form.partner" placeholder="Partner">
      <el-option label="Zone one" value="shanghai"></el-option>
      <el-option label="Zone two" value="beijing"></el-option>
  </el-select>
</el-form-item>
</code>```

and the JS validating the element looks like this

```<code>partner: [ { validator: validateInput, trigger: 'blur' } ]
</code>```

My standard <el-input> validations are being triggered however. I have tried to change the trigger to input, blur as well as focus and neither of these events are firing. I cannot find any docs around what type of triggers their are either.

Edit: I have uploaded a fiddle with the issue. The validator will trigger onSubmit, however will also not clear once the rule should pass.

https://jsfiddle.net/k66a1gst/

答: I found the correct trigger for this element, it is the change trigger. The change trigger will also be required for things like dates. However it won't throw a validation error at you while tabbing past it.

Title: Element-UI el-select validation

Body:
I'm using Vue with Element-Ui and I'm having issues with the validation trigger on my <el-select> element. Essentially this is what the HTML looks like

<el-form-item label="Partner" prop="partner">
  <el-select class="dialog-select" v-model="form.partner" placeholder="Partner">
      <el-option label="Zone one" value="shanghai"></el-option>
      <el-option label="Zone two" value="beijing"></el-option>
  </el-select>
</el-form-item>

and the JS validating the element looks like this

partner: [ { validator: validateInput, trigger: 'blur' } ]

My standard <el-input> validations are being triggered however. I have tried to change the trigger to input, blur as well as focus and neither of these events are firing. I cannot find any docs around what type of triggers their are either.

Edit: I have uploaded a fiddle with the issue. The validator will trigger onSubmit, however will also not clear once the rule should pass.

https://jsfiddle.net/k66a1gst/


问:
Merge multiple scss files into one css file
I'd like to merge all of my scss files into one compressed css file:

Structure:

stylesheets/

test.scss

test2.scss

gulpfile.js

I tried this two tasks, which I found in several answers and tutorials, but I always got the scss file into a duplicated css file:

```<code>gulp.task('sass', function() {
    return gulp.src('stylesheets/**/*.scss')
      .pipe(sass())
      .pipe(gulp.dest('css/'))
});
</code>```

and

```<code>gulp.task('sass', function() {
    return gulp.src('stylesheets/**/*.scss')
      .pipe(sass())
      .pipe(gulp.dest('css/styles.css'))
});
</code>```

!!! EFFECTIV RESULT !!!

stylesheets/

test.scss

test2.scss

css/

test.css

test2.css

gulpfile.js

or with second tried task:

stylesheets/

test.scss

test2.scss

css/styles.css/

test.css

test2.css

gulpfile.js

??? EXPECTED RESULT ???

stylesheets/

test.scss

test2.scss

css/

styles.css

gulpfile.js

Any ideas?

答:
You indicated that you want to merge your files into one file and compress that file, so you need to add two plugins to do each of those.

Gulp-concat and gulp-uglify

```<code>const concat = require('gulp-concat');
const uglify = require('gulp-uglify');

gulp.task('sass', function() {
return gulp.src('stylesheets/**/*.scss')
  .pipe(sass())
  .pipe(concat('styles.css'))
  .pipe(uglify())

  // .pipe(rename({
   //  basename: "styles",
   //   suffix: ".min",
   //   extname: ".css"
  //  }))

  .pipe(gulp.dest('css'))
});
</code>```

In addition, you may want to add gulp-rename to indicate that the file has been uglified/minified via a .min.css extension (and change your html link to point to that filename).

Body:
I'd like to merge all of my scss files into one compressed css file:

Structure:

stylesheets/

test.scss

test2.scss

gulpfile.js

I tried this two tasks, which I found in several answers and tutorials, but I always got the scss file into a duplicated css file:

gulp.task('sass', function() {
    return gulp.src('stylesheets/**/*.scss')
      .pipe(sass())
      .pipe(gulp.dest('css/'))
});

and

gulp.task('sass', function() {
    return gulp.src('stylesheets/**/*.scss')
      .pipe(sass())
      .pipe(gulp.dest('css/styles.css'))
});

!!! EFFECTIV RESULT !!!

stylesheets/

test.scss

test2.scss

css/

test.css

test2.css

gulpfile.js

or with second tried task:

stylesheets/

test.scss

test2.scss

css/styles.css/

test.css

test2.css

gulpfile.js

??? EXPECTED RESULT ???

stylesheets/

test.scss

test2.scss

css/

styles.css

gulpfile.js

Any ideas?

Body:
You indicated that you want to merge your files into one file and compress that file, so you need to add two plugins to do each of those.

Gulp-concat and gulp-uglify

const concat = require('gulp-concat');
const uglify = require('gulp-uglify');

gulp.task('sass', function() {
return gulp.src('stylesheets/**/*.scss')
  .pipe(sass())
  .pipe(concat('styles.css'))
  .pipe(uglify())

  // .pipe(rename({
   //  basename: "styles",
   //   suffix: ".min",
   //   extname: ".css"
  //  }))

  .pipe(gulp.dest('css'))
});

In addition, you may want to add gulp-rename to indicate that the file has been uglified/minified via a .min.css extension (and change your html link to point to that filename).


问:
liferay 7 web content template vm serviceLocator not work
I create a template for web content using vm. But the serviceLocator does not work.
I added

```<code>    journal.template.velocity.restricted.variables=
</code>```

to my portal-ext.properties file, but it did not help.

I did not find the journal.template.velocity.restricted.variables property in the original portal.properties file.

How to make serviceLocator work?

答:
I think you are looking for velocity.engine.restricted.variables=

Also, note that Velocity is not the best option going forward FreeMarker would be a better way to go.

Body:
I create a template for web content using vm. But the serviceLocator does not work.
I added

    journal.template.velocity.restricted.variables=

to my portal-ext.properties file, but it did not help.

I did not find the journal.template.velocity.restricted.variables property in the original portal.properties file.

How to make serviceLocator work?


问:
Stream of optional fields return values
I have a few Optional fields with String and Long values:

```<code>Optional<Long> id;
Optional<String> name;
Optional<String> lastname;
Optional<Long> number;
....
</code>```

I would like to return List with contains all of the values. If e.g optional "name" is no present, should be stored empty String. Result of method should be List with values e.q: "1", "John", "", "5".

I made stream:

```<code>Stream fields = Stream.of(id, name, lastname, number);
</code>```

But I have no idea what next.

Regards.

答:
```<code>List<String> ls = Stream.of(a, b).filter(o -> o != null && !o.trim().equals("")).map(o -> o instanceof Long ? String.valueOf(o) : o).collect(Collectors.toList());
</code>```

Create a stream

Add a filter which will keep the values if two condition are respected: they are not null and if it is true the string value is not empty (the trim() method permits to remove the empty chars which are on the left and the right of the value)

Use a map method in order to transform objects which are Long instances into String instances

Use a collect method in order to retrieve values

Title: Stream of optional fields return values

Body:
I have a few Optional fields with String and Long values:

Optional<Long> id;
Optional<String> name;
Optional<String> lastname;
Optional<Long> number;
....

I would like to return List with contains all of the values. If e.g optional "name" is no present, should be stored empty String. Result of method should be List with values e.q: "1", "John", "", "5".

I made stream:

Stream fields = Stream.of(id, name, lastname, number);

But I have no idea what next.

Regards.

Body:
List<String> ls = Stream.of(a, b).filter(o -> o != null && !o.trim().equals("")).map(o -> o instanceof Long ? String.valueOf(o) : o).collect(Collectors.toList());

Create a stream

Add a filter which will keep the values if two condition are respected: they are not null and if it is true the string value is not empty (the trim() method permits to remove the empty chars which are on the left and the right of the value)

Use a map method in order to transform objects which are Long instances into String instances

Use a collect method in order to retrieve values


问:
How to remove or stop a child XMLElement inheriting its Parent's NameSpace
I know I can set the namespace for my XmlRoot with the following code:

```<code><System.Xml.Serialization.XmlRoot(ElementName:="Requirement", [Namespace]:="http://open-services.net/ns/rm#")>
Public Class Requirement
</code>```

and once my namespaces have been setup, any XmlElements will have namespace prefix set at the root.

But what if I have an XmlElement that does not have a namespace, how can I then remove the namespace?  I know I can change each Element by setting it's namespace:

```<code> <System.Xml.Serialization.XmlElement("title", [Namespace]:="http://purl.org/dc/terms/")>
 Public title As String = ""
</code>```

but I can't see a way to remove it, is it possible using the Serialization settings?

答: I was sure I'd tried this and it didn't work, but just set the [Namespace]:="" did it.

Body:
I know I can set the namespace for my XmlRoot with the following code:

<System.Xml.Serialization.XmlRoot(ElementName:="Requirement", [Namespace]:="http://open-services.net/ns/rm#")>
Public Class Requirement

and once my namespaces have been setup, any XmlElements will have namespace prefix set at the root.

But what if I have an XmlElement that does not have a namespace, how can I then remove the namespace?  I know I can change each Element by setting it's namespace:

 <System.Xml.Serialization.XmlElement("title", [Namespace]:="http://purl.org/dc/terms/")>
 Public title As String = ""

but I can't see a way to remove it, is it possible using the Serialization settings?


答:
You can use:

```<code>List<String> list = Stream.of(id, name, lastname, number)
        .map(op -> op.map(o -> o.toString()).orElse(""))
        .collect(Collectors.toList());
</code>```

On each optional in stream you will map it into it's String version using toString() from Object class and for null you will map it into empty String. Than, you will collect it into list.

Title: Stream of optional fields return values

Body:
You can use:

List<String> list = Stream.of(id, name, lastname, number)
        .map(op -> op.map(o -> o.toString()).orElse(""))
        .collect(Collectors.toList());

On each optional in stream you will map it into it's String version using toString() from Object class and for null you will map it into empty String. Than, you will collect it into list.


问:
ASP.NET Membership Web-Based Administration
Does anyone know if there's a way to manage users/roles in the asp.net membership database using a web-based interface you can access remotely?

I need one which doesn't require installation to the Default Website.

Thanks

答:
There is a great article here.

with samples of how to implement the aspnet membership database through webservices.

Download asp.net example from here

For the downloaded example using SQL express for local testing, I struggeled a little bit, but found a solution:

In web.confing:

```<code><connectionStrings>
    <remove name="LocalSqlServer"/>
    <add name="LocalSqlServer" connectionString="Data Source=name of the local machine\SQLEXPRESS;Initial Catalog=ASPNETDB;Integrated Security=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>
</code>```

OwnerDisplayName: Shahin

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Shahin

Body:
There is a great article here.

with samples of how to implement the aspnet membership database through webservices.

Download asp.net example from here

For the downloaded example using SQL express for local testing, I struggeled a little bit, but found a solution:

In web.confing:

<connectionStrings>
    <remove name="LocalSqlServer"/>
    <add name="LocalSqlServer" connectionString="Data Source=name of the local machine\SQLEXPRESS;Initial Catalog=ASPNETDB;Integrated Security=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>

OwnerDisplayName: Keb

LastEditorDisplayName: Keb


问:
%D field in Apache access logs - first or last byte?
The Apache Httpd manual has a section on custom access log formats.  One of these options is the %D field, which is documented as

The time taken to serve the request, in microseconds.

Can anyone tell me what exactly this is measuring?  Is it time-to-first-byte, or time-to-last-byte, for example, or something more complex than that?

I need this is demonstrate compliance to performance requirements, and I want to know exactly what's being measured here.

答: It's the last byte or rather, apr_time_now() - request_rec->request_time which is worked out during the logging phase. That phase happens last in the processing cycle, after the response has been sent.


答:
This works :

```<code>List<String> result = fields.map(o -> o.orElse(""))  // provide default value
                            .map(o -> o.toString())  // cast to String
                            .collect(Collectors.toList()); // collect into List
</code>```

See it in action.

Title: Stream of optional fields return values

Body:
This works :

List<String> result = fields.map(o -> o.orElse(""))  // provide default value
                            .map(o -> o.toString())  // cast to String
                            .collect(Collectors.toList()); // collect into List

See it in action.