问:
Vue-Router: $router.go(-1) doesn't work in Safari
I have the following setup in the App.vue:

```<code><top-nav></top-nav>
<main>
    <router-view v-bind="{isOnline}"></router-view>
</main>
</code>```

And in the top-nav's js I have the goBack method:

```<code>methods: {
    goBack() {
        this.$router.go(-1);
    },
    ...
},
</code>```

This works just fine in Chrome and Internet Explorer, not Safari though. When debugging and setting a breakpoint on that .go(-1)-line it hits the breakpoint and everything looks fine (nothing undefined). The navigation call isn't done though.

This doesn't work on mobile nor desktop. I thought Safari had support for the History API?

答:
I found out that the icon I used for going back was wrapped in an anchor tag with a set href attribute.

```<code><a v-if="showBackButton" href="#" @click="goBack">
    <i class="icon icon-200-chevron-left-small"></i>
    <p>back</p>
</a>
</code>```

Solution:

Change the anchor tag to a span or something and of course remove the href attribute.

Body:
I have the following setup in the App.vue:

<top-nav></top-nav>

    <router-view v-bind="{isOnline}"></router-view>

And in the top-nav's js I have the goBack method:

methods: {
    goBack() {
        this.$router.go(-1);
    },
    ...
},

This works just fine in Chrome and Internet Explorer, not Safari though. When debugging and setting a breakpoint on that .go(-1)-line it hits the breakpoint and everything looks fine (nothing undefined). The navigation call isn't done though.

This doesn't work on mobile nor desktop. I thought Safari had support for the History API?

Body:
I found out that the icon I used for going back was wrapped in an anchor tag with a set href attribute.

<a v-if="showBackButton" href="#" @click="goBack">
    <i class="icon icon-200-chevron-left-small"></i>
    <p>back</p>
</a>

Solution:

Change the anchor tag to a span or something and of course remove the href attribute.


来源: stackexchange

问:
remove specific lines of file using bash
I have to file suppost 1.txt and 2.txt
1.txt has a number in each line indicate the itemID. for example

```<code>43
345
65
</code>```

the second file is csv and has the following pattern
userID,itemID,time

I want to remove from second file all lines which their itemID is in the first file
for this purpose I do the following

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

while IFS= read -r var
do
 paste -sd '|' | xargs -I{} grep -v -E {} 2.txt
done < "1.txt"
</code>```

I read the first file and create a regular expression, but don't know the argument of egrep to get the second filed(itemID)

答:
You can use sed to add commas to the beginning and end of each id in 1.txt, then just use grep to filter out the resulting strings:

```<code>sed 's/^\|$/,/g' 1.txt | grep -vFf- 2.txt
</code>```

-F interprets the patterns as fixed strings, i.e. not regular expressions

-f tells grep to read the patterns from the given file, in this case -, i.e. standard input

ContentLicense: CC BY-SA 3.0

Body:
I have to file suppost 1.txt and 2.txt
1.txt has a number in each line indicate the itemID. for example

43
345
65

the second file is csv and has the following pattern
userID,itemID,time

I want to remove from second file all lines which their itemID is in the first file
for this purpose I do the following

#!/bin/bash

while IFS= read -r var
do
 paste -sd '|' | xargs -I{} grep -v -E {} 2.txt
done < "1.txt"

I read the first file and create a regular expression, but don't know the argument of egrep to get the second filed(itemID)

Body:
You can use sed to add commas to the beginning and end of each id in 1.txt, then just use grep to filter out the resulting strings:

sed 's/^\|$/,/g' 1.txt | grep -vFf- 2.txt

-F interprets the patterns as fixed strings, i.e. not regular expressions

-f tells grep to read the patterns from the given file, in this case -, i.e. standard input


问:
How to do "adb logcat" via Wifi without connecting the device to the computer first?
I'm developing an app for a custom Android x86 build using a mini PC. I'm trying to debug and do the logcat on it via Wifi, since I can't really connect the mini PC to my workstation using USB and logcat it the usual way. Or at least not that I'm aware of. But on every articles and tutorials that I've read, the first step to do adb via Wifi is to connect the device first and do "adb tcpip 5555", which I cannot do, or I don't know how to do. So is there anyway to debug and log the mini PC without connecting it to the workstation first?

Thanks.

答: There is no way to do that in devices that are not rooted,even for rooted ones you do realize that would be a security problem right ,anyone whose debugging is enabled could be connected then.</p>


问:
Is bulkIndexOnStartup needed when using mirrorChanges = true in Grails Searchable plugin?
The mirrorChanges option will mirror all changes made through GORM/Hibernate, so if I'm not making any external changes to the database, then is bulkIndexOnStartup needed?

The problem is that our data set is very large (>1M rows) and the bulk indexer may take 30+ minutes.

When set to 'fork' lucene will crash if any changes are made though the GORM, because lucene is not thread safe and the GORM transaction will attempt to update the index while the forked bulk index thread is running.

When set to true, the application will finish initializing for those 30+ minutes.

答: If you are not modifying the data from another source, then you don't need to set bulkIndexOnStartup to true, specially if you set mirrorChanges to true. This is pretty much how we handle it in our application. We have a controller action that calls the indexer, forked, for a specific class so we can call it on demand in case we need to, for example if for some reason we needed to update the database directly. We then call the indexer for a specific class and not the entire set of class, in that way if we need to call it then it won't take that long.</p>

ContentLicense: CC BY-SA 2.5


问:
Angular4 deletes entry from database but I have to reload page to see the results
After I press delete button, the message gets deleted from database but I have to refresh the page to see the message disappear from page.

dashboard.component.html

```<code><h2 *ngIf="user"> Hello, {{user.username}} </h2>
<a [routerLink]="['/']">Log Out</a>

<form (submit)="createMessage()">
<label>Message</label>
<input type="text" name="message" [(ngModel)]="message.message">
<input type="submit" value="create new message">
</form>

<div *ngFor="let message of messages">
<h1>{{message.userId.username}}</h1>
<h3>{{message.message}}</h3>
<h2 *ngIf="user.username === message.userId.username">
<form (submit) = "delete(message._id)">
    <button type="submit" name="" value="">DeleteOne</button>
</form>
</h2>
<hr>
</div>
</code>```

dashboard.component.ts

```<code>export class DashboardComponent implements OnInit {
messages: Message[] =[];
user: User;
message: Message = new Message();
currentId;

constructor(public _user: UserService, public _router:Router,private
_route: ActivatedRoute, private _message: MessageService) {
this.user = _user.currentUser;
this._route.params.subscribe((param)=>{
console.log("task details url id is: ", param.id);
this.currentId = param.id;
})
}

delete(val) {
console.log("delete method!", val);
 this._message.delete({id: val})
 .then((data)=>{
})
</code>```

答:
You may remove it from array once deleted, or you also can get the data back and re initialize your array.</p>

```<code>delete(val) {

 this._message.delete({id: val})
.then((data)=>{
     this.messages.remove(this.messages.findIndex((message => message._id === val));
  });
}
</code>```

Body:
After I press delete button, the message gets deleted from database but I have to refresh the page to see the message disappear from page.

dashboard.component.html

 Hello, {{user.username}}

Log Out

<form (submit)="createMessage()">
Message
<input type="text" name="message" [(ngModel)]="message.message">
<input type="submit" value="create new message">
</form>

{{message.userId.username}}

{{message.message}}

<form (submit) = "delete(message._id)">
    <button type="submit" name="" value="">DeleteOne</button>
</form>

dashboard.component.ts

export class DashboardComponent implements OnInit {
messages: Message[] =[];
user: User;
message: Message = new Message();
currentId;

constructor(public _user: UserService, public _router:Router,private
_route: ActivatedRoute, private _message: MessageService) {
this.user = _user.currentUser;
this._route.params.subscribe((param)=>{
console.log("task details url id is: ", param.id);
this.currentId = param.id;
})
}

delete(val) {
console.log("delete method!", val);
 this._message.delete({id: val})
 .then((data)=>{
})

Body:
You may remove it from array once deleted, or you also can get the data back and re initialize your array.

delete(val) {

 this._message.delete({id: val})
.then((data)=>{
     this.messages.remove(this.messages.findIndex((message => message._id === val));
  });
}


问:
How can I watch an object created in a "with block"?
I have an no named object created in a "with block".

```<code>With Factory.CreateSomeObject()
    .SomeProp = someValue
    ...
End With
</code>```

My question is: how can I inspect the object when the debugger is in break mode?

答:
I think this is not possible, but you can use an additional line:

```<code>Dim someObj As Object = Factory.CreateSomeObject()

With someObj
    .SomeProp = someValue
End With
</code>```

With this solution you can inspect on the first line.

Some additional information on StackOverflow (similar question).

Body:
I have an no named object created in a "with block".

With Factory.CreateSomeObject()
    .SomeProp = someValue
    ...
End With

My question is: how can I inspect the object when the debugger is in break mode?

Body:
I think this is not possible, but you can use an additional line:

Dim someObj As Object = Factory.CreateSomeObject()

With someObj
    .SomeProp = someValue
End With

With this solution you can inspect on the first line.

Some additional information on StackOverflow (similar question).


问:
want to separate frontend and backend user in yii2
as there is only user table in yii2 advanced. so user can login to both frontend and backend with same credential . we want saperate it out.

so I created frontuser table ,with same structure as of user table.
then created its model using gii model generator

made it as common model/user.

here is frontend/model/frontuser

```<code><?php

namespace frontend\models;

use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;

/**
 * This is the model class for table "frontuser".
 *
 * @property integer $id
 * @property string $username
 * @property string $auth_key
 * @property string $password_hash
 * @property string $password_reset_token
 * @property string $email
 * @property integer $status
 * @property integer $created_at
 * @property integer $updated_at
 */
//class Frontuser extends \yii\db\ActiveRecord
class Frontuser extends ActiveRecord implements IdentityInterface
{
    /**
     * @inheritdoc
     */
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 10;
    public static function tableName()
    {
       return '{{%frontuser}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
       return [
            ['status', 'default', 'value' => self::STATUS_ACTIVE],
            ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
        ];
    }

    /**
     *  inheritdoc
     */
    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }

    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * Finds user by password reset token
     *
     * @param string $token password reset token
     * @return static|null
     */
    public static function findByPasswordResetToken($token)
    {
        if (!static::isPasswordResetTokenValid($token)) {
            return null;
        }

        return static::findOne([
            'password_reset_token' => $token,
            'status' => self::STATUS_ACTIVE,
        ]);
    }

    /**
     * Finds out if password reset token is valid
     *
     * @param string $token password reset token
     * @return bool
     */
    public static function isPasswordResetTokenValid($token)
    {
        if (empty($token)) {
            return false;
        }

        $timestamp = (int) substr($token, strrpos($token, '_') + 1);
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
        return $timestamp + $expire >= time();
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return bool if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    /**
     * Generates new password reset token
     */
    public function generatePasswordResetToken()
    {
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken()
    {
        $this->password_reset_token = null;
    }
}
</code>```

and in frontend/config/main.php

```<code><?php
$params = array_merge(
    require(__DIR__ . '/../../common/config/params.php'),
    require(__DIR__ . '/../../common/config/params-local.php'),
    require(__DIR__ . '/params.php'),
    require(__DIR__ . '/params-local.php')
);

return [
    'id' => 'app-frontend',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'controllerNamespace' => 'frontend\controllers',
    'components' => [
        'request' => [
            'csrfParam' => '_csrf-frontend',
        ],
        // 'user' => [
        //     'identityClass' => 'common\models\User',
        //     'enableAutoLogin' => true,
        //     'identityCookie' => ['name' => '_identity-frontend', 'httpOnly' => true],
        // ],
        'user' => [
                'class' => 'yii\web\User', // basic class
                'identityClass' => 'frontend\models\Frontuser', // your admin model
                'enableAutoLogin' => true,
                'loginUrl' => '/admin/frontend/login',
            ],
        'session' => [
            // this is the name of the session cookie used for login on the frontend
            'name' => 'advanced-frontend',
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'authManager' => [
            'class' => 'yii\rbac\DbManager', // or use 'yii\rbac\DbManager'
            'defaultRoles'=> ['guest'],
            ],
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
        /*
        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => [
            ],
        ],
        */
    ],
    'params' => $params,
];
</code>```

but still ,I sign up ,entry goes in user table ..
I want to use user table for backend user
and frontuser table for frontend user
how to do it?

答:
you can do this in two way :
first one is add field type in user table to separate admin and user
but in your way you should declare another component in web.php

```<code>'admin' => [
        'identityClass' => 'app\models\admin',
        'enableAutoLogin' => true,
        'idParam'         => '_admin'
    ],
'user' => [
        'identityClass' => 'app\models\User',
        'enableAutoLogin' => true,
        'idParam'         => '_user'
    ],
</code>```

and in access behaviour backend add this parametr

'user'  => Yii::$app->admin,

Body:
as there is only user table in yii2 advanced. so user can login to both frontend and backend with same credential . we want saperate it out.

so I created frontuser table ,with same structure as of user table.
then created its model using gii model generator

made it as common model/user.

here is frontend/model/frontuser

<?php

namespace frontend\models;

use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;

/**
 * This is the model class for table "frontuser".
 *
 * @property integer $id
 * @property string $username
 * @property string $auth_key
 * @property string $password_hash
 * @property string $password_reset_token
 * @property string $email
 * @property integer $status
 * @property integer $created_at
 * @property integer $updated_at
 */
//class Frontuser extends \yii\db\ActiveRecord
class Frontuser extends ActiveRecord implements IdentityInterface
{
    /**
     * @inheritdoc
     */
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 10;
    public static function tableName()
    {
       return '{{%frontuser}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
       return [
            ['status', 'default', 'value' => self::STATUS_ACTIVE],
            ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
        ];
    }

    /**
     *  inheritdoc
     */
    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }

    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * Finds user by password reset token
     *
     * @param string $token password reset token
     * @return static|null
     */
    public static function findByPasswordResetToken($token)
    {
        if (!static::isPasswordResetTokenValid($token)) {
            return null;
        }

        return static::findOne([
            'password_reset_token' => $token,
            'status' => self::STATUS_ACTIVE,
        ]);
    }

    /**
     * Finds out if password reset token is valid
     *
     * @param string $token password reset token
     * @return bool
     */
    public static function isPasswordResetTokenValid($token)
    {
        if (empty($token)) {
            return false;
        }

        $timestamp = (int) substr($token, strrpos($token, '_') + 1);
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
        return $timestamp + $expire >= time();
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return bool if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    /**
     * Generates new password reset token
     */
    public function generatePasswordResetToken()
    {
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken()
    {
        $this->password_reset_token = null;
    }
}

and in frontend/config/main.php

<?php
$params = array_merge(
    require(__DIR__ . '/../../common/config/params.php'),
    require(__DIR__ . '/../../common/config/params-local.php'),
    require(__DIR__ . '/params.php'),
    require(__DIR__ . '/params-local.php')
);

return [
    'id' => 'app-frontend',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'controllerNamespace' => 'frontend\controllers',
    'components' => [
        'request' => [
            'csrfParam' => '_csrf-frontend',
        ],
        // 'user' => [
        //     'identityClass' => 'common\models\User',
        //     'enableAutoLogin' => true,
        //     'identityCookie' => ['name' => '_identity-frontend', 'httpOnly' => true],
        // ],
        'user' => [
                'class' => 'yii\web\User', // basic class
                'identityClass' => 'frontend\models\Frontuser', // your admin model
                'enableAutoLogin' => true,
                'loginUrl' => '/admin/frontend/login',
            ],
        'session' => [
            // this is the name of the session cookie used for login on the frontend
            'name' => 'advanced-frontend',
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'authManager' => [
            'class' => 'yii\rbac\DbManager', // or use 'yii\rbac\DbManager'
            'defaultRoles'=> ['guest'],
            ],
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
        /*
        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => [
            ],
        ],
        */
    ],
    'params' => $params,
];

but still ,I sign up ,entry goes in user table ..
I want to use user table for backend user
and frontuser table for frontend user
how to do it?

Body:
you can do this in two way :
first one is add field type in user table to separate admin and user
but in your way you should declare another component in web.php

'admin' => [
        'identityClass' => 'app\models\admin',
        'enableAutoLogin' => true,
        'idParam'         => '_admin'
    ],
'user' => [
        'identityClass' => 'app\models\User',
        'enableAutoLogin' => true,
        'idParam'         => '_user'
    ],

and in access behaviour backend add this parametr

'user'  => Yii::$app->admin,


问:
Are there any good strategies when a functional test fails normally, but passes in the debugger?
I have a functional test which fails when I run it normally.  I have the ruby-debug gem installed, so I inserted a "debugger" line into the controller method and when I run the test it breaks on that line.  I would then step through the remainder of the function, but it got to the exit point and it was correct (and then the test passed).  After that I ran it again, and immediately when the debugger started I just hit "c" for continue.  The test passed.

Does anyone have some suggestions on how to approach a problem like this?  Are there some common mistakes that can lead to this situation?

答:
I'm not completely sure because I don't have access to the code you are testing. However, I once had a problem where there was data that took time outside of the controller. (For instance an ajax call on the page, or something using an event queue)
The debug just added enough of a delay that the data was there when I wanted to check it, but it wasn't there if the debugger wasn't included.

Would this sound like something going on in this test?


问:
SQL Server Management Studio 2012 - Export/Import data from/to table
I have table with more than 3 000 000 rows. I have try to export the data from it manually and with SQL Server Management Studio Export data functionality to Excel but I have met several problems:

when create .txt file manually copying and pasting the data (this is several times, because if you copy all rows from the SQL Server Management Studio it throws out of memory error) I am not able to open it with any text editor and to copy the rows;

the Export data to Excel do not work, because Excel do not support so many rows

Finally, with the Export data functionality I have created a .sql file, but it is 1.5 GB, and I am not able to open it in SQL Server Management Studio again.

Is there a way to import it with the Import data functionality, or other more clever way to make a backup of the information of my table and then to import it again if I need it?

Thanks in advance.

答:
Here a way of doing it without bcp:

EXPORT THE SCHEMA AND DATA IN A FILE

Use the ssms wizard
Database >> Tasks >> generate Scripts… >> Choose the table >> choose db model and schema

Save the SQL file (can be huge)

Transfer the SQL file on the other server

SPLIT THE DATA IN SEVERAL FILES

Use a program like textfilesplitter to split the file in smaller files and split in files of 10 000 lines (so each file is not too big)

Put all the files in the same folder, with nothing else

IMPORT THE DATA IN THE SECOND SERVER

Create a .bat file in the same folder, name execFiles.bat

You may need to check the table schema to disable the identity in the first file, you can add that after the import in finished.

This will execute all the files in the folder against the server and the database with, the –f define the Unicode text encoding should be used to handle the accents:

for %%G in (*.sql) do sqlcmd /S ServerName /d DatabaseName -E -i"%%G" -f 65001
pause


问:
How to redirect the page based on login success and using single form in multiple condition
Here I have two button one is login button and second one is go to rent.php .my requirement is if i am clicking login button means i want to show login form in modal,after that user enter their credential and also succfully logged in means i want to redirect the home page(index.php). Now i coming to main point suppose i am clicking go to rent.php means ,First  i have to check this user is already logged in or not , suppose logged in means directly i have to redirect the rent.php.Suppose he is not yet logged means i have to show the login form in modal after that user will enter the email & password suppose successfully logged in means now i have to redirect the rent.php ,How can do this please any one update my answer.

function checkLogin(argument) {
   $('#modalForm').modal('show');
  }

  // Login Check

   $(document).ready(function(){
             $("#loginbtn").click(function(e){
               e.preventDefault();
                    var loginEmail = $('#loginEmail').val();
                    var password = $('#password').val();

                      $.ajax({
                       type:'POST',
                       url :"test_session.php",
                       data: {email: loginEmail, password: password},
                       success: function(response) {
                        if(response['status'] =='success'){
                          console.log(response);
                         window.location.href = "index.php";
                        }
                      else{

                           $("#update_Failed").show();
                        }
                         },
                     error:function(exception){
                     alert('Exeption:'+exception);
                    }
                    });
             });
           });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><?php
session_start();
?>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
 <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<!-- Modal -->
<div class="modal fade" id="modalForm" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <!-- Modal Header -->
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">
                    <span aria-hidden="true">×</span>
                    <span class="sr-only">Close</span>
                </button>
                <h4 class="modal-title" id="myModalLabel">Login Form</h4>
            </div>

            <!-- Modal Body -->
            <div class="modal-body">
                <p class="statusMsg"></p>
               <form id="loginForm">
                  <div class="form-group" id="loginmobile">
                      <label for="email">Email address or Mobile:</label>
                          <input type="text" class="form-control stl" name="email" id="loginEmail" required="" data-msg-required="Please Enter Valid Email or Mobile no." aria-required="true">
                      </div>
                          <div class="form-group" id="loginmobile1"  style="display:none">
                            <label for="email"> Mobile:</label>
                              <input type="number" class="form-control stl" name="email1" id="loginMobile" required="" data-msg-required="Please Enter  Mobile no." aria-required="true">
                            </div>

                            <div class="form-group" id="otppwd">
                            <!-- <label for="pwd">Password Or OTP:</label> -->
                              <label for="pwd">Password :</label>
                              <input type="password" class="form-control stl" name="password" id="password" required="" data-msg-required="Please Enter Password" aria-required="true">
                            </div>

                             </br>
                            <div style="text-align: center;">
                            <button type="submit" id="loginbtn" class="btn btn-default contact_us_btn rentListLogin" >SUBMIT</button>

                            </div>

                              <div class="alert alert-danger" id="update_Failed" style="display:none;margin-top: 5%">
                              <br>
                                    <strong>Username or Password is Incorrect</strong>
                            </div><br>
                      </form>
            </div>

        </div>
    </div>
</div>

Login
<?php
if(!empty($_SESSION['userName'])){
?>
Go to rent.php
<?php
}
else
{
?>
go to rent.php
 <?php
}
?></code>```

答:
You can check set a variable to identify if the user is logged in or not. Then using that decide whether to show log in modal or go to rent.php page.</p>

```<code><script>
<?php
if(!empty($_SESSION['userName'])){
    var loggedIn = 1;
}
else {
    var loggedIn = 0;
}
?>

function checkLogin(argument) {
    if(loggedIn === 0) {
        $('#modalForm').modal('show');
    }
    else {
        window.location.href = "rent.php";
    }
}
 // Login Check
</script>
</code>```

Body:
Here I have two button one is login button and second one is go to rent.php .my requirement is if i am clicking login button means i want to show login form in modal,after that user enter their credential and also succfully logged in means i want to redirect the home page(index.php). Now i coming to main point suppose i am clicking go to rent.php means ,First  i have to check this user is already logged in or not , suppose logged in means directly i have to redirect the rent.php.Suppose he is not yet logged means i have to show the login form in modal after that user will enter the email & password suppose successfully logged in means now i have to redirect the rent.php ,How can do this please any one update my answer.

function checkLogin(argument) {
   $('#modalForm').modal('show');
  }

  // Login Check

   $(document).ready(function(){
             $("#loginbtn").click(function(e){
               e.preventDefault();
                    var loginEmail = $('#loginEmail').val();
                    var password = $('#password').val();

                      $.ajax({
                       type:'POST',
                       url :"test_session.php",
                       data: {email: loginEmail, password: password},
                       success: function(response) {
                        if(response['status'] =='success'){
                          console.log(response);
                         window.location.href = "index.php";
                        }
                      else{

                           $("#update_Failed").show();
                        }
                         },
                     error:function(exception){
                     alert('Exeption:'+exception);
                    }
                    });
             });
           });

<?php
session_start();
?>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

                <button type="button" class="close" data-dismiss="modal">
                    ×
                    Close
                </button>

Login Form

               <form id="loginForm">

                      Email address or Mobile:
                          <input type="text" class="form-control stl" name="email" id="loginEmail" required="" data-msg-required="Please Enter Valid Email or Mobile no." aria-required="true">

                             Mobile:
                              <input type="number" class="form-control stl" name="email1" id="loginMobile" required="" data-msg-required="Please Enter  Mobile no." aria-required="true">

                              Password :
                              <input type="password" class="form-control stl" name="password" id="password" required="" data-msg-required="Please Enter Password" aria-required="true">

                            <button type="submit" id="loginbtn" class="btn btn-default contact_us_btn rentListLogin" >SUBMIT</button>

                                    Username or Password is Incorrect

                      </form>

Login
<?php
if(!empty($_SESSION['userName'])){
?>
Go to rent.php
<?php
}
else
{
?>
go to rent.php
 <?php
}
?>

Body:
You can check set a variable to identify if the user is logged in or not. Then using that decide whether to show log in modal or go to rent.php page.

<script>
<?php
if(!empty($_SESSION['userName'])){
    var loggedIn = 1;
}
else {
    var loggedIn = 0;
}
?>

function checkLogin(argument) {
    if(loggedIn === 0) {
        $('#modalForm').modal('show');
    }
    else {
        window.location.href = "rent.php";
    }
}
 // Login Check
</script>


Title: Python/Pandas - check if column's values is the same by another column values

Body:
I have DataFrame like this:

        product_id          dt  products_qty  stock_qty
0          8225  2017-10-16         12.000    13.000
1          8280  2017-10-16         0.000     11.000
2          8225  2017-10-17         0.000     41.000
3          8280  2017-10-17         7.134     64.698
4          8225  2017-10-18         1.000      8.000
5          8280  2017-10-18         2.728     27.417
6          8225  2017-10-19         0.000     41.000
7          8280  2017-10-19         1.000     -2.000
8          8225  2017-10-20         2.000     -7.000
9          8280  2017-10-20         1.000     25.000
10         8225  2017-10-21         0.000     41.000
11         8280  2017-10-21         0.000     11.000

I have to get all rows where products_qty equals 0 and stock_qty values are the same. So in this case I shoul get DataFrame like this:

            product_id          dt  products_qty  stock_qty
    0          8280  2017-10-16         0.000     11.000
    2          8225  2017-10-17         0.000     41.000
    6          8225  2017-10-19         0.000     41.000
    10         8225  2017-10-21         0.000     41.000
    11         8280  2017-10-21         0.000     11.000

Thanks for help!

Body:
Use boolean indexing with chained conditions - second by duplicated with parameter keep=False for check all duplicates:

print (df)
    product_id          dt  products_qty  stock_qty
0      2948225  2017-10-16        12.000     13.000
1      2948280  2017-10-16         0.000     11.000
2      2948225  2017-10-17         0.000     41.000
3      2948280  2017-10-17         7.134     64.698
4      2948225  2017-10-18         1.000      8.000
5      2948280  2017-10-18         2.728     27.417
6      2948225  2017-10-19         0.000     41.000
7      2948280  2017-10-19         1.000     -2.000
8      2948225  2017-10-20         2.000     -7.000
9      2948280  2017-10-20         1.000     25.000
10     2948225  2017-10-21         0.000     13.000 <- changed to 13
11     2948280  2017-10-21         0.000     11.000

#if need check duplicates in all column data
df1 = df[(df['products_qty'] == 0) & (df['stock_qty'].duplicated(keep=False))]
print (df1)
    product_id          dt  products_qty  stock_qty
1      2948280  2017-10-16           0.0       11.0
2      2948225  2017-10-17           0.0       41.0
6      2948225  2017-10-19           0.0       41.0
10     2948225  2017-10-21           0.0       13.0 <- because dupe with first row
11     2948280  2017-10-21           0.0       11.0

#if need check only duplicates in rows with 0 in products_qty

df2 = (df[df.loc[df['products_qty'] == 0, 'stock_qty']
           .duplicated(keep=False).reindex(df.index, fill_value=False)])
print (df2)
    product_id          dt  products_qty  stock_qty
1      2948280  2017-10-16           0.0       11.0
2      2948225  2017-10-17           0.0       41.0
6      2948225  2017-10-19           0.0       41.0
11     2948280  2017-10-21           0.0       11.0

df2 = df[df['products_qty'] == 0]
df2 = df2[df2['stock_qty'].duplicated(keep=False)]
print (df2)
    product_id          dt  products_qty  stock_qty
1      2948280  2017-10-16           0.0       11.0
2      2948225  2017-10-17           0.0       41.0
6      2948225  2017-10-19           0.0       41.0
11     2948280  2017-10-21           0.0       11.0


问:
How to use conditions in .gitlab-ci.yml variables?
I want to know, if it's possible to set custom Gitlab CI variable from if-else condition statement.

In my .gitlab-ci.yml file I have the following:

```<code>variables:
    PROJECT_VERSION: (if [ "${CI_COMMIT_TAG}" == "" ]; then "${CI_COMMIT_REF_NAME}-${CI_PIPELINE_ID}"; else ${CI_COMMIT_TAG}; fi);

Trying to set project version:
    image: php:7.1-cli
    stage: test
    script:
        # this echoes correct string (eg. "master-2794")
        - (if [ "${CI_COMMIT_TAG}" == "" ]; then echo "${CI_COMMIT_REF_NAME}-${CI_PIPELINE_ID}"; else echo ${CI_COMMIT_TAG}; fi);
        # this echoes something like "(if [ "" == "" ]; then "master-2794"; else ; fi);"
        - echo $PROJECT_VERSION
</code>```

Can this be done? If so, what have I missed? Thanks

答:
This is expected behavior.

CI_COMMIT_TAG is only set to a value in a GitLab job. From https://docs.gitlab.com/ee/ci/variables/README.html

CI_COMMIT_TAG - The commit tag name. Present only when building tags.

Therefore in the variables section CI_COMMIT_TAG is not defined, hence equals to "".

So if you want to use CI_COMMIT_TAG use in job where tags are defined. See https://docs.gitlab.com/ee/ci/yaml/README.html#tags

Body:
I want to know, if it's possible to set custom Gitlab CI variable from if-else condition statement.

In my .gitlab-ci.yml file I have the following:

variables:
    PROJECT_VERSION: (if [ "${CI_COMMIT_TAG}" == "" ]; then "${CI_COMMIT_REF_NAME}-${CI_PIPELINE_ID}"; else ${CI_COMMIT_TAG}; fi);

Trying to set project version:
    image: php:7.1-cli
    stage: test
    script:
        # this echoes correct string (eg. "master-2794")
        - (if [ "${CI_COMMIT_TAG}" == "" ]; then echo "${CI_COMMIT_REF_NAME}-${CI_PIPELINE_ID}"; else echo ${CI_COMMIT_TAG}; fi);
        # this echoes something like "(if [ "" == "" ]; then "master-2794"; else ; fi);"
        - echo $PROJECT_VERSION

Can this be done? If so, what have I missed? Thanks

ContentLicense: CC BY-SA 4.0


问:
Issues with updating my app version in gradle file
So I was using API 25 which is Nougat version, and I wanted to update my app to Version ApI27 which is newly out these days. but whenever I update to 27.0.1, this Error:

```<code>"Error:Failed to resolve: com.android.support:appcompat-v7.27.0.1"
</code>```

keeps occurring. I don't know what I've done wrong and I'm struggling all day to find the resolution. Thank you very much for your time and assistance in this matter.

Oh, and I'm sure that I've downloaded SDK Versions and all the files that are needed already in SDK manager.

My Gradle File(Module App):

```<code>apply plugin: 'com.android.application'

android {
compileSdkVersion 27
buildToolsVersion '27.0.1'
defaultConfig {
    applicationId "org.poream.dejaview"
    minSdkVersion 15
    targetSdkVersion 27
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
    }
}
}

dependencies {

implementation 'com.google.firebase:firebase-storage:11.6.0'
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2',
{
    exclude group: 'com.android.support', module: 'support-annotations'
})

compile 'com.android.support:design:27.0.1'
compile 'com.google.android.gms:play-services-maps:11.6.0'
compile 'com.android.support:appcompat-v7.27.0.1'
compile 'com.android.support:design:27.0.1'
compile 'com.google.android.gms:play-services-maps:11.6.0'
compile 'com.android.support:cardview-v7:27.0.1'
compile 'com.google.android.gms:play-services-location:11.6.0'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.firebase:firebase-core:11.6.0'
compile 'com.google.firebase:firebase-database:11.6.0'
compile 'com.google.firebase:firebase-crash:11.6.0'
compile 'com.google.firebase:firebase-auth:11.6.0'
compile 'com.android.support:support-v4:27.0.1'
compile 'com.android.support:recyclerview-v7:27.0.1'
compile 'com.google.android.gms:play-services-auth:11.6.0'
testCompile 'junit:junit:4.12'
}

apply plugin: 'com.google.gms.google-services'
</code>```

My Gradle File(Project):

```<code>// Top-level build file where you can add configuration options common to
all sub-projects/modules.

buildscript {
repositories {

    mavenCentral()
    jcenter()
    google()
}
dependencies {

    classpath 'com.android.tools.build:gradle:3.0.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
    classpath 'com.google.gms:google-services:3.1.0'
}
}

allprojects {
repositories {
    jcenter()
    google()
}
}

task clean(type: Delete) {
delete rootProject.buildDir
}
</code>```

答:
Add maven { url 'https://maven.google.com/' } line in your project level build.gradle

```<code>   repositories {
        maven { url 'https://maven.google.com/' }
    }
</code>```

Body:
So I was using API 25 which is Nougat version, and I wanted to update my app to Version ApI27 which is newly out these days. but whenever I update to 27.0.1, this Error:

"Error:Failed to resolve: com.android.support:appcompat-v7.27.0.1"

keeps occurring. I don't know what I've done wrong and I'm struggling all day to find the resolution. Thank you very much for your time and assistance in this matter.

Oh, and I'm sure that I've downloaded SDK Versions and all the files that are needed already in SDK manager.

My Gradle File(Module App):

apply plugin: 'com.android.application'

android {
compileSdkVersion 27
buildToolsVersion '27.0.1'
defaultConfig {
    applicationId "org.poream.dejaview"
    minSdkVersion 15
    targetSdkVersion 27
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
    }
}
}

dependencies {

implementation 'com.google.firebase:firebase-storage:11.6.0'
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2',
{
    exclude group: 'com.android.support', module: 'support-annotations'
})

compile 'com.android.support:design:27.0.1'
compile 'com.google.android.gms:play-services-maps:11.6.0'
compile 'com.android.support:appcompat-v7.27.0.1'
compile 'com.android.support:design:27.0.1'
compile 'com.google.android.gms:play-services-maps:11.6.0'
compile 'com.android.support:cardview-v7:27.0.1'
compile 'com.google.android.gms:play-services-location:11.6.0'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.firebase:firebase-core:11.6.0'
compile 'com.google.firebase:firebase-database:11.6.0'
compile 'com.google.firebase:firebase-crash:11.6.0'
compile 'com.google.firebase:firebase-auth:11.6.0'
compile 'com.android.support:support-v4:27.0.1'
compile 'com.android.support:recyclerview-v7:27.0.1'
compile 'com.google.android.gms:play-services-auth:11.6.0'
testCompile 'junit:junit:4.12'
}

apply plugin: 'com.google.gms.google-services'

My Gradle File(Project):

// Top-level build file where you can add configuration options common to
all sub-projects/modules.

buildscript {
repositories {

    mavenCentral()
    jcenter()
    google()
}
dependencies {

    classpath 'com.android.tools.build:gradle:3.0.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
    classpath 'com.google.gms:google-services:3.1.0'
}
}

allprojects {
repositories {
    jcenter()
    google()
}
}

task clean(type: Delete) {
delete rootProject.buildDir
}

Body:
Add maven { url 'https://maven.google.com/' } line in your project level build.gradle

   repositories {
        maven { url 'https://maven.google.com/' }
    }


问:
No file was sent to SAP Leonardo Image Feature Extraction API using FormData
I'm testing SAP Leonardo Image Feature Extraction API (https://sandbox.api.sap.com/ml/featureextraction/inference_sync). I have the base64 string of the image and I want to transform it to a file object and zip it, then to send the zipped image file to this API using XMLHttpRequest. But the response text is "Service requires a list of (zipped) images".

I attach my HTTP request header and parameters in below screenshots.

Although we see a messy code in parameters, the zipped file Download here is created successfully.

If you cannot download the zipped file, please refer to the screenshot below.

Everything seems to be fine. However, the response text is as below with status 400.

My javascript code is shown below. What is wrong? It drives me crazy...

dataURItoBlob: function(dataURI, fileName) {
 //convert base64/URLEncoded data component to raw binary data held in a string
 var byteString;
 if (dataURI.split(',')[0].indexOf('base64') >= 0)
  byteString = atob(dataURI.split(',')[1]);
 else
  byteString = unescape(dataURI.split(',')[1]);

 //separate out the mime component
 var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

 //write the bytes of the string to a typed array
 var ia = new Uint8Array(byteString.length);
 for (var i = 0; i < byteString.length; i++) {
  ia[i] = byteString.charCodeAt(i);
 }

 var blob = new Blob([ia], {encoding:"UTF-8",type:mimeString});
 //A Blob() is almost a File() - it's just missing the two properties below which we will add
 blob.lastModifiedDate = new Date();
 blob.name = fileName + '.' + mimeString.split('/')[1];

 return blob;
},

onSubmit: function(oEvent) {
 var oImage = this.getView().byId('myImage');
 //oImage.getSrc() : 'data:image/png;base64,iVBORw0KGgo...'
 var imageFile = this.dataURItoBlob(oImage.getSrc(), 'myImage');
 var zip = new JSZip();
 zip.file(imageFile.name, imageFile);

 zip.generateAsync({
  type:"blob",
  compression: 'DEFLATE', // force a compression for this file
  compressionOptions: {
   level: 6,
     },
 }).then(function(content) {
  //saveAs(content, "hello.zip");
  // start the busy indicator
  var oBusyIndicator = new sap.m.BusyDialog();
  oBusyIndicator.open();

  var formData = new FormData();
  formData.append('files', content, 'myImage.zip');

  var xhr = new XMLHttpRequest();
  xhr.withCredentials = false;

  xhr.addEventListener("readystatechange", function () {
   if (this.readyState === this.DONE) {
    oBusyIndicator.close();
    //navigator.notification.alert(this.responseText);
    console.log(this.responseText);
   }
  });

  //setting request method
  //API endpoint for API sandbox
  //Destionation '/SANDBOX_API' in HCP is configured as 'https://sandbox.api.sap.com'
  var api = "/SANDBOX_API/ml/featureextraction/inference_sync";
  xhr.open("POST", api);

  //adding request headers
  xhr.setRequestHeader("Content-Type", "multipart/form-data");
  xhr.setRequestHeader("Accept", "application/json");
  //API Key for API Sandbox
  xhr.setRequestHeader("APIKey", "yQd5Oy785NkAIob6g1eNwctBg4m1LGQS");

  //sending request
  xhr.send(formData);
 });

},```

答:
I fix this issue by myself. I put my solution just for others' information. It's very easy and only below code needs to be removed before sending request. I have no idea why. Please suggest if you know the reason. Thanks in advance!

xhr.setRequestHeader("Content-Type", "multipart/form-data");```

Best Regards,
Shelwin Wei

Body:
I fix this issue by myself. I put my solution just for others' information. It's very easy and only below code needs to be removed before sending request. I have no idea why. Please suggest if you know the reason. Thanks in advance!

xhr.setRequestHeader("Content-Type", "multipart/form-data");

Best Regards,
Shelwin Wei


问:
Error in password decryption
I have to store the password field in SQL Server database in an encrypted format and I have to decrypt it while the user is logging into the system. The encryption part is working fine. But I am getting the error in decryption part as "Invalid length for a Base-64 char array" at the line

```<code>byte[] todecode_byte = Convert.FromBase64String(encryptpwd);
</code>```

of decryption module.

```<code>private string Encryptdata(string password)
{
        string encryptpwd = string.Empty;
        byte[] encode = new byte[password.Length];
        encode = Encoding.UTF8.GetBytes(password);
        encryptpwd = Convert.ToBase64String(encode);
        return encryptpwd;
}

private string Decryptdata(string encryptpwd)
{
        string decryptpwd = string.Empty;
        UTF8Encoding encodepwd = new UTF8Encoding();
        Decoder Decode = encodepwd.GetDecoder();
        byte[] todecode_byte = Convert.FromBase64String(encryptpwd); //here I am getting error as "Invalid length for a Base-64 char array"
        int charCount = Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
        char[] decoded_char = new char[charCount];
        Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
        decryptpwd = new String(decoded_char);
        return decryptpwd;
}
</code>```

Input Data: prabu

Encrypted Data: cHJhYnU=

答:
```<code>private string Decrypt(string cipherText)
        {
            string EncryptionKey = "MAKV2SPBNI99212";
            byte[] cipherBytes = Convert.FromBase64String(cipherText);
            using (Aes encryptor = Aes.Create())
            {
                Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                encryptor.Key = pdb.GetBytes(32);
                encryptor.IV = pdb.GetBytes(16);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(cipherBytes, 0, cipherBytes.Length);
                        cs.Close();
                    }
                    cipherText = Encoding.Unicode.GetString(ms.ToArray());
                }
            }
            return cipherText;
        }
</code>```

Title: Error in password decryption

Body:
I have to store the password field in SQL Server database in an encrypted format and I have to decrypt it while the user is logging into the system. The encryption part is working fine. But I am getting the error in decryption part as "Invalid length for a Base-64 char array" at the line

byte[] todecode_byte = Convert.FromBase64String(encryptpwd);

of decryption module.

private string Encryptdata(string password)
{
        string encryptpwd = string.Empty;
        byte[] encode = new byte[password.Length];
        encode = Encoding.UTF8.GetBytes(password);
        encryptpwd = Convert.ToBase64String(encode);
        return encryptpwd;
}

private string Decryptdata(string encryptpwd)
{
        string decryptpwd = string.Empty;
        UTF8Encoding encodepwd = new UTF8Encoding();
        Decoder Decode = encodepwd.GetDecoder();
        byte[] todecode_byte = Convert.FromBase64String(encryptpwd); //here I am getting error as "Invalid length for a Base-64 char array"
        int charCount = Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
        char[] decoded_char = new char[charCount];
        Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
        decryptpwd = new String(decoded_char);
        return decryptpwd;
}

Input Data: prabu

Encrypted Data: cHJhYnU=


问:
extract data from a json file in python
I have been try to find the best way to search a particular value and extract the data. I am new and hope i have worded this correctly. </p>

```<code>    {"family": {
    "name": "Mary",
    "age": "32",
    "sex": "female",
    "kids": [
      {
        "name": "jim",
        "age": "10",
        "sex": "male",
        "dob_year": "2007",
        "ssn": "123-23-1234"
      },
      {
        "name": "jill",
        "age": "6",
        "sex": "female",
        "dob_year": "2011",
        "ssn": "123-23-1235"
      }]}}
</code>```

<p>if i needed to search "ssn" containing "1234" and return the "name" "jim" what would be the best way to go about achieving this?  </p>

答:
say you load your json text into js variable. kn = next((sj['name'] for sj in js['family']['kids'] if ('1234' in sj['ssn'])), None)

kn will give you the name if criteria found, otherwise it will be None. And of course you can change the condition into variable. Hope it helps.

Title: extract data from a json file in python

Body:
I have been try to find the best way to search a particular value and extract the data. I am new and hope i have worded this correctly.

    {"family": {
    "name": "Mary",
    "age": "32",
    "sex": "female",
    "kids": [
      {
        "name": "jim",
        "age": "10",
        "sex": "male",
        "dob_year": "2007",
        "ssn": "123-23-1234"
      },
      {
        "name": "jill",
        "age": "6",
        "sex": "female",
        "dob_year": "2011",
        "ssn": "123-23-1235"
      }]}}

if i needed to search "ssn" containing "1234" and return the "name" "jim" what would be the best way to go about achieving this?


问:
How to randomize the size of faces on a mesh in three.js?
I recently started experimenting in three.js, and have been wondering if there is a way to randomize the size of the faces in a mesh created from one of their existing geometries.

Three.js is excellent for low-poly work, but the symmetry of the generated meshes ruin the effects somewhat-- I'm looking to find a way to give each face a slightly different size and perhaps jitter/rotation as well, to give it a more "handcrafted" look, so to speak.

I thought there might be a way to do it with math.random, but I'm a javascript newbie and am not sure how to go about using it.

This is the code for the object I want to give a less uniform appearance:

```<code>function createObject() {
    var geometry = new THREE.SphereGeometry(70, 31, 17);
    var material = new THREE.MeshPhongMaterial({
        color:Colors.blue,
        shading:THREE.FlatShading
    });
    var sphere = new THREE.Mesh(geometry, material);
    sphere.position.set(45,100,0);
    sphere.castShadow = true;
    sphere.receiveShadow = true;
    scene.add(sphere);
}
</code>```

Here's a fiddle with the rest of the code, but for whatever reason, although the code works locally, I can't get it to run in the browser. Still, it's there if you want to look at it. https://jsfiddle.net/redheadedmandy/f8fy4Lg8/1/

If anyone has a suggestion for how one might go about roughing up the uniformity of a three.js mesh, I would much appreciate it!

答:
There's the jsfiddle example, based on yours. Well, mostly it's your example, just slightly modified, uses the latest version of Three.js.

As an option for "roughing", you can do it like that:

```<code>  var geometry = new THREE.SphereGeometry(70, 31, 17);

  geometry.vertices.forEach(v => {
    v.x += THREE.Math.randFloatSpread(2);
    v.y += THREE.Math.randFloatSpread(2);
    v.z += THREE.Math.randFloatSpread(2);
  });

  geometry.computeFaceNormals(); // don't forget to do it, when you change vertices
</code>```

Actually, there are many ways of how to change coordinates of vertices in a geometry. Creativity is up to you.

Body:
I recently started experimenting in three.js, and have been wondering if there is a way to randomize the size of the faces in a mesh created from one of their existing geometries.

Three.js is excellent for low-poly work, but the symmetry of the generated meshes ruin the effects somewhat-- I'm looking to find a way to give each face a slightly different size and perhaps jitter/rotation as well, to give it a more "handcrafted" look, so to speak.

I thought there might be a way to do it with math.random, but I'm a javascript newbie and am not sure how to go about using it.

This is the code for the object I want to give a less uniform appearance:

function createObject() {
    var geometry = new THREE.SphereGeometry(70, 31, 17);
    var material = new THREE.MeshPhongMaterial({
        color:Colors.blue,
        shading:THREE.FlatShading
    });
    var sphere = new THREE.Mesh(geometry, material);
    sphere.position.set(45,100,0);
    sphere.castShadow = true;
    sphere.receiveShadow = true;
    scene.add(sphere);
}

Here's a fiddle with the rest of the code, but for whatever reason, although the code works locally, I can't get it to run in the browser. Still, it's there if you want to look at it. https://jsfiddle.net/redheadedmandy/f8fy4Lg8/1/

If anyone has a suggestion for how one might go about roughing up the uniformity of a three.js mesh, I would much appreciate it!

Body:
There's the jsfiddle example, based on yours. Well, mostly it's your example, just slightly modified, uses the latest version of Three.js.

As an option for "roughing", you can do it like that:

  var geometry = new THREE.SphereGeometry(70, 31, 17);

  geometry.vertices.forEach(v => {
    v.x += THREE.Math.randFloatSpread(2);
    v.y += THREE.Math.randFloatSpread(2);
    v.z += THREE.Math.randFloatSpread(2);
  });

  geometry.computeFaceNormals(); // don't forget to do it, when you change vertices

Actually, there are many ways of how to change coordinates of vertices in a geometry. Creativity is up to you.


问:
Difference between x.toString() and x+""
Back in college one of my profs. taught us to just do x + "" as a quick conversion from basic types to strings.

I don't remember which class it was in I had him for some Java and C++ courses(I haven't used either for some time now), but I use it in C#/.Net now which is what I'm primarily developing in lately.

Is there an advantage to using .toString() over +"" for basic types such at int, decimal, float...?
What cases would .toString() be better?

Note:I was shown .toString() as well, that prof just recommended +"" because it was shorter and I have just done that since then without questioning it.

答:
In C# I would completely disregard this advice in favor of something more declarative such as using .ToString directly.

The only potential advantage this syntax provides you is it will create an empty string if x is null.  I would favor an extension method if this is considered an advantage in your code.

```<code>public static string NullSafeToString<T>(this T value) where T : class {
  return value == null ? "" : value.ToString();
}
</code>```

The other reason to avoid this is because it can create precedence confusion.  For example do you know exactly what the value of z is in the following scenario without the use of reference materials?

```<code>int x = 42;
int y = 15;
string z = x + y + "";
</code>```

Now same question with the following

```<code>int x = 42;
int y = 15;
string z = x + y.ToString();
</code>```

The latter is more likely to be understood at a glance by the average developer who hasn't taken the time to memory C# operator precedence.  Hence I would prefer it because it has a lesser chance of being misunderstood.

Body:
In C# I would completely disregard this advice in favor of something more declarative such as using .ToString directly.

The only potential advantage this syntax provides you is it will create an empty string if x is null.  I would favor an extension method if this is considered an advantage in your code.

public static string NullSafeToString<T>(this T value) where T : class {
  return value == null ? "" : value.ToString();
}

The other reason to avoid this is because it can create precedence confusion.  For example do you know exactly what the value of z is in the following scenario without the use of reference materials?

int x = 42;
int y = 15;
string z = x + y + "";

Now same question with the following

int x = 42;
int y = 15;
string z = x + y.ToString();

The latter is more likely to be understood at a glance by the average developer who hasn't taken the time to memory C# operator precedence.  Hence I would prefer it because it has a lesser chance of being misunderstood.


问:
django channels: WebSocket is closed before the connection is established
I am pretty new in django channels. I read this tutorial to create a realtime chat application, but I have this error

in Chrome:

WebSocket connection to 'ws://127.0.0.1:8000/chat/stream/' failed: WebSocket is
closed before the connection is established.

in Firefox:

Firefox can't establish a connection to the server at ws://127.0.0.1:8001/chat/stream/.

The connection to ws://127.0.0.1:8001/chat/stream/ was interrupted while the page was loading.

Please help me. Thanks a lot.

答:
You may miss this in your code:

```<code>message.reply_channel.send({"accept": True})
</code>```

in ws_connect

Body:
You may miss this in your code:

message.reply_channel.send({"accept": True})

in ws_connect


问:
How to get location name without showing map on screen?
I want location name in textfield without showing map on screen. I have implemented map by using google map API. And it is showing me the location on map.All i want is to save location in a Textfield without showing map.  </p>

答:
You can get the address from the Latitude and Longitude you've previously got from the map with Geocoder:

```<code>// 1 means only get one address.
List<Address> addresses = Geocoder.getFromLocation(latitude, longitude, 1);
</code>```

If you don't want to use the map at all, you can use Google Android Place Autocomplete or use Web Place Autocomplete.

For Web Place Autocomplete, you need to handle the result manually.

Body:
You can get the address from the Latitude and Longitude you've previously got from the map with Geocoder:

// 1 means only get one address.
List<Address> addresses = Geocoder.getFromLocation(latitude, longitude, 1);

If you don't want to use the map at all, you can use Google Android Place Autocomplete or use Web Place Autocomplete.

For Web Place Autocomplete, you need to handle the result manually.


问:
What does "~[]" do?
I saw the following line of code here .

```<code>puts("sigprocmask(SIG_UNBLOCK, ~[], []) = 0");
</code>```

I don't understand, what does empty array script([]) do?

Also, What is the purpose of ~[] in C?

答:
The reference say's :

On the other hand, bit-sets are also shown using square brackets but
  set elements are separated only by a space. Here is the shell
  preparing to execute an external command:

```<code>sigprocmask(SIG_BLOCK, [CHLD TTOU], []) = 0
</code>```

Here the second argument is a bit-set of two signals, SIGCHLD and
  SIGTTOU. In some cases the bit-set is so full that printing out the
  unset elements is more valuable. In that case, the bit-set is prefixed
  by a tilde like this:

```<code>sigprocmask(SIG_UNBLOCK, ~[], NULL) = 0
</code>```

Here the second argument represents the full set of all signals.

Title: What does "~[]" do?

Body:
I saw the following line of code here .

puts("sigprocmask(SIG_UNBLOCK, ~[], []) = 0");

I don't understand, what does empty array script([]) do?

Also, What is the purpose of ~[] in C?

Body:
The reference say's :

On the other hand, bit-sets are also shown using square brackets but
  set elements are separated only by a space. Here is the shell
  preparing to execute an external command:

sigprocmask(SIG_BLOCK, [CHLD TTOU], []) = 0

Here the second argument is a bit-set of two signals, SIGCHLD and
  SIGTTOU. In some cases the bit-set is so full that printing out the
  unset elements is more valuable. In that case, the bit-set is prefixed
  by a tilde like this:

sigprocmask(SIG_UNBLOCK, ~[], NULL) = 0

Here the second argument represents the full set of all signals.


问:
Can't set focus on first item of ListBox
I can't set focus on first item of my ListBox. ListBox has some collection bound. It looks like, that first everything in code-behind doing its stuff then there is control initializing so I would have always -1 as SelectedIndex.

XAML

```<code><Window x:Class="Labels.Szablony"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:Labels"
    mc:Ignorable="d"
    Title="Labels" Height="350" Width="250" WindowStartupLocation="CenterScreen"
    ResizeMode="CanMinimize" KeyDown="Window_KeyDown" Background="#FFF6A300" >
<Window.DataContext>
    <local:LabelGridViewModel/>
</Window.DataContext>
<ScrollViewer VerticalScrollBarVisibility="Hidden" VerticalContentAlignment="Center"
              VerticalAlignment="Center" Background="#FFF6A300">
    <Grid Background="#FFF6A300" Name="labelGrid">
        <ListBox x:Name="SzablonyBox" ItemsSource="{Binding LabelsCollection, IsAsync=True}"
              HorizontalAlignment="Center" VerticalAlignment="Top"
             MinWidth="100" MinHeight="100" BorderBrush="{x:Null}"
             Background="{x:Null}" TextSearch.Text="BLABLAB"
             TextSearch.TextPath="Name" IsTextSearchEnabled="True"
                 VerticalContentAlignment="Center" Margin="0 25 0 0"
                 Width="250" HorizontalContentAlignment="Center">
            <ListBox.ItemContainerStyle>
                <Style TargetType="{x:Type ListBoxItem}">
                    <EventSetter Event="PreviewKeyDown"
                                 Handler="ListBoxItem_PreviewKeyDown"/>
                </Style>
            </ListBox.ItemContainerStyle>
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <DockPanel Width="214">
                        <TextBlock Text="{Binding Name}"
                               FontSize="12" Height="35"
                               VerticalAlignment="Center"
                               HorizontalAlignment="Center"
                               Width="250"
                               TextAlignment="Center"/>
                    </DockPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
        <TextBox x:Name="InputText"
                 Text="{Binding Path=Filter, UpdateSourceTrigger=PropertyChanged}"
                 HorizontalAlignment="Center" Height="22" TextWrapping="Wrap"
                 VerticalAlignment="Top" Width="250" Background="#FFF6A300"
                 IsEnabled="False" BorderBrush="#FFF6A300"
                 VerticalContentAlignment="Center"
                 HorizontalContentAlignment="Center"
                 Foreground="Black" SelectionBrush="{x:Null}"/>
    </Grid>
</ScrollViewer>
</code>```

What i'm trying to do looks like:

```<code>public Labels()
{
    InitializeComponent();

    LabelsBox.Focus();
    LabelsBox.SelectedIndex = 0;

    var item = LabelsBox.ItemContainerGenerator.ContainerFromIndex(0) as ListBoxItem;

    item.Focus();
}
</code>```

Of course there is an exception, because item is null. Like I said SelectedIndex is always -1. What am I doing wrong ?

答:
The ItemsSource Binding is asynchronous, so there are certainly not yet any items available while the constructor is running.

Change the Binding to be synchronous, i.e. the default behavior:

```<code><ListBox ItemsSource="{Binding LabelsCollection}" ...>
</code>```

You may also execute your initialization code as late as possible, by moving it to a Loaded event handler:

```<code>public Labels()
{
    InitializeComponent();
    ...

    Loaded += (s, e) =>
    {
        var item = (ListBoxItem)LabelsBox.ItemContainerGenerator.ContainerFromIndex(0);
        item?.Focus();
    };
}
</code>```

Body:
I can't set focus on first item of my ListBox. ListBox has some collection bound. It looks like, that first everything in code-behind doing its stuff then there is control initializing so I would have always -1 as SelectedIndex.

XAML

<Window x:Class="Labels.Szablony"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:Labels"
    mc:Ignorable="d"
    Title="Labels" Height="350" Width="250" WindowStartupLocation="CenterScreen"
    ResizeMode="CanMinimize" KeyDown="Window_KeyDown" Background="#FFF6A300" >
<Window.DataContext>
    <local:LabelGridViewModel/>
</Window.DataContext>
<ScrollViewer VerticalScrollBarVisibility="Hidden" VerticalContentAlignment="Center"
              VerticalAlignment="Center" Background="#FFF6A300">
    <Grid Background="#FFF6A300" Name="labelGrid">
        <ListBox x:Name="SzablonyBox" ItemsSource="{Binding LabelsCollection, IsAsync=True}"
              HorizontalAlignment="Center" VerticalAlignment="Top"
             MinWidth="100" MinHeight="100" BorderBrush="{x:Null}"
             Background="{x:Null}" TextSearch.Text="BLABLAB"
             TextSearch.TextPath="Name" IsTextSearchEnabled="True"
                 VerticalContentAlignment="Center" Margin="0 25 0 0"
                 Width="250" HorizontalContentAlignment="Center">
            <ListBox.ItemContainerStyle>

            </ListBox.ItemContainerStyle>
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <DockPanel Width="214">
                        <TextBlock Text="{Binding Name}"
                               FontSize="12" Height="35"
                               VerticalAlignment="Center"
                               HorizontalAlignment="Center"
                               Width="250"
                               TextAlignment="Center"/>
                    </DockPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
        <TextBox x:Name="InputText"
                 Text="{Binding Path=Filter, UpdateSourceTrigger=PropertyChanged}"
                 HorizontalAlignment="Center" Height="22" TextWrapping="Wrap"
                 VerticalAlignment="Top" Width="250" Background="#FFF6A300"
                 IsEnabled="False" BorderBrush="#FFF6A300"
                 VerticalContentAlignment="Center"
                 HorizontalContentAlignment="Center"
                 Foreground="Black" SelectionBrush="{x:Null}"/>
    </Grid>
</ScrollViewer>

What i'm trying to do looks like:

public Labels()
{
    InitializeComponent();

    LabelsBox.Focus();
    LabelsBox.SelectedIndex = 0;

    var item = LabelsBox.ItemContainerGenerator.ContainerFromIndex(0) as ListBoxItem;

    item.Focus();
}

Of course there is an exception, because item is null. Like I said SelectedIndex is always -1. What am I doing wrong ?

Body:
The ItemsSource Binding is asynchronous, so there are certainly not yet any items available while the constructor is running.

Change the Binding to be synchronous, i.e. the default behavior:

<ListBox ItemsSource="{Binding LabelsCollection}" ...>

You may also execute your initialization code as late as possible, by moving it to a Loaded event handler:

public Labels()
{
    InitializeComponent();
    ...

    Loaded += (s, e) =>
    {
        var item = (ListBoxItem)LabelsBox.ItemContainerGenerator.ContainerFromIndex(0);
        item?.Focus();
    };
}


答:
A way  could be based on modelMap

in Your frontend/config/main.php

you could reassign  the model map for user module  and your user model point to the table you need eg:

```<code>'modules' => [
    .......
    'user' => [
        'class' => your_user_class',  // eg:  'class' => 'yii2\user\Module'
                                      // check in Yii2 / Yiisoft vendor
                                      // or in your vendor  for the right module
        'admins' => ['your_admin'],
        'modelMap' => [
            'User'      => 'frontend\models\FrontUser',
        ],
    ],
</code>```

Title: want to separate frontend and backend user in yii2

Body:
as there is only user table in yii2 advanced. so user can login to both frontend and backend with same credential . we want saperate it out.

so I created frontuser table ,with same structure as of user table.
then created its model using gii model generator

made it as common model/user.

here is frontend/model/frontuser

<?php

namespace frontend\models;

use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;

/**
 * This is the model class for table "frontuser".
 *
 * @property integer $id
 * @property string $username
 * @property string $auth_key
 * @property string $password_hash
 * @property string $password_reset_token
 * @property string $email
 * @property integer $status
 * @property integer $created_at
 * @property integer $updated_at
 */
//class Frontuser extends \yii\db\ActiveRecord
class Frontuser extends ActiveRecord implements IdentityInterface
{
    /**
     * @inheritdoc
     */
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 10;
    public static function tableName()
    {
       return '{{%frontuser}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
       return [
            ['status', 'default', 'value' => self::STATUS_ACTIVE],
            ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
        ];
    }

    /**
     *  inheritdoc
     */
    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }

    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * Finds user by password reset token
     *
     * @param string $token password reset token
     * @return static|null
     */
    public static function findByPasswordResetToken($token)
    {
        if (!static::isPasswordResetTokenValid($token)) {
            return null;
        }

        return static::findOne([
            'password_reset_token' => $token,
            'status' => self::STATUS_ACTIVE,
        ]);
    }

    /**
     * Finds out if password reset token is valid
     *
     * @param string $token password reset token
     * @return bool
     */
    public static function isPasswordResetTokenValid($token)
    {
        if (empty($token)) {
            return false;
        }

        $timestamp = (int) substr($token, strrpos($token, '_') + 1);
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
        return $timestamp + $expire >= time();
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return bool if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    /**
     * Generates new password reset token
     */
    public function generatePasswordResetToken()
    {
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken()
    {
        $this->password_reset_token = null;
    }
}

and in frontend/config/main.php

<?php
$params = array_merge(
    require(__DIR__ . '/../../common/config/params.php'),
    require(__DIR__ . '/../../common/config/params-local.php'),
    require(__DIR__ . '/params.php'),
    require(__DIR__ . '/params-local.php')
);

return [
    'id' => 'app-frontend',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'controllerNamespace' => 'frontend\controllers',
    'components' => [
        'request' => [
            'csrfParam' => '_csrf-frontend',
        ],
        // 'user' => [
        //     'identityClass' => 'common\models\User',
        //     'enableAutoLogin' => true,
        //     'identityCookie' => ['name' => '_identity-frontend', 'httpOnly' => true],
        // ],
        'user' => [
                'class' => 'yii\web\User', // basic class
                'identityClass' => 'frontend\models\Frontuser', // your admin model
                'enableAutoLogin' => true,
                'loginUrl' => '/admin/frontend/login',
            ],
        'session' => [
            // this is the name of the session cookie used for login on the frontend
            'name' => 'advanced-frontend',
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'authManager' => [
            'class' => 'yii\rbac\DbManager', // or use 'yii\rbac\DbManager'
            'defaultRoles'=> ['guest'],
            ],
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
        /*
        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => [
            ],
        ],
        */
    ],
    'params' => $params,
];

but still ,I sign up ,entry goes in user table ..
I want to use user table for backend user
and frontuser table for frontend user
how to do it?

Body:
A way  could be based on modelMap

in Your frontend/config/main.php

you could reassign  the model map for user module  and your user model point to the table you need eg:

'modules' => [
    .......
    'user' => [
        'class' => your_user_class',  // eg:  'class' => 'yii2\user\Module'
                                      // check in Yii2 / Yiisoft vendor
                                      // or in your vendor  for the right module
        'admins' => ['your_admin'],
        'modelMap' => [
            'User'      => 'frontend\models\FrontUser',
        ],
    ],


问:
Monitoring tool for docker containers
We have a AWS Server with docker installed and configured. We are running few docker containers and also we want to monitor all the docker containers like CPU Usage, Memory Usage, Disk Usage, etc.

Is it possible to monitor docker container remotely and also graphically?

答:
There are some open source components that you can blend together like the previous answer mentioned. cAdvisor and Prometheus + Grafana is another option.

If you are more looking for an integrated commercial solution, have a look at CoScale and its product for Docker monitoring.

Title: Monitoring tool for docker containers


问:
Getting type signatures for a function in elm
I'm using elm 0.18.

Let's say I have a function that strings together a bunch of stuff that I threw together in a hurry.  It works, but I'm not sure what it's type signature is, and I'd like elm to tell me (or hint for me) that type signature.

For example, I use graphql and have a function that takes a graphql string, a decoder (which also doesn't have a type signature), and a Cmd Msg, and runs it through HttpBuilder.

```<code>graphQLPost graphiql decoder msg =
    HttpBuilder.post (url ++ "api")
        |> HttpBuilder.withStringBody "text/plain" graphiql
        |> HttpBuilder.withExpect (Http.expectJson decoder)
        |> HttpBuilder.send msg
</code>```

This works, though I don't know why.  I tried fitting it with the type signature graphQLPost : String -> Json.Decode.Decoder -> Cmd Msg, but I get an error.

Figuring out this type signature is not as important to me as finding a way to induce them through elm.  Is there a command that I can enter into elm-repl or something that will tell me the signature?

答:
Running elm-make with the --warn option will cause the compiler to suggest that you include a type annotation on functions that don't have one, and it will provide one for you to copy and paste in.

Also, some editor integrations, such as the Visual Studio Code language extension for Elm, will display these kinds of warnings as a hint icon that you can click to add the missing type annotation automatically. You can set a keyboard shortcut for this to do it without your hands leaving the keyboard.

Body:
I'm using elm 0.18.

Let's say I have a function that strings together a bunch of stuff that I threw together in a hurry.  It works, but I'm not sure what it's type signature is, and I'd like elm to tell me (or hint for me) that type signature.

For example, I use graphql and have a function that takes a graphql string, a decoder (which also doesn't have a type signature), and a Cmd Msg, and runs it through HttpBuilder.

graphQLPost graphiql decoder msg =
    HttpBuilder.post (url ++ "api")
        |> HttpBuilder.withStringBody "text/plain" graphiql
        |> HttpBuilder.withExpect (Http.expectJson decoder)
        |> HttpBuilder.send msg

This works, though I don't know why.  I tried fitting it with the type signature graphQLPost : String -> Json.Decode.Decoder -> Cmd Msg, but I get an error.

Figuring out this type signature is not as important to me as finding a way to induce them through elm.  Is there a command that I can enter into elm-repl or something that will tell me the signature?


问:
Python: Why am I getting a "ZeroDivisionError: division by zero" in function?
My goal is to count the total amount of tweets in a file that fall under certain time zones.
I have the following function (I have noted the trouble area near the end of the function with comments):

```<code>def readTweets(inFile, wordsName):
words = []
lat = 0
long = 0
keyword = keywords(wordsName)
sents = keywordSentiment(wordsName)
value = 0
eastern = 0
central = 0
mountain = 0
pacific = 0
a = 0
b = 0
c = 0
d = 0
easternTweets = 0
centralTweets = 0
mountainTweets = 0
pacificTweets = 0

for line in inFile:
    entry = line.split()

    for n in range(0, len(entry) - 1):
        entry[n] = entry[n].strip("[],!?#./-=+_@")
        if n > 4:   # n>4 because words begin on 5th index of list
            entry[n] = entry[n].lower()
            words.append(entry[n])

    lat = float(entry[0])
    long = float(entry[1])

    timezone = getTimeZone(lat, long)
    if timezone == "eastern":
        easternTweets += 1
    if timezone == "central":
        centralTweets += 1
    if timezone == "mountain":
        mountainTweets += 1
    if timezone == "pacific":
        pacificTweets += 1

    for i in range(0, len(words)):
        for k in range(0, len(keyword)):
            if words[i] == keyword[k]:
                value = int(sents[k])
                if timezone == "eastern":
                    eastern += value
                    a += 1
                if timezone == "central":
                    central += value
                    b += 1
                if timezone == "mountain":
                    mountain += value
                    c += 1
                if timezone == "pacific":
                    pacific += value
                    d += 1

# the values of a,b,c,d are 0
easternTotal = eastern/a    # getting error
centralTotal = central/b    # for
mountainTotal = mountain/c  # these
pacificTotal = pacific/d    # values

print("Total tweets per time zone:")
print("Eastern: %d" % easternTweets)
print("Central: %d" % centralTweets)
print("Mountain: %d" % mountainTweets)
print("Pacific: %d" % pacificTweets)
</code>```

I am getting a ZeroDivisionError: division by zero error for easternTotal and the other total values that use a, b, c, and d for division.

If I print the values of a, b, c, or d it shows 0. My question is why are their values 0? Does the value of a, b, c, and d not change in the if statements?

答:
because you set a,b,c,d=0;
when readTweets(inFile, wordsName) did not get any data, "eastern/a" may cause "eastern/0 " .

So, make sure your readTweets() did get data first.

Body:
My goal is to count the total amount of tweets in a file that fall under certain time zones.
I have the following function (I have noted the trouble area near the end of the function with comments):

def readTweets(inFile, wordsName):
words = []
lat = 0
long = 0
keyword = keywords(wordsName)
sents = keywordSentiment(wordsName)
value = 0
eastern = 0
central = 0
mountain = 0
pacific = 0
a = 0
b = 0
c = 0
d = 0
easternTweets = 0
centralTweets = 0
mountainTweets = 0
pacificTweets = 0

for line in inFile:
    entry = line.split()

    for n in range(0, len(entry) - 1):
        entry[n] = entry[n].strip("[],!?#./-=+_@")
        if n > 4:   # n>4 because words begin on 5th index of list
            entry[n] = entry[n].lower()
            words.append(entry[n])

    lat = float(entry[0])
    long = float(entry[1])

    timezone = getTimeZone(lat, long)
    if timezone == "eastern":
        easternTweets += 1
    if timezone == "central":
        centralTweets += 1
    if timezone == "mountain":
        mountainTweets += 1
    if timezone == "pacific":
        pacificTweets += 1

    for i in range(0, len(words)):
        for k in range(0, len(keyword)):
            if words[i] == keyword[k]:
                value = int(sents[k])
                if timezone == "eastern":
                    eastern += value
                    a += 1
                if timezone == "central":
                    central += value
                    b += 1
                if timezone == "mountain":
                    mountain += value
                    c += 1
                if timezone == "pacific":
                    pacific += value
                    d += 1

# the values of a,b,c,d are 0
easternTotal = eastern/a    # getting error
centralTotal = central/b    # for
mountainTotal = mountain/c  # these
pacificTotal = pacific/d    # values

print("Total tweets per time zone:")
print("Eastern: %d" % easternTweets)
print("Central: %d" % centralTweets)
print("Mountain: %d" % mountainTweets)
print("Pacific: %d" % pacificTweets)

I am getting a ZeroDivisionError: division by zero error for easternTotal and the other total values that use a, b, c, and d for division.

If I print the values of a, b, c, or d it shows 0. My question is why are their values 0? Does the value of a, b, c, and d not change in the if statements?


问:
How create no-op version for firebase performance monitoring
I want to use firebase performace monitoring in a big android multidex application, who's using modules. So I add apply plugin and dependencies to my gradle file. But my build time increased too much. So tell me how to create a no-op version in debug builds. My problem is that I don't want apply plugin in gradle file (because it is still BETA) in debug and release build, only in alpha build.

答:
Solution is now proven:</p>

```<code>buildTypes
{
    debug
    {
        manifestPlaceholders = [firebaseDisableMonitoring: true]
    }
    release
    {
        manifestPlaceholders = [firebaseDisableMonitoring: false]
    }
}
</code>```

Body:
Solution is now proven:

buildTypes
{
    debug
    {
        manifestPlaceholders = [firebaseDisableMonitoring: true]
    }
    release
    {
        manifestPlaceholders = [firebaseDisableMonitoring: false]
    }
}


问:
Interacting with multiple servers over SSH in PHP
I'm currently writing a deployment framework in PHP.  The framework connects to servers and executes commands over SSH.  I've been looking for quite a while trying to find a way in PHP to do this better.  Here are the requirements.  The technique should be able to:

Enter the SSH password programmatically.  I know that using SSH keys is the way to go when you want password-less SSH logons, but remember, this is a deployment framework.  It could potentially be deploying to 25 servers at a time.  It doesn't seem right to require the user to have set up SSH keys to use the framework, and who wants to enter their password 25 times?  I'm using Capistrano as a model here - it asks for your password once, then uses it to establish the SSH connections without re-prompting the user.  I'm not suggesting the passwords be stored in the deploy script, just (silently) entered once and used until the deploy tasks are finished.

Send output to the PHP script.  I would like to be able to intercept the terminal output from each of the SSH sessions independently, modify it, then send it back to the terminal for the user to see.  This way, I can prepend the name of the server onto each line of output to show what's going on.

Provide write (as well as read) access to the terminal.  It's important that the user (or the script) be able to enter other information into the terminal besides just the SSH password.

Support SSH v2.

Currently, my framework "compiles" the commands from the deploy script into one giant string and executes them by using the SSH command.  Each final deploy command looks something like this:

ssh -t -t -p 12345 user@server.com 'command1; command2;'

Each of these SSH commands is executed via PHP's built-in passthru function:

<?php passthru("ssh -t -t -p 12345 user@server.com 'command1; command2;'"); ?>

I have tried using proc_open and nearly all of PHP's other command-executing functions to no avail - none of them provide all the functionality I've listed above.  In addition, I've tried several pure PHP SSH implementations, also to no avail.  The libraries either don't supply write access to the terminal or don't support SSH v2.

Any help on this would be greatly appreciated - thanks in advance!

答:
You can make SSH connection with a PECL extension in PHP.
http://php.net/manual/en/book.ssh2.php

```<code>$connection = ssh2_connect('server.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$stream1 = ssh2_exec($connection, $command1);
$stream2 = ssh2_exec($connection, $command2);
</code>```

You can also create a ssh interactive shell with ssh2_shell() if you need to more advanced things.

Body:
You can make SSH connection with a PECL extension in PHP.
http://php.net/manual/en/book.ssh2.php

$connection = ssh2_connect('server.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$stream1 = ssh2_exec($connection, $command1);
$stream2 = ssh2_exec($connection, $command2);

You can also create a ssh interactive shell with ssh2_shell() if you need to more advanced things.