问:
Running Celery as Daemon with Supervisor and Django on Elastic Beanstalk
I am attempting to get Celery to run on an EB environment with Django and I have gotten super close to getting it all running. I have this config file for supervisor

```<code>#!/usr/bin/env bash

# Get django environment variables
celeryenv=`cat /opt/python/current/env | tr '\n' ',' | sed 's/export //g' | sed 's/$PATH/%(ENV_PATH)s/g' | sed 's/$PYTHONPATH//g' | sed 's/$LD_LIBRARY_PATH//g'`
celeryenv=${celeryenv%?}

# Create celery configuraiton script
celeryconf="[program:celeryd-worker]
; Set full path to celery program if using virtualenv
command=/opt/python/run/venv/bin/celery worker -A unite --loglevel=INFO

directory=/opt/python/current/app
user=ec2-user
numprocs=1
stdout_logfile=/var/log/celery-worker.log
stderr_logfile=/var/log/celery-worker.log
autostart=true
autorestart=true
startsecs=10

; Need to wait for currently executing tasks to finish at shutdown.
; Increase this if you have very long running tasks.
stopwaitsecs = 600

; When resorting to send SIGKILL to the program to terminate it
; send SIGKILL to its whole process group instead,
; taking care of its children as well.
killasgroup=true

; if rabbitmq is supervised, set its priority higher
; so it starts first
priority=998

environment=$celeryenv,USER="ec2-user"

[program:celeryd-beat]
; Set full path to celery program if using virtualenv
command=/opt/python/run/venv/bin/celery beat -A unite --loglevel=INFO --workdir=/tmp -S django

directory=/opt/python/current/app
user=nobody
numprocs=1
stdout_logfile=/var/log/celery-beat.log
stderr_logfile=/var/log/celery-beat.log
autostart=true
autorestart=true
startsecs=10

; Need to wait for currently executing tasks to finish at shutdown.
; Increase this if you have very long running tasks.
stopwaitsecs = 600

; When resorting to send SIGKILL to the program to terminate it
; send SIGKILL to its whole process group instead,
; taking care of its children as well.
killasgroup=true

; if rabbitmq is supervised, set its priority higher
; so it starts first
priority=998

environment=$celeryenv"

# Create the celery supervisord conf script
echo "$celeryconf" | tee /opt/python/etc/celery.conf

# Add configuration script to supervisord conf (if not there already)
if ! grep -Fxq "[include]" /opt/python/etc/supervisord.conf
  then
  echo "[include]" | tee -a /opt/python/etc/supervisord.conf
  echo "files: celery.conf" | tee -a /opt/python/etc/supervisord.conf
fi

# Reread the supervisord config
echo reread
supervisorctl -c /opt/python/etc/supervisord.conf reread

echo reload
# supervisorctl -c /opt/python/etc/supervisord.conf reload

# Update supervisord in cache without restarting all services
echo update
supervisorctl -c /opt/python/etc/supervisord.conf update

# Start/Restart celeryd through supervisord
echo restart
supervisorctl -c /opt/python/etc/supervisord.conf restart celeryd-beat
supervisorctl -c /opt/python/etc/supervisord.conf restart celeryd-worker
</code>```

As it stands right now when I deploy it celery beat will run (verified by sshing in and using ps -aux | less to see the running processes) but no celeryd-worker. In my activity.log I have this.

```<code>[2017-05-30T17:23:15.243Z] INFO  [8806]  - [Application update app-cebf-170530_101825@6/AppDeployStage1/AppDeployEnactHook/02create_pids_for_monitoring.sh] : Completed activity. Result:
  + chmod 0755 /var/run/httpd
  + /opt/elasticbeanstalk/bin/healthd-track-pidfile --proxy httpd
  + /opt/elasticbeanstalk/bin/healthd-track-pidfile --name application --location /opt/python/run/supervisord.pid
[2017-05-30T17:23:15.243Z] INFO  [8806]  - [Application update app-cebf-170530_101825@6/AppDeployStage1/AppDeployEnactHook] : Completed activity. Result:
  Successfully execute hooks in directory /opt/elasticbeanstalk/hooks/appdeploy/enact.
[2017-05-30T17:23:15.243Z] INFO  [8806]  - [Application update app-cebf-170530_101825@6/AppDeployStage1/AppDeployPostHook] : Starting activity...
[2017-05-30T17:23:15.243Z] INFO  [8806]  - [Application update app-cebf-170530_101825@6/AppDeployStage1/AppDeployPostHook/run_supervised_celeryd.sh] : Starting activity...
[2017-05-30T17:23:37.675Z] INFO  [8806]  - [Application update app-cebf-170530_101825@6/AppDeployStage1/AppDeployPostHook/run_supervised_celeryd.sh] : Completed activity. Result:
  [program:celeryd-worker]
  ; Set full path to celery program if using virtualenv
  command=/opt/python/run/venv/bin/celery worker -A unite --loglevel=INFO

  directory=/opt/python/current/app
  user=ec2-user
  numprocs=1
  stdout_logfile=/var/log/celery-worker.log
  stderr_logfile=/var/log/celery-worker.log
  autostart=true
  autorestart=true
  startsecs=10

  ; Need to wait for currently executing tasks to finish at shutdown.
  ; Increase this if you have very long running tasks.
  stopwaitsecs = 600

  ; When resorting to send SIGKILL to the program to terminate it
  ; send SIGKILL to its whole process group instead,
  ; taking care of its children as well.
  killasgroup=true

  ; if rabbitmq is supervised, set its priority higher
  ; so it starts first
  priority=998

  environment=PYTHONPATH="/opt/python/current/app/:",PATH="/opt/python/run/venv/bin/:%(ENV_PATH)s",DJANGO_SETTINGS_MODULE="settings"

  [program:celeryd-beat]
  ; Set full path to celery program if using virtualenv
  command=/opt/python/run/venv/bin/celery beat -A unite --loglevel=INFO --workdir=/tmp -S django

  directory=/opt/python/current/app
  user=nobody
  numprocs=1
  stdout_logfile=/var/log/celery-beat.log
  stderr_logfile=/var/log/celery-beat.log
  autostart=true
  autorestart=true
  startsecs=10

  ; Need to wait for currently executing tasks to finish at shutdown.
  ; Increase this if you have very long running tasks.
  stopwaitsecs = 600

  ; When resorting to send SIGKILL to the program to terminate it
  ; send SIGKILL to its whole process group instead,
  ; taking care of its children as well.
  killasgroup=true

  ; if rabbitmq is supervised, set its priority higher
  ; so it starts first
  priority=998

  environment=PYTHONPATH="/opt/python/current/app/:",PATH="/opt/python/run/venv/bin/:%(ENV_PATH)s",DJANGO_SETTINGS_MODULE="settings"
  reread
  No config updates to processes
  reload
  update
  restart
  celeryd-beat: stopped
  celeryd-beat: started
  celeryd-worker: ERROR (not running)
  celeryd-worker: ERROR (abnormal termination)
</code>```

so there is something wrong with when I try and start the worker but not with beat.

If I SSH into the EB and look at the /var/log/celery-worker.log file I see this.

```<code>[2017-05-30 12:30:21,370: CRITICAL/MainProcess] Unrecoverable error: ImportError('The curl client requires the pycurl library.',)
Traceback (most recent call last):
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/kombu/async/http/__init__.py", line 20, in get_client
    return hub._current_http_client
AttributeError: 'Hub' object has no attribute '_current_http_client'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/celery/worker/worker.py", line 203, in start
    self.blueprint.start(self)
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/celery/bootsteps.py", line 119, in start
    step.start(parent)
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/celery/bootsteps.py", line 370, in start
    return self.obj.start()
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/celery/worker/consumer/consumer.py", line 318, in start
    blueprint.start(self)
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/celery/bootsteps.py", line 119, in start
    step.start(parent)
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/celery/worker/consumer/consumer.py", line 584, in start
    c.loop(*c.loop_args())
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/celery/worker/loops.py", line 88, in asynloop
    next(loop)
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/kombu/async/hub.py", line 282, in create_loop
    item()
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/vine/promises.py", line 139, in __call__
    return self.throw()
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/vine/promises.py", line 136, in __call__
    retval = fun(*final_args, **final_kwargs)
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/kombu/transport/SQS.py", line 290, in _schedule_queue
    queue, callback=promise(self._loop1, (queue,)),
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/kombu/transport/SQS.py", line 306, in _get_bulk_async
    return self._get_async(queue, maxcount, callback=callback)
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/kombu/transport/SQS.py", line 315, in _get_async
    q, count=count, connection=self.asynsqs,
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/kombu/transport/SQS.py", line 412, in asynsqs
    AsyncSQSConnection, _asynsqs.regions(),
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/kombu/transport/SQS.py", line 400, in _aws_connect_to
    port=port)
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/kombu/async/aws/sqs/connection.py", line 39, in __init__
    https_connection_factory=https_connection_factory, **kwargs
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/kombu/async/aws/connection.py", line 223, in __init__
    AsyncConnection.__init__(self, http_client, **http_client_params)
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/kombu/async/aws/connection.py", line 172, in __init__
    self._httpclient = http_client or get_client()
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/kombu/async/http/__init__.py", line 22, in get_client
    client = hub._current_http_client = Client(hub, **kwargs)
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/kombu/async/http/__init__.py", line 13, in Client
    return CurlClient(hub, **kwargs)
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/kombu/async/http/curl.py", line 43, in __init__
    raise ImportError('The curl client requires the pycurl library.')
ImportError: The curl client requires the pycurl library.
</code>```

Which I also encountered when doing this on my local machine. Although I have made sure that curl is installed using nss with this container command.

```<code>container_commands:
  01_libcurl_ssl_backend:
    command: "export PYCURL_SSL_LIBRARY=nss"
    leader_only: true
</code>```

Which is what pycurl is looking for. I also have pycurl in my requirements file and if I pip freeze I can see that pycurl is installed. I fixed this problem locally by recreating my virtual environment. But not quite sure what to do here.

Edit 1
I added in

```<code>PYCURL_SSL_LIBRARY: nss
</code>```

to my options settings in my config files and was able to deploy and have a slightly different behaviour show up. When looking at the activity log after.

Instead of

```<code>update
restart
celeryd-beat: stopped
celeryd-beat: started
celeryd-worker: ERROR (not running)
celeryd-worker: ERROR (abnormal termination)
</code>```

I got:

```<code>    reread
  celeryd-beat: changed
  celeryd-worker: changed
  reload
  update
  celeryd-beat: stopped
  celeryd-beat: updated process group
  celeryd-worker: stopped
  celeryd-worker: updated process group
  restart
  celeryd-beat: stopped
  celeryd-beat: started
  celeryd-worker: stopped
  celeryd-worker: ERROR (abnormal termination)
</code>```

but the celery-worker.log still has the same error in it about pycurl

答:
1 - Follow the answer of this question: https://stackoverflow.com/a/41097851/3407986

2 - You must add libcurl-devel in packages eb configuration file/section, see my .ebextensions/02_packages.config file:

```<code>packages:
  yum:
    // ... your another packages where ...
    // add libcurl-devel, dependency of pycurl package
    libcurl-devel: []
</code>```

Body:
I am attempting to get Celery to run on an EB environment with Django and I have gotten super close to getting it all running. I have this config file for supervisor

#!/usr/bin/env bash

# Get django environment variables
celeryenv=`cat /opt/python/current/env | tr '\n' ',' | sed 's/export //g' | sed 's/$PATH/%(ENV_PATH)s/g' | sed 's/$PYTHONPATH//g' | sed 's/$LD_LIBRARY_PATH//g'`
celeryenv=${celeryenv%?}

# Create celery configuraiton script
celeryconf="[program:celeryd-worker]
; Set full path to celery program if using virtualenv
command=/opt/python/run/venv/bin/celery worker -A unite --loglevel=INFO

directory=/opt/python/current/app
user=ec2-user
numprocs=1
stdout_logfile=/var/log/celery-worker.log
stderr_logfile=/var/log/celery-worker.log
autostart=true
autorestart=true
startsecs=10

; Need to wait for currently executing tasks to finish at shutdown.
; Increase this if you have very long running tasks.
stopwaitsecs = 600

; When resorting to send SIGKILL to the program to terminate it
; send SIGKILL to its whole process group instead,
; taking care of its children as well.
killasgroup=true

; if rabbitmq is supervised, set its priority higher
; so it starts first
priority=998

environment=$celeryenv,USER="ec2-user"

[program:celeryd-beat]
; Set full path to celery program if using virtualenv
command=/opt/python/run/venv/bin/celery beat -A unite --loglevel=INFO --workdir=/tmp -S django

directory=/opt/python/current/app
user=nobody
numprocs=1
stdout_logfile=/var/log/celery-beat.log
stderr_logfile=/var/log/celery-beat.log
autostart=true
autorestart=true
startsecs=10

; Need to wait for currently executing tasks to finish at shutdown.
; Increase this if you have very long running tasks.
stopwaitsecs = 600

; When resorting to send SIGKILL to the program to terminate it
; send SIGKILL to its whole process group instead,
; taking care of its children as well.
killasgroup=true

; if rabbitmq is supervised, set its priority higher
; so it starts first
priority=998

environment=$celeryenv"

# Create the celery supervisord conf script
echo "$celeryconf" | tee /opt/python/etc/celery.conf

# Add configuration script to supervisord conf (if not there already)
if ! grep -Fxq "[include]" /opt/python/etc/supervisord.conf
  then
  echo "[include]" | tee -a /opt/python/etc/supervisord.conf
  echo "files: celery.conf" | tee -a /opt/python/etc/supervisord.conf
fi

# Reread the supervisord config
echo reread
supervisorctl -c /opt/python/etc/supervisord.conf reread

echo reload
# supervisorctl -c /opt/python/etc/supervisord.conf reload

# Update supervisord in cache without restarting all services
echo update
supervisorctl -c /opt/python/etc/supervisord.conf update

# Start/Restart celeryd through supervisord
echo restart
supervisorctl -c /opt/python/etc/supervisord.conf restart celeryd-beat
supervisorctl -c /opt/python/etc/supervisord.conf restart celeryd-worker

As it stands right now when I deploy it celery beat will run (verified by sshing in and using ps -aux | less to see the running processes) but no celeryd-worker. In my activity.log I have this.

[2017-05-30T17:23:15.243Z] INFO  [8806]  - [Application update app-cebf-170530_101825@6/AppDeployStage1/AppDeployEnactHook/02create_pids_for_monitoring.sh] : Completed activity. Result:
  + chmod 0755 /var/run/httpd
  + /opt/elasticbeanstalk/bin/healthd-track-pidfile --proxy httpd
  + /opt/elasticbeanstalk/bin/healthd-track-pidfile --name application --location /opt/python/run/supervisord.pid
[2017-05-30T17:23:15.243Z] INFO  [8806]  - [Application update app-cebf-170530_101825@6/AppDeployStage1/AppDeployEnactHook] : Completed activity. Result:
  Successfully execute hooks in directory /opt/elasticbeanstalk/hooks/appdeploy/enact.
[2017-05-30T17:23:15.243Z] INFO  [8806]  - [Application update app-cebf-170530_101825@6/AppDeployStage1/AppDeployPostHook] : Starting activity...
[2017-05-30T17:23:15.243Z] INFO  [8806]  - [Application update app-cebf-170530_101825@6/AppDeployStage1/AppDeployPostHook/run_supervised_celeryd.sh] : Starting activity...
[2017-05-30T17:23:37.675Z] INFO  [8806]  - [Application update app-cebf-170530_101825@6/AppDeployStage1/AppDeployPostHook/run_supervised_celeryd.sh] : Completed activity. Result:
  [program:celeryd-worker]
  ; Set full path to celery program if using virtualenv
  command=/opt/python/run/venv/bin/celery worker -A unite --loglevel=INFO

  directory=/opt/python/current/app
  user=ec2-user
  numprocs=1
  stdout_logfile=/var/log/celery-worker.log
  stderr_logfile=/var/log/celery-worker.log
  autostart=true
  autorestart=true
  startsecs=10

  ; Need to wait for currently executing tasks to finish at shutdown.
  ; Increase this if you have very long running tasks.
  stopwaitsecs = 600

  ; When resorting to send SIGKILL to the program to terminate it
  ; send SIGKILL to its whole process group instead,
  ; taking care of its children as well.
  killasgroup=true

  ; if rabbitmq is supervised, set its priority higher
  ; so it starts first
  priority=998

  environment=PYTHONPATH="/opt/python/current/app/:",PATH="/opt/python/run/venv/bin/:%(ENV_PATH)s",DJANGO_SETTINGS_MODULE="settings"

  [program:celeryd-beat]
  ; Set full path to celery program if using virtualenv
  command=/opt/python/run/venv/bin/celery beat -A unite --loglevel=INFO --workdir=/tmp -S django

  directory=/opt/python/current/app
  user=nobody
  numprocs=1
  stdout_logfile=/var/log/celery-beat.log
  stderr_logfile=/var/log/celery-beat.log
  autostart=true
  autorestart=true
  startsecs=10

  ; Need to wait for currently executing tasks to finish at shutdown.
  ; Increase this if you have very long running tasks.
  stopwaitsecs = 600

  ; When resorting to send SIGKILL to the program to terminate it
  ; send SIGKILL to its whole process group instead,
  ; taking care of its children as well.
  killasgroup=true

  ; if rabbitmq is supervised, set its priority higher
  ; so it starts first
  priority=998

  environment=PYTHONPATH="/opt/python/current/app/:",PATH="/opt/python/run/venv/bin/:%(ENV_PATH)s",DJANGO_SETTINGS_MODULE="settings"
  reread
  No config updates to processes
  reload
  update
  restart
  celeryd-beat: stopped
  celeryd-beat: started
  celeryd-worker: ERROR (not running)
  celeryd-worker: ERROR (abnormal termination)

so there is something wrong with when I try and start the worker but not with beat.

If I SSH into the EB and look at the /var/log/celery-worker.log file I see this.

[2017-05-30 12:30:21,370: CRITICAL/MainProcess] Unrecoverable error: ImportError('The curl client requires the pycurl library.',)
Traceback (most recent call last):
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/kombu/async/http/__init__.py", line 20, in get_client
    return hub._current_http_client
AttributeError: 'Hub' object has no attribute '_current_http_client'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/celery/worker/worker.py", line 203, in start
    self.blueprint.start(self)
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/celery/bootsteps.py", line 119, in start
    step.start(parent)
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/celery/bootsteps.py", line 370, in start
    return self.obj.start()
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/celery/worker/consumer/consumer.py", line 318, in start
    blueprint.start(self)
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/celery/bootsteps.py", line 119, in start
    step.start(parent)
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/celery/worker/consumer/consumer.py", line 584, in start
    c.loop(*c.loop_args())
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/celery/worker/loops.py", line 88, in asynloop
    next(loop)
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/kombu/async/hub.py", line 282, in create_loop
    item()
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/vine/promises.py", line 139, in __call__
    return self.throw()
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/vine/promises.py", line 136, in __call__
    retval = fun(*final_args, **final_kwargs)
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/kombu/transport/SQS.py", line 290, in _schedule_queue
    queue, callback=promise(self._loop1, (queue,)),
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/kombu/transport/SQS.py", line 306, in _get_bulk_async
    return self._get_async(queue, maxcount, callback=callback)
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/kombu/transport/SQS.py", line 315, in _get_async
    q, count=count, connection=self.asynsqs,
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/kombu/transport/SQS.py", line 412, in asynsqs
    AsyncSQSConnection, _asynsqs.regions(),
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/kombu/transport/SQS.py", line 400, in _aws_connect_to
    port=port)
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/kombu/async/aws/sqs/connection.py", line 39, in __init__
    https_connection_factory=https_connection_factory, **kwargs
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/kombu/async/aws/connection.py", line 223, in __init__
    AsyncConnection.__init__(self, http_client, **http_client_params)
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/kombu/async/aws/connection.py", line 172, in __init__
    self._httpclient = http_client or get_client()
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/kombu/async/http/__init__.py", line 22, in get_client
    client = hub._current_http_client = Client(hub, **kwargs)
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/kombu/async/http/__init__.py", line 13, in Client
    return CurlClient(hub, **kwargs)
  File "/opt/python/run/venv/local/lib/python3.4/site-packages/kombu/async/http/curl.py", line 43, in __init__
    raise ImportError('The curl client requires the pycurl library.')
ImportError: The curl client requires the pycurl library.

Which I also encountered when doing this on my local machine. Although I have made sure that curl is installed using nss with this container command.

container_commands:
  01_libcurl_ssl_backend:
    command: "export PYCURL_SSL_LIBRARY=nss"
    leader_only: true

Which is what pycurl is looking for. I also have pycurl in my requirements file and if I pip freeze I can see that pycurl is installed. I fixed this problem locally by recreating my virtual environment. But not quite sure what to do here.

Edit 1
I added in

PYCURL_SSL_LIBRARY: nss

to my options settings in my config files and was able to deploy and have a slightly different behaviour show up. When looking at the activity log after.

Instead of

update
restart
celeryd-beat: stopped
celeryd-beat: started
celeryd-worker: ERROR (not running)
celeryd-worker: ERROR (abnormal termination)

I got:

    reread
  celeryd-beat: changed
  celeryd-worker: changed
  reload
  update
  celeryd-beat: stopped
  celeryd-beat: updated process group
  celeryd-worker: stopped
  celeryd-worker: updated process group
  restart
  celeryd-beat: stopped
  celeryd-beat: started
  celeryd-worker: stopped
  celeryd-worker: ERROR (abnormal termination)

but the celery-worker.log still has the same error in it about pycurl

Body:
1 - Follow the answer of this question: https://stackoverflow.com/a/41097851/3407986

2 - You must add libcurl-devel in packages eb configuration file/section, see my .ebextensions/02_packages.config file:

packages:
  yum:
    // ... your another packages where ...
    // add libcurl-devel, dependency of pycurl package
    libcurl-devel: []


来源: stackexchange

问:
Improving the performance of Matrix Multiplication
This is my code for speeding up matrix multiplication, but it is only 5% faster than the simple one.
What can i do to boost it as much as possible?

*The tables are being accessed for example as: C[sub2ind(i,j,n)] for the C[i, j] position.

```<code>void matrixMultFast(float * const C,            /* output matrix */
                float const * const A,      /* first matrix */
                float const * const B,      /* second matrix */
                int const n,                /* number of rows/cols */
                int const ib,               /* size of i block */
                int const jb,               /* size of j block */
                int const kb)               /* size of k block */
{

int i=0, j=0, jj=0, k=0, kk=0;
float sum;

for(i=0;i<n;i++)
    for(j=0;j<n;j++)
        C[sub2ind(i,j,n)]=0;

for(kk=0;kk<n;kk+=kb)
{
    for(jj=0;jj<n;jj+=jb)
    {
        for(i=0;i<n;i++)
        {
            for(j=jj;j<jj+jb;j++)
            {
                sum=C[sub2ind(i,j,n)];
                for(k=kk;k<kk+kb;k++)
                    sum += A[sub2ind(i,k,n)]*B[sub2ind(k,j,n)];
                C[sub2ind(i,j,n)]=sum;
            }
        }
    }
}
} // end function 'matrixMultFast4'
</code>```

*It is written in C and it needs to support C99

答:
There are many, many things you can do to improve the efficiency of matrix multiplication.

To examine how to improve the basic algorithm, let's first take a look at our current options. The naive implementation, of course, has 3 loops with a time complexity of the order of O(n^3). There is another method called Strassen's Method which achieves a appreciable speedup and has the order of O(n^2.73) (but in practice is useless since it offers no appreciable means of optimization).

This is in theory. Now consider how matrices are stored in memory. Row major is the standard, but you find column major too. Depending on the scheme, transposing your matrix might improve speed due to fewer cache misses. Matrix multiplication in theory is just a bunch of vector dot products and addition. The same vector is to be operated upon by multiple vectors, thus it makes sense to keep that vector in cache for faster access.

Now, with the introduction of multiple cores, parallelism and the cache concept, the game changes. If we look a little closely, we see that a dot product is nothing but a bunch of multiplications followed by summations. These multiplications can be done in parallel. Hence, we can now look at parallel loading of numbers.

Now let's make things a little more complicated. When talking about matrix multiplication, there is a distinction between single floating point and double floating point in their size. Often the former is 32 bits while the latter, 64 (of course, this depends on the CPU). Each CPU only has a fixed number of registers, meaning the bigger your numbers, the lesser you can fit in the CPU. Moral of the story is, stick to single floating point unless you really need double.

Now that we've gone through the basics of how we can tune matrix multiplication, worry not. You need do nothing of what has been discussed above since there are already subroutines to do it. As mentioned in the comments, there's GotoBLAS, OpenBLAS, Intel's MKL, and Apple's Accelerate framework. MKL/Accelerate are proprietary, but OpenBLAS is a very competitive alternative.

Here's a nice little example that multiplies 2 8k x 8k matrices in a few milliseconds on my Macintosh:

```<code>#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <Accelerate/Accelerate.h>

int SIZE = 8192;

typedef float point_t;

point_t* transpose(point_t* A) {
    point_t* At = (point_t*) calloc(SIZE * SIZE, sizeof(point_t));
    vDSP_mtrans(A, 1, At, 1, SIZE, SIZE);

    return At;
}

point_t* dot(point_t* A, point_t* B) {
    point_t* C = (point_t*) calloc(SIZE * SIZE, sizeof(point_t));
    int i;
    int step = (SIZE * SIZE / 4);

    cblas_sgemm (CblasRowMajor,
       CblasNoTrans, CblasNoTrans, SIZE/4, SIZE, SIZE,
       1.0, &A[0], SIZE, B, SIZE, 0.0, &C[0], SIZE);

    cblas_sgemm (CblasRowMajor,
       CblasNoTrans, CblasNoTrans, SIZE/4, SIZE, SIZE,
       1.0, &A[step], SIZE, B, SIZE, 0.0, &C[step], SIZE);

    cblas_sgemm (CblasRowMajor,
       CblasNoTrans, CblasNoTrans, SIZE/4, SIZE, SIZE,
       1.0, &A[step * 2], SIZE, B, SIZE, 0.0, &C[step * 2], SIZE);

    cblas_sgemm (CblasRowMajor,
       CblasNoTrans, CblasNoTrans, SIZE/4, SIZE, SIZE,
       1.0, &A[step * 3], SIZE, B, SIZE, 0.0, &C[step * 3], SIZE);

    return C;
}

void print(point_t* A) {
    int i, j;
    for(i = 0; i < SIZE; i++) {
        for(j = 0; j < SIZE; j++) {
            printf("%f  ", A[i * SIZE + j]);
        }
        printf("\n");
    }
}

int main() {
    for(; SIZE <= 8192; SIZE *= 2) {
        point_t* A = (point_t*) calloc(SIZE * SIZE, sizeof(point_t));
        point_t* B = (point_t*) calloc(SIZE * SIZE, sizeof(point_t));

        srand(getpid());

        int i, j;
        for(i = 0; i < SIZE * SIZE; i++) {
            A[i] = ((point_t)rand() / (double)RAND_MAX);
            B[i] = ((point_t)rand() / (double)RAND_MAX);
        }

        struct timeval t1, t2;
        double elapsed_time;

        gettimeofday(&t1, NULL);
        point_t* C = dot(A, B);
        gettimeofday(&t2, NULL);

        elapsed_time = (t2.tv_sec - t1.tv_sec) * 1000.0;      // sec to ms
        elapsed_time += (t2.tv_usec - t1.tv_usec) / 1000.0;   // us to ms

        printf("Time taken for %d size matrix multiplication: %lf\n", SIZE, elapsed_time/1000.0);

        free(A);
        free(B);
        free(C);

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

At this point I should also mention SSE (Streaming SIMD Extension), which is basically something you shouldn't do unless you've worked with assembly. Basically, you're vectorising your C code, to work with vectors instead of integers. This means you can operate on blocks of data instead of single values. The compiler gives up and just translates your code as is without doing its own optimizations. If done right, it can speed up your code like nothing before - you can touch the theoretical floor of O(n^2) even! But it is easy to abuse SSE, and most people unfortunately do, making the end result worse than before.

I hope this motivates you to dig deeper. The world of matrix multiplication is a large and fascinating one. Below, I attach links for further reading.

OpenBLAS

More about SSE

Intel Intrinsics

ContentLicense: CC BY-SA 4.0

Body:
This is my code for speeding up matrix multiplication, but it is only 5% faster than the simple one.
What can i do to boost it as much as possible?

*The tables are being accessed for example as: C[sub2ind(i,j,n)] for the C[i, j] position.

void matrixMultFast(float * const C,            /* output matrix */
                float const * const A,      /* first matrix */
                float const * const B,      /* second matrix */
                int const n,                /* number of rows/cols */
                int const ib,               /* size of i block */
                int const jb,               /* size of j block */
                int const kb)               /* size of k block */
{

int i=0, j=0, jj=0, k=0, kk=0;
float sum;

for(i=0;i<n;i++)
    for(j=0;j<n;j++)
        C[sub2ind(i,j,n)]=0;

for(kk=0;kk<n;kk+=kb)
{
    for(jj=0;jj<n;jj+=jb)
    {
        for(i=0;i<n;i++)
        {
            for(j=jj;j<jj+jb;j++)
            {
                sum=C[sub2ind(i,j,n)];
                for(k=kk;k<kk+kb;k++)
                    sum += A[sub2ind(i,k,n)]*B[sub2ind(k,j,n)];
                C[sub2ind(i,j,n)]=sum;
            }
        }
    }
}
} // end function 'matrixMultFast4'

*It is written in C and it needs to support C99

Body:
There are many, many things you can do to improve the efficiency of matrix multiplication.

To examine how to improve the basic algorithm, let's first take a look at our current options. The naive implementation, of course, has 3 loops with a time complexity of the order of O(n^3). There is another method called Strassen's Method which achieves a appreciable speedup and has the order of O(n^2.73) (but in practice is useless since it offers no appreciable means of optimization).

This is in theory. Now consider how matrices are stored in memory. Row major is the standard, but you find column major too. Depending on the scheme, transposing your matrix might improve speed due to fewer cache misses. Matrix multiplication in theory is just a bunch of vector dot products and addition. The same vector is to be operated upon by multiple vectors, thus it makes sense to keep that vector in cache for faster access.

Now, with the introduction of multiple cores, parallelism and the cache concept, the game changes. If we look a little closely, we see that a dot product is nothing but a bunch of multiplications followed by summations. These multiplications can be done in parallel. Hence, we can now look at parallel loading of numbers.

Now let's make things a little more complicated. When talking about matrix multiplication, there is a distinction between single floating point and double floating point in their size. Often the former is 32 bits while the latter, 64 (of course, this depends on the CPU). Each CPU only has a fixed number of registers, meaning the bigger your numbers, the lesser you can fit in the CPU. Moral of the story is, stick to single floating point unless you really need double.

Now that we've gone through the basics of how we can tune matrix multiplication, worry not. You need do nothing of what has been discussed above since there are already subroutines to do it. As mentioned in the comments, there's GotoBLAS, OpenBLAS, Intel's MKL, and Apple's Accelerate framework. MKL/Accelerate are proprietary, but OpenBLAS is a very competitive alternative.

Here's a nice little example that multiplies 2 8k x 8k matrices in a few milliseconds on my Macintosh:

#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <Accelerate/Accelerate.h>

int SIZE = 8192;

typedef float point_t;

point_t* transpose(point_t* A) {
    point_t* At = (point_t*) calloc(SIZE * SIZE, sizeof(point_t));
    vDSP_mtrans(A, 1, At, 1, SIZE, SIZE);

    return At;
}

point_t* dot(point_t* A, point_t* B) {
    point_t* C = (point_t*) calloc(SIZE * SIZE, sizeof(point_t));
    int i;
    int step = (SIZE * SIZE / 4);

    cblas_sgemm (CblasRowMajor,
       CblasNoTrans, CblasNoTrans, SIZE/4, SIZE, SIZE,
       1.0, &A[0], SIZE, B, SIZE, 0.0, &C[0], SIZE);

    cblas_sgemm (CblasRowMajor,
       CblasNoTrans, CblasNoTrans, SIZE/4, SIZE, SIZE,
       1.0, &A[step], SIZE, B, SIZE, 0.0, &C[step], SIZE);

    cblas_sgemm (CblasRowMajor,
       CblasNoTrans, CblasNoTrans, SIZE/4, SIZE, SIZE,
       1.0, &A[step * 2], SIZE, B, SIZE, 0.0, &C[step * 2], SIZE);

    cblas_sgemm (CblasRowMajor,
       CblasNoTrans, CblasNoTrans, SIZE/4, SIZE, SIZE,
       1.0, &A[step * 3], SIZE, B, SIZE, 0.0, &C[step * 3], SIZE);

    return C;
}

void print(point_t* A) {
    int i, j;
    for(i = 0; i < SIZE; i++) {
        for(j = 0; j < SIZE; j++) {
            printf("%f  ", A[i * SIZE + j]);
        }
        printf("\n");
    }
}

int main() {
    for(; SIZE <= 8192; SIZE *= 2) {
        point_t* A = (point_t*) calloc(SIZE * SIZE, sizeof(point_t));
        point_t* B = (point_t*) calloc(SIZE * SIZE, sizeof(point_t));

        srand(getpid());

        int i, j;
        for(i = 0; i < SIZE * SIZE; i++) {
            A[i] = ((point_t)rand() / (double)RAND_MAX);
            B[i] = ((point_t)rand() / (double)RAND_MAX);
        }

        struct timeval t1, t2;
        double elapsed_time;

        gettimeofday(&t1, NULL);
        point_t* C = dot(A, B);
        gettimeofday(&t2, NULL);

        elapsed_time = (t2.tv_sec - t1.tv_sec) * 1000.0;      // sec to ms
        elapsed_time += (t2.tv_usec - t1.tv_usec) / 1000.0;   // us to ms

        printf("Time taken for %d size matrix multiplication: %lf\n", SIZE, elapsed_time/1000.0);

        free(A);
        free(B);
        free(C);

    }
    return 0;
}

At this point I should also mention SSE (Streaming SIMD Extension), which is basically something you shouldn't do unless you've worked with assembly. Basically, you're vectorising your C code, to work with vectors instead of integers. This means you can operate on blocks of data instead of single values. The compiler gives up and just translates your code as is without doing its own optimizations. If done right, it can speed up your code like nothing before - you can touch the theoretical floor of O(n^2) even! But it is easy to abuse SSE, and most people unfortunately do, making the end result worse than before.

I hope this motivates you to dig deeper. The world of matrix multiplication is a large and fascinating one. Below, I attach links for further reading.

OpenBLAS

More about SSE

Intel Intrinsics


问:
F# - Turn simple for loop into more functional construct
I have this simple "Investment" type with a "lifetime" property:

```<code>type Investment = {
PurchasePayment: float;
Lifetime: float;
TaxWriteoff: float;
ResidualValue: float;
}

let CoffeMachine = {
    PurchasePayment = 13000.0;
    Lifetime = 4.0;
    TaxWriteoff = 2000.0;
    ResidualValue = 500.0;
}
</code>```

I would like to iterate over the years of investment and perform some calculations for each year:

```<code>for i = 1 to int CoffeMachine.Lifetime do
    printf "%i" i
    // doSomething
</code>```

Is there a way to avoid using for loop for that and write it in a more functional style?

Cheers,

Wojtek

答:
A couple of short examples of recursive ways to do this. Usually, you'll just use .iter or .map, though.

```<code>let rec map f = function
  | [] -> []
  | h::t -> f h::map f t

map (fun x->x+1) [1;2;3]

let rec iter f = function
  | [] -> ()
  | h::t ->
      f h
      iter f t
</code>```

Signatures:

```<code>for iter, f:('a -> unit)

for map, f:('a -> 'b)
</code>```

You get standard looping syntax, too:

```<code>for i in [0 .. 4] do
  printfn "%i" i

for i = 0 to 4 do
  printfn "%i" i
</code>```

To use a for loop in a functional way, this syntax can be convenient:

```<code>[for i in [0..10]->i]

[for i = 0 to 10 do yield i]
</code>```

note that

List.map f [0..10] is equivalent to [for i in [0..10]->i]

ContentLicense: CC BY-SA 3.0

Body:
I have this simple "Investment" type with a "lifetime" property:

type Investment = {
PurchasePayment: float;
Lifetime: float;
TaxWriteoff: float;
ResidualValue: float;
}

let CoffeMachine = {
    PurchasePayment = 13000.0;
    Lifetime = 4.0;
    TaxWriteoff = 2000.0;
    ResidualValue = 500.0;
}

I would like to iterate over the years of investment and perform some calculations for each year:

for i = 1 to int CoffeMachine.Lifetime do
    printf "%i" i
    // doSomething

Is there a way to avoid using for loop for that and write it in a more functional style?

Cheers,

Wojtek

Body:
A couple of short examples of recursive ways to do this. Usually, you'll just use .iter or .map, though.

let rec map f = function
  | [] -> []
  | h::t -> f h::map f t

map (fun x->x+1) [1;2;3]

let rec iter f = function
  | [] -> ()
  | h::t ->
      f h
      iter f t

Signatures:

for iter, f:('a -> unit)

for map, f:('a -> 'b)

You get standard looping syntax, too:

for i in [0 .. 4] do
  printfn "%i" i

for i = 0 to 4 do
  printfn "%i" i

To use a for loop in a functional way, this syntax can be convenient:

[for i in [0..10]->i]

[for i = 0 to 10 do yield i]

note that

List.map f [0..10] is equivalent to [for i in [0..10]->i]


问:
Query custom post types and return one post from EACH custom post type
I have set up a query to search through some custom post types that I have set up. I can get it to show all the post so I know it is searching the custom post types that I want. But what I cant figure out is how to have it just return ONE post from each custom post type that I am searching.

Example: I have 4 custom post types. CPT1, CPT2, CPT3, CPT4. I want to get one post from CPT1, one post from CPT2, etc. etc. so that way in the loop it would be: title of CPT1, title of CPT2, etc etc.

Then I figured I could do a query for each custom post type and make it each have their own loop, but that seems like a lot of code for that. Thank you for any help in advanced.

This is the code I have now:

```<code>$mystate = get_state();

// args
$args = array(
    'numberposts'   => -1,
    'post_type'     => array('CPT1','CPT2','CPT3','CPT4'),
    'meta_key'      => 'state_420',
    'meta_value'    => $mystate,
    'order' => 'ASC',

);

/ query
$the_query = new WP_Query( $args );

?>

<?php
        if ( $the_query->have_posts() ) : ?>

            <?php
            /* Start the Loop */
            while ( $the_query->have_posts() ) : $the_query->the_post();

                /**
                 * Run the loop for the search to output the results.
                 * If you want to overload this in a child theme then include a file
                 * called content-search.php and that will be used instead.
                 */
                ?>

                <li style="display: inline-block;"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>, </li>
<?php

            endwhile;

             the_posts_pagination( array( 'mid_size' => 2 ) );

        else :

            get_template_part( 'template-parts/content', 'none' );

        endif; ?>
<?php wp_reset_query();  // Restore global post data stomped by the_post(). ?>
</code>```

答: You should pass this argument posts_per_page=>1</p>

Body:
I have set up a query to search through some custom post types that I have set up. I can get it to show all the post so I know it is searching the custom post types that I want. But what I cant figure out is how to have it just return ONE post from each custom post type that I am searching.

Example: I have 4 custom post types. CPT1, CPT2, CPT3, CPT4. I want to get one post from CPT1, one post from CPT2, etc. etc. so that way in the loop it would be: title of CPT1, title of CPT2, etc etc.

Then I figured I could do a query for each custom post type and make it each have their own loop, but that seems like a lot of code for that. Thank you for any help in advanced.

This is the code I have now:

$mystate = get_state();

// args
$args = array(
    'numberposts'   => -1,
    'post_type'     => array('CPT1','CPT2','CPT3','CPT4'),
    'meta_key'      => 'state_420',
    'meta_value'    => $mystate,
    'order' => 'ASC',

);

/ query
$the_query = new WP_Query( $args );

?>

<?php
        if ( $the_query->have_posts() ) : ?>

            <?php
            /* Start the Loop */
            while ( $the_query->have_posts() ) : $the_query->the_post();

                /**
                 * Run the loop for the search to output the results.
                 * If you want to overload this in a child theme then include a file
                 * called content-search.php and that will be used instead.
                 */
                ?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>,

<?php

            endwhile;

             the_posts_pagination( array( 'mid_size' => 2 ) );

        else :

            get_template_part( 'template-parts/content', 'none' );

        endif; ?>
<?php wp_reset_query();  // Restore global post data stomped by the_post(). ?>


问:
lucene.net problem with wildcard "*"
hello i have a question to lucene searching syntax

the "" is a wildcard.
when i search  te  : i find test ,...
but when i search *st  i don't find "test :>
whats the issue?

and i have a search concerning the text and an other search concerning the filename

in the filename search i use ""+searchstring ""
in the textsearch just "searchstring"

what can i do when i search both, but filename with "" ""

```<code>parser = New MultiFieldQueryParser(New [String]() {"title", "bodytext"}, New StandardAnalyzer())
</code>```

答:
The default setting in the QueryParser is to not allow leading wildcards.

You can alter this with setting property on the QueryParser -  SetAllowLeadingWildcard(true);

Be aware though the performance can take a major tumble since you potentially open up a huge number of hits with this kind of wildcard search.

Roger

ContentLicense: CC BY-SA 2.5

Title: lucene.net problem with wildcard "*"

Body:
hello i have a question to lucene searching syntax

the "" is a wildcard.
when i search  te  : i find test ,...
but when i search *st  i don't find "test :>
whats the issue?

and i have a search concerning the text and an other search concerning the filename

in the filename search i use ""+searchstring ""
in the textsearch just "searchstring"

what can i do when i search both, but filename with "" ""

parser = New MultiFieldQueryParser(New [String]() {"title", "bodytext"}, New StandardAnalyzer())


问:
go lang too many arguments in call
I am enhancing this Golang project: https://github.com/webrtc/apprtc/blob/master/src/collider/collider/collider.go

I added new parameters to the Run method:

```<code>// Run starts the collider server and blocks the thread until the program exits.
func (c *Collider) Run(p int, useTls bool, cert string, key string) {
    http.Handle("/ws", websocket.Handler(c.wsHandler))
    http.HandleFunc("/status", c.httpStatusHandler)
    http.HandleFunc("/", c.httpHandler)

    var e error
</code>```

and it is invoked from main.go:

https://github.com/webrtc/apprtc/blob/master/src/collider/collidermain/main.go

```<code>// run the program
func (p *program) run() {
    configuration := InitConfiguration()

    log.Printf("Running collider: tls = %t, port = %d, room_server=%s",
                configuration.Tls, configuration.Port, configuration.RoomServer)

    c := collider.NewCollider(configuration.RoomServer)
    c.Run(configuration.Port, configuration.Tls, configuration.Cert, configuration.Key)
}
</code>```

For some reasons I keep getting the below error:

```<code>/usr/local/go/src/collidermain/main.go:84: too many arguments in call to c.Run
</code>```

I cross checked the src in:
/usr/local/go/src/collider
/usr/local/go/src/collidermain

Everything is fine. Not sure why this error keeps happening.

Any thoughts?

答:
I finally fixed it before uninstalling go.

I removed the /usr/local/go folder and reinstalled.

Note: collider folder in /usr/local/go/collider had my changes previously and still collidermain didn't link properly with it. Must have been a cached build intermediates?

Title: go lang too many arguments in call

Body:
I am enhancing this Golang project: https://github.com/webrtc/apprtc/blob/master/src/collider/collider/collider.go

I added new parameters to the Run method:

// Run starts the collider server and blocks the thread until the program exits.
func (c *Collider) Run(p int, useTls bool, cert string, key string) {
    http.Handle("/ws", websocket.Handler(c.wsHandler))
    http.HandleFunc("/status", c.httpStatusHandler)
    http.HandleFunc("/", c.httpHandler)

    var e error

and it is invoked from main.go:

https://github.com/webrtc/apprtc/blob/master/src/collider/collidermain/main.go

// run the program
func (p *program) run() {
    configuration := InitConfiguration()

    log.Printf("Running collider: tls = %t, port = %d, room_server=%s",
                configuration.Tls, configuration.Port, configuration.RoomServer)

    c := collider.NewCollider(configuration.RoomServer)
    c.Run(configuration.Port, configuration.Tls, configuration.Cert, configuration.Key)
}

For some reasons I keep getting the below error:

/usr/local/go/src/collidermain/main.go:84: too many arguments in call to c.Run

I cross checked the src in:
/usr/local/go/src/collider
/usr/local/go/src/collidermain

Everything is fine. Not sure why this error keeps happening.

Any thoughts?


问:
Each loop explained?
Assuming person is a javascript object that has firstname & lastname, in an each loop in jade (pug) template how do I render something like :

```<code><li>
     <div>{person.firstname} ({person.lastname})</div>
</li>
</code>```

Below is what I got so far but it's kinda confusing me with the equal sign in the official documentation and couldn't find any example where the each loop uses multiple attributes of the person object through loop.

```<code>each person in persons
  li
    div
      = person.firstname
      = person.email
</code>```

The parenthesis are needed for the person.lastname and not a mistake.

答:
For anyone who struggled  : loop array of objects in meteor using jade

Way much easier & clearer than the provided syntax with "=" at https://pugjs.org/language/iteration.html

Title: Each loop explained?

Body:
Assuming person is a javascript object that has firstname & lastname, in an each loop in jade (pug) template how do I render something like :

{person.firstname} ({person.lastname})

Below is what I got so far but it's kinda confusing me with the equal sign in the official documentation and couldn't find any example where the each loop uses multiple attributes of the person object through loop.

each person in persons
  li
    div
      = person.firstname
      = person.email

The parenthesis are needed for the person.lastname and not a mistake.


问:
How to ease nested looping?
I find myself looping over vectors of vectors a lot:

```<code>std::vector<std::vector<int> > foo;

for(unsigned int i=0; i != foo.size(); ++i) {
 for(unsigned int j=0; j != foo[i].size(); ++j) {
  // use foo[i][j]
 }
}
</code>```

I don't have a good minimal example why the "data" is represented best by a vector of vectors of int but let's don't doubt it here.

What do you suggest to simplify the looping? I could think of a function that implements the explicit looping and takes a pointer to a function for the body.

How to "generate" nested for-loops in case of more levels?

Are there languages that have "built-in" support for "nested looping"?

Thanks in advance,

Somebody

答:
I could think of a function that
  implements the explicit looping and
  takes a pointer to a function for the
  body.

Seems like the visitor pattern:

http://en.wikipedia.org/wiki/Visitor_pattern

edit:

I have not tested the template part but something like this:

```<code>class Visitor
{
    public:
        template<typename T>
        void visit(const std::vector<T> &vector)
        {
            for(typename std::vector<T>::const_iterator it(vector.begin());
                it != vector.end();
                ++it)
            {
                visit(*it);
            }
        }

        void visit(int i)
        {
            // do something with i
        }
}

// usage:
std::vector<std::vector<int> > theData;

Visitor v;
v.visit(theData);
std::cout << v.result() << std::endl;
</code>```

Title: How to ease nested looping?

Body:
I find myself looping over vectors of vectors a lot:

std::vector<std::vector<int> > foo;

for(unsigned int i=0; i != foo.size(); ++i) {
 for(unsigned int j=0; j != foo[i].size(); ++j) {
  // use foo[i][j]
 }
}

I don't have a good minimal example why the "data" is represented best by a vector of vectors of int but let's don't doubt it here.

What do you suggest to simplify the looping? I could think of a function that implements the explicit looping and takes a pointer to a function for the body.

How to "generate" nested for-loops in case of more levels?

Are there languages that have "built-in" support for "nested looping"?

Thanks in advance,

Somebody

Body:
I could think of a function that
  implements the explicit looping and
  takes a pointer to a function for the
  body.

Seems like the visitor pattern:

http://en.wikipedia.org/wiki/Visitor_pattern

edit:

I have not tested the template part but something like this:

class Visitor
{
    public:
        template<typename T>
        void visit(const std::vector<T> &vector)
        {
            for(typename std::vector<T>::const_iterator it(vector.begin());
                it != vector.end();
                ++it)
            {
                visit(*it);
            }
        }

        void visit(int i)
        {
            // do something with i
        }
}

// usage:
std::vector<std::vector<int> > theData;

Visitor v;
v.visit(theData);
std::cout << v.result() << std::endl;


问:
bootstrap glyphicon as button display on table
I'm new to the whole bootstrap thing so even though i tried to solve this for last 3 hours, i could'nt. I need a table to have 2 buttons in a cell that looks like a glypicon (so i can add javascript functions to them later). I managed to do this in 2 ways, but the problem is these buttons expand table row a lot. How do i solve this? maybe alternate method of making a button?

Here is how the table looks right now:

https://puu.sh/wbMUf/50a535e0f9.png

here are the lines used to achieve the result for the cell in the first row:

```<code><td>
    <p class = "btn"><span class = "fa fa-edit"></span></p>
    <p class = "btn"><span class = "fa fa-trash"></span></p>
</td>
</code>```

and for the cell in the second row:

```<code><td>
    <button type = "button" class = "btn btn-link"><span class = "fa fa-edit"></span></button>
    <button type = "button" class = "btn btn-link"><span class = "fa fa-trash"></span></button>
</td>
</code>```

Second option doesnt work, because the glyphs have to styled the same as the rest of the text in the table.

答:
you can give td width:10%; or less.

for extra space, check margin-top and margin-bottom in css.

Body:
I'm new to the whole bootstrap thing so even though i tried to solve this for last 3 hours, i could'nt. I need a table to have 2 buttons in a cell that looks like a glypicon (so i can add javascript functions to them later). I managed to do this in 2 ways, but the problem is these buttons expand table row a lot. How do i solve this? maybe alternate method of making a button?

Here is how the table looks right now:

https://puu.sh/wbMUf/50a535e0f9.png

here are the lines used to achieve the result for the cell in the first row:

and for the cell in the second row:

    <button type = "button" class = "btn btn-link"></button>
    <button type = "button" class = "btn btn-link"></button>

Second option doesnt work, because the glyphs have to styled the same as the rest of the text in the table.


问:
Two questions on Team Foundation Server 2010
I've some questions about TFS 2010.

1) Do you know an easy way to move a work item from a project to another one using Team Explorer?

2) Can TFS's reporting portal show work items of all projects in some collection in the same listing?

Thank you very much.

答:
1) No, you can't.  Each project has separate set of work item type definitions, so moving from one project to another isn't supported.

2) Yes, you can - just tell your report not to filter by project.


问:
Cannot change Azure tier using SSMS
I am the database owner on my Azure Database and I confirmed that using SELECT IS_MEMBER('db_owner') (returns 1)
When I try to run the command:

```<code>ALTER DATABASE [db] MODIFY (EDITION = 'standard', SERVICE_OBJECTIVE = 'S3');
</code>```

it gives me the error as follows:

```<code>User does not have permission to alter database 'db', the database does not exist, or the database is not in a state that allows access checks.
</code>```

So I tried to grant myself the alter permissions on the database:

```<code>GRANT ALTER ON DATABASE:: db TO [USER_NAME]

Cannot grant, deny, or revoke permissions to sa, dbo, entity owner, information_schema, sys, or yourself.
</code>```

I dont know why I cant change the Azure Edition through script. I have done this through the Azure dashboard portal and it works just fine. But not through SSMS. Am I doing something wrong?

答:
Go look at the documentation. Just because you are owner does not mean you can alter the database.

https://learn.microsoft.com/en-us/sql/t-sql/statements/alter-database-azure-sql-database

Title: Cannot change Azure tier using SSMS

Body:
I am the database owner on my Azure Database and I confirmed that using SELECT IS_MEMBER('db_owner') (returns 1)
When I try to run the command:

ALTER DATABASE [db] MODIFY (EDITION = 'standard', SERVICE_OBJECTIVE = 'S3');

it gives me the error as follows:

User does not have permission to alter database 'db', the database does not exist, or the database is not in a state that allows access checks.

So I tried to grant myself the alter permissions on the database:

GRANT ALTER ON DATABASE:: db TO [USER_NAME]

Cannot grant, deny, or revoke permissions to sa, dbo, entity owner, information_schema, sys, or yourself.

I dont know why I cant change the Azure Edition through script. I have done this through the Azure dashboard portal and it works just fine. But not through SSMS. Am I doing something wrong?


问:
Elastic search language configuration
I work on a project with symfony and sonata admin,
my project will be in two language: fr and de so i used elastic search so i installed "friendsofsymfony/elastica-bundle": "3.2.1".
in the elasticconfiguration file how can add the language configuration?
this is my fos elastic bundle configuration file:</p>

```<code>fos_elastica:
    clients:
        default: { host: %elastic_host%, port: %elastic_port% }
    indexes:
        myproject:
            settings:
                index:
                    analysis:
                       analyzer:
                           custom_analyzer :
                               type     :    custom
                               tokenizer:    nGram
                               filter   :    [stopwords, asciifolding ,lowercase, elision, worddelimiter]
                           custom_search_analyzer :
                               type     :    custom
                               tokenizer:    standard
                               filter   :    [stopwords, asciifolding ,lowercase, elision, worddelimiter]
                       tokenizer:
                           nGram:
                               type:     nGram
                               min_gram: 3
                               max_gram: 20
                       filter:
                           elision:
                               type:     elision
                               articles: [l, m, t, qu, n, s, j, d]
                           stopwords:
                               type:      stop
                               stopwords: [_french_]
                               ignore_case : true
                           worddelimiter:
                               type:      word_delimiter

            types:
                produit:
                    mappings:
                        titre: ~
                        active:
                            type: boolean
                        descriptifTexteOriginal:
                            index_analyzer: custom_analyzer
                            search_analyzer : custom_search_analyzer
                            type: string
                            norms: { enabled: false }
                            explain: true
                            index_options: freqs

                    persistence:
                        driver: orm
                        model: myproject\BOBundle\Entity\Produit
                        finder: ~
                        provider: ~
                        listener: ~
</code>```

答:
In base, we will about two situtaion. First one is you have a field and it can store
two or more different language text. For example, you have a title field which can
store english or turkish. Not both of them is at the same time. The second situation
is, your data have multiple language value in one document.

In my opinion, there is two way of this problem, too. First is separate your fields
and second is separating index. Let's explain both of them to you:

Think about you have the following data for your products on e-commerce website:

```<code>id => identify of your data
name => name of the product
price => price of the product
</code>```

Our first opinion has multiple option. Now, let's look our first option of the first
opinion and create a mapping:

```<code>PUT 44369578
{
  "mappings": {
    "product": {
      "properties": {
        "id": { "type": "integer" },
        "name": {
          "type": "text",
          "fields": {
            "en": {
              "type": "text",
              "analyzer": "englishAnalyzer"
            },
            "tr": {
              "type": "text",
              "analyzer": "turkishAnalyzer"
            }
          }
        },
        "price": { "type": "double"}
      }
    }
  }
}
</code>```

There is a name field which can take english or turkish value
And in this field only can handle one of them. Not both of them
When you try to improve your language support, you should change your mapping, too.

Then, let's look our second options of the first opinion.

```<code>PUT 44369578
{
  "mappings": {
    "product": {
      "properties": {
        "id": { "type": "integer" },
        "name_en": {"type": "text", "analyzer": "englishAnalyzer" },
        "name_tr": {"type": "text", "analyzer": "turkishAnalyzer" },
        "price": { "type": "double"}
      }
    }
  }
}
</code>```

In this example there is two field for our two language. And we can
save english and turkish values for our documents at the same time.
When you try to improve your language support, you should change your mapping, too.
These are two options of the first opinion.

Now, lets look our second opinion. In this example, we have same data structure for
product documents. But we create multiple indexes for each languages.

```<code>PUT 44369578
{
  "mappings": {
    "product": {
      "properties": {
        "id": { "type": "integer" },
        "name": {"type": "text", "analyzer": "englishAnalyzer" },
        "price": { "type": "double"}
      }
    }
  }
}

PUT 44369578
{
  "mappings": {
    "product": {
      "properties": {
        "id": { "type": "integer" },
        "name": {"type": "text", "analyzer": "turkishAnalyzer" },
        "price": { "type": "double"}
      }
    }
  }
}
</code>```

In this opinion, we have two documents for each document and we try to merge the
documents on our application while we are searching documents. This is odd part of
this opinion. But we can create a new index while we create a new language support.

Conclusion, As far as, I know these three methods. You can select one of them and
don't forget, each election will get some features but take away some features.

Title: Elastic search language configuration

Body:
I work on a project with symfony and sonata admin,
my project will be in two language: fr and de so i used elastic search so i installed "friendsofsymfony/elastica-bundle": "3.2.1".
in the elasticconfiguration file how can add the language configuration?
this is my fos elastic bundle configuration file:

fos_elastica:
    clients:
        default: { host: %elastic_host%, port: %elastic_port% }
    indexes:
        myproject:
            settings:
                index:
                    analysis:
                       analyzer:
                           custom_analyzer :
                               type     :    custom
                               tokenizer:    nGram
                               filter   :    [stopwords, asciifolding ,lowercase, elision, worddelimiter]
                           custom_search_analyzer :
                               type     :    custom
                               tokenizer:    standard
                               filter   :    [stopwords, asciifolding ,lowercase, elision, worddelimiter]
                       tokenizer:
                           nGram:
                               type:     nGram
                               min_gram: 3
                               max_gram: 20
                       filter:
                           elision:
                               type:     elision
                               articles: [l, m, t, qu, n, s, j, d]
                           stopwords:
                               type:      stop
                               stopwords: [_french_]
                               ignore_case : true
                           worddelimiter:
                               type:      word_delimiter

            types:
                produit:
                    mappings:
                        titre: ~
                        active:
                            type: boolean
                        descriptifTexteOriginal:
                            index_analyzer: custom_analyzer
                            search_analyzer : custom_search_analyzer
                            type: string
                            norms: { enabled: false }
                            explain: true
                            index_options: freqs

                    persistence:
                        driver: orm
                        model: myproject\BOBundle\Entity\Produit
                        finder: ~
                        provider: ~
                        listener: ~

Body:
In base, we will about two situtaion. First one is you have a field and it can store
two or more different language text. For example, you have a title field which can
store english or turkish. Not both of them is at the same time. The second situation
is, your data have multiple language value in one document.

In my opinion, there is two way of this problem, too. First is separate your fields
and second is separating index. Let's explain both of them to you:

Think about you have the following data for your products on e-commerce website:

id => identify of your data
name => name of the product
price => price of the product

Our first opinion has multiple option. Now, let's look our first option of the first
opinion and create a mapping:

PUT 44369578
{
  "mappings": {
    "product": {
      "properties": {
        "id": { "type": "integer" },
        "name": {
          "type": "text",
          "fields": {
            "en": {
              "type": "text",
              "analyzer": "englishAnalyzer"
            },
            "tr": {
              "type": "text",
              "analyzer": "turkishAnalyzer"
            }
          }
        },
        "price": { "type": "double"}
      }
    }
  }
}

There is a name field which can take english or turkish value
And in this field only can handle one of them. Not both of them
When you try to improve your language support, you should change your mapping, too.

Then, let's look our second options of the first opinion.

PUT 44369578
{
  "mappings": {
    "product": {
      "properties": {
        "id": { "type": "integer" },
        "name_en": {"type": "text", "analyzer": "englishAnalyzer" },
        "name_tr": {"type": "text", "analyzer": "turkishAnalyzer" },
        "price": { "type": "double"}
      }
    }
  }
}

In this example there is two field for our two language. And we can
save english and turkish values for our documents at the same time.
When you try to improve your language support, you should change your mapping, too.
These are two options of the first opinion.

Now, lets look our second opinion. In this example, we have same data structure for
product documents. But we create multiple indexes for each languages.

PUT 44369578
{
  "mappings": {
    "product": {
      "properties": {
        "id": { "type": "integer" },
        "name": {"type": "text", "analyzer": "englishAnalyzer" },
        "price": { "type": "double"}
      }
    }
  }
}

PUT 44369578
{
  "mappings": {
    "product": {
      "properties": {
        "id": { "type": "integer" },
        "name": {"type": "text", "analyzer": "turkishAnalyzer" },
        "price": { "type": "double"}
      }
    }
  }
}

In this opinion, we have two documents for each document and we try to merge the
documents on our application while we are searching documents. This is odd part of
this opinion. But we can create a new index while we create a new language support.

Conclusion, As far as, I know these three methods. You can select one of them and
don't forget, each election will get some features but take away some features.


问:
Javascript - move all commas in a string to a new position
in a given string, I want to move all commas at the ends of words in a string to the end of the word before the word they are attached to.
ex: "sometime soon the, cat said let's, go!" would read: "sometime soon, the cat said, let's go!"
any suggestions?</p>

答:
One way to do this is with RegExp and string.replace():

```<code>  str.replace(/(\w*)(,)/g, '$2$1');
</code>```

What this is doing is capturing a line of word characters \w* that are succeeded by commas in two separate capture groups. The second parameter actually allows us to reference these capture groups in what we should replace the matched substring with!

Body:
One way to do this is with RegExp and string.replace():

  str.replace(/(\w*)(,)/g, '$2$1');

What this is doing is capturing a line of word characters \w* that are succeeded by commas in two separate capture groups. The second parameter actually allows us to reference these capture groups in what we should replace the matched substring with!


问:
How to Convert String to Char and Integer in Java ?
I have the following :

String contain 5* ;

char opr ;

int data ;

I would like to store the 5 in the data and * in the opr

any idea how to do it ?
 as i know if the string contain only Integer then I will split and the parse it but in this case the String contain int and char

Input :

String input = 5* ;

I want the Output will be like this :

this.opr = *

this.data = 5

答:
A simple way to achieve that (if you don't want to use Regex) is to do something like this:

```<code>String temp ="";
// read every char in the input String
for(char c: input.toCharArray()){
   // if it's a digit
   if(Character.isDigit(c)){
       temp +=c; // append it
   }
   else{ // at the end parse the temp String
        data = Integer.parseInt(temp);
        opr = c;
        break;
   }
}

//test
System.out.println("Input: " + input
                    + "\t Data: " + data
                    + "\t Opr: " + opr);
</code>```

Test

```<code>Input: 5*    Data: 5     Opr: *
Input: 123*  Data: 123   Opr: *
</code>```

Body:
A simple way to achieve that (if you don't want to use Regex) is to do something like this:

String temp ="";
// read every char in the input String
for(char c: input.toCharArray()){
   // if it's a digit
   if(Character.isDigit(c)){
       temp +=c; // append it
   }
   else{ // at the end parse the temp String
        data = Integer.parseInt(temp);
        opr = c;
        break;
   }
}

//test
System.out.println("Input: " + input
                    + "\t Data: " + data
                    + "\t Opr: " + opr);

Test

Input: 5*    Data: 5     Opr: *
Input: 123*  Data: 123   Opr: *


问:
R & XML2: Replace missing XML elements with NA
I'm using XML2 to pull publication data out of an online XML doc, like this one, with this code:

```<code>xF <- read_xml(target, encoding = "UTF-8")   ## target = above link
</code>```

No problems getting items that exist for each publication node.

```<code>Titles <- xml_text(xml_find_all(xF, "//publication-base_uk:title", xml_ns(xF)))
Pub.Lang <- xml_text(xml_find_all(xF, "//publication-base_uk:language/core:term/core:localizedString", xml_ns(xF)))
## etc...
</code>```

However, I'm stumped as to how to get items that don't always have an entry, like the peer review tag.

```<code>Peer.Rev <- xml_text(xml_find_all(xF, "//extensions-core:peerReviewed", xml_ns(xF)))
</code>```

Returns a value for all of the publications with a child for peerReviewed but since some of the peerReviewed tags have no child, the count is off. Is there a way to put an NA (or anything really) in place of the missing text values?

Thanks an advance.

答:
Using xml2::xml_find_first() should get you what you want.

Example:

Let's say we want the blog post categories from this xml rss feed:
https://eagereyes.org/feed. Some of these posts have one category, some have more than one. Searching for one works just fine:

```<code>feed <- "https://eagereyes.org/feed"
doc <- httr::GET(feed) %>% xml2::read_xml()
channel <- xml2::xml_find_all(doc, "channel")
site <- xml2::xml_find_all(channel, "item")

categories <- tibble::tibble(
    category1 = xml2::xml_text(xml2::xml_find_all(site, "category[1]"))
  )

> categories
# A tibble: 10 x 1
       category1
           <chr>
 1        Papers
 2     Blog 2017
 3         Links
 4     Blog 2017
 5     Blog 2017
 6          Talk
 7 ISOTYPE Books
 8    Techniques
 9        Basics
10     Blog 2017
</code>```

But trying this for more than one does not:

```<code>categories <- tibble::tibble(
    category1 = xml2::xml_text(xml2::xml_find_all(site, "category[1]")),
    category2 = xml2::xml_text(xml2::xml_find_all(site, "category[2]"))
  )

Error: Column `category2` must be length 1 or 10, not 3
</code>```

xml_find_first to the rescue:

```<code>categories <- tibble::tibble(
    category1 = xml2::xml_text(xml2::xml_find_first(site, "category[1]")),
    category2 = xml2::xml_text(xml2::xml_find_first(site, "category[2]"))
  )
> categories
# A tibble: 10 x 2
       category1  category2
           <chr>      <chr>
 1        Papers      paper
 2     Blog 2017 conference
 3         Links       <NA>
 4     Blog 2017       <NA>
 5     Blog 2017       <NA>
 6          Talk       <NA>
 7 ISOTYPE Books    isotype
 8    Techniques       <NA>
 9        Basics       <NA>
10     Blog 2017       <NA>
</code>```

Hope that helps.

Body:
I'm using XML2 to pull publication data out of an online XML doc, like this one, with this code:

xF <- read_xml(target, encoding = "UTF-8")   ## target = above link

No problems getting items that exist for each publication node.

Titles <- xml_text(xml_find_all(xF, "//publication-base_uk:title", xml_ns(xF)))
Pub.Lang <- xml_text(xml_find_all(xF, "//publication-base_uk:language/core:term/core:localizedString", xml_ns(xF)))
## etc...

However, I'm stumped as to how to get items that don't always have an entry, like the peer review tag.

Peer.Rev <- xml_text(xml_find_all(xF, "//extensions-core:peerReviewed", xml_ns(xF)))

Returns a value for all of the publications with a child for peerReviewed but since some of the peerReviewed tags have no child, the count is off. Is there a way to put an NA (or anything really) in place of the missing text values?

Thanks an advance.

Body:
Using xml2::xml_find_first() should get you what you want.

Example:

Let's say we want the blog post categories from this xml rss feed:
https://eagereyes.org/feed. Some of these posts have one category, some have more than one. Searching for one works just fine:

feed <- "https://eagereyes.org/feed"
doc <- httr::GET(feed) %>% xml2::read_xml()
channel <- xml2::xml_find_all(doc, "channel")
site <- xml2::xml_find_all(channel, "item")

categories <- tibble::tibble(
    category1 = xml2::xml_text(xml2::xml_find_all(site, "category[1]"))
  )

> categories
# A tibble: 10 x 1
       category1
           <chr>
 1        Papers
 2     Blog 2017
 3         Links
 4     Blog 2017
 5     Blog 2017
 6          Talk
 7 ISOTYPE Books
 8    Techniques
 9        Basics
10     Blog 2017

But trying this for more than one does not:

categories <- tibble::tibble(
    category1 = xml2::xml_text(xml2::xml_find_all(site, "category[1]")),
    category2 = xml2::xml_text(xml2::xml_find_all(site, "category[2]"))
  )

Error: Column `category2` must be length 1 or 10, not 3

xml_find_first to the rescue:

categories <- tibble::tibble(
    category1 = xml2::xml_text(xml2::xml_find_first(site, "category[1]")),
    category2 = xml2::xml_text(xml2::xml_find_first(site, "category[2]"))
  )
> categories
# A tibble: 10 x 2
       category1  category2
           <chr>      <chr>
 1        Papers      paper
 2     Blog 2017 conference
 3         Links       <NA>
 4     Blog 2017       <NA>
 5     Blog 2017       <NA>
 6          Talk       <NA>
 7 ISOTYPE Books    isotype
 8    Techniques       <NA>
 9        Basics       <NA>
10     Blog 2017       <NA>

Hope that helps.


问:
Add new field in body exception spring rest
I want to handle exceptions in my Rest spring boot application. I know that with @ControllerAdvice and ResponseEntity I can return a custom object that will represent my error, but what I want is to add a new field to the body of the exesting exception that's all.

I created a custom Exception that inherit RuntimeException with an extra attribute, a list of string :

```<code>@ResponseStatus(HttpStatus.CONFLICT)
public class CustomException extends RuntimeException {

    private List<String> errors = new ArrayList<>();

    public CustomException(List<String> errors) {
        this.errors = errors;
    }

    public CustomException(String message) {
        super(message);
    }

    public CustomException(String message, List<String> errors) {
        super(message);
        this.errors = errors;
    }

    public List<String> getErrors() {
        return errors;
    }

    public void setErrors(List<String> errors) {
        this.errors = errors;
    }
}
</code>```

In my controller I just throw this custom exception this way:

```<code>@GetMapping("/appointment")
public List<Appointment> getAppointments() {
    List<String> errors = new ArrayList<>();
    errors.add("Custom message");
    throw new CustomException("This is my message", errors);
}
</code>```

When I test my Rest endpoint with postman, it seems like that spring boot doesn't marshall my errors field, the response is :

```<code>{
  "timestamp": "2017-06-05T18:19:03",
  "status": 409,
  "error": "Conflict",
  "exception": "com.htech.bimaristan.utils.CustomException",
  "message": "This is my message",
  "path": "/api/agenda/appointment"
}
</code>```

I can go for a custom object with @ControllerAdvice if I can get the "path" and "timestamp" fields from the exception but there's no getters for these two attributes.

Thank you.

答:
Well! Here is the implementation of "path" and "timestamp" in DefaultErrorAttributes which you could do it in your custom implementation too:

Path:

```<code>String path = getAttribute(requestAttributes, "javax.servlet.error.request_uri");
if (path != null) {
    errorAttributes.put("path", path);
}
</code>```

Timestamp:

```<code>errorAttributes.put("timestamp", new Date());
</code>```

The documentation on error customization in spring boot is here.

```<code>@Bean
public ErrorAttributes errorAttributes() {
    return new DefaultErrorAttributes() {
        @Override
        public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
            Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, includeStackTrace);
            // customize here
            return errorAttributes;
        }

   };
}
</code>```

Or you could write a custom implementation:

```<code>@Component
public class CustomErrorAttributes extends DefaultErrorAttributes {

    @Override
    public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
        Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, includeStackTrace);
        // customize here
        return errorAttributes;
    }
}
</code>```

The ErrorAttributes bean customizes the error response below:

```<code>{
   "timestamp": 1413883870237,
   "status": 500,
   "error": "Internal Server Error",
   "exception": "org.example.ServiceException",
   "message": "somthing goes wrong",
   "path": "/index"
}
</code>```

The "exception" attribute can be customized using the @ExceptionHandler. A @ControlerAdvice could be used to customize the exception generically across controllers. To customize at the Controller level, you could place them within the controller.

In your case:

```<code>   @ResponseStatus(value=HttpStatus.BAD_REQUEST, reason="Invalid Inputs")
    @ExceptionHandler(CustomException.class)
    private void errorHanlder() {
        //Log exception
    }

  public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
    Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, includeStackTrace);
    Throwable error = getError(requestAttributes);
    if (error instanceof CustomException) {
        errorAttributes.put("errorList", ((CustomException)error).getErrors());
    }
    return errorAttributes;
}
</code>```

Body:
I want to handle exceptions in my Rest spring boot application. I know that with @ControllerAdvice and ResponseEntity I can return a custom object that will represent my error, but what I want is to add a new field to the body of the exesting exception that's all.

I created a custom Exception that inherit RuntimeException with an extra attribute, a list of string :

@ResponseStatus(HttpStatus.CONFLICT)
public class CustomException extends RuntimeException {

    private List<String> errors = new ArrayList<>();

    public CustomException(List<String> errors) {
        this.errors = errors;
    }

    public CustomException(String message) {
        super(message);
    }

    public CustomException(String message, List<String> errors) {
        super(message);
        this.errors = errors;
    }

    public List<String> getErrors() {
        return errors;
    }

    public void setErrors(List<String> errors) {
        this.errors = errors;
    }
}

In my controller I just throw this custom exception this way:

@GetMapping("/appointment")
public List<Appointment> getAppointments() {
    List<String> errors = new ArrayList<>();
    errors.add("Custom message");
    throw new CustomException("This is my message", errors);
}

When I test my Rest endpoint with postman, it seems like that spring boot doesn't marshall my errors field, the response is :

{
  "timestamp": "2017-06-05T18:19:03",
  "status": 409,
  "error": "Conflict",
  "exception": "com.htech.bimaristan.utils.CustomException",
  "message": "This is my message",
  "path": "/api/agenda/appointment"
}

I can go for a custom object with @ControllerAdvice if I can get the "path" and "timestamp" fields from the exception but there's no getters for these two attributes.

Thank you.

Body:
Well! Here is the implementation of "path" and "timestamp" in DefaultErrorAttributes which you could do it in your custom implementation too:

Path:

String path = getAttribute(requestAttributes, "javax.servlet.error.request_uri");
if (path != null) {
    errorAttributes.put("path", path);
}

Timestamp:

errorAttributes.put("timestamp", new Date());

The documentation on error customization in spring boot is here.

@Bean
public ErrorAttributes errorAttributes() {
    return new DefaultErrorAttributes() {
        @Override
        public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
            Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, includeStackTrace);
            // customize here
            return errorAttributes;
        }

   };
}

Or you could write a custom implementation:

@Component
public class CustomErrorAttributes extends DefaultErrorAttributes {

    @Override
    public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
        Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, includeStackTrace);
        // customize here
        return errorAttributes;
    }
}

The ErrorAttributes bean customizes the error response below:

{
   "timestamp": 1413883870237,
   "status": 500,
   "error": "Internal Server Error",
   "exception": "org.example.ServiceException",
   "message": "somthing goes wrong",
   "path": "/index"
}

The "exception" attribute can be customized using the @ExceptionHandler. A @ControlerAdvice could be used to customize the exception generically across controllers. To customize at the Controller level, you could place them within the controller.

In your case:

   @ResponseStatus(value=HttpStatus.BAD_REQUEST, reason="Invalid Inputs")
    @ExceptionHandler(CustomException.class)
    private void errorHanlder() {
        //Log exception
    }

  public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
    Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, includeStackTrace);
    Throwable error = getError(requestAttributes);
    if (error instanceof CustomException) {
        errorAttributes.put("errorList", ((CustomException)error).getErrors());
    }
    return errorAttributes;
}


问:
How to use React Router with Laravel?
I needing use React Router with a Laravel project.

But when I create router on the React Router and try access, Laravel accuse Route not exist error.

How to can I use React Router to manager Laravel project routes?

```<code>render((
    <Router history={browserHistory}>
        <Route path="/" component={App}/>
        <Route path="/profile" component={Profile}/> // this route I trying access
    </Router>
), document.getElementById('root'));
</code>```

答:
This seems works for me

For any react routes

```<code>Route::get('{reactRoutes}', function () {
    return view('welcome'); // your start view
})->where('reactRoutes', '^((?!api).)*$'); // except 'api' word
</code>```

For laravel routes

```<code>Route::get('api/whatever/1', function() {
    return [
        'one' => 'two',
        'first' => 'second'
    ];
});

Route::get('api/something/2', function() {
    return [
        'hello' => 'good bye',
        'dog' => 'cat'
    ];
});
</code>```

Title: How to use React Router with Laravel?

Body:
I needing use React Router with a Laravel project.

But when I create router on the React Router and try access, Laravel accuse Route not exist error.

How to can I use React Router to manager Laravel project routes?

render((
    <Router history={browserHistory}>
        <Route path="/" component={App}/>
        <Route path="/profile" component={Profile}/> // this route I trying access
    </Router>
), document.getElementById('root'));

Body:
This seems works for me

For any react routes

Route::get('{reactRoutes}', function () {
    return view('welcome'); // your start view
})->where('reactRoutes', '^((?!api).)*$'); // except 'api' word

For laravel routes

Route::get('api/whatever/1', function() {
    return [
        'one' => 'two',
        'first' => 'second'
    ];
});

Route::get('api/something/2', function() {
    return [
        'hello' => 'good bye',
        'dog' => 'cat'
    ];
});


问:
How do I make wordpress comment fields required?
Here is my form:

```<code><form action="<?php echo get_option('siteurl'); ?>/wp-comments-post.php" method="post" id="commentform" class="validate">
   <?php if($user_ID) : ?>
   <?php else : ?>
   <div class="label_container">
      <div class="left">
         <label for="author" class="label label_name">Name*</label>
      </div>
      <div class="right">
         <label for="email" class="label label_email">Email*</label>
      </div>
      </div>
   <div class="input_container">
      <input id="name" name="author" class="required input_text input_name" type="text" value="" />
      <input id="email" name="email" class="required input_text email input_email" type="text" value="" />
   </div>
   <?php endif; ?>
      <div class="label_container">
         <label for="comment" class="label label_comment">Comment</label>
      </div>
   <textarea id="comment_box" class="required input_comment" name="comment" cols="40" rows="6"></textarea>
   <p><input name="submit" class="input_submit" type="submit" id="submit" tabindex="5" value="Submit Comment" />
   <input type="hidden" name="comment_post_ID" value="<?php echo $id; ?>" /></p>
   <input type="hidden" id="redirect_to" name="redirect_to" value="<?php echo get_bloginfo('wpurl');?>/comment">
   <?php do_action('comment_form', $post->ID); ?>
</form>
</code>```

I have required fields on all inputs, but it is only working on the comment text field.

Any ideas?

答:
you can actually control that from the settings discussion tab in the wp-admin panel.

make sure to check Comment author must fill out name and e-mail. that should do it.

is this what you are looking for?

Body:
Here is my form:

<form action="<?php echo get_option('siteurl'); ?>/wp-comments-post.php" method="post" id="commentform" class="validate">
   <?php if($user_ID) : ?>
   <?php else : ?>

         Name*

         Email*

      <input id="name" name="author" class="required input_text input_name" type="text" value="" />
      <input id="email" name="email" class="required input_text email input_email" type="text" value="" />

   <?php endif; ?>

         Comment

   <textarea id="comment_box" class="required input_comment" name="comment" cols="40" rows="6"></textarea>

<input name="submit" class="input_submit" type="submit" id="submit" tabindex="5" value="Submit Comment" />
   <input type="hidden" name="comment_post_ID" value="<?php echo $id; ?>" />

   <input type="hidden" id="redirect_to" name="redirect_to" value="<?php echo get_bloginfo('wpurl');?>/comment">
   <?php do_action('comment_form', $post->ID); ?>
</form>

I have required fields on all inputs, but it is only working on the comment text field.

Any ideas?


问:
Local storage to change background colour
I am trying to change the background colour of my website with local storage. I am using onchange() within the HTML for the colours() function, and the rest is the JavaScript below

```<code>var bgcolour;

window.onload = function theme(){

    document.body.style.backgroundColor = "red";
    localStorage.setItem("bgcolour", 1);
}

function colours(){
    localStorage.bgcolour = document.getElementById("party").value;

    if (localStorage.bgcolour == '1'){
        document.body.style.backgroundColor = "red";
    }
}
</code>```

It does nothing. It doesn't even change, let alone store it as local storage.

I keep missing vital, small parts of code and it feels like I have done it again with this one.

Any help is greatly appreciated!

HTML:

```<code> <select name="pnumber" id="party" onchange="colours()">
     <option value="1">1</option>
     <option value="2">2</option>
     <option value="3">3</option>
     <option value="4">4</option>
     <option value="5">5</option>
     <option value="6">6</option>
     <option value="7">7</option>
     <option value="8">8</option>
     <option value="9">9</option>
     <option value="10">10</option>
     <option value="11">11</option>
     <option value="12">12</option>
     <option value="13">13</option>
     <option value="14">14</option>
     <option value="15">15 (maximum)</option>
 </select>
</code>```

答:
the code is wrong, you are improperly setting and checking localStorage values. Also, you need to get the value from the node with id party.

var bgcolour;

window.onload = function theme(){

    document.body.style.backgroundColor = "red";
    localStorage.setItem("bgcolour", 1);
}

var party = document.getElementById('party')
function colours(){

    localStorage.setItem('bgcolour', party.value);

    if (localStorage.getItem('bgcolour') === '1'){
        document.body.style.backgroundColor = "red";
    }
  else{
    document.body.style.backgroundColor = "green";
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select name="pnumber" id="party" onchange="colours()">
     <option value="1">1</option>
     <option value="2">2</option>
     <option value="3">3</option>
     <option value="4">4</option>
     <option value="5">5</option>
     <option value="6">6</option>
     <option value="7">7</option>
     <option value="8">8</option>
     <option value="9">9</option>
     <option value="10">10</option>
     <option value="11">11</option>
     <option value="12">12</option>
     <option value="13">13</option>
     <option value="14">14</option>
     <option value="15">15 (maximum)</option>
 </select></code>```

Body:
I am trying to change the background colour of my website with local storage. I am using onchange() within the HTML for the colours() function, and the rest is the JavaScript below

var bgcolour;

window.onload = function theme(){

    document.body.style.backgroundColor = "red";
    localStorage.setItem("bgcolour", 1);
}

function colours(){
    localStorage.bgcolour = document.getElementById("party").value;

    if (localStorage.bgcolour == '1'){
        document.body.style.backgroundColor = "red";
    }
}

It does nothing. It doesn't even change, let alone store it as local storage.

I keep missing vital, small parts of code and it feels like I have done it again with this one.

Any help is greatly appreciated!

HTML:

 <select name="pnumber" id="party" onchange="colours()">
     <option value="1">1</option>
     <option value="2">2</option>
     <option value="3">3</option>
     <option value="4">4</option>
     <option value="5">5</option>
     <option value="6">6</option>
     <option value="7">7</option>
     <option value="8">8</option>
     <option value="9">9</option>
     <option value="10">10</option>
     <option value="11">11</option>
     <option value="12">12</option>
     <option value="13">13</option>
     <option value="14">14</option>
     <option value="15">15 (maximum)</option>
 </select>

Body:
the code is wrong, you are improperly setting and checking localStorage values. Also, you need to get the value from the node with id party.

var bgcolour;

window.onload = function theme(){

    document.body.style.backgroundColor = "red";
    localStorage.setItem("bgcolour", 1);
}

var party = document.getElementById('party')
function colours(){

    localStorage.setItem('bgcolour', party.value);

    if (localStorage.getItem('bgcolour') === '1'){
        document.body.style.backgroundColor = "red";
    }
  else{
    document.body.style.backgroundColor = "green";
  }
}

<select name="pnumber" id="party" onchange="colours()">
     <option value="1">1</option>
     <option value="2">2</option>
     <option value="3">3</option>
     <option value="4">4</option>
     <option value="5">5</option>
     <option value="6">6</option>
     <option value="7">7</option>
     <option value="8">8</option>
     <option value="9">9</option>
     <option value="10">10</option>
     <option value="11">11</option>
     <option value="12">12</option>
     <option value="13">13</option>
     <option value="14">14</option>
     <option value="15">15 (maximum)</option>
 </select>


问:
Expected ',' seperator When adding images
```<code>@IBOutlet weak var ImageView: UIImageView!
@IBOutlet weak var Button: UIButton!

Imagenames = ["#imageLiteral(resourceName: "image2")", "#imageLiteral(resourceName: "image1"]

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func Buttonpress(_ sender: UIButton) {

    let imageV = Int(arc4random_uniform(2))

    ImageView.image = UIImage(named: Imagenames[ImageView])
}
</code>```

How can I fix this issue? please help. Running the latest version of Xcode

答:
#imageLiterals are not supposed to go into a String. Your code should be

```<code>Imagenames = [#imageLiteral(resourceName: "image2"), #imageLiteral(resourceName: "image1")]
</code>```

As you can already see the code is properly highlighted both in Xcode as well as on Stackoverflow.

Note that you are missing a var or let in front of Imagenames as well. And that your variable should start with a lower case, e.g. images. Your functions should follow that naming as well by the way.

Then you should change your code logic inside Buttonpress to be:

```<code>ImageView.image = images[imageV]
</code>```

Putting all the naming advices together your code should probably be something like:

```<code>@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var button: UIButton!

let images = [#imageLiteral(resourceName: "image2"), #imageLiteral(resourceName: "image1")]

@IBAction func buttonPressed(_ sender: UIButton) {

    let imageIndex = Int(arc4random_uniform(2))

    imageView.image = images[imageIndex]
}
</code>```

Body:
@IBOutlet weak var ImageView: UIImageView!
@IBOutlet weak var Button: UIButton!

Imagenames = ["#imageLiteral(resourceName: "image2")", "#imageLiteral(resourceName: "image1"]

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func Buttonpress(_ sender: UIButton) {

    let imageV = Int(arc4random_uniform(2))

    ImageView.image = UIImage(named: Imagenames[ImageView])
}

How can I fix this issue? please help. Running the latest version of Xcode

Body:
#imageLiterals are not supposed to go into a String. Your code should be

Imagenames = [#imageLiteral(resourceName: "image2"), #imageLiteral(resourceName: "image1")]

As you can already see the code is properly highlighted both in Xcode as well as on Stackoverflow.

Note that you are missing a var or let in front of Imagenames as well. And that your variable should start with a lower case, e.g. images. Your functions should follow that naming as well by the way.

Then you should change your code logic inside Buttonpress to be:

ImageView.image = images[imageV]

Putting all the naming advices together your code should probably be something like:

@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var button: UIButton!

let images = [#imageLiteral(resourceName: "image2"), #imageLiteral(resourceName: "image1")]

@IBAction func buttonPressed(_ sender: UIButton) {

    let imageIndex = Int(arc4random_uniform(2))

    imageView.image = images[imageIndex]
}