问:
not able to connect mysql built with dockerfile using MySQLWorkbench
dockerfile is:

```<code>  FROM mysql

ENV MYSQL_DATABASE=xxx
ENV MYSQL_ROOT_PASSWORD=password
ENV MYSQL_ROOT_HOST=172.17.0.1

EXPOSE 3306
</code>```

I create an image and it is executed and the output in the console is:

```<code>Initializing database
2017-06-04T21:45:27.614648Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2017-06-04T21:45:28.165234Z 0 [Warning] InnoDB: New log files created, LSN=45790
2017-06-04T21:45:28.239707Z 0 [Warning] InnoDB: Creating foreign key constraint system tables.
2017-06-04T21:45:28.268303Z 0 [Warning] No existing UUID has been found, so we assume that this is the first time that this server has been started. Generating a new UUID: 1fda3bc6-496f-11e7-b3b9-0242ac110002.
2017-06-04T21:45:28.277209Z 0 [Warning] Gtid table is not ready to be used. Table 'mysql.gtid_executed' cannot be opened.
2017-06-04T21:45:28.278001Z 1 [Warning] root@localhost is created with an empty password ! Please consider switching off the --initialize-insecure option.
2017-06-04T21:45:30.879290Z 1 [Warning] 'user' entry 'root@localhost' ignored in --skip-name-resolve mode.
2017-06-04T21:45:30.879349Z 1 [Warning] 'user' entry 'mysql.sys@localhost' ignored in --skip-name-resolve mode.
2017-06-04T21:45:30.879370Z 1 [Warning] 'db' entry 'sys mysql.sys@localhost' ignored in --skip-name-resolve mode.
2017-06-04T21:45:30.879385Z 1 [Warning] 'proxies_priv' entry '@ root@localhost' ignored in --skip-name-resolve mode.
2017-06-04T21:45:30.879548Z 1 [Warning] 'tables_priv' entry 'sys_config mysql.sys@localhost' ignored in --skip-name-resolve mode.
Database initialized
Initializing certificates
Generating a 2048 bit RSA private key
......+++
........................................................+++
unable to write 'random state'
writing new private key to 'ca-key.pem'
-----
Generating a 2048 bit RSA private key
...+++
.................................+++
unable to write 'random state'
writing new private key to 'server-key.pem'
-----
Generating a 2048 bit RSA private key
....................+++
..................+++
unable to write 'random state'
writing new private key to 'client-key.pem'
-----
Certificates initialized
MySQL init process in progress...
2017-06-04T21:45:34.509988Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2017-06-04T21:45:34.510828Z 0 [Note] mysqld (mysqld 5.7.18) starting as process 88 ...
2017-06-04T21:45:34.513894Z 0 [Note] InnoDB: PUNCH HOLE support available
2017-06-04T21:45:34.513959Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2017-06-04T21:45:34.513962Z 0 [Note] InnoDB: Uses event mutexes
2017-06-04T21:45:34.513964Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier
2017-06-04T21:45:34.513966Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.3
2017-06-04T21:45:34.513968Z 0 [Note] InnoDB: Using Linux native AIO
2017-06-04T21:45:34.514876Z 0 [Note] InnoDB: Number of pools: 1
2017-06-04T21:45:34.515104Z 0 [Note] InnoDB: Using CPU crc32 instructions
2017-06-04T21:45:34.517544Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M
2017-06-04T21:45:34.525700Z 0 [Note] InnoDB: Completed initialization of buffer pool
2017-06-04T21:45:34.528014Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().
2017-06-04T21:45:34.539849Z 0 [Note] InnoDB: Highest supported file format is Barracuda.
2017-06-04T21:45:34.562076Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables
2017-06-04T21:45:34.562134Z 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
2017-06-04T21:45:34.678858Z 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
2017-06-04T21:45:34.680707Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active.
2017-06-04T21:45:34.680766Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active.
2017-06-04T21:45:34.682159Z 0 [Note] InnoDB: 5.7.18 started; log sequence number 2535558
2017-06-04T21:45:34.682671Z 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
2017-06-04T21:45:34.683101Z 0 [Note] Plugin 'FEDERATED' is disabled.
2017-06-04T21:45:34.685166Z 0 [Note] InnoDB: Buffer pool(s) load completed at 170604 21:45:34
2017-06-04T21:45:34.696752Z 0 [Note] Found ca.pem, server-cert.pem and server-key.pem in data directory. Trying to enable SSL support using them.
2017-06-04T21:45:34.697436Z 0 [Warning] CA certificate ca.pem is self signed.
2017-06-04T21:45:34.711955Z 0 [Warning] 'user' entry 'root@localhost' ignored in --skip-name-resolve mode.
2017-06-04T21:45:34.712006Z 0 [Warning] 'user' entry 'mysql.sys@localhost' ignored in --skip-name-resolve mode.
2017-06-04T21:45:34.712021Z 0 [Warning] 'db' entry 'sys mysql.sys@localhost' ignored in --skip-name-resolve mode.
2017-06-04T21:45:34.712029Z 0 [Warning] 'proxies_priv' entry '@ root@localhost' ignored in --skip-name-resolve mode.
2017-06-04T21:45:34.713467Z 0 [Warning] 'tables_priv' entry 'sys_config mysql.sys@localhost' ignored in --skip-name-resolve mode.
2017-06-04T21:45:34.718411Z 0 [Note] Event Scheduler: Loaded 0 events
2017-06-04T21:45:34.718587Z 0 [Note] mysqld: ready for connections.
Version: '5.7.18'  socket: '/var/run/mysqld/mysqld.sock'  port: 0  MySQL Community Server (GPL)
2017-06-04T21:45:34.718607Z 0 [Note] Executing 'SELECT * FROM INFORMATION_SCHEMA.TABLES;' to get a list of tables using the deprecated partition engine. You may use the startup option '--disable-partition-engine-check' to skip this check.
2017-06-04T21:45:34.718614Z 0 [Note] Beginning of list of non-natively partitioned tables
2017-06-04T21:45:34.728015Z 0 [Note] End of list of non-natively partitioned tables
Warning: Unable to load '/usr/share/zoneinfo/iso3166.tab' as time zone. Skipping it.
Warning: Unable to load '/usr/share/zoneinfo/leap-seconds.list' as time zone. Skipping it.
Warning: Unable to load '/usr/share/zoneinfo/zone.tab' as time zone. Skipping it.
2017-06-04T21:45:37.697877Z 5 [Warning] 'user' entry 'root@localhost' ignored in --skip-name-resolve mode.
2017-06-04T21:45:37.697939Z 5 [Warning] 'user' entry 'mysql.sys@localhost' ignored in --skip-name-resolve mode.
2017-06-04T21:45:37.698177Z 5 [Warning] 'db' entry 'sys mysql.sys@localhost' ignored in --skip-name-resolve mode.
2017-06-04T21:45:37.698388Z 5 [Warning] 'proxies_priv' entry '@ root@localhost' ignored in --skip-name-resolve mode.
2017-06-04T21:45:37.698537Z 5 [Warning] 'tables_priv' entry 'sys_config mysql.sys@localhost' ignored in --skip-name-resolve mode.
mysql: [Warning] Using a password on the command line interface can be insecure.

2017-06-04T21:45:37.705631Z 0 [Note] Giving 0 client threads a chance to die gracefully
2017-06-04T21:45:37.705651Z 0 [Note] Shutting down slave threads
2017-06-04T21:45:37.705674Z 0 [Note] Forcefully disconnecting 0 remaining clients
2017-06-04T21:45:37.705677Z 0 [Note] Event Scheduler: Purging the queue. 0 events
2017-06-04T21:45:37.705714Z 0 [Note] Binlog end
2017-06-04T21:45:37.706515Z 0 [Note] Shutting down plugin 'ngram'
2017-06-04T21:45:37.706553Z 0 [Note] Shutting down plugin 'BLACKHOLE'
2017-06-04T21:45:37.706560Z 0 [Note] Shutting down plugin 'partition'
2017-06-04T21:45:37.706565Z 0 [Note] Shutting down plugin 'ARCHIVE'
2017-06-04T21:45:37.706700Z 0 [Note] Shutting down plugin 'INNODB_SYS_VIRTUAL'
2017-06-04T21:45:37.706733Z 0 [Note] Shutting down plugin 'INNODB_SYS_DATAFILES'
2017-06-04T21:45:37.706755Z 0 [Note] Shutting down plugin 'INNODB_SYS_TABLESPACES'
2017-06-04T21:45:37.706781Z 0 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN_COLS'
2017-06-04T21:45:37.706942Z 0 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN'
2017-06-04T21:45:37.706974Z 0 [Note] Shutting down plugin 'INNODB_SYS_FIELDS'
2017-06-04T21:45:37.706979Z 0 [Note] Shutting down plugin 'INNODB_SYS_COLUMNS'
2017-06-04T21:45:37.707008Z 0 [Note] Shutting down plugin 'INNODB_SYS_INDEXES'
2017-06-04T21:45:37.707013Z 0 [Note] Shutting down plugin 'INNODB_SYS_TABLESTATS'
2017-06-04T21:45:37.707018Z 0 [Note] Shutting down plugin 'INNODB_SYS_TABLES'
2017-06-04T21:45:37.707040Z 0 [Note] Shutting down plugin 'INNODB_FT_INDEX_TABLE'
2017-06-04T21:45:37.707182Z 0 [Note] Shutting down plugin 'INNODB_FT_INDEX_CACHE'
2017-06-04T21:45:37.707212Z 0 [Note] Shutting down plugin 'INNODB_FT_CONFIG'
2017-06-04T21:45:37.707218Z 0 [Note] Shutting down plugin 'INNODB_FT_BEING_DELETED'
2017-06-04T21:45:37.707223Z 0 [Note] Shutting down plugin 'INNODB_FT_DELETED'
2017-06-04T21:45:37.707228Z 0 [Note] Shutting down plugin 'INNODB_FT_DEFAULT_STOPWORD'
2017-06-04T21:45:37.707407Z 0 [Note] Shutting down plugin 'INNODB_METRICS'
2017-06-04T21:45:37.707429Z 0 [Note] Shutting down plugin 'INNODB_TEMP_TABLE_INFO'
2017-06-04T21:45:37.707434Z 0 [Note] Shutting down plugin 'INNODB_BUFFER_POOL_STATS'
2017-06-04T21:45:37.707456Z 0 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE_LRU'
2017-06-04T21:45:37.707607Z 0 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE'
2017-06-04T21:45:37.707636Z 0 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX_RESET'
2017-06-04T21:45:37.707658Z 0 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX'
2017-06-04T21:45:37.707663Z 0 [Note] Shutting down plugin 'INNODB_CMPMEM_RESET'
2017-06-04T21:45:37.707684Z 0 [Note] Shutting down plugin 'INNODB_CMPMEM'
2017-06-04T21:45:37.707820Z 0 [Note] Shutting down plugin 'INNODB_CMP_RESET'
2017-06-04T21:45:37.707850Z 0 [Note] Shutting down plugin 'INNODB_CMP'
2017-06-04T21:45:37.707856Z 0 [Note] Shutting down plugin 'INNODB_LOCK_WAITS'
2017-06-04T21:45:37.707877Z 0 [Note] Shutting down plugin 'INNODB_LOCKS'
2017-06-04T21:45:37.707992Z 0 [Note] Shutting down plugin 'INNODB_TRX'
2017-06-04T21:45:37.708006Z 0 [Note] Shutting down plugin 'InnoDB'
2017-06-04T21:45:37.708201Z 0 [Note] InnoDB: FTS optimize thread exiting.
2017-06-04T21:45:37.708420Z 0 [Note] InnoDB: Starting shutdown...
2017-06-04T21:45:37.809135Z 0 [Note] InnoDB: Dumping buffer pool(s) to /var/lib/mysql/ib_buffer_pool
2017-06-04T21:45:37.810270Z 0 [Note] InnoDB: Buffer pool(s) dump completed at 170604 21:45:37
2017-06-04T21:45:40.157631Z 0 [Note] InnoDB: Shutdown completed; log sequence number 12139694
2017-06-04T21:45:40.166913Z 0 [Note] InnoDB: Removed temporary tablespace data file: "ibtmp1"
2017-06-04T21:45:40.167059Z 0 [Note] Shutting down plugin 'MRG_MYISAM'
2017-06-04T21:45:40.167298Z 0 [Note] Shutting down plugin 'MyISAM'
2017-06-04T21:45:40.167390Z 0 [Note] Shutting down plugin 'CSV'
2017-06-04T21:45:40.167503Z 0 [Note] Shutting down plugin 'MEMORY'
2017-06-04T21:45:40.167541Z 0 [Note] Shutting down plugin 'PERFORMANCE_SCHEMA'
2017-06-04T21:45:40.167599Z 0 [Note] Shutting down plugin 'sha256_password'
2017-06-04T21:45:40.167717Z 0 [Note] Shutting down plugin 'mysql_native_password'
2017-06-04T21:45:40.168032Z 0 [Note] Shutting down plugin 'binlog'
2017-06-04T21:45:40.171056Z 0 [Note] mysqld: Shutdown complete

MySQL init process done. Ready for start up.

2017-06-04T21:45:40.451048Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2017-06-04T21:45:40.451891Z 0 [Note] mysqld (mysqld 5.7.18) starting as process 1 ...
2017-06-04T21:45:40.457755Z 0 [Note] InnoDB: PUNCH HOLE support available
2017-06-04T21:45:40.457782Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2017-06-04T21:45:40.457786Z 0 [Note] InnoDB: Uses event mutexes
2017-06-04T21:45:40.457788Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier
2017-06-04T21:45:40.457790Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.3
2017-06-04T21:45:40.457795Z 0 [Note] InnoDB: Using Linux native AIO
2017-06-04T21:45:40.458346Z 0 [Note] InnoDB: Number of pools: 1
2017-06-04T21:45:40.458615Z 0 [Note] InnoDB: Using CPU crc32 instructions
2017-06-04T21:45:40.460659Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M
2017-06-04T21:45:40.469391Z 0 [Note] InnoDB: Completed initialization of buffer pool
2017-06-04T21:45:40.471616Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().
2017-06-04T21:45:40.483436Z 0 [Note] InnoDB: Highest supported file format is Barracuda.
2017-06-04T21:45:40.498521Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables
2017-06-04T21:45:40.498599Z 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
2017-06-04T21:45:40.577051Z 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
2017-06-04T21:45:40.578116Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active.
2017-06-04T21:45:40.578141Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active.
2017-06-04T21:45:40.578560Z 0 [Note] InnoDB: Waiting for purge to start
2017-06-04T21:45:40.628859Z 0 [Note] InnoDB: 5.7.18 started; log sequence number 12139694
2017-06-04T21:45:40.629153Z 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
2017-06-04T21:45:40.629256Z 0 [Note] Plugin 'FEDERATED' is disabled.
2017-06-04T21:45:40.633930Z 0 [Note] InnoDB: Buffer pool(s) load completed at 170604 21:45:40
2017-06-04T21:45:40.634507Z 0 [Note] Found ca.pem, server-cert.pem and server-key.pem in data directory. Trying to enable SSL support using them.
2017-06-04T21:45:40.634772Z 0 [Warning] CA certificate ca.pem is self signed.
2017-06-04T21:45:40.636787Z 0 [Note] Server hostname (bind-address): '*'; port: 3306
2017-06-04T21:45:40.636867Z 0 [Note] IPv6 is available.
2017-06-04T21:45:40.636871Z 0 [Note]   - '::' resolves to '::';
2017-06-04T21:45:40.636948Z 0 [Note] Server socket created on IP: '::'.
2017-06-04T21:45:40.647855Z 0 [Warning] 'user' entry 'root@localhost' ignored in --skip-name-resolve mode.
2017-06-04T21:45:40.647964Z 0 [Warning] 'user' entry 'mysql.sys@localhost' ignored in --skip-name-resolve mode.
2017-06-04T21:45:40.648018Z 0 [Warning] 'db' entry 'sys mysql.sys@localhost' ignored in --skip-name-resolve mode.
2017-06-04T21:45:40.648026Z 0 [Warning] 'proxies_priv' entry '@ root@localhost' ignored in --skip-name-resolve mode.
2017-06-04T21:45:40.651259Z 0 [Warning] 'tables_priv' entry 'sys_config mysql.sys@localhost' ignored in --skip-name-resolve mode.
2017-06-04T21:45:40.655887Z 0 [Note] Event Scheduler: Loaded 0 events
2017-06-04T21:45:40.656165Z 0 [Note] mysqld: ready for connections.
Version: '5.7.18'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server (GPL)
2017-06-04T21:45:40.656176Z 0 [Note] Executing 'SELECT * FROM INFORMATION_SCHEMA.TABLES;' to get a list of tables using the deprecated partition engine. You may use the startup option '--disable-partition-engine-check' to skip this check.
2017-06-04T21:45:40.656178Z 0 [Note] Beginning of list of non-natively partitioned tables
2017-06-04T21:45:40.664203Z 0 [Note] End of list of non-natively partitioned tables
2017-06-04T21:48:18.537406Z 3 [Note] Access denied for user 'root'@'localhost' (using password: NO)
</code>```

I tried to connect to DB using root user and diff host as localhost,{ContainerID}, 0.0.0.0, 8.8.8.8, 172.17.0.1, 172.17.0.2 and no luck.
Could anyone help me out why I can't connect to the DB, please?

everything is running locally. so Mysql Db is running in a container and MySQLWorkbench tool is intalled in my laptop and when I setup MySQLWorkbench to connect to Mysql within container I am getting an error message:
You connection attempt to failed for user root from your host to server at 172.17.0.1:3306.
Can't connect to MySQL server on 172.17.0.1 (10060)
Thx in advance

答: you need to add a -p 3306:3306 parameter to your docker run command. this will map the port to locahost:3306

Body:
dockerfile is:

  FROM mysql

ENV MYSQL_DATABASE=xxx
ENV MYSQL_ROOT_PASSWORD=password
ENV MYSQL_ROOT_HOST=172.17.0.1

EXPOSE 3306

I create an image and it is executed and the output in the console is:

Initializing database
2017-06-04T21:45:27.614648Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2017-06-04T21:45:28.165234Z 0 [Warning] InnoDB: New log files created, LSN=45790
2017-06-04T21:45:28.239707Z 0 [Warning] InnoDB: Creating foreign key constraint system tables.
2017-06-04T21:45:28.268303Z 0 [Warning] No existing UUID has been found, so we assume that this is the first time that this server has been started. Generating a new UUID: 1fda3bc6-496f-11e7-b3b9-0242ac110002.
2017-06-04T21:45:28.277209Z 0 [Warning] Gtid table is not ready to be used. Table 'mysql.gtid_executed' cannot be opened.
2017-06-04T21:45:28.278001Z 1 [Warning] root@localhost is created with an empty password ! Please consider switching off the --initialize-insecure option.
2017-06-04T21:45:30.879290Z 1 [Warning] 'user' entry 'root@localhost' ignored in --skip-name-resolve mode.
2017-06-04T21:45:30.879349Z 1 [Warning] 'user' entry 'mysql.sys@localhost' ignored in --skip-name-resolve mode.
2017-06-04T21:45:30.879370Z 1 [Warning] 'db' entry 'sys mysql.sys@localhost' ignored in --skip-name-resolve mode.
2017-06-04T21:45:30.879385Z 1 [Warning] 'proxies_priv' entry '@ root@localhost' ignored in --skip-name-resolve mode.
2017-06-04T21:45:30.879548Z 1 [Warning] 'tables_priv' entry 'sys_config mysql.sys@localhost' ignored in --skip-name-resolve mode.
Database initialized
Initializing certificates
Generating a 2048 bit RSA private key
......+++
........................................................+++
unable to write 'random state'
writing new private key to 'ca-key.pem'
-----
Generating a 2048 bit RSA private key
...+++
.................................+++
unable to write 'random state'
writing new private key to 'server-key.pem'
-----
Generating a 2048 bit RSA private key
....................+++
..................+++
unable to write 'random state'
writing new private key to 'client-key.pem'
-----
Certificates initialized
MySQL init process in progress...
2017-06-04T21:45:34.509988Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2017-06-04T21:45:34.510828Z 0 [Note] mysqld (mysqld 5.7.18) starting as process 88 ...
2017-06-04T21:45:34.513894Z 0 [Note] InnoDB: PUNCH HOLE support available
2017-06-04T21:45:34.513959Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2017-06-04T21:45:34.513962Z 0 [Note] InnoDB: Uses event mutexes
2017-06-04T21:45:34.513964Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier
2017-06-04T21:45:34.513966Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.3
2017-06-04T21:45:34.513968Z 0 [Note] InnoDB: Using Linux native AIO
2017-06-04T21:45:34.514876Z 0 [Note] InnoDB: Number of pools: 1
2017-06-04T21:45:34.515104Z 0 [Note] InnoDB: Using CPU crc32 instructions
2017-06-04T21:45:34.517544Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M
2017-06-04T21:45:34.525700Z 0 [Note] InnoDB: Completed initialization of buffer pool
2017-06-04T21:45:34.528014Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().
2017-06-04T21:45:34.539849Z 0 [Note] InnoDB: Highest supported file format is Barracuda.
2017-06-04T21:45:34.562076Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables
2017-06-04T21:45:34.562134Z 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
2017-06-04T21:45:34.678858Z 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
2017-06-04T21:45:34.680707Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active.
2017-06-04T21:45:34.680766Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active.
2017-06-04T21:45:34.682159Z 0 [Note] InnoDB: 5.7.18 started; log sequence number 2535558
2017-06-04T21:45:34.682671Z 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
2017-06-04T21:45:34.683101Z 0 [Note] Plugin 'FEDERATED' is disabled.
2017-06-04T21:45:34.685166Z 0 [Note] InnoDB: Buffer pool(s) load completed at 170604 21:45:34
2017-06-04T21:45:34.696752Z 0 [Note] Found ca.pem, server-cert.pem and server-key.pem in data directory. Trying to enable SSL support using them.
2017-06-04T21:45:34.697436Z 0 [Warning] CA certificate ca.pem is self signed.
2017-06-04T21:45:34.711955Z 0 [Warning] 'user' entry 'root@localhost' ignored in --skip-name-resolve mode.
2017-06-04T21:45:34.712006Z 0 [Warning] 'user' entry 'mysql.sys@localhost' ignored in --skip-name-resolve mode.
2017-06-04T21:45:34.712021Z 0 [Warning] 'db' entry 'sys mysql.sys@localhost' ignored in --skip-name-resolve mode.
2017-06-04T21:45:34.712029Z 0 [Warning] 'proxies_priv' entry '@ root@localhost' ignored in --skip-name-resolve mode.
2017-06-04T21:45:34.713467Z 0 [Warning] 'tables_priv' entry 'sys_config mysql.sys@localhost' ignored in --skip-name-resolve mode.
2017-06-04T21:45:34.718411Z 0 [Note] Event Scheduler: Loaded 0 events
2017-06-04T21:45:34.718587Z 0 [Note] mysqld: ready for connections.
Version: '5.7.18'  socket: '/var/run/mysqld/mysqld.sock'  port: 0  MySQL Community Server (GPL)
2017-06-04T21:45:34.718607Z 0 [Note] Executing 'SELECT * FROM INFORMATION_SCHEMA.TABLES;' to get a list of tables using the deprecated partition engine. You may use the startup option '--disable-partition-engine-check' to skip this check.
2017-06-04T21:45:34.718614Z 0 [Note] Beginning of list of non-natively partitioned tables
2017-06-04T21:45:34.728015Z 0 [Note] End of list of non-natively partitioned tables
Warning: Unable to load '/usr/share/zoneinfo/iso3166.tab' as time zone. Skipping it.
Warning: Unable to load '/usr/share/zoneinfo/leap-seconds.list' as time zone. Skipping it.
Warning: Unable to load '/usr/share/zoneinfo/zone.tab' as time zone. Skipping it.
2017-06-04T21:45:37.697877Z 5 [Warning] 'user' entry 'root@localhost' ignored in --skip-name-resolve mode.
2017-06-04T21:45:37.697939Z 5 [Warning] 'user' entry 'mysql.sys@localhost' ignored in --skip-name-resolve mode.
2017-06-04T21:45:37.698177Z 5 [Warning] 'db' entry 'sys mysql.sys@localhost' ignored in --skip-name-resolve mode.
2017-06-04T21:45:37.698388Z 5 [Warning] 'proxies_priv' entry '@ root@localhost' ignored in --skip-name-resolve mode.
2017-06-04T21:45:37.698537Z 5 [Warning] 'tables_priv' entry 'sys_config mysql.sys@localhost' ignored in --skip-name-resolve mode.
mysql: [Warning] Using a password on the command line interface can be insecure.

2017-06-04T21:45:37.705631Z 0 [Note] Giving 0 client threads a chance to die gracefully
2017-06-04T21:45:37.705651Z 0 [Note] Shutting down slave threads
2017-06-04T21:45:37.705674Z 0 [Note] Forcefully disconnecting 0 remaining clients
2017-06-04T21:45:37.705677Z 0 [Note] Event Scheduler: Purging the queue. 0 events
2017-06-04T21:45:37.705714Z 0 [Note] Binlog end
2017-06-04T21:45:37.706515Z 0 [Note] Shutting down plugin 'ngram'
2017-06-04T21:45:37.706553Z 0 [Note] Shutting down plugin 'BLACKHOLE'
2017-06-04T21:45:37.706560Z 0 [Note] Shutting down plugin 'partition'
2017-06-04T21:45:37.706565Z 0 [Note] Shutting down plugin 'ARCHIVE'
2017-06-04T21:45:37.706700Z 0 [Note] Shutting down plugin 'INNODB_SYS_VIRTUAL'
2017-06-04T21:45:37.706733Z 0 [Note] Shutting down plugin 'INNODB_SYS_DATAFILES'
2017-06-04T21:45:37.706755Z 0 [Note] Shutting down plugin 'INNODB_SYS_TABLESPACES'
2017-06-04T21:45:37.706781Z 0 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN_COLS'
2017-06-04T21:45:37.706942Z 0 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN'
2017-06-04T21:45:37.706974Z 0 [Note] Shutting down plugin 'INNODB_SYS_FIELDS'
2017-06-04T21:45:37.706979Z 0 [Note] Shutting down plugin 'INNODB_SYS_COLUMNS'
2017-06-04T21:45:37.707008Z 0 [Note] Shutting down plugin 'INNODB_SYS_INDEXES'
2017-06-04T21:45:37.707013Z 0 [Note] Shutting down plugin 'INNODB_SYS_TABLESTATS'
2017-06-04T21:45:37.707018Z 0 [Note] Shutting down plugin 'INNODB_SYS_TABLES'
2017-06-04T21:45:37.707040Z 0 [Note] Shutting down plugin 'INNODB_FT_INDEX_TABLE'
2017-06-04T21:45:37.707182Z 0 [Note] Shutting down plugin 'INNODB_FT_INDEX_CACHE'
2017-06-04T21:45:37.707212Z 0 [Note] Shutting down plugin 'INNODB_FT_CONFIG'
2017-06-04T21:45:37.707218Z 0 [Note] Shutting down plugin 'INNODB_FT_BEING_DELETED'
2017-06-04T21:45:37.707223Z 0 [Note] Shutting down plugin 'INNODB_FT_DELETED'
2017-06-04T21:45:37.707228Z 0 [Note] Shutting down plugin 'INNODB_FT_DEFAULT_STOPWORD'
2017-06-04T21:45:37.707407Z 0 [Note] Shutting down plugin 'INNODB_METRICS'
2017-06-04T21:45:37.707429Z 0 [Note] Shutting down plugin 'INNODB_TEMP_TABLE_INFO'
2017-06-04T21:45:37.707434Z 0 [Note] Shutting down plugin 'INNODB_BUFFER_POOL_STATS'
2017-06-04T21:45:37.707456Z 0 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE_LRU'
2017-06-04T21:45:37.707607Z 0 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE'
2017-06-04T21:45:37.707636Z 0 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX_RESET'
2017-06-04T21:45:37.707658Z 0 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX'
2017-06-04T21:45:37.707663Z 0 [Note] Shutting down plugin 'INNODB_CMPMEM_RESET'
2017-06-04T21:45:37.707684Z 0 [Note] Shutting down plugin 'INNODB_CMPMEM'
2017-06-04T21:45:37.707820Z 0 [Note] Shutting down plugin 'INNODB_CMP_RESET'
2017-06-04T21:45:37.707850Z 0 [Note] Shutting down plugin 'INNODB_CMP'
2017-06-04T21:45:37.707856Z 0 [Note] Shutting down plugin 'INNODB_LOCK_WAITS'
2017-06-04T21:45:37.707877Z 0 [Note] Shutting down plugin 'INNODB_LOCKS'
2017-06-04T21:45:37.707992Z 0 [Note] Shutting down plugin 'INNODB_TRX'
2017-06-04T21:45:37.708006Z 0 [Note] Shutting down plugin 'InnoDB'
2017-06-04T21:45:37.708201Z 0 [Note] InnoDB: FTS optimize thread exiting.
2017-06-04T21:45:37.708420Z 0 [Note] InnoDB: Starting shutdown...
2017-06-04T21:45:37.809135Z 0 [Note] InnoDB: Dumping buffer pool(s) to /var/lib/mysql/ib_buffer_pool
2017-06-04T21:45:37.810270Z 0 [Note] InnoDB: Buffer pool(s) dump completed at 170604 21:45:37
2017-06-04T21:45:40.157631Z 0 [Note] InnoDB: Shutdown completed; log sequence number 12139694
2017-06-04T21:45:40.166913Z 0 [Note] InnoDB: Removed temporary tablespace data file: "ibtmp1"
2017-06-04T21:45:40.167059Z 0 [Note] Shutting down plugin 'MRG_MYISAM'
2017-06-04T21:45:40.167298Z 0 [Note] Shutting down plugin 'MyISAM'
2017-06-04T21:45:40.167390Z 0 [Note] Shutting down plugin 'CSV'
2017-06-04T21:45:40.167503Z 0 [Note] Shutting down plugin 'MEMORY'
2017-06-04T21:45:40.167541Z 0 [Note] Shutting down plugin 'PERFORMANCE_SCHEMA'
2017-06-04T21:45:40.167599Z 0 [Note] Shutting down plugin 'sha256_password'
2017-06-04T21:45:40.167717Z 0 [Note] Shutting down plugin 'mysql_native_password'
2017-06-04T21:45:40.168032Z 0 [Note] Shutting down plugin 'binlog'
2017-06-04T21:45:40.171056Z 0 [Note] mysqld: Shutdown complete

MySQL init process done. Ready for start up.

2017-06-04T21:45:40.451048Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2017-06-04T21:45:40.451891Z 0 [Note] mysqld (mysqld 5.7.18) starting as process 1 ...
2017-06-04T21:45:40.457755Z 0 [Note] InnoDB: PUNCH HOLE support available
2017-06-04T21:45:40.457782Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2017-06-04T21:45:40.457786Z 0 [Note] InnoDB: Uses event mutexes
2017-06-04T21:45:40.457788Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier
2017-06-04T21:45:40.457790Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.3
2017-06-04T21:45:40.457795Z 0 [Note] InnoDB: Using Linux native AIO
2017-06-04T21:45:40.458346Z 0 [Note] InnoDB: Number of pools: 1
2017-06-04T21:45:40.458615Z 0 [Note] InnoDB: Using CPU crc32 instructions
2017-06-04T21:45:40.460659Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M
2017-06-04T21:45:40.469391Z 0 [Note] InnoDB: Completed initialization of buffer pool
2017-06-04T21:45:40.471616Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().
2017-06-04T21:45:40.483436Z 0 [Note] InnoDB: Highest supported file format is Barracuda.
2017-06-04T21:45:40.498521Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables
2017-06-04T21:45:40.498599Z 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
2017-06-04T21:45:40.577051Z 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
2017-06-04T21:45:40.578116Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active.
2017-06-04T21:45:40.578141Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active.
2017-06-04T21:45:40.578560Z 0 [Note] InnoDB: Waiting for purge to start
2017-06-04T21:45:40.628859Z 0 [Note] InnoDB: 5.7.18 started; log sequence number 12139694
2017-06-04T21:45:40.629153Z 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
2017-06-04T21:45:40.629256Z 0 [Note] Plugin 'FEDERATED' is disabled.
2017-06-04T21:45:40.633930Z 0 [Note] InnoDB: Buffer pool(s) load completed at 170604 21:45:40
2017-06-04T21:45:40.634507Z 0 [Note] Found ca.pem, server-cert.pem and server-key.pem in data directory. Trying to enable SSL support using them.
2017-06-04T21:45:40.634772Z 0 [Warning] CA certificate ca.pem is self signed.
2017-06-04T21:45:40.636787Z 0 [Note] Server hostname (bind-address): '*'; port: 3306
2017-06-04T21:45:40.636867Z 0 [Note] IPv6 is available.
2017-06-04T21:45:40.636871Z 0 [Note]   - '::' resolves to '::';
2017-06-04T21:45:40.636948Z 0 [Note] Server socket created on IP: '::'.
2017-06-04T21:45:40.647855Z 0 [Warning] 'user' entry 'root@localhost' ignored in --skip-name-resolve mode.
2017-06-04T21:45:40.647964Z 0 [Warning] 'user' entry 'mysql.sys@localhost' ignored in --skip-name-resolve mode.
2017-06-04T21:45:40.648018Z 0 [Warning] 'db' entry 'sys mysql.sys@localhost' ignored in --skip-name-resolve mode.
2017-06-04T21:45:40.648026Z 0 [Warning] 'proxies_priv' entry '@ root@localhost' ignored in --skip-name-resolve mode.
2017-06-04T21:45:40.651259Z 0 [Warning] 'tables_priv' entry 'sys_config mysql.sys@localhost' ignored in --skip-name-resolve mode.
2017-06-04T21:45:40.655887Z 0 [Note] Event Scheduler: Loaded 0 events
2017-06-04T21:45:40.656165Z 0 [Note] mysqld: ready for connections.
Version: '5.7.18'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server (GPL)
2017-06-04T21:45:40.656176Z 0 [Note] Executing 'SELECT * FROM INFORMATION_SCHEMA.TABLES;' to get a list of tables using the deprecated partition engine. You may use the startup option '--disable-partition-engine-check' to skip this check.
2017-06-04T21:45:40.656178Z 0 [Note] Beginning of list of non-natively partitioned tables
2017-06-04T21:45:40.664203Z 0 [Note] End of list of non-natively partitioned tables
2017-06-04T21:48:18.537406Z 3 [Note] Access denied for user 'root'@'localhost' (using password: NO)

I tried to connect to DB using root user and diff host as localhost,{ContainerID}, 0.0.0.0, 8.8.8.8, 172.17.0.1, 172.17.0.2 and no luck.
Could anyone help me out why I can't connect to the DB, please?

everything is running locally. so Mysql Db is running in a container and MySQLWorkbench tool is intalled in my laptop and when I setup MySQLWorkbench to connect to Mysql within container I am getting an error message:
You connection attempt to failed for user root from your host to server at 172.17.0.1:3306.
Can't connect to MySQL server on 172.17.0.1 (10060)
Thx in advance


来源: stackexchange

问:
Swift CollectionView Vertical Paging
I enabled paging on my collectionview and encountered the first issue of each swipe not stopping on a different cell, but page.

I then tried to enter code and handle the paging manually in ScrollViewWillEndDecelerating.
However my problem is the changing the collectionviews ContentOffset or scrolling to a Point both do not work unless called in LayoutSubiews. that is the only place where they effect the CollectionView

Each cell in my collection view is full screen.  I handle the cell sizing in layout subviews.

```<code>override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    if let layout = customCollectionView.collectionViewLayout as? UICollectionViewFlowLayout {
        let itemWidth = view.frame.width
        let itemHeight = view.frame.height
        layout.itemSize = CGSize(width: itemWidth, height: itemHeight)
        layout.invalidateLayout()
    }

    let ip = IndexPath(row: 2, section: 0)

    view.layoutIfNeeded()
    customCollectionView.scrollToItem(at: ip, at: UICollectionViewScrollPosition.centeredVertically, animated: true)

    let point = CGPoint(x: 50, y: 600)
    customCollectionView.setContentOffset(point, animated: true)

}

func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {

    let pageHeight = customCollectionView.bounds.size.height
    let videoLength = CGFloat(videoArray.count)

    let minSpace:CGFloat = 10

    var cellToSwipe = (scrollView.contentOffset.y) / (pageHeight + minSpace) + 0.5
    if cellToSwipe < 0 {
        cellToSwipe = 0
    }
    else if (cellToSwipe >= videoLength){
        cellToSwipe = videoLength - 1
    }
    let p = Int(cellToSwipe)
    let roundedIP = round(Double(Int(cellToSwipe)))
    let ip = IndexPath(row: Int(roundedIP), section: 0)

   let ip = IndexPath(row: 2, section: 0)
    view.layoutIfNeeded()
    customCollectionView.scrollToItem(at: ip, at: UICollectionViewScrollPosition.centeredVertically, animated: true)

}
</code>```

答:
First off, I would recommend making your view controller class conform to UICollectionViewDelegateFlowLayout and use the following delegate method to size your UICollectionViewCells

```<code>func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let size = CGSize(width: view.frame.width, height: view.frame.height)
    return size
}
</code>```

Then in your viewDidLoad call

```<code>customCollectionView.isPagingEnabled = true
</code>```

ContentLicense: CC BY-SA 3.0

Title: Swift CollectionView Vertical Paging

Body:
I enabled paging on my collectionview and encountered the first issue of each swipe not stopping on a different cell, but page.

I then tried to enter code and handle the paging manually in ScrollViewWillEndDecelerating.
However my problem is the changing the collectionviews ContentOffset or scrolling to a Point both do not work unless called in LayoutSubiews. that is the only place where they effect the CollectionView

Each cell in my collection view is full screen.  I handle the cell sizing in layout subviews.

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    if let layout = customCollectionView.collectionViewLayout as? UICollectionViewFlowLayout {
        let itemWidth = view.frame.width
        let itemHeight = view.frame.height
        layout.itemSize = CGSize(width: itemWidth, height: itemHeight)
        layout.invalidateLayout()
    }

    let ip = IndexPath(row: 2, section: 0)

    view.layoutIfNeeded()
    customCollectionView.scrollToItem(at: ip, at: UICollectionViewScrollPosition.centeredVertically, animated: true)

    let point = CGPoint(x: 50, y: 600)
    customCollectionView.setContentOffset(point, animated: true)

}

func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {

    let pageHeight = customCollectionView.bounds.size.height
    let videoLength = CGFloat(videoArray.count)

    let minSpace:CGFloat = 10

    var cellToSwipe = (scrollView.contentOffset.y) / (pageHeight + minSpace) + 0.5
    if cellToSwipe < 0 {
        cellToSwipe = 0
    }
    else if (cellToSwipe >= videoLength){
        cellToSwipe = videoLength - 1
    }
    let p = Int(cellToSwipe)
    let roundedIP = round(Double(Int(cellToSwipe)))
    let ip = IndexPath(row: Int(roundedIP), section: 0)

   let ip = IndexPath(row: 2, section: 0)
    view.layoutIfNeeded()
    customCollectionView.scrollToItem(at: ip, at: UICollectionViewScrollPosition.centeredVertically, animated: true)

}

Body:
First off, I would recommend making your view controller class conform to UICollectionViewDelegateFlowLayout and use the following delegate method to size your UICollectionViewCells

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let size = CGSize(width: view.frame.width, height: view.frame.height)
    return size
}

Then in your viewDidLoad call

customCollectionView.isPagingEnabled = true


问:
C++: How to return abstract class in a method of this abstract class
I have an abstract class and it has two derived classes. I'm trying to overload operator+ in the base class so I could do derivedClass=derivedClass+differentDerivedClass like this:

```<code>class iMatrix{
iMatrix operator+(const iMatrix& obj)
}

class UsualMatrix : public iMatrix

class SparseMatrix : public iMatrix
</code>```

Inside of main, I want to do

```<code>SparseMatrix a, b;
UsualMatrix c=a+b;
</code>```

I have copy constructors and everything that may be helpful. Now if I create the function like

```<code>iMatrix operator+(const iMatrix& obj)
</code>```

Compiler (LLVM in Xcode) says "Return type 'iMatrix' is an abstract class", but theoretically everything else should work properly. I've read manuals and other StackOverflow threads, so I've tried this:

```<code>iMatrix& operator+(const iMatrix& obj)
</code>```

Whereas function on its own does "add obj to this" and returns *this. The problem is when I do c=a+b, a becomes equal to c, but it should not be changed.

```<code>a=
1 1
1 1
b=
1 1
1 1
a+b=c;
c=
2 2
2 2
b=
1 1
1 1
a=
2 2
2 2
</code>```

What should I do? Addition and multiplying must be implemented inside of base class, and I have no idea how to fix this error.
Any advice would be appreciated, thanks.

答:
The problem with your intend design is the abstract return type.  Abstract classes can't be returned by value.  Only concrete classes can be returned by value.  So, to return abstract class you'd need a pointer or a reference.

Unfortunately, this will not work with the semantics of operator+() :

either you'd return by reference the current object, and change it with the operation; but this is not compliant with the expected semantics, and furthermore might lead to wrong answerds (e.g. when doing c = a+b+a+b; )

or you'd return the reference to a temporary object.  but this would be UB, because the temporaray object will decease when the function returns, making the reference irrelevant.

finally operator+ would not have a way to decide on its own of the concrete type to use for the return.  For example: SparseMatrix a; UsualMatrix b;   a+b; what should be the type to be used for the matrix a+b ?

You can use polymorphic and abstract types within operators, but not as a return type.  To implement this kind of things, you'd need to opt for your own set of operators, and letting the caller manage the temporary results manually:

```<code>UsualMatrix c,tmp;
SparseMatrix a,b,x;
...
a.add(b, tmp);
tmp.add(x, c);   // c = a+b+x;
</code>```

with virtual void add(const iMatrix& x, iMatrix z) = 0;

Body:
I have an abstract class and it has two derived classes. I'm trying to overload operator+ in the base class so I could do derivedClass=derivedClass+differentDerivedClass like this:

class iMatrix{
iMatrix operator+(const iMatrix& obj)
}

class UsualMatrix : public iMatrix

class SparseMatrix : public iMatrix

Inside of main, I want to do

SparseMatrix a, b;
UsualMatrix c=a+b;

I have copy constructors and everything that may be helpful. Now if I create the function like

iMatrix operator+(const iMatrix& obj)

Compiler (LLVM in Xcode) says "Return type 'iMatrix' is an abstract class", but theoretically everything else should work properly. I've read manuals and other StackOverflow threads, so I've tried this:

iMatrix& operator+(const iMatrix& obj)

Whereas function on its own does "add obj to this" and returns *this. The problem is when I do c=a+b, a becomes equal to c, but it should not be changed.

a=
1 1
1 1
b=
1 1
1 1
a+b=c;
c=
2 2
2 2
b=
1 1
1 1
a=
2 2
2 2

What should I do? Addition and multiplying must be implemented inside of base class, and I have no idea how to fix this error.
Any advice would be appreciated, thanks.

Body:
The problem with your intend design is the abstract return type.  Abstract classes can't be returned by value.  Only concrete classes can be returned by value.  So, to return abstract class you'd need a pointer or a reference.

Unfortunately, this will not work with the semantics of operator+() :

either you'd return by reference the current object, and change it with the operation; but this is not compliant with the expected semantics, and furthermore might lead to wrong answerds (e.g. when doing c = a+b+a+b; )

or you'd return the reference to a temporary object.  but this would be UB, because the temporaray object will decease when the function returns, making the reference irrelevant.

finally operator+ would not have a way to decide on its own of the concrete type to use for the return.  For example: SparseMatrix a; UsualMatrix b;   a+b; what should be the type to be used for the matrix a+b ?

You can use polymorphic and abstract types within operators, but not as a return type.  To implement this kind of things, you'd need to opt for your own set of operators, and letting the caller manage the temporary results manually:

UsualMatrix c,tmp;
SparseMatrix a,b,x;
...
a.add(b, tmp);
tmp.add(x, c);   // c = a+b+x;

with virtual void add(const iMatrix& x, iMatrix z) = 0;


问:
How to get parent value in this situation (using Telerik Panel Bar)
Using telerik Panel Bar

```<code>Html.Telerik().PanelBar()
    .Name("PanelBar")
    .BindTo(Model, mappings =>
    {
        mappings.For<Category>(binding => binding
                .ItemDataBound((item, category) =>
                {
                    item.Text = category.CategoryName;
                })
                .Children(category => category.Products));
        mappings.For<Product>(binding => binding
                .ItemDataBound((item, product) =>
                {
                    item.Text = product.ProductName;
                }));
    })
</code>```

http://www.telerik.com/help/aspnet-mvc/telerik-ui-components-panelbar-data-binding.html

What I need is to generate a URL based on categoryID and productID

i.e. :

```<code>.Children(category => category.Products));
    mappings.For<Product>(binding => binding
            .ItemDataBound((item, product) =>
            {
                item.Text = product.ProductName;
                item.Url = (Get at the parent to get the categoryid somehow) + "/Details/" + product.productID;
            }));
</code>```

But I can't figure out how I can access any of the category fields.

And I can't get it from product because it will be one-many, and i'll have product.Categories. linq methods

Cheers

答:
Although I didn't want to, I managed to store the value like this:

```<code>mappings.For<Category>(binding => binding
                .ItemDataBound((item, category) =>
                {
                    item.Text = category.CategoryName;
                    item.ActionName = category.CategoryID.ToString();
                })
                .Children(category => category.Products));
        mappings.For<Product>(binding => binding
                .ItemDataBound((item, product) =>
                {
                    item.Text = product.ProductName;
                    item.Url = item.Parent.ActionName + "/Detail/" + product.ProductID;
                }));
</code>```

Wonder if anyone ends up with a cleaner solution

ContentLicense: CC BY-SA 2.5

Body:
Using telerik Panel Bar

Html.Telerik().PanelBar()
    .Name("PanelBar")
    .BindTo(Model, mappings =>
    {
        mappings.For<Category>(binding => binding
                .ItemDataBound((item, category) =>
                {
                    item.Text = category.CategoryName;
                })
                .Children(category => category.Products));
        mappings.For<Product>(binding => binding
                .ItemDataBound((item, product) =>
                {
                    item.Text = product.ProductName;
                }));
    })

http://www.telerik.com/help/aspnet-mvc/telerik-ui-components-panelbar-data-binding.html

What I need is to generate a URL based on categoryID and productID

i.e. :

.Children(category => category.Products));
    mappings.For<Product>(binding => binding
            .ItemDataBound((item, product) =>
            {
                item.Text = product.ProductName;
                item.Url = (Get at the parent to get the categoryid somehow) + "/Details/" + product.productID;
            }));

But I can't figure out how I can access any of the category fields.

And I can't get it from product because it will be one-many, and i'll have product.Categories. linq methods

Cheers

Body:
Although I didn't want to, I managed to store the value like this:

mappings.For<Category>(binding => binding
                .ItemDataBound((item, category) =>
                {
                    item.Text = category.CategoryName;
                    item.ActionName = category.CategoryID.ToString();
                })
                .Children(category => category.Products));
        mappings.For<Product>(binding => binding
                .ItemDataBound((item, product) =>
                {
                    item.Text = product.ProductName;
                    item.Url = item.Parent.ActionName + "/Detail/" + product.ProductID;
                }));

Wonder if anyone ends up with a cleaner solution


问:
ngFor not updating when pushing new data
I have a set of reactive forms that I'm setting up as an array of reactive forms:

```<code>typesForms: FormGroup[] = [];
</code>```

Which I loop through in my html:

```<code><form *ngFor="let type of typesForms; let i = index" [formGroup]="typesForms[i]" class="row">
</code>```

However, when I push a new form, the HTML doesn't update.

```<code>this.typesForms.push(this.formBuilder.group({
    type: { value: data['type'], disabled: true }
}));
</code>```

I've logged out the resulting data, and it shows the new form object, but nothing on the front end. I assume this has something to do with reactive forms, but I'm not sure if I'm screwing something else up.

答:
Have you tried just <form *ngFor="let type of typesForm" [formGroup]="type" class="row">?

Update:

If you have multiple forms you can utilize Angular's built-in FormArray data structure. It does simplifying manipulations on set of form groups - allows you to easily track changes and validate linked FormGroup's or FormControl's.

Punkr example

Note: thanks to how things structured under the ReactiveFormsModule hood you can compose FormArrays, FormGroups and FormControls as you want:

you can have a FormArray as field a of FormGroup

FormArray can contain FormArrays, FormGroups and FormControls

Body:
I have a set of reactive forms that I'm setting up as an array of reactive forms:

typesForms: FormGroup[] = [];

Which I loop through in my html:

<form *ngFor="let type of typesForms; let i = index" [formGroup]="typesForms[i]" class="row">

However, when I push a new form, the HTML doesn't update.

this.typesForms.push(this.formBuilder.group({
    type: { value: data['type'], disabled: true }
}));

I've logged out the resulting data, and it shows the new form object, but nothing on the front end. I assume this has something to do with reactive forms, but I'm not sure if I'm screwing something else up.


问:
Maximum number of columns in view
There is a (complex) maximum number of columns in a table in mySQL.

But what about a maximum number of columns in a view?

I mean, a view might be a join of numerous tables. Will there be a maximum of the total number of columns?

Thanks in advance.

答:
By way of example, a questionnaire table might look like this:

```<code>questionnaire_id, question_no, question
               1            1  What is your name?
               1            2  Where do you live?
               1            3  What is your favourite colour?
               2            1  What is the capital of France?
               2            2  Who wrote Beethoven's Fifth?
               2            3  When was the Great Fire of London?
</code>```

So, there we have two questionnaires (of potentially unlimited length) occupying exactly 3 columns in a table.

Any remaining 'user-experience' issues would properly be handled in application code.

Title: Maximum number of columns in view

Body:
By way of example, a questionnaire table might look like this:

questionnaire_id, question_no, question
               1            1  What is your name?
               1            2  Where do you live?
               1            3  What is your favourite colour?
               2            1  What is the capital of France?
               2            2  Who wrote Beethoven's Fifth?
               2            3  When was the Great Fire of London?

So, there we have two questionnaires (of potentially unlimited length) occupying exactly 3 columns in a table.

Any remaining 'user-experience' issues would properly be handled in application code.


问:
Changing css background image property by jquery setTimeout
I want to change my header image (which I gave it's source in the css, not in HTML) every 10 seconds Using jQuery.
I may have up to 15 16 images so the code I wrote may be too long for my js file.
I wrote the code below , but I'm looking for much compact code , hopefully using arrays.</p>

```<code>$(function() {
  setTimeout(function() {
    changeHeaderImg3()
  }, 10000);

  setTimeout(function() {
    changeHeaderImg2()
  }, 20000);

  setTimeout(function() {
    changeHeaderImg1()
  }, 30000);

  setTimeout(function() {
    changeHeaderImg4()
  }, 40000);
  setTimeout(function() {
    changeHeaderImg3()
  }, 50000);
});

function changeHeaderImg3() {

  $('header').css('background', 'url(assets/img/bg3.jpg) center center').css('background-size', 'cover');
  $('footer').css('background', 'url(assets/img/bg3.jpg) center center').css('background-size', 'cover');
};

function changeHeaderImg2() {

  $('header').css('background', 'url(assets/img/bg2.jpg) center center').css('background-size', 'cover');
  $('footer').css('background', 'url(assets/img/bg2.jpg) center center').css('background-size', 'cover');
};

function changeHeaderImg1() {

  $('header').css('background', 'url(assets/img/bg1.jpg) center center').css('background-size', 'cover');
  $('footer').css('background', 'url(assets/img/bg1.jpg) center center').css('background-size', 'cover');
};

function changeHeaderImg4() {

  $('header').css('background', 'url(assets/img/bg4.jpg) center center').css('background-size', 'cover');
  $('footer').css('background', 'url(assets/img/bg4.jpg) center center').css('background-size', 'cover');
};

function changeHeaderImg3() {

  $('header').css('background', 'url(assets/img/bg3.jpg) center center').css('background-size', 'cover');
  $('footer').css('background', 'url(assets/img/bg3.jpg) center center').css('background-size', 'cover');
};
</code>```

答:
Another solution :</p>

```<code>$(function() {
    let pictures = ["bg3.jpg", "bg2.jpg", "bg1.jpg"];
    $.each(pictures, function(i,e) {
        setTimeout(function() {
            changeHeaderImg(e);
        }, i*10000);
    });
}

function changeHeaderImg(pictureName: string) {
    $('header').css('background', 'url(assets/img/'+pictureName+') center center').css('background-size', 'cover');
    $('footer').css('background', 'url(assets/img/'+pictureName+') center center').css('background-size', 'cover');
}
</code>```

Body:
I want to change my header image (which I gave it's source in the css, not in HTML) every 10 seconds Using jQuery.
I may have up to 15 16 images so the code I wrote may be too long for my js file.
I wrote the code below , but I'm looking for much compact code , hopefully using arrays.

$(function() {
  setTimeout(function() {
    changeHeaderImg3()
  }, 10000);

  setTimeout(function() {
    changeHeaderImg2()
  }, 20000);

  setTimeout(function() {
    changeHeaderImg1()
  }, 30000);

  setTimeout(function() {
    changeHeaderImg4()
  }, 40000);
  setTimeout(function() {
    changeHeaderImg3()
  }, 50000);
});

function changeHeaderImg3() {

  $('header').css('background', 'url(assets/img/bg3.jpg) center center').css('background-size', 'cover');
  $('footer').css('background', 'url(assets/img/bg3.jpg) center center').css('background-size', 'cover');
};

function changeHeaderImg2() {

  $('header').css('background', 'url(assets/img/bg2.jpg) center center').css('background-size', 'cover');
  $('footer').css('background', 'url(assets/img/bg2.jpg) center center').css('background-size', 'cover');
};

function changeHeaderImg1() {

  $('header').css('background', 'url(assets/img/bg1.jpg) center center').css('background-size', 'cover');
  $('footer').css('background', 'url(assets/img/bg1.jpg) center center').css('background-size', 'cover');
};

function changeHeaderImg4() {

  $('header').css('background', 'url(assets/img/bg4.jpg) center center').css('background-size', 'cover');
  $('footer').css('background', 'url(assets/img/bg4.jpg) center center').css('background-size', 'cover');
};

function changeHeaderImg3() {

  $('header').css('background', 'url(assets/img/bg3.jpg) center center').css('background-size', 'cover');
  $('footer').css('background', 'url(assets/img/bg3.jpg) center center').css('background-size', 'cover');
};

Body:
Another solution :

$(function() {
    let pictures = ["bg3.jpg", "bg2.jpg", "bg1.jpg"];
    $.each(pictures, function(i,e) {
        setTimeout(function() {
            changeHeaderImg(e);
        }, i*10000);
    });
}

function changeHeaderImg(pictureName: string) {
    $('header').css('background', 'url(assets/img/'+pictureName+') center center').css('background-size', 'cover');
    $('footer').css('background', 'url(assets/img/'+pictureName+') center center').css('background-size', 'cover');
}


问:
Sentence similarity using keras
I'm trying to implement sentence similarity architecture based on this work using the STS dataset. Labels are normalized similarity scores from 0 to 1 so it is assumed to be a regression model.

My problem is that the loss goes directly to NaN starting from the first epoch. What am I doing wrong?

I have already tried updating to latest keras and theano versions.

The code for my model is:

```<code>def create_lstm_nn(input_dim):
    seq = Sequential()`
    # embedd using pretrained 300d embedding
    seq.add(Embedding(vocab_size, emb_dim, mask_zero=True, weights=[embedding_weights]))
    # encode via LSTM
    seq.add(LSTM(128))
    seq.add(Dropout(0.3))
    return seq

lstm_nn = create_lstm_nn(input_dim)

input_a = Input(shape=(input_dim,))
input_b = Input(shape=(input_dim,))

processed_a = lstm_nn(input_a)
processed_b = lstm_nn(input_b)

cos_distance = merge([processed_a, processed_b], mode='cos', dot_axes=1)
cos_distance = Reshape((1,))(cos_distance)
distance = Lambda(lambda x: 1-x)(cos_distance)

model = Model(input=[input_a, input_b], output=distance)

# train
rms = RMSprop()
model.compile(loss='mse', optimizer=rms)
model.fit([X1, X2], y, validation_split=0.3, batch_size=128, nb_epoch=20)
</code>```

I also tried using a simple Lambda instead of the Merge layer, but it has the same result.

```<code>def cosine_distance(vests):
    x, y = vests
    x = K.l2_normalize(x, axis=-1)
    y = K.l2_normalize(y, axis=-1)
    return -K.mean(x * y, axis=-1, keepdims=True)

def cos_dist_output_shape(shapes):
    shape1, shape2 = shapes
    return (shape1[0],1)

distance = Lambda(cosine_distance, output_shape=cos_dist_output_shape)([processed_a, processed_b])
</code>```

答:
I didn't run into the nan issue, but my loss wouldn't change. I found this info
check this out

```<code>def cosine_distance(shapes):
    y_true, y_pred = shapes
    def l2_normalize(x, axis):
        norm = K.sqrt(K.sum(K.square(x), axis=axis, keepdims=True))
        return K.sign(x) * K.maximum(K.abs(x), K.epsilon()) /     K.maximum(norm, K.epsilon())
    y_true = l2_normalize(y_true, axis=-1)
    y_pred = l2_normalize(y_pred, axis=-1)
    return K.mean(1 - K.sum((y_true * y_pred), axis=-1))
</code>```

Title: Sentence similarity using keras

Body:
I'm trying to implement sentence similarity architecture based on this work using the STS dataset. Labels are normalized similarity scores from 0 to 1 so it is assumed to be a regression model.

My problem is that the loss goes directly to NaN starting from the first epoch. What am I doing wrong?

I have already tried updating to latest keras and theano versions.

The code for my model is:

def create_lstm_nn(input_dim):
    seq = Sequential()`
    # embedd using pretrained 300d embedding
    seq.add(Embedding(vocab_size, emb_dim, mask_zero=True, weights=[embedding_weights]))
    # encode via LSTM
    seq.add(LSTM(128))
    seq.add(Dropout(0.3))
    return seq

lstm_nn = create_lstm_nn(input_dim)

input_a = Input(shape=(input_dim,))
input_b = Input(shape=(input_dim,))

processed_a = lstm_nn(input_a)
processed_b = lstm_nn(input_b)

cos_distance = merge([processed_a, processed_b], mode='cos', dot_axes=1)
cos_distance = Reshape((1,))(cos_distance)
distance = Lambda(lambda x: 1-x)(cos_distance)

model = Model(input=[input_a, input_b], output=distance)

# train
rms = RMSprop()
model.compile(loss='mse', optimizer=rms)
model.fit([X1, X2], y, validation_split=0.3, batch_size=128, nb_epoch=20)

I also tried using a simple Lambda instead of the Merge layer, but it has the same result.

def cosine_distance(vests):
    x, y = vests
    x = K.l2_normalize(x, axis=-1)
    y = K.l2_normalize(y, axis=-1)
    return -K.mean(x * y, axis=-1, keepdims=True)

def cos_dist_output_shape(shapes):
    shape1, shape2 = shapes
    return (shape1[0],1)

distance = Lambda(cosine_distance, output_shape=cos_dist_output_shape)([processed_a, processed_b])

Body:
I didn't run into the nan issue, but my loss wouldn't change. I found this info
check this out

def cosine_distance(shapes):
    y_true, y_pred = shapes
    def l2_normalize(x, axis):
        norm = K.sqrt(K.sum(K.square(x), axis=axis, keepdims=True))
        return K.sign(x) * K.maximum(K.abs(x), K.epsilon()) /     K.maximum(norm, K.epsilon())
    y_true = l2_normalize(y_true, axis=-1)
    y_pred = l2_normalize(y_pred, axis=-1)
    return K.mean(1 - K.sum((y_true * y_pred), axis=-1))


问:
I want to display a random object
I want to display a random object in cards.

  <% @slots.sample(3).each do |slot| %>

      <%= link_to slot_path(slot) do %>
        <% if slot.photo? %>
          <%= cl_image_tag slot.photo, class: "img-rounded img-responsive", height: 262, width: 195 %>
        <% else %>
          <%= image_tag "image_placeholder.jpg", class: "fileinput-new thumbnail img-no-padding", height: 250, width: 400 %>
        <% end %>
        <% end %>

          <%= link_to slot_user(slot) do %>
            <%= cl_image_tag slot.user.photo, class: "img-circle img-no-padding img-responsive" %>
            <%= slot.name %>
            <%= slot.user.first_name %> <%= slot.user.last_name %>
          <% end %>

  <% end %>

```

<p>My code returns error messages like:</p>

```"undefined method `sample' for nil:NilClass",
"undefined method `photo' for nil:NilClass",
"undefined method `user' for nil:NilClass"
```

I don't understand. Can you help me?

答:
You can randomize your @slots collection in the conntroller, eg:

```<code>@slots = Slot.where(id: Slot.pluck(:id).sample(3))
</code>```

Then use directly in the view

```<code><% @slots.each do |slot| %>
</code>```

Title: I want to display a random object

Body:
I want to display a random object in cards.

  <% @slots.sample(3).each do |slot| %>

      <%= link_to slot_path(slot) do %>
        <% if slot.photo? %>
          <%= cl_image_tag slot.photo, class: "img-rounded img-responsive", height: 262, width: 195 %>
        <% else %>
          <%= image_tag "image_placeholder.jpg", class: "fileinput-new thumbnail img-no-padding", height: 250, width: 400 %>
        <% end %>
        <% end %>

          <%= link_to slot_user(slot) do %>
            <%= cl_image_tag slot.user.photo, class: "img-circle img-no-padding img-responsive" %>
            <%= slot.name %>
            <%= slot.user.first_name %> <%= slot.user.last_name %>
          <% end %>

  <% end %>

My code returns error messages like:

"undefined method `sample' for nil:NilClass",
"undefined method `photo' for nil:NilClass",
"undefined method `user' for nil:NilClass"

I don't understand. Can you help me?

Body:
You can randomize your @slots collection in the conntroller, eg:

@slots = Slot.where(id: Slot.pluck(:id).sample(3))

Then use directly in the view

<% @slots.each do |slot| %>


问:
What should be the `IEnumerable<T>` type for the content of a `.csv` file?
I have a .csv file (Book1.csv) including transitions of a finite state machine:

```<code>q_src,eve,q_dst
q0,sig1,q1
q1,sig2,q2
</code>```

I need to write a method to find the result of a transition.

```<code>State FindDestination(State q0, Event s0)
{
    var transitions = File.ReadAllLines(@"Book1.csv").Skip(1).Select(x => x.Split(','));
    State newq = from t in transitions
                 where t.q_src ==q0 && t.eve == s0
                 select new t.q_dst;
    return newq;
}
</code>```

But it's not efficient because the method will read the file every time for each transition:

Now if I try to read the file once and pass its content to the method, I don't k
now what type should I use for the transitions in the method's argument:

```<code>var transitions = File.ReadAllLines(@"Book1.csv").Skip(1).Select(x => x.Split(','));

State FindDestination(State q0, Event s0, ? transitions)   //?type
{
    State newq = from t in transitions
                 where t.q_src ==q0 && t.eve == s0
                 select new t.q_dst;
    return newq;
}
</code>```

Furthermore, State and Event classes have only one attribute Name.

I've read that the rough ideas is using IEnumerable<?>, but what is the ? type for a .csv file?

答: As ReadAllLines returns a string[] IEnumerable<string> should be a valid match.

Body:
I have a .csv file (Book1.csv) including transitions of a finite state machine:

q_src,eve,q_dst
q0,sig1,q1
q1,sig2,q2

I need to write a method to find the result of a transition.

State FindDestination(State q0, Event s0)
{
    var transitions = File.ReadAllLines(@"Book1.csv").Skip(1).Select(x => x.Split(','));
    State newq = from t in transitions
                 where t.q_src ==q0 && t.eve == s0
                 select new t.q_dst;
    return newq;
}

But it's not efficient because the method will read the file every time for each transition:

Now if I try to read the file once and pass its content to the method, I don't k
now what type should I use for the transitions in the method's argument:

var transitions = File.ReadAllLines(@"Book1.csv").Skip(1).Select(x => x.Split(','));

State FindDestination(State q0, Event s0, ? transitions)   //?type
{
    State newq = from t in transitions
                 where t.q_src ==q0 && t.eve == s0
                 select new t.q_dst;
    return newq;
}

Furthermore, State and Event classes have only one attribute Name.

I've read that the rough ideas is using IEnumerable<?>, but what is the ? type for a .csv file?


问:
Am I overspawning IO bound web scraping threads?
TL;DR:
If I spawn 10 web requests, each on its own thread, with a CPU that has a 4 thread limit, is this okay or inefficient? Threads are IO bound so sit idle while awaiting server response (I believe). How does CPU deal if more than 4 threads return simultaneously?

I've got a script that currently starts a new thread for every file I need to download (each located at a unique URL) through an http.client.HTTPSConnection. At max, I may need to spawn 730 threads. I have done this, since the threads are all IO bound work (downloading and saving to file), but I am not sure if they are executing in parallel or if the CPU is only executing a set at a time. Total run time for file sizes ranging between 20MB to 110MB was roughly 15 minutes.

My CPU is quad-core with no Hyper-Threading. This means that it should only support 4 threads simultaneously at any given time. Since the work is IO bound and not CPU bound, am I still limited by the hold of only 4 simultaneous threads?

I suppose what is confusing is I am not sure what sequence of events takes place if say I send out just 1 request on 10 threads; what happens if they all return at the same time? Or how does the CPU choose which 4 to finish before moving onto the next available thread?

And after all of this, if the CPU is only handling 4 threads at a time, I would image it is still smart to spawn as many IO threads as I need (since they will sit idle while waiting for server response) right?

答:
You can have significantly more than 4 IO-bound threads on a quad-core CPU.  However, you  do want to have some maximum.  Even IO bound processes use the CPU some of the time.  For example, when a packet is received, that packet needs to be handled to update TCP state.  If you are reading from a socket and writing to a file, some CPU is required to actually copy the characters from the socket buffer to the file buffer under most circumstances.  If you use TLS, CPU is typically required to decrypt and encrypt data.  So even threads that are mostly doing IO use the CPU some.  Eventually the small fraction of time that you are using the CPU will add up and consume the available CPU resources.
Also, note that in Python, because of the global interpreter lock, you can only have one thread using the CPU to run python code at a time.  So, the GIL would not typically be held while doing something like waiting for an outgoing connection.  During that time other threads could be run.  However, for some fraction of the time while reading and writing from a socket or file, the GIL will be held.  It's likely with most common work loads that the performance of your application will reach a maximum when  the fraction of time your threads need a CPU reaches one full CPU rather than four full CPUs.
You may find that using asyncio or some other event-driven architecture provides better performance.  When true this is typically because the event-driven model is better at reducing cross-thread contention for resources.
In response to your question edit, I would not expect 10 threads to be a problem


问:
Prestashop 1.6 - Send a second email to the customer after order confirmation email
I've search on some Prestashop forums and here on Stackoverflow but it seem that i can't find an answer for that question :

-Would it be possible to send a second email (based on a custom mail template), to the customer after the Order confirmation mail ?

The customer is buying a product, making payment, receive his order confirmation by email and then an other email would be sent to him saying a custom message.

I've looked into Email Alert Module but it doesn't look like it's meant to do that.

I'm on Prestashop v1.6

Thanks a lot for your help and time.

答:
In addition to Raghubendra Singh answer. Not sure it is the best approach.

You can do it by overriding the PaymentModule class (see Mail::Send();)

To create a custom email subjet, you have to modify :

```<code>app/Resources/translations/fr-FR/EmailsSubject.fr-FR.xlf
</code>```

add you subject :

```<code><trans-unit id="fca7e8d1c86db11246e429e40aa10c82" approved="yes">
        <source>Your new subject</source>
        <target xml:lang="fr">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</target>
        <note>Context:
File: classes/PaymentModule.php:844</note>
 </trans-unit>
</code>```

You can also create a new email template :
add your file here :
(you can copy paste one of the template and modify it to your needs)

```<code>mail/fr/new-template.html
mail/fr/new-template.txt
</code>```

Body:
In addition to Raghubendra Singh answer. Not sure it is the best approach.

You can do it by overriding the PaymentModule class (see Mail::Send();)

To create a custom email subjet, you have to modify :

app/Resources/translations/fr-FR/EmailsSubject.fr-FR.xlf

add you subject :

<trans-unit id="fca7e8d1c86db11246e429e40aa10c82" approved="yes">
        <source>Your new subject</source>
        <target xml:lang="fr">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</target>
        <note>Context:
File: classes/PaymentModule.php:844</note>
 </trans-unit>

You can also create a new email template :
add your file here :
(you can copy paste one of the template and modify it to your needs)

mail/fr/new-template.html
mail/fr/new-template.txt


问:
Orchard Widget for front end DB Access
I'm new to Orchard development, C# and MVC, so forgive me if this is actually simple...

I used Orchard CMS in my profession so I understand the widgets, layer zones, content parts etc... however, I have tasked my self with improving one of the processes that is quite common, and I decided the best way would to be to create a module for this purpose.

The basic outline of the process using widgets would be as follows:

Customer navigates to a page and is presented with three sections, Submit and View

The "submit" section is a widget which is a form (most likely a custom form) which posts to a controller, and submits that data to a DB, I think I have this figured out.. but to make sure I am going to use something like the following to do this:

```<code>    [HttpPost]
public ActionResult Index(string fName, string lName) {
    // var post values
    string fName = Request.Form["fName"];
    string lName = Request.Form["lName"];

    System.Data.SqlClient.SqlConnection sqlConnection1 =
        new System.Data.SqlClient.SqlConnection(@"[CONNECTION STRING]");

    System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
    cmd.CommandType = System.Data.CommandType.Text;
    cmd.CommandText = "INSERT INTO Persons (FirstName, LastName) VALUES ('" + fName + "','" + lName +"')";
    cmd.Connection = sqlConnection1;

    sqlConnection1.Open();
    cmd.ExecuteNonQuery();
    sqlConnection1.Close();

    return View();
}
</code>```

However, I am not sure this is the correct way to go about it, and I'm sure there is some better way I can do this, tutorials have recommended I use contentParts and contentPart records to submit data to the db however, this is only useful when submitting data from the admin side, this has to be able to be submitted from the front end by an end-user

The second section is a table which would get a list of records from the database and display them to the user, however, for this I have no idea how to go about this at all, could anyone point me to a tutorial, example source code, or even code snippets where this is achieved?

It is worth noting, I have gone through the documentation for creating modules and widgets on Orchard's site, however, they are all updating the DB via the backend...

Odatia

答:
For anybody stumbling across this post looking for help, I did the two listed things in the following way:

Controller:

```<code> [Themed]
    public class PortingController : Controller
    {
        // GET Porting/Index
        public ActionResult Index()
        {
            List<port> ports = new List<port>();
            string constr = "Data Source=127.0.0.1;Port=3307;Database=orchard;User Id=root;Password=usbw ";
            using (MySqlConnection con = new MySqlConnection(constr))
            {
                string query = "SELECT * FROM icc_porting_icc_activesoftswitch_ports";
                using (MySqlCommand cmd = new MySqlCommand(query))
                {
                    cmd.Connection = con;
                    con.Open();
                    using (MySqlDataReader sdr = cmd.ExecuteReader()) {
                        while (sdr.Read())
                        {
                            ports.Add(new port {
                                Id = Convert.ToInt32(sdr["Id"]),
                                MBN = sdr["MBN"].ToString(),
                                Partner = sdr["Partner"].ToString()
                            });
                        }
                    }
                }
                con.Close();
            }
            return View(ports);
        }

        // POST AddRequest
        [HttpPost]
        public ActionResult AddRequest(FormCollection forms)
        {
            // init vars
            string mbn = forms["PortingRequestForm.mbn.Value"];
            string partner = forms["PortingRequestForm.Partner.Value"];

            // db con string
            string connString = "Data Source=127.0.0.1;Port=3307;Database=orchard;User Id=root;Password=usbw ";
            MySqlConnection conn = new MySqlConnection(connString);
            conn.Open();
            MySqlCommand comm = conn.CreateCommand();
            comm.CommandText = "INSERT INTO icc_porting_icc_activesoftswitch_ports(mbn, partner) VALUES(?mbn, ?partner)";
            comm.Parameters.AddWithValue("?mbn", mbn);
            comm.Parameters.AddWithValue("?partner", partner);
            comm.ExecuteNonQuery();
            conn.Close();

            //string endContent = mbn + " " + partner;
            return RedirectToAction("Index");
        }
    }
}
</code>```

And then the model is just simply declaring some basic properties

To add to the DB I created a custom form and used jQuery to change the forms action so instead of using orchard's custom form controller it posted to the following: ~/{moduleName}/{Controller}/{Action}

Then just use standard razor mark up to get variables from the index controller example:

```<code>@using Porting.Models
@model IEnumerable<port>
    <table class="demo">
        <thead>
            <tr>
                <th>ID</th>
                <th>MBN</th>
                <th>Status</th>
            </tr>
        </thead>
        <tbody>
            @foreach (port Port in Model) {
                <tr>
                    <td>@Port.Id</td>
                    <td>@Port.MBN</td>
                    <td>@Port.Partner</td>
                </tr>
            }
        <tbody>
</table>
</code>```

It isn't the best and I know there are probably a million ways I can improve this so if anyone wouldn't mind helping please send me a private message or even just comment here?

Thanks

Odatia

Title: Orchard Widget for front end DB Access

Body:
I'm new to Orchard development, C# and MVC, so forgive me if this is actually simple...

I used Orchard CMS in my profession so I understand the widgets, layer zones, content parts etc... however, I have tasked my self with improving one of the processes that is quite common, and I decided the best way would to be to create a module for this purpose.

The basic outline of the process using widgets would be as follows:

Customer navigates to a page and is presented with three sections, Submit and View

The "submit" section is a widget which is a form (most likely a custom form) which posts to a controller, and submits that data to a DB, I think I have this figured out.. but to make sure I am going to use something like the following to do this:

    [HttpPost]
public ActionResult Index(string fName, string lName) {
    // var post values
    string fName = Request.Form["fName"];
    string lName = Request.Form["lName"];

    System.Data.SqlClient.SqlConnection sqlConnection1 =
        new System.Data.SqlClient.SqlConnection(@"[CONNECTION STRING]");

    System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
    cmd.CommandType = System.Data.CommandType.Text;
    cmd.CommandText = "INSERT INTO Persons (FirstName, LastName) VALUES ('" + fName + "','" + lName +"')";
    cmd.Connection = sqlConnection1;

    sqlConnection1.Open();
    cmd.ExecuteNonQuery();
    sqlConnection1.Close();

    return View();
}

However, I am not sure this is the correct way to go about it, and I'm sure there is some better way I can do this, tutorials have recommended I use contentParts and contentPart records to submit data to the db however, this is only useful when submitting data from the admin side, this has to be able to be submitted from the front end by an end-user

The second section is a table which would get a list of records from the database and display them to the user, however, for this I have no idea how to go about this at all, could anyone point me to a tutorial, example source code, or even code snippets where this is achieved?

It is worth noting, I have gone through the documentation for creating modules and widgets on Orchard's site, however, they are all updating the DB via the backend...

Odatia

Body:
For anybody stumbling across this post looking for help, I did the two listed things in the following way:

Controller:

 [Themed]
    public class PortingController : Controller
    {
        // GET Porting/Index
        public ActionResult Index()
        {
            List<port> ports = new List<port>();
            string constr = "Data Source=127.0.0.1;Port=3307;Database=orchard;User Id=root;Password=usbw ";
            using (MySqlConnection con = new MySqlConnection(constr))
            {
                string query = "SELECT * FROM icc_porting_icc_activesoftswitch_ports";
                using (MySqlCommand cmd = new MySqlCommand(query))
                {
                    cmd.Connection = con;
                    con.Open();
                    using (MySqlDataReader sdr = cmd.ExecuteReader()) {
                        while (sdr.Read())
                        {
                            ports.Add(new port {
                                Id = Convert.ToInt32(sdr["Id"]),
                                MBN = sdr["MBN"].ToString(),
                                Partner = sdr["Partner"].ToString()
                            });
                        }
                    }
                }
                con.Close();
            }
            return View(ports);
        }

        // POST AddRequest
        [HttpPost]
        public ActionResult AddRequest(FormCollection forms)
        {
            // init vars
            string mbn = forms["PortingRequestForm.mbn.Value"];
            string partner = forms["PortingRequestForm.Partner.Value"];

            // db con string
            string connString = "Data Source=127.0.0.1;Port=3307;Database=orchard;User Id=root;Password=usbw ";
            MySqlConnection conn = new MySqlConnection(connString);
            conn.Open();
            MySqlCommand comm = conn.CreateCommand();
            comm.CommandText = "INSERT INTO icc_porting_icc_activesoftswitch_ports(mbn, partner) VALUES(?mbn, ?partner)";
            comm.Parameters.AddWithValue("?mbn", mbn);
            comm.Parameters.AddWithValue("?partner", partner);
            comm.ExecuteNonQuery();
            conn.Close();

            //string endContent = mbn + " " + partner;
            return RedirectToAction("Index");
        }
    }
}

And then the model is just simply declaring some basic properties

To add to the DB I created a custom form and used jQuery to change the forms action so instead of using orchard's custom form controller it posted to the following: ~/{moduleName}/{Controller}/{Action}

Then just use standard razor mark up to get variables from the index controller example:

@using Porting.Models
@model IEnumerable<port>
    <table class="demo">
        <thead>
            <tr>
                <th>ID</th>
                <th>MBN</th>
                <th>Status</th>
            </tr>
        </thead>
        <tbody>
            @foreach (port Port in Model) {
                <tr>
                    <td>@Port.Id</td>
                    <td>@Port.MBN</td>
                    <td>@Port.Partner</td>
                </tr>
            }
        <tbody>
</table>

It isn't the best and I know there are probably a million ways I can improve this so if anyone wouldn't mind helping please send me a private message or even just comment here?

Thanks

Odatia


问:
Resize an image inside a container dynamically using jQuery
I have a div container, and I call it "content_container". This container is able to drag and resize using jQuery UI. Inside this container, I implemented TinyMCE (content text editor). My problem is:

If the user inserts a 2000 pixels x 2000 pixels image, the container max-width is 1000 pixels. Then it will look like this:

```<code> ____________________
| Container header   |
----------------------
| text [image...................image]
|      [image...................image]
|____________________|
</code>```

(I am sorry, I am still developing it in my localhost, and I haven't found a web hosting company yet, thus I can't give you the direct link to see the demo).

Okay, the container is still resizeable, just that, the image size is always 2000 pixels x 2000 pixels. My question is: Is it possible when I resize the "content_container", the image will auto resize and fit into the container width?

If yes, how do I do it?

If no, is there another solution to solve this?

Code

Before TinyMCE, the container code:

```<code><div id="content_container">
    <div id="header">The header</div>
    <div id="content">
        <div id="inlineEditor"></div>
    </div>
</div>
</code>```

After the user enters content (for example, insert the image), the container will become:

```<code><div id="content_container">
    <div id="header">The header</div>
    <div id="content">
        <div class="inlineEditor">
            <p>some text <img alt="test" src="../usrXX/img/imgname.jpg"></p>
        </div>
    </div>
</div>
</code>```

As you can see, I can only manipulate the inlineEditor class.

答:
This answer is CSS based. Have you tried applying a class to your image like so?

```<code>.fluid-img{width:90%;}
</code>```

And your image:

```<code><img src="your_image.png" class="fluid-img">
</code>```

Here's an example (tested in Chrome).

Body:
I have a div container, and I call it "content_container". This container is able to drag and resize using jQuery UI. Inside this container, I implemented TinyMCE (content text editor). My problem is:

If the user inserts a 2000 pixels x 2000 pixels image, the container max-width is 1000 pixels. Then it will look like this:

 ____________________
| Container header   |
----------------------
| text [image...................image]
|      [image...................image]
|____________________|

(I am sorry, I am still developing it in my localhost, and I haven't found a web hosting company yet, thus I can't give you the direct link to see the demo).

Okay, the container is still resizeable, just that, the image size is always 2000 pixels x 2000 pixels. My question is: Is it possible when I resize the "content_container", the image will auto resize and fit into the container width?

If yes, how do I do it?

If no, is there another solution to solve this?

Code

Before TinyMCE, the container code:

The header

After the user enters content (for example, insert the image), the container will become:

The header

some text

As you can see, I can only manipulate the inlineEditor class.

Body:
This answer is CSS based. Have you tried applying a class to your image like so?

.fluid-img{width:90%;}

And your image:

<img src="your_image.png" class="fluid-img">

Here's an example (tested in Chrome).


问:
Make different UICollectionViewCells conform to different layouts?
This is in regards to position not size.

From what I've seen online, convention is usually to override the layout and implement your own custom properties using:

```<code>override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
</code>```

and I have been able to set custom layout attributes. However, layoutAttributesForElement does the following according to the documentation:

Returns the layout attributes for all of the cells and views in the specified rectangle.

"All of the cells"

I want two different cells to conform to two different sets of layout attributes in the same view.

Any suggestions?

答: You need to define different cell prototypes, not different layout attributes. Each one needs a unique identifier, and then in your collection data source's collectionView(_:cellForItemAtIndexPath:), call the collection view's dequeueReusableCell(withReuseIdentifier:for:) with the identifier that you want for the given path.

Body:
This is in regards to position not size.

From what I've seen online, convention is usually to override the layout and implement your own custom properties using:

override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {

and I have been able to set custom layout attributes. However, layoutAttributesForElement does the following according to the documentation:

Returns the layout attributes for all of the cells and views in the specified rectangle.

"All of the cells"

I want two different cells to conform to two different sets of layout attributes in the same view.

Any suggestions?


问:
Reuse inheritance to define a method in Java
I'm a new Java developer and I met some difficulties with the concept of inheritance in java to define my classes...

In one side, I have a generic class named Vehicle that defines a decades of attributes (with their getters/setters). And I have a Vehicle1 class that extends Vehicle class.

In other side, I have a generic classe named VehicleFactory that defines one single static method like this :

```<code>public class VehicleFactory {

    protected static Vehicle makeResult() {
        Vehicle result = new Vehicle();

        result.setCode("1");
        result.setNumber("2");
        // other setters methods
        return result;
    }
</code>```

The problem is that I want to create a Vehicle1Factory class with its own makeResult method that USE the makeResult method of its parent class. But I failed to do this (the aim here is the optimisation since Vehicle1 has all the generic attributes of Vehicle classe but has some additional attributes).

What I tried to write is like this :

```<code>public class Vehicle1Factory extends VehicleFactory {

    protected static Vehicle1 makeResult() {
        Vehicle1 result = new Vehicle1();

         result = (Vehicle1) VehicleFactory.makeResult();

        // I want to reuse the makeResult of its parent class to define
        // its own makeResult method
    }
}
</code>```

But when I do this, Java told me that there a ClassCastException and that I can't use the cast here...

Is there any solution in that case?

答:
Since ClassCastException issue is already answered. I want to give some comments on how you are setting up your abstraction.

1) It is usually a good idea to define abstract factory concept inside abstract class.

2) I don't see point of having "protected" and "static" together. Unless your class is only to be used by subclasses and classes in the same package.

3) Extending concrete class and just using its static method does not make sense. It is usually a bad practice to mix static and inheritance together.

Anyways here is example code with cleaner abstraction definition:

```<code> public class Vehicle {
    private int code = 0;
    private int number = 0;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }
}

public class Vehicle1 extends Vehicle {
    private String engine = null;

    public String getEngine() {
        return engine;
    }

    public void setEngine(String engine) {
        this.engine = engine;
    }
}

public abstract class AbstractVehicleFactory<T extends Vehicle> {

    protected T makeVehicle() {
        T result = create();

        result.setCode(11);
        result.setNumber(24);

        return result;
    }

    protected abstract T create();
}

public class VehicleFactory extends AbstractVehicleFactory<Vehicle> {

    public static Vehicle makeResult(){
        return new VehicleFactory().makeVehicle();
    }

    @Override
    protected Vehicle makeVehicle() {
        Vehicle result = super.makeVehicle();
        return result;
    }

    @Override
    protected Vehicle create(){
        return new Vehicle();
    }
}

public class Vehicle1Factory extends AbstractVehicleFactory<Vehicle1> {

    public static Vehicle1 makeResult(){
        return new Vehicle1Factory().makeVehicle();
    }

    @Override
    protected Vehicle1 makeVehicle() {
        Vehicle1 result = super.makeVehicle();

        result.setEngine("V8");

        return result;
    }

    @Override
    protected Vehicle1 create(){
        return new Vehicle1();
    }
}
</code>```

Body:
I'm a new Java developer and I met some difficulties with the concept of inheritance in java to define my classes...

In one side, I have a generic class named Vehicle that defines a decades of attributes (with their getters/setters). And I have a Vehicle1 class that extends Vehicle class.

In other side, I have a generic classe named VehicleFactory that defines one single static method like this :

public class VehicleFactory {

    protected static Vehicle makeResult() {
        Vehicle result = new Vehicle();

        result.setCode("1");
        result.setNumber("2");
        // other setters methods
        return result;
    }

The problem is that I want to create a Vehicle1Factory class with its own makeResult method that USE the makeResult method of its parent class. But I failed to do this (the aim here is the optimisation since Vehicle1 has all the generic attributes of Vehicle classe but has some additional attributes).

What I tried to write is like this :

public class Vehicle1Factory extends VehicleFactory {

    protected static Vehicle1 makeResult() {
        Vehicle1 result = new Vehicle1();

         result = (Vehicle1) VehicleFactory.makeResult();

        // I want to reuse the makeResult of its parent class to define
        // its own makeResult method
    }
}

But when I do this, Java told me that there a ClassCastException and that I can't use the cast here...

Is there any solution in that case?

Body:
Since ClassCastException issue is already answered. I want to give some comments on how you are setting up your abstraction.

1) It is usually a good idea to define abstract factory concept inside abstract class.

2) I don't see point of having "protected" and "static" together. Unless your class is only to be used by subclasses and classes in the same package.

3) Extending concrete class and just using its static method does not make sense. It is usually a bad practice to mix static and inheritance together.

Anyways here is example code with cleaner abstraction definition:

 public class Vehicle {
    private int code = 0;
    private int number = 0;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }
}

public class Vehicle1 extends Vehicle {
    private String engine = null;

    public String getEngine() {
        return engine;
    }

    public void setEngine(String engine) {
        this.engine = engine;
    }
}

public abstract class AbstractVehicleFactory<T extends Vehicle> {

    protected T makeVehicle() {
        T result = create();

        result.setCode(11);
        result.setNumber(24);

        return result;
    }

    protected abstract T create();
}

public class VehicleFactory extends AbstractVehicleFactory<Vehicle> {

    public static Vehicle makeResult(){
        return new VehicleFactory().makeVehicle();
    }

    @Override
    protected Vehicle makeVehicle() {
        Vehicle result = super.makeVehicle();
        return result;
    }

    @Override
    protected Vehicle create(){
        return new Vehicle();
    }
}

public class Vehicle1Factory extends AbstractVehicleFactory<Vehicle1> {

    public static Vehicle1 makeResult(){
        return new Vehicle1Factory().makeVehicle();
    }

    @Override
    protected Vehicle1 makeVehicle() {
        Vehicle1 result = super.makeVehicle();

        result.setEngine("V8");

        return result;
    }

    @Override
    protected Vehicle1 create(){
        return new Vehicle1();
    }
}


问:
facebook shareDialog when app is\isn't installed - weird behavior?
I'm using the ShareDialog of Facebook in order to share a printScreen image on facebook within my app.

When Facebook app is installed, it works alright.

When Facebook app isn't installed, it doesn't work. I see the "loading" screen and then it's disappeared and nothing happens.
The share dialog object reaches onError callback with the FacebookException:

```<code>{FacebookGraphResponseException: (#200) Requires extended permission: publish_actions httpResponseCode: 403, facebookErrorCode: 200, facebookErrorType: OAuthException, message: (#200) Requires extended permission: publish_actions}
</code>```

So do I really need "publish_actions" permission only for facebook web and not for facebook app? weird..

```<code>Facebook writes:
</code>```

https://developers.facebook.com/docs/sharing/android

```<code>"If the Facebook app is not installed it will automatically fallback to the web-based dialog"

"Now the SDK automatically checks for the native Facebook app. If it isn't installed, the SDK switches people to their default browser and opens the Feed Dialog."
</code>```

my code:

```<code>mShareDialog = new ShareDialog(mActivity);

    mShareDialog.registerCallback(callbackManager, new FacebookCallback<Sharer.Result>() {
        @Override
        public void onSuccess(Sharer.Result result) {}

        @Override
        public void onCancel() {}

        @Override
        public void onError(FacebookException error) {
            if (error != null) {
                showDialog("facebook app isn't installed");
            }
        }
    });

    if (ShareDialog.canShow(ShareLinkContent.class)) {

        // get a screenshot
        Bitmap image = getScreenshot();

        SharePhoto photo = new SharePhoto.Builder()
                .setBitmap(image)
                .setCaption(getResources().getString(R.string.shareBodyText))
                .build();

        SharePhotoContent content = new SharePhotoContent.Builder()
                .addPhoto(photo)
                .build();

        mShareDialog.show(content);
    }
</code>```

So why does it work when facebook app is installed without the "publish_actions" and doesn't work when facebook app isn't installed?

答:
It's a requirement of the SharePhotoContent, you must have installed the native faceboook app in order to share photos.

From Facebook Docs

Photos

People can share photos from your app to Facebook with the Share
Dialog or with a custom interface.

The photos must be less than 12MB in size

People need the native Facebook for Android app installed, version 7.0 or higher

Body:
I'm using the ShareDialog of Facebook in order to share a printScreen image on facebook within my app.

When Facebook app is installed, it works alright.

When Facebook app isn't installed, it doesn't work. I see the "loading" screen and then it's disappeared and nothing happens.
The share dialog object reaches onError callback with the FacebookException:

{FacebookGraphResponseException: (#200) Requires extended permission: publish_actions httpResponseCode: 403, facebookErrorCode: 200, facebookErrorType: OAuthException, message: (#200) Requires extended permission: publish_actions}

So do I really need "publish_actions" permission only for facebook web and not for facebook app? weird..

Facebook writes:

https://developers.facebook.com/docs/sharing/android

"If the Facebook app is not installed it will automatically fallback to the web-based dialog"

"Now the SDK automatically checks for the native Facebook app. If it isn't installed, the SDK switches people to their default browser and opens the Feed Dialog."

my code:

mShareDialog = new ShareDialog(mActivity);

    mShareDialog.registerCallback(callbackManager, new FacebookCallback<Sharer.Result>() {
        @Override
        public void onSuccess(Sharer.Result result) {}

        @Override
        public void onCancel() {}

        @Override
        public void onError(FacebookException error) {
            if (error != null) {
                showDialog("facebook app isn't installed");
            }
        }
    });

    if (ShareDialog.canShow(ShareLinkContent.class)) {

        // get a screenshot
        Bitmap image = getScreenshot();

        SharePhoto photo = new SharePhoto.Builder()
                .setBitmap(image)
                .setCaption(getResources().getString(R.string.shareBodyText))
                .build();

        SharePhotoContent content = new SharePhotoContent.Builder()
                .addPhoto(photo)
                .build();

        mShareDialog.show(content);
    }

So why does it work when facebook app is installed without the "publish_actions" and doesn't work when facebook app isn't installed?


答:
The problem is a downcasting problem. Think that you have X and Y parameter in Vehicle but addition Z parameter in Vehicle1. Vehicle1 have all 3 of them as its the daughter of Vehicle. When you cast it to Vehicle it just hides the reference of Z but when you cast Vehicle to Vehicle1 the casting problem occurs as the Z variable is not initialized for Vehicle1. </p>

<p>initialize the vehicle1 in method and set the parameters. as </p>

```<code>public class

    Vehicle1Factory extends VehicleFactory {

    protected static Vehicle1 makeResult(){
        Vehicle1 result = new Vehicle1();
        Vehicle veh = (Vehicle1) VehicleFactory.makeResult();
        result.setCode(veh.getCode);
        result.setNumber(veh.getNumber);
        return result;
    }
}
</code>```

Title: Reuse inheritance to define a method in Java

Body:
The problem is a downcasting problem. Think that you have X and Y parameter in Vehicle but addition Z parameter in Vehicle1. Vehicle1 have all 3 of them as its the daughter of Vehicle. When you cast it to Vehicle it just hides the reference of Z but when you cast Vehicle to Vehicle1 the casting problem occurs as the Z variable is not initialized for Vehicle1.

initialize the vehicle1 in method and set the parameters. as

public class

    Vehicle1Factory extends VehicleFactory {

    protected static Vehicle1 makeResult(){
        Vehicle1 result = new Vehicle1();
        Vehicle veh = (Vehicle1) VehicleFactory.makeResult();
        result.setCode(veh.getCode);
        result.setNumber(veh.getNumber);
        return result;
    }
}