text:
Q: Docker-Sync issue : Can't have simultaneous environments anymore since 0.4.2 Since I've updated my Docker-Sync version to 0.4.0, then 0.4.1 and 0.4.2, it's getting worse every time.
I tried to switch to navive_osx mode as told, and the sync didn't work with the 0.4.0. The logs were fine, but the sync didn't happen anymore. So I came back to the Unison sync strategy.
I've set the :nocopy statement instead of :rw in docker compose for the volumes as the changelog asked with the 0.4.1 with no improvement.
Now with the 0.4.2 I can't even launch the environment at the same time. Whenever I am launching in a new terminal the second one, everything is getting mixed up in the first docker-sync window as you can see :
ENV1_mysql | 2017-05-10T23:05:19.944798Z 0 [Note] Giving 2 client threads a chance to die gracefully
ENV1_mysql | 2017-05-10T23:05:19.944837Z 0 [Note] Shutting down slave threads
ENV1_redis | 1:signal-handler (1494457519) Received SIGTERM scheduling shutdown...
ENV1_redis | 1:M 10 May 23:05:19.959 # User requested shutdown...
ENV1_redis | 1:M 10 May 23:05:19.959 * Saving the final RDB snapshot before exiting.
ENV1_redis | 1:M 10 May 23:05:19.964 * DB saved on disk
ENV1_redis | 1:M 10 May 23:05:19.964 # Redis is now ready to exit, bye bye...
ENV1_job | 2017-05-10T23:05:20.074Z 1 TID-qhhnw ERROR: Error fetching job: Error connecting to Redis on redis:6379 (Errno::ECONNREFUSED)
ENV1_job | 2017-05-10T23:05:20.074Z 1 TID-qhhnw ERROR: /bundle/gems/redis-3.3.3/lib/redis/client.rb:345:in `rescue in establish_connection'
ENV1_job | 2017-05-10T23:05:20.074Z 1 TID-qhhnw ERROR: /bundle/gems/redis-3.3.3/lib/redis/client.rb:331:in `establish_connection'
ENV1_job | 2017-05-10T23:05:20.074Z 1 TID-qhhnw ERROR: /bundle/gems/redis-3.3.3/lib/redis/client.rb:101:in `block in connect'
ENV1_job | 2017-05-10T23:05:20.074Z 1 TID-qhhnw ERROR: /bundle/gems/redis-3.3.3/lib/redis/client.rb:293:in `with_reconnect'

(.... ENV1_job tons of log...)

ENV1_job | 2017-05-10T23:05:20.255Z 1 TID-qhiv8 ERROR: /bundle/gems/sidekiq-4.2.10/lib/sidekiq/processor.rb:88:in `get_one'
ENV1_job | 2017-05-10T23:05:20.256Z 1 TID-qhiv8 ERROR: /bundle/gems/sidekiq-4.2.10/lib/sidekiq/processor.rb:98:in `fetch'
ENV1_job | 2017-05-10T23:05:20.256Z 1 TID-qhiv8 ERROR: /bundle/gems/sidekiq-4.2.10/lib/sidekiq/processor.rb:81:in `process_one'
ENV1_job | 2017-05-10T23:05:20.256Z 1 TID-qhiv8 ERROR: /bundle/gems/sidekiq-4.2.10/lib/sidekiq/processor.rb:70:in `run'
ENV1_job | 2017-05-10T23:05:20.256Z 1 TID-qhiv8 ERROR: /bundle/gems/sidekiq-4.2.10/lib/sidekiq/util.rb:17:in `watchdog'
ENV1_job | 2017-05-10T23:05:20.256Z 1 TID-qhiv8 ERROR: /bundle/gems/sidekiq-4.2.10/lib/sidekiq/util.rb:26:in `block in safe_thread'
ENV1_redis exited with code 0
ENV2_redis | 1:C 10 May 23:05:21.731 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
ENV2_redis |                 _._
ENV2_redis |            _.-``__ ''-._
ENV2_redis |       _.-``    `.  `_.  ''-._           Redis 3.2.8 (00000000/0) 64 bit
ENV2_redis |   .-`` .-```.  ```\/    _.,_ ''-._
ENV2_redis |  (    '      ,       .-`  | `,    )     Running in standalone mode
ENV2_redis |  |`-._`-...-` __...-.``-._|'` _.-'|     Port: 6379
ENV2_redis |  |    `-._   `._    /     _.-'    |     PID: 1
ENV2_redis |   `-._    `-._  `-./  _.-'    _.-'
ENV2_redis |  |`-._`-._    `-.__.-'    _.-'_.-'|
ENV2_redis |  |    `-._`-._        _.-'_.-'    |           http://redis.io
ENV2_redis |   `-._    `-._`-.__.-'_.-'    _.-'
ENV2_redis |  |`-._`-._    `-.__.-'    _.-'_.-'|
ENV2_redis |  |    `-._`-._        _.-'_.-'    |
ENV2_redis |   `-._    `-._`-.__.-'_.-'    _.-'
ENV2_redis |       `-._    `-.__.-'    _.-'
ENV2_redis |           `-._        _.-'
ENV2_redis |               `-.__.-'
ENV2_redis |
ENV2_redis | 1:M 10 May 23:05:21.735 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
ENV2_redis | 1:M 10 May 23:05:21.735 # Server started, Redis version 3.2.8
ENV2_redis | 1:M 10 May 23:05:21.735 # WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled.
ENV2_redis | 1:M 10 May 23:05:21.740 * DB loaded from disk: 0.004 seconds
ENV2_redis | 1:M 10 May 23:05:21.740 * The server is now ready to accept connections on port 6379
ENV1_mysql | 2017-05-10T23:05:21.946243Z 0 [Note] Forcefully disconnecting 2 remaining clients
ENV1_mysql | 2017-05-10T23:05:21.946330Z 0 [Warning] mysqld: Forcing close of thread 4  user: 'root'
ENV1_mysql |
ENV1_mysql | 2017-05-10T23:05:21.946665Z 0 [Warning] mysqld: Forcing close of thread 3  user: 'root'
ENV1_mysql |
ENV1_mysql | 2017-05-10T23:05:21.947247Z 0 [Note] Event Scheduler: Purging the queue. 0 events
ENV1_mysql | 2017-05-10T23:05:21.947988Z 0 [Note] Binlog end
ENV1_mysql | 2017-05-10T23:05:21.962498Z 0 [Note] Shutting down plugin 'ngram'
ENV1_mysql | 2017-05-10T23:05:21.962585Z 0 [Note] Shutting down plugin 'BLACKHOLE'
ENV1_mysql | 2017-05-10T23:05:21.962606Z 0 [Note] Shutting down plugin 'partition'
ENV1_mysql | 2017-05-10T23:05:21.962623Z 0 [Note] Shutting down plugin 'ARCHIVE'
ENV1_mysql | 2017-05-10T23:05:21.962639Z 0 [Note] Shutting down plugin 'INNODB_SYS_VIRTUAL'
ENV1_mysql | 2017-05-10T23:05:21.962668Z 0 [Note] Shutting down plugin 'INNODB_SYS_DATAFILES'
ENV1_mysql | 2017-05-10T23:05:21.962682Z 0 [Note] Shutting down plugin 'INNODB_SYS_TABLESPACES'
ENV1_mysql | 2017-05-10T23:05:21.962710Z 0 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN_COLS'
ENV1_mysql | 2017-05-10T23:05:21.962733Z 0 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN'
ENV1_mysql | 2017-05-10T23:05:21.962747Z 0 [Note] Shutting down plugin 'INNODB_SYS_FIELDS'
ENV1_mysql | 2017-05-10T23:05:21.962778Z 0 [Note] Shutting down plugin 'INNODB_SYS_COLUMNS'
ENV1_mysql | 2017-05-10T23:05:21.962791Z 0 [Note] Shutting down plugin 'INNODB_SYS_INDEXES'
ENV1_mysql | 2017-05-10T23:05:21.962804Z 0 [Note] Shutting down plugin 'INNODB_SYS_TABLESTATS'
ENV1_mysql | 2017-05-10T23:05:21.962822Z 0 [Note] Shutting down plugin 'INNODB_SYS_TABLES'
ENV1_mysql | 2017-05-10T23:05:21.962835Z 0 [Note] Shutting down plugin 'INNODB_FT_INDEX_TABLE'
ENV1_mysql | 2017-05-10T23:05:21.962875Z 0 [Note] Shutting down plugin 'INNODB_FT_INDEX_CACHE'
ENV1_mysql | 2017-05-10T23:05:21.962886Z 0 [Note] Shutting down plugin 'INNODB_FT_CONFIG'
ENV1_mysql | 2017-05-10T23:05:21.962896Z 0 [Note] Shutting down plugin 'INNODB_FT_BEING_DELETED'
ENV1_mysql | 2017-05-10T23:05:21.962904Z 0 [Note] Shutting down plugin 'INNODB_FT_DELETED'
ENV1_mysql | 2017-05-10T23:05:21.962914Z 0 [Note] Shutting down plugin 'INNODB_FT_DEFAULT_STOPWORD'
ENV1_mysql | 2017-05-10T23:05:21.962924Z 0 [Note] Shutting down plugin 'INNODB_METRICS'
ENV1_mysql | 2017-05-10T23:05:21.962937Z 0 [Note] Shutting down plugin 'INNODB_TEMP_TABLE_INFO'
ENV1_mysql | 2017-05-10T23:05:21.962985Z 0 [Note] Shutting down plugin 'INNODB_BUFFER_POOL_STATS'
ENV1_mysql | 2017-05-10T23:05:21.962997Z 0 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE_LRU'
ENV1_mysql | 2017-05-10T23:05:21.963007Z 0 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE'
ENV1_mysql | 2017-05-10T23:05:21.963016Z 0 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX_RESET'
ENV1_mysql | 2017-05-10T23:05:21.963045Z 0 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX'
ENV1_mysql | 2017-05-10T23:05:21.963054Z 0 [Note] Shutting down plugin 'INNODB_CMPMEM_RESET'
ENV1_mysql | 2017-05-10T23:05:21.963063Z 0 [Note] Shutting down plugin 'INNODB_CMPMEM'
ENV1_mysql | 2017-05-10T23:05:21.963071Z 0 [Note] Shutting down plugin 'INNODB_CMP_RESET'
ENV1_mysql | 2017-05-10T23:05:21.963081Z 0 [Note] Shutting down plugin 'INNODB_CMP'
ENV1_mysql | 2017-05-10T23:05:21.963094Z 0 [Note] Shutting down plugin 'INNODB_LOCK_WAITS'
ENV1_mysql | 2017-05-10T23:05:21.963128Z 0 [Note] Shutting down plugin 'INNODB_LOCKS'
ENV1_mysql | 2017-05-10T23:05:21.963149Z 0 [Note] Shutting down plugin 'INNODB_TRX'
ENV1_mysql | 2017-05-10T23:05:21.963163Z 0 [Note] Shutting down plugin 'InnoDB'
ENV1_mysql | 2017-05-10T23:05:21.963427Z 0 [Note] InnoDB: FTS optimize thread exiting.
ENV1_mysql | 2017-05-10T23:05:21.963841Z 0 [Note] InnoDB: Starting shutdown...
ENV1_mysql | 2017-05-10T23:05:22.066175Z 0 [Note] InnoDB: Dumping buffer pool(s) to /var/lib/mysql/ib_buffer_pool
ENV1_mysql | 2017-05-10T23:05:22.070328Z 0 [Note] InnoDB: Buffer pool(s) dump completed at 170510 23:05:22
ENV1_job | 2017-05-10T23:05:23.069Z 1 TID-qhjgc ERROR: heartbeat: getaddrinfo: Name or service not known
ENV1_mysql | 2017-05-10T23:05:23.495794Z 0 [Note] InnoDB: Shutdown completed; log sequence number 209478342
ENV1_mysql | 2017-05-10T23:05:23.497199Z 0 [Note] InnoDB: Removed temporary tablespace data file: "ibtmp1"
ENV1_mysql | 2017-05-10T23:05:23.497241Z 0 [Note] Shutting down plugin 'MRG_MYISAM'
ENV1_mysql | 2017-05-10T23:05:23.497249Z 0 [Note] Shutting down plugin 'MyISAM'
ENV1_mysql | 2017-05-10T23:05:23.497259Z 0 [Note] Shutting down plugin 'CSV'
ENV1_mysql | 2017-05-10T23:05:23.497263Z 0 [Note] Shutting down plugin 'MEMORY'
ENV1_mysql | 2017-05-10T23:05:23.497268Z 0 [Note] Shutting down plugin 'PERFORMANCE_SCHEMA'
ENV1_mysql | 2017-05-10T23:05:23.497629Z 0 [Note] Shutting down plugin 'sha256_password'
ENV1_mysql | 2017-05-10T23:05:23.497651Z 0 [Note] Shutting down plugin 'mysql_native_password'
ENV1_mysql | 2017-05-10T23:05:23.497987Z 0 [Note] Shutting down plugin 'binlog'
ENV1_mysql | 2017-05-10T23:05:23.501084Z 0 [Note] mysqld: Shutdown complete
ENV1_mysql |
ENV1_mysql exited with code 0
ENV1_job | 2017-05-10T23:05:25.488Z 1 TID-5ccjc INFO: Shutting down
ENV1_job | 2017-05-10T23:05:25.488Z 1 TID-5ccjc INFO: Terminating quiet workers
ENV1_job | 2017-05-10T23:05:25.488Z 1 TID-qhjas INFO: Scheduler exiting...
ENV1_job | 2017-05-10T23:05:25.989Z 1 TID-5ccjc INFO: Pausing to allow workers to finish...
ENV2_sql | 2017-05-10T23:05:26.401023Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
ENV2_sql | 2017-05-10T23:05:26.407562Z 0 [Note] mysqld (mysqld 5.7.18) starting as process 1 ...
ENV2_sql | 2017-05-10T23:05:26.413174Z 0 [Warning] Setting lower_case_table_names=2 because file system for /var/lib/mysql/ is case insensitive
ENV2_sql | 2017-05-10T23:05:26.417101Z 0 [Note] InnoDB: PUNCH HOLE support available
ENV2_sql | 2017-05-10T23:05:26.417219Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
ENV2_sql | 2017-05-10T23:05:26.417228Z 0 [Note] InnoDB: Uses event mutexes
ENV2_sql | 2017-05-10T23:05:26.417615Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier
ENV2_sql | 2017-05-10T23:05:26.417853Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.3
ENV2_sql | 2017-05-10T23:05:26.417876Z 0 [Note] InnoDB: Using Linux native AIO
ENV2_sql | 2017-05-10T23:05:26.419199Z 0 [Note] InnoDB: Number of pools: 1
ENV2_sql | 2017-05-10T23:05:26.420183Z 0 [Note] InnoDB: Using CPU crc32 instructions
ENV2_sql | 2017-05-10T23:05:26.424034Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M
ENV2_sql | 2017-05-10T23:05:26.439491Z 0 [Note] InnoDB: Completed initialization of buffer pool
ENV2_sql | 2017-05-10T23:05:26.441642Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().
ENV2_sql | 2017-05-10T23:05:26.506532Z 0 [Note] InnoDB: Highest supported file format is Barracuda.
ENV2_sql | 2017-05-10T23:05:26.849378Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables
ENV2_sql | 2017-05-10T23:05:26.852156Z 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
ENV2_sql | 2017-05-10T23:05:26.941263Z 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
ENV2_sql | 2017-05-10T23:05:26.949972Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active.
ENV2_sql | 2017-05-10T23:05:26.950017Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active.
ENV2_sql | 2017-05-10T23:05:26.950423Z 0 [Note] InnoDB: Waiting for purge to start
ENV2_sql | 2017-05-10T23:05:27.001600Z 0 [Note] InnoDB: 5.7.18 started; log sequence number 33405165
ENV2_sql | 2017-05-10T23:05:27.001924Z 0 [Note] Plugin 'FEDERATED' is disabled.
ENV2_sql | 2017-05-10T23:05:27.004603Z 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
ENV2_sql | 2017-05-10T23:05:27.133456Z 0 [Note] Found ca.pem, server-cert.pem and server-key.pem in data directory. Trying to enable SSL support using them.
ENV2_sql | 2017-05-10T23:05:27.165752Z 0 [Warning] CA certificate ca.pem is self signed.
ENV2_sql | 2017-05-10T23:05:27.171471Z 0 [Note] Server hostname (bind-address): '*'; port: 3306
ENV2_sql | 2017-05-10T23:05:27.171547Z 0 [Note] IPv6 is available.
ENV2_sql | 2017-05-10T23:05:27.171563Z 0 [Note]   - '::' resolves to '::';
ENV2_sql | 2017-05-10T23:05:27.171613Z 0 [Note] Server socket created on IP: '::'.
ENV2_sql | 2017-05-10T23:05:27.231101Z 0 [Note] InnoDB: Buffer pool(s) load completed at 170510 23:05:27
ENV2_sql | 2017-05-10T23:05:27.299944Z 0 [Warning] 'user' entry 'root@localhost' ignored in --skip-name-resolve mode.
ENV2_sql | 2017-05-10T23:05:27.300034Z 0 [Warning] 'user' entry 'mysql.sys@localhost' ignored in --skip-name-resolve mode.
ENV2_sql | 2017-05-10T23:05:27.304521Z 0 [Warning] 'db' entry 'sys mysql.sys@localhost' ignored in --skip-name-resolve mode.
ENV2_sql | 2017-05-10T23:05:27.305993Z 0 [Warning] 'proxies_priv' entry '@ root@localhost' ignored in --skip-name-resolve mode.
ENV2_sql | 2017-05-10T23:05:27.420660Z 0 [Warning] 'tables_priv' entry 'sys_config mysql.sys@localhost' ignored in --skip-name-resolve mode.
ENV1_job | 2017-05-10T23:05:27.494Z 1 TID-5ccjc INFO: Bye!
ENV2_sql | 2017-05-10T23:05:27.788719Z 0 [Note] Event Scheduler: Loaded 0 events
ENV2_sql | 2017-05-10T23:05:27.790225Z 0 [Note] mysqld: ready for connections.
ENV2_sql | Version: '5.7.18'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server (GPL)
ENV2_sql | 2017-05-10T23:05:27.790320Z 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.
ENV2_sql | 2017-05-10T23:05:27.790330Z 0 [Note] Beginning of list of non-natively partitioned tables
ENV1_job exited with code 0
ENV2_sql | 2017-05-10T23:05:28.588345Z 0 [Note] End of list of non-natively partitioned tables
ENV2_job | 2017-05-10T23:05:32.681Z 1 TID-afb0o INFO: Running in ruby 2.4.1p111 (2017-03-22 revision 58053) [x86_64-linux]
ENV2_job | 2017-05-10T23:05:32.681Z 1 TID-afb0o INFO: See LICENSE and the LGPL-3.0 for licensing details.
ENV2_job | 2017-05-10T23:05:32.681Z 1 TID-afb0o INFO: Upgrade to Sidekiq Pro for more features and support: http://sidekiq.org
ENV2_job | 2017-05-10T23:05:32.682Z 1 TID-afb0o INFO: Booting Sidekiq 4.2.10 with redis options {:url=>"redis://redis:6379"}
ENV2_job | 2017-05-10T23:05:32.690Z 1 TID-afb0o INFO: Starting processing, hit Ctrl-C to stop
ENV2_web | The Gemfile's dependencies are satisfied
ENV2_web | => Booting Puma
ENV2_web | => Rails 5.1.0.rc2 application starting in development on http://0.0.0.0:3000
ENV2_web | => Run `rails server -h` for more startup options
ENV2_web | Puma starting in single mode...
ENV2_web | * Version 3.8.2 (ruby 2.4.1-p111), codename: Sassy Salamander
ENV2_web | * Min threads: 5, max threads: 5
ENV2_web | * Environment: development
ENV2_web | * Listening on tcp://0.0.0.0:3000
ENV2_web | Use Ctrl-C to stop
An HTTP request took too long to complete. Retry with --verbose to obtain debug information.
If you encounter this issue regularly because of slow network conditions, consider setting COMPOSE_HTTP_TIMEOUT to a higher value (current value: 60).
EXCEPTION: #<Docker::Compose::Error: 'up' failed with status 'pid 77888 exit 1': Attaching to ENV1_mysql, ENV1_redis, ENV1_web, ENV1_job>
MESSAGE: 'up' failed with status 'pid 77888 exit 1': Attaching to ENV1_mysql, ENV1_redis, ENV1_web, ENV1_job

And everything shuts down.
ENV1 configuration:
Docker-compose
version: '2'
services:
  db:
    container_name: env1_mysql
    image: mysql
    volumes:
      - ./data/sql:/var/lib/mysql
    ports:
      - "3306:3306"
    environment:
      MYSQL_DATABASE: dev
      MYSQL_USER: rails
      MYSQL_PASSWORD: rails
      MYSQL_ROOT_PASSWORD: root

  redis:
    container_name: env1_redis
    image: redis
    ports:
      - "6379:6379"
    volumes:
      - ./data/redis:/data

  web:
    container_name: env1_web
    build: .
    command: sh scripts/start-dev.sh
    volumes:
      - /etc/localtime:/etc/localtime:ro
      - env1-web-sync:/app:nocopy
      - env1-bundle-sync:/bundle:nocopy
      # - env1-static-sync:/static:ro
    ports:
      - "3030:3030"
    environment:
      REDIS_URL: redis://redis:6379
      DB_USER: rails
      DB_PASSWORD: rails
    links:
      - db
      - redis
    tty: true
    stdin_open: true

  job:
    container_name: env1_job
    build: .
    command: bundle exec sidekiq -C config/sidekiq.yml
    volumes:
      - env1-web-sync:/app:nocopy
      - env1-bundle-sync:/bundle:nocopy
    environment:
      REDIS_URL: redis://redis:6379
    links:
      - db
      - redis

volumes:
  env1-web-sync:
    external: true
  env1-bundle-sync:
    external: true

Docker-sync
version: '2'
options:
  compose-file-path: 'docker-compose.yml'
syncs:
  env1-web-sync:
    src: './ENV1'
    sync_strategy: 'unison'
    sync_excludes: [ '.git', '.idea', 'tmp/*' ]
  env1-bundle-sync:
    src: './bundle'
    sync_strategy: 'unison'

ENV2 configuration:
Docker-compose
version: '2'
services:
  db:
    container_name: env2_sql
    image: mysql
    volumes:
      - ./data/sql:/var/lib/mysql
    ports:
      - "3307:3306"
    environment:
      MYSQL_DATABASE: dev
      MYSQL_USER: rails
      MYSQL_PASSWORD: rails
      MYSQL_ROOT_PASSWORD: root

  redis:
    container_name: env2_redis
    image: redis
    ports:
      - "6380:6379"
    volumes:
      - ./data/redis:/data

  web:
    container_name: env2_web
    build: .
    command: sh scripts/start-dev.sh
    volumes:
      - env2-web-sync:/app:nocopy
      - env2-bundle-sync:/bundle:nocopy
      - env2-static-sync:/static:nocopy
    ports:
      - "3000:3000"
    environment:
      REDIS_URL: redis://redis:6379
      MYSQL_USER: rails
      MYSQL_PASSWORD: rails
    links:
      - db
      - redis
    tty: true
    stdin_open: true

  java:
    container_name: env2_java
    image: java:openjdk-8
    volumes:
      - env2-java-sync:/app:nocopy
    links:
      - db
    tty: true
    stdin_open: true

  job:
    container_name: env2_job
    build: .
    command: bundle exec sidekiq -C config/sidekiq.yml
    volumes:
      - env2-web-sync:/app:nocopy
      - env2-bundle-sync:/bundle:nocopy
    environment:
      REDIS_URL: redis://redis:6379
    links:
      - db
      - redis

volumes:
  env2-web-sync:
    external: true
  env2-bundle-sync:
    external: true
  env2-static-sync:
    external: true
  env2-java-sync:
    external: true

Docker-sync:
version: "2"
options:
  compose-file-path: 'docker-compose.yml'
syncs:
  env2-web-sync:
    src: './ENV2'
    sync_strategy: 'unison'
    sync_excludes: [ '.git', '.idea', 'tmp/*' ]
  env2-bundle-sync:
    src: './bundle'
    sync_strategy: 'unison'
  env2-static-sync:
    src: '../static'
    sync_strategy: 'unison'
  env2-java-sync:
    src: './java'
    sync_strategy: 'unison'

A: please upgrade to 0.4.5, this should fix your issues. Reconsider native_osx - its generally a lot better then the old unison way, especially with regard on CPU usage.
In any way, check your sync_excludes syntax, since "Name" is used by default, 'tmp/*' is wrong. Either use tmp or use
https://github.com/EugenMayer/docker-sync/blob/master/example/docker-sync.yml#L75
sync_excludes_type: 'none'
sync_excludes: [ 'Name .git', 'Path .idea', 'Path tmp' ]

0.4.x was quiet a hard ride, i understand your frustration, see https://github.com/EugenMayer/docker-sync/issues/370 for the background story


text:
Q: Styling the google maps api window I did some changes to our app within the map by switching out our normal generic icons, to smaller icons (that look quite nice). However my new icons aren't as tall as my old ones, and so when I select a new icon, the window that I have associated with it is sitting too high.
I'm having a tough time styling my window so that it rests lower towards the icon.
(see image)
I'm using the angular, and trying to find something in these docs. http://angular-ui.github.io/angular-google-maps/#!/api/window
my code looks like
%ui-gmap-window{ show: '$ctrl.selectedLocation', coords: "$ctrl.selectedLocation", options: '$ctrl.windowOptions', closeClick: '$ctrl.closeClick()' }

And thats all I really need to show as it selects the location that I need and then displays the window.
Is there a way to style that at all?

A: If we read the API docs starting with the link you gave: http://angular-ui.github.io/angular-google-maps/#!/api/window we see the options parameter. It's description:

Additional options to pass to the InfoWindow. See InfoWindowOptions.

If we follow that link we find an option called pixelOffset. It's description:

Type:  Size
The offset, in pixels, of the tip of the info window from the point on the map at whose geographical coordinates the info window is anchored. If an InfoWindow is opened with an anchor, the pixelOffset will be calculated from the anchor's anchorPoint property.

So the answer to your question is: yes, if we read the docs.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is __slots__ behaving differently in Python 2 and 3 when inheriting from an abstract base class I created the following class to store changeable points on a plane in a memory-efficient manner - I need a mutable equivalent of namedtuple('Point', 'x y'). Since instance dictionaries are big, I thought I'd go for __slots__:
from collections import Sequence

class Point(Sequence):
    __slots__ = ('x', 'y')

    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

    def __getitem__(self, item):
        return getattr(self, self.__slots__[item])

    def __setitem__(self, item, value):
        return setattr(self, self.__slots__[item], value)

    def __repr__(self):
        return 'Point(x=%r, y=%r)' % (self.x, self.y)

    def __len__(self):
        return 2

When testing it on Python 3, everything seemed to be OK:
>>> pt = Point(12, 42)
>>> pt[0], pt.y
(12, 42)
>>> pt.x = 5
>>> pt
Point(x=5, y=42)
>>> pt.z = 6
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Point' object has no attribute 'z'

However on Python 2, I can set the attribute z even when it is not in slots:
>>> pt = Point(12, 42)
>>> pt.z = 5
>>> pt.z
5
>>> pt.__slots__
('x', 'y')
>>> pt.__dict__
{'z': 5}

Why is that so, and why the difference between Python 2 and Python 3?

A: The Python 2 data model says the following on __slots__:

*

*When inheriting from a class without __slots__, the __dict__ attribute of that class will always be accessible, so a __slots__ definition in the subclass is meaningless.

And that is what is happening here. In Python 2 the abstract base classes in the collections module did not have the __slots__ at all:
>>> from collections import Sequence
>>> Sequence.__slots__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'Sequence' has no attribute '__slots__'

This was reported as the issue 11333 in CPython issue tracker, and was fixed in Python 3.3.
In Python 3.3+ the Sequence abstract base class now has __slots__ set to an empty tuple:
>>> from collections import Sequence
>>> Sequence.__slots__
()

Thus in Python 2, you cannot inherit from a collections base class and have memory efficient storage with __slots__ at the same time.

Note however that even though the documentation on collections abstract base classes claims that

These ABCs allow us to ask classes or instances if they provide particular functionality, for example:
size = None
if isinstance(myvar, collections.Sized):
    size = len(myvar)

This is not the case with Sequence; simply implementing all the methods required by the Sequence does not make instances of your class to pass the isinstance check.
The reason for that is that the Sequence class does not have a __subclasshook__; and in its absence, the parent class __subclasshook__ is consulted instead; in this case Sized.__subclasshook__; and that returns NotImplemented if the tested-against class wasn't exactly Sized.
On the other hand, one couldn't distinguish between a mapping type and a sequence type by the magic methods, as both of them can have the exactly same magic methods - of collections.OrderedDict has all the magic methods of a Sequence, including the __reversed__ method, yet it isn't a sequence.
However, you still do not need to inherit from Sequence to make isinstance(Point, Sequence) return True. In the following example, the Point is the same, except derived from object instead of Sequence, on Python 2:
>>> pt = Point(12, 42)
>>> pt.z = 5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Point' object has no attribute 'z'
>>> isinstance(pt, Sequence)
False
>>> Sequence.register(pt)
>>> isinstance(pt, Sequence)
True

You can register any class as a subclass of the abstract base class for the purpose of isinstance checks; and of the extra mix-in methods, you really need to implement only count and index; the functionality for others will be filled in by Python runtime.


text:
Q: Rails routes for cms cms powered site I've been away from Rails for a while but I have a site that is running on rails where I have created a page editor. I need some help with my routes.
I want to have something like this for my URL on the front end of the site:
//domain/welcome/pagename/page or //domain/welcome/page/pagename
Then within the welcome_controller I have this:
def page
# I provide the user with the a page
@mypage = Contents.find_by_name(params[:pagename])
end

Then within the page view itself I can render aspects of the @mypage record as I see fit.
However, I need some help with the routes to get this all working the way I intend.
Currently, I have this for my welcome route:
  resources :welcome do
     collection do
        get :site
        get :home
        get :page
        get :thankyou
        post :newslettersignup
        post :sendcontact
      end
    end

I know that I need more... Just now sure exactly what it should be.
Any help would greatly be appreciated!

A: You can use non-resourceful routing to do this easily:
get '/welcome/:pagename/site', to: 'welcome#site'
get '/welcome/:pagename/home', to: 'welcome#home'
get '/welcome/:pagename/page', to: 'welcome#page'
get '/welcome/:pagename/thankyou', to: 'welcome#thankyou'
post '/welcome/:pagename/newslettersignup', to: 'welcome#newslettersignup'
post '/welcome/:pagename/sendcontact', to: 'welcome#sendcontact'

The :pagename syntax allows the value of that segment of the URL to be included in params[:pagename]. The to: 'welcome#site' bit means, "Route this to the WelcomeController#site action."
Please see Rails Routing from the Outside In for a great reference when working with routes.


text:
Q: Creating nested dynamic components in angular I Want to know how to create nested dynamic components and maintains its parent child relationship.
For example, I have data like this,
- A
--A.1
--A.2
-B
--B.1
-C

I wanted to create the component like this,

   <A1></A1>
   <A2></A2>

   <B1></B1>

<C></C>

But with my code I could only create parent component or child component. But not both.
Below is my code,
  setRootViewContainerRef(view: ViewContainerRef): void {
    this.rootViewContainer = view;
  }

  createComponent(content: any, type: any) {
 console.log(content);
    if (content.child && content.child.length > 0) {
      content.child.forEach(type => {
        const typeP = this.contentMappings[type.type];
        this.createComponent(type, typeP);
      });
    } else {
      this.renderComp(content,type)
    }
  }

  renderComp(content,type) {
    if (!type) {
      return
    }
    this.componentFactory = this.componentFactoryResolver.resolveComponentFactory(type);
    this.componentReference = this.rootViewContainer.createComponent(this.componentFactory);

    if (this.componentReference.instance.contentOnCreate) {
      this.componentReference.instance.contentOnCreate(content);
    }
  }

With this code, I get this output.

Link to working example, StackBlitz
Please help me to resolve this issue.

Updated.
Even after adding the viewChild, It still throws the viewchild not defined.
Refer this image, In the component.instance I'm not seeing the view child element.

Updated stackblitz link https://stackblitz.com/edit/angular-dynamic-new-mepwch?file=src/app/content/a/a.component.ts

A: You should create ViewContainer on each level that is going to render child components:
a.component.html

a works!

<ng-container #container></ng-container>

a.component.ts
export class AComponent implements OnInit {
  @ViewChild('container', { read: ViewContainerRef, static: true }) embeddedContainer: ViewContainerRef;

And then render component to dedicated container:
create-dynamic-component.service.ts
@Injectable()
export class CreateDynamicComponentService {
  constructor(
    private componentFactoryResolver: ComponentFactoryResolver,
    @Inject(CONTENT_MAPPINGS) private contentMappings: any,
    private inlineService: InlineService
  ) { }

  createComponent(content: any, type: any, vcRef) {
    const componentRef = this.renderComp(content, type, vcRef)
    if (content.child && content.child.length) {
      if (!componentRef.instance.embeddedContainer) {
        const cmpName = componentRef.instance.constructor.name;
        throw new TypeError(`Trying to render embedded content. ${cmpName} must have @ViewChild() embeddedContainer defined`);
      }

       content.child.forEach(type => {
        const typeP = this.contentMappings[type.type];
        this.createComponent(type, typeP, componentRef.instance.embeddedContainer);
      });
    }
  }

  renderComp(content,type, vcRef: ViewContainerRef) {
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(type);
    const componentRef = vcRef.createComponent<any>(componentFactory);

    if (componentRef.instance.contentOnCreate) {
      componentRef.instance.contentOnCreate(content);
    }

    return componentRef;
  }
}

Note how renderComp method takes ViewContainerRef from the component with children:
 this.createComponent(type, typeP, componentRef.instance.embeddedContainer);

Forked Stackblitz


text:
Q: Python line profiler results inconsistent Why is it that python code runs at drastically different speeds despite being the same code run twice?
Code
I was doing some profiling for a short Python code:
import urllib3

@profile
def download(url, file_path):
    http = urllib3.PoolManager()
    r = http.request("GET", url)
    print("FINISHED GET!")
    print("WRITING TO "+file_path)
    with open(file_path, "wb") as f:
        f.write(r.data)
    r.release_conn()

url = "http://interactivepaper.todayonline.com/jrsrc/260516/260516.pdf"

download(url, "")

Testing
I am using line_profiler with the command kernprof -l -v test.py. I tested this code multiple times and all the results are inconsistent.
Test 1:
FINISHED GET!
WRITING TO
Wrote profile results to test.py.lprof
Timer unit: 1e-06 s

Total time: 44.653 s
File: test.py
Function: download at line 3

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     3                                           @profile
     4                                           def download(url, file_path):
     5         1          273    273.0      0.0      http = urllib3.PoolManager()
     6         1     44652667 44652667.0    100.0      r = http.request("GET", url)
     7         1           37     37.0      0.0      print("FINISHED GET!")
     8         1            4      4.0      0.0      print("WRITING TO "+file_path)
     9         1           29     29.0      0.0      with open(file_path, "wb") as f:
    10                                                   f.write(r.data)
    11                                               r.release_conn()
(There was an IO Error from here onwards as I used an empty string)

Test 2 (I edited the code):
FINISHED GET!
WRITING TO
Wrote profile results to test.py.lprof
Timer unit: 1e-06 s

Total time: 44.6693 s
File: test.py
Function: download at line 3

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     3                                           @profile
     4                                           def download(url, file_path):
     5         1          186    186.0      0.0      http = urllib3.PoolManager()
     6         1     44669082 44669082.0    100.0      r = http.request("GET", url)
     7         1           42     42.0      0.0      print("FINISHED GET!")
     8         1            4      4.0      0.0      print("WRITING TO "+file_path)

Test 3:
FINISHED GET!
WRITING TO
Wrote profile results to test.py.lprof
Timer unit: 1e-06 s

Total time: 4.53504 s
File: test.py
Function: download at line 3

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     3                                           @profile
     4                                           def download(url, file_path):
     5         1          262    262.0      0.0      http = urllib3.PoolManager()
     6         1      4534736 4534736.0    100.0      r = http.request("GET", url)
     7         1           37     37.0      0.0      print("FINISHED GET!")
     8         1            4      4.0      0.0      print("WRITING TO "+file_path)

This is the part that I found confusing. A process that took 44s to run at first now takes 4s to run. I also noted that whenever I edited the file, it would take a long time to run again. Here are three more tests proving my point:
First test after edit:
Wrote profile results to test.py.lprof
Timer unit: 1e-06 s

Total time: 49.7018 s
File: test.py
Function: download at line 3

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     3                                           @profile
     4                                           def download(url, file_path):
     5         1          187    187.0      0.0      http = urllib3.PoolManager()
     6         1     49701585 49701585.0    100.0      r = http.request("GET", url)

Second test after edit:
Timer unit: 1e-06 s

Total time: 9.10985 s
File: test.py
Function: download at line 3

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     3                                           @profile
     4                                           def download(url, file_path):
     5         1          185    185.0      0.0      http = urllib3.PoolManager()
     6         1      9109665 9109665.0    100.0      r = http.request("GET", url)

Third test after edit (its similar to second test):
Wrote profile results to test.py.lprof
Timer unit: 1e-06 s

Total time: 12.9593 s
File: test.py
Function: download at line 3

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     3                                           @profile
     4                                           def download(url, file_path):
     5         1          189    189.0      0.0      http = urllib3.PoolManager()
     6         1     12959072 12959072.0    100.0      r = http.request("GET", url)

A: The major difference is in the following line of code:
r = http.request("GET", url)

In this line you are trying to access remote web server.
The following reasons might result with different access time to the Web Server:
1) Caching
2) Network load
3) Remote server load


text:
Q: Is there a way to slowdown mysql query for lower cpu usage? I am ordering INT rows by DESC on a table with 300k rows and selecting @rownum:=@rownum+1 to update the same row's RANK field.
It works perfectly but takes a long time. I can accept the longer time, but can i somewhat let it sleep to give some free space to CPU to make the other jobs?
Like putting sleep(0.25 sec) in a while(1>0) loop...
UPDATE:
SET @rownum=0;
update user u, (SELECT @rownum:=@rownum+1 as rank, id FROM user u order by score DESC) as bb SET u.rank=bb.rank WHERE u.id=bb.id

A: I would probably create a temp table with autoincrement ID to do this.  You could then INSERT ... SELECT the sorted values into the temp table to generate the rank sequence.  Then you could update the original table across a join.

A: No. You can have some minor influence on priority with the insert delayed statement, by adding low_priority to an update, or by adding high_priority to a select. This only affects some queueing with table locks in storage engines using them. You cannot however have more granular control than that. It shouldn't be that way either, since the DBMS will balance itself internally, and one slow query should never make another query MUCH slower. If by 'other jobs' you mean other tasks on the same server, you could just ionice or nice the entire mysqld process.
Having answered the actual question, your query is probably this slow because it misses an index on the field you're sorting by, as such triggering filesort and temporary flags on the execution plan. Fixing that might make the whole point moot.


text:
Q: Component to HTML I know this question may be a bit weird, so let me describe my problem.
In a project I use Primefaces with JSF2leaf in one view. I add few markers to the map,
and I need to add 2 buttons to popup window. The popup opens when I click on the marker, and I add markers in this way:
placesLayer.addMarker(new Marker(new LatLong("42.120286","-72.547488"),"Hospital
Dr. Hibbert lol"));

Last parameter is a HTML String. I need to add commandButton to popup. Normally I would do something like this:
<h:commandButton value="#{msgs['action.details']}"
 action="#{mBean.goToDetailElementPage(hBean.selectedElement)}"
 rendered="#{secBean.isUserInGroup('SUPER_USER')}"/>

But of course it's not possible if I want to add buttons to JSF2leaf popups, because I need HTML there.
I don't think it's possible, but I'm not JSF/PrimeFaces expert, so maybe someone has any suggestions or ideas?


text:
Q: Bootstrap Popover is not working on last row I am using Bootstrap popover. It doesn't show on last row.
I am using jquery each function to loop.
Here is the code:
HTML:

JS:

var table = $('#Tableid');
var hostId = 1;
var count = 0;
var row = $('

').addClass('test');
for(var i=0; i<10; i++){

    for(j=0; j<3; j++){

        var button = "<button data-content = \""+hostId+"\" data-id=\""+hostId+"\"class=\"btn btn-primary btn-lg open-InfoModal\" data-toggle=\"modal\" rel=\"popover\" data-target=\"#hostInfo\" href=\"#infoModal\"></button>";
           $("[rel='popover']").popover({trigger: "hover"});

        var cell = $(''+hostId+'	').addClass('test').wrapInner(button);    //We use wrapInner to add HTML content
        hostId++;
        row.append(cell);
    }
    if(count<1) {
        count++;
    } else {

    table.append(row);
    row = $('

').addClass('test');
    count = 0;
    }
}

Here is my JSFiddle

A: Move this line to the end of the script, outside of for loops:
$("[rel='popover']").popover({trigger: "hover"});

fiddle

A: Try This
var table = $('#Tableid');
var hostId = 1;
var count = 0;
var row = $('

').addClass('test');
for(var i=0; i<10; i++){

    for(j=0; j<3; j++){

        var button = "<button data-content = \""+hostId+"\" data-id=\""+hostId+"\"class=\"btn btn-primary btn-lg open-InfoModal\" data-toggle=\"modal\" rel=\"popover\" data-target=\"#hostInfo\" href=\"#infoModal\"></button>";

        var cell = $(''+hostId+'	').addClass('test').wrapInner(button);    //We use wrapInner to add HTML content
        hostId++;
        row.append(cell);
    }
    if(count<1) {
        count++;
    } else {

    table.append(row);
        row = $('

').addClass('test');
        count = 0;
    }
}

$("[rel='popover']").each(function(i, e){
    $(e).popover({trigger: "hover"});
});

Check it here JsFiddle


text:
Q: Tab Bar with JSQMessageViewController I am using JSQmessageViewController and I have a Tab Bar in my Application. The Tab Bar hides the text field and makes it unusable. Anybody have a solution?

A: Set the contentInset for the view to the hight of your tabBar


text:
Q: Is it possible to create a trigger to copy values into same field in another row (in the same table)? I have the following table test with the fields
id (PK),
Project Code (CFK),
item code (CFK)
date_code

rows could look like:
id, project code, item code, date code
1,  project1,     item1,     1220
2,  project1,     item2,     1224
3,  project1,     item1,     null
3,  project1,     item4,     null
4,  project1,     item1,     null

To update date code I can do that with a simple update table
update table test
set date_code='1220'
where project_code='project1' and item_code='item1'

But can this be done with a trigger on insert and update?
I want the trigger find the same/matching composite foreign key fields (project code & item code) like in update table syntax and copy the same value in other rows for the date code field?
All the rows would exist before the date_code field is given values so it is something that is done last.

A: Are you looking for something like this?
CREATE TRIGGER tg_projects_insert
BEFORE INSERT ON projects
FOR EACH ROW
  SET NEW.date_code = IF(NULLIF(TRIM(NEW.date_code), '') IS NULL,
  (
    SELECT date_code
      FROM projects
     WHERE project_code = NEW.project_code
       AND item_code = NEW.item_code
     LIMIT 1
  ), NEW.date_code);

CREATE TRIGGER tg_projects_update
BEFORE UPDATE ON projects
FOR EACH ROW
  SET NEW.date_code = IF(NULLIF(TRIM(NEW.date_code), '') IS NULL,
  (
    SELECT date_code
      FROM projects
     WHERE project_code = NEW.project_code
       AND item_code = NEW.item_code
     LIMIT 1
  ), NEW.date_code);

Now we can insert and update row into projects table
-- insert a new row and let the trigger to set date_code automatically
INSERT INTO projects VALUES (5, 'project1', 'item1', NULL);

-- update all rows that currently have NULL in date_code
-- and let the trigger to set date_code automatically
UPDATE projects SET date_code = NULL WHERE date_code IS NULL;

-- insert a new row and explicitly set a value to date_code
INSERT INTO projects VALUES (6, 'project2', 'item1', '1115');

Here is SQLFiddle demo


text:
Q: Feature Columns Embedding lookup I have been working with the datasets and feature_columns in tensorflow(https://developers.googleblog.com/2017/11/introducing-tensorflow-feature-columns.html). I see they have categorical features and a way to create embedding features from categorical features. But when working on nlp tasks, how do we create a single embedding lookup?
For eg: Consider text classification task. Every data point would have a lot of textual columns but they would not be separate categories. How do we create and use a single embedding lookup for all these columns?
Below is an example of how I am currently using the embedding features. I am building a categorical feature for each column and using that for creating embedding. The problem would be that the embeddings for same word could be different for different columns.
def create_embedding_features(key, vocab_list=None, embedding_size=20):
    cat_feature = \
        tf.feature_column.categorical_column_with_vocabulary_list(
            key=key,
            vocabulary_list = vocab_list
            )
    embedding_feature = tf.feature_column.embedding_column(
            categorical_column = cat_feature,
            dimension = embedding_size
        )
    return embedding_feature

le_features_embd = [create_embedding_features(f, vocab_list=vocab_list)
                     for f in feature_keys]

A: I think you have some misunderstanding. For text classification task, if your input is a piece of text (a sentence), you should treat the entire sentence as a single feature column. Thus every data point has only a single textual column NOT a lot of columns. The value in this column is usually a combined embedding of all the tokens. That's the way we convert a var-length sparse feature (unknown number of text tokens) into one dense feature (e.g., a fixed 256 dimensional float vector).
Let's start with a _CategoricalColumn.
cat_column_with_vocab = tf.feature_column.categorical_column_with_vocabulary_list(
    key='my-text',
    vocabulary_list=vocab_list)

Note if your vocabulary is huge, your should use categorical_column_with_vocabulary_file.
We create an embedding column by using an initializer to read from a checkpoint (if we have pre-trained embedding) or randomize.
embedding_initializer = None
if has_pretrained_embedding:
  embedding_initializer=tf.contrib.framework.load_embedding_initializer(
        ckpt_path=xxxx)
else:
  embedding_initializer=tf.random_uniform_initializer(-1.0, 1.0)
embed_column = embedding_column(
    categorical_column=cat_column_with_vocab,
    dimension=256,   ## this is your pre-trained embedding dimension
    initializer=embedding_initializer,
    trainable=False)

Suppose you have another dense feature price:
price_column = tf.feature_column.numeric_column('price')

Create your feature columns
columns = [embed_column, price_column]

Build the model:
features = tf.parse_example(...,
    features=make_parse_example_spec(columns))
dense_tensor = tf.feature_column.input_layer(features, columns)
for units in [128, 64, 32]:
  dense_tensor = tf.layers.dense(dense_tensor, units, tf.nn.relu)
prediction = tf.layers.dense(dense_tensor, 1)

By the way, for tf.parse_example to work, this assumes your input data is tf.Example like this (text protobuf):
features {
  feature {
    key: "price"
    value { float_list {
      value: 29.0
    }}
  }
  feature {
    key: "my-text"
    value { bytes_list {
      value: "this"
      value: "product"
      value: "is"
      value: "for sale"
      value: "within"
      value: "us"
    }}
  }
}

That is, I assume you have two feature types, one is the product price, and the other is the text description of the product. Your vocabulary list would be a superset of
["this", "product", "is", "for sale", "within", "us"].

A: You are passing the weights directly to the "embedding_column" layer, but it is expecting callable object.
Best way is to create an initializer class and pass it to the embedding_column like this
import tensorflow as tf

class embedding_initialize(tf.keras.initializers.Initializer):
  def __call__(self, shape, dtype=None, **kwargs):
    return tf.compat.v1.Variable(initial_value=[[1, 2], [2,3],[3,4]], dtype = dtype)

one_hot_layer = tf.feature_column.sequence_categorical_column_with_identity('text', num_buckets=3)
text_embedding = tf.feature_column.embedding_column(one_hot_layer,
                                      dimension=2,
                                      initializer = embedding_initialize())
columns = [text_embedding]

features = {'text': tf.sparse.from_dense([[1, 2], [2, 1]])}

sequence_input_layer = tf.keras.experimental.SequenceFeatures(columns)
sequence_input, sequence_length = sequence_input_layer(features, training=True)


text:
Q: "a coroutine's promise must declare either 'return_value' or 'return_void'" Error Visual Studio 2019 C++ 20 VS2019 latest c++ compiler.
Error is :"a coroutine's promise must declare either 'return_value' or 'return_void'"
Example pulled from David Mazièreshttps://www.scs.stanford.edu/~dm/blog/c++-coroutines.html blog
that works under a different compiler,GCC 10.2.
I can't get the source code to compile in VS2019.
#include <concepts>
#include <coroutine>
#include <exception>
#include <iostream>
struct ReturnObject {
    struct promise_type {
        ReturnObject get_return_object() { return {}; }
        std::suspend_never initial_suspend() { return {}; }
        std::suspend_never final_suspend() noexcept { return{}; }
        void unhandled_exception() {}

    };
};

struct Awaiter {
    std::coroutine_handle<>* hp_;
    constexpr bool await_ready() const noexcept { return false; }
    void await_suspend(std::coroutine_handle<> h) { *hp_ = h; }
    constexpr void await_resume() const noexcept {}
};

ReturnObject
counter(std::coroutine_handle<>* continuation_out)
{
    Awaiter a{ continuation_out };
    for (unsigned i = 0;; ++i) {
        co_await a;
        std::cout << "counter: " << i << std::endl;
    }
}

void
main1()
{
    std::coroutine_handle<> h;
    counter(&h);
    for (int i = 0; i < 100; ++i) {
        std::cout << "In main1 function\n";
        h();
    }
    h.destroy();
}

What am I missing? New to coroutines in C++. Who isn't?

A: Both compilers are correct. Flowing off the end of a coroutine when the promise type doesn't have return_void is undefined behaviour:

[stmt.return.coroutine]/3:

If p.return_void() is a valid expression, flowing off the end of a coroutine is equivalent to a co_return with no operand; otherwise flowing off the end of a coroutine results in undefined behavior.

You can define a noop return_void in the promise type to get the behaviour you seem to be going for:
void return_void() noexcept {}


text:
Q: Tunneling apt-get Through SSH Works... Mostly I am running a Linux container under Proxmox 4.4. The container is based on Debian Jessie. Here are the version specifics:
root@myHostName:/home/myUserName# uname -a
Linux myHostName 4.4.35-1-pve #1 SMP Fri Dec 9 11:09:55 CET 2016 x86_64 GNU/Linux
root@myHostName:/home/myUserName# cat /etc/debian_version
8.6
root@myHostName:/home/myUserName# cat /etc/issue
Debian GNU/Linux 8 \n \l

This container is isolated. Its only way out is via an SSH tunnel. And so, I'm using an SSH tunnel for package management (apt-get, etc.). This seems to mostly be working, but I do get some occasional warning / errors.
Here is the original /etc/apt/sources.list:
deb http://ftp.debian.org/debian jessie main contrib
deb http://ftp.debian.org/debian jessie-updates main contrib
deb http://security.debian.org jessie/updates main contrib

Here is what the updated /etc/apt/sources.list:
deb http://localhost:39860/debian jessie main contrib
deb http://localhost:39860/debian jessie-updates main contrib
deb http://localhost:39861 jessie/updates main contrib

Here's how I create the SSH tunnel:
ssh -N -L39860:ftp.debian.org:80 -L39861:security.debian.org:80 myRemoteUserName@myRemoteHostname

Here is what happens when I execute apt-get update:
root@myHostName:/home/myUserName# apt-get update
Ign http://localhost:39860 jessie InRelease
Hit http://localhost:39860 jessie-updates InRelease
Ign http://localhost:39861 jessie/updates InRelease
Hit http://localhost:39860 jessie Release.gpg
Get:1 http://localhost:39860 jessie-updates/main amd64 Packages/DiffIndex [8392 B]
Hit http://localhost:39860 jessie-updates/contrib amd64 Packages
Hit http://localhost:39860 jessie-updates/contrib Translation-en
Get:2 http://localhost:39860 jessie-updates/main Translation-en/DiffIndex [3196 B]
Ign http://localhost:39861 jessie/updates Release.gpg
Hit http://localhost:39860 jessie Release
Ign http://localhost:39861 jessie/updates Release
Hit http://localhost:39860 jessie/main amd64 Packages
Hit http://localhost:39860 jessie/contrib amd64 Packages
Hit http://localhost:39860 jessie/contrib Translation-en
Hit http://localhost:39860 jessie/main Translation-en
Err http://localhost:39861 jessie/updates/main amd64 Packages
  404  Not Found [IP: ::1 39861]
Err http://localhost:39861 jessie/updates/contrib amd64 Packages
  404  Not Found [IP: ::1 39861]
Ign http://localhost:39861 jessie/updates/contrib Translation-en
Ign http://localhost:39861 jessie/updates/main Translation-en
Fetched 11.6 kB in 9s (1279 B/s)
W: Failed to fetch http://localhost:39861/dists/jessie/updates/main/binary-amd64/Packages  404  Not Found [IP: ::1 39861]

W: Failed to fetch http://localhost:39861/dists/jessie/updates/contrib/binary-amd64/Packages  404  Not Found [IP: ::1 39861]

E: Some index files failed to download. They have been ignored, or old ones used instead.

How can I best get around the warnings and errors shown at the end?

A: Your approach doesn't work because of the HTTP protocol's Host: header.
Under normal circumstances, the HTTP client (in this case, apt-get) sends the header Host: ftp.debian.org, which lets the server know which website to load, in case the server is hosting multiple domains.
What you have done is make apt-get send Host: localhost:39860, which likely ends up not being anything on the remote server.  That explains your HTTP 404 Not Found errors.

Proposed Resolution
Put an HTTP proxy on your host and make it available to your container via SSH port forwarding.

*

*Install Squid on your Internet-connected machine.  Ubuntu/Debian: sudo apt install squid

*Write this configuration into /etc/squid/squid.conf:
http_port 8080

acl container src XXX.XXX.XXX.XXX/32
http_access allow container

Replace XXX.XXX.XXX.XXX with your container's IP address.

*Start or restart Squid with service squid restart.

*Connect to your container from your Internet-connected machine with this command:
ssh -R8080:localhost:8080 myRemoteUserName@myRemoteHostname

Replace myRemoteUserName@myRemoteHostname with the login credentials to your container.

*Inside the container, create a new file called /etc/apt/apt.conf.d/80proxy with the following contents:
Acquire::http::Proxy "http://localhost:8080/";

*As long as the connection from step #4 is up, your container's apt package manager can now make remote requests.

If you need to add site restrictions to your proxy, check out Restrict Squid access to only one site.


text:
Q: Azure Virtual Machine vs dedicated server I need to provide a desktop application up to 10 users. This application is a ERP, basically database mining and reporting.
I will use Windows Server to offer support to concurrent users via Remote Desktop Connection.
Do somebody have experience comparing the performance between Azure Virtual Machine and a dedicated server?
At the present, I use Azure, but changing the settings to a powerful machine does not seem to affect to the time to generate reports, specially when the application needs to read the database or load the dlls for first .

A: I used both systems and I prefer Azure, it's cheapest and you shouldn't worry about some things that you should if you have your own server on premise.
Anyway, I recommend you Azure RemoteApp, it's a new feature, introduced at the last build by Microsoft and it's more powerful if you only need that feature of your server.
Changing IaaS to SaaS, maybe you should consider that option for this service.
https://www.remoteapp.windowsazure.com
H.

A: If scaling up the size of the Azure VM doesn't help improve performance then your issue is almost certainly not going to be due to the virtualized environment itself, which means that moving to a dedicated server most likely won't fix the issue.
I would suggest a couple options:

*

*Consider checking out RemoteApp (http://azure.microsoft.com/en-us/services/RemoteApp/).  This is a dedicated offering specifically for what you are trying to accomplish.

*Investigate where the perf problem is coming from and fix that issue rather than randomly changing environments.  If database lookups are slow - is the database on the same server as the app or is it remote? have you created appropriate indexes?  have you gone through the SQL Server on Azure VM Performance best practices whitepaper (http://msdn.microsoft.com/en-us/library/dn133149.aspx)?

A: Your environment sounds similar to ours - datawarehousing with online reporting. We considered switching from a dedicated server to azure, but after some evaluation, we discovered that our MySQL / PHP reports took about twice as long as our relatively low specification dedicated server. So we are currently sticking with dedicated server running windows server 2012.


text:
Q: Need help to split string in java Please help me to split string like this "mumbai (or) pune" using java.
I want the string after ")", I tried using string.split() but not working on above String format.
my expected output is "pune".
input:
String abc="mumbai (or) pune"

output:
String result="pune".

A: If your input string is always similar to the one you showed:
yourString.split("\\)")[1].trim();

A: It doesn't work because ) is special in regex. Escape the regex with \\.
Use string.split("\\)")[1].trim(); instead.

A: You can split it into parts:
String abc="mumbai (or) pune"
String result = "pune";

String[] parts = abc.split(" ");
String partOne = parts[0];
String partTwo = parts[2];

if (partOne == result){
   System.out.println(partOne);
}
else{
   System.out.println(partTwo);
}

A: Try this:
String s = "mumbai (or) pune";
String result = s.substring(s.lastIndexOf(')') + 1).trim();

A: A replace would be actually more efficient here.
Use :
 String abc="mumbai (or) pune";
 abc = abc.replaceAll(".*\\s+(\\w+)","$1");
 // abc will be "pune" here

A: There are many ways to do the simple thing which you are looking for. Best approach: Read of String Operations in Java
Following are just some ways to achieve what you need:
 public static void main(String[] args)
{
    String output1 = "mumbai (or) pune";
    String output2 = output1.split("or\\) ")[1];
    String output3 = output1.substring(output1.indexOf(")")+2);;

    System.out.println(output1);
    System.out.println(output2);
    System.out.println(output3);
}


text:
Q: use mongodb inside aws lambda I have created a lambda function using nodeJs. i have configured it to run inside my VPC where my mongo EC2 instance is running and the lambda is connected to Kinesis stream. first i worked with DynamoDB but regarding query capabilities and overall prices, I have decided to use mongo. When my function get trigger I am getting invocation errors and I dont know the real source and reasons
the error I get:
    Unable to import module 'index': Error
    at Function.Module._resolveFilename (module.js:325:15)
    at Function.Module._load (module.js:276:25)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (/var/task/node_modules/bson/index.js:1:74)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (/var/task/node_modules/mongodb-     core/index.js:1:74)
   at Module._compile (module.js:409:26)
   at Object.Module._extensions..js (module.js:416:10)
   at Module.load (module.js:343:32)
   at Function.Module._load (module.js:300:12)

my dependencies are

"dependencies": {
>             "bluebird": "^3.4.7",
>             "lodash": "^4.17.2",
>             "moment": "^2.17.1",
>             "mongodb": "^2.2.21",
>             "request": "^2.79.0",
>             "request-promise": "^4.1.1"
>        }

A: My mistake - bad zip. it didnt include the lib folders


text:
Q: Eclipse Kepler RCP CoolBar Actions CSS Similar to this question's screenshot, my RCP App has those annoying spaces between actions on the coolbar. My guess is that it's because I'm using deprecated extensions in the plugin.xml (i.e. viewActions actionSets).
For now, I don't want to begin changing all those action implementations to comply with the new rules (mostly because there are A LOT of those actions).
Question: Can I somehow apply CSS styling to that CoolBar so that extra spaces are grabbed by the actions?
The road so far:

*

*NO e4 STUFF! This question does not satisfy mine.

*My other (similar) question. Feel free to complete that guy's answer.

*RAP CSS - does this apply to RCP as well?

A: Looking at the debug plugin which does align the toolbar entries correctly it first defines a toolbar like this:
<extension
     point="org.eclipse.ui.menus">
  <menuContribution
         locationURI="toolbar:org.eclipse.ui.main.toolbar?after=additions">
      <toolbar
            id="org.eclipse.debug.ui.main.toolbar"
            label="%DebugActionSet.label">
         <separator
               name="breakpointGroup"
               visible="true">
         </separator>
         <separator
               name="threadGroup"
               visible="true">
         </separator>
         <separator
               name="stepGroup">
         </separator>
         <separator
               name="stepIntoGroup">
         </separator>
         <separator
               name="stepOverGroup">
         </separator>
         <separator
               name="stepReturnGroup">
         </separator>
         <separator
               name="emptyStepGroup">
         </separator>
         <separator
               name="renderGroup"
               visible="true">
         </separator>
      </toolbar>
   </menuContribution>

and then in the actionSet references the defined toolbar:
      <action
           toolbarPath="org.eclipse.debug.ui.main.toolbar/breakpointGroup"
           ... other stuff ...
           id="org.eclipse.debug.ui.actions.SkipAllBreakpoints">
     </action>


text:
Q: Do some debian builds not have lsb_release? A .deb package I am releasing expects that it can call lsb_release.  One customer using Debian 6.0.5 indicated that the lsb_release command (even in the terminal) produces a command not found error.  Is this standard or is there something wrong with his Debian build?

A: There is an lsb-release package that supplies the lsb_release command.  This is separate from the lsb, lsb-base, and lsb-core packages.  None of the lsb packages are essential.  So if your package needs lsb_release it should specify that it depends on lsb-release.

A: Not all Debian builds have lsb_release. For example, even the official Ubuntu Docker image does not have lsb_release.
The alternative is to use cat /etc/os-release.


text:
Q: C# Dictionary Loop Through Only Certain Datasets Say I have a Dictionary wipProfile which is defined as:
Dictionary<string, int> wipProfile = new Dictionary<string, int>() { { "L1", 10 }, { "L2", 12 }, { "L3", 23 }, { "L4", 9 } };

I wonder how can I only loop through those with value >= 10?
I know I can do something like this:
foreach (KeyValuePair<string, int> lot in wipProfile)
{
        if (lot.Value >= 10)
        {
            //Do something here.
        }
}

But is there a way to specify filtering criteria before entering the loop, so that I don't need to iterate through the entire dictionary, say something like this:
foreach (KeyValuePair<string, int> lot in wipProfile where lot.Value >= 10){
    //...
}

A: Try this, using System.Linq
foreach (KeyValuePair<string, int> lot in wipProfile.Where(kv => kv.Value >= 10))
{
    //...
}

A: You are looking for somethign like this:
 wipProfile.Where((key, value) => value > 10).ToList();

That will give you the list filtered with online the items that have a value greater than 10. Then you can do a ForEach in Linq style or with the reserved word as you showed!
EDIT:
as Steward mention the right way to do it is like this:
 wipProfile.Where(keyValuePair => keyValuePair.Value > 10).ToList();


text:
Q: jQuery UI Tooltip and AJAX, how to implement live() with it? On certain pages I have code like $('.tooltip').tooltip();. Example element would look like:

This works beautifully unless I want to reload those elements with AJAX. Then, the tooltip handlers are not reattached to the new content and the tooltips do not work any more.
I have attempted to do a workarounds to somehow reattach the tooltip to the elements with no particular success. Any advice is appreciated!

A: You need to reinitialise tool-tip $('.tooltip').tooltip(); in your AJAX success callback

A: You can reinitialise tooltip for new added elements only by:
$('.tooltip').not('.hasTooltip').tooltip().addClass('hasTooltip');


text:
Q: Using a Roberts operator on an image This algorithm is meant to apply a Roberts operator to an image, and store the result in a new file.
Instead, this code outputs the exact same image as the input.
I am new to Matlab, so your tips and feedback on my code are welcome.
I know there is a built in function for this purpose, I am doing this as an exercise.
function [] = Roberts(filename)
%somehow, it outputs the exact same image back.
%I know that this doesn't include the y component of the Roberts operator'

Img = imread(filename);
NewImg = Img;

SI = size(Img);

I_W = SI(2)
I_H = SI(1)

Roberts = [1,0;0,-1];

M_W = 2;
y = 0;
x = 0;
M_Y = 0;
M_X = 0;
%I initialized these counters here, because Matlab told me that these variables were
%used before they were initialized. This is strange, because they are initialized in the for loop, correct?
    for y=0 :1: y<I_H
        for x=0 :1: x<I_W

            S = 0;

            for M_Y = 0 :1: M_Y < M_W
                for M_X = 0 :1: M_X < M_W

                    if (x + M_X - 1 < 0) || (x + M_X - 1 > I_W)
                       S = 0;
                       disp('debug: tried to go beyond the image, value of that component, set to 0');

                    elseif (y + M_Y - 1 < 0) || (y + M_Y - 1 > I_H)
                       S = 0;
                       disp('debug: tried to go beyond the image, value of that component, set to 0');

                    else
                        S = S + Img(x + M_X - 1, y + M_Y - 1) * Roberts(M_X,M_Y);
                    end
                end

            end

            NewImg(x,y) = S;
        end

    end

imwrite(NewImg,'Roberts.bmp');
end

EDIT - I have another question as well - in this example, if said x = Img(x,y), would that get the pixel at row x, column y, or the pixel at row y, column x?

A: This doesn't do what you think:
for y=0 :1: y<I_H

You actually want:
for y = 0:I_H


text:
Q: Excel 2013: Cannot open PivotTable source file error after renaming the file/workbook I have a pivot table on tab PTable.  The data for this pivot table is in the same workbook (PTWork) on tab PriList.  Everything works fine.
If I change the name of the workbook to PTWorkRen, and try to refresh the pivot table, I get
Cannot open PivotTable source file '[PTWork]PriList'.

Is there any way to tell Excel to just use the current workbook?

A: Somehow the data source for the pivot table has the workbooks filename in the reference. I could change it by going to change PivotTable Tools on the ribbon and then clicking Analyze > Change Data Source. There I just erased the filename.


text:
Q: MVC Bundle {version} when old file still exists in directory In MVC 4, using the Bundles to define the files you want to include, you can use a {version} wildcard, for example...
"~/Scripts/jquery-{version}.js"

This works well when you have one version in the folder, e.g. jquery-1.7.js.  However, when we have two versions in the folder jquery-1.7.js & jquery-1.9.js, it seems to pick up the old version, ignoring the new version.
Does the {version} wildcard find the first instance, and then move on? if so, the first instance in this example seems to the be the old version (as 1.7 comes before 1.9).  So, is there a way of forcing it to look for the newest version if we have two files?
NOTE: The above version numbers may not be accurate, just used for scenario purpose.

A: In Mvc. It will load the old version first and then latest version. following will be sequence of jquery file load.
1.jquery-1.7.js
2.jquery-1.9.js
In this situation . latest file will overwrite the old version. so your page always get latest jquery functionality.

A: We ended up using something similar to this post, which tackles a similar issue.  I will update the answer with a full description and code in the next few weeks once implemented fully.


text:
Q: How far do the propagation paths in QED go? I am currently reading Feynman's popular book on QED "the strange theory of light and matter". I know classical optics quite well, know about Fresnel, Brewster angle and the like.
I also am now used to the concept that QED sums up all the probability amplitudes of all possible propagation paths. And the little clocks are basically the complex phases of the photons. The higher the photon's frequency, the faster the clock ticks.
However I am wondering: if I want to calculate the propagation of light from point A to B which are let's say 1m apart. I now have to calculate all contributions of all possible paths. Even from A to Alpha Centauri back to B. This sounds pretty crazy. But is it correct?
How does reality determine this in a finite amount of time? Or is this simply the model of reality—it "just works" this way?
Also: for practical computations—would I limit the summing to a certain length of paths, if I were to numerically approximate a solution?


text:
Q: Insert Statement using multiple where clauses Hi I'm trying to create a new table where they are based off the same variable. Below is my attempt at getting it to work, I've tried a few other thins as well.
I have to create a table where x and x1 are side by side. When I try to insert individually, I get a table that looks like
x  | null
x  | null
null | x1
null | x1
I want a table that results in
x      |  x1
x  | x1
insert into inter
(
x,
x1
)

select

unrolled.`Sum of New Lds` from unrolled where pastdate(`Week end`)='2014-06-08',

(select unrolled.`Sum of New Lds` from unrolled where `Week end`='2014-06-08')

A: The syntax is:
INSERT INTO TableName (ColumnX1, ColumnX2) VALUES ('x1', 'x2')

If you need to do it in 2 separate statements for some reason, you cant insert into an existing row, for that you want update, something like
UPDATE TableName SET ColumnX2='X2' WHERE ColumnX1 = 'x1'


text:
Q: DateTime.Parse issue on 1st of March 2017 I'm working with Xamarin (mainly forms) and a few days ago I discovered that issue.
When i call a webservice I look on response's header for Date field and try to parse it.
That works fine until 28th of February:
DateTime dt_OK = DateTime.Parse("Tue, 28 Feb 2017 11:07:06 GMT");

But, starting from 01 of March:
DateTime dt_KO = DateTime.Parse("Wed, 01 Mar 2017 11:07:06 GMT");

I get: "String was not recognized as a valid DateTime". But it is a valid datetime! 01 March 2017 was a wednesday...
ok, I know that exit ParseExact (which I tried and worked) but how about .Parse()?
DateTime dt_always_ok = DateTime.ParseExact(dateFromHeader, "ddd, dd MMM yyyy HH:mm:ss Z", System.Globalization.CultureInfo.InvariantCulture);

All days of march will not be recognized and parsed.. it restarts to work from April 01.
Anyone else faced that behaviour?

A: I think Hans is on the right way. Looks like your "Mar" is not parsed in Parse method as an abbreviate month name of the marzo which is March in Italian. It try to parse it as an abbreviate day name of the martedi instead which is tuesday in Italian. And since you try to parse two different abbreviate day names in your string, you get an exception.
But still, it is too weird to parse your english month and day names with an italian culture. Use a english-based culture instead like InvariantCulture. And if you have a custom format, you might wanna choose ParseExact or TryParseExact methods to prevent this kind of ambiguous situations.

A: The issue seems reproducible only for Mono mcs compiler, not for .Net framework.
In that case, it looks like a known bug, because even (!)
DateTime dt_KO = DateTime.Parse("01 Mar 2017",CultureInfo.GetCultureInfo("it-IT"));

produces the following error
System.FormatException: Giorno della settimana non corretto. Stringa non riconosciuta come DateTime valido.

that means "String was not recognized as a valid DateTime because the day of week was incorrect", while "Mar" is the correct "MMM" format for the month.
It looks like they didn't consider that a month and a day could have the same abbreviation in the current Italian language.
A possible workaround for DateTime.Parse would be
DateTime dt_KO = DateTime.Parse("Wed, 01 Mar 2017 11:07:06 GMT",
                                CultureInfo.GetCultureInfo("en-US"));


text:
Q: get data from ajax in jstree here is my code:
var data = "";
    $(function() {
        $("#MainTree,#SubTree").jstree({
            "json_data": {
                "data": data,
                "ajax":{
                    type: "POST",
                    async: true,
                    url: "Default.aspx/GetJson",
                    contentType: "application/json; charset=utf-8",
                    //data: '{name:""}',
                    dataType: "json",
                    cache: false,
                    success: function(msg) {
                         data = msg;

                    },
                    error: function(err) {
                        alert(err);
                    }
                },

            },
            "plugins": ["themes", "json_data", "ui", "dnd"]
        });
    });

This is my GetJson method:
[System.Web.Services.WebMethod]
public static string GetJson()
{
    System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
    Dictionary<string, object> row = null;

    DataTable dtEmployee = new DataTable();

    dtEmployee.Columns.Add("EmpId", typeof(int));
    dtEmployee.Columns.Add("Name", typeof(string));
    dtEmployee.Columns.Add("Address", typeof(string));
    dtEmployee.Columns.Add("Date", typeof(DateTime));

    //
    // Here we add five DataRows.
    //
    dtEmployee.Rows.Add(25, "Rk", "Gurgaon", DateTime.Now);
    dtEmployee.Rows.Add(50, "Sachin", "Noida", DateTime.Now);
    dtEmployee.Rows.Add(10, "Nitin", "Noida", DateTime.Now);
    dtEmployee.Rows.Add(21, "Aditya", "Meerut", DateTime.Now);
    dtEmployee.Rows.Add(100, "Mohan", "Banglore", DateTime.Now);

    foreach (DataRow dr in dtEmployee.Rows)
    {
        row = new Dictionary<string, object>();
        foreach (DataColumn col in dtEmployee.Columns)
        {
            row.Add(col.ColumnName, dr[col]);
        }
        rows.Add(row);
    }
    return serializer.Serialize(rows);
}

In my Default.aspx.cs, I created a method name GetJson, when I run this code, it returned alert(error). Please help me to find out what was happened?
Editted: when i check in browser,the method get status code 200 OK, but in respone..it show me the page Default.aspx(context html)


text:
Q: use sed to replace a line I have been struggling to do this. I need to replace a line in a document with either blank space or the word "DELETED." The lines are different, and I am running a counter to determine the correct line to replace. So far, I have been using:
sed -ie ''$NUMLINE's/^$/DELETED/' Brown_Adam_CIVForms.txt

I would like to replace the NUMLINE-th line from this document (whatever it may be) and replace it with either blank space or the word "DELETED." Please help!!
Thank you!!!

A: Just insert .* between ^ and $. Like:
sed -ie $NUMLINE's/^.*$/DELETED/' Brown_Adam_CIVForms.txt

A: you can also use awk
awk -vnum=$NUMLINE 'NR==num{$0="DELETED"}1' file


text:
Q: PrimeNG Angular 6 turbotable with separate search field throws error I am trying to use a global "search" filter box for a PrimeNG turbotable, as in their example, except putting the global search field outside the table (they have their inside the table in a caption, but my design calls for a toolbar above the table.
It should work, but I keep getting the error on compile
Property 'filterGlobal' does not exist on type 'DataTable'.
and the app won't run.  I see nothing in their example about filterGlobal. At this point, I am stumped. It feels like something needs to be declared or imported somewhere, but I have no idea.
My table html:

    <form class="form-inline">
        <input type="text"
               placeholder="Search"
               (input)="dt.filterGlobal($event.target.value, 'contains')">
    </form>

  <ng-template pTemplate="header">

      {{col.header}}

  </ng-template>
  <ng-template pTemplate="body"
              let-rowData
              let-columns="cols">

      {{rowData[col.field]}}

  </ng-template>

And in my Typescript:
import { Component, OnInit, ViewChild } from '@angular/core';
import { MockDataService } from '../../shared/services/mock-data.service';
import { DataTable } from 'primeng/primeng';

@Component({
  selector: 'app-turbotable-deluxe',
  templateUrl: './turbotable-deluxe.component.html',
  styles: []
})
export class TurbotableDeluxeComponent implements OnInit {
  @ViewChild('dt')
  dt: DataTable;

  people$;
  cols;

  constructor(private mockdata: MockDataService) {}

  ngOnInit() {
    this.people$ = this.mockdata.get('people_100.json');

    this.cols = [
      { field: 'first_name', header: 'First Name' },
      { field: 'last_name', header: 'Last Name' },
      { field: 'age', header: 'Age' },
      { field: 'email', header: 'Email' },
      { field: 'country', header: 'Country' }
    ];
  }

A: The right class for p-table is "Table".
I found it in the source code of primeNg.


text:
Q: Rule creation on VSTS I am facing the problem with the created rules.
Requirement: I created 3 status drop down values, ie. temp1,temp2, and temp3. While updating status to temp1 - starttime1 should be updated with current time. Again updating from temp1 to temp2 - starttime2 should be updated with curent time,
Issue: When i tried to update the status from temp1 to temp2, both starttime1 and starttime2 are updated with starttime2.

A: I could reproduce your scenario. To avoid this phenomenon, you could add an action to make read-only to starttime1 when set current time to starttime2. Check my example below:


text:
Q: Android SmackInitialization: org.xmlpull.v1.XmlPullParserFactory.newInstance Error I keep getting the below error message and I can't figure out why. Any help would be appreciated:
Exception in thread "main" java.lang.ExceptionInInitializerError
    at org.jivesoftware.smack.SmackConfiguration.getVersion(SmackConfiguration.java:96)
    at org.jivesoftware.smack.ConnectionConfiguration.<clinit>(ConnectionConfiguration.java:38)
    at com.parental.control.XmppClient.connect(XmppClient.java:32)
    at com.parental.control.XmppClient.main(XmppClient.java:23)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.lang.IllegalStateException: java.lang.RuntimeException: Stub!
    at org.jivesoftware.smack.SmackInitialization.<clinit>(SmackInitialization.java:119)
    ... 9 more
Caused by: java.lang.RuntimeException: Stub!
    at org.xmlpull.v1.XmlPullParserFactory.newInstance(XmlPullParserFactory.java:16)
    at org.jivesoftware.smack.SmackInitialization.processConfigFile(SmackInitialization.java:153)
    at org.jivesoftware.smack.SmackInitialization.processConfigFile(SmackInitialization.java:148)
    at org.jivesoftware.smack.SmackInitialization.<clinit>(SmackInitialization.java:116)
    ... 9 more

Just running the below code:
private void connect() throws InterruptedException, IOException, XMPPException, SmackException {
    XMPPTCPConnectionConfiguration conf = XMPPTCPConnectionConfiguration.builder().setServiceName(hostName).setHost(<openFireServerHost).setPort(5222).setUsernameAndPassword(userName, password).setCompressionEnabled(false).build();
    XMPPTCPConnection connection = new XMPPTCPConnection(conf);
}

A: You have compiled your application with android library stub, read the docs:

By default, the Android Plug-in for Gradle executes your local unit tests against a modified version of the android.jar library, which does not contain any actual code. Instead, method calls to Android classes from your unit test throw an exception. This is to make sure you test only your code and do not depend on any particular behavior of the Android platform (that you have not explicitly mocked).

So, your build environment isn't configured properly to build a real android application for the device/emulator

A: So . . . this was actually an XMLPullParser error which has nothing to do with the Smack libraries. It took me all weekend to trace through the code and figure this out but the issue was that I was trying to connect to my Open Fire server without using the my Android emulator.
The below Stack Overflow post helped me figure it out: how to instantiate an XmlPullParser in android-8?
Just figured that I would post this for the next slob that runs into this problem.


text:
Q: Entity Framework Linq2Db Translation I am upgrading a website that used Entity Framework and now uses Linq2Db. I notice Linq2Db has no navigation properties. How would I translate this code from Entity Framework? I need to return an order with a list of order items, shipments, and other related objects. I am unable to query order items, shipments, and the other objects one by one.
           IQueryable<Order> query = GetExpandedOrderTable();
            DateTime beginTime = settings.LastDownloadUtc;
            DateTime endTime = settings.LastDownloadUtcEnd;

            query = query.Where(a => a.CreatedOnUtc >= beginTime);
            query = query.Where(a => a.CreatedOnUtc <= endTime);

            List<int> storeIds = GetStoreIds();

            if (storeIds.Count() > 0)
                query = query.Where(a => storeIds.Contains(a.StoreId));

            return new PagedList<Order>(query, 0, 1000).ToList();

    /// <summary>
    /// Expands order items and other sub properties.
    /// Increases performance.
    /// </summary>
    /// <returns></returns>
    private IQueryable<Order> GetExpandedOrderTable()
    {
        return orderRepository.Table
            .Include(a => a.OrderItems)
            .Include("OrderItems.Product")
            .Include(a => a.OrderNotes)
            .Include(a => a.GiftCardUsageHistory)
            .Include(a => a.BillingAddress)
            .Include(a => a.BillingAddress.StateProvince)
            .Include(a => a.BillingAddress.Country)
            .Include(a => a.ShippingAddress)
            .Include(a => a.ShippingAddress.StateProvince)
            .Include(a => a.ShippingAddress.Country)
            .Include(a => a.Customer)
            .Include(a => a.DiscountUsageHistory)
            .Include(a => a.Shipments);
    }`

A: EF Navigation Property => linq2db Association
EF Eager Loading Include() => linq2db LoadWith()


text:
Q: Rest api route name when dealing with user specific data I have restful service and I'm trying to follow the best practices. I was wondering what is the best practice when naming a resource that returns data for a specific user. The user is authenticated with a Token sent in the header.
I need to get all the favorites of a specific user.
Examples:
myservice.com/Favorites -> I get the user with the token and then query the favorites, but it seems weird, i would expect /Favorites to return all favorites of any user.
myservice.com/MyFavorites -> MyFavorites is not really an entity, but that would make things clearer.
myservice.com/Favorites?userId=123 -> This one is clear, but it feels redundant to send the userId since I already know the user with the token.
Is there any other way to do this? What is the best practice?

A: All are valid and of the three you mention, I like the 3rd, However...  but I'd suggest a different pattern for your needs:
https://myservice.com/user/123/favorites

Also, stick to all lowercase in your resource urls.
Tokens are fine authentication, but you might have a need where a user might be a 'super user' and would need to hit other user resources for example.


text:
Q: Replacing a javascript list button with a visualforce page to run on group edition I am less than a novice at this.  I was able to piece together some javascript to enable a button on list view that would allow me to make selections of "students" and then mark them as "attended" by creating attendence records on the student object in mass.  However, now I am running group edition for financial reasons and the button will not work.  As I understand it, I need to use visualforce in order to do this, but I have no clue.  Here is my javascript code, any help would be appreciated.  Thanks
{!REQUIRESCRIPT("/soap/ajax/19.0/connection.js")};
    var url = parent.location.href;
var records = {!GETRECORDIDS($ObjectType.Student__c)};
var CreateNewRecords = [];
var answer = prompt("Enter a Date", "1/1/13");
try
{

    if (records[0] == null)
    {
        alert("Please select at least one record to update.");
    }
    else
    {
        for (var a=0; a<records.length; a++)
        {
            var create_new_opportunity = new sforce.SObject("Attendance__c");

            create_new_opportunity.Date__c = sforce.internal.dateTimeToString(new Date(answer));
            create_new_opportunity.Student__c = records[a];
            CreateNewRecords.push(create_new_opportunity);
        }
        var result = sforce.connection.create(CreateNewRecords);
        if (result[0].success=='false')
        {
            alert(result[0].errors.message);
        }
        else
        {
            alert("records created successfully.");
            location.reload(true);
        }

    }
}
catch(error)
{
    alert("Error In Attendance creation  = "+error);
}

A: You can't replicate this in Group Edition. It requires the API, which simply isn't available in Group Edition. Users will need to create new records manually.


text:
Q: How to implement a multithreaded pool in Java I have a scenario where I use threads.
Firstly I have a folder where there are files which get updated frequently.
So, I wrote a thread which reads the contents of the folder and writes the file names to a static list and updates the list if new files come in.
Secondly i wrote another thread which takes the file names from the list and do some processing with the files.
These two threads run continuously, one checking for new files, one processing the new files.
Now I need to process three files at a time with three threads running. When one thread completes processing another thread takes another file name from the list and starts the process.
So I need some mechanism to have three threads and checking them whether they are alive or not and accordingly starts a new thread and the file list also gets updated frequently.
I also looked into ExecutorService but while the list get updated I could not provide it updated list.
Thanks,
Sandeep

A: Building on the existing answers, your code would look something like:
    final ExecutorService executor = Executors.newFixedThreadPool(2);

    final FilePoller poller = ...
    final FileProcessor processor = ...

    new Thread(new Runnable()
      {
        @Override
        public void run()
        {
          while (true)
          {
            final File file = poller.pollForFile();
            executor.submit(new Runnable() { public void run() { processor.processFile(file); } } );
          }
        }
      });

Assuming your processors can keep up with the poller this would be fine, otherwise you'd want to put in some throttling mechanism before submitting to the executor.

A: Don't use a list; instead use a java.util.concurrent.ThreadPoolExecutor and just drop Runnable's representing the file to be processed into the executor instead of putting them into your global list.

A: Similar to @SimonC's suggestion but instead of a really long comment I have an answer.
final FilePoller poller = ...
final FileProcessor processor = ...

final ExecutorService executor = Executors.newFixedThreadPool(4);

executor.submit(new Runnable() {
    public void run() {
        final File file = poller.pollForFile();
        executor.submit(new Runnable() { public void run() { processor.processFile(file); } } );
        // repeat, but wait for a free thread.
        executor.submit(this);
    }
  });
 // to stop the whole thing
 executor.shutdown();

A: How about watching for changes in the folder and spawn a thread/file, assuming that the notification change is giving you a list of changes in the folder?


text:
Q: Use Rest API to return link from sharepoint list I'm trying to use REST API in SharePoint to getlistitems to display the link from a hyperlink field from my sharepoint list.
I AM successfully using the code to display the title field - but NOT the url from the hyperlink field.
I've tried appending the url in the code below with /_api/web/lists/getbytitle('test')/items?$select=URL without success.

<input type="button" id="btnSubmit" value="Get List Data using Rest API">

A: You need to use the internal name of the column. For developing in REST I recommend using something like Postman or I use a Chrome extension called Talend API Tester (free version). This allows you to write and send REST calls a lot quicker than writing it in javascript, testing, debugging, fixing, etc.
But either way you can find the internal name either by going to the list properties and editing the column, the internal name will be in the url.
Or you can make a rest call to {site}/_api/lists/getbytitle('{name}')/fields?$select=Title,InternalName. That will give you a list of all the display and internal named columns available in that list.

A: I just did a quick test to see if you were going to need to use $expand in your REST query to expand out the values of the hyperlink field (description and actual URL), and it looks like you won't.  But you do have to know that a hyperlink field value returned from a REST query is a JSON object, not just a simple primitive value like a string or integer.
It looks something like this:

Now, in the case of my screenshot, the internal name of my hyperlink field is in fact "URL", but that may not be the case for your hyperlink field.  So you will still need to know the internal name of your hyperlink field in order to access the values, but once you know that you can access the values of the Description and Url properties of the field.
Based on your code example, you would get to the URL of your hyperlink field by doing something like this:
function onQuerySucceeded(data) {
    var listItemInfo = '';
    $.each(data.d.results, function (key, value) {
        listItemInfo += 'Title: ' + value.Title + '
';

        // access the description as a sub-property of your hyperlink field
        var linkDescription = value.YourHyperlinkField.Description;

        // access the url as a sub-property of your hyperlink field
        var linkUrl = value.YourHyperlinkField.Url;

        listItemInfo += '' + linkDescription + '
';
    });
    $("#divResults").html(listItemInfo);
}

where you would have to replace YourHyperlinkField with the internal name of your hyperlink field.  If that does indeed happen to be "URL", then you would use
value.URL.Description
value.URL.Url


text:
Q: Where is Magento Homepage file located in File Manager? Where to find magento homepage in .html or .xml format in FTP?
I actually want to host my javascripts/ CSS in html itself for better SEO.

A: Magento's home page is not saved a flat html document, it is a CMS page configured in the admin panel.  To find what page is currently being used, go to;
system > configuration

From the top menu, then go to;
General > Web

From the left menu.  Find the 'default pages' block in the main content area and there you will find the name of the cms page being used for the home page.  You can search for this page here;
Cms > Pages

From the top menu, then search by name.
Note if you have more than 1 store setup in Magento, you may need to change the viewscope when checking the settings in configuration.


text:
Q: Why is the central maximum of single slit diffraction pattern wider than other fringes? I had answered a question Single Slit Diffraction Experiment, telling why the central maximum is the brightest one, but it asks:

Why is the central maximum twice as wide as the others?

Now, that is tricking me, I have tried my best to search the reason and seen many diagrams, but I can't understand why.

A: You can know that from the derivation of fringe width in single slit experiment, though I will give you a simple answer, without much mathematics.
If you look at diagrams of Fraunhofer single-slit diffraction patterns, you will see that the central maximum is symmetrical about the center line. All the other maxima and minima are found on just one side of the center line. Of course, the pattern as a whole is also symmetrical about the center line.
Both the mathematics and experimental results show that the positions of the minima are at distances from the center line that depend on the details of the particular experiment.
Those minima distances are found fairly accurately by multiplying a constant (which depends on the experiment) by a whole number (that number is $1$ for the first two minima and $2$ for the second two minima, and so on). There is no minimum on the center line, of course (corresponding to the number $0$).
Let $\text{Min}_1$ be the distance from the center line to the first two minima, one on each side of the center line. Let the distance of the second two minima from the center line be $\text{Min}_2$, and so on. $\text{Min}_2$ is about twice of $\text{Min}_1$. The width of the maxima is roughly the distance between adjacent minima. So, all the secondary maxima are about $\text{Min}_1$ in width.
However, the distance between the two first two minima, on each side of the center line is $2 \times \text{Min}_1$. The central maximum lies between the first two minima (located on opposite sides of the center line). All the secondary bright fringes lie between adjacent minima on the same side of the center line. So now you can see why the width of the central maximum is about twice the width of the other bright fringes


text:
Q: BizTalk Scripting - Receive Location Schedule I'm tasked with 2 things that I'm not seeing support for.

*

*Writing a script to enable a receive location with a schedule (No
schedule currently set)

*Writing a script to remove a schedule from a receive location.

I see how to enable/disable a receive location, but I don't see how to manipulate the schedule via script.

A: Create two bindings files, one representing the receive port with schedule and one without. Then use BTSTask importbindings command to import whichever bindings file you want.

A: Check the below article. This may help to create script.
http://msdn.microsoft.com/en-us/library/aa559496.aspx

A: There is no support for scripting the scheduling of a receive location that I'm aware of.
You can achieve this in many other ways though. The simplest being to script the delivery
of the files to the receive location using shell script/etc.

A: Before going down your own scripting route, I'll consider 2 options

*

*Check the schedule/service window capability in Receive Location and see if it solves your problems, else

*There is a community Scheduled task adapter, which is suitable for such activities.
http://biztalkscheduledtask.codeplex.com/


text:
Q: Write Data to parallel port what's the problem with this code :
(Writes 11111111 to LPT1 data pins )
note the OUTPUT at run time is :
run:

Port : LPT1 is detected
Port identified :
javax.comm.CommPortIdentifier@be858
Port opened : LPT1
Out put taken :
java.io.FileOutputStream@1bbe9ba

and still waiting (doing nothing)
package javaapplication9;
import java.io.*;
import java.util.Enumeration;
import javax.comm.CommPortIdentifier;
import javax.comm.NoSuchPortException;
import javax.comm.ParallelPort;
import javax.comm.PortInUseException;
public class JavaApplication9 {

    public static void main(String[] args) throws NoSuchPortException,            IOException {

    ParallelIO p1=new ParallelIO();

}

}
 class ParallelIO {

private static OutputStream outputStream;

private static InputStream inputStream;
private static ParallelPort parallelPort;
private static CommPortIdentifier port;
static int dat=0b11111111;
public static final String PARALLEL_PORT = "LPT1";

public ParallelIO() {
   try {
        //detec the port
        System.out.println("Port : " + PARALLEL_PORT + " is detected");
        // get the parallel port connected to the output
        port = CommPortIdentifier.getPortIdentifier(PARALLEL_PORT);
        //port identified

        System.out.println("Port identified : " + port);

// open the parallel port --
        //port(App name, timeout);
        parallelPort = (ParallelPort) port.open("0x0378", 1200);

        //port opened
        System.out.println("Port opened : " + parallelPort);

         outputStream = parallelPort.getOutputStream( );
         parallelPort.notifyOnBuffer(true);
    //get output
        System.out.println("Out put taken : " + outputStream);
        outputStream.write(dat);
        //data written
        System.out.println("Data Written : " + dat);
        outputStream.flush();
        outputStream.close();

    } catch (NoSuchPortException nspe) {
        System.out.println("\nPrinter Port" +PARALLEL_PORT +"not found :         NoSuchPortException.\nException:\n" + nspe + "\n");
    } catch (PortInUseException piue) {
        System.out.println("\nPrinter Port " +PARALLEL_PORT +" is in use : " +     "PortInUseException.\nException:\n" + piue + "\n");
    } catch (IOException ioe) {
        System.out.println("\nPrinter Port " +PARALLEL_PORT +" failed to write : " + "IOException.\nException:\n" + ioe + "\n");
    } catch (Exception e) {
        System.out.println("\nFailed to open Printer Port " +PARALLEL_PORT +" with exception : " + e.getMessage() +   "\n");
    } finally {
        if (port != null && port.isCurrentlyOwned()) {
        parallelPort.close();
        }
    System.out.println("Closed all resources.\n");
    }
}
 }

A:
Port identified : javax.comm.CommPortIdentifier@be858

is just a hashcode of the class CommPortIdentifier, since there is no
override of the toString method, then you will get a non sence in here,
your write looks ok,
..and still waiting (doing nothing), does this mean you are not able to write the LPT ??? or are you expecting some echo/answer??