Percona MySQL 5.7 Replication error 1236 "unknown error reading log event on the master"

Question: we are using two instances of 5.7.20-18-log (in the meantime updated to 5.7.21-21-lo) Percona Server in a master-master (dbm1 / dbm2) replication. The application only uses dbm1 for writes and reads so the dbm2 is used as a cold standby only.
Since a couple of weeks the replication on dbm2 stops multiple times per week with the error message "unknown error reading log event on the master".
Here is the full slave status (dbm2) from the last incident:
mysql> show slave status \G
*************************** 1. row ***************************
               Slave_IO_State:
                  Master_Host: 10.6.233.101
                  Master_User: replicator
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.007091
          Read_Master_Log_Pos: 71137
               Relay_Log_File: mysqld-relay-bin.001603
                Relay_Log_Pos: 71350
        Relay_Master_Log_File: mysql-bin.007091
             Slave_IO_Running: No
            Slave_SQL_Running: Yes
              Replicate_Do_DB:
          Replicate_Ignore_DB:
           Replicate_Do_Table:
       Replicate_Ignore_Table:
      Replicate_Wild_Do_Table:
  Replicate_Wild_Ignore_Table:
                   Last_Errno: 0
                   Last_Error:
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 71137
              Relay_Log_Space: 71605
              Until_Condition: None
               Until_Log_File:
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File:
           Master_SSL_CA_Path:
              Master_SSL_Cert:
            Master_SSL_Cipher:
               Master_SSL_Key:
        Seconds_Behind_Master: NULL
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 1236
                Last_IO_Error: Got fatal error 1236 from master when reading data from binary log: 'unknown error reading log event on the master; the first event 'mysql-bin.007003' at 43445, the last event read from './mysql-bin.007091' at 71137, the last byte read from './mysql-bin.007091' at 71137.'
               Last_SQL_Errno: 0
               Last_SQL_Error:
  Replicate_Ignore_Server_Ids:
             Master_Server_Id: 1
                  Master_UUID: 7cb8eccb-e1a0-11e7-9d96-545edb2e572a
             Master_Info_File: /var/lib/mysql/master.info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: Slave has read all relay log; waiting for more updates
           Master_Retry_Count: 86400
                  Master_Bind:
      Last_IO_Error_Timestamp: 180308 06:41:25
     Last_SQL_Error_Timestamp:
               Master_SSL_Crl:
           Master_SSL_Crlpath:
           Retrieved_Gtid_Set:
            Executed_Gtid_Set:
                Auto_Position: 0
         Replicate_Rewrite_DB:
                 Channel_Name:
           Master_TLS_Version:
1 row in set (0.00 sec)

Generally we address this with a full restore of dbm2 with XtraBackup but after a few days the problem on dbm2 appears again.
As we can see in our monitoring, both servers have enough resources left (and no IO-Wait) - what we can see is, that this often happens when the application is doing some import jobs.
Both servers are located in the same datacenter, communication via the internal network.
More details:
OS: Ubuntu 14.04.5 LTS
Kernel: OpenVZ VPS (Kernel 2.6.32-042stab127.2)
CPU: 8 cores Intel(R) Xeon(R) CPU E5-2670 0 @ 2.60GHz
RAM: 16 gb
Percona: 5.7.20-18-log Percona Server (GPL), Release '18', Revision '7ce54a6deef'

my.cnf:
[client]
port = 3306
socket = /var/run/mysqld/mysqld.sock

[isamchk]
key_buffer_size = 16M

[mysqld]
basedir = /usr
bind_address = *
binlog_cache_size = 1M
binlog_format = mixed
bulk_insert_buffer_size = 64M
datadir = /var/lib/mysql
expire_logs_days = 2
innodb_buffer_pool_dump_at_shutdown = ON
innodb_buffer_pool_load_at_startup = ON
innodb_buffer_pool_size = 12G
innodb_doublewrite = OFF
innodb_flush_log_at_trx_commit = 2
innodb_io_capacity = 1000
innodb_log_file_size = 256M
innodb_read_io_threads = 8
innodb_write_io_threads = 8
join_buffer_size = 244K
key_buffer_size = 100M
log-bin = mysql-bin
log-error = /var/log/mysql/error.log
log_slow_verbosity = full
long_query_time = 1
max_allowed_packet = 16M
max_binlog_files = 200
max_binlog_size = 100M
max_connections = 500
max_heap_table_size = 128M
max_relay_log_size = 256M
max_slowlog_files = 1
max_slowlog_size = 4G
myisam_sort_buffer_size = 64M
optimizer_switch = index_merge=on,index_merge_union=on,index_merge_sort_union=on,index_merge_intersection=on,engine_condition_pushdown=on,index_condition_pushdown=on,mrr=on,mrr_cost_based=off,block_nested_loop=off,batched_key_access=on,materialization=on,semijoin=on,loosescan=on,firstmatch=on,duplicateweedout=on,subquery_materialization_cost_based=on,use_index_extensions=on,condition_fanout_filter=on,derived_merge=on
pid-file = /var/run/mysqld/mysqld.pid
port = 3306
query_cache_limit = 1M
query_cache_size = 128M
query_cache_type = ON
read_buffer_size = 244K
relay_log = mysqld-relay-bin
server_id = 1
skip-external-locking
skip_name_resolve = ON
slow_query_log = ON
slow_query_log_file = /var/log/mysql/mysqld.slowlog
socket = /var/run/mysqld/mysqld.sock
sort_buffer_size = 2047K
sql_mode = STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
ssl = false
ssl-ca = /etc/mysql/cacert.pem
ssl-cert = /etc/mysql/server-cert.pem
ssl-key = /etc/mysql/server-key.pem
thread_cache_size = 8
thread_stack = 256K
tmp_table_size = 128M
tmpdir = /tmp
user = mysql
userstat = ON

[mysqld-5.0]
myisam-recover = BACKUP

[mysqld-5.1]
myisam-recover = BACKUP

[mysqld-5.5]
myisam-recover = BACKUP

[mysqld-5.6]
myisam-recover-options = BACKUP

[mysqld-5.7]
myisam-recover-options = BACKUP

[mysqld_safe]
log-error = /var/log/mysql/error.log
nice = 0
socket = /var/run/mysqld/mysqld.sock

[mysqldump]
max_allowed_packet = 16M
quick
quote-names

Any Ideas on how to mitigate the root cause for this type of replication error?
Edit to answer questions from @wilson-hauck:
MySQLTuner report from dbm1
>>  MySQLTuner 1.7.9 - Major Hayden <firstname.lastname@example.com>
>>  Bug reports, feature requests, and downloads at mysqltuner.com
>>  Run with '--help' for additional options and output filtering

[--] Skipped version check for MySQLTuner script
[OK] Currently running supported MySQL version 5.7.20-18-log
[OK] Operating on 64-bit architecture

-------- Log file Recommendations ------------------------------------------------------------------
[--] Log file: /var/log/mysql/error.log(0B)
[OK] Log file /var/log/mysql/error.log exists
[OK] Log file /var/log/mysql/error.log is readable.
[!!] Log file /var/log/mysql/error.log is empty
[OK] Log file /var/log/mysql/error.log is smaller than 32 Mb
[OK] /var/log/mysql/error.log doesn't contain any warning.
[OK] /var/log/mysql/error.log doesn't contain any error.
[--] 0 start(s) detected in /var/log/mysql/error.log
[--] 0 shutdown(s) detected in /var/log/mysql/error.log

-------- Storage Engine Statistics -----------------------------------------------------------------
[--] Status: +ARCHIVE +BLACKHOLE +CSV -FEDERATED +InnoDB +MEMORY +MRG_MYISAM +MyISAM +PERFORMANCE_SCHEMA
[--] Data in MEMORY tables: 46M (Tables: 2)
[--] Data in MyISAM tables: 9G (Tables: 368)
[--] Data in InnoDB tables: 12G (Tables: 131)
[OK] Total fragmented tables: 0

-------- Security Recommendations ------------------------------------------------------------------
[OK] There are no anonymous accounts for any database users
[OK] All database users have passwords assigned
[!!] There is no basic password file list!

-------- CVE Security Recommendations --------------------------------------------------------------
[--] Skipped due to --cvefile option undefined

-------- Performance Metrics -----------------------------------------------------------------------
[--] Up for: 6d 19h 49m 31s (3B q [5K qps], 7M conn, TX: 5877G, RX: 1160G)
[--] Reads / Writes: 94% / 6%
[--] Binary logging is enabled (GTID MODE: OFF)
[--] Physical Memory     : 16.0G
[--] Max MySQL memory    : 13.8G
[--] Other process memory: 160.2M
[--] Total buffers: 12.4G global + 3.0M per thread (500 max threads)
[--] P_S Max memory usage: 72B
[--] Galera GCache Max memory usage: 0B
[OK] Maximum reached memory usage: 13.1G (82.10% of installed RAM)
[!!] Maximum possible memory usage: 13.8G (86.35% of installed RAM)
[OK] Overall possible memory usage with other process is compatible with memory available
[OK] Slow queries: 0% (31K/3B)
[OK] Highest usage of available connections: 53% (266/500)
[OK] Aborted connections: 0.13%  (9830/7378007)
[!!] Query cache may be disabled by default due to mutex contention.
[OK] Query cache efficiency: 53.3% (1B cached / 3B selects)
[!!] Query cache prunes per day: 93123042
[OK] Sorts requiring temporary tables: 0% (261K temp sorts / 112M sorts)
[OK] No joins without indexes
[OK] Temporary tables created on disk: 12% (4M on disk / 35M total)
[OK] Thread cache hit rate: 88% (883K created / 7M connections)
[!!] Table cache hit rate: 0% (2K open / 360K opened)
[OK] Open file limit used: 28% (1K/5K)
[OK] Table locks acquired immediately: 99% (1B immediate / 1B locks)
[OK] Binlog cache memory access: 100.00% (47747694 Memory / 47748535 Total)

-------- Performance schema ------------------------------------------------------------------------
[--] Memory used by P_S: 72B
[--] Sys schema is installed.

-------- ThreadPool Metrics ------------------------------------------------------------------------
[--] ThreadPool stat is enabled.
[--] Thread Pool Size: 8 thread(s).
[!!] thread_pool_size between 16 and 36 when using InnoDB storage engine.

-------- MyISAM Metrics ----------------------------------------------------------------------------
[OK] Key buffer used: 100.0% (104M used / 104M cache)
[OK] Key buffer size / total MyISAM indexes: 100.0M/3.0G
[OK] Read Key buffer hit rate: 99.6% (41B cached / 152M reads)
[!!] Write Key buffer hit rate: 14.2% (1B cached / 242M writes)

-------- InnoDB Metrics ----------------------------------------------------------------------------
[--] InnoDB is enabled.
[--] InnoDB Thread Concurrency: 0
[OK] InnoDB File per table is activated
[!!] InnoDB buffer pool / data size: 12.0G/12.8G
[!!] Ratio InnoDB log file size / InnoDB Buffer pool size (4.16666666666667 %): 256.0M * 2/12.0G should be equal 25%
[!!] InnoDB buffer pool instances: 8
[--] Number of InnoDB Buffer Pool Chunk : 96 for 8 Buffer Pool Instance(s)
[OK] Innodb_buffer_pool_size aligned with Innodb_buffer_pool_chunk_size & Innodb_buffer_pool_instances
[OK] InnoDB Read buffer efficiency: 100.00% (55125068296 hits/ 55125632976 total)
[OK] InnoDB Write log efficiency: 92.59% (140220341 hits/ 151440226 total)
[OK] InnoDB log waits: 0.00% (0 waits / 11219885 writes)

-------- AriaDB Metrics ----------------------------------------------------------------------------
[--] AriaDB is disabled.

-------- TokuDB Metrics ----------------------------------------------------------------------------
[--] TokuDB is disabled.

-------- XtraDB Metrics ----------------------------------------------------------------------------
[--] XtraDB is disabled.

-------- RocksDB Metrics ---------------------------------------------------------------------------
[--] RocksDB is disabled.

-------- Spider Metrics ----------------------------------------------------------------------------
[--] Spider is disabled.

-------- Connect Metrics ---------------------------------------------------------------------------
[--] Connect is disabled.

-------- Galera Metrics ----------------------------------------------------------------------------
[--] Galera is disabled.

-------- Replication Metrics -----------------------------------------------------------------------
[--] Galera Synchronous replication: NO
[--] No replication slave(s) for this server.
[--] Binlog format: MIXED
[--] XA support enabled: ON
[--] Semi synchronous replication Master: Not Activated
[--] Semi synchronous replication Slave: Not Activated
[!!] This replication slave is running with the read_only option disabled.
[OK] This replication slave is up to date with master.

-------- Recommendations ---------------------------------------------------------------------------
General recommendations:
   Reduce your overall MySQL memory footprint for system stability
   Increasing the query_cache size over 128M may reduce performance
   Increase table_open_cache gradually to avoid file descriptor limits
   Read this before increasing table_open_cache over 64:
   This is MyISAM only table_cache scalability problem, InnoDB not affected.
   See more details here:
   This bug already fixed in MySQL 5.7.9 and newer MySQL versions.
   Beware that open_files_limit (5000) variable
   should be greater than table_open_cache (2000)
   Thread pool size for InnoDB usage (8)
   Read this before changing innodb_log_file_size and/or innodb_log_files_in_group:
Variables to adjust:
   query_cache_size (=0)
   query_cache_type (=0)
   query_cache_size (> 128M) [see warning above]
   table_open_cache (> 2000)
   thread_pool_size between 16 and 36 for InnoDB usage
   innodb_buffer_pool_size (>= 12G) if possible.
   innodb_log_file_size should be (=1G) if possible, so InnoDB total log files size equals to 25% of buffer pool size.
   innodb_buffer_pool_instances(=12)

MySQLTuner report from dbm2
>>  MySQLTuner 1.7.9 - Major Hayden <email@example.com>
 >>  Bug reports, feature requests, and downloads at mysqltuner.com
 >>  Run with '--help' for additional options and output filtering

[--] Skipped version check for MySQLTuner script
[OK] Currently running supported MySQL version 5.7.20-18-log
[OK] Operating on 64-bit architecture

-------- Log file Recommendations ------------------------------------------------------------------
[--] Log file: /var/log/mysql/error.log(0B)
[OK] Log file /var/log/mysql/error.log exists
[OK] Log file /var/log/mysql/error.log is readable.
[!!] Log file /var/log/mysql/error.log is empty
[OK] Log file /var/log/mysql/error.log is smaller than 32 Mb
[OK] /var/log/mysql/error.log doesn't contain any warning.
[OK] /var/log/mysql/error.log doesn't contain any error.
[--] 0 start(s) detected in /var/log/mysql/error.log
[--] 0 shutdown(s) detected in /var/log/mysql/error.log

-------- Storage Engine Statistics -----------------------------------------------------------------
[--] Status: +ARCHIVE +BLACKHOLE +CSV -FEDERATED +InnoDB +MEMORY +MRG_MYISAM +MyISAM +PERFORMANCE_SCHEMA
[--] Data in InnoDB tables: 12G (Tables: 131)
[--] Data in MEMORY tables: 46M (Tables: 2)
[--] Data in MyISAM tables: 9G (Tables: 368)
[!!] Total fragmented tables: 2

-------- Security Recommendations ------------------------------------------------------------------
[OK] There are no anonymous accounts for any database users
[OK] All database users have passwords assigned
[!!] There is no basic password file list!

-------- CVE Security Recommendations --------------------------------------------------------------
[--] Skipped due to --cvefile option undefined

-------- Performance Metrics -----------------------------------------------------------------------
[--] Up for: 6d 21h 4m 15s (89K q [0.150 qps], 39K conn, TX: 325M, RX: 52G)
[--] Reads / Writes: 0% / 100%
[--] Binary logging is enabled (GTID MODE: OFF)
[--] Physical Memory     : 20.0G
[--] Max MySQL memory    : 13.8G
[--] Other process memory: 166.5M
[--] Total buffers: 12.4G global + 3.0M per thread (500 max threads)
[--] P_S Max memory usage: 72B
[--] Galera GCache Max memory usage: 0B
[OK] Maximum reached memory usage: 12.4G (61.86% of installed RAM)
[OK] Maximum possible memory usage: 13.8G (69.08% of installed RAM)
[OK] Overall possible memory usage with other process is compatible with memory available
[OK] Slow queries: 2% (1K/89K)
[OK] Highest usage of available connections: 0% (3/500)
[!!] Aborted connections: 24.95%  (9904/39702)
[!!] Query cache may be disabled by default due to mutex contention.
[!!] Query cache efficiency: 0.0% (0 cached / 29K selects)
[OK] Query cache prunes per day: 0
[!!] Sorts requiring temporary tables: 7837% (26K temp sorts / 342 sorts)
[OK] No joins without indexes
[OK] Temporary tables created on disk: 0% (392 on disk / 1M total)
[OK] Thread cache hit rate: 99% (3 created / 39K connections)
[!!] Table cache hit rate: 14% (1K open / 7K opened)
[OK] Open file limit used: 13% (657/5K)
[OK] Table locks acquired immediately: 100% (30M immediate / 30M locks)
[OK] Binlog cache memory access: 0% (0 Memory / 0 Total)

-------- Performance schema ------------------------------------------------------------------------
[--] Memory used by P_S: 72B
[--] Sys schema is installed.

-------- ThreadPool Metrics ------------------------------------------------------------------------
[--] ThreadPool stat is enabled.
[--] Thread Pool Size: 8 thread(s).
[!!] thread_pool_size between 16 and 36 when using InnoDB storage engine.

-------- MyISAM Metrics ----------------------------------------------------------------------------
[OK] Key buffer used: 99.9% (104M used / 104M cache)
[OK] Key buffer size / total MyISAM indexes: 100.0M/3.0G
[OK] Read Key buffer hit rate: 98.8% (6B cached / 73M reads)
[!!] Write Key buffer hit rate: 14.9% (1B cached / 186M writes)

-------- InnoDB Metrics ----------------------------------------------------------------------------
[--] InnoDB is enabled.
[--] InnoDB Thread Concurrency: 0
[OK] InnoDB File per table is activated
[!!] InnoDB buffer pool / data size: 12.0G/12.7G
[!!] Ratio InnoDB log file size / InnoDB Buffer pool size (4.16666666666667 %): 256.0M * 2/12.0G should be equal 25%
[!!] InnoDB buffer pool instances: 8
[--] Number of InnoDB Buffer Pool Chunk : 96 for 8 Buffer Pool Instance(s)
[OK] Innodb_buffer_pool_size aligned with Innodb_buffer_pool_chunk_size & Innodb_buffer_pool_instances
[OK] InnoDB Read buffer efficiency: 99.99% (2954768806 hits/ 2955078519 total)
[OK] InnoDB Write log efficiency: 95.93% (111839144 hits/ 116582132 total)
[OK] InnoDB log waits: 0.00% (0 waits / 4742988 writes)

-------- AriaDB Metrics ----------------------------------------------------------------------------
[--] AriaDB is disabled.

-------- TokuDB Metrics ----------------------------------------------------------------------------
[--] TokuDB is disabled.

-------- XtraDB Metrics ----------------------------------------------------------------------------
[--] XtraDB is disabled.

-------- RocksDB Metrics ---------------------------------------------------------------------------
[--] RocksDB is disabled.

-------- Spider Metrics ----------------------------------------------------------------------------
[--] Spider is disabled.

-------- Connect Metrics ---------------------------------------------------------------------------
[--] Connect is disabled.

-------- Galera Metrics ----------------------------------------------------------------------------
[--] Galera is disabled.

-------- Replication Metrics -----------------------------------------------------------------------
[--] Galera Synchronous replication: NO
[--] This server is acting as master for 1 server(s).
[--] Binlog format: MIXED
[--] XA support enabled: ON
[--] Semi synchronous replication Master: Not Activated
[--] Semi synchronous replication Slave: Not Activated
[!!] This replication slave is not running but seems to be configured.

-------- Recommendations ---------------------------------------------------------------------------
General recommendations:
    Run OPTIMIZE TABLE to defragment tables for better performance
      OPTIMIZE TABLE `REDACTED`.`REDACTED`; -- can free 191.703922271729 MB
      OPTIMIZE TABLE `REDACTED`.`REDACTED`; -- can free 143.067314147949 MB
    Total freed space after theses OPTIMIZE TABLE : 334.771236419678 Mb
    Reduce or eliminate unclosed connections and network issues
    Increase table_open_cache gradually to avoid file descriptor limits
    Read this before increasing table_open_cache over 64:
    This is MyISAM only table_cache scalability problem, InnoDB not affected.
    See more details here:
    This bug already fixed in MySQL 5.7.9 and newer MySQL versions.
    Beware that open_files_limit (5000) variable
    should be greater than table_open_cache (2000)
    Thread pool size for InnoDB usage (8)
    Read this before changing innodb_log_file_size and/or innodb_log_files_in_group:
Variables to adjust:
    query_cache_size (=0)
    query_cache_type (=0)
    query_cache_limit (> 1M, or use smaller result sets)
    sort_buffer_size (> 1M)
    read_rnd_buffer_size (> 256K)
    table_open_cache (> 2000)
    thread_pool_size between 16 and 36 for InnoDB usage
    innodb_buffer_pool_size (>= 12G) if possible.
    innodb_log_file_size should be (=1G) if possible, so InnoDB total log files size equals to 25% of buffer pool size.
    innodb_buffer_pool_instances(=12)

ulimits of dbm1
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 514886
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 1024
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 10240
cpu time               (seconds, -t) unlimited
max user processes              (-u) 514886
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

ulimits of dbm2
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 1030587
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 1024
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 10240
cpu time               (seconds, -t) unlimited
max user processes              (-u) 1030587
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

SHOW GLOBAL STATUS @ dbm1: https://gist.github.com/adriankirchner/cfffedfcc0699798e6c9276b09094ee1
SHOW GLOBAL STATUS @ dbm2: https://gist.github.com/adriankirchner/b021d8943f59c9a2448caf5dba6f89af
SHOW GLOBAL VARIABLES @ dbm1: https://gist.github.com/adriankirchner/b644072f063f80c2f41c604d5551eb18
SHOW GLOBAL VARIABLES @ dbm2: https://gist.github.com/adriankirchner/fa0ce51eb30a7368a30242fc9acba93b
Unfortunately iostat does not work inside of OpenVZ containers.
Just to be on the safe side I increased the RAM on both containers from 16GB to 20 GB.
The monitoring history for replication failures can be found here: https://i.stack.imgur.com/18Dff.png
Update 2018-04-30
Wilson provided us with a number of performance tweaks which we slowly deploy to this configuration - thank you very much for this!
In the meantime we updated both servers to Percona 5.7.21-21-log but the replication errors still occur.
When I dig into the binlog position stated in the error log ([..]the last event read from './mysql-bin.007091' at 71137, the last byte read from './mysql-bin.007091' at 71137.) this is the statement causing the error:
# at 71049
#180308  6:41:25 server id 1  end_log_pos 71137 CRC32 0x8bbeaab8    Query   thread_id=61875722  exec_time=0 error_code=0
SET TIMESTAMP=1520487685/*!*/;
COMMIT
/*!*/;
# at 71137 <---- position from the error message
#180308  6:41:25 server id 1  end_log_pos 71202 CRC32 0x87513662    Anonymous_GTID  last_committed=140  sequence_number=141 rbr_only=no
SET @@SESSION.GTID_NEXT= 'ANONYMOUS'/*!*/;
# at 71202
#180308  6:41:25 server id 1  end_log_pos 71289 CRC32 0xda97e104    Query   thread_id=61875722  exec_time=0 error_code=0
SET TIMESTAMP=1520487685/*!*/;
BEGIN
/*!*/;
# at 71289
#180308  6:41:25 server id 1  end_log_pos 71631 CRC32 0x7c566dd1    Query   thread_id=61875722  exec_time=0 error_code=0
SET TIMESTAMP=1520487685/*!*/;
update some_tables set some_col = 'some_value' where some_pk = 'some_value' <-- REDACTED
/*!*/;
# at 71631
#180308  6:41:25 server id 1  end_log_pos 71719 CRC32 0x37a2a3a9    Query   thread_id=61875722  exec_time=0 error_code=0
SET TIMESTAMP=1520487685/*!*/;
COMMIT
/*!*/;

So the statement causing the error is SET @@SESSION.GTID_NEXT= 'ANONYMOUS'/*!*/; - I verified this with the binlog of another replication outage. There are very few records on this:
- https://bugs.mysql.com/bug.php?id=85480
- https://groups.google.com/forum/#!topic/percona-discussion/u1k85oY5DB8
Both are operating with GTID_MODE=ON (we use GTID_MODE=OFF) and are facing totally different error message in the slave status.
Comment: For MASTER and SLAVE, individually, please post in pastebin.com Additional information request.
RAM on your Host server are they each 16GB?
current complete my.cnf/ini
Text results of:
A) SHOW GLOBAL STATUS;
B) SHOW GLOBAL VARIABLES;
Optional very helpful information, if available includes -
htop   OR  top for most active apps
ulimit -a       for a linux/unix list of limits,
iostat -x when system is busy for an idea of IOPS by device
df -h  for a linux/unix free space list by device
free -m  for a linux/unix free memory report
complete MySQLTuner.com  report  for analysis.
Comment: I think this is an issue of MySQL. Please see the following for detail.
https://wild-growth.blogspot.com/2018/09/mysqlreplicationunknown-error-reading.html
Comment: FROM dbm2 (Ubuntu OS), Please post to pastebin.com or here,
A) iostat -x when system is busy for an idea of IOPS by device,
B) df -h  for a linux/unix free space list by device,
   includes hda & sda (SSD) filesystem type clues
C) free -m  for a linux/unix free memory report
D) cat /proc/meminfo includes VMallocUused .
Analysis of dbm2 almost completed, this information will help.
Answer: This error is usually caused by a hardware glitch or a bug so obscure that it hasn't been found in over a decade. You haven't mentioned anything about the hardware, so the obvious first question to ask is whether it has ECC memory and whether you are seeing any MCE errors in your syslog, or if sensors are showing overheating on any of the components. If you are always seeing this on the same server(s) (but not ALL servers), then failing hardware could be a very likely explanation.
The optimal solution is obviously to fully re-initialize the replica, as that will avoid any risk of anomalies creeping in.
Having said that, this also clearly unpalatable if you have terabytes of data, so there may be a way you can restore replication without rebuilding the slave completely. Use mysqlbinlog on the master to identify where the transactions begin, and look for the adjacent transactions near positions 71137 (your Exec_Master_Log_Pos) and 43445 (where the error says it choked on reading the binlog). There is a very good chance that the positions listed are actually erroneous and no transaction in the binlog starts at those positions.
If that is the case, you can reset your replication coordinates on the slave to the last transaction mysqlbinlog lists that is before the position the slave thinks it is at. You can find more details on exactly what to do in this mysql troubleshooting article. There is risk associated with doing this (if the coordinates got corrupted, there is no telling what else got corrupted), but if doing the full re-initialisation immediately is prohibitively expensive, you might be able to buy yourself some time using this approach, at least until you can verify (e.g. using pt-table-checksum whether you have to rebuild the entire replica data set.
Answer: Suggestions for your my.cnf-ini [mysqld] section to consider
innodb_buffer_pool_size=8G  # from 12G only 16G on server and MyISAM involved
#sort_buffer_size=2047K  lead with # for default
#read_buffer_size=244K  lead with # for default
#join_buffer_size=244K  lead with # for default
thread_cache_size=16  # from 8 to avoid threads_created as often
query_cache_min_res_unit=512  # from 4096 to reduce QC RAM reqd per SELECT stored

Please spend 2 minutes at MySQLCalculator.com to recognize the extreme RAM footprint your current my.cnf-ini variables would require.  Only 16G available.
Also, please post complete Mysqltuner report that will include version of MySQL you are using, by ENGINE data space used and table counts, cache utilization, threads created and other helpful information.
Please post complete results of
A) ulimit -a   so we know the limits your OS are working with and
B) iostat -x   for extended IOPS read/writing to your drives when busy.
Comment: Until yesterday the replication was stable. But then the replication crashed again with:

Got fatal error 1236 from master when reading data from binary log: 'unknown error reading log event on the master; the first event 'mysql-bin.009853' at 74393, the last event read from './mysql-bin.010340' at 1238, the last byte read from './mysql-bin.010340' at 1238.'

I'll add the information you asked for.
Comment: Hey @Wilson, sorry for the late answer. Thank you very much for your time and effort. I added you in Skype - feel free to ping me when you have the time.
I already knew the blog post from Percona, but unfortunately they are only dealing with known fatal errors.
Before my last comment, the replication ran fine for about a month. But as you can see in the following screenshot, the replication survived just for about 6 days after the last time we fixed it: https://i.stack.imgur.com/18Dff.png
Comment: @adrian How many days was replication stable?  Thanks for posting requested available information.  Will pursue analysis during the next week and offer suggestions as details emerge.  A TON of into to analyze.  THANKS.
Comment: @Adrian  Please review this link's information from Percona technician dated October 8, 2014
https://www.percona.com/blog/2014/10/08/mysql-replication-got-fatal-error-1236-causes-and-cures/     When will you have time to use Chat of serverfault.com with me?  I am available next 72 hours, then next availability will be after May 2, 2018.
Comment: @Adrian could you chat at this time?
Comment: @Adrian  Do you have SKYPE available for Linux or Windows? Would be more convenient than chat here.  With Screen Sharing and chat together.  Should be able to find me as Wilson Hauck  Birmingham AL  USA   or at wlhauck at aol dot com on SKYPE.
Comment: @Adrian When could we schedule a SKYPE session?  Thanks
Comment: Adrian,  What is your UTC time zone?  I am UTC -6 hrs.  And I see you in my Skype list of ID's.  Would have have time to Skype this week?  Thanks
Comment: Hey Wilson, thank you for asking. The project is in the process of migrating to entire new hardware and software instances. I will update this thread about whether the problem persists or not. Thank you!
Comment: @Adrian Thanks for your comment.  May your migration be very successful.  Looking forward to providing analysis services for you in the future.  Thanks for your Skype connection.


How to make an app that gives me name by writing the ID

Question: I need to make a console app using arrays
I have to declare an array with few names and another array with few IDs  and then I have to make the app
to ask me write  the ID and it displays the name of the current ID (0 positioned name has 0 positioned ID and so on)
and if the typed ID is not correct I need to get an answer that the ID doesn't exist also I loops should be used to know which ID goes to which name
ok here is the code and I Don't know what to do more
{fak y'all for downvoting}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp10
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] names ={ "Endrit", "Endrit1", "Endrit2", "Endrit3", "Endrit4", "Endrit5", "Endrit6" };
            string[] ID = { "001", "002", "003", "004", "005", "006", "007" };

            Console.Write("Type the ID :");
            string IDN = Console.ReadLine();
            Console.ReadKey();
        }
    }
}

Comment: Are you asking us to code it for you? I hope not. Show us what you got and what you tried.
Comment: Sounds like homework?
Comment: Well, for starters, you should be using objects there's no relation between the 2 arrays. I suggest you read more into C# and OOP.
Comment: Ok. So what is your question? There are many examples of exactly what you're talking about on this site. Which part are you stuck on? Please show the code you have so far and let us know where you need help.
Comment: @12seconds but I have to make a relation between them using indexes I Don't know how
Comment: Why do you have to? Homework assignment on arrays? If not homework, then what's stopping you from doing objects? Clients don't tell us how to code.
Comment: no dude its not homework I am just trying to learn c# today in class we did something like that but I was sitting behind and I couldn't see anything so I didn't understand well how it worked.... @12seconds and what do you mean objects ? we learned loops , if statement , arrays and with that teacher said you can do it
Comment: Sorry if I sounded rude, but to answer your question. You don't need `string[] ID`, each value in `names` have `index`, so you would just apply that index like `names[0]` which would be `Endrit`
Comment: Objects will come later, this is a normal progression to learning them.
Answer: You can use Array.IndexOf to get the index of a particular item in an array. If the item is not found, it will return -1.
So, you can just find the index of the user input in the ID array, and return the item at the same index in the names array:
// Get the index in the ID array of the item the user entered
int indexOfUserEntry = Array.IndexOf(ID, IDN);

// If the item was found (index is > -1) show the item at the same index in the names array
if (indexOfUserEntry > -1)
{
    Console.WriteLine("The name for that id is: " + names[indexOfUserEntry]);
}
else
{
    Console.WriteLine("The specified Id does not exist");
}

Console.WriteLine("\nDone!\nPress any key to exit...");
Console.ReadKey();


Como obter o IP do HOST através do domínio em PYTHON?

Question: Em PHP, para obter o ip de um determinado domínio, eu costumo utilizar a função gethostbyname.
Exemplo PHP:
gethostbyname('www.google.com'); //220.127.116.11

E em Python? Como eu posso fazer isso?
Answer: Na realidade em python é quase isso:
import socket
socket.gethostbyname('www.google.com') # 220.127.116.11


Chromatic accordion: how can the left hand slide down while pushing?

Question: My accordion method specifies that pushing should be done against the right inner thigh.  Hence, this is a upper left to lower right movement, from the accordionist point of view.  I cannot see how this can be compatible with my wrist sliding down — once it is down, I can resume the upper left to lower right move, even if it's a little bit more awkward.
I like my method because it has very definite rules ("your thumb should not go further than the ridge of the instrument, the wrist should be snuggly strapped, so that pulling does not really create a space from your hand and the instrument, the fingers should be curved and the articulations tense but soft, the thumb should be outstreched and slide with the hand, …")  but this one is an open question to me.  "Becoming one with the accordion" is still far.
Thanks for your input!
Answer: I'd say your book is a bit obsessive.  Now it's true that a lot of accordion players, in particular those playing the accordion as a portable piano, severely underestimate the importance of bellows control.  It's like not worrying about bowing when playing the violin.  That's where the soul of the sound originates.
To make use of that, you need to have a good control of the accordion, have the bellows pressure correspond directly with force and/or position of your arm.  An additional consideration is that you don't want the cardboard part of the bellows move across your thighs since that makes the bellows-protecting stripes to get worn away over time.
To avoid that, you basically have the halves of your instruments poised against your inner thighs and (particularly the right one) a bit of their top (which is where the accordionist curates his hematomata).  Which is probably what your method is trying to achieve.
So in a way, that's what you are moving against at the bottom.  But that that not mean that your hands are aiming or moving towards those points.  They are doing their work on the bellows in a manner consistent with keeping the instrument's bottom parts poised against/on their respective thighs.
The basic effect you want to achieve here is that your left arm is in direct control of the instruments lung in your embrace.
What actually helps a lot towards that goal is a back strap.  If you don't have one yet, get one.


Why is any compact metric space the union of a countable set a subset which is a perfect space under the induced topology?

Question: Recently I stumbled across the fact that any compact metric space is the union of some countable set and a subset that, when given the induced topology, is a perfect space.
Can anyone provide a proof or reference to a proof of this fact? Thanks.
Comment: See http://en.wikipedia.org/wiki/Cantor%E2%80%93Bendixson_theorem
Comment: Note that the set of points with a countable neighborhood is itself both countable and open. Its complement is closed and perfect.
Answer: A compact metric space is second countable (i.e. has a countable basis): an open cover consisting of all open balls with radius $1/n$ has a finite subcover $\mathcal{B}_n$ by compactness, and one can show that the union of all these $\mathcal{B}_n,n\in\mathbb{N}$ is a countable basis.
Now that we know that a compact metric space is second countable, we can use the following proposition which can be proven using the hint given in the comments by George Lowther.

Every second countable space is a union of a countable set and a perfect set.

Proof: Let $X$ be a second countable space. Pick a countable basis $\mathcal{B}$ of $X$. Denote
$$C=\{x\in X:x\text{ has a countable neighbourhood}\}\quad\text{and}\quad P=X\setminus C.$$
Let us show that $C$ is countable. For each $x\in C$ choose a countable neighbourhood $B_x\in\mathcal{B}$ of $x$. For each $B\in\mathcal{B}$ denote $C_B=\{x\in C:B_x=B\}$. Since $x\in B_x$ and $B_x$ is countable for each $x\in C$, each $C_B$ is countable too. Now $C=\bigcup_{B\in\mathcal{B}}C_B$ is countable, being a countable union of countable sets.
Note that any open and countable neighbourhood $U$ of a point $x\in C$ is a subset of $C$, since the same $U$ is a countable neighbourhood of each point of $U$. Since each point of $C$ has such a neighbourhood, $C$ is open and $P$ is closed.
Lastly let us show that $P$ does not have isolated points in itself (i.e. $P$ is dense-it-itself). Pick $x\in P$ and a neighbourhood $U$ of $x$. $U$ is uncountable by definition of $C$, so $C$ being countable, $U\setminus(C\cup\{x\})\subseteq P$ is nonempty and thus $x$ is not an isolated point in $P$.
We have shown that $X=C\cup P$, where $C$ is countable and $P$ is perfect. $\square$
By the way, a similar argument can be used to prove that every space having a basis of cardinality $\kappa$ is a union of a set of cardinality $\kappa$ and a perfect set.
Comment: This is of course correct (with mild choice assumptions), but in my opinion the tricky part of this problem is that compact metric spaces are automatically separable (equiv., second countable).  This solution glosses over that step.
Comment: @ccc: Yes, somewhere along the way I managed to forget that the question was about compact rather than separable metric spaces. I added a few words indicating how one can show that compact metric implies second countable.
Answer: Every compact metric space is second countable (see, e.g. this proof on PlanetMath). In the book "Basic real analysis" by Sohrab you can find the theorem attributed to Cantor-Bendixon (sic):

Let $(M,d)$ be a second countable metric space and let $F\subset M$ be any closed subset. Then $F=P\cup C$ where $P\subset M$ is perfect and $C\subset M$ is countable.

Here's the link to the relevant theorem (5.3.4) in Google Books.
The theorem thus stated is more general. If you take $(M,d)$ to be compact, then by the first observation, and taking $F=M$ you get the desired result.
Comment: Thanks, I'm going to browse through this and try to figure it out.


JAX-RS: Double @PathParam passing

Question: I would like to pass Double path params like 5, 5.0, 0.5, 3.5, 3.65 etc.
So I make such method on JAX-RS resource:
 @GET
 @Path("/rated-above/{minAvgRating : \\d+(\\.\\d+)? }")
 @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
 public Response getProvidersOnAverageRatedAbove( @PathParam("minAvgRating") Double minAvgRating,
                                                         @BeanParam PaginationBeanParam params) throws ForbiddenException {
             // method
 }

But this method seems to doesn't work correctly even without Regex pattern.
Caused by: org.jboss.resteasy.core.NoMessageBodyWriterFoundFailure: Could not find MessageBodyWriter for response object of type: pl.salonea.jaxrs.utils.ErrorResponseWrapper of media type: application/octet-stream
at org.jboss.resteasy.core.ServerResponseWriter.writeNomapResponse(ServerResponseWriter.java:67)
at org.jboss.resteasy.core.SynchronousDispatcher.writeException(SynchronousDispatcher.java:153)

UPDATE
Sorry without regex it works correctly there is some problem with regex
 \d+(\.\d+)? I have been also trying to use:  [0-9]+(\.[0-9]+)? and just \S+ (not white space)
Answer: Try to use a BigDecimal instead of a Double, e.g.
@GET
@Path("/rated-above/{minAvgRating}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response getProvidersOnAverageRatedAbove(@PathParam("minAvgRating") BigDecimal minAvgRating, @BeanParam PaginationBeanParam params) throws ForbiddenException {
  Double myDouble = Double.valueOf(minAvgRating.toString());
  // .. and then use myDouble

Comment: It's odd but I thinks there is some problem with IntelliJ compilation deployment as this hasn't been working about 20 min and then whan I have rewritten it without pattern and than again with the above pattern it starts to work

JAX-RS: Double @PathParam passing


Can the Drupal 6 search function also index block content?

Question: I have a site where much of content has been entered into blocks instead of Pages, Articles or Blogs.  The blocks have then been enabled to show up on specific pages, creating the desired effect for the site.
However, as content as been added to these blocks, the search feature of Drupal won't find the pages that have that content on it.
Are there any options to adjust the search engine features for something like this?  Is there a hook that can be used to customize the search results?
Answer: No, block content is not searchable by default.
Have you tried the Block Search module? Seems that is what you need.
edit: After reviewing the module, I now see that the search functionality inside block content is done for only administrators, so that module probably doesn't help.


select sequelize realiza consulta diferente dos parâmetros passados com datetime

Question: Esta é a função que realiza a query:

router.get('/out_filtered', async (req, res, next) => {
    try {
        const dateStart = req.body.date_start;
        const dateEnd = req.body.date_end;
        console.log('start', dateStart);
        console.log('end', dateEnd);

        const where = {
            date_create: {
                [Op.between]: [dateStart, dateEnd],
            }
        };

        const result = await cashFlowOutsModel.findAll({
            where,
            logging: console.log
        });

        return res.status(200).send(result);

    } catch (err) {
        console.log(err)
        res.logger.log('error', err);
        return res.status(500).send(err);
    }
});

Como estou passando os parâmetros:

Como é feito a requisição, pelo log do console:

Os horários que são passados via parâmetro não correspondem à consulta.
Comment: Qual o banco que voce esta usando? postgres ou mysql? se for postgres, acho que sei qual o problema.
Comment: Se possivel, mostre como esta configurado o seu `const sequelize = new Sequelize()`.
Comment: const Sequelize = require('sequelize');
Comment: estou usando mysql
Answer: Ao usar o Sequelize, é possível que ocorra um problema na hora de recuperar a hora  banco de dados. O Sequelize converte a hora da data para a hora UTC. E como se o sequelize reconhecesse a hora no campo de entrada como a hora UTC, logo baseado na timezone, ele adiciona mais 2 horas (baseado no log que voce mostrou) se o timezone estiver com alguma valor.
Nessa situação, é necessário alterar a configuração do Sequelize para obter os registros adequados sem alteracao de hora. Tente fazer esse ajuste na configuracao do sequelize:
const sequelize = new Sequelize('db_name', 'user', 'password', {
     host: '<seu host>',
     dialectOptions: {
      useUTC: false     // para considerar a hora da consulta como a hora
                        // local, logo nao soma +02:00 horas
     },
     dialect: 'mysql',
     timezone: '+02:00',// para salvar a data baseado no fuso horario
});


Evento que identifica quando o navegador é redimensionado.

Question: Existe algum evento javascript que identifique quando o navegador redimensiona a página?
Estou tendo problemas com redimensionamento da página com uma janela FancyBox, que perde suas mudanças dinâmicas e volta a configuração de quando ela foi aberta.
Answer: Existe sim.
Javascript
var addEvent = function(elem, type, eventHandle) {
    if (elem == null || typeof(elem) == 'undefined') return;
    if ( elem.addEventListener ) {
        elem.addEventListener( type, eventHandle, false );
    } else if ( elem.attachEvent ) {
        elem.attachEvent( "on" + type, eventHandle );
    } else {
        elem["on"+type]=eventHandle;
    }
};

addEvent(window, "resize", function(){
  console.log("a página foi redimensionada ");
});

jQuery
$(window).resize(function(){
  console.log("a página foi redimensionada ");
})

Answer: Você pode fazer o seguinte:
jQuery
$(function(){

width_inicial=window.innerWidth;
heigth_inicial=window.innerHeight;

setInterval(function(){
  if(window.innerWidth!=width_inicial || window.innerHeight!=heigth_inicial)
  {
    /* seu código */
    alert('a página foi redimensionada');
  }
},1000);

});


How can I create a view that lists users who have NOT completed an order?

Question: I am helping with a Drupal 6 / Ubercart site that has tons of spam user accounts registered.
I want to create a view that will list spam accounts. My thinking is that users who have registered but never bought anything in Ubercart have a high probability of being spam so I want to create this view. However, I can't figure out how to filter my user view to list only users who have not completed an order.
Is this possible?
Answer: To save to anyone else the trouble, this is the view I created to achieve the above.
<code>$view = new view;
$view->name = 'Spambots';
$view->description = '';
$view->tag = '';
$view->base_table = 'users';
$view->core = 6;
$view->api_version = '2';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */
$handler = $view->new_display('default', 'Defaults', 'default');
$handler->override_option('relationships', array(
  'uid' => array(
    'label' => 'Order user',
    'required' => 0,
    'id' => 'uid',
    'table' => 'uc_orders',
    'field' => 'uid',
    'relationship' => 'none',
  ),
));
$handler->override_option('fields', array(
  'mail' => array(
    'label' => 'E-mail',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'absolute' => 0,
      'link_class' => '',
      'alt' => '',
      'rel' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'hide_alter_empty' => 1,
    'link_to_user' => 'mailto',
    'exclude' => 0,
    'id' => 'mail',
    'table' => 'users',
    'field' => 'mail',
    'relationship' => 'none',
  ),
  'created' => array(
    'label' => 'Created date',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'absolute' => 0,
      'link_class' => '',
      'alt' => '',
      'rel' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'hide_alter_empty' => 1,
    'date_format' => 'small',
    'custom_date_format' => '',
    'exclude' => 0,
    'id' => 'created',
    'table' => 'users',
    'field' => 'created',
    'relationship' => 'none',
  ),
  'login' => array(
    'label' => 'Last login',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'absolute' => 0,
      'link_class' => '',
      'alt' => '',
      'rel' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'hide_alter_empty' => 1,
    'date_format' => 'small',
    'custom_date_format' => '',
    'exclude' => 0,
    'id' => 'login',
    'table' => 'users',
    'field' => 'login',
    'relationship' => 'none',
  ),
  'edit_node' => array(
    'label' => 'Edit link',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'absolute' => 0,
      'link_class' => '',
      'alt' => '',
      'rel' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'hide_alter_empty' => 1,
    'text' => '',
    'exclude' => 0,
    'id' => 'edit_node',
    'table' => 'users',
    'field' => 'edit_node',
    'relationship' => 'none',
  ),
  'delete_node' => array(
    'label' => 'Delete link',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'absolute' => 0,
      'link_class' => '',
      'alt' => '',
      'rel' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'hide_alter_empty' => 1,
    'text' => '',
    'exclude' => 0,
    'id' => 'delete_node',
    'table' => 'users',
    'field' => 'delete_node',
    'relationship' => 'none',
  ),
));
$handler->override_option('sorts', array(
  'uid' => array(
    'order' => 'DESC',
    'id' => 'uid',
    'table' => 'users',
    'field' => 'uid',
    'relationship' => 'none',
  ),
));
$handler->override_option('filters', array(
  'order_id' => array(
    'operator' => 'empty',
    'value' => array(
      'value' => '',
      'min' => '',
      'max' => '',
    ),
    'group' => '0',
    'exposed' => FALSE,
    'expose' => array(
      'operator' => FALSE,
      'label' => '',
    ),
    'id' => 'order_id',
    'table' => 'uc_orders',
    'field' => 'order_id',
    'relationship' => 'none',
  ),
  'rid' => array(
    'operator' => 'not',
    'value' => array(
      3 => '3',
      6 => '6',
      4 => '4',
      5 => '5',
    ),
    'group' => '0',
    'exposed' => FALSE,
    'expose' => array(
      'operator' => FALSE,
      'label' => '',
    ),
    'id' => 'rid',
    'table' => 'users_roles',
    'field' => 'rid',
    'relationship' => 'none',
    'reduce_duplicates' => 0,
  ),
));
$handler->override_option('access', array(
  'type' => 'role',
  'role' => array(
    3 => 3,
    5 => 5,
  ),
));
$handler->override_option('cache', array(
  'type' => 'none',
));
$handler->override_option('header', 'The following accounts have no orders associated with them and are not assigned a specific role. Therefore it is safe to assume they are spambots.');
$handler->override_option('header_format', '1');
$handler->override_option('header_empty', 1);
$handler->override_option('use_ajax', TRUE);
$handler->override_option('items_per_page', 20);
$handler->override_option('use_pager', '1');
$handler->override_option('style_plugin', 'table');
$handler->override_option('style_options', array(
  'grouping' => '',
  'override' => 1,
  'sticky' => 0,
  'order' => 'asc',
  'summary' => '',
  'columns' => array(
    'mail' => 'mail',
    'login' => 'login',
    'uid' => 'uid',
    'delete_node' => 'delete_node',
  ),
  'info' => array(
    'mail' => array(
      'sortable' => 0,
      'separator' => '',
    ),
    'login' => array(
      'sortable' => 0,
      'separator' => '',
    ),
    'uid' => array(
      'sortable' => 0,
      'separator' => '',
    ),
    'delete_node' => array(
      'separator' => '',
    ),
  ),
  'default' => '-1',
));
$handler = $view->new_display('page', 'Page', 'page_1');
$handler->override_option('path', 'spambots');
$handler->override_option('menu', array(
  'type' => 'none',
  'title' => '',
  'description' => '',
  'weight' => 0,
  'name' => 'navigation',
));
$handler->override_option('tab_options', array(
  'type' => 'none',
  'title' => '',
  'description' => '',
  'weight' => 0,
  'name' => 'navigation',
));
</code>
It will need tweaking to your needs because I've got it set up to filter based on user role too but should give you a good base to start with.
Also the SQL is:
<code>SELECT users.uid AS uid, users.mail AS users_mail FROM users users  LEFT JOIN uc_orders uc_orders ON users.uid = uc_orders.uid LEFT JOIN users users_uc_orders ON uc_orders.uid = users_uc_orders.uid LEFT JOIN users_roles users_roles ON users.uid = users_roles.uid AND (users_roles.rid = 3 OR users_roles.rid = 6 OR users_roles.rid = 4 OR users_roles.rid = 5) WHERE (uc_orders.order_id IS NULL) AND (users_roles.rid IS NULL) ORDER BY uid DESC
</code>
Comment: I finally got around to using this and it works perfectly, but one thing to note is this view requires that the Ubercart Views module is installed.
Answer: first you will have to add a relationship linking ubercart orders to a user, then filter by the order number that is not greater than 0.


Why is there a natural accidental on this C?

Question: In Simandl's 30 Etudes for String Bass, Etude #10, there is this natural accidental on the note C (fourth bar of the second line):

Since there is no alteration of the note either by the key signature or some previous accidental, what does this natural accidental imply?
Is it a mistake or was I supposed to play some previous C differently?
Comment: I could see putting it there if it sounds weird to play C natural. It's like the composer saying, "Yeah, I know it sounds weird, I want it that way. Yes, it's supposed to be natural."
Comment: This kind of confusion is why I (when I'm wearing my composer/editor hat) think cautionary accidentals should always be in parentheses. Without parentheses, it's unclear to the attentive performer/reader if the marking is cautionary, if they missed something earlier, or if someone on the composer/editor/engraver side of things made a mistake (which is hardly uncommon).
Comment: @ToddWilcox right, but the C♮ sounds not only not weird at this spot, it's almost _inevitable_ after the leading note B♮.
Comment: Since it's in, presumably, C minor, and the lower C in the same bar isn't marked, it's sloppy writing/editing.
Comment: @ToddWilcox - agree with your idea. However, it's an octave melodic minor scale run, C- C. Anything other than a C natural would sound weird, and a muso playing up the scale would expect it to go to a C natural. Yet another reason for NOT putting the sign.
Comment: There's no rule against redundant markings;  I agree with @ToddWilcox on this one.
Comment: @LiberalArtist - true, but this particular C doesn't even need parentheses. The section is in C minor anyway. He didn't bother for the lower C at the beginning of the run.
Comment: I'm not sure if I understood your comment @ToddWilcox. that passage is the C melodic minor scale (ascending), so the C natural is expected to go there (like Leftaround said). What exactly do you mean by 'sounds weird' ?
Answer: In the full score here http://imslp.org/wiki/30_Etudes_for_the_Double_Bass_(Simandl,_Franz) (top of page 29) there is no accidental on the C.
The OP's image is apparently a different edition - the dynamic markings are also different. I call "typo", and/or "poor editing and proofreading".
Comment: @NeilMeyer spurious accidentals are nothing. I have an early Russian edition of some piano music by Scriabin that even has some incorrect clefs, not to mention MM marks that say "half-note = 40" when it should be "eighth-note = 40", etc, etc...!!!
Comment: Research for the win.
Comment: Probably non existing proofreading
Comment: Yep.  The only possible reason for the C natural sign would have been an unlikely C♯ or a very unlikely Cb somewhere in the vicinity in the piano score, and there isn't one.  Typo it is.
Answer: The measure in question is a straightforward melodic minor scale.  It is an "Etude for String Bass" so presumably there are no other instruments possibly playing (or having played) a different C.  There is no similar/transposed passage in the vicinity that would require an accidental/natural.
So you are correct in being irritated: this particular natural is uncalled for and does not help in any conceivable way.
Comment: @ToddWilcox I disagree. This answer seems to me to be a reasonable explanation of why the natural sign is unnecessary. And as alephzero's answer shows, the natural sign demonstrably shouldn't have been included in the first place, so there's objectively no good way to "edit in something about why the natural sign would be written in."
Comment: @Kevin I see where you're coming from (and where user26925 is probably coming from). To me, pointing out that the natural sign is unneccessary is not the same as answering why it's there, but it's not so far off that I downvoted or flagged, I see it both ways. I mainly commented to point out the nuance to a new user.
Comment: This isn't exactly an answer, more of a comment. I suspect you don't have the rep to comment. You might want to either edit in something about why the natural sign would be written in or delete this.
Comment: I'm not a bass player, but is it possible that the "4" fingering might suggest playing a C# for some reason? Personally I would have thought a cautionary flat on the E would have been more useful, to head off anybody thinking "whoopee - C major scale ahead, I know how to play that"!


Greatest common divisor of a number and the same number multiple of some rational

Question: I want to simplify (e.g. in terms of prime factors and its exponents) given expression:
$$
\gcd\left(a, a \frac{b}{c}\right),
$$
where $c\mid ab$.
Is it possible?
Thanks!
Answer: Conside the prime factorisation:
$$a = \prod\limits_i p_i^{k_i}, b=\prod\limits_i p_i^{l_i}, c=\prod\limits_i p_i^{m_i}$$
Then
$$\begin{align}
\gcd\left(a, a \dfrac{b}{c}\right) & = \gcd\left(\prod\limits_i p_i^{k_i}, \prod\limits_i p_i^{k_i+l_i-m_i}\right)\\
 & =\prod\limits_i p_i^{k_i-m_i}\gcd\left(\prod\limits_i p_i^{m_i}, \prod\limits_i p_i^{l_i}\right)\\
 & = \dfrac{a  \gcd(b,c)}{c}
\end{align}$$
Answer: Not really. For example, if $c\mid b$ and $\gcd(a,b) = 1$, then your expression is equal to $a$; on the other hand, if $c\mid a$ and $\gcd(c,b) = 1$, then the expression is $\frac{a}{c}$.
Answer: Let $a=\prod\limits_{i =0}^kp_i^{r_i},b=\prod\limits_{i =0}^kp_i^{s_i},c=\prod\limits_{i =0}^kp_i^{t_i}$, then we have
$$\frac {ab}c=\prod_{i =0}^kp_i^{r_i+s_i-t_i}\\
\text{gcd}\left(a,\frac{ab}c\right)=\prod_{i=0}^kp_i^{\min(r_i,r_i+s_i-t_i)}$$
This does not simplify as I initially thought to gcd$\left(a,\frac {ab}c\right)=\frac a{\text{gcd}(a,c)}$ but instead includes the factors present in $b$, probably something like
$$\frac{a\cdot\text{gcd}(a,b,c)}{\text{gcd}(a,c)}$$
where gcd$(a,b,c)=\text{gcd}(a,\text{gcd}(b,c))$.
The short answer is no, the expression does not really simplify from your starting point.


HiClass: Modelling a Hierarchical Classifier

Question: My question is specifically directed to the hiClass Python package for hierarchical classification (I am not sure if it is right to ask here, since I am not reporting an issue). After reading answer to this question that the package is actively supported.
I am working on a dataset for travel mode recognition problem. I would like to model the problem using hierarchical classification approach to proceed like in figure below:

The orange oval represent nodes and the green rectangle, the classes to predict.
I read in the related paper, that the class labels should be somehow transform into (n_samples x n_levels).

While features are exactly the same shape as expected
for training flat models in scikit-learn, hierarchical training labels are represented as an
array of shape n samples × n levels, where each column must contain either a label for the
respective level in the hierarchy or an empty string that indicates missing labels in the leaf
nodes.

Currently, my labels data structure in an array of shape (n_samples,):
>>> ytrain.shape
(31683,)

>>> ytrain[:10] # 0:walk, 1:bike, 2:bus, 3:car, 4:train
array([0, 0, 4, 1, 4, 2, 2, 3, 3, 3])

Questions
Assuming I am using the Local Classifier Per Parent Node algorithm:

Is there a handy way to retrieve just the predicted classes (e.g. predicting just the "Bike"  class instead of the hierarchical passway ["Root", "non-Motorised", "Bike"]?
Having that my classes have different tree levels (Walk & Bike -> level-2, others level-3), How then should the hierarchy of the Walk & Bike classes be (["Root", "non-Motorised", "Bike"] or ["Root", "non-Motorised", "Bike", " "]) considering the statement I qouted above?

Cc: Fabio
Answer: I am the main developer of HiClass.
Apparently, from the URL you linked you are using a third-party package from globality-corp, which is developed by someone else. This is the correct link for HiClass, which is currently hosted on scikit-learn-contrib.
Answering your questions:
1. Is there a handy way to retrieve just the predicted classes (e.g. predicting just the "Bike" class instead of the hierarchical passway ["Root", "non-Motorised", "Bike"]?
Unfortunately there is not an implementation to only return the leaf nodes at the moment, since the assumption we had with hierarchical classification is that all levels are important for the prediction. Please, correct me if I am wrong, but if you are only interested in the leaf nodes wouldn't flat classification be more appropriate for your use-case? I would need to update the algorithm to accommodate for that and it will probably take some time. I imagine an easier alternative would be for you to do some post-processing to return the last level that is not empty.
2. Having that my classes have different tree levels (Walk & Bike -> level-2, others level-3), How then should the hierarchy of the Walk & Bike classes be (["Root", "non-Motorised", "Bike"] or ["Root", "non-Motorised", "Bike", " "]) considering the statement I qouted above?
It is fine to provide the labels with nested lists, i.e., just as ["Root", "non-Motorised", "Bike"] and HiClass will add empty levels as necessary.
Edit: I think it would be useful to link this example from the gallery of examples to complement my answer to question 2: training with different number of levels
For future questions, please feel free to open an issue on GitHub or send me an email since I only read stack exchange occasionally.
Best regards,
Fabio
Comment: Thank you this detailed answer.


How to order rows by columns at arbitrary order ? MYSQL

Question: I have this query :
$query = "SELECT * FROM table1 ONE ORDER BY ....:
the order should be in this way :

first the mysql should get the rows with status 2.
then get the row with status 1.
then get the row with status 3.

**status is a col at table1.
Answer: Use FIELD function like this
 $query = "SELECT * FROM table1 ONE ORDER BY FIELD(status, 2, 1, 3)";

Answer: You can use conditionals in the order by.  Here is one method:
order by field(status, 2, 1, 3)


Remove Multiple values from an Array - Odin Project

Question: I am trying to do the 4th Javascript excercise in The Odin Project (https://github.com/TheOdinProject/javascript-exercises/tree/main/04_removeFromArray) and i am facing huge difficulties.
Currently the only thing that i managed to do is pass the first test, which was about to remove one value from the array. My code is the one below:
let array = new Array();

const removeFromArray = function(array) {
   let index = array.indexOf(3);
   if (index > -1) {
       array.splice(index,1);
      }
return array;
}

Any help on how i could advance on the level that i could remove multiple values, that would be amazing.
I ve read some solutions online but i really didn't get a lot.
Thank you very much in advance!
Answer: Let's say you want to remove multiple values that are passed as an array argument to your function. Then one possible solution would be something like this:
function removeFromArray(array, args) {

    const result = array.filter(element => !args.includes(element));
    return result

}

console.log(removeFromArray([1, 2, 3, 4], [2,3]))

In your console you can see that the resulting array is [1,4]. There are may ways to solve this kind of problem. Also, As, already suggested in the comments above, you should have taken an argument for the first part of the assignment too. The solution would be something like this:
function removeFromArray(array, arg) {

    const result = array.filter(element => element !== arg);
    return result

}

console.log(removeFromArray([1, 2, 3, 4], 3))

The result is of course [1,2,4].
Answer: Let's approach this problem by thinking of what we want our function to do and what we need to pass our function for that.
Here is our desired function as pseudo-code:
myArray= ["one", "two", "three", "four"]

function removeFromArray(array, index) {
  return array without element in given index
}

And calling removeFromArray(myArray, 3) should return ["one", "two", "four"].
Awesome. Now that we know what we are aiming to achieve, implementing it should be a breeze.
You seem to have approached this problem with the splice function.
Here is a way to do it that is semantically more clear:
  let arr = ["zero", "one", "two", "three", "four"];

  function removeIndex(i, array) {
    let newArray = [];
    for (let j = 0; j < array.length; j++) {
      if (j !== i) {
        newArray.push(array[j]);
      }
    }
    return newArray;
  }
  console.log(removeIndex(2, arr));

Comment: Alternatively this could also be done by using a preexistent function such as: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

In our case, you should just call `splice(, 1)`
Answer: Solution:
const removeFromArray = (arr, ...args) => arr.filter((item) => !args.includes(item))

Explanation:
(arr, ...args) - I'm accepting input array as first argument and spreading  any other arguments using spread operator (...)
=> - I'm using arrow notation to return value without the need of using return keyword
arr.filter() - I'm using build in filter method to return filtered array based on given restrictions
!args.includes(item) - I'm checking each element of the input array against the spreaded array of arguments
Comment: Thank you very much!! i haven't understood everything but i will do my reading!
But i tested it any it totally works. And also passes all the tests.
Comment: Hello again, if i wanted to write the exact same code without the arrow notation, how can i do it? Thanks in advance!
Comment: function removeFromArray (arr, ...args) {
  return arr.filter(function(item) {
    return !args.includes(item)
  })
}
Comment: Could you please also tell me what the exclamation mark before args do, in the end? And why we put it
Comment: It negates the condition. So `args.includes(item)` returns true if element is present in array, but we want the opposite. So thats why there is the exclamation mark before !args.includes()


Find all triples of non-negative Integers $a,b,c$ such that $a!b!=a!+b!+c!$

Question: Exactly what it says in the Title;  not much development from there :/
Comment: How can you determine that $b>a$, when your equation is symmetric in $a$ and $b$?
Comment: @BrianTung, but it would also be a *wrong* finding....
Comment: See "Factorial Problems" [here](http://mathschallenge.net/problems/pdfs/mathschallenge_3_star.pdf), Problem ID: 216 (09 Mar 2005).
Comment: This problem is also discussed on Ask Dr. Math [here](http://mathforum.org/library/drmath/view/65132.html).
Comment: Formatting tips [here](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).
Comment: @HenningMakholm: Maybe OP determined that $a \not= b$, and then wlog $b > a$.  It would be a non-trivial finding. :-)
Comment: Ignore that then, I am truly stumped
Comment: @BarryCipra: Ha ha, yeah, just noticed that. :-)
Comment: @DietrichBurde unable to find it. I downloaded as a pdf, got 142 pages. What pages are involved?
Comment: @DietrichBurde that worked, for me it says page 36
Answer: I assume you mean you've determined that without loss of generality $b\geq a$. We then have $$b!=1+\frac{b!}{a!}+\frac{c!}{a!},\,c\geq a.$$ Since $a!b!>a!+b!$, we have $a!,\,b!\geq 2$ so $b\geq a\geq 2$. In fact if $a=2$ then $2\times b! = 2+b!+c!,\,b!=2+c!$, which has no solutions. So $b\geq a\geq 3$ and $3|b!$, so $\frac{b!}{a!},\,\frac{c!}{a!}$ are not both multiples of $3$, and $b,\,c$ are not both $\geq a+3$. But $a!=1+\frac{a!}{b!}+\frac{c!}{b!}$, so either $a=b\leq c$ or $a<b>c$. The latter case precludes $c\geq a+3$, and so does the former since $\frac{c!}{a!}=a!-2\notin 3\mathbb{Z}$. So $c\in \left\{a,\,a+1,\,a+2\right\}$.
Case I: $c=a$ so $3|b!=2+\frac{b!}{a!}$ so $b\geq a+2$. If $b=a$ then $a!=3$; if $b=a+1$ then $\left(a+1\right)!=a+3$; if $b=a+2$ then $\left(a+2\right)!=a^2+3a+4$. One can easily check none of these is solved by integers $a \geq 3$.
Case II: $c=a+1$ so $b!=a+2+\frac{b!}{a!}$ and $a!-1|b!-\frac{b!}{a!}=a+2$. Since $a!-1 > a+2$  for $a\geq 4$ we have $a=3,\,c=4$, giving one solution with $b=3$. It turns out there are no others (see the next paragraph).
Case III: $c=a+2$ so $b!=a^2+3a+3+\frac{b!}{a!}$, so $a!-1|a^2+3a+3$, which is consistent with neither $a=3$ nor $a=4$. But $a!-1>a^2+3a+3$ whenever $a\geq 5$, so there are no more solutions.
Answer: First assume $a = b,$ so the equation becomes $a!(a!-2) = c!.$  In particular this implies that $a!-2 = 0$ or $(a+1)\cdots(a+k)$ for some $k > 0.$ The first case is impossible, and in the second, either $a+1\mid a!$ or $a!\equiv -1\mod (a+1)$ and $a+1$ is prime (Wilson's theorem). Actually there is a remaining case, in which $a! - 2 = a+1,$ which is when $a = b =3,$ giving a solution with $c = 4.$ Evidently when $a > 3,$ this is no longer possible, so we reduce to the cases above.
If $a+1\mid a!,$ then $a+1$ does not divide $a!-2$ unless $a+1\mid 2,$ whence $a = 1$ or $0.$ This is impossible, so $a+1$ is prime and $a! - 2\equiv -3\mod (a+1).$ But $a+1\mid a! - 2,$ so $a+1 = 3\Rightarrow a = b = 2,$ which again is impossible. Hence $a\not= b.$
Without loss of generality let $1 < a < b.$ Note then that $c > b,$ since $b!\mid RHS \Rightarrow b! \mid a! + c! < b! + c!.$ Divide through by $a!$ to get
$$b! = 1 + b!/a! + c!/a!.$$
Then mod $a+1,$ the LHS is $0,$ while the RHS is $1,$ so the only solution is $(a,b,c) = (3,3,4).$


$X$ and $Y$ are independent Poisson$(\lambda)$, $\lambda\sim\mathrm{exp}(\theta)$. What is the conditional distribution for $X$ given that $X+Y=n$?

Question: To clarify, the parameter $\lambda$ is a random variable with exponential distribution and parameter $\theta$. Can someone please tell me if I've correctly computed the conditional distribution for $X$ given $X+Y=n$. Thanks!
$$\begin{align*}
P\{X=k\} &= \int_0^\infty e^{\lambda}\frac{\lambda^{k}}{k!} \theta e^{-\theta\lambda} \, d\lambda \\
&=\frac{\theta}{k!}\int_0^\infty \lambda^{k} e^{-(1+\theta)\lambda} \, d\lambda \\
&=\frac{\theta}{k!(1+\theta)^{k+1}}\int_0^\infty u^k e^{-u} \, du\\
&=\frac{\theta}{(1+\theta)^{k+1}}  \text{ for } k = 0, 1, \ldots \\
\end{align*}
$$
Then $$P\{Y=\ell\} =\frac{\theta}{(1+\theta)^{\ell+1}} \text{ for } \ell = 0, 1, \ldots$$
Therefore,
$$\begin{align*}
 P\{X=k\mid X+Y=n\} &= P\{X=k\mid Y=n-k\} \\
&=\frac{\theta}{(1+\theta)^{k+1}}\frac{\theta}{(1+\theta)^{n-k+1}} \\
&=\frac{\theta^{2}}{(1+\theta)^{n+2}}
\end{align*}
$$
Comment: Are $X$ and $Y$ _unconditionally_ independent or are they conditionally independent given $\lambda$ for all values of $\lambda$? The marginal distributions of $X$ and $Y$ sure seem to resemble _geometric_ random variables with parameter $\frac{\theta}{1+\theta}$.
Answer: $\newcommand{\E}{\operatorname{E}}$I will denote the random variable by capital $\Lambda$ and the variable in the integral by lower-case $\lambda$. I take $X$ and $Y$ to be conditionally independent given $\Lambda$, so conditional on $\Lambda$, $X+Y\sim\mathrm{Poisson}(2\lambda)$.  Then we have
\begin{align}
\Pr(X+Y=n) & = \E(\Pr(X+Y=n\mid\Lambda)) = \E\left( \frac{(2\Lambda)^n e^{-2\Lambda}}{n!} \right) \\[10pt]
& = \int_0^\infty \frac{(2\lambda)^n e^{-2\lambda}}{n!} e^{-\theta\lambda} (\theta\,d\lambda) = \text{etc.} \tag 1
\end{align}
By a similar method find $\Pr(X=k\ \&\ Y=n-k)$, but don't write that as $\Pr(X=k)\cdot\Pr(Y=n-k)$ since $X$ and $Y$ are not marginally independent but only conditionally independent.  In other words, you're looking for
\begin{align}
& \Pr(X=k\ \&\ Y=n-k) = \E(\Pr(X=k\ \&\ Y=n-k\mid \Lambda)) \\[10pt]
= {} & \E(\Pr(X=k\mid \Lambda)\Pr(Y=n-k\mid \Lambda)) \\[10pt]
= {} & \int_0^\infty \frac{\lambda^k e^{-\lambda}}{k!} \cdot \frac{\lambda^{n-k} e^{-\lambda}}{(n-k)!} e^{-\theta\lambda} (\theta\,d\lambda). \tag 2
\end{align}
Later postscript: Just for fun, let's see what this comes to.  From $(2)$, we get
\begin{align}
& \frac \theta {k!(n-k)!} \int_0^\infty \lambda^n e^{-(\theta+2)\lambda} \, d\lambda \\[10pt]
= {} & \frac \theta {k!(n-k)!(\theta+2)^{n+1}} \int_0^\infty ((\theta+2)\lambda)^n e^{-(\theta+2)\lambda} ((\theta+2)\, d\lambda) \\[10pt]
= {} & \frac \theta {k!(n-k)!(\theta+2)^{n+1}} \int_0^\infty u^n e^{-u}\,du = \binom n k \frac\theta {(\theta+2)^{n+1}}. \tag 3
\end{align}
From $(1)$, we get
\begin{align}
& \int_0^\infty \frac{(2\lambda)^n e^{-2\lambda}}{n!} e^{-\theta\lambda} (\theta\,d\lambda) = \frac {2^n\theta}{n!} \int_0^\infty \lambda^n e^{-(\theta+2)\lambda} \, d\lambda \\[10pt]
= {} & \frac {2^n\theta}{n!(\theta+2)^{n+1}} \int_0^\infty ((\theta+2)\lambda)^n e^{-(\theta+2)\lambda} ((\theta+2)\,d\lambda) \\[10pt]
= {} &  \frac {2^n\theta}{n!(\theta+2)^{n+1}} \int_0^\infty u^n e^{-u} \, du = \frac{2^n \theta}{(\theta+2)^{n+1}}. \tag 4
\end{align}
Dividing $(3)$ by $(4)$ we get
$$
\binom n k \frac 1 {2^n}.
$$
In other words
$$
\Big( X\mid (x+Y=n) \Big) \sim \mathrm{Binomial}\left(n, \frac 1 2 \right).
$$
Still later postscript: By hindsight I definitely did all this the hard way.  Conditional on $\Lambda$, we have $X,Y\sim\text{independent Poisson}(\Lambda)$. Supposing $X\sim\operatorname{Poisson}(\alpha)$ and $Y\sim\operatorname{Poisson}(\beta)$ and $X,Y$ are independent, then one can show that the conditional distribution of $X$ given $X+Y=n$ is $\operatorname{Binomial}\left(n,\dfrac \alpha {\alpha + \beta}\right)$.  If $\alpha=\beta$, then clearly that means it is $\operatorname{Binomial}\left(n, \dfrac 1 2 \right)$.  So conditional on $\Lambda$ we have a result that does not depend on $\Lambda$; hence it must be the same as the marginal (i.e. "unconditional") distribution.
Comment: Thank you for your help. I need to study your steps to understand it better. Wouldn't dividing $(3)$ by $(4)$ yield $$
\binom n k \frac {\theta+2} {2^n}$$ I could be wrong.
Comment: @mmh0015 : I'm going to check some details, but I think one should get an answer that does not depend on $\theta$.  And I now suspect there is a simpler way to do this whole thing. ${}\qquad{}$
Comment: @mmh0015 : I should have had $n+1$ as the exponent in both $(3)$ and $(4)$, so $\theta$ cancels.  Also, there is a simpler way to do this than what I used, so I've added a postscript explaining that. ${}\qquad{}$
Answer: Update: This answer is wrong (I leave it only because I think the error can be instructive) in that it assumes that $X$ and $Y$ are independent, as if the distribution of each one depends on different (independent) parameters (say, $\lambda_X$ , $\lambda_Y$). But this is not what the problem statement imply; rather, it makes more sense to assume that both are driven by a single parameter $\lambda$, and hence they are not independent but only conditionally independent (that is, given the value of $\lambda$). The correct answer, thus, is that of Michael Hardy

The last step looks wrong to me.
$$P\{X=k \mid X+Y=n\}=\frac{P\{X=k \cap X+Y=n\}}{P\{X+Y=n\}}=\frac{P\{X=k \cap Y=n-k\}}{P\{X+Y=n\}}=\frac{P\{X=k\} P\{Y=n-k\}}{P\{X+Y=n\}}$$
Haven't you missed the denominator?
Comment: Oh yes, you're right! Ok then I have $$\frac{P\{X=k\}P\{Y=n-k\}}{\sum_{k=0}^{\infty} P\{X=k\}P\{Y=n-k\}}$$. And since $X$ and $Y$ are independent, I can just multiply the distributions in the numerator together. Is that correct for the denominator?
Comment: I'm getting that the numerator and denominator cancel out and thus, the distribution is $1$. This doesn't seem right.
Comment: You're assuming $X$ and $Y$ are independent, but the question as phrased seems to make sense only if we assume only conditional independence given $\lambda$. ${}\qquad{}$
Comment: @MichaelHardy : It seems you are right, I assumed that both  X and Y were totally independent (as if generated by indpendent realizatins of the parameter $\lambda$) but your approach makes more sense.
Comment: One easy way to see that $X$ and $Y$ are not independent is this: Suppose $X$ is observed to be in the vicinity of $20/\theta$, whereas its expected value is $1/\theta$.  That means _probably_ $\Lambda$ is much larger than it would usually be, and therefore $Y$ is also likely to be much larger than it would usually be. ${}\qquad{}$


Why do I need the this. qualifier to use an extension method in a master page?

Question: I have the following line of code in some master page code behind, but it fails without the this.  Why is that?
Repeater rep = this.FindControlsByIdRegEx("maintTableRepeater")[0] as Repeater;

This is in the master page Load event, and the extension method is defined as;
        public static List<Control> FindControlsByIdRegEx(this Control control, string idPattern)

Comment: "I have the following line of code in some master page code behind": Which code??
Answer: Extension methods must have an instance to "hang off of".
A method call without an object always refers to the method with that signature - in the same instance. Extension methods are not part of the instance. They are static methods that live elsewhere in the system, and use a little bit of compiler sugar - a trick, really - to look like they hang off of an object for ease of coding.
Comment: Yes, but everywhere else my extensions methods use the implicit 'this' in instance methods.


Dynamic list for Ionic App using Angular JS in two views

Question: I have a Ionic app with Angular JS. I have a Dynamic checkbox list which is called from an array in app.js. I have it so that when a user clicks on a checkbox, the list above gets updated with their choice, what I want is for the choice to get put into another view not another div i.e tab 1 = List, tab - 2 = choices. The code is:
  $scope.myList = [
      {name:'Choice one'},
      {name:'Choice two)'}
  ];

  $scope.myChoices = [];

  $scope.stateChanged = function(checked,indx){
    var item = $scope.myList[indx];
    if(checked){
        $scope.myChoices.push(item);
    }else{
        var index = $scope.myChoices.indexOf(item);
        $scope.myChoices.splice(index,1);
    }
}

html:

   My Choices

{{item.name}}

     University list

       <input type="text" placeholder="Search" ng-model="search">

     <button class="button ion-close-circled input-button button-small"
               ng-click="search = ''" ng-show="search.length">
               Clear search
             </button>

   <input type="checkbox" ng-model="checked" ng-change='stateChanged(checked,$index)'>

{{item.name}}

Tabs:
<ion-tabs class="tabs-icon-top tabs-dark">

    <ion-tab title ="List" icon-on="home" icon-off="home"  href="#/tab/list">
    <ion-nav-view name="list-tab"></ion-nav-view></ion-tab>

    <ion-tab title ="My choices" icon-on="choices" icon-off="choices" href="#/tab/choice">
    <ion-nav-view name="choice-tab"></ion-nav-view></ion-tab>

</ion-tabs>

Answer: When you are trying to send data across multiple views, the easiest way is to store the data in a factory variable.  Whenever you need the data, you can get it from the factory with a simple get.
// This module can be in its own javascript file
angular.module('choicesFactory', [])
.factory('choicesFactory', function() {
    var choicesStored = [];
    return {
        storeChoices: function(choices) {
           choicesStored = choices;
           return;
        },
        getChoices: function() {
           return choicesStored;
        },
    };
});

Now, to implement this bit of code, all you have to do is include the javascript file after your inclusion of angularjs in your index.html and add choicesFactory to your app dependencies.
When you call the function from your controller, you can say:
.controller('choicesController', [
    '$scope',
    '$state',
    'choicesFactory'
    function($scope, $state, choicesFactory) {
        // An example with getting the choices
        var choices = choicesFactory.getChoices()
}]);

If this doesn't quite make sense,  I made a codepen example app that demonstrates all the pieces working together.
Click here to check out the example. :) Happy coding
Comment: And where would this go Alex?
Comment: Hi Alex, ok but what would the HTML look like, to implement this code?
Comment: One thing is Alex, I noticed if I use the search and select say the result it will select the option that is originally presented in the list....
Comment: Ok,  I fixed it.  You will notice that the issue had to do with tying the ng-model to a single checked variable.  Everything should be in working order now.
Comment: Also,  that fix ended up causing another issue when I added a checked key to each of the names.  I had to do some array filtering with a for loop to get something that I could search with indexOf.  I hope NOW everything works.
Comment: Excellent Alex, that fixed it
Comment: Sorry sole, but after double checking the code again, I noticed that there was another small bug that prevented the factory delete from grabbing the correct spot in the choicesStored array.  I should have put the array filtering into the factory.  I mean it... Everything should be working this time.  I promise. :)


Windows 7 unattended deployment - prompt for password, and use it to autologin

Question: I have used System Image Manager to create an unattended XML answer file, which I have written to a Windows 7 DVD. This contains almost all system configuration, but deliberately does not include username or password for the installed system - I want the user to enter these, at the console, during setup.
However, I then run some post-install scripts, some of which reboot the machine and continue after the reboot. This means the user has to log in multiple times during the installation - and since some scripts take a while to run, this is quite inconvenient. Because of this, I'm looking for a way to enable auto-login after the install.
However, all the examples I can find only support using a username/password which is set in the answer file, not supplied by the user. Am I missing something obvious, or can anyone think of any clever workaround for this?
I have tried adding a FirstLogonCommand to the oobeSystem pass, which uses %USERNAME% and %USERPASSWORD% to enable autologin via Sysinternals "Autologon" utility, but found that %USERPASSWORD% was not expanded. Is there a way of finding this information?
The only other workaround I can think of is to run my post-install scripts before any user logs in, probably by creating a service. This would increase complexity though - I'd much rather have them running interactively and visibly in a user session.
(Edit: Perhaps it's relevant to mention that I am not using an AD domain here either).
Answer: I would recommend using MDT (Microsoft Deployment Toolkit) to handle this automatically.
It has a user account page for user defined account(s). It will place the created user(s) into a var(s). You can run a command (from cmd or powershell) using that var. Or if you're really into unattend.xml you can have it integrated into the unattend.xml file when it is generated for the target system.
I personally recommend the command line way because it is easier to keep track of and manage without having to load up the image editor that comes with the WAIK.
Comment: If you need me to build that batch file for you give me a heads up. I would also edit the answer so it contains the same batch file.
Comment: Hm, thanks, but the unattend.xml file doesn't contain the username/password - they are provided by the user during the install. Unless you mean there's another file that the installer writes as it runs?
Comment: Do you know about the unattended.XML auto login section?
Comment: I do - I couldn't get it to auto-login without providing a password, though, and it wouldn't expand %USERNAME% or password fields (I ended up with a login prompt for, literally, "%USERNAME%").
Comment: Ok, then have you heard of MDT, Microsoft Deployment Toolkit (it is free)?
Comment: Oh, I haven't! I've just been using "System Image Manager" to make my unattened.xml. I'll look in to MDT and report back! :)
Comment: MDT contains a user account page which creates users based upon input.  It will put the new user into a var and you can run commands with those vars. E.G. the autologon utility or you can use the system to expand those vars into the unattend.xml (dynamic xml generator which you can predefine stuff even though it generates a new file for every installation.) All in all it is the best way to deploy MS OSs without having to pay for SCCM (it provides almost all of the same functionality).


Using drush to run a local script on a remote site

Question: I frequently use drush scr for little tasks throughout my day.  Sometimes these end up a proper commands in my environment, but more often they are just standalone things.
If I have @foo set up in my drush aliases with remote-host, and try to run a local script, I get
$ drush @foo scr ./foo.php
Unable to find any of the following:                                     [error]
/home/mpd/drush/commands/core/./foo.php, /home/mpd/./foo.php

Can this command run a local script on a remote site?
Comment: Is the script present in your current directory? Does it have the executable flag enabled for your current user (+x)? Are you able to run `drush @foo status` where, @foo is the remote alias? I know these are basic questions...but it's what I thought of first.
Comment: I would think that the script needs to be installed on the remote, since really all you're doing is referencing Drush that is running on the remote server.
Comment: For the sake of this question, yes, remote communication works and the script is on the local machine and being pathed correctly from the commands line.
Comment: @amateurbarista Scripts executed with `drush scr` don't need to be +x unless you want to include the shebang.
Answer: Nope, what you want to do is not supported.  When you run drush @foo scr, it causes Drush to run your scr command on the remote system.  The scr command on the remote system will then look for the script it wants to run on its own filesystem.  In order to make this work, you'll need to somehow get your script on the remote system, and then run it with your remote scr command.
Note that this is different than the drush php-eval command, which takes the php code to run on the commandline.  So, in theory, you could passing your php over on the commandline rather than in a file; however, in practice you may find this to be problematic due to the fact that bash is going to process your text, so you'll have to make sure that everything is properly escaped.  Moving the script to execute to the target machine will be more reliable for any nontrivial script.
Comment: I think what you are looking for is just a combination of drush rsync and drush scr. Maybe a bash alias or a drush alias to run these commands in sequence would be better?  You could in theory build something that used backend invoke with method post to send your file over to the remote system, and have the receiving end write it to a temporary file. I think such a patch would be welcome, if written, but it would be quite a bit more complicated than just making the compound command.
Comment: Is a patch to either php-script or php-eval to handle this situation feasible?  I would be willing to tackle it if it is.  I have close to twenty servers now, so consolidating as much on my local machine is a big benefit for me.
Comment: Look at the implementation of `drush ssh`, which is marked to run `drush @remote ssh` on the local system instead of the remote system.  You would then need to read your script file locally, and call backend invoke directly to run drush ev or drush scr on the remote system.  You might be able to get drush_invoke_process to work; that would be easier, but I don't know that it provides enough control.  Post to the issue queue if you need help with your patch.  Or just go with rsync + remote drush scr.


Hashtable in java is giving me the last stored value, but not the right value

Question: Sorry this is code is kind of long, but I needed to get the right scenario.
Why does this code outputs all 'C''s?
import java.util.Hashtable;

public class Main {
    public static ContainsTheHash containsthehash = new ContainsTheHash();
    public static StoresValues storesvalues = new StoresValues();
    public static GetsValuesAndPrints getsvaluesandprints = new GetsValuesAndPrints();
    public static void main(String[] args) {}

}

class ContainsTheHash {

    Hashtable script_code = new Hashtable();
    public Contains_The_Hash() {};
    public void put(long key, Script_Hash_Type sht){script_code.put(key, sht);}
    public ScriptHashType get(long key){return (Script_Hash_Type)script_code.get(key);}

}

class ScriptHashType {

     String string;
     public ScriptHashType(){}
     public String getstring () {return string;}
     public void setstring(String str){string = str;}

}

 class StoresValues {

     public StoresValues(){
         put();
     }
     public void put(){

          ScriptHashType sht = new ScriptHashType();
          sht.setstring("A");
          Main.contains_the_hash.put(1,sht);
          sht.setstring("B");
          Main.contains_the_hash.put(2,sht);
          sht.setstring("C");
          Main.contains_the_hash.put(3,sht);
     }

}

class GetsValuesAndPrints {

    public GetsValuesAndPrints(){

           //should print "A\n B\n  C\n"
           long temp = 1;
           System.out.println(get(temp));
           temp = 2;
           System.out.println(get(temp));
           temp = 3;
           System.out.println(get(temp));
    };

    public String get(long key){

        return new String(((Script_Hash_Type)Main.contains_the_hash.get(key)).getstring());

   }
}

Comment: This is maybe because your containsthehash object is static, so you only have one instance. So when you setString, this is C.But your code is not really clear
Comment: This code doesn't compile (there is confusion between Script_Hash_Type and ScriptHashType as well as Contains_The_Hash and  ContainsTheHas).  Can you clean up the example first?
Comment: I think LB is right that the problem is you are using only one instance of ContainsTheHash.
Answer: Change :
ScriptHashType sht = new ScriptHashType();
sht.setstring("A");
Main.contains_the_hash.put(1,sht);
sht.setstring("B");
Main.contains_the_hash.put(2,sht);
sht.setstring("C");
Main.contains_the_hash.put(3,sht);

to
ScriptHashType sht = new ScriptHashType();
sht.setstring("A");
Main.contains_the_hash.put(1,sht);
sht = new ScriptHashType();
sht.setstring("B");
Main.contains_the_hash.put(2,sht);
sht = new ScriptHashType();
sht.setstring("C");
Main.contains_the_hash.put(3,sht);

In the first piece of code You're updating the same object each time
Comment: To explain this, collections store references to objects (not copies of them), so you had 3 references to the same object in the hash.
Comment: I agree, that was my first comment. Yet, Is this a good design ? I find the code really weird
Comment: Same thing I was going to reply. Your updating the string value within the same object. YOu end up with a single ScriptHashType instance set to "C" instead of 3 instances set to "A", "B", and "C".
Comment: lol, the code is actually a skeleton of a much more complicated program. so that might explain why its wierd.
Answer: class StoresValues {

     public StoresValues() {
         put();
     };

     public void put() {
          ScriptHashType sht = new ScriptHashType();
          sht.setstring("A");
          Main.contains_the_hash.put(1,sht);
          sht.setstring("B");
          Main.contains_the_hash.put(2,sht);
          sht.setstring("C");
          Main.contains_the_hash.put(3,sht);
     }

You build only one single object, sht, using the new operator. You add that object 3 times. The last setstring on that object sets the string to "C". As there is only 1 object sht that single object will have the value "C".
What you should have done is something like:
 public void put() {
  ScriptHashType sht = new ScriptHashType();
  sht.setstring("A");
  Main.contains_the_hash.put(1,sht);
  sht = new ScriptHashType();
  sht.setstring("B");
  Main.contains_the_hash.put(2,sht);
  sht = new ScriptHashType();
  sht.setstring("C");
  Main.contains_the_hash.put(3,sht);
 }

Answer: You are only ever storing one instance of ScriptHashType into the Hashtable and then manipulating its value. To get the behavior you are expecting you would need to create three instances of ScriptHashType, one for each desired value.
Comment: Thank you very much, everyone's comments have been sooo helpful, and responded so fast too.

I did not realize that I had to have multiple instances of scripthashtype. I was using the hashtable improperly.

Again thanks


Executing a PHP file from a .GZ archive?

Question: With PHP, Is it possible to extract to memory another PHP file from a .GZ, execute it and delete it from memory?
Suppose to have into the public html directory:
index.php and site.gz
Inside it, there are:
page.php
article.php
news.php

When I give index.php?p=page1
it extract page.php from the .gz file and put it into the memory (not on the Disk) , execute it, so that the user can have the generated content displayed, and then "destroyed" once have finished to be executed?
Comment: Is it really just a gzipped file? Or a compressed tarball? How was it created?
Comment: Just a gzipped file. My goal is to have everything packed in only one file, to be able to optimize portability
Answer: If it's really a single gzip -c compressed file, then you can use stream wrappers to unpack and load a PHP script right away:
 include "compress.zlib://example.php.gz";

Otherwise Phars are a more convenient alternative for distribution than e.g. plain zip/tar archives.

Take note that you shouldn't use unvetted user input $_GET["p"] for including local files. (If that's what you're trying to do.)
Comment: yes but I need to use $_GET["p"] . Is there a way? and: I have not clue how to extract a file and use it at the fly, without saving it to the HD, execute it etc.