问:
Yii 2 signup does not save records
In first, sorry for my bad English, I am little bit tried...
My problem is that, when iI want to create a new user everything goes well, but ActiveRecord does not save my new account.

This is my first question.. don't realy know what to paste in here... But:

Here is My signup view:

```<code><?php

/* @var $this yii\web\View */
/* @var $form yii\bootstrap\ActiveForm */
/* @var $model \frontend\models\SignupForm */

use yii\helpers\Html;
use yii\bootstrap\ActiveForm;

$this->title = 'Signup';
$this->params['breadcrumbs'][] = $this->title;
?>

<div class="site-signup">
    <h1><?= Html::encode($this->title) ?></h1>

    <p>Please fill these forms with the correct informations:</p>

    <div class="row">
        <div class="col-lg-5">
            <?php $form = ActiveForm::begin(['id' => 'form-signup']); ?>

               <?= $form->field($model, 'firstname')->textInput() ?>
               <?= $form->field($model, 'lastname')->textInput() ?>
               <?= $form->field($model, 'email')->textInput(['autofocus' => true]) ?>
               <?= $form->field($model, 'username')->textInput() ?>

               <?= $form->field($model, 'password')->passwordInput() ?>

                <div class="form-group">
                    <?= Html::submitButton('Signup', ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?>
                </div>

            <?php ActiveForm::end(); ?>
        </div>
    </div>
</div>
</code>```

Here is the signupForm model:

```<code><?php
namespace frontend\models;

use yii\base\Model;
use common\models\User;

/**
 * Signup form
 */
class SignupForm extends Model
{
    public $username;
    public $firstname;
    public $lastname;
    public $email;
    public $password;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [

            ['firstname', 'required', 'message'=>'You need to fill this'],
            ['firstname','string', 'min'=> 1, 'max'=>30],
            ['lastname', 'required', 'message'=>'You need to fill this'],
            ['lastname','string', 'min'=> 1, 'max'=>30],

            ['username', 'trim'],
            ['username', 'required'],
            ['username', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This username has already been taken.'],
            ['username', 'string', 'min' => 2, 'max' => 255],

            ['email', 'trim'],
            ['email', 'required'],
            ['email', 'email'],
            ['email', 'string', 'max' => 255],
            ['email', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This email address has already been taken.'],

            ['password', 'required'],
            ['password', 'string', 'min' => 6],
        ];
    }

    /**
     * Signs user up.
     *
     * @return User|null the saved model or null if saving fails
     */
    public function signup()
    {
        if (!$this->validate()) {

        $user = new User();
        $user->firstname = $this->firstname;
        $user->lastname = $this->lastname;
        $user->username = $this->username;
        $user->email = $this->email;
        $user->setPassword($this->password);
        $user->generateAuthKey();
        $user->save();
        return $user;
    }
        return null;
    }

    public function sendEmail(){
        $user = User::findOne([
        'status_id' => User::STATUS_ACTIVE,
        'email' => $this->email,
        ]);
        if ($user) {
        $user->generatePasswordResetToken();
        if ($user->save()) {
        return Yii::$app->mailer->compose('passwordResetToken',
        ['user' => $user])
        ->setFrom([\Yii::$app->params['supportEmail'] => Yii::$app->name . ' robot'])
        ->setTo($this->email)
        ->setSubject('Password reset for ' . Yii::$app->name)
        ->send();
            }
        }
    return false;

    }
}
</code>```

And the controller:

```<code><?php
namespace frontend\controllers;

use Yii;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;
/**
 * Site controller
 */
class SiteController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout', 'signup'],
                'rules' => [
                    [
                        'actions' => ['signup'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public function actionIndex()
    {
        return $this->render('index');
        $name = Yii::$app->user->identity->username;
        return $this->render('index',['name' => $name]);
    }

    /**
     * Logs in a user.
     *
     * @return mixed
     */
    public function actionLogin()
    {
        $this->layout ='login';
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->redirect('?r=site%2Fhome');;
        } else {
            return $this->render('login', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Logs out the current user.
     *
     * @return mixed
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }

    /**
     * Displays contact page.
     *
     * @return mixed
     */
    public function actionContact()
    {
        $model = new ContactForm();

        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail(Yii::$app->params['adminEmail']))
            {
                Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
            } else {
                Yii::$app->session->setFlash('error', 'There was an error sending your message.');
            }

            return $this->refresh();
        } else {
            return $this->render('contact', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Displays about page.
     *
     * @return mixed
     */
    public function actionAbout()
    {
        return $this->render('about');
    }

    /**
     * Signs user up.
     *
     * @return mixed
     */
    public function actionSignup(){
        $model = new SignupForm();
            if ($model->load(Yii::$app->request->post())) {
                if ($user = $model->signup()) {
                    if (Yii::$app->getUser()->login($user)) {
                        return $this->goHome();
                    }
                }
            }
        return $this->render('signup', ['model' => $model,]);
    }

    /**
     * Requests password reset.
     *
     * @return mixed
     */
    public function actionRequestPasswordReset()
    {
        $model = new PasswordResetRequestForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail()) {
                Yii::$app->session->setFlash('success', 'Check your email for further instructions.');

                return $this->goHome();
            } else {
                Yii::$app->session->setFlash('error', 'Sorry, we are unable to reset password for the provided email address.');
            }
        }

        return $this->render('requestPasswordResetToken', [
            'model' => $model,
        ]);
    }

    /**
     * Resets password.
     *
     * @param string $token
     * @return mixed
     * @throws BadRequestHttpException
     */
    public function actionResetPassword($token)
    {
        try {
            $model = new ResetPasswordForm($token);
        } catch (InvalidParamException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }

        if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
            Yii::$app->session->setFlash('success', 'New password saved.');

            return $this->goHome();
        }

        return $this->render('resetPassword', [
            'model' => $model,
        ]);
    }
}
</code>```

And if you don't mind i have one more question...
How can I make and index page like this? ... I can't call anything into the index file.

https://imgur.com/kkEJT3Q

I created something what i want to saw.

And somebody can link an explanition how to make " list " page for every registred user?

Thank you very much guys..
I know it's pretty much, but I am tilted.

答:
Like @nicolascolman said in the comment up first change

```<code>public function signup()
{
    if (!$this->validate()) {
...
</code>```

to

```<code>public function signup()
{
    if ($this->validate()) {
...
</code>```

How to make "list" page for every registered user

For manage creation of user and assign roles or privilages I recommend you to try this extension module: mdmsoft/yii2-admin

Here you can find a simply guide for install and configure it:

Yii 2.0: Installation guide: Yii-2 advanced template with RBAC system

Title: Yii 2 signup does not save records

Body:
In first, sorry for my bad English, I am little bit tried...
My problem is that, when iI want to create a new user everything goes well, but ActiveRecord does not save my new account.

This is my first question.. don't realy know what to paste in here... But:

Here is My signup view:

<?php

/* @var $this yii\web\View */
/* @var $form yii\bootstrap\ActiveForm */
/* @var $model \frontend\models\SignupForm */

use yii\helpers\Html;
use yii\bootstrap\ActiveForm;

$this->title = 'Signup';
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

Please fill these forms with the correct informations:

            <?php $form = ActiveForm::begin(['id' => 'form-signup']); ?>

               <?= $form->field($model, 'firstname')->textInput() ?>
               <?= $form->field($model, 'lastname')->textInput() ?>
               <?= $form->field($model, 'email')->textInput(['autofocus' => true]) ?>
               <?= $form->field($model, 'username')->textInput() ?>

               <?= $form->field($model, 'password')->passwordInput() ?>

                    <?= Html::submitButton('Signup', ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?>

            <?php ActiveForm::end(); ?>

Here is the signupForm model:

<?php
namespace frontend\models;

use yii\base\Model;
use common\models\User;

/**
 * Signup form
 */
class SignupForm extends Model
{
    public $username;
    public $firstname;
    public $lastname;
    public $email;
    public $password;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [

            ['firstname', 'required', 'message'=>'You need to fill this'],
            ['firstname','string', 'min'=> 1, 'max'=>30],
            ['lastname', 'required', 'message'=>'You need to fill this'],
            ['lastname','string', 'min'=> 1, 'max'=>30],

            ['username', 'trim'],
            ['username', 'required'],
            ['username', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This username has already been taken.'],
            ['username', 'string', 'min' => 2, 'max' => 255],

            ['email', 'trim'],
            ['email', 'required'],
            ['email', 'email'],
            ['email', 'string', 'max' => 255],
            ['email', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This email address has already been taken.'],

            ['password', 'required'],
            ['password', 'string', 'min' => 6],
        ];
    }

    /**
     * Signs user up.
     *
     * @return User|null the saved model or null if saving fails
     */
    public function signup()
    {
        if (!$this->validate()) {

        $user = new User();
        $user->firstname = $this->firstname;
        $user->lastname = $this->lastname;
        $user->username = $this->username;
        $user->email = $this->email;
        $user->setPassword($this->password);
        $user->generateAuthKey();
        $user->save();
        return $user;
    }
        return null;
    }

    public function sendEmail(){
        $user = User::findOne([
        'status_id' => User::STATUS_ACTIVE,
        'email' => $this->email,
        ]);
        if ($user) {
        $user->generatePasswordResetToken();
        if ($user->save()) {
        return Yii::$app->mailer->compose('passwordResetToken',
        ['user' => $user])
        ->setFrom([\Yii::$app->params['supportEmail'] => Yii::$app->name . ' robot'])
        ->setTo($this->email)
        ->setSubject('Password reset for ' . Yii::$app->name)
        ->send();
            }
        }
    return false;

    }
}

And the controller:

<?php
namespace frontend\controllers;

use Yii;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;
/**
 * Site controller
 */
class SiteController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout', 'signup'],
                'rules' => [
                    [
                        'actions' => ['signup'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public function actionIndex()
    {
        return $this->render('index');
        $name = Yii::$app->user->identity->username;
        return $this->render('index',['name' => $name]);
    }

    /**
     * Logs in a user.
     *
     * @return mixed
     */
    public function actionLogin()
    {
        $this->layout ='login';
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->redirect('?r=site%2Fhome');;
        } else {
            return $this->render('login', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Logs out the current user.
     *
     * @return mixed
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }

    /**
     * Displays contact page.
     *
     * @return mixed
     */
    public function actionContact()
    {
        $model = new ContactForm();

        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail(Yii::$app->params['adminEmail']))
            {
                Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
            } else {
                Yii::$app->session->setFlash('error', 'There was an error sending your message.');
            }

            return $this->refresh();
        } else {
            return $this->render('contact', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Displays about page.
     *
     * @return mixed
     */
    public function actionAbout()
    {
        return $this->render('about');
    }

    /**
     * Signs user up.
     *
     * @return mixed
     */
    public function actionSignup(){
        $model = new SignupForm();
            if ($model->load(Yii::$app->request->post())) {
                if ($user = $model->signup()) {
                    if (Yii::$app->getUser()->login($user)) {
                        return $this->goHome();
                    }
                }
            }
        return $this->render('signup', ['model' => $model,]);
    }

    /**
     * Requests password reset.
     *
     * @return mixed
     */
    public function actionRequestPasswordReset()
    {
        $model = new PasswordResetRequestForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail()) {
                Yii::$app->session->setFlash('success', 'Check your email for further instructions.');

                return $this->goHome();
            } else {
                Yii::$app->session->setFlash('error', 'Sorry, we are unable to reset password for the provided email address.');
            }
        }

        return $this->render('requestPasswordResetToken', [
            'model' => $model,
        ]);
    }

    /**
     * Resets password.
     *
     * @param string $token
     * @return mixed
     * @throws BadRequestHttpException
     */
    public function actionResetPassword($token)
    {
        try {
            $model = new ResetPasswordForm($token);
        } catch (InvalidParamException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }

        if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
            Yii::$app->session->setFlash('success', 'New password saved.');

            return $this->goHome();
        }

        return $this->render('resetPassword', [
            'model' => $model,
        ]);
    }
}

And if you don't mind i have one more question...
How can I make and index page like this? ... I can't call anything into the index file.

https://imgur.com/kkEJT3Q

I created something what i want to saw.

And somebody can link an explanition how to make " list " page for every registred user?

Thank you very much guys..
I know it's pretty much, but I am tilted.

Body:
Like @nicolascolman said in the comment up first change

public function signup()
{
    if (!$this->validate()) {
...

to

public function signup()
{
    if ($this->validate()) {
...

How to make "list" page for every registered user

For manage creation of user and assign roles or privilages I recommend you to try this extension module: mdmsoft/yii2-admin

Here you can find a simply guide for install and configure it:

Yii 2.0: Installation guide: Yii-2 advanced template with RBAC system


来源: stackexchange

问:
Android Studio DDMS can't open /data folder in an emulator phone
I recently created an Emulator device with Android Studio，but only to find that I can't open the /data/data folder to get the sqlite db file.The folder just can't open,I have tried to use shell scirpt to chmod the /data directory,but it says the su command not found.

The Emulator

Can't open!

Is there anyone has the same problem? Or I have to root the Emulator?
But it's an Emulator! I just think it's kind of inconvenient to root a Emulator!

答:
Update

Can't remember whether it's from Android Studio 3.0 or later but if you have downloaded AS 3.3+, you'll find the tab on bottom right corner called Device File Explorer, which lets you to see and easily get the data of your app without rooting.

Opening as Administrator didn't help but rooting the phone did worked, and no I'm not lowering my SDK version.

Open cmd and go to C:\Users\{User}\AppData\Local\Android\Sdk\platform-tools or to the folder location and type cmd at the address bar.

Whether you're super user or not can be determined by $:

```<code>C:\{User}\...\platform-tools>adb shell
generic_x86:/ $ exit
</code>```

To have su/root privileges type adb root and exit:

```<code>C:\{User}\...\platform-tools>adb root
generic_x86:/ # exit
</code>```

Next run the Android Device Monitor to extract the data.

To turn off root type adb unroot.

ContentLicense: CC BY-SA 3.0

Body:
Update

Can't remember whether it's from Android Studio 3.0 or later but if you have downloaded AS 3.3+, you'll find the tab on bottom right corner called Device File Explorer, which lets you to see and easily get the data of your app without rooting.

Opening as Administrator didn't help but rooting the phone did worked, and no I'm not lowering my SDK version.

Open cmd and go to C:\Users\{User}\AppData\Local\Android\Sdk\platform-tools or to the folder location and type cmd at the address bar.

Whether you're super user or not can be determined by $:

C:\{User}\...\platform-tools>adb shell
generic_x86:/ $ exit

To have su/root privileges type adb root and exit:

C:\{User}\...\platform-tools>adb root
generic_x86:/ # exit

Next run the Android Device Monitor to extract the data.

To turn off root type adb unroot.

ContentLicense: CC BY-SA 4.0


问:
boost asio SSL server error: called a function you should not call
I am using the example from boost with three minor differences:

I use threads to process io_service

I have limited the protocol to > TLS v1.1

There is no password callback, because the cert key has no password

The threads simply process various connections in parallel

```<code>void server::start()
{
    for (std::size_t i = 0; i < thread_pool_size_; i++) {
        threads_.push_back(std::thread([&]() {
            io_service_.run();
        }));
    }
    for (auto & t : threads_) {
        t.join();
    }
}
</code>```

The context arguments are:

```<code>ctx.set_options(boost::asio::ssl::context::default_workarounds
               |boost::asio::ssl::context::no_sslv2
               |boost::asio::ssl::context::no_sslv3
               |boost::asio::ssl::context::no_tlsv1
               |boost::asio::ssl::context::no_tlsv1_1
               |boost::asio::ssl::context::single_dh_use);
</code>```

Apart from that, a connection class controls internally a ssl_socket,
which follows the following callback chain:

ctor
  -> start
    -> async_handshake
      -> read_header
        -> async_read_until
          -> process_header
            ...

If I replace the SSL socket with a plaintext socket ip::tcp::socket then everything works fine.
When using the SSL socket, I keep getting called a function you should not call.

GDB shows that this originates from async_handshake. After reading this SO post I managed to obtain the error code:

(20,197,66) error:140C5042:SSL routines:ssl_undefined_function:called a function you should not call.

I'm using Boost 1.58 on Ubuntu 16.04.
Any help as to why this is happening, what might be causing it, or what I could possibly have done wrong?

If it matters, I am testing with curl using the -insecure flag.

EDIT

Did try without the restrictive protocol flags, and by setting a password callback - problem still persists.

答:
Seems that the following line triggers the problem:

```<code>context_(io_service, boost::asio::ssl::context::tlsv12_client)
</code>```

I should have paid more attention to my code (copy-paste is the root of all evil):
The offending line was in the context constructor:

```<code>ctx_(io_service, boost::asio::ssl::context::tlsv12_client)
</code>```

I've replaced with the server version:

```<code>context_(io_service, boost::asio::ssl::context::tlsv12_server)
</code>```

The full list is hidden in the implementation header of boost.
Insert big facepalm here :-)

Body:
I am using the example from boost with three minor differences:

I use threads to process io_service

I have limited the protocol to > TLS v1.1

There is no password callback, because the cert key has no password

The threads simply process various connections in parallel

void server::start()
{
    for (std::size_t i = 0; i < thread_pool_size_; i++) {
        threads_.push_back(std::thread([&]() {
            io_service_.run();
        }));
    }
    for (auto & t : threads_) {
        t.join();
    }
}

The context arguments are:

ctx.set_options(boost::asio::ssl::context::default_workarounds
               |boost::asio::ssl::context::no_sslv2
               |boost::asio::ssl::context::no_sslv3
               |boost::asio::ssl::context::no_tlsv1
               |boost::asio::ssl::context::no_tlsv1_1
               |boost::asio::ssl::context::single_dh_use);

Apart from that, a connection class controls internally a ssl_socket,
which follows the following callback chain:

ctor
  -> start
    -> async_handshake
      -> read_header
        -> async_read_until
          -> process_header
            ...

If I replace the SSL socket with a plaintext socket ip::tcp::socket then everything works fine.
When using the SSL socket, I keep getting called a function you should not call.

GDB shows that this originates from async_handshake. After reading this SO post I managed to obtain the error code:

(20,197,66) error:140C5042:SSL routines:ssl_undefined_function:called a function you should not call.

I'm using Boost 1.58 on Ubuntu 16.04.
Any help as to why this is happening, what might be causing it, or what I could possibly have done wrong?

If it matters, I am testing with curl using the -insecure flag.

EDIT

Did try without the restrictive protocol flags, and by setting a password callback - problem still persists.

Body:
Seems that the following line triggers the problem:

context_(io_service, boost::asio::ssl::context::tlsv12_client)

I should have paid more attention to my code (copy-paste is the root of all evil):
The offending line was in the context constructor:

ctx_(io_service, boost::asio::ssl::context::tlsv12_client)

I've replaced with the server version:

context_(io_service, boost::asio::ssl::context::tlsv12_server)

The full list is hidden in the implementation header of boost.
Insert big facepalm here :-)


问:
Storing encrypted datas in DB viewable by app in any time, but not by me (admin)
I need to store in my Database some datas that should only be read by the owner (specific user) or by my application (some background batchs).
But, those datas are highly sensitive, and I, the developper, don't even want to be able to retrieve it.
So :

I can't just encrypt datas with a secret key kept in the server, because I would personally have access to it, so if I wanted, I could retrieve the entire datas.

I can't encrypt with user password because my app need to have access to it without the user puting his password each time.

What can I do to solve this?

答:
If you want to let the user encrypt something in such a way that only he can decrypt it, then you need a key to do this.

You could use the users password to do this, or you could use something else (a separate encryption key).

Now as for the password, you should not have access to that anyway; if you need the app to have access, then you should provide it with an access token of some sort, which will let the user get the access he needs without keeping the password in clear text. Entering the password should then only be necessary when the token is no longer valid (either due to timeout, manual cancellation / logout, or due to some kind of irregular event that might trigger a cancellation for security reasons).

Under a regime like this, where you don't need the password, your reason for not using the password as the encryption key falls away.

Note that no matter what you use as a key here, there will always be a question of trust here so long as you are doing the encryption on the server side; if you need your user to provide a key to encrypt / decrypt on your server, then what guarantees do they have that you will not simply steal that key and read their data anyway - or easier yet, simply not really encrypt it at all?

I realize that this solution is an improvement compared to using a single server-side secret key, since you will now have separate keys for each user, and keys that are not stored on the server (great in case someone is able to get unauthorized access to your DB), but an even better solution if possible, would be to let your users encrypt data on the client side. That way your server side logic would only ever see the encrypted data, and never even have to deal with either encryption logic or keys or any of that.


问:
duplicate record on sql left join
When I use this sql query, There is no duplicate shops.id:

```<code>SELECT *
FROM   shops
LEFT JOIN expiration
       ON shops.id = expiration.shopid
ORDER  BY shops.id
</code>```

But when I use this one (with where statement)  there are many duplicate shops.id:

```<code>SELECT *
FROM   shops
LEFT JOIN expiration
       ON shops.id = expiration.shopid
WHERE  shops.ref = 9
ORDER  BY shops.id
</code>```

Why left join returns duplicate rows and how adding where cause this?

答:
You Can try Select Distinct

```<code>SELECT DISTINCT *
FROM   shops
LEFT JOIN expiration
       ON shops.id = expiration.shopid
WHERE  shops.ref = 9
ORDER  BY shops.id
</code>```

Its difficult without the data. but that might help.

Another option might be to include left outer join as well:

```<code>  SELECT DISTINCT *
    FROM   shops
    LEFT OUTER JOIN expiration
           ON shops.id = expiration.shopid
    WHERE  shops.ref = 9
    ORDER  BY shops.id
</code>```

Hope it helps.

Title: duplicate record on sql left join

Body:
When I use this sql query, There is no duplicate shops.id:

SELECT *
FROM   shops
LEFT JOIN expiration
       ON shops.id = expiration.shopid
ORDER  BY shops.id

But when I use this one (with where statement)  there are many duplicate shops.id:

SELECT *
FROM   shops
LEFT JOIN expiration
       ON shops.id = expiration.shopid
WHERE  shops.ref = 9
ORDER  BY shops.id

Why left join returns duplicate rows and how adding where cause this?

Body:
You Can try Select Distinct

SELECT DISTINCT *
FROM   shops
LEFT JOIN expiration
       ON shops.id = expiration.shopid
WHERE  shops.ref = 9
ORDER  BY shops.id

Its difficult without the data. but that might help.

Another option might be to include left outer join as well:

  SELECT DISTINCT *
    FROM   shops
    LEFT OUTER JOIN expiration
           ON shops.id = expiration.shopid
    WHERE  shops.ref = 9
    ORDER  BY shops.id

Hope it helps.


问:
Github/Cygwin error: cygheap base mismatch detected
Git has been giving me this error

```<code>    0 [main] sh (47116) C:\Users\Marcus\AppData\Local\GitHub\PortableGit_c7e0cbde92ba565cb218a521411d0e854079a28c\usr\bin\sh.exe: *** fatal error - cygheap base mismatch detected - 0x11C7400/0x1297400.
This problem is probably due to using incompatible versions of the cygwin DLL.
Search for cygwin1.dll using the Windows Start->Find/Search facility
and delete all but the most recent version.  The most recent version *should*
reside in x:\cygwin\bin, where 'x' is the drive on which you have
installed the cygwin distribution.  Rebooting is also suggested if you
are unable to find another cygwin DLL.
    0 [main] sh 42052 fork: child -1 - forked process 47116 died unexpectedly, retry 0, exit code 0xC0000142, errno 11
/mingw32/libexec/git-core/git-sh-setup: fork: retry: No child processes
This problem is probably due to using incompatible versions of the cygwin DLL.
Search for cygwin1.dll using the Windows Start->Find/Search facility
and delete all but the most recent version.  The most recent version *should*
reside in x:\cygwin\bin, where 'x' is the drive on which you have
installed the cygwin distribution.  Rebooting is also suggested if you
are unable to find another cygwin DLL.
    0 [main] sh 42052 fork: child -1 - forked process 47116 died unexpectedly, retry 0, exit code 0xC0000142, errno 11
/mingw32/libexec/git-core/git-sh-setup: fork: retry: No child processes
</code>```

Things I've tried include:

deleting cygwin from C:\cygwin and C:\cygwin64 and reinstalling

reinstalling github using the uninstaller and installer.

uninstalling github and manually removing its local and roaming appdata folders, and reinstalling.

rebooting the computer

rebasing C:\cygwin, it succeeded, but didnt fix any issues.

rebasing %appdata%\Local\Github\PortableGit_c7e...\. it returned the original error again.

for reference, I'm running windows 10 64 bit. The only other question I could find that pin pointed the error I'm getting never reached a solution: link here

I'm not sure where else to go aside from just reinstalling windows altogether, any help would be greatly appreciated.

答:
I had a very similar problem, but neither restarts nor reinstalling git or cygwin helped. I always got:

```<code>      1 [main] sh (12220) C:\Program Files\Git\usr\bin\sh.exe: *** fatal error - cygheap base mismatch detected - 0x37C7408/0x38E7408.
This problem is probably due to using incompatible versions of the cygwin DLL.
Search for cygwin1.dll using the Windows Start->Find/Search facility
and delete all but the most recent version.  The most recent version *should*
reside in x:\cygwin\bin, where 'x' is the drive on which you have
installed the cygwin distribution.  Rebooting is also suggested if you
are unable to find another cygwin DLL.
      0 [main] sh 6928 fork: child -1 - forked process 12220 died unexpectedly, retry 0, exit code 0xC0000142, errno 11
C:\Program Files\Git\mingw64/libexec/git-core\git-stash: fork: retry: Resource temporarily unavailable
</code>```

Took me a while to figure out that it started after I read about a windows bug related to "System-wide mandatory ASLR", and how the settings available via Windows UI weren't setting the proper registry keys. After making my system more secure by adding this registry entry, cygwin forking broke:

```<code>Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\kernel]
"MitigationOptions"=hex:00,01,01,00,00,00,00,00,00,00,00,00,00,00,00,00
</code>```

Source: Clarifying the behavior of mandatory ASLR

That resulted in git-stash not working anymore, nor cygwin working (which I installed later.
Removing that registry key again fixed the issue.

Body:
Git has been giving me this error

    0 [main] sh (47116) C:\Users\Marcus\AppData\Local\GitHub\PortableGit_c7e0cbde92ba565cb218a521411d0e854079a28c\usr\bin\sh.exe: *** fatal error - cygheap base mismatch detected - 0x11C7400/0x1297400.
This problem is probably due to using incompatible versions of the cygwin DLL.
Search for cygwin1.dll using the Windows Start->Find/Search facility
and delete all but the most recent version.  The most recent version *should*
reside in x:\cygwin\bin, where 'x' is the drive on which you have
installed the cygwin distribution.  Rebooting is also suggested if you
are unable to find another cygwin DLL.
    0 [main] sh 42052 fork: child -1 - forked process 47116 died unexpectedly, retry 0, exit code 0xC0000142, errno 11
/mingw32/libexec/git-core/git-sh-setup: fork: retry: No child processes
This problem is probably due to using incompatible versions of the cygwin DLL.
Search for cygwin1.dll using the Windows Start->Find/Search facility
and delete all but the most recent version.  The most recent version *should*
reside in x:\cygwin\bin, where 'x' is the drive on which you have
installed the cygwin distribution.  Rebooting is also suggested if you
are unable to find another cygwin DLL.
    0 [main] sh 42052 fork: child -1 - forked process 47116 died unexpectedly, retry 0, exit code 0xC0000142, errno 11
/mingw32/libexec/git-core/git-sh-setup: fork: retry: No child processes

Things I've tried include:

deleting cygwin from C:\cygwin and C:\cygwin64 and reinstalling

reinstalling github using the uninstaller and installer.

uninstalling github and manually removing its local and roaming appdata folders, and reinstalling.

rebooting the computer

rebasing C:\cygwin, it succeeded, but didnt fix any issues.

rebasing %appdata%\Local\Github\PortableGit_c7e...\. it returned the original error again.

for reference, I'm running windows 10 64 bit. The only other question I could find that pin pointed the error I'm getting never reached a solution: link here

I'm not sure where else to go aside from just reinstalling windows altogether, any help would be greatly appreciated.

Body:
I had a very similar problem, but neither restarts nor reinstalling git or cygwin helped. I always got:

      1 [main] sh (12220) C:\Program Files\Git\usr\bin\sh.exe: *** fatal error - cygheap base mismatch detected - 0x37C7408/0x38E7408.
This problem is probably due to using incompatible versions of the cygwin DLL.
Search for cygwin1.dll using the Windows Start->Find/Search facility
and delete all but the most recent version.  The most recent version *should*
reside in x:\cygwin\bin, where 'x' is the drive on which you have
installed the cygwin distribution.  Rebooting is also suggested if you
are unable to find another cygwin DLL.
      0 [main] sh 6928 fork: child -1 - forked process 12220 died unexpectedly, retry 0, exit code 0xC0000142, errno 11
C:\Program Files\Git\mingw64/libexec/git-core\git-stash: fork: retry: Resource temporarily unavailable

Took me a while to figure out that it started after I read about a windows bug related to "System-wide mandatory ASLR", and how the settings available via Windows UI weren't setting the proper registry keys. After making my system more secure by adding this registry entry, cygwin forking broke:

Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\kernel]
"MitigationOptions"=hex:00,01,01,00,00,00,00,00,00,00,00,00,00,00,00,00

Source: Clarifying the behavior of mandatory ASLR

That resulted in git-stash not working anymore, nor cygwin working (which I installed later.
Removing that registry key again fixed the issue.


问:
Apply formula across pandas rows/ regression line
I'm trying to apply a formula across the rows of a data frame to get the trend of the numbers in the rows.

The below example works until the part where .apply is used.

```<code>df = pd.DataFrame(np.random.randn(10, 4), columns=list('ABCD'))
axisvalues=list(range(1,len(db.columns)+1))

def calc_slope(row):
    return scipy.stats.linregress(df.iloc[row,:], y=axisvalues)

calc_slope(1) # this works

df["New"]=df.apply(calc_slope,axis=1) # this fails *- "too many values to unpack"*
</code>```

Thank you for any help

Body:
I'm trying to apply a formula across the rows of a data frame to get the trend of the numbers in the rows.

The below example works until the part where .apply is used.

df = pd.DataFrame(np.random.randn(10, 4), columns=list('ABCD'))
axisvalues=list(range(1,len(db.columns)+1))

def calc_slope(row):
    return scipy.stats.linregress(df.iloc[row,:], y=axisvalues)

calc_slope(1) # this works

df["New"]=df.apply(calc_slope,axis=1) # this fails *- "too many values to unpack"*

Thank you for any help

Body:
I think you need for one attribute:

def calc_slope(row):
    a = scipy.stats.linregress(row, y=axisvalues)
    return a.slope

df["slope"]=df.apply(calc_slope,axis=1)
print (df)
          A         B         C         D     slope
0  0.444640  0.024624 -0.016216  0.228935 -2.553465
1  1.226611  1.962481  1.103834  0.645562 -1.455239
2 -0.259415  0.971097  0.124538 -0.704115 -0.718621
3  1.938422  1.787310 -0.619745 -2.560187 -0.575519
4 -0.986231 -1.942930  2.677379 -1.813071  0.075679
5  0.611214 -0.258453  0.053452  1.223544  0.841865
6  0.685435  0.962880 -1.517077 -0.101108 -0.652503
7  0.368278  1.314202  0.748189  2.116189  1.350132
8 -0.322053 -1.135443 -0.161071 -1.836761 -0.987341
9  0.798461  0.461736 -0.665127 -0.247887 -1.610447

And for all atributes convert named tuple to dict and then to Series. Output is new DataFrame, so if is necessaryjoin to original:

np.random.seed(1997)

df = pd.DataFrame(np.random.randn(10, 4), columns=list('ABCD'))
axisvalues=list(range(1,len(df.columns)+1))

def calc_slope(row):
    a = scipy.stats.linregress(row, y=axisvalues)
    return pd.Series(a._asdict())

print (df.apply(calc_slope,axis=1))
      slope  intercept    rvalue    pvalue    stderr
0 -2.553465   2.935355 -0.419126  0.580874  3.911302
1 -1.455239   4.296670 -0.615324  0.384676  1.318236
2 -0.718621   2.523733 -0.395862  0.604138  1.178774
3 -0.575519   2.578530 -0.956682  0.043318  0.123843
4  0.075679   2.539066  0.127254  0.872746  0.417101
5  0.841865   2.156991  0.425333  0.574667  1.266674
6 -0.652503   2.504915 -0.561947  0.438053  0.679154
7  1.350132   0.965285  0.794704  0.205296  0.729193
8 -0.987341   1.647104 -0.593680  0.406320  0.946311
9 -1.610447   2.639780 -0.828856  0.171144  0.768641

df = df.join(df.apply(calc_slope,axis=1))
print (df)
          A         B         C         D     slope  intercept    rvalue  \
0  0.444640  0.024624 -0.016216  0.228935 -2.553465   2.935355 -0.419126
1  1.226611  1.962481  1.103834  0.645562 -1.455239   4.296670 -0.615324
2 -0.259415  0.971097  0.124538 -0.704115 -0.718621   2.523733 -0.395862
3  1.938422  1.787310 -0.619745 -2.560187 -0.575519   2.578530 -0.956682
4 -0.986231 -1.942930  2.677379 -1.813071  0.075679   2.539066  0.127254
5  0.611214 -0.258453  0.053452  1.223544  0.841865   2.156991  0.425333
6  0.685435  0.962880 -1.517077 -0.101108 -0.652503   2.504915 -0.561947
7  0.368278  1.314202  0.748189  2.116189  1.350132   0.965285  0.794704
8 -0.322053 -1.135443 -0.161071 -1.836761 -0.987341   1.647104 -0.593680
9  0.798461  0.461736 -0.665127 -0.247887 -1.610447   2.639780 -0.828856

     pvalue    stderr
0  0.580874  3.911302
1  0.384676  1.318236
2  0.604138  1.178774
3  0.043318  0.123843
4  0.872746  0.417101
5  0.574667  1.266674
6  0.438053  0.679154
7  0.205296  0.729193
8  0.406320  0.946311
9  0.171144  0.768641


问:
Android WebView not loading an HTTPS URL
```<code>public void onCreate(Bundle savedInstance)
{
    super.onCreate(savedInstance);
    setContentView(R.layout.show_voucher);
    webView=(WebView)findViewById(R.id.webview);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setBuiltInZoomControls(true);
    String url ="https://www.paymeon.com/Vouchers/?v=%C80%8D%B1x%D9%CFqh%FA%84%C35%0A%1F%CE&iv=%25%EE%BEi%F4%DAT%E1"
    //webView.loadUrl(url); // Not Working... Showing blank
    webView.loadUrl("http://www.yahoo.com"); // its working
}
</code>```

When I try to load a URL in the WebBView it only shows a blank screen. If I load Google.com or yahoo.com it's working fine.

答:
To solve Google security, do this:

Lines to the top:

```<code>import android.webkit.SslErrorHandler;
import android.net.http.SslError;
</code>```

Code:

```<code>class SSLTolerentWebViewClient extends WebViewClient {
    @Override
    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
        if (error.toString() == "piglet")
            handler.cancel();
        else
            handler.proceed(); // Ignore SSL certificate errors
    }
}
</code>```

Body:
public void onCreate(Bundle savedInstance)
{
    super.onCreate(savedInstance);
    setContentView(R.layout.show_voucher);
    webView=(WebView)findViewById(R.id.webview);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setBuiltInZoomControls(true);
    String url ="https://www.paymeon.com/Vouchers/?v=%C80%8D%B1x%D9%CFqh%FA%84%C35%0A%1F%CE&iv=%25%EE%BEi%F4%DAT%E1"
    //webView.loadUrl(url); // Not Working... Showing blank
    webView.loadUrl("http://www.yahoo.com"); // its working
}

When I try to load a URL in the WebBView it only shows a blank screen. If I load Google.com or yahoo.com it's working fine.

Body:
To solve Google security, do this:

Lines to the top:

import android.webkit.SslErrorHandler;
import android.net.http.SslError;

Code:

class SSLTolerentWebViewClient extends WebViewClient {
    @Override
    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
        if (error.toString() == "piglet")
            handler.cancel();
        else
            handler.proceed(); // Ignore SSL certificate errors
    }
}


问:
many selectize inputs in RShiny connected with each other
I'm quite a beginner in R Shiny and I would like to create many multiple selectize inputs which are connected with each other. In other words : if an item is selected in one of the selectizeinputs i would like that it disappears from the other selectizeinputs' choices.

Below is an example of what i want (does not work)

```<code> modalities <- LETTERS[1:10]

 library(shiny)

 app <- shinyApp(
   ui = tabPanel("Change modalities",
            selectizeInput("ui_mod_choose1", label=paste0("Modality 1"),choices=NULL, multiple = TRUE),
            selectizeInput("ui_mod_choose2", label=paste0("Modality 2"),choices=NULL, multiple = TRUE),
            selectizeInput("ui_mod_choose3", label=paste0("Modality 3"),choices=NULL, multiple = TRUE)
   ),

 server = function(input, output, session) {
   observe({
updateSelectizeInput(session,"ui_mod_choose1",choices=  modalities)
updateSelectizeInput(session,"ui_mod_choose2",choices=  modalities)
updateSelectizeInput(session,"ui_mod_choose3",choices=  modalities)
   })
 }

      )
 runApp(app)
</code>```

EDIT : Here is a solution based on Bertil Nestorius' answer

```<code> modalities <- LETTERS[1:10]

 library(shiny)

 app <- shinyApp(
   ui = tabPanel("Change modalities",
            numericInput("ui_number", label="Number of modalities",min = 1, max = 4, value=3),
            uiOutput("renderui")
   ),

   server = function(input, output, session) {

     output$renderui <- renderUI({
       output = tagList()
       for(i in 1:input$ui_number){
         output[[i]] = tagList()
         output[[i]][[1]] = selectizeInput(paste0("ui_mod_choose",i), label=paste0("Modality ",i),choices=modalities, multiple = TRUE)
  }
  return(output)
})

 lapply(
  X = 1:100, ####### QUESTION HERE
  FUN = function(j){
    observeEvent({
      input[[paste0("ui_mod_choose",j)]]
    },
    {
      sapply(1:input$ui_number,function(i){
        vecteur <- do.call(c,lapply((1:input$ui_number)[-i],function(i){input[[paste0("ui_mod_choose",i)]]}))
        updateSelectizeInput(session,paste0("ui_mod_choose",i),choices=  modalities[!modalities %in% vecteur],selected = input[[paste0("ui_mod_choose",i)]])
      })
    },
    ignoreNULL = FALSE)

  }
)

observeEvent({
  input$ui_num
},
{
  sapply(1:nput$ui_num,function(i){
    updateSelectizeInput(session,paste0("ui_mod_choose",i),choice= modalities,selected=NULL)
       })
     }
     )

   }

 )
 runApp(app)
</code>```

The only problem I have left is on the following line  :

```<code>  X = 1:100, ####### QUESTION HERE
</code>```

See this issue for more information : lapply function using a numericInput parameter around an observeEvent in RShiny

答:
Something like this?</p>

```<code>rm(list = ls())
library(shiny)
modalities <- LETTERS[1:10]

app <- shinyApp(
  ui = tabPanel("Change modalities",
                selectizeInput("ui_mod_choose1", label=paste0("Modality 1"),choices= modalities, multiple = TRUE),
                selectizeInput("ui_mod_choose2", label=paste0("Modality 2"),choices=NULL, multiple = TRUE),
                selectizeInput("ui_mod_choose3", label=paste0("Modality 3"),choices=NULL, multiple = TRUE)
  ),

  server = function(input, output, session) {

    observe({
      updateSelectizeInput(session,"ui_mod_choose2",choices =  modalities[!modalities%in% input$ui_mod_choose1])
    })
    observe({
      updateSelectizeInput(session,"ui_mod_choose3",choices =  modalities[!modalities %in% c(input$ui_mod_choose1,input$ui_mod_choose2)])
    })
  }
)
runApp(app)
</code>```

Body:
I'm quite a beginner in R Shiny and I would like to create many multiple selectize inputs which are connected with each other. In other words : if an item is selected in one of the selectizeinputs i would like that it disappears from the other selectizeinputs' choices.

Below is an example of what i want (does not work)

 modalities <- LETTERS[1:10]

 library(shiny)

 app <- shinyApp(
   ui = tabPanel("Change modalities",
            selectizeInput("ui_mod_choose1", label=paste0("Modality 1"),choices=NULL, multiple = TRUE),
            selectizeInput("ui_mod_choose2", label=paste0("Modality 2"),choices=NULL, multiple = TRUE),
            selectizeInput("ui_mod_choose3", label=paste0("Modality 3"),choices=NULL, multiple = TRUE)
   ),

 server = function(input, output, session) {
   observe({
updateSelectizeInput(session,"ui_mod_choose1",choices=  modalities)
updateSelectizeInput(session,"ui_mod_choose2",choices=  modalities)
updateSelectizeInput(session,"ui_mod_choose3",choices=  modalities)
   })
 }

      )
 runApp(app)

EDIT : Here is a solution based on Bertil Nestorius' answer

 modalities <- LETTERS[1:10]

 library(shiny)

 app <- shinyApp(
   ui = tabPanel("Change modalities",
            numericInput("ui_number", label="Number of modalities",min = 1, max = 4, value=3),
            uiOutput("renderui")
   ),

   server = function(input, output, session) {

     output$renderui <- renderUI({
       output = tagList()
       for(i in 1:input$ui_number){
         output[[i]] = tagList()
         output[[i]][[1]] = selectizeInput(paste0("ui_mod_choose",i), label=paste0("Modality ",i),choices=modalities, multiple = TRUE)
  }
  return(output)
})

 lapply(
  X = 1:100, ####### QUESTION HERE
  FUN = function(j){
    observeEvent({
      input[[paste0("ui_mod_choose",j)]]
    },
    {
      sapply(1:input$ui_number,function(i){
        vecteur <- do.call(c,lapply((1:input$ui_number)[-i],function(i){input[[paste0("ui_mod_choose",i)]]}))
        updateSelectizeInput(session,paste0("ui_mod_choose",i),choices=  modalities[!modalities %in% vecteur],selected = input[[paste0("ui_mod_choose",i)]])
      })
    },
    ignoreNULL = FALSE)

  }
)

observeEvent({
  input$ui_num
},
{
  sapply(1:nput$ui_num,function(i){
    updateSelectizeInput(session,paste0("ui_mod_choose",i),choice= modalities,selected=NULL)
       })
     }
     )

   }

 )
 runApp(app)

The only problem I have left is on the following line  :

  X = 1:100, ####### QUESTION HERE

See this issue for more information : lapply function using a numericInput parameter around an observeEvent in RShiny

Body:
Something like this?

rm(list = ls())
library(shiny)
modalities <- LETTERS[1:10]

app <- shinyApp(
  ui = tabPanel("Change modalities",
                selectizeInput("ui_mod_choose1", label=paste0("Modality 1"),choices= modalities, multiple = TRUE),
                selectizeInput("ui_mod_choose2", label=paste0("Modality 2"),choices=NULL, multiple = TRUE),
                selectizeInput("ui_mod_choose3", label=paste0("Modality 3"),choices=NULL, multiple = TRUE)
  ),

  server = function(input, output, session) {

    observe({
      updateSelectizeInput(session,"ui_mod_choose2",choices =  modalities[!modalities%in% input$ui_mod_choose1])
    })
    observe({
      updateSelectizeInput(session,"ui_mod_choose3",choices =  modalities[!modalities %in% c(input$ui_mod_choose1,input$ui_mod_choose2)])
    })
  }
)
runApp(app)


问:
Waiting in a redux-saga
I want to introduce a delay in a saga (using redux-saga).

How can I do this?

If redux-saga provides an API, I would also be interested in how to achieve it manually.

```<code>function* save({ payload }) {
    yield put(pending());
    // I want to simply wait (non-blocking) here for say 2 seconds
    yield put(complete());
}
</code>```

答:
Redux-sagas has a special effect for this:

delay(ms, [val])

Returns a Promise that will resolve after ms milliseconds with val.

Example:

```<code>import { delay, call } from 'redux-saga/effects'

function* someSaga(input) {
  yield put(someAction())
  yield delay(500)
  yield put(anotherAction())
}
</code>```

Title: Waiting in a redux-saga

Body:
I want to introduce a delay in a saga (using redux-saga).

How can I do this?

If redux-saga provides an API, I would also be interested in how to achieve it manually.

function* save({ payload }) {
    yield put(pending());
    // I want to simply wait (non-blocking) here for say 2 seconds
    yield put(complete());
}

Body:
Redux-sagas has a special effect for this:

delay(ms, [val])

Returns a Promise that will resolve after ms milliseconds with val.

Example:

import { delay, call } from 'redux-saga/effects'

function* someSaga(input) {
  yield put(someAction())
  yield delay(500)
  yield put(anotherAction())
}


问:
DescribeStreamOutcome reported as "incomplete type"
I cloned aws-sdk-cpp from github and I managed to build it without problems (tests passed as well). I did not do "make install". I wanted to compile the dynamodbstreams part of the SDK exclusively, so I added -DBUILD_ONLY="dynamodbstreams" to the cmake parameters. I wrote a small test code, but it fails to compile because of the DescribeStreamOutcome type that is reported to be undefined ("inclomplete type"). However, it exists in the header file where it ought to be.

cmake version: 3.5.1, g++ version: 5.4.0 (I did not tried clang so far)

Could anyone please look at the codes and point out what's wrong?

I have the following code:

```<code>#include "aws/core/Aws.h"
#include "aws/dynamodbstreams/DynamoDBStreamsClient.h"
#include "aws/dynamodbstreams/model/DescribeStreamRequest.h"

int main()
{
    Aws::SDKOptions options;
    Aws::InitAPI(options);

    Aws::DynamoDBStreams::DynamoDBStreamsClient client;
    Aws::DynamoDBStreams::Model::DescribeStreamRequest request;
    auto result = client.DescribeStream(request);
    if (result.IsSuccess()) {}

    Aws::ShutdownAPI(options);

    return 0;
}
</code>```

With this Makefile:

```<code>all: test

CFLAGS = -std=c++11 -Wall -fPIC \
-I$(SDK_SOURCE_DIR)/aws-cpp-sdk-core/include \
-I$(SDK_SOURCE_DIR)/aws-cpp-sdk-dynamodbstreams/include

LFLAGS = -shared -fPIC \
-L$(SDK_BUILD_DIR)/aws-cpp-sdk-core -laws-cpp-sdk-core \
-L$(SDK_BUILD_DIR)/aws-cpp-sdk-dynamodbstreams -laws-cpp-sdk-dynamodbstreams

test: test.o \
     $(CXX) -shared -fPIC -o $@ $^

test.o: test.cc
     $(CXX) $(CFLAGS) -c -o $@ $<

.PHONY: clean
clean:
     rm -f *.o test
</code>```

Upon making I get the following error:

```<code>g++ -std=c++11 -Wall -fPIC -I/home/attilacsabai/git-projects/aws-sdk-cpp/aws-cpp-sdk-core/include -I/home/attilacsabai/git-projects/aws-sdk-cpp/aws-cpp-sdk-dynamodbstreams/include -c -o test.o test.cc
test.cc: In function ‘int main()’:
test.cc:12:48: error: invalid use of incomplete type ‘Aws::DynamoDBStreams::Model::DescribeStreamOutcome {aka class Aws::Utils::Outcome<Aws::DynamoDBStreams::Model::DescribeStreamResult, Aws::Client::AWSError<Aws::DynamoDBStreams::DynamoDBStreamsErrors> >}’
     auto result = client.DescribeStream(request);
                                                ^
In file included from /home/attilacsabai/git-projects/aws-sdk-cpp/aws-cpp-sdk-core/include/aws/core/utils/crypto/Hash.h:19:0,
                 from /home/attilacsabai/git-projects/aws-sdk-cpp/aws-cpp-sdk-core/include/aws/core/client/AWSClient.h:23,
                 from /home/attilacsabai/git-projects/aws-sdk-cpp/aws-cpp-sdk-dynamodbstreams/include/aws/dynamodbstreams/DynamoDBStreamsClient.h:21,
                 from test.cc:2:
/home/attilacsabai/git-projects/aws-sdk-cpp/aws-cpp-sdk-core/include/aws/core/utils/crypto/HashResult.h:26:50: note: declaration of ‘Aws::DynamoDBStreams::Model::DescribeStreamOutcome {aka class Aws::Utils::Outcome<Aws::DynamoDBStreams::Model::DescribeStreamResult, Aws::Client::AWSError<Aws::DynamoDBStreams::DynamoDBStreamsErrors> >}’
         template< typename R, typename E > class Outcome;
                                                  ^
Makefile:16: recipe for target 'test.o' failed
make: *** [test.o] Error 1
</code>```

However, DescribeStreamOutcome is defined in DynamoDBStreamsClient.h:

```<code>$ grep -i describestreamoutcome $SDK_SOURCE_DIR/aws-cpp-sdk-dynamodbstreams/include/aws/dynamodbstreams/DynamoDBStreamsClient.h | head -1
typedef Aws::Utils::Outcome<DescribeStreamResult, Aws::Client::AWSError<DynamoDBStreamsErrors>> DescribeStreamOutcome;
</code>```

So could you please help me out? Thanks.

答:
The statement "DescribeStreamOutcome is defined in DynamoDBStreamsClient.h" is incorrect. That line in DynamoDBStreamsClient.h defines an alias  to an instantiation of Outcome.

clang gives a somewhat more concise error message:

```<code>meow.cpp:12:26: error: implicit instantiation of undefined template 'Aws::Utils::Outcome<Aws::DynamoDBStreams::Model::DescribeStreamResult,
      Aws::Client::AWSError<Aws::DynamoDBStreams::DynamoDBStreamsErrors> >'
    auto result = client.DescribeStream(request);
                         ^
/usr/local/include/aws/dynamodbstreams/DynamoDBStreamsClient.h:44:43: note: template is declared here
  template< typename R, typename E> class Outcome;
                                          ^
</code>```

You need to #include "aws/core/utils/Outcome.h"

Perhaps aws/dynamodbstreams/DynamoDBStreamsClient.h should have included Outcome.h, although code using DynamoDBStreamsClient compiles without it, as long as you don't call any of the Outcome-returning methods.

Body:
I cloned aws-sdk-cpp from github and I managed to build it without problems (tests passed as well). I did not do "make install". I wanted to compile the dynamodbstreams part of the SDK exclusively, so I added -DBUILD_ONLY="dynamodbstreams" to the cmake parameters. I wrote a small test code, but it fails to compile because of the DescribeStreamOutcome type that is reported to be undefined ("inclomplete type"). However, it exists in the header file where it ought to be.

cmake version: 3.5.1, g++ version: 5.4.0 (I did not tried clang so far)

Could anyone please look at the codes and point out what's wrong?

I have the following code:

#include "aws/core/Aws.h"
#include "aws/dynamodbstreams/DynamoDBStreamsClient.h"
#include "aws/dynamodbstreams/model/DescribeStreamRequest.h"

int main()
{
    Aws::SDKOptions options;
    Aws::InitAPI(options);

    Aws::DynamoDBStreams::DynamoDBStreamsClient client;
    Aws::DynamoDBStreams::Model::DescribeStreamRequest request;
    auto result = client.DescribeStream(request);
    if (result.IsSuccess()) {}

    Aws::ShutdownAPI(options);

    return 0;
}

With this Makefile:

all: test

CFLAGS = -std=c++11 -Wall -fPIC \
-I$(SDK_SOURCE_DIR)/aws-cpp-sdk-core/include \
-I$(SDK_SOURCE_DIR)/aws-cpp-sdk-dynamodbstreams/include

LFLAGS = -shared -fPIC \
-L$(SDK_BUILD_DIR)/aws-cpp-sdk-core -laws-cpp-sdk-core \
-L$(SDK_BUILD_DIR)/aws-cpp-sdk-dynamodbstreams -laws-cpp-sdk-dynamodbstreams

test: test.o \
     $(CXX) -shared -fPIC -o $@ $^

test.o: test.cc
     $(CXX) $(CFLAGS) -c -o $@ $<

.PHONY: clean
clean:
     rm -f *.o test

Upon making I get the following error:

g++ -std=c++11 -Wall -fPIC -I/home/attilacsabai/git-projects/aws-sdk-cpp/aws-cpp-sdk-core/include -I/home/attilacsabai/git-projects/aws-sdk-cpp/aws-cpp-sdk-dynamodbstreams/include -c -o test.o test.cc
test.cc: In function ‘int main()’:
test.cc:12:48: error: invalid use of incomplete type ‘Aws::DynamoDBStreams::Model::DescribeStreamOutcome {aka class Aws::Utils::Outcome<Aws::DynamoDBStreams::Model::DescribeStreamResult, Aws::Client::AWSError<Aws::DynamoDBStreams::DynamoDBStreamsErrors> >}’
     auto result = client.DescribeStream(request);
                                                ^
In file included from /home/attilacsabai/git-projects/aws-sdk-cpp/aws-cpp-sdk-core/include/aws/core/utils/crypto/Hash.h:19:0,
                 from /home/attilacsabai/git-projects/aws-sdk-cpp/aws-cpp-sdk-core/include/aws/core/client/AWSClient.h:23,
                 from /home/attilacsabai/git-projects/aws-sdk-cpp/aws-cpp-sdk-dynamodbstreams/include/aws/dynamodbstreams/DynamoDBStreamsClient.h:21,
                 from test.cc:2:
/home/attilacsabai/git-projects/aws-sdk-cpp/aws-cpp-sdk-core/include/aws/core/utils/crypto/HashResult.h:26:50: note: declaration of ‘Aws::DynamoDBStreams::Model::DescribeStreamOutcome {aka class Aws::Utils::Outcome<Aws::DynamoDBStreams::Model::DescribeStreamResult, Aws::Client::AWSError<Aws::DynamoDBStreams::DynamoDBStreamsErrors> >}’
         template< typename R, typename E > class Outcome;
                                                  ^
Makefile:16: recipe for target 'test.o' failed
make: *** [test.o] Error 1

However, DescribeStreamOutcome is defined in DynamoDBStreamsClient.h:

$ grep -i describestreamoutcome $SDK_SOURCE_DIR/aws-cpp-sdk-dynamodbstreams/include/aws/dynamodbstreams/DynamoDBStreamsClient.h | head -1
typedef Aws::Utils::Outcome<DescribeStreamResult, Aws::Client::AWSError<DynamoDBStreamsErrors>> DescribeStreamOutcome;

So could you please help me out? Thanks.

Body:
The statement "DescribeStreamOutcome is defined in DynamoDBStreamsClient.h" is incorrect. That line in DynamoDBStreamsClient.h defines an alias  to an instantiation of Outcome.

clang gives a somewhat more concise error message:

meow.cpp:12:26: error: implicit instantiation of undefined template 'Aws::Utils::Outcome<Aws::DynamoDBStreams::Model::DescribeStreamResult,
      Aws::Client::AWSError<Aws::DynamoDBStreams::DynamoDBStreamsErrors> >'
    auto result = client.DescribeStream(request);
                         ^
/usr/local/include/aws/dynamodbstreams/DynamoDBStreamsClient.h:44:43: note: template is declared here
  template< typename R, typename E> class Outcome;
                                          ^

You need to #include "aws/core/utils/Outcome.h"

Perhaps aws/dynamodbstreams/DynamoDBStreamsClient.h should have included Outcome.h, although code using DynamoDBStreamsClient compiles without it, as long as you don't call any of the Outcome-returning methods.


问:
jquery ui 's autocomplete not working inside form wizard
I'm using jquery steps as a form wizard and I need to implement the autocomplete of jquery UI in a field inside the form wizard, but the autocomplete is not working, when I put the field out of the form, it works, this is the code that I use</p>

```<code><script>
 $(function (){

                    var availableTags = [""];
                   $("#wizard").on('keyup','.tags',function () {

                        $.post('LinkingPages', {Request : 'GetAirports',StartWith : $(this).val()}, function(data) {

                               var Tab = data.split(";");
                               var i;
                               for (i = 0; i < Tab.length; i++) {
                                      availableTags[i] = Tab[i];
                               }
                               for (var j = i; j < availableTags.length; j++) {
                                      availableTags[j]="";
                               }
                        },"text");

                 });

                    $('.tags').autocomplete({
                        open: function() {alert("Hello");},
                        source : availableTags

                 });

                     $("#wizard").steps({

                         headerTag: "h3",
                         bodyTag: "span",
                         transitionEffect: "slideLeft",

                         stepsOrientation: "vertical",
                           onStepChanging: function (event, currentIndex, newIndex)
                         {

                             $("#SendReqForm").validate().settings.ignore = ":disabled,:hidden";
                            return $("#SendReqForm").valid();
                         },
                         onFinishing: function (event, currentIndex)
                         {

                             $("#SendReqForm").validate().settings.ignore = ":disabled";
                             return $("#SendReqForm").valid();
                         },
                         onFinished: function (event, currentIndex)
                         {
                            $("#SendReqForm").submit();
                         }

                     });
                        function errorPlacement(error, element)
                    {
                        element.before(error);
                    }

                        $("#SendReqForm").validate({
                            //errorLabelContainer: '#errors',
                            errorPlacement: errorPlacement,
                            rules: {
                                Co_Password: {
                                    equalTo: "#password"
                                },
                                Co_Email: {
                                    equalToEmail: "#Email"
                                },
                                Password:{
                                    pwdComp:true

                                    }
                            }
                        });
                        jQuery.validator.addMethod("pwdComp", function(input,element, param) {
                            var reg = /^[^%\s]{6,}$/;
                            var reg2 = /[a-zA-Z]/;
                            var reg3 = /[0-9]/;

                            return reg.test(input) && reg2.test(input) && reg3.test(input);
                            },
                             jQuery.validator.format("For security reasons passwords must include a capital letter, small letter, number and be more than 6 characters."));

                });

        </script>
</code>```

答:
Declare Jquery steps configuration before the autocomplete. This works for me:

HTML

```<code><form id="example-form" action="#">
            <div>
                <h3>@Resources.Filter</h3>
                <section>

                    <div class="row">
                        <div class="col-md-12">
                            <div class="col-md-12">
                                <input type="text" style="margin: 15px 0px; font-size: 16px; color: #777; text-transform: uppercase;" class="form-control" id="academiaInput" placeholder="@Resources.TypeSearchForGym..." />
                            </div>

                        </div>
                    </div>

                </section>
                <h3>Profile</h3>
                <section>

                </section>
                <h3>Hints</h3>
                <section>

                </section>
                <h3>Finish</h3>
                <section>

                </section>
            </div>
        </form>
</code>```

Javascript

```<code>$(document).ready(function () {

    var form = $("#example-form");

    form.children("div").steps({
        headerTag: "h3",
        bodyTag: "section",
        transitionEffect: "slideLeft",
        onStepChanging: function (event, currentIndex, newIndex) {
            form.validate().settings.ignore = ":disabled,:hidden";
            return form.valid();
        },
        onFinishing: function (event, currentIndex) {
            form.validate().settings.ignore = ":disabled";
            return form.valid();
        },
        onFinished: function (event, currentIndex) {
            alert("Submitted!");
        }
    });

    $("#academiaInput").autocomplete({
        minLength: 1,
        source: function (request, response) {
            $.ajax({
                MY AJAX TO AUTOCOMPLETE
            })
        },
        select: function (event, ui) {
            event.preventDefault();
            $("#academiaInput").val(ui.item.label);

        },
        change: function (event, ui) {

        }
    })
})
</code>```

Body:
Declare Jquery steps configuration before the autocomplete. This works for me:

HTML

<form id="example-form" action="#">
            <div>
                <h3>@Resources.Filter</h3>
                <section>

                    <div class="row">
                        <div class="col-md-12">
                            <div class="col-md-12">
                                <input type="text" style="margin: 15px 0px; font-size: 16px; color: #777; text-transform: uppercase;" class="form-control" id="academiaInput" placeholder="@Resources.TypeSearchForGym..." />
                            </div>

                        </div>
                    </div>

                </section>
                <h3>Profile</h3>
                <section>

                </section>
                <h3>Hints</h3>
                <section>

                </section>
                <h3>Finish</h3>
                <section>

                </section>
            </div>
        </form>

Javascript

$(document).ready(function () {

    var form = $("#example-form");

    form.children("div").steps({
        headerTag: "h3",
        bodyTag: "section",
        transitionEffect: "slideLeft",
        onStepChanging: function (event, currentIndex, newIndex) {
            form.validate().settings.ignore = ":disabled,:hidden";
            return form.valid();
        },
        onFinishing: function (event, currentIndex) {
            form.validate().settings.ignore = ":disabled";
            return form.valid();
        },
        onFinished: function (event, currentIndex) {
            alert("Submitted!");
        }
    });

    $("#academiaInput").autocomplete({
        minLength: 1,
        source: function (request, response) {
            $.ajax({
                MY AJAX TO AUTOCOMPLETE
            })
        },
        select: function (event, ui) {
            event.preventDefault();
            $("#academiaInput").val(ui.item.label);

        },
        change: function (event, ui) {

        }
    })
})


问:
How to write a nice Low-Pass-Filter in Scala
I needed a Low-Pass-Filter in one of my Scala projects and came up with this:

```<code>def filter(numbers: Seq[Double], filterSize: Int): Seq[Double] = {
  assert(filterSize > 0)
  val ringBuffer = new Array[Double](filterSize)
  var ringBufferIndex = 0

  numbers.map(x => {
    // update ring buffer
    ringBuffer(ringBufferIndex) = x

    // increase ring index
    ringBufferIndex += 1
    if (ringBufferIndex == filterSize) {
      ringBufferIndex = 0
    }

    // get avarage
    ringBuffer.foldLeft(0.0)(_ + _) / filterSize
  })
}
</code>```

However, there are some things I don't like about it:

It uses map (nicely functional) but needs a mutable variable (ringBufferIndex - BAD).

It work's on Seq[Double] (which is fine), but returns Seq[Double], which is bad cause it requires the caller to call .toList or whatever he actually uses. I tried using Generics here like this:

def filter\[T <% Seq[Double]](numbers: T, filterSize: Int): T

but that would not compile.

Does anyone have suggestionts how to improve those two issues?

答:
If the input can be a List rather than Seq, you can clean it up a bit with zipWithIndex:

```<code>def filter(numbers: List[Double], filterSize: Int): List[Double] = {
  require(filterSize > 0)
  val ringBuffer = new Array[Double](filterSize)
  numbers.zipWithIndex.map(pair => {
    // update ring buffer
    ringBuffer(pair._2 % filterSize) = pair._1
    // get avarage
    ringBuffer.foldLeft(0.0)(_ + _) / filterSize
  })
}
</code>```

Note that the return value is also now List and I replaced assert with require.

OwnerDisplayName: Lemmy

Body:
I needed a Low-Pass-Filter in one of my Scala projects and came up with this:

def filter(numbers: Seq[Double], filterSize: Int): Seq[Double] = {
  assert(filterSize > 0)
  val ringBuffer = new Array[Double](filterSize)
  var ringBufferIndex = 0

  numbers.map(x => {
    // update ring buffer
    ringBuffer(ringBufferIndex) = x

    // increase ring index
    ringBufferIndex += 1
    if (ringBufferIndex == filterSize) {
      ringBufferIndex = 0
    }

    // get avarage
    ringBuffer.foldLeft(0.0)(_ + _) / filterSize
  })
}

However, there are some things I don't like about it:

It uses map (nicely functional) but needs a mutable variable (ringBufferIndex - BAD).

It work's on Seq[Double] (which is fine), but returns Seq[Double], which is bad cause it requires the caller to call .toList or whatever he actually uses. I tried using Generics here like this:

def filter\[T <% Seq[Double]](numbers: T, filterSize: Int): T

but that would not compile.

Does anyone have suggestionts how to improve those two issues?

Body:
If the input can be a List rather than Seq, you can clean it up a bit with zipWithIndex:

def filter(numbers: List[Double], filterSize: Int): List[Double] = {
  require(filterSize > 0)
  val ringBuffer = new Array[Double](filterSize)
  numbers.zipWithIndex.map(pair => {
    // update ring buffer
    ringBuffer(pair._2 % filterSize) = pair._1
    // get avarage
    ringBuffer.foldLeft(0.0)(_ + _) / filterSize
  })
}

Note that the return value is also now List and I replaced assert with require.

OwnerDisplayName: Dave Ray

ContentLicense: CC BY-SA 2.5


问:
ES6 - How to modify a variable in other modules
in module Global.js:

```<code>export let transLog = [];
</code>```

in main:

```<code>import * as G from "./Global";
G.transLog = [];
</code>```

I got a error:

```<code>app.js?c99e:19 Uncaught TypeError: Cannot set property q of #<Object> which has only a getter
    at eval (app.js?c99e:19)
    at Object.<anonymous> (bootstrap e92860b74eb6dd40b159:62)
    at __webpack_require__ (bootstrap e92860b74eb6dd40b159:19)
    at bootstrap e92860b74eb6dd40b159:62
    at bootstrap e92860b74eb6dd40b159:62
</code>```

webpack config:

```<code>const webpack = require('webpack');

module.exports = {
    entry: './js/app.js',
    plugins: [
        new webpack.SourceMapDevToolPlugin({
            filename: "[file].map"
        })
    ],
    output: {
        filename: './dist/app.js'
    },
    devtool: 'source-map'
};
</code>```

So, how to modify a variable in other modules?

答:
You cannot assign new values to exported variables, only the module itself can do that (and when it does, it can be pretty confusing, so I'd recommend to avoid this).

You can mutate exported objects though, e.g. G.translog.push(…) or G.translog.length = 0.

Body:
in module Global.js:

export let transLog = [];

in main:

import * as G from "./Global";
G.transLog = [];

I got a error:

app.js?c99e:19 Uncaught TypeError: Cannot set property q of #<Object> which has only a getter
    at eval (app.js?c99e:19)
    at Object.<anonymous> (bootstrap e92860b74eb6dd40b159:62)
    at __webpack_require__ (bootstrap e92860b74eb6dd40b159:19)
    at bootstrap e92860b74eb6dd40b159:62
    at bootstrap e92860b74eb6dd40b159:62

webpack config:

const webpack = require('webpack');

module.exports = {
    entry: './js/app.js',
    plugins: [
        new webpack.SourceMapDevToolPlugin({
            filename: "[file].map"
        })
    ],
    output: {
        filename: './dist/app.js'
    },
    devtool: 'source-map'
};

So, how to modify a variable in other modules?


问:
Detect moving the windows from one display to another
I have a window with an opengl view where content ist rendered. The problem I have in macOS is, that when I move the window from one monitor to the other, its content gets messed up. A redraw fixes the issue. Thus I need to redraw the GL Area when it gets moved from one monitor to the other. Is there any way to detect the transition of the window from one monitor to the other?</p>

答: You can register for notifications that fire when the view's window changes screens: NSWindowDidChangeScreenNotification</p>


问:
How to create Athena database via API
I would like to create a database in Athena via API. I have parquet files in S3 that I would like to query using the API and I would like to use Athena for the query.

Anyway I can create a database via API for Athena?

答:
Creating a database in Athena can be done by creating your own API request or using the SDK.

Here is a Python example using the SDK:

```<code>import boto3

client = boto3.client('athena')

config = {'OutputLocation': 's3://TEST_BUCKET/'}

client.start_query_execution(
                             QueryString = 'create database TEST_DATABASE',
                             ResultConfiguration = config
)
</code>```

There are SDKs available for Java, .NET, Node, PHP, Python, Ruby, Go, and C++.  If you want to create your own API requests, I recommend developing a good understanding of the signing process.  You could also use the AWS CLI as such:

```<code>$ aws athena start-query-execution --query-string "CREATE database ATHENA_TEST_TWO" --result-configuration "OutputLocation=s3://TEST_BUCKET/"
</code>```

Once you have a database created, you can then pass the database name in your query requests.

```<code>context = {'Database': 'TEST_DATABASE'}
client.start_query_execution(QueryString='CREATE TABLE ...',
                             QueryExecutionContext = context,
                             ResultConfiguration=config)
</code>```

To see some DDL creating a table from Parquet files see the following examples on the Amazon Athena User Guide.

Edit In reponse to @condo1234's questions:

But how do I associated a database with a file in S3?

The short answer is you don't.  You associate a table with files sharing a prefix in a bucket in S3.

For example, say I want to create a table to analyze data held in s3://TEST_BUCKET.  Through the AWS Console, I can use the poorly named "Create Folder" button to create a prefix called one-table-many-files/.  I then created two csv files:

f1.csv

```<code>Codd,1923
Ellison,1944
Chamberlin,1944
Boyce,1947
</code>```

f2.csv

```<code>Hopper,1906
Floyd,1953
Moriarty Wolf Chambers,1980
</code>```

I then uploaded these text files to the example bucket/prefix combination s3://TEST_BUCKET/one-table-many-files/

I ran the following DDL:

```<code>CREATE EXTERNAL TABLE php_test.computer_scientists (
  name string,
  year_born int
  )
ROW FORMAT DELIMITED
 FIELDS TERMINATED BY ','
 LINES TERMINATED BY '\n'
LOCATION 's3://TEST_BUCKET/one-table-many-files/';
</code>```

And ran the following SQL Statement:

```<code>SELECT * FROM php_test.computer_scientists;
</code>```

I got the following results back, with data from both files in the bucket + prefix combination specified in the DDL.

```<code>"name","year_born"
"Hopper","1906"
"Floyd","1953"
"Moriarty Wolf Chambers","1980"
"Codd","1923"
"Ellison","1944"
"Chamberlin","1944"
"Boyce","1947"
</code>```

Notice that I am using the word "prefix" and not "folder"?  That is because S3 has no concept of a folder!  These prefixes are useful however, as they allow for Athena Partitioning.

Per your request, here is a php example as well.

```<code><?php
print('Welcome to PHP');

require 'aws-autoloader.php';

$athena = new Aws\Athena\AthenaClient(['version' => 'latest', 'region' => 'us-east-1' ]);

$athena->StartQueryExecution([
    'QueryString' => 'CREATE DATABASE php_test;',
    'ResultConfiguration' => [
        'OutputLocation' => 's3://TEST_BUCKET/', // REQUIRED
    ],
]);

?>
</code>```

See the PHP SDK Documentation for more.

Title: How to create Athena database via API

Body:
Creating a database in Athena can be done by creating your own API request or using the SDK.

Here is a Python example using the SDK:

import boto3

client = boto3.client('athena')

config = {'OutputLocation': 's3://TEST_BUCKET/'}

client.start_query_execution(
                             QueryString = 'create database TEST_DATABASE',
                             ResultConfiguration = config
)

There are SDKs available for Java, .NET, Node, PHP, Python, Ruby, Go, and C++.  If you want to create your own API requests, I recommend developing a good understanding of the signing process.  You could also use the AWS CLI as such:

$ aws athena start-query-execution --query-string "CREATE database ATHENA_TEST_TWO" --result-configuration "OutputLocation=s3://TEST_BUCKET/"

Once you have a database created, you can then pass the database name in your query requests.

context = {'Database': 'TEST_DATABASE'}
client.start_query_execution(QueryString='CREATE TABLE ...',
                             QueryExecutionContext = context,
                             ResultConfiguration=config)

To see some DDL creating a table from Parquet files see the following examples on the Amazon Athena User Guide.

Edit In reponse to @condo1234's questions:

But how do I associated a database with a file in S3?

The short answer is you don't.  You associate a table with files sharing a prefix in a bucket in S3.

For example, say I want to create a table to analyze data held in s3://TEST_BUCKET.  Through the AWS Console, I can use the poorly named "Create Folder" button to create a prefix called one-table-many-files/.  I then created two csv files:

f1.csv

Codd,1923
Ellison,1944
Chamberlin,1944
Boyce,1947

f2.csv

Hopper,1906
Floyd,1953
Moriarty Wolf Chambers,1980

I then uploaded these text files to the example bucket/prefix combination s3://TEST_BUCKET/one-table-many-files/

I ran the following DDL:

CREATE EXTERNAL TABLE php_test.computer_scientists (
  name string,
  year_born int
  )
ROW FORMAT DELIMITED
 FIELDS TERMINATED BY ','
 LINES TERMINATED BY '\n'
LOCATION 's3://TEST_BUCKET/one-table-many-files/';

And ran the following SQL Statement:

SELECT * FROM php_test.computer_scientists;

I got the following results back, with data from both files in the bucket + prefix combination specified in the DDL.

"name","year_born"
"Hopper","1906"
"Floyd","1953"
"Moriarty Wolf Chambers","1980"
"Codd","1923"
"Ellison","1944"
"Chamberlin","1944"
"Boyce","1947"

Notice that I am using the word "prefix" and not "folder"?  That is because S3 has no concept of a folder!  These prefixes are useful however, as they allow for Athena Partitioning.

Per your request, here is a php example as well.

<?php
print('Welcome to PHP');

require 'aws-autoloader.php';

$athena = new Aws\Athena\AthenaClient(['version' => 'latest', 'region' => 'us-east-1' ]);

$athena->StartQueryExecution([
    'QueryString' => 'CREATE DATABASE php_test;',
    'ResultConfiguration' => [
        'OutputLocation' => 's3://TEST_BUCKET/', // REQUIRED
    ],
]);

?>

See the PHP SDK Documentation for more.


问:
Refresh ng-repeat data
I have a big list containing all of my data, and I have another shorter list containing only the selected data.
Originally, all the data is selected so both lists are identical, and the user must uncheck the checkbox of the unwanted data, and then the unchecked data must disappear from the selected_data_list.

When the page is loaded, the two lists are being filled correctly. But when I uncheck the unwanted data, the selected_data_list is not updating.

I tried to use $scope.$apply(), but it gave me this error:

Error: $rootScope:inprog
  Action Already In Progress

Here is my code:

Complete list:

```<code><div ng-controller="BrainRegionsCtrl">

    <div ng-repeat="region in brain_regions">

        <label>

           <input type="checkbox"
              name="checkbox_brain_region__included"
              id="checkbox_brain_region_{/region.id/}"
              value="{/region.id/}"
              ng-model="region.show"
              ng-change="update_selected_Brain_regions(region)">

           <b>{/region.name/}</b>

         </label>

    </div>
</div>
</code>```

Selected regions list:

```<code><div ng-controller="BrainRegionsCtrl">

    <label ng-repeat="region in selected_brain_regions">
        <input type="radio" name="radio_brain_regions_graphical_search_soma" value="{/region.id/}">
        <b>{/region.name/}</b>
    </label>

 </div>
</code>```

Controller:

```<code>ngApp.controller('BrainRegionsCtrl', function ($scope, $http) {

    $scope.brain_regions = [];
    $scope.selected_brain_regions = [];

    $scope.update_selected_Brain_regions = function (region) {

        for (var i = 0; i < $scope.brain_regions.length; i++) {
            var current_region = $scope.brain_regions[i];
            if (current_region.id === region.id) {
                if (region.show) {
                    $scope.selected_brain_regions.push(current_region);
                }
                else {
                    $scope.selected_brain_regions.splice(i,1);
                }
            }
        }
        console.log($scope.selected_brain_regions);

    };

});
</code>```

Here is a jsfiddle
Thank you.

答:
Just try to use $rootScope.
Because you give the ng-controller="BrainRegionsCtrl"  for two div that's why the $scope.selected_brain_regions will go to the initial state in the second div.

OR

you should give the ng-controller="BrainRegionsCtrl" to the root div which contains the two parts of your code..

Title: Refresh ng-repeat data

Body:
I have a big list containing all of my data, and I have another shorter list containing only the selected data.
Originally, all the data is selected so both lists are identical, and the user must uncheck the checkbox of the unwanted data, and then the unchecked data must disappear from the selected_data_list.

When the page is loaded, the two lists are being filled correctly. But when I uncheck the unwanted data, the selected_data_list is not updating.

I tried to use $scope.$apply(), but it gave me this error:

Error: $rootScope:inprog
  Action Already In Progress

Here is my code:

Complete list:

           <input type="checkbox"
              name="checkbox_brain_region__included"
              id="checkbox_brain_region_{/region.id/}"
              value="{/region.id/}"
              ng-model="region.show"
              ng-change="update_selected_Brain_regions(region)">

           {/region.name/}

Selected regions list:

        <input type="radio" name="radio_brain_regions_graphical_search_soma" value="{/region.id/}">
        {/region.name/}

Controller:

ngApp.controller('BrainRegionsCtrl', function ($scope, $http) {

    $scope.brain_regions = [];
    $scope.selected_brain_regions = [];

    $scope.update_selected_Brain_regions = function (region) {

        for (var i = 0; i < $scope.brain_regions.length; i++) {
            var current_region = $scope.brain_regions[i];
            if (current_region.id === region.id) {
                if (region.show) {
                    $scope.selected_brain_regions.push(current_region);
                }
                else {
                    $scope.selected_brain_regions.splice(i,1);
                }
            }
        }
        console.log($scope.selected_brain_regions);

    };

});

Here is a jsfiddle
Thank you.


问:
Ruby replace string if next letter is found
I want to replace a pattern in Ruby only if the next letter after the pattern is one of the given.

Example: replace "αυ" with "av" ONLY IF next letter after "αυ" is one of the followings: α|γ|δ|λ|μ|ν|ρ|σμ|ω

This code will not work of course, I suppose I need to use a regex more complicate to match one of the letter after the pattern.

```<code>string.gsub!("αυ", "av") if string =~ /α|γ|δ|λ|μ|ν|ρ|σμ|ω/
</code>```

Thanks for any suggestion.

答:
Use a positive lookahead:

```<code>string.gsub!(/αυ(?=α|γ|δ|λ|μ|ν|ρ|σμ|ω)/, "av")
</code>```

See the Rubular demo

Details

αυ - a αυ substring

(?=α|γ|δ|λ|μ|ν|ρ|σμ|ω) - a positive lookahead that requires the presence of one of the alternatives inside it while excluding the alternative inside the match value, i.e. it will be left in the resulting string).

You may also "contract" the single-char alternations into a character class

```<code>/αυ(?=[αγδλμνρω]|σμ)/
      ^^^^^^^^^^
</code>```

See another Rubular demo. σμ cannot be put inside a character class since it contains 2 chars.

Body:
I want to replace a pattern in Ruby only if the next letter after the pattern is one of the given.

Example: replace "αυ" with "av" ONLY IF next letter after "αυ" is one of the followings: α|γ|δ|λ|μ|ν|ρ|σμ|ω

This code will not work of course, I suppose I need to use a regex more complicate to match one of the letter after the pattern.

string.gsub!("αυ", "av") if string =~ /α|γ|δ|λ|μ|ν|ρ|σμ|ω/

Thanks for any suggestion.

Body:
Use a positive lookahead:

string.gsub!(/αυ(?=α|γ|δ|λ|μ|ν|ρ|σμ|ω)/, "av")

See the Rubular demo

Details

αυ - a αυ substring

(?=α|γ|δ|λ|μ|ν|ρ|σμ|ω) - a positive lookahead that requires the presence of one of the alternatives inside it while excluding the alternative inside the match value, i.e. it will be left in the resulting string).

You may also "contract" the single-char alternations into a character class

/αυ(?=[αγδλμνρω]|σμ)/
      ^^^^^^^^^^

See another Rubular demo. σμ cannot be put inside a character class since it contains 2 chars.


问:
StopPropagation in HTML with Angular
I am having a problem with stopPropagation, I don't know how to write in html and typescript for angular.
It opens the dialog but at the same time makes a propagation.

Here is my code in HTML:

```<code><label for="tab-two">PROJECTS
    <a class="plus" (click)="opentestdialog()">+</a>
</label>
</code>```

And here is my code in TypeScript:

```<code>opentestdialog() {
    this.dialog.open(TestdialogComponent);
}
</code>```

答:
This is the HTML:

```<code><a class="plus" ng-click="opentestdialog($event)">+</a>
</code>```

This is the typescript file:

public opentestdialog(event: angular.IAngularEvent) {
    event.stopPropagation();
    this.dialog.open(TestdialogComponent);
}
```

Title: StopPropagation in HTML with Angular

Body:
I am having a problem with stopPropagation, I don't know how to write in html and typescript for angular.
It opens the dialog but at the same time makes a propagation.

Here is my code in HTML:

PROJECTS
    +

And here is my code in TypeScript:

opentestdialog() {
    this.dialog.open(TestdialogComponent);
}

Body:
This is the HTML:

<a class="plus" ng-click="opentestdialog($event)">+</a>

This is the typescript file:

public opentestdialog(event: angular.IAngularEvent) {
    event.stopPropagation();
    this.dialog.open(TestdialogComponent);
}


问:
Datatables missing last row
I have a problem when I try to show "All" records in my Datatable.
I use the Pipelining function with my Datatables and (except for the pipeline) this is my JS:

```<code>var dTable = $('#myTable').DataTable( {
    "processing": true,
    "serverSide": true,
    "bSortCellsTop": true,
    "autoWidth": false,
    "aLengthMenu": [
        [25, 50, 100, 500, -1],
        [25, 50, 100, 500, "All"]
    ],
    "iDisplayLength": 50,
    "order": [[ 10, "asc" ]],
    "dom": '<"top"<"dd-area">flp<"button-area">>rt<"bottom"flpi><"clear">',
    "ajax": $.fn.dataTable.pipeline( {
        url: '_handler.php?action='+action+'&cms='+curr_cms
    } ),
    "columns": [
        /* columns defined here */
    ],
    "columnDefs": [
        {
            "targets": ['_all'],
            "createdCell": function (td, cellData, rowData, row, col) {
                $(td).attr('title', $titles[col]);
            }
        }
    ],
    "search": "Search:",
    "zeroRecords": "No record found",
    "fnInitComplete" : function(oSettings, json) {
        /* code here */
    },
    "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
        /* code here */
    }
} );
</code>```

With "All" selected in the length menu, I get Showing 1 to 337 of 338 entries.

I already checked my remote source and all 338 records are correctly sent, but the very last item of the 'data' array isn't shown in the frontend table.

If I set bPaginate: false all entries are correctly shown.

Any idea?

答:
if you use the example code Pipelining of Datatable, they have an error into this.
You need to modify this lines

```<code>if ( requestLength >= -1 ) {
    json.data.splice( requestLength, json.data.length );
}
</code>```

and remove the equal

```<code>if ( requestLength > -1 ) {
    json.data.splice( requestLength, json.data.length );
}
</code>```

Title: Datatables missing last row

Body:
I have a problem when I try to show "All" records in my Datatable.
I use the Pipelining function with my Datatables and (except for the pipeline) this is my JS:

var dTable = $('#myTable').DataTable( {
    "processing": true,
    "serverSide": true,
    "bSortCellsTop": true,
    "autoWidth": false,
    "aLengthMenu": [
        [25, 50, 100, 500, -1],
        [25, 50, 100, 500, "All"]
    ],
    "iDisplayLength": 50,
    "order": [[ 10, "asc" ]],
    "dom": '<"top"<"dd-area">flp<"button-area">>rt<"bottom"flpi><"clear">',
    "ajax": $.fn.dataTable.pipeline( {
        url: '_handler.php?action='+action+'&cms='+curr_cms
    } ),
    "columns": [
        /* columns defined here */
    ],
    "columnDefs": [
        {
            "targets": ['_all'],
            "createdCell": function (td, cellData, rowData, row, col) {
                $(td).attr('title', $titles[col]);
            }
        }
    ],
    "search": "Search:",
    "zeroRecords": "No record found",
    "fnInitComplete" : function(oSettings, json) {
        /* code here */
    },
    "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
        /* code here */
    }
} );

With "All" selected in the length menu, I get Showing 1 to 337 of 338 entries.

I already checked my remote source and all 338 records are correctly sent, but the very last item of the 'data' array isn't shown in the frontend table.

If I set bPaginate: false all entries are correctly shown.

Any idea?

Body:
if you use the example code Pipelining of Datatable, they have an error into this.
You need to modify this lines

if ( requestLength >= -1 ) {
    json.data.splice( requestLength, json.data.length );
}

and remove the equal

if ( requestLength > -1 ) {
    json.data.splice( requestLength, json.data.length );
}


问:
Make some sub-directories using one rule in makefile
I am trying to make some sub directories in a makefile. I know how to do it using a rule for each sub-directory. I am looking for the syntax that will do it using one rule for all subdirectories (either using a loop or using SUBDIRs list).

For example:

```<code>$(dst_dir)/%.o : $(M2M_GENERIC_DIR)/rm/src/%.c
    $(TRACE_CC)
    $(Q)$(GCC) -c $(CFLAGS) $< -o $@
    $(Q)$(GCC) -c $(CFLAGS) -MM -MT $@ -MF $(subst .o,.d,$@) $< -o $(subst .o,.d,$@)

$(dst_dir)/%.o : $(M2M_GENERIC_DIR)/utility/src/%.c
    $(TRACE_CC)
    $(Q)$(GCC) -c $(CFLAGS) $< -o $@
    $(Q)$(GCC) -c $(CFLAGS) -MM -MT $@ -MF $(subst .o,.d,$@) $< -o $(subst .o,.d,$@)

$(dst_dir)/%.o : $(M2M_GENERIC_DIR)/fota/src/%.c
    $(TRACE_CC)
    $(Q)$(GCC) -c $(CFLAGS) $< -o $@
    $(Q)$(GCC) -c $(CFLAGS) -MM -MT $@ -MF $(subst .o,.d,$@) $< -o $(subst .o,.d,$@)

$(dst_dir)/%.o : $(M2M_GENERIC_DIR)/fota/src/lzo/%.c
    $(TRACE_CC)
    $(Q)$(GCC) -c $(CFLAGS) $< -o $@
    $(Q)$(GCC) -c $(CFLAGS) -MM -MT $@ -MF $(subst .o,.d,$@) $< -o $(subst .o,.d,$@)
</code>```

答:
Ok, I think what you're looking for is this:

```<code>#-------------------------------------
define mk_subdir =

$1/%.o : $(M2M_GENERIC_DIR)/rm/src/%.c
    $(TRACE_CC)
    $(Q)$(GCC) -c $(CFLAGS) $< -o $@
    $(Q)$(GCC) -c $(CFLAGS) -MM -MT $@ -MF $(subst .o,.d,$@) $< -o $(subst .o,.d,$@)

$1/%.o : $(M2M_GENERIC_DIR)/utility/src/%.c
    $(TRACE_CC)
    $(Q)$(GCC) -c $(CFLAGS) $< -o $@
    $(Q)$(GCC) -c $(CFLAGS) -MM -MT $@ -MF $(subst .o,.d,$@) $< -o $(subst .o,.d,$@)

$1/%.o : $(M2M_GENERIC_DIR)/fota/src/%.c
    $(TRACE_CC)
    $(Q)$(GCC) -c $(CFLAGS) $< -o $@
    $(Q)$(GCC) -c $(CFLAGS) -MM -MT $@ -MF $(subst .o,.d,$@) $< -o $(subst .o,.d,$@)

$1/%.o : $(M2M_GENERIC_DIR)/fota/src/lzo/%.c
    $(TRACE_CC)
    $(Q)$(GCC) -c $(CFLAGS) $< -o $@
    $(Q)$(GCC) -c $(CFLAGS) -MM -MT $@ -MF $(subst .o,.d,$@) $< -o $(subst .o,.d,$@)

endef
#-------------------------------------

foreach (dir,$(SUBDIRS),$(eval $(call mk_subdir,$(dir)))
</code>```

See eval for more details.

Of course defines like these make it hard for others to understand/debug/maintain makefiles, so only use if you really need to...   (disclaimer -- I never tested the above code, so there could be a syntax error hiding in there somewhere...)

Body:
I am trying to make some sub directories in a makefile. I know how to do it using a rule for each sub-directory. I am looking for the syntax that will do it using one rule for all subdirectories (either using a loop or using SUBDIRs list).

For example:

$(dst_dir)/%.o : $(M2M_GENERIC_DIR)/rm/src/%.c
    $(TRACE_CC)
    $(Q)$(GCC) -c $(CFLAGS) $< -o $@
    $(Q)$(GCC) -c $(CFLAGS) -MM -MT $@ -MF $(subst .o,.d,$@) $< -o $(subst .o,.d,$@)

$(dst_dir)/%.o : $(M2M_GENERIC_DIR)/utility/src/%.c
    $(TRACE_CC)
    $(Q)$(GCC) -c $(CFLAGS) $< -o $@
    $(Q)$(GCC) -c $(CFLAGS) -MM -MT $@ -MF $(subst .o,.d,$@) $< -o $(subst .o,.d,$@)

$(dst_dir)/%.o : $(M2M_GENERIC_DIR)/fota/src/%.c
    $(TRACE_CC)
    $(Q)$(GCC) -c $(CFLAGS) $< -o $@
    $(Q)$(GCC) -c $(CFLAGS) -MM -MT $@ -MF $(subst .o,.d,$@) $< -o $(subst .o,.d,$@)

$(dst_dir)/%.o : $(M2M_GENERIC_DIR)/fota/src/lzo/%.c
    $(TRACE_CC)
    $(Q)$(GCC) -c $(CFLAGS) $< -o $@
    $(Q)$(GCC) -c $(CFLAGS) -MM -MT $@ -MF $(subst .o,.d,$@) $< -o $(subst .o,.d,$@)

Body:
Ok, I think what you're looking for is this:

#-------------------------------------
define mk_subdir =

$1/%.o : $(M2M_GENERIC_DIR)/rm/src/%.c
    $(TRACE_CC)
    $(Q)$(GCC) -c $(CFLAGS) $< -o $@
    $(Q)$(GCC) -c $(CFLAGS) -MM -MT $@ -MF $(subst .o,.d,$@) $< -o $(subst .o,.d,$@)

$1/%.o : $(M2M_GENERIC_DIR)/utility/src/%.c
    $(TRACE_CC)
    $(Q)$(GCC) -c $(CFLAGS) $< -o $@
    $(Q)$(GCC) -c $(CFLAGS) -MM -MT $@ -MF $(subst .o,.d,$@) $< -o $(subst .o,.d,$@)

$1/%.o : $(M2M_GENERIC_DIR)/fota/src/%.c
    $(TRACE_CC)
    $(Q)$(GCC) -c $(CFLAGS) $< -o $@
    $(Q)$(GCC) -c $(CFLAGS) -MM -MT $@ -MF $(subst .o,.d,$@) $< -o $(subst .o,.d,$@)

$1/%.o : $(M2M_GENERIC_DIR)/fota/src/lzo/%.c
    $(TRACE_CC)
    $(Q)$(GCC) -c $(CFLAGS) $< -o $@
    $(Q)$(GCC) -c $(CFLAGS) -MM -MT $@ -MF $(subst .o,.d,$@) $< -o $(subst .o,.d,$@)

endef
#-------------------------------------

foreach (dir,$(SUBDIRS),$(eval $(call mk_subdir,$(dir)))

See eval for more details.

Of course defines like these make it hard for others to understand/debug/maintain makefiles, so only use if you really need to...   (disclaimer -- I never tested the above code, so there could be a syntax error hiding in there somewhere...)