问:
Notification not Queuable on Laravel 5.4 (SlackMessage)
I started to use notification system on Slack provided by Laravel 5.4 and it is awesome (src: https://laravel.com/docs/5.4/notifications)!

However I have a problem to notify with a queue it triggers an Exception: Serialization of 'Closure' is not allowed in /var/www/project_test/vendor/laravel/framework/src/Illuminate/Queue/Queue.php:125

Can you help me please, what is my mistake ?

Information :

it works well without Queue

queue driver is database

queue worker is started with 'queue:work --queue=default,mail --sleep=3 --tries=3 --timeout=60'

Here my code in app/Notifications/Slack.php :

```<code>namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\SlackMessage;

class Slack extends Notification implements ShouldQueue
{
    use Queueable;

    private $channel;
    private $username;
    private $icon;
    private $message;
    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct(String $channel = '', String $username = '', String $icon = '', String $message = '')
    {
        $this->channel = $channel;
        $this->username = $username;
        $this->icon = $icon;
        $this->message = $message;
    }
    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['slack'];
    }
    /**
    * Get the Slack representation of the notification.
    *
    * @param  mixed  $notifiable
    * @return SlackMessage
    */
    public function toSlack($notifiable)
    {
        return (new SlackMessage)
                ->from($this->username, $this->icon)
                ->to($this->channel)
                ->content($this->message);
    }
    /**
    * Get the array representation of the notification.
    *
    * @param  mixed  $notifiable
    * @return array
    */
    public function toArray($notifiable)
    {
        return [
            'channel' => $this->channel,
            'username' => $this->username,
            'icon' => $this->icon,
            'message' => $this->message,
        ];
    }
}
</code>```

Here my code in app/Providers/AppServiceProvider.php which use slack notifications:

```<code>namespace App\Providers;
use Queue;
use Carbon\Carbon;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Log;
use Illuminate\Queue\Events\JobFailed;
use Illuminate\Notifications\Notifiable;
use App\Notifications\Slack;

class AppServiceProvider extends ServiceProvider
{
    use Notifiable;
    /**
     * Route notifications for the Slack channel.
     *
     * @return string
     */
    public function routeNotificationForSlack()
    {
        return 'http://hook.slack.com/XXXXXx/my_slack_endpoint';
    }
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        // When a queue job fail
        Queue::failing(function (JobFailed $event) {
            // Notify team of failing job
            $when = Carbon::now()->addSeconds(10);
            $this->notify((new Slack('slack_channel', 'slack_username', 'slack_icon', 'Job Failed !'))->delay($when));
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}
</code>```

Full error dump :

```<code>local.ERROR: Exception: Serialization of 'Closure' is not allowed in /var/www/project_test/vendor/laravel/framework/src/Illuminate/Queue/Queue.php:125
Stack trace:
#0 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Queue/Queue.php(125): serialize(Object(Illuminate\Notifications\SendQueuedNotifications))
#1 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Queue/Queue.php(106): Illuminate\Queue\Queue->createObjectPayload(Object(Illuminate\Notifications\SendQueuedNotifications))
#2 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Queue/Queue.php(86): Illuminate\Queue\Queue->createPayloadArray(Object(Illuminate\Notifications\SendQueuedNotifications), '', NULL)
#3 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Queue/DatabaseQueue.php(108): Illuminate\Queue\Queue->createPayload(Object(Illuminate\Notifications\SendQueuedNotifications), '')
#4 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(181): Illuminate\Queue\DatabaseQueue->later(Object(Carbon\Carbon), Object(Illuminate\Notifications\SendQueuedNotifications))
#5 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(159): Illuminate\Bus\Dispatcher->pushCommandToQueue(Object(Illuminate\Queue\DatabaseQueue), Object(Illuminate\Notifications\SendQueuedNotifications))
#6 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(73): Illuminate\Bus\Dispatcher->dispatchToQueue(Object(Illuminate\Notifications\SendQueuedNotifications))
#7 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Notifications/NotificationSender.php(160): Illuminate\Bus\Dispatcher->dispatch(Object(Illuminate\Notifications\SendQueuedNotifications))
#8 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Notifications/NotificationSender.php(61): Illuminate\Notifications\NotificationSender->queueNotification(Array, Object(App\Notifications\Slack))
#9 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Notifications/ChannelManager.php(36): Illuminate\Notifications\NotificationSender->send(Array, Object(App\Notifications\Slack))
#10 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Notifications/RoutesNotifications.php(18): Illuminate\Notifications\ChannelManager->send(Object(App\Providers\AppServiceProvider), Object(App\Notifications\Slack))
#11 /var/www/project_test/app/Providers/AppServiceProvider.php(57): App\Providers\AppServiceProvider->notify(Object(App\Notifications\Slack))
#12 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php(334): App\Providers\AppServiceProvider->App\Providers\{closure}(Object(Illuminate\Queue\Events\JobFailed))
#13 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php(199): Illuminate\Events\Dispatcher->Illuminate\Events\{closure}('Illuminate\\Queu...', Array)
#14 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php(172): Illuminate\Events\Dispatcher->dispatch('Illuminate\\Queu...', Array, false)
#15 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Queue/FailingJob.php(36): Illuminate\Events\Dispatcher->fire(Object(Illuminate\Queue\Events\JobFailed))
#16 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(392): Illuminate\Queue\FailingJob::handle('database', Object(Illuminate\Queue\Jobs\DatabaseJob), Object(Swift_TransportException))
#17 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(378): Illuminate\Queue\Worker->failJob('database', Object(Illuminate\Queue\Jobs\DatabaseJob), Object(Swift_TransportException))
#18 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(321): Illuminate\Queue\Worker->markJobAsFailedIfWillExceedMaxAttempts('database', Object(Illuminate\Queue\Jobs\DatabaseJob), 3, Object(Swift_TransportException))
#19 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(295): Illuminate\Queue\Worker->handleJobException('database', Object(Illuminate\Queue\Jobs\DatabaseJob), Object(Illuminate\Queue\WorkerOptions), Object(Swift_TransportException))
#20 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(258): Illuminate\Queue\Worker->process('database', Object(Illuminate\Queue\Jobs\DatabaseJob), Object(Illuminate\Queue\WorkerOptions))
#21 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(110): Illuminate\Queue\Worker->runJob(Object(Illuminate\Queue\Jobs\DatabaseJob), 'database', Object(Illuminate\Queue\WorkerOptions))
#22 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(100): Illuminate\Queue\Worker->daemon('database', 'default,q-mail', Object(Illuminate\Queue\WorkerOptions))
#23 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(83): Illuminate\Queue\Console\WorkCommand->runWorker('database', 'default,q-mail')
#24 [internal function]: Illuminate\Queue\Console\WorkCommand->fire()
#25 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(29): call_user_func_array(Array, Array)
#26 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(87): Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
#27 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(31): Illuminate\Container\BoundMethod::callBoundMethod(Object(Illuminate\Foundation\Application), Array, Object(Closure))
#28 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Container/Container.php(524): Illuminate\Container\BoundMethod::call(Object(Illuminate\Foundation\Application), Array, Array, NULL)
#29 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Console/Command.php(182): Illuminate\Container\Container->call(Array)
#30 /var/www/project_test/vendor/symfony/console/Command/Command.php(265): Illuminate\Console\Command->execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
#31 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Console/Command.php(167): Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
#32 /var/www/project_test/vendor/symfony/console/Application.php(826): Illuminate\Console\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#33 /var/www/project_test/vendor/symfony/console/Application.php(189): Symfony\Component\Console\Application->doRunCommand(Object(Illuminate\Queue\Console\WorkCommand), Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#34 /var/www/project_test/vendor/symfony/console/Application.php(120): Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#35 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(123): Symfony\Component\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#36 /var/www/project_test/artisan(35): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#37 {main}
</code>```

Thank by advance for your responses,

Rergards

答:
Loooks like themsaid answered your issue request on laravel bug tracker. To save others a click, I'll quote that reply here if you don't mind:

Don't use the Illuminate\Notifications\Notifiable, it's meant to be
  used with Eloquent models, now the Queue driver will try to serliaize
  your service provider thinking it's the notifiable, this is something
  you don't want.

Instead you can create a MySlack class or something that uses
  Notifiable and you send the notification from the service provider
  like:

Notification::Send(new MySlack(), new MyNotification());
```

Body:
I started to use notification system on Slack provided by Laravel 5.4 and it is awesome (src: https://laravel.com/docs/5.4/notifications)!

However I have a problem to notify with a queue it triggers an Exception: Serialization of 'Closure' is not allowed in /var/www/project_test/vendor/laravel/framework/src/Illuminate/Queue/Queue.php:125

Can you help me please, what is my mistake ?

Information :

it works well without Queue

queue driver is database

queue worker is started with 'queue:work --queue=default,mail --sleep=3 --tries=3 --timeout=60'

Here my code in app/Notifications/Slack.php :

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\SlackMessage;

class Slack extends Notification implements ShouldQueue
{
    use Queueable;

    private $channel;
    private $username;
    private $icon;
    private $message;
    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct(String $channel = '', String $username = '', String $icon = '', String $message = '')
    {
        $this->channel = $channel;
        $this->username = $username;
        $this->icon = $icon;
        $this->message = $message;
    }
    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['slack'];
    }
    /**
    * Get the Slack representation of the notification.
    *
    * @param  mixed  $notifiable
    * @return SlackMessage
    */
    public function toSlack($notifiable)
    {
        return (new SlackMessage)
                ->from($this->username, $this->icon)
                ->to($this->channel)
                ->content($this->message);
    }
    /**
    * Get the array representation of the notification.
    *
    * @param  mixed  $notifiable
    * @return array
    */
    public function toArray($notifiable)
    {
        return [
            'channel' => $this->channel,
            'username' => $this->username,
            'icon' => $this->icon,
            'message' => $this->message,
        ];
    }
}

Here my code in app/Providers/AppServiceProvider.php which use slack notifications:

namespace App\Providers;
use Queue;
use Carbon\Carbon;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Log;
use Illuminate\Queue\Events\JobFailed;
use Illuminate\Notifications\Notifiable;
use App\Notifications\Slack;

class AppServiceProvider extends ServiceProvider
{
    use Notifiable;
    /**
     * Route notifications for the Slack channel.
     *
     * @return string
     */
    public function routeNotificationForSlack()
    {
        return 'http://hook.slack.com/XXXXXx/my_slack_endpoint';
    }
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        // When a queue job fail
        Queue::failing(function (JobFailed $event) {
            // Notify team of failing job
            $when = Carbon::now()->addSeconds(10);
            $this->notify((new Slack('slack_channel', 'slack_username', 'slack_icon', 'Job Failed !'))->delay($when));
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Full error dump :

local.ERROR: Exception: Serialization of 'Closure' is not allowed in /var/www/project_test/vendor/laravel/framework/src/Illuminate/Queue/Queue.php:125
Stack trace:
#0 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Queue/Queue.php(125): serialize(Object(Illuminate\Notifications\SendQueuedNotifications))
#1 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Queue/Queue.php(106): Illuminate\Queue\Queue->createObjectPayload(Object(Illuminate\Notifications\SendQueuedNotifications))
#2 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Queue/Queue.php(86): Illuminate\Queue\Queue->createPayloadArray(Object(Illuminate\Notifications\SendQueuedNotifications), '', NULL)
#3 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Queue/DatabaseQueue.php(108): Illuminate\Queue\Queue->createPayload(Object(Illuminate\Notifications\SendQueuedNotifications), '')
#4 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(181): Illuminate\Queue\DatabaseQueue->later(Object(Carbon\Carbon), Object(Illuminate\Notifications\SendQueuedNotifications))
#5 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(159): Illuminate\Bus\Dispatcher->pushCommandToQueue(Object(Illuminate\Queue\DatabaseQueue), Object(Illuminate\Notifications\SendQueuedNotifications))
#6 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(73): Illuminate\Bus\Dispatcher->dispatchToQueue(Object(Illuminate\Notifications\SendQueuedNotifications))
#7 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Notifications/NotificationSender.php(160): Illuminate\Bus\Dispatcher->dispatch(Object(Illuminate\Notifications\SendQueuedNotifications))
#8 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Notifications/NotificationSender.php(61): Illuminate\Notifications\NotificationSender->queueNotification(Array, Object(App\Notifications\Slack))
#9 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Notifications/ChannelManager.php(36): Illuminate\Notifications\NotificationSender->send(Array, Object(App\Notifications\Slack))
#10 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Notifications/RoutesNotifications.php(18): Illuminate\Notifications\ChannelManager->send(Object(App\Providers\AppServiceProvider), Object(App\Notifications\Slack))
#11 /var/www/project_test/app/Providers/AppServiceProvider.php(57): App\Providers\AppServiceProvider->notify(Object(App\Notifications\Slack))
#12 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php(334): App\Providers\AppServiceProvider->App\Providers\{closure}(Object(Illuminate\Queue\Events\JobFailed))
#13 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php(199): Illuminate\Events\Dispatcher->Illuminate\Events\{closure}('Illuminate\\Queu...', Array)
#14 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php(172): Illuminate\Events\Dispatcher->dispatch('Illuminate\\Queu...', Array, false)
#15 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Queue/FailingJob.php(36): Illuminate\Events\Dispatcher->fire(Object(Illuminate\Queue\Events\JobFailed))
#16 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(392): Illuminate\Queue\FailingJob::handle('database', Object(Illuminate\Queue\Jobs\DatabaseJob), Object(Swift_TransportException))
#17 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(378): Illuminate\Queue\Worker->failJob('database', Object(Illuminate\Queue\Jobs\DatabaseJob), Object(Swift_TransportException))
#18 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(321): Illuminate\Queue\Worker->markJobAsFailedIfWillExceedMaxAttempts('database', Object(Illuminate\Queue\Jobs\DatabaseJob), 3, Object(Swift_TransportException))
#19 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(295): Illuminate\Queue\Worker->handleJobException('database', Object(Illuminate\Queue\Jobs\DatabaseJob), Object(Illuminate\Queue\WorkerOptions), Object(Swift_TransportException))
#20 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(258): Illuminate\Queue\Worker->process('database', Object(Illuminate\Queue\Jobs\DatabaseJob), Object(Illuminate\Queue\WorkerOptions))
#21 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(110): Illuminate\Queue\Worker->runJob(Object(Illuminate\Queue\Jobs\DatabaseJob), 'database', Object(Illuminate\Queue\WorkerOptions))
#22 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(100): Illuminate\Queue\Worker->daemon('database', 'default,q-mail', Object(Illuminate\Queue\WorkerOptions))
#23 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(83): Illuminate\Queue\Console\WorkCommand->runWorker('database', 'default,q-mail')
#24 [internal function]: Illuminate\Queue\Console\WorkCommand->fire()
#25 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(29): call_user_func_array(Array, Array)
#26 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(87): Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
#27 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(31): Illuminate\Container\BoundMethod::callBoundMethod(Object(Illuminate\Foundation\Application), Array, Object(Closure))
#28 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Container/Container.php(524): Illuminate\Container\BoundMethod::call(Object(Illuminate\Foundation\Application), Array, Array, NULL)
#29 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Console/Command.php(182): Illuminate\Container\Container->call(Array)
#30 /var/www/project_test/vendor/symfony/console/Command/Command.php(265): Illuminate\Console\Command->execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
#31 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Console/Command.php(167): Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
#32 /var/www/project_test/vendor/symfony/console/Application.php(826): Illuminate\Console\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#33 /var/www/project_test/vendor/symfony/console/Application.php(189): Symfony\Component\Console\Application->doRunCommand(Object(Illuminate\Queue\Console\WorkCommand), Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#34 /var/www/project_test/vendor/symfony/console/Application.php(120): Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#35 /var/www/project_test/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(123): Symfony\Component\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#36 /var/www/project_test/artisan(35): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#37 {main}

Thank by advance for your responses,

Rergards


来源: stackexchange

问:
CAKEPHP 3 : Select * and sum() in one statement
I am trying to fetch result from database table with SELECT * and SUM() function.
The sql query is :

SELECT * ,SUM(msg_send) AS msg_send FROM msg_campaigns

Now how to write this query in cakephp3.

I am trying this :

```<code>$this->loadModel('MsgCampaigns');
$SmsDetails = $this->MsgCampaigns->find('all',[
'conditions'=>['YEAR(date_time)'=>date('Y')],
'fields'=>['msg_send'=>'SUM(msg_send)','msg_failed'=>'SUM(msg_failed)']
]);
</code>```

But I do not know how to use SELECT * . Please help

答:
Check the CakePHP Query Builder on how to use SQL functions and how to select all fields.</p>

```<code>$query = $this->MsgCampaigns->find();
$query
    ->select([
        'sum_msg_send' => $query->func()->sum('msg_send'),
        'sum_msg_failed' => $query->func()->sum('msg_failed')
    ])
    // passing the table instance to the `select` function, selects all fields
    ->select($this->MsgCampaigns);

$query->execute();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to fetch result from database table with SELECT * and SUM() function.
The sql query is :

SELECT * ,SUM(msg_send) AS msg_send FROM msg_campaigns

Now how to write this query in cakephp3.

I am trying this :

$this->loadModel('MsgCampaigns');
$SmsDetails = $this->MsgCampaigns->find('all',[
'conditions'=>['YEAR(date_time)'=>date('Y')],
'fields'=>['msg_send'=>'SUM(msg_send)','msg_failed'=>'SUM(msg_failed)']
]);

But I do not know how to use SELECT * . Please help

Body:
Check the CakePHP Query Builder on how to use SQL functions and how to select all fields.

$query = $this->MsgCampaigns->find();
$query
    ->select([
        'sum_msg_send' => $query->func()->sum('msg_send'),
        'sum_msg_failed' => $query->func()->sum('msg_failed')
    ])
    // passing the table instance to the `select` function, selects all fields
    ->select($this->MsgCampaigns);

$query->execute();


问:
Class vs Struct for data only?
Is there any advantage over using a class over a struct in cases such as these?
(note: it will only hold variables, there will never be functions)

```<code>class Foo {
private:
   struct Pos { int x, y, z };
public:
   Pos Position;
};
</code>```

Versus:

```<code>struct Foo {
   struct Pos { int x, y, z } Pos;
};
</code>```

Similar questions:

When should you use a class vs a struct in C++?

What are the differences between struct and class in C++?

When should I use a struct instead of a class?

答: If the contents of the type have no memory allocation issues (such as plain int), then using struct is fine if that's the way you want to go and you've made a conscious decision about it that you can justify to those who use your code.  However, if any of the members is a pointer type, then you need to think hard about the memory management issues.  It may still be OK to use a struct, but you are much more likely to need a destructor, and some constructors, and so on.  At that point, you want a class.

OwnerDisplayName: Daniel

ContentLicense: CC BY-SA 2.5

Title: Class vs Struct for data only?

Body:
Is there any advantage over using a class over a struct in cases such as these?
(note: it will only hold variables, there will never be functions)

class Foo {
private:
   struct Pos { int x, y, z };
public:
   Pos Position;
};

Versus:

struct Foo {
   struct Pos { int x, y, z } Pos;
};

Similar questions:

When should you use a class vs a struct in C++?

What are the differences between struct and class in C++?

When should I use a struct instead of a class?

LastEditorDisplayName: dmckee

OwnerDisplayName: Jonathan Leffler


问:
Concurrency: Processes vs Threads
What are the main advantages of using a model for concurrency based on processes over one
based on threads and in what contexts is the latter appropriate?</p>

答:
Fault-tolerance and scalability are the main advantages of using Processes vs. Threads.

A system that relies on shared memory or some other kind of technology that is only available when using threads, will be useless when you want to run the system on multiple machines. Sooner or later you will need to communicate between different processes.

When using processes you are forced to deal with communication via messages, for example, this is the way Erlang handles communication. Data is not shared, so there is no risk of data corruption.

Another advantage of processes is that they can crash and you can feel relatively safe in the knowledge that you can just restart them (even across network hosts). However, if a thread crashes, it may crash the entire process, which may bring down your entire application. To illustrate: If an Erlang process crashes, you will only lose that phone call, or that webrequest, etc. Not the whole application.

In saying all this, OS processes also have many drawbacks that can make them harder to use, like the fact that it takes forever to spawn a new process. However, Erlang has it's own notion of processes, which are extremely lightweight.

With that said, this discussion is really a topic of research. If you want to get into more of the details, you can give Joe Armstrong's paper on fault-tolerant systems]1 a read, it explains a lot about Erlang and the  philosophy that drives it.

Title: Concurrency: Processes vs Threads


问:
405 method not allowed Web API
This error is very common, and I tried all of the solutions and non of them worked. I have disabled WebDAV publishing in control panel and added this to my web config file:

```<code>  <handlers>
  <remove name="WebDAV"/>
  </handlers>
  <modules runAllManagedModulesForAllRequests="true">
  <remove name="WebDAVModule"/>
  </modules>
</code>```

The error still persists. This is the controller:

```<code>   static readonly IProductRepository repository = new ProductRepository();

    public Product Put(Product p)
    {
        return repository.Add(p);
    }
</code>```

Method implementation:

```<code> public Product Add(Product item)
    {
        if (item == null)
        {
            throw new ArgumentNullException("item");
        }
        item.Id = _nextId++;
        products.Add(item);
        return item;
    }
</code>```

And this is where the exception is thrown:

```<code>client.BaseAddress = new Uri("http://localhost:5106/");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.PostAsJsonAsync("api/products", product);//405 exception
</code>```

Any suggestions?

答:
If you have a route like

```<code>[Route("nuclearreactors/{reactorId}")]
</code>```

You need to use the exact same parameter name in the method e.g.

```<code>public ReactorModel GetReactor(reactorId)
{
 ...
}
</code>```

If you do not pass the exact same parameter you may get the error "405 method not allowed" because the route will not match the request and WebApi will hit a different controller method with different allowed HTTP method.

ContentLicense: CC BY-SA 4.0

Title: 405 method not allowed Web API

Body:
This error is very common, and I tried all of the solutions and non of them worked. I have disabled WebDAV publishing in control panel and added this to my web config file:

  <handlers>
  <remove name="WebDAV"/>
  </handlers>
  <modules runAllManagedModulesForAllRequests="true">
  <remove name="WebDAVModule"/>
  </modules>

The error still persists. This is the controller:

   static readonly IProductRepository repository = new ProductRepository();

    public Product Put(Product p)
    {
        return repository.Add(p);
    }

Method implementation:

 public Product Add(Product item)
    {
        if (item == null)
        {
            throw new ArgumentNullException("item");
        }
        item.Id = _nextId++;
        products.Add(item);
        return item;
    }

And this is where the exception is thrown:

client.BaseAddress = new Uri("http://localhost:5106/");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.PostAsJsonAsync("api/products", product);//405 exception

Any suggestions?

Body:
If you have a route like

[Route("nuclearreactors/{reactorId}")]

You need to use the exact same parameter name in the method e.g.

public ReactorModel GetReactor(reactorId)
{
 ...
}

If you do not pass the exact same parameter you may get the error "405 method not allowed" because the route will not match the request and WebApi will hit a different controller method with different allowed HTTP method.


问:
OCaml pattern matching with int and bool
```<code>let disting v =
  match v with
  | int -> (*expression1*)
  | bool -> (*expression2*)
  | _ -> (*expression3*)
</code>```

Whenever I run the code, disting true and disting false also turns out expression1. The result is vice versa with this code

```<code>let disting v =
  match v with
  | bool -> (*expression2*)
  | int -> (*expression1*)
  | _ -> (*expression3*)
</code>```

This one also have similar problem. How can I get the result I want?

答:
The way to do it in Ocaml is to use sum types :</p>

```<code>       type i_or_b = I of int | B of bool;
       let disting v =
         match v with
         | I x -> Printf.printf "v = I %d\n" x
         | B x -> Printf.printf "v = B %s\n" (string_of_bool x)
</code>```

Body:
let disting v =
  match v with
  | int -> (*expression1*)
  | bool -> (*expression2*)
  | _ -> (*expression3*)

Whenever I run the code, disting true and disting false also turns out expression1. The result is vice versa with this code

let disting v =
  match v with
  | bool -> (*expression2*)
  | int -> (*expression1*)
  | _ -> (*expression3*)

This one also have similar problem. How can I get the result I want?

Body:
The way to do it in Ocaml is to use sum types :

       type i_or_b = I of int | B of bool;
       let disting v =
         match v with
         | I x -> Printf.printf "v = I %d\n" x
         | B x -> Printf.printf "v = B %s\n" (string_of_bool x)


问:
Swift collectionViewCells are not showing
I have got this Swift code
`

```<code>let cellId="cellId"

class FeedController: UICollectionViewController{
override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.title = "Centill"

    collectionView?.reloadData()
    collectionView?.backgroundColor = UIColor(white: 0.95, alpha: 1)
    collectionView?.register(FeedCell.self, forCellWithReuseIdentifier: cellId)
}

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 3
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell=collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath);
    cell.backgroundColor = .yellow
    return cell
}

}

class FeedCell: UICollectionViewCell {

override init(frame: CGRect){
    super.init(frame: frame)

    setupViews()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
func setupViews(){
    backgroundColor = .yellow
}
}
</code>```

`
But unfortunately my cells are not showing.It only shows navigation bar and background color.what may be the problem with my code?

答:
In your cellForItemAt dataSource method you need to give custom UICollectionCell Class

```<code>let cell=collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! FeedCell
cell.backgroundColor = .yellow
return cell
</code>```

Then you will able to see cell.

Body:
I have got this Swift code
`

let cellId="cellId"

class FeedController: UICollectionViewController{
override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.title = "Centill"

    collectionView?.reloadData()
    collectionView?.backgroundColor = UIColor(white: 0.95, alpha: 1)
    collectionView?.register(FeedCell.self, forCellWithReuseIdentifier: cellId)
}

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 3
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell=collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath);
    cell.backgroundColor = .yellow
    return cell
}

}

class FeedCell: UICollectionViewCell {

override init(frame: CGRect){
    super.init(frame: frame)

    setupViews()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
func setupViews(){
    backgroundColor = .yellow
}
}

`
But unfortunately my cells are not showing.It only shows navigation bar and background color.what may be the problem with my code?

Body:
In your cellForItemAt dataSource method you need to give custom UICollectionCell Class

let cell=collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! FeedCell
cell.backgroundColor = .yellow
return cell

Then you will able to see cell.


问:
mysql replication : utilizing insert delayed
I have a batch database that i would like to replicate to a reporting database but the queries that run on the reporting database might be very long (execution time wise) to the point where they can cause a deadlock (this is happening now because both batch and reporting applications are using the same DB) , i thought of changing the table's engines in the reporting database (the once that are replicated from batch) to mysiam and then somehow replicate with insert delayed and thus simulating somehow a "persist eventually" mechanism in mysql and as a result prioritize the reporting reads (they do allot of temp table creations) .
can this be done on the replication client alone (i.e. : not touching the master queries , the batch does not insert with insert delayed)  ? and is this a good solution ?
thanks </p>

答: You can just ignore any deadlock queries on your slave.  The only queries that would affect your replication would be insert/update queries.  A long-running SELECT query would only hog resources.</p>


问:
read method for jTextArea makes BufferedReader null
I'm trying to use read method for jTextArea from BufferedReader. It works and my text appears in jTextArea successfully. but after using read method it makes BufferedReader null. Here is my example code:

```<code>    private void Calculate() throws IOException{
       BufferedReader br = new BufferedReader(new FileReader(file)) ;

            jTextArea.read(br, "jTextArea");

            System.out.println(br.readLine());
}
</code>```

When I comment out this "jTextArea.read(br, "jTextArea");" println works properly and prints out the first line. But in normal case It prints null.
P.S: "file" is my instance variable. There is no problem with this variable, it works properly too.

答:
BufferedReader br object has reached its end after being read. So, not the br is null, but it's current line, which you're trying to read by br.readLine(). Otherwise a NullPointerException would be thrown on calling br.readLine().
You need to reinitialize BufferedReader and got the first line printed:

```<code>private void Calculate() throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(file));
    jTextArea.read(br, "jTextArea");
    br = new BufferedReader(new FileReader(file));
    System.out.println(br.readLine());
}
</code>```

Body:
I'm trying to use read method for jTextArea from BufferedReader. It works and my text appears in jTextArea successfully. but after using read method it makes BufferedReader null. Here is my example code:

    private void Calculate() throws IOException{
       BufferedReader br = new BufferedReader(new FileReader(file)) ;

            jTextArea.read(br, "jTextArea");

            System.out.println(br.readLine());
}

When I comment out this "jTextArea.read(br, "jTextArea");" println works properly and prints out the first line. But in normal case It prints null.
P.S: "file" is my instance variable. There is no problem with this variable, it works properly too.

Body:
BufferedReader br object has reached its end after being read. So, not the br is null, but it's current line, which you're trying to read by br.readLine(). Otherwise a NullPointerException would be thrown on calling br.readLine().
You need to reinitialize BufferedReader and got the first line printed:

private void Calculate() throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(file));
    jTextArea.read(br, "jTextArea");
    br = new BufferedReader(new FileReader(file));
    System.out.println(br.readLine());
}


问:
Octave - Create a matrix of all binary values
In Octave, given a number, (say 5), I need to make a matrix of (2^5 X 5) with each row having the binary representation of numbers from 0 to 2^5 - 1 i.e the matrix would be like

[[ 0,  0,  0,  0,  0],

[ 0,  0,  0,  0,  1]]

[ 0,  0,  0,  1,  0]]

and so on. Is there any built-in function to do this? Unable to figure out how to do it efficiently? One way I can think of is running a loop and generating the binary value for each value from 0:(2^5-1) and storing it in matrix, but this seems very inefficient.

答:
i don't know about octave, but in matlab you have de2bi:

```<code>n = 5;
nums = 0:2^n-1;
b = de2bi(nums);
</code>```

Body:
i don't know about octave, but in matlab you have de2bi:

n = 5;
nums = 0:2^n-1;
b = de2bi(nums);


问:
How to add Navigation bar programmatically by clicking the button
I have Login, Signup and Reset viewControllers I have connected the UINavigation controller to login controller but when I go to other view controllers by clicking the button like signup or reset password the destination controller appears without navigation bar. help to include navigation bar programmatically when I click the below button.

```<code>@IBAction func signupButton(_ sender: Any) {
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let newViewController = storyBoard.instantiateViewController(withIdentifier: "SignUpViewController") as! SignUpViewController
self.present(newViewController, animated: true, completion: nil)
}
</code>```

答:
For display navigation bar you need to add your  SignUpViewController in UINavigationController you can add directly in storyboard By

Selecting SignUpViewController -> Editor Menu -> Embed in -> Navigation Controller

OR

you can add programmatically  like this

```<code>IBAction func signupButton(_ sender: Any) {
     let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
     let newViewController = storyBoard.instantiateViewController(withIdentifier: "SignUpViewController") as! SignUpViewController
     let naviCon = UINavigationController(rootViewController:newViewController)
     self.present(naviCon, animated: true, completion: nil)
}
</code>```

Body:
I have Login, Signup and Reset viewControllers I have connected the UINavigation controller to login controller but when I go to other view controllers by clicking the button like signup or reset password the destination controller appears without navigation bar. help to include navigation bar programmatically when I click the below button.

@IBAction func signupButton(_ sender: Any) {
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let newViewController = storyBoard.instantiateViewController(withIdentifier: "SignUpViewController") as! SignUpViewController
self.present(newViewController, animated: true, completion: nil)
}

Body:
For display navigation bar you need to add your  SignUpViewController in UINavigationController you can add directly in storyboard By

Selecting SignUpViewController -> Editor Menu -> Embed in -> Navigation Controller

OR

you can add programmatically  like this

IBAction func signupButton(_ sender: Any) {
     let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
     let newViewController = storyBoard.instantiateViewController(withIdentifier: "SignUpViewController") as! SignUpViewController
     let naviCon = UINavigationController(rootViewController:newViewController)
     self.present(naviCon, animated: true, completion: nil)
}


问:
How can I write if/else with Boolean in Bash?
How can I write an 'if then' statement to switch between these to variables as in the following?

```<code>if(switch){
  server_var_shortname=$server_shared_shortname
  server_var=$server_shared
  server_var_bare=$server_shared_bare
} else {
  server_var_shortname=$server_vps_shortname
  server_var=$server_vps
  server_var_bare=$server_vps_bare
}
</code>```

I'm not familiar with Bash syntax and basically just need an 'if/else' statement on a Boolean. Also, can I use true / false values as such? Also how do I do the 'else' statement?

```<code>$switch=true;
if $switch
then
  server_var_shortname=$server_shared_shortname
  server_var=$server_shared
  server_var_bare=$server_shared_bare
fi
</code>```

答:
You need something like this:

```<code>if
  CONDITION_SEE_BELOW
then
  server_var_shortname=$server_shared_shortname
  server_var=$server_shared
  server_var_bare=$server_shared_bare
else
  server_var_shortname=$server_vps_shortname
  server_var=$server_vps
  server_var_bare=$server_vps_bare
fi
</code>```

In Bash (and other shells), the CONDITION_SEE_BELOW part has to be a command. A command returns a numerical value, and by convention 0 means "true" and any non-zero value means "false". The then clause will execute if the command returns 0, or the else clause in all other cases. The return value is not the text output by the command. In shells, you can access it with the special variable expansion $? right after executing a command.

You can test that with commands true and false, which do one thing: generate a zero (true) and non-zero (false) return value. Try this at the command line:

```<code>true ; echo "true returns $?"
false ; echo "false returns $?"
</code>```

You can use any command you want in a condition. There are two commands in particular that have been created with the idea of defining conditions: the classic test command [ ] (the actual command only being the opening bracket, which is also available as the test command), and the double-bracketed, Bash-specific [[ ]] (which is not technically a command, but rather special shell syntax).

For instance, say your switch variable contains either nothing (null string), or something (string with at least one character), and assume in your case you mean a null string to be "false" and any other string to be "true".  Then you could use as a condition:

```<code>[ "$switch" ]
</code>```

If you are OK with a string containing only spaces and tabs to be considered empty (which will happen as a result of standard shell expansion and word splitting of arguments to a command), then you may remove the double quotes.

The double-bracket test command is mostly similar, but has some nice things about it, including double-quoting not being needed most of the time, supporting Boolean logic with && and || inside the expression, and having regular expression matching as a feature.  It is, however a Bashism.

You can use this as a reference to various tests that can be performed with both test commands:

6.4 Bash Conditional Expressions

If at all interested in shell programming, be sure to find out about the various tests you can use, as you are likely to be using many of them frequently.

Body:
How can I write an 'if then' statement to switch between these to variables as in the following?

if(switch){
  server_var_shortname=$server_shared_shortname
  server_var=$server_shared
  server_var_bare=$server_shared_bare
} else {
  server_var_shortname=$server_vps_shortname
  server_var=$server_vps
  server_var_bare=$server_vps_bare
}

I'm not familiar with Bash syntax and basically just need an 'if/else' statement on a Boolean. Also, can I use true / false values as such? Also how do I do the 'else' statement?

$switch=true;
if $switch
then
  server_var_shortname=$server_shared_shortname
  server_var=$server_shared
  server_var_bare=$server_shared_bare
fi

Body:
You need something like this:

if
  CONDITION_SEE_BELOW
then
  server_var_shortname=$server_shared_shortname
  server_var=$server_shared
  server_var_bare=$server_shared_bare
else
  server_var_shortname=$server_vps_shortname
  server_var=$server_vps
  server_var_bare=$server_vps_bare
fi

In Bash (and other shells), the CONDITION_SEE_BELOW part has to be a command. A command returns a numerical value, and by convention 0 means "true" and any non-zero value means "false". The then clause will execute if the command returns 0, or the else clause in all other cases. The return value is not the text output by the command. In shells, you can access it with the special variable expansion $? right after executing a command.

You can test that with commands true and false, which do one thing: generate a zero (true) and non-zero (false) return value. Try this at the command line:

true ; echo "true returns $?"
false ; echo "false returns $?"

You can use any command you want in a condition. There are two commands in particular that have been created with the idea of defining conditions: the classic test command [ ] (the actual command only being the opening bracket, which is also available as the test command), and the double-bracketed, Bash-specific [[ ]] (which is not technically a command, but rather special shell syntax).

For instance, say your switch variable contains either nothing (null string), or something (string with at least one character), and assume in your case you mean a null string to be "false" and any other string to be "true".  Then you could use as a condition:

[ "$switch" ]

If you are OK with a string containing only spaces and tabs to be considered empty (which will happen as a result of standard shell expansion and word splitting of arguments to a command), then you may remove the double quotes.

The double-bracket test command is mostly similar, but has some nice things about it, including double-quoting not being needed most of the time, supporting Boolean logic with && and || inside the expression, and having regular expression matching as a feature.  It is, however a Bashism.

You can use this as a reference to various tests that can be performed with both test commands:

6.4 Bash Conditional Expressions

If at all interested in shell programming, be sure to find out about the various tests you can use, as you are likely to be using many of them frequently.


问:
How to reorder/sort dataframe indexes with Pandas?
I got some data:

```<code># 3 Experiments 0,1 and 2.
# 2 Setups 'foo' and 'bar'
# 3 Measured parameters 'a', 'b' and 'c'
d = {0: {'foo': {'a': 12.68, 'b': 54.44, 'c': 83.98},
         'bar': {'a': 11.73, 'b': 53.34, 'c': 82.93}},
     2: {'foo': {'a': 11.12, 'b': 57.99, 'c': 81.05},
         'bar': {'a': 10.05, 'b': 56.12, 'c': 80.01}},
     1: {'foo': {'a': 13.41, 'b': 54.32, 'c': 82.74},
         'bar': {'a': 12.77, 'b': 53.15, 'c': 82.01}}}
</code>```

I imported them in Pandas

```<code>ds = (pd.DataFrame.from_dict(d, orient='index')
      .stack().apply(pd.Series)
      .rename_axis(['experiment', 'setup']))
</code>```

Which then is nicely displayed:

```<code>                      a      b      c
experiment setup
0          foo    12.68  54.44  83.98
           bar    11.73  53.34  82.93
2          foo    11.12  57.99  81.05
           bar    10.05  56.12  80.01
1          foo    13.41  54.32  82.74
           bar    12.77  53.15  82.01
</code>```

You notice the experiments are in the wrong order and the setups are also not sorted. So I would like to sort the indexes to display it as follow:

```<code>                      a      b      c
experiment setup
0          bar    11.73  53.34  82.93
           foo    12.68  54.44  83.98
1          bar    12.77  53.15  82.01
           foo    13.41  54.32  82.74
2          bar    10.05  56.12  80.01
           foo    11.12  57.99  81.05
</code>```

I tried many things using sort, sort_index, sort_values or even sortlevel, but I doesn't seem to work. I also tried to flatten everything using reset_index and tried again with sort, but it doesn't work.

How to sort or reorder a dataframe as wanted?

答:
It's very weird that sort_index doesn't work as expected but I managed to get the expected output by resetting index, sorting values and setting the index back:

```<code>ds = ds.reset_index()\
       .sort_values(by=['experiment','setup'])\
       .set_index(['experiment','setup'])
</code>```

Body:
I got some data:

# 3 Experiments 0,1 and 2.
# 2 Setups 'foo' and 'bar'
# 3 Measured parameters 'a', 'b' and 'c'
d = {0: {'foo': {'a': 12.68, 'b': 54.44, 'c': 83.98},
         'bar': {'a': 11.73, 'b': 53.34, 'c': 82.93}},
     2: {'foo': {'a': 11.12, 'b': 57.99, 'c': 81.05},
         'bar': {'a': 10.05, 'b': 56.12, 'c': 80.01}},
     1: {'foo': {'a': 13.41, 'b': 54.32, 'c': 82.74},
         'bar': {'a': 12.77, 'b': 53.15, 'c': 82.01}}}

I imported them in Pandas

ds = (pd.DataFrame.from_dict(d, orient='index')
      .stack().apply(pd.Series)
      .rename_axis(['experiment', 'setup']))

Which then is nicely displayed:

                      a      b      c
experiment setup
0          foo    12.68  54.44  83.98
           bar    11.73  53.34  82.93
2          foo    11.12  57.99  81.05
           bar    10.05  56.12  80.01
1          foo    13.41  54.32  82.74
           bar    12.77  53.15  82.01

You notice the experiments are in the wrong order and the setups are also not sorted. So I would like to sort the indexes to display it as follow:

                      a      b      c
experiment setup
0          bar    11.73  53.34  82.93
           foo    12.68  54.44  83.98
1          bar    12.77  53.15  82.01
           foo    13.41  54.32  82.74
2          bar    10.05  56.12  80.01
           foo    11.12  57.99  81.05

I tried many things using sort, sort_index, sort_values or even sortlevel, but I doesn't seem to work. I also tried to flatten everything using reset_index and tried again with sort, but it doesn't work.

How to sort or reorder a dataframe as wanted?

Body:
It's very weird that sort_index doesn't work as expected but I managed to get the expected output by resetting index, sorting values and setting the index back:

ds = ds.reset_index()\
       .sort_values(by=['experiment','setup'])\
       .set_index(['experiment','setup'])


问:
PHP: game loop (threads or the sort)
I am writing PHP code to be a game client. It uses socket; socket_create followed by socket_connect and then socket_read. It works fine, but the issue is that the server can send a packet at any time which means socket_read needs to be happening constantly in a "game loop". So something like this:

```<code><?php
$reply = "";
do {
     $recv = "";
     $recv = socket_read($socket, '1400');
     if($recv != "") {
         $reply .= $recv;
     }
} while($recv != "");

echo($reply);
?>
</code>```

Doesn't work because it's stuck in the loop (server doesn't terminate connection until game is quit by client) and the PHP code needs to handle the packet stuff as it comes in.

So PHP doesn't really have threading. What's the best way of handling this?

答: PHP has no multithreading, so you should really consider to use a more suitable language (like Andrey mentioned in its comment).</p>

Title: PHP: game loop (threads or the sort)

Body:
I am writing PHP code to be a game client. It uses socket; socket_create followed by socket_connect and then socket_read. It works fine, but the issue is that the server can send a packet at any time which means socket_read needs to be happening constantly in a "game loop". So something like this:

<?php
$reply = "";
do {
     $recv = "";
     $recv = socket_read($socket, '1400');
     if($recv != "") {
         $reply .= $recv;
     }
} while($recv != "");

echo($reply);
?>

Doesn't work because it's stuck in the loop (server doesn't terminate connection until game is quit by client) and the PHP code needs to handle the packet stuff as it comes in.

So PHP doesn't really have threading. What's the best way of handling this?


问:
When should you check if a view != null before implementing it?
I am looking at Cheesesquare to learn some new design tools and I came across this bit of code that left me wondering. The code finds a view, then checks if it is null before continuing its setup.

Why would the view ever return null, assuming it exists and the id matches?

I trust the expertise of the person who wrote this code and I assume it is not a mistake, but what is its purpose? When should I check for null values and when is it unnecessary?

```<code>    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    if (navigationView != null) {
        setupDrawerContent(navigationView);
    }

    ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
    if (viewPager != null) {
        setupViewPager(viewPager);
    }
</code>```

...

```<code>private void setupViewPager(ViewPager viewPager) {
    Adapter adapter = new Adapter(getSupportFragmentManager());
    adapter.addFragment(new CheeseListFragment(), "Category 1");
    adapter.addFragment(new CheeseListFragment(), "Category 2");
    adapter.addFragment(new CheeseListFragment(), "Category 3");
    viewPager.setAdapter(adapter);
}

private void setupDrawerContent(NavigationView navigationView) {
    navigationView.setNavigationItemSelectedListener(
            new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {
            menuItem.setChecked(true);
</code>```

答: In addition to the other answers, I just want to make a point. Because we don't know the entirety of this code base I am assuming this user is writing his/her code to be modular. There are times we may want to dynamically add views and the timing of the binding causes us to be cautious. In those scenarios, we'd like to make sure the view we're trying to load isn't null. </p>

Body:
I am looking at Cheesesquare to learn some new design tools and I came across this bit of code that left me wondering. The code finds a view, then checks if it is null before continuing its setup.

Why would the view ever return null, assuming it exists and the id matches?

I trust the expertise of the person who wrote this code and I assume it is not a mistake, but what is its purpose? When should I check for null values and when is it unnecessary?

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    if (navigationView != null) {
        setupDrawerContent(navigationView);
    }

    ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
    if (viewPager != null) {
        setupViewPager(viewPager);
    }

...

private void setupViewPager(ViewPager viewPager) {
    Adapter adapter = new Adapter(getSupportFragmentManager());
    adapter.addFragment(new CheeseListFragment(), "Category 1");
    adapter.addFragment(new CheeseListFragment(), "Category 2");
    adapter.addFragment(new CheeseListFragment(), "Category 3");
    viewPager.setAdapter(adapter);
}

private void setupDrawerContent(NavigationView navigationView) {
    navigationView.setNavigationItemSelectedListener(
            new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {
            menuItem.setChecked(true);


答: Can be done, but I agree with @Andrey and @DampeS8N, not the best choice.  If you are dead set on doing this, check out this book:  You want to do WHAT with PHP?

Title: PHP: game loop (threads or the sort)


问:
Requests in authenticated session are sometimes sent by AnonymousUser in Django
I've a django application which runs on gunicorn behind nginx proxy.

When users log in, I redirect them to a single page application which is developed by Angular.

I'm using @login_required decorator for all functions used in SPA.

While using the application, one random function call suddenly is sent as AnonymousUser, so the @login_required decorator does not work, so I log out the user, or show error.

I'm using a custom user profile, with session engine as cached_db run by memcached & postgresql behind pgbouncer

My authentication relative settings are as follows:
ps: get_env_variable() function gets the variable from the OS environment.

```<code>AUTH_USER_MODEL = 'main.User'
AUTH_PROFILE_MODULE = 'main.User'
INSTALLED_APPS = [
    'django.contrib.auth',
    'django.contrib.sessions',
    ***
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

#Sessions
SESSION_SAVE_EVERY_REQUEST = True
SESSION_COOKIE_NAME = 'sesid'
SESSION_COOKIE_PATH = '/'
SESSION_COOKIE_DOMAIN = 'domain.com'
SESSION_COOKIE_SECURE  = True
SESSION_COOKIE_AGE = 1800
SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'
CSRF_COOKIE_NAME = 'csrftkn'
CSRF_COOKIE_PATH = '/'
CSRF_COOKIE_SECURE = True
CSRF_COOKIE_HTTPONLY = True
CSRF_COOKIE_DOMAIN = 'domain.com'
CSRF_COOKIE_AGE = 1800
CSRF_TRUSTED_ORIGINS = ['domain.com']
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
X_FRAME_OPTIONS = "SAMEORIGIN"
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': get_env_variable("DATABASE_NAME"),
        'USER': get_env_variable("DATABASE_USER"),
        'PASSWORD': get_env_variable("DATABASE_PASSWORD"),
        'HOST': get_env_variable("DATABASE_HOST"),
        'PORT' : get_env_variable("DATABASE_PORT"),
        'CONN_MAX_AGE': None,
        'OPTIONS': {
            'sslmode': 'verify-full',
        }
    }
}
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': "127.0.0.1:11211",
    }
}
</code>```

Funny thing is, I'm using the same settings for another Django application, which works perfect. What could be the reason for Django sending one request as AnonymousUser? I've never seen this before..

Also, if I remove the @login_required decorator, the next function call is sent as the logged user. So 1 out of 15-20 requests is sent as AnonymousUser. Which is really strange..

答:
My sentry logs showed up a strange issue which is;

```<code>DjangoUnicodeDecodeError: 'utf8' codec can't decode byte 0xdd in position 12: invalid continuation byte. You passed in 'HTTP_CONNECT\xddON' (<type 'str'>
</code>```

When I dug into the situation, it turns out that in one of my functions I was using locale and set the locale to tr_TR. After setting the locale, the request headers are converted to HTTP_CONNECT\xddON from HTTP_CONNECTION, which messes the request and turns the request user into AnonymousUser.

I don't know why this happens but when I removed the locale, it works perfectly.

Body:
I've a django application which runs on gunicorn behind nginx proxy.

When users log in, I redirect them to a single page application which is developed by Angular.

I'm using @login_required decorator for all functions used in SPA.

While using the application, one random function call suddenly is sent as AnonymousUser, so the @login_required decorator does not work, so I log out the user, or show error.

I'm using a custom user profile, with session engine as cached_db run by memcached & postgresql behind pgbouncer

My authentication relative settings are as follows:
ps: get_env_variable() function gets the variable from the OS environment.

AUTH_USER_MODEL = 'main.User'
AUTH_PROFILE_MODULE = 'main.User'
INSTALLED_APPS = [
    'django.contrib.auth',
    'django.contrib.sessions',
    ***
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

#Sessions
SESSION_SAVE_EVERY_REQUEST = True
SESSION_COOKIE_NAME = 'sesid'
SESSION_COOKIE_PATH = '/'
SESSION_COOKIE_DOMAIN = 'domain.com'
SESSION_COOKIE_SECURE  = True
SESSION_COOKIE_AGE = 1800
SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'
CSRF_COOKIE_NAME = 'csrftkn'
CSRF_COOKIE_PATH = '/'
CSRF_COOKIE_SECURE = True
CSRF_COOKIE_HTTPONLY = True
CSRF_COOKIE_DOMAIN = 'domain.com'
CSRF_COOKIE_AGE = 1800
CSRF_TRUSTED_ORIGINS = ['domain.com']
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
X_FRAME_OPTIONS = "SAMEORIGIN"
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': get_env_variable("DATABASE_NAME"),
        'USER': get_env_variable("DATABASE_USER"),
        'PASSWORD': get_env_variable("DATABASE_PASSWORD"),
        'HOST': get_env_variable("DATABASE_HOST"),
        'PORT' : get_env_variable("DATABASE_PORT"),
        'CONN_MAX_AGE': None,
        'OPTIONS': {
            'sslmode': 'verify-full',
        }
    }
}
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': "127.0.0.1:11211",
    }
}

Funny thing is, I'm using the same settings for another Django application, which works perfect. What could be the reason for Django sending one request as AnonymousUser? I've never seen this before..

Also, if I remove the @login_required decorator, the next function call is sent as the logged user. So 1 out of 15-20 requests is sent as AnonymousUser. Which is really strange..

Body:
My sentry logs showed up a strange issue which is;

DjangoUnicodeDecodeError: 'utf8' codec can't decode byte 0xdd in position 12: invalid continuation byte. You passed in 'HTTP_CONNECT\xddON' (<type 'str'>

When I dug into the situation, it turns out that in one of my functions I was using locale and set the locale to tr_TR. After setting the locale, the request headers are converted to HTTP_CONNECT\xddON from HTTP_CONNECTION, which messes the request and turns the request user into AnonymousUser.

I don't know why this happens but when I removed the locale, it works perfectly.


问:
Why am I not listed as a contributor to a project that merged my PR?
I had a PR merged to the master branch of an open source project on GitHub. The project is not a fork, and if I view the file in the master tree that I edited in my PR, I am listed there as a contributor to that file.

For some reason, however, I am not appearing in the project's main "contributors" page. Does anyone know why this would be? I've already viewed this GitHub help page about contributions showing up on my own profile but my question is about showing up in the "contributors" page of the actual project.

For reference, here is the PR in question: https://github.com/octokit/octokit.rb/pull/780

答:
For some cases, it could be a squash merged PR.

The authorship then completely belongs to the person who merged the PR. GitHub seems to credit you as contribution on your profile, but since it's not counted in commit there's a possibility that the changes doesn't makes you a contributor.

When a pull request is merged and commits are squashed, only the user that merged the pull request and the user that opened the pull request receive contribution credit. No other contributors to the pull request will receive contribution credit. link

Update: only the "top" 100 contributors are crawled, and it's a strict limit of 100 and cuts the rest. You only contributed one, so you're end up hiding in the cutted part.

The best way to confirm whether you have the contributor status is to use the recently implemented badge feature in the comments. You seem to have it.


问:
How to select multiple checkbox in for loop in angular2?
I have tried angular 2 to list categories list with checkbox and user can select any category. I tried with below code. The issue is if I selected any one checkbox all the checkbox are selected and I cannot get the form values on save function. Food.category is dynamic. How can I fix this?</p>

```<code><form #f="ngForm" novalidate>
    <div class="checkbox checkbox-primary" *ngFor="let categoryname of Food.category;">
        <label for="categoryname">
            <input type = "checkbox" name="categoryname[]" [(ngModel)]="Catcheckbox" (click)="onClick(categoryname)" value="{{categoryname}}"/>
            {{categoryname}}
        </label>
    </div>
    <button type="submit" (click)="save(f.value, f.valid)" class="btn btn-default">Submit</button>
</form>

export class ExploreListComponent implements OnInit {
    Catcheckbox:true ;

    onClick(categoryname) {
        alert(categoryname + ' was clicked!');
    }

    save(isValid: boolean, f: User) {
        if (!isValid) return;
        console.log(f);
    }
}
</code>```

答:
Change your code as below , and you will get all selected checkboxes values;

Template :

```<code><form #f="ngForm" novalidate>
    <div class="checkbox checkbox-primary" *ngFor="let categoryname of Food.category;let i=index;">
        <label for="categoryname">
            <input type="checkbox" name="categoryname[{{i}}]"  [value]="categoryname"
(change)="categories[$event.target.getAttribute('value')]=$event.target.checked"/>
        {{categoryname}}
        </label>
    </div>
        <button type="submit" (click)="save(f.valid)" class="btn btn-default">Submit</button>
</form>
</code>```

Component :

```<code>export class ExploreListComponent implements OnInit {

        categories = {};

        save(isValid: boolean) {
            if (!isValid) return;
            console.log(this.categories);
        }
    }
</code>```

Body:
I have tried angular 2 to list categories list with checkbox and user can select any category. I tried with below code. The issue is if I selected any one checkbox all the checkbox are selected and I cannot get the form values on save function. Food.category is dynamic. How can I fix this?

<form #f="ngForm" novalidate>

            <input type = "checkbox" name="categoryname[]" [(ngModel)]="Catcheckbox" (click)="onClick(categoryname)" value="{{categoryname}}"/>
            {{categoryname}}

    <button type="submit" (click)="save(f.value, f.valid)" class="btn btn-default">Submit</button>
</form>

export class ExploreListComponent implements OnInit {
    Catcheckbox:true ;

    onClick(categoryname) {
        alert(categoryname + ' was clicked!');
    }

    save(isValid: boolean, f: User) {
        if (!isValid) return;
        console.log(f);
    }
}

Body:
Change your code as below , and you will get all selected checkboxes values;

Template :

<form #f="ngForm" novalidate>
    <div class="checkbox checkbox-primary" *ngFor="let categoryname of Food.category;let i=index;">
        <label for="categoryname">
            <input type="checkbox" name="categoryname[{{i}}]"  [value]="categoryname"
(change)="categories[$event.target.getAttribute('value')]=$event.target.checked"/>
        {{categoryname}}
        </label>
    </div>
        <button type="submit" (click)="save(f.valid)" class="btn btn-default">Submit</button>
</form>

Component :

export class ExploreListComponent implements OnInit {

        categories = {};

        save(isValid: boolean) {
            if (!isValid) return;
            console.log(this.categories);
        }
    }


问:
Signal handling for background processes
I'm trying to implement a simple Unix shell in C. However, I could not implement background process feature by using sigaction. My code structure is like the following:

```<code>int main() {
struct sigaction act;
act.sa_handler = handler;

sigaction(SIGCHLD, &act, 0);

while(1) {
    parseCommand();
    execCommand();
}
}
</code>```

Also, in my execCommand function, the structure is like:

```<code>if (fork()) {
    if (!isBackground) {
        wait(&child_status);
    }
    else
    printf("Background process\n");
}
else
    ... // Command execution...
</code>```

My handler is like the following:

```<code>void handler(int s) {
while (waitpid(-1, NULL, WNOHANG) > 0) {
}
printf("OK.\n");
}
</code>```

But this structure harms my whole implementation. Even the foreground processes are not working. When I execute a foreground command, it gives:

```<code>Segmentation fault (core dumped)
</code>```

When I execute a background command, it gives:

```<code>Bus error (core dumped)
</code>```

So, how can I solve this problem?

Thanks in advance...

EDIT : When I debug my code with valgrind, it gives the following:

```<code>==6768== Memcheck, a memory error detector
==6768== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==6768== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==6768== Command: ./shell
==6768==
==6768== Syscall param rt_sigaction(act->sa_mask) points to uninitialised byte(s)
==6768==    at 0x4E6F5AE: __libc_sigaction (sigaction.c:62)
==6768==    by 0x400E90: main (in /home/enes/Desktop/Shell/shell)
==6768==  Address 0xffefff908 is on thread 1's stack
==6768==
==6768== Syscall param rt_sigaction(act->sa_flags) points to uninitialised byte(s)
==6768==    at 0x4E6F5AE: __libc_sigaction (sigaction.c:62)
==6768==    by 0x400E90: main (in /home/enes/Desktop/Shell/shell)
==6768==  Address 0xffefff8f8 is on thread 1's stack
==6768==
> ls
==6768== Use of uninitialised value of size 8
==6768==    at 0x4EA8C80: _IO_getline_info (iogetline.c:77)
==6768==    by 0x4EA7B7C: fgets (iofgets.c:53)
==6768==    by 0x400EC9: main (in /home/enes/Desktop/Shell/shell)
==6768==
==6768== Invalid write of size 1
==6768==    at 0x4EA8C80: _IO_getline_info (iogetline.c:77)
==6768==    by 0x4EA7B7C: fgets (iofgets.c:53)
==6768==    by 0x400EC9: main (in /home/enes/Desktop/Shell/shell)
==6768==  Address 0x0 is not stack'd, malloc'd or (recently) free'd
==6768==
==6768==
==6768== Process terminating with default action of signal 11 (SIGSEGV)
==6768==  Access not within mapped region at address 0x0
==6768==    at 0x4EA8C80: _IO_getline_info (iogetline.c:77)
==6768==    by 0x4EA7B7C: fgets (iofgets.c:53)
==6768==    by 0x400EC9: main (in /home/enes/Desktop/Shell/shell)
==6768==  If you believe this happened as a result of a stack
==6768==  overflow in your program's main thread (unlikely but
==6768==  possible), you can try to increase the size of the
==6768==  main thread stack using the --main-stacksize= flag.
==6768==  The main thread stack size used in this run was 8388608.
==6768==
==6768== HEAP SUMMARY:
==6768==     in use at exit: 0 bytes in 0 blocks
==6768==   total heap usage: 2 allocs, 2 frees, 2,048 bytes allocated
==6768==
==6768== All heap blocks were freed -- no leaks are possible
==6768==
==6768== For counts of detected and suppressed errors, rerun with: -v
==6768== Use --track-origins=yes to see where uninitialised values come from
==6768== ERROR SUMMARY: 4 errors from 4 contexts (suppressed: 0 from 0)
Segmentation fault (core dumped)
</code>```

答:
```<code>Syscall param rt_sigaction(act->sa_mask) points to uninitialised byte(s)
</code>```

You need to completely initialise the sigaction structure, else it contains indeterminate values. Reading those (probably by the sigaction() function call) might very well cause Undefined Behaviour, from which on anything can happen.

To fix this change

```<code>struct sigaction act;
</code>```

to be

```<code>struct sigaction act = {0};
</code>```

Probably not the issue you are facing, but still:

It is not save to call any member of the printf()-family of functions from a signal handler.

Even more: the set of functions which can safely be called from a signal handler is (very) limited. For a complete list see chapter 2.4.3 on this page.

To fix this change

```<code>printf("OK.\n");
</code>```

to be

```<code>write(STDERR_FILENO, "OK.\n", sizeof "OK.\n" -1);
</code>```

or alike. As per the list linked above write() is save to call from a signal handler.

```<code>==6768== Use of uninitialised value of size 8
==6768==    at 0x4EA8C80: _IO_getline_info (iogetline.c:77)
==6768==    by 0x4EA7B7C: fgets (iofgets.c:53)
</code>```

What's actually wrong with the call to fgets() we cannot tell, as you do not show us the relevant code.

Body:
I'm trying to implement a simple Unix shell in C. However, I could not implement background process feature by using sigaction. My code structure is like the following:

int main() {
struct sigaction act;
act.sa_handler = handler;

sigaction(SIGCHLD, &act, 0);

while(1) {
    parseCommand();
    execCommand();
}
}

Also, in my execCommand function, the structure is like:

if (fork()) {
    if (!isBackground) {
        wait(&child_status);
    }
    else
    printf("Background process\n");
}
else
    ... // Command execution...

My handler is like the following:

void handler(int s) {
while (waitpid(-1, NULL, WNOHANG) > 0) {
}
printf("OK.\n");
}

But this structure harms my whole implementation. Even the foreground processes are not working. When I execute a foreground command, it gives:

Segmentation fault (core dumped)

When I execute a background command, it gives:

Bus error (core dumped)

So, how can I solve this problem?

Thanks in advance...

EDIT : When I debug my code with valgrind, it gives the following:

==6768== Memcheck, a memory error detector
==6768== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==6768== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==6768== Command: ./shell
==6768==
==6768== Syscall param rt_sigaction(act->sa_mask) points to uninitialised byte(s)
==6768==    at 0x4E6F5AE: __libc_sigaction (sigaction.c:62)
==6768==    by 0x400E90: main (in /home/enes/Desktop/Shell/shell)
==6768==  Address 0xffefff908 is on thread 1's stack
==6768==
==6768== Syscall param rt_sigaction(act->sa_flags) points to uninitialised byte(s)
==6768==    at 0x4E6F5AE: __libc_sigaction (sigaction.c:62)
==6768==    by 0x400E90: main (in /home/enes/Desktop/Shell/shell)
==6768==  Address 0xffefff8f8 is on thread 1's stack
==6768==
> ls
==6768== Use of uninitialised value of size 8
==6768==    at 0x4EA8C80: _IO_getline_info (iogetline.c:77)
==6768==    by 0x4EA7B7C: fgets (iofgets.c:53)
==6768==    by 0x400EC9: main (in /home/enes/Desktop/Shell/shell)
==6768==
==6768== Invalid write of size 1
==6768==    at 0x4EA8C80: _IO_getline_info (iogetline.c:77)
==6768==    by 0x4EA7B7C: fgets (iofgets.c:53)
==6768==    by 0x400EC9: main (in /home/enes/Desktop/Shell/shell)
==6768==  Address 0x0 is not stack'd, malloc'd or (recently) free'd
==6768==
==6768==
==6768== Process terminating with default action of signal 11 (SIGSEGV)
==6768==  Access not within mapped region at address 0x0
==6768==    at 0x4EA8C80: _IO_getline_info (iogetline.c:77)
==6768==    by 0x4EA7B7C: fgets (iofgets.c:53)
==6768==    by 0x400EC9: main (in /home/enes/Desktop/Shell/shell)
==6768==  If you believe this happened as a result of a stack
==6768==  overflow in your program's main thread (unlikely but
==6768==  possible), you can try to increase the size of the
==6768==  main thread stack using the --main-stacksize= flag.
==6768==  The main thread stack size used in this run was 8388608.
==6768==
==6768== HEAP SUMMARY:
==6768==     in use at exit: 0 bytes in 0 blocks
==6768==   total heap usage: 2 allocs, 2 frees, 2,048 bytes allocated
==6768==
==6768== All heap blocks were freed -- no leaks are possible
==6768==
==6768== For counts of detected and suppressed errors, rerun with: -v
==6768== Use --track-origins=yes to see where uninitialised values come from
==6768== ERROR SUMMARY: 4 errors from 4 contexts (suppressed: 0 from 0)
Segmentation fault (core dumped)

Body:
Syscall param rt_sigaction(act->sa_mask) points to uninitialised byte(s)

You need to completely initialise the sigaction structure, else it contains indeterminate values. Reading those (probably by the sigaction() function call) might very well cause Undefined Behaviour, from which on anything can happen.

To fix this change

struct sigaction act;

to be

struct sigaction act = {0};

Probably not the issue you are facing, but still:

It is not save to call any member of the printf()-family of functions from a signal handler.

Even more: the set of functions which can safely be called from a signal handler is (very) limited. For a complete list see chapter 2.4.3 on this page.

To fix this change

printf("OK.\n");

to be

write(STDERR_FILENO, "OK.\n", sizeof "OK.\n" -1);

or alike. As per the list linked above write() is save to call from a signal handler.

==6768== Use of uninitialised value of size 8
==6768==    at 0x4EA8C80: _IO_getline_info (iogetline.c:77)
==6768==    by 0x4EA7B7C: fgets (iofgets.c:53)

What's actually wrong with the call to fgets() we cannot tell, as you do not show us the relevant code.


问:
Typescript type safety in switch case statements
I'm working with Redux and I'm trying to make my reducers type safe. I found some code example from the ngrx-store/example app where they perfectly succeed in doing this. (https://github.com/ngrx/example-app/blob/master/src/app/actions/book.ts)

While integrating this in my own project, I noticed something strange, which I cannot explain. Check the following code sample (some comments inline):

```<code>// Action has a type and payload property
interface Action {
    type: string;
    payload?: any;
}

// Here I declare the action types as plain strings
const FIRST = "FIRST";
const SECOND = "SECOND";

// I create classes for every action with there respective types
class FirstAction implements Action {
    public type = FIRST;
    payload: { id: number };

    public constructor(id: number) {
        this.payload = { id };
    }
}

class SecondAction implements Action {
    public type = SECOND;

    public constructor() { }
}

// Create a union type
type Actions = FirstAction | SecondAction;

// Use the union type as type parameter in my function
function test(action: Actions): void {
    switch (action.type) {
        case FIRST:
                    // compiler will complain it cannot find the payload
                    // property on Actions
            let temp = action.payload.id;
        case SECOND:
        // empty
        default:
        //empty
    }
}
</code>```

If I replace the definition of the FIRST and SECOND properties into the following, it does work.

```<code>export function type<T>(label: T | ''): T {
    return <T>label;
}

const FIRST = type("FIRST");
const SECOND = type("SECOND");
</code>```

As far as I can see, the type function only casts the string back to a string. Why does the code work with calling the type function but not when declaring the strings immediately?

Here's a typescript playground example where you can just comment the definitons in or out (first with the working version).

答:
I would use the as operator:

```<code>let temp = (action as FirstAction).payload.id;
</code>```

Some other thoughts:

- Do you really need Actions if you already have Action that all
   your action classes implement?

- Extracting the reducer of each case into a function may help readability and unit testing.

- Remember that reducers take state and action, and return state (I understand you just simplified your example).

```<code>function test(state: State, action: Action): State {
    switch (action.type) {
        case FIRST:
            return handleFirst(state, action as FirstAction);
        case SECOND:
            return handleSecond(state, action as SecondAction);
        default:
            return state;
    }
}

function handleFirst(state: State, action: FirstAction): State {
    let temp = action.payload.id;
    // ...
}

// ...
</code>```

Body:
I'm working with Redux and I'm trying to make my reducers type safe. I found some code example from the ngrx-store/example app where they perfectly succeed in doing this. (https://github.com/ngrx/example-app/blob/master/src/app/actions/book.ts)

While integrating this in my own project, I noticed something strange, which I cannot explain. Check the following code sample (some comments inline):

// Action has a type and payload property
interface Action {
    type: string;
    payload?: any;
}

// Here I declare the action types as plain strings
const FIRST = "FIRST";
const SECOND = "SECOND";

// I create classes for every action with there respective types
class FirstAction implements Action {
    public type = FIRST;
    payload: { id: number };

    public constructor(id: number) {
        this.payload = { id };
    }
}

class SecondAction implements Action {
    public type = SECOND;

    public constructor() { }
}

// Create a union type
type Actions = FirstAction | SecondAction;

// Use the union type as type parameter in my function
function test(action: Actions): void {
    switch (action.type) {
        case FIRST:
                    // compiler will complain it cannot find the payload
                    // property on Actions
            let temp = action.payload.id;
        case SECOND:
        // empty
        default:
        //empty
    }
}

If I replace the definition of the FIRST and SECOND properties into the following, it does work.

export function type<T>(label: T | ''): T {
    return <T>label;
}

const FIRST = type("FIRST");
const SECOND = type("SECOND");

As far as I can see, the type function only casts the string back to a string. Why does the code work with calling the type function but not when declaring the strings immediately?

Here's a <a href="http://www.typescriptlang.org/play/#src=interface%20Action%20%7B%0D%0A%09type:%20string;%0D%0A%09payload?:%20any;%0D%0A%7D%0D%0A%0D%0Aexport%20function%20type%3CT%3E(label:%20T%20%7C%20''):%20T%20%7B%0D%0A%09return%20%3CT%3Elabel;%0D%0A%7D%0D%0A%0D%0Aconst%20FIRST%20=%20type(%22FIRST%22);%0D%0Aconst%20SECOND%20=%20type(%22SECOND%22);%0D%0A%0D%0A//const%20FIRST%20=%20%22FIRST%22;%0D%0A//const%20SECOND%20=%20%22SECOND%22;%0D%0A%0D%0Aclass%20FirstAction%20implements%20Action%20%7B%0D%0A%09public%20type%20=%20FIRST;%0D%0A%09payload:%20%7B%20id:%20number%20%7D;%0D%0A%0D%0A%09public%20constructor(id:%20number)%20%7B%0D%0A%09%09this.payload%20=%20%7B%20id%20%7D;%0D%0A%09%7D%0D%0A%7D%0D%0A%0D%0Aclass%20SecondAction%20implements%20Action%20%7B%0D%0A%09public%20type%20=%20SECOND;%0D%0A%0D%0A%09public%20constructor()%20%7B%20%7D%0D%0A%7D%0D%0A%0D%0Atype%20Actions%20=%20FirstAction%20%7C%20SecondAction;%0D%0A%0D%0Afunction%20test(action:%20Actions):%20void%20%7B%0D%0A%09switch%20(action.type)%20%7B%0D%0A%09%09case%20FIRST:%0D%0A%09%09%09let%20temp%20=%20action.payload.id;%0D%0A%09%09case%20SECOND:%0D%0A%09%09//%20empty%0D%0A%09%09default:%0D%0A%09%09//empty%0D%0A%09%7D%0D%0A%7D%0D%0A" rel="noreferrer">typescript playground example where you can just comment the definitons in or out (first with the working version).

Body:
I would use the as operator:

let temp = (action as FirstAction).payload.id;

Some other thoughts:

- Do you really need Actions if you already have Action that all
   your action classes implement?

- Extracting the reducer of each case into a function may help readability and unit testing.

- Remember that reducers take state and action, and return state (I understand you just simplified your example).

function test(state: State, action: Action): State {
    switch (action.type) {
        case FIRST:
            return handleFirst(state, action as FirstAction);
        case SECOND:
            return handleSecond(state, action as SecondAction);
        default:
            return state;
    }
}

function handleFirst(state: State, action: FirstAction): State {
    let temp = action.payload.id;
    // ...
}

// ...


问:
Omnifaces socket + commandScript combinations
I'd like to implement the OmniFaces <o:socket> with the <o:commandScript> option as documented here.

My JSF page looks like:

```<code><h:form id="myForm">
    <!-- the socket is by default disconnected. It will
         connect when the user selects a subChannel.
         Setting the subChannel to "null" must disconnect
         the socket -->
    <o:socket channel="myChannel" scope="session"
              connected="#{myManager.subChannel ne null}"
              user="#{myManager.subChannel}"
              onmessage="someTestScript" onopen="onOpen" onclose="onClose"/>

    <o:commandScript name="someTestScript"
                     actionListener="#{myManager.testPush}"
                     render=":testValue" />

    <!-- dummy rendering to check if everything is working -->
    <h:panelGroup id="testValue"
                  rendered="#{myManager.subChannel ne null}" >
        <h:outputText value="#{myManager.bbb} #{myManager.aaa}" />
    </h:panelGroup>

    <!-- To simplify: I have several buttons which allows
         the user to select the socket "user". The buttons
         are only displayed when no "user" is selected
         (thus, socket is not connected yet as well) -->
    <p:dataGrid value=#{...a list...} var="sth"
                rendered="#{myManager.subChannel eq null">

        <p:ajax event="click"
                update="myForm"
                listener="#{myManager.setSubChannel(sth.id)}" />

        <p:panel>
            <h:outputText value=#{sth.text} />
        </p:panel>

    </p:dataGrid>

    <!-- Resetting -->
    <p:commandButton value="Reset"
                     actionListener="#{myManager.setSubChannel(null)"
                     update="myForm" />
</h:form>
</code>```

My backing bean:

```<code>@Named(value = "myManager")
@SessionScoped
public class MyStuffManager implements Serializable{

    private Long subChannel = null;
    private Long aaa;
    private String bbb;

    public void testPush(Long aaa, String bbb){
       System.out.println("Text received: " + bbb + ", Number received: " + aaa);
       this.aaa = aaa;
       this.bbb = bbb;
    }

    // getter & setter

}
</code>```

My socket push point:

```<code>@Named
@ApplicationScoped
public Class mySocket implements Serializable{
    @Inject
    @Push(channel = "myChannel")
    private PushContext socket;

    // Basically, all methods are triggered by CDI events. So
    // far, I just want to send an int and a String to see how
    // I send parameters.
    public void test(@Observes @MyEventQualifier AnEvent event) {
        Map<String, Object> input = new HashMap<>();
        input.put("aaa", 123456789);
        input.put("bbb", "a text");
        socket.send(input);
    }
}
</code>```

Currently, my situation is:

When clicking a panel and the "reset" button, the socket properly connects and disconnect.

Still according to linked documentation, the <f:ajax> option properly works but I cannot send parameters.

However, my open points are:

the <o:socket> has a "null" user attribute. Regardless if I use the "connect" attribute to trigger a connection or a ```oncomplete="OmniFaces.Push.open('myChannel')"```, the subChannel is still resolved to null. Strangely enough, if I execute other JSF stuff (like updating an <h:outputText> field), the subChannel is properly updated and retrieved. How should I have a dynamic "user" attribute depending on a EL when connection is not automatic?

I have missed something from the OmniFaces documentation as the myManager.testPush is never called. What have I missed? Instead, I have a ReferenceError: someTestScript is not defined on my Firefox console. I tried to add an empty someTestScript in a JavaScript file but it looks like only the empty one is called, not the o:commandScript.

We're using OmniFaces 2.6 as stated by the documentation.

Any hint/advise is obviously welcomed. Thanks.

答:
I finally fixed it! For those who are interested in the solving, and note for myself later:

1) How to dynamically change sub channel

Option 1: Change the o:socket scope to view so that the HTTP session scope is wider than the socket scope.

```<code><o:socket channel="myChannel" scope="view"
          connected="#{myManager.subChannel ne null}"
          user="#{myManager.subChannel}"
          onmessage="someTestScript" onopen="onOpen" onclose="onClose"/>
</code>```

When exiting the socket, the socket will properly closes and re-open with the correct subChannel value. For some reasons, it seems than having a "subChannel" as a String works better than Long.

Option 2: Use a "sub channel map". Actually, I haven't stated in my problem than multiple users can connect to the same sub channel. Another option is to have all users connected via their userId <o:socket channel="myChannel" user="#{user.id}" session="scope" /*default value anyway*/ {...}/>

Then, instead of sending to a subchannel, I send to a collection of user id:

```<code>Map<String, Set<String>> subChannelUserMap = new HashMap<>();
// ...
public void onUserConnect(User user, String subChannel){
    subChannelUserMap.get(subChannel).add(user.getId());
}
// ....
public void sendMessage(Map<K, V> input, String subChannel){
    socket.send(input, subChannelUserMap.get(subChannel));
}
</code>```

2) Call backing bean methods from JavaScript

As stated in my self-comment, I misunderstood <o:commandScript> usage. Let's consider the backing bean method:

```<code>// ...
public class BackingBean{
    public void test(){
        String aaa = Faces.getRequestParameter("aaa", String.class);
        String bbb = Faces.getRequestParameter("aSillyName", String.class);
        LOGGER.debug("aaa={}, bbb={}", aaa, bbb);
    }
}
</code>```

with the socket written as <o:socket /*...*/ onmessage=onMessage />, I'll have:

JSF Page:

```<code> <o:commandScript name="aSillyFunctionName" render="..."
                  actionListener="#{backingBean.test}" ... />
</code>```

JavaScript file:

```<code> function onMessage(message, channel, event){
     aSillyFunctionName({aaa: message.aaa, aSillyName: bbb});
 }
</code>```

And here I'm done.

Body:
I'd like to implement the OmniFaces <o:socket> with the <o:commandScript> option as documented here.

My JSF page looks like:

<h:form id="myForm">

    <o:socket channel="myChannel" scope="session"
              connected="#{myManager.subChannel ne null}"
              user="#{myManager.subChannel}"
              onmessage="someTestScript" onopen="onOpen" onclose="onClose"/>

    <o:commandScript name="someTestScript"
                     actionListener="#{myManager.testPush}"
                     render=":testValue" />

    <h:panelGroup id="testValue"
                  rendered="#{myManager.subChannel ne null}" >
        <h:outputText value="#{myManager.bbb} #{myManager.aaa}" />
    </h:panelGroup>

            <h:outputText value=#{sth.text} />

</h:form>

My backing bean:

@Named(value = "myManager")
@SessionScoped
public class MyStuffManager implements Serializable{

    private Long subChannel = null;
    private Long aaa;
    private String bbb;

    public void testPush(Long aaa, String bbb){
       System.out.println("Text received: " + bbb + ", Number received: " + aaa);
       this.aaa = aaa;
       this.bbb = bbb;
    }

    // getter & setter

}

My socket push point:

@Named
@ApplicationScoped
public Class mySocket implements Serializable{
    @Inject
    @Push(channel = "myChannel")
    private PushContext socket;

    // Basically, all methods are triggered by CDI events. So
    // far, I just want to send an int and a String to see how
    // I send parameters.
    public void test(@Observes @MyEventQualifier AnEvent event) {
        Map<String, Object> input = new HashMap<>();
        input.put("aaa", 123456789);
        input.put("bbb", "a text");
        socket.send(input);
    }
}

Currently, my situation is:

When clicking a panel and the "reset" button, the socket properly connects and disconnect.

Still according to linked documentation, the <f:ajax> option properly works but I cannot send parameters.

However, my open points are:

the <o:socket> has a "null" user attribute. Regardless if I use the "connect" attribute to trigger a connection or a
oncomplete="OmniFaces.Push.open('myChannel')"
, the subChannel is still resolved to null. Strangely enough, if I execute other JSF stuff (like updating an <h:outputText> field), the subChannel is properly updated and retrieved. How should I have a dynamic "user" attribute depending on a EL when connection is not automatic?

I have missed something from the OmniFaces documentation as the myManager.testPush is never called. What have I missed? Instead, I have a ReferenceError: someTestScript is not defined on my Firefox console. I tried to add an empty someTestScript in a JavaScript file but it looks like only the empty one is called, not the o:commandScript.

We're using OmniFaces 2.6 as stated by the documentation.

Any hint/advise is obviously welcomed. Thanks.

Body:
I finally fixed it! For those who are interested in the solving, and note for myself later:

1) How to dynamically change sub channel

Option 1: Change the o:socket scope to view so that the HTTP session scope is wider than the socket scope.

<o:socket channel="myChannel" scope="view"
          connected="#{myManager.subChannel ne null}"
          user="#{myManager.subChannel}"
          onmessage="someTestScript" onopen="onOpen" onclose="onClose"/>

When exiting the socket, the socket will properly closes and re-open with the correct subChannel value. For some reasons, it seems than having a "subChannel" as a String works better than Long.

Option 2: Use a "sub channel map". Actually, I haven't stated in my problem than multiple users can connect to the same sub channel. Another option is to have all users connected via their userId <o:socket channel="myChannel" user="#{user.id}" session="scope" /*default value anyway*/ {...}/>

Then, instead of sending to a subchannel, I send to a collection of user id:

Map<String, Set<String>> subChannelUserMap = new HashMap<>();
// ...
public void onUserConnect(User user, String subChannel){
    subChannelUserMap.get(subChannel).add(user.getId());
}
// ....
public void sendMessage(Map<K, V> input, String subChannel){
    socket.send(input, subChannelUserMap.get(subChannel));
}

2) Call backing bean methods from JavaScript

As stated in my self-comment, I misunderstood <o:commandScript> usage. Let's consider the backing bean method:

// ...
public class BackingBean{
    public void test(){
        String aaa = Faces.getRequestParameter("aaa", String.class);
        String bbb = Faces.getRequestParameter("aSillyName", String.class);
        LOGGER.debug("aaa={}, bbb={}", aaa, bbb);
    }
}

with the socket written as <o:socket /*...*/ onmessage=onMessage />, I'll have:

JSF Page:

 <o:commandScript name="aSillyFunctionName" render="..."
                  actionListener="#{backingBean.test}" ... />

JavaScript file:

 function onMessage(message, channel, event){
     aSillyFunctionName({aaa: message.aaa, aSillyName: bbb});
 }

And here I'm done.