问:
action create not working Yii2 frontend
i want to execute action create in my view frontend, the code of actionCreate in site controller is correct , but it redirect me to index.php with this url "http://localhost/advanced/frontend/web/index.php?Subsidize%5Bname%5D..........."
knowing that i want to redirect to view.php after creating a new item in table "subsidize"

action create in siteController.php

```<code>public function actionView($id) {
    $model = Subsidize::findOne($id);
    if ($model === null) {
        throw new NotFoundHttpException;
    }

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

public function actionCreate() {
    $model = new Subsidize();

    if ($model->load(Yii::$app->request->post()) && $model->save()) {

         return $this->redirect(['view', 'id' => $model->subsidize_id]);

    } else {

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

code of  submitButton in view "create.php"

```<code>        <?= Html::submitButton($model->isNewRecord ? 'إرسال ' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</code>```

also , function behaviors in  siteController

```<code> public function behaviors() {
    return [
        'access' => [
            'class' => AccessControl::className(),
            'only' => ['create'],
            'rules' => [
                [
                    'actions' => ['login', 'error'],
                    'allow' => true,
                ],
                [
                    'actions' => ['create', 'view'],
                    'allow' => true,
                    'roles' => ['@'],
                ],
                [
                    //see captcha and error added here, this fixes the issue
                    'actions' => ['support', 'test', 'delete', 'update', 'create', 'view'],
                    'allow' => true,
                    'roles' => ['?', '@'],
                ],
            ],
        ],
        'verbs' => [
            'class' => VerbFilter::className(),
            'actions' => [
                'index' => ['get'],
                'view' => ['get'],
                'create' => ['get', 'post'],
                'update' => ['get', 'put', 'post'],
                'delete' => ['post', 'delete'],
            ],
        ],
    ];
}
</code>```

code of my view : create.php

```<code><?php use yii\helpers\Html; use yii\widgets\ActiveForm; $model = new app\models\Subsidize; ?> <section class="support">
<div class="container">
    <form class="dialog-form row">
        <?php $form = ActiveForm::begin() ?>
        <div class="col-md-12">
            <div class="form-group">

                <?php echo $form->field($model, 'name', [
       'inputOptions' => ['autofocus' => 'autofocus', 'class' => 'form-control transparent']
 ])->textInput()->input('name', ['placeholder' => "الإسم الكريم"])->label(false); ?>

            </div><!--End Form-group-->
        </div><!-- col -->
        <div class="col-md-12">
            <div class="form-group">
                 <?php echo $form->field($model, 'montant', [
       'inputOptions' => ['autofocus' => 'autofocus', 'class' => 'form-control transparent']
 ])->textInput()->input('montant', ['placeholder' => "المبلغ "])->label(false); ?>
            </div><!--End Form-group-->
        </div><!-- col -->

         <div class="col-md-12">
            <div class="form-group">
                 <?php echo $form->field($model, 'date', [
       'inputOptions' => ['autofocus' => 'autofocus', 'class' => 'form-control transparent']
 ])->textInput()->input('date', ['placeholder' => "تاريخ التذكير "])->label(false); ?>
            </div><!--End Form-group-->
        </div><!-- col -->

        <div class="col-md-12">
            <div class="form-group">
                 <?php echo $form->field($model, 'phone', [
       'inputOptions' => ['autofocus' => 'autofocus', 'class' => 'form-control transparent']
 ])->textInput()->input('phone', ['placeholder' => "رقم الجوال"])->label(false); ?>
            </div><!--End Form-group-->
        </div><!-- col -->

        <div class="col-md-12">
            <div class="form-group">

                    <?php echo $form->field($model, 'remarks', [
       'inputOptions' => ['autofocus' => 'autofocus', 'class' => 'form-control transparent']
 ])->textInput(['rows' =>6])->input('remarks', ['placeholder' => "ملاحظات"])->label(false); ?>
            </div><!-- form-group -->
        </div><!-- col -->
        <div class="col-md-12">
            <div class="form-group" style="text-align:center ">

    <?= Html::submitButton($model->isNewRecord ? 'إرسال ' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

            </div><!-- form-group -->
        </div><!-- col -->
         <?php ActiveForm::end(); ?>
    </form><!--End-->
</div><!-- container -->
</code>```

答:
Did you forget to specify method attribute of your HTML form?

```<code><form method="POST" ...>
</code>```

Looks like form just being submitted as GET request

Title: action create not working Yii2 frontend

Body:
i want to execute action create in my view frontend, the code of actionCreate in site controller is correct , but it redirect me to index.php with this url "http://localhost/advanced/frontend/web/index.php?Subsidize%5Bname%5D..........."
knowing that i want to redirect to view.php after creating a new item in table "subsidize"

action create in siteController.php

public function actionView($id) {
    $model = Subsidize::findOne($id);
    if ($model === null) {
        throw new NotFoundHttpException;
    }

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

public function actionCreate() {
    $model = new Subsidize();

    if ($model->load(Yii::$app->request->post()) && $model->save()) {

         return $this->redirect(['view', 'id' => $model->subsidize_id]);

    } else {

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

code of  submitButton in view "create.php"

        <?= Html::submitButton($model->isNewRecord ? 'إرسال ' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

also , function behaviors in  siteController

 public function behaviors() {
    return [
        'access' => [
            'class' => AccessControl::className(),
            'only' => ['create'],
            'rules' => [
                [
                    'actions' => ['login', 'error'],
                    'allow' => true,
                ],
                [
                    'actions' => ['create', 'view'],
                    'allow' => true,
                    'roles' => ['@'],
                ],
                [
                    //see captcha and error added here, this fixes the issue
                    'actions' => ['support', 'test', 'delete', 'update', 'create', 'view'],
                    'allow' => true,
                    'roles' => ['?', '@'],
                ],
            ],
        ],
        'verbs' => [
            'class' => VerbFilter::className(),
            'actions' => [
                'index' => ['get'],
                'view' => ['get'],
                'create' => ['get', 'post'],
                'update' => ['get', 'put', 'post'],
                'delete' => ['post', 'delete'],
            ],
        ],
    ];
}

code of my view : create.php

<?php use yii\helpers\Html; use yii\widgets\ActiveForm; $model = new app\models\Subsidize; ?>

    <form class="dialog-form row">
        <?php $form = ActiveForm::begin() ?>

                <?php echo $form->field($model, 'name', [
       'inputOptions' => ['autofocus' => 'autofocus', 'class' => 'form-control transparent']
 ])->textInput()->input('name', ['placeholder' => "الإسم الكريم"])->label(false); ?>

                 <?php echo $form->field($model, 'montant', [
       'inputOptions' => ['autofocus' => 'autofocus', 'class' => 'form-control transparent']
 ])->textInput()->input('montant', ['placeholder' => "المبلغ "])->label(false); ?>

                 <?php echo $form->field($model, 'date', [
       'inputOptions' => ['autofocus' => 'autofocus', 'class' => 'form-control transparent']
 ])->textInput()->input('date', ['placeholder' => "تاريخ التذكير "])->label(false); ?>

                 <?php echo $form->field($model, 'phone', [
       'inputOptions' => ['autofocus' => 'autofocus', 'class' => 'form-control transparent']
 ])->textInput()->input('phone', ['placeholder' => "رقم الجوال"])->label(false); ?>

                    <?php echo $form->field($model, 'remarks', [
       'inputOptions' => ['autofocus' => 'autofocus', 'class' => 'form-control transparent']
 ])->textInput(['rows' =>6])->input('remarks', ['placeholder' => "ملاحظات"])->label(false); ?>

    <?= Html::submitButton($model->isNewRecord ? 'إرسال ' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

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

Body:
Did you forget to specify method attribute of your HTML form?

<form method="POST" ...>

Looks like form just being submitted as GET request


来源: stackexchange

问:
AWS Lambda RDS connection timeout
I'm trying to write a Lambda function using Node.js which connects to my RDS database. The database is working and accessible from my Elastic Beanstalk environment. When I run the function, it returns a timeout error.

Tried to increase the timeout up to 5 minutes with the exact same result.

The conclusion I came to after some research is that it's probably a security issue but couldn't find the solution in Amazon's documentation or in this answer (which is the only one I could find on the topic).

Here are the security details:

Both the RDS and the Lambda are in the same security group.

The RDS has All traffic inbound and outbound rules.

The Lambda has AmazonVPCFullAccess policy in it's role.

My code is:

```<code>'use strict';
console.log("Loading getContacts function");

var AWS = require('aws-sdk');
var mysql = require('mysql');

exports.handler = (event, context, callback) => {

   var connection = mysql.createConnection({
        host     : '...',
        user     : '...',
        password : '...',
        port     : 3306,
        database: 'ebdb',
        debug    :  false
    });

    connection.connect(function(err) {
      if (err) callback(null, 'error ' +err);
      else callback(null, 'Success');
    });

};
</code>```

The result I'm getting is:

```<code>"errorMessage": "2017-03-05T05:57:46.851Z 9ae64c49-0168-11e7-b49a-a1e77ae6f56c Task timed out after 10.00 seconds"
</code>```

答:
The problem does not originate from the timeout, but from the way you close the connection. Use .destroy() instead if you do not want to wait for the callback that OR use the callback correctly when closing the connection in .end(function(err) { //Now call your callback });

See this thread for a more in depth explanation.

ContentLicense: CC BY-SA 3.0

Title: AWS Lambda RDS connection timeout

Body:
I'm trying to write a Lambda function using Node.js which connects to my RDS database. The database is working and accessible from my Elastic Beanstalk environment. When I run the function, it returns a timeout error.

Tried to increase the timeout up to 5 minutes with the exact same result.

The conclusion I came to after some research is that it's probably a security issue but couldn't find the solution in Amazon's documentation or in this answer (which is the only one I could find on the topic).

Here are the security details:

Both the RDS and the Lambda are in the same security group.

The RDS has All traffic inbound and outbound rules.

The Lambda has AmazonVPCFullAccess policy in it's role.

My code is:

'use strict';
console.log("Loading getContacts function");

var AWS = require('aws-sdk');
var mysql = require('mysql');

exports.handler = (event, context, callback) => {

   var connection = mysql.createConnection({
        host     : '...',
        user     : '...',
        password : '...',
        port     : 3306,
        database: 'ebdb',
        debug    :  false
    });

    connection.connect(function(err) {
      if (err) callback(null, 'error ' +err);
      else callback(null, 'Success');
    });

};

The result I'm getting is:

"errorMessage": "2017-03-05T05:57:46.851Z 9ae64c49-0168-11e7-b49a-a1e77ae6f56c Task timed out after 10.00 seconds"


问:
Divide and conquer algorithm
I had a job interview a few weeks ago and I was asked to design a divide and conquer algorithm. I could not solve the problem, but they just called me for a second interview! Here is the question:

we are giving as input two n-element arrays A[0..n − 1] and B[0..n − 1] (which
are not necessarily sorted) of integers, and an integer value. Give an O(nlogn) divide and conquer algorithm that determines if there exist distinct values i, j (that is, i != j) such that A[i] + B[j] = value. Your algorithm should return True if i, j exists, and return False otherwise. You may assume that the elements in A are distinct, and the elements in B are distinct.

can anybody solve the problem? Thanks

答:
I suggest using hashing. Even if it's not the way you are supposed to solve the problem, it's worth mentioning since hashing has a better time complexity O(n) v. O(n*log(n)) and that's why more efficient.

Turn A into a hashset (or dictionary if we want i index) - O(n)

Scan B and check if there's value - B[j] in the hashset (dictionary) - O(n)

So you have an O(n) + O(n) = O(n) algorithm (which is better that required (O n * log(n)), however the solution is NOT Divide and Conquer):

Sample C# implementation

```<code>  int[] A = new int[] { 7, 9, 5, 3, 47, 89, 1 };
  int[] B = new int[] { 5, 7, 3, 4, 21, 59, 0 };

  int value = 106; // 47 + 59 = A[4] + B[5]

  // Turn A into a dictionary: key = item's value; value = item's key
  var dict = A
    .Select((val, index) => new {
      v = val,
      i = index, })
    .ToDictionary(item => item.v, item => item.i);

  int i = -1;
  int j = -1;

  // Scan B array
  for (int k = 0; k < B.Length; ++k) {
    if (dict.TryGetValue(value - B[k], out i)) {
      // Solution found: {i, j}
      j = k;

      // if you want any solution then break
      break;

      // scan further (comment out "break") if you want all pairs
    }
  }

  Console.Write(j >= 0 ? $"{i} {j}" : "No solution");
</code>```

Title: Divide and conquer algorithm

Body:
I suggest using hashing. Even if it's not the way you are supposed to solve the problem, it's worth mentioning since hashing has a better time complexity O(n) v. O(n*log(n)) and that's why more efficient.

Turn A into a hashset (or dictionary if we want i index) - O(n)

Scan B and check if there's value - B[j] in the hashset (dictionary) - O(n)

So you have an O(n) + O(n) = O(n) algorithm (which is better that required (O n * log(n)), however the solution is NOT Divide and Conquer):

Sample C# implementation

  int[] A = new int[] { 7, 9, 5, 3, 47, 89, 1 };
  int[] B = new int[] { 5, 7, 3, 4, 21, 59, 0 };

  int value = 106; // 47 + 59 = A[4] + B[5]

  // Turn A into a dictionary: key = item's value; value = item's key
  var dict = A
    .Select((val, index) => new {
      v = val,
      i = index, })
    .ToDictionary(item => item.v, item => item.i);

  int i = -1;
  int j = -1;

  // Scan B array
  for (int k = 0; k < B.Length; ++k) {
    if (dict.TryGetValue(value - B[k], out i)) {
      // Solution found: {i, j}
      j = k;

      // if you want any solution then break
      break;

      // scan further (comment out "break") if you want all pairs
    }
  }

  Console.Write(j >= 0 ? $"{i} {j}" : "No solution");


问:
Bootstrap Dropdown menu is not working (Does not show a dropdown list)
I have this code snippet extracted from Bootstrap website. Everything works fine except when I click See Product, it won't show anything.

```<code>    <!DOCTYPE html>
<html>
<head>
    <title>Omicron.com</title>
    <link rel="stylesheet" type="text/css" href="css/bootstrap.css">
    <link rel="stylesheet" type="text/css" href="css/custom.css">
    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="css/bootstrap-theme.css">
    <link rel="stylesheet" type="text/css" href="css/bootstrap-theme.min.css">
    <style>
/*#MostUpperGreyLine img{
    width: 100%;
    min-width: 10px;
    height:auto;
}*/
#Header-New img{
    width: 100%;
    min-width: 10px;
    height: auto;
    position: relative;
    top:10px;
}

</style>
</head>
<body>

    <!--<div id="MostUpperGreyLine">
        <img src="MostUpperGreyLine.png" alt="No Green Header Found!">
    </div>-->

    <nav class="navbar navbar-default">
        <div class="container-fluid">
            <!-- Brand and toggle get grouped for better mobile display -->
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="#">Omicron.Inc</a>
            </div>

            <!-- Collect the nav links, forms, and other content for toggling -->
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                <ul class="nav navbar-nav">
                    <li class="active"><a href="#">Our Applications<span class="sr-only">(current)</span></a></li>
                    <li><a href="#">Link</a></li>
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">See Products <span class="caret"></span></a>
                        <ul class="dropdown-menu">
                            <li><a href="#">Action</a></li>
                            <li><a href="#">Another action</a></li>
                            <li><a href="#">Something else here</a></li>
                            <li role="separator" class="divider"></li>
                            <li><a href="#">Separated link</a></li>
                            <li role="separator" class="divider"></li>
                            <li><a href="#">One more separated link</a></li>
                        </ul>
                    </li>
                </ul>
                <form class="navbar-form navbar-left">
                    <div class="form-group">
                        <input type="text" class="form-control" placeholder="Search">
                    </div>
                    <button type="submit" class="btn btn-default">Submit</button>
                </form>
                <ul class="nav navbar-nav navbar-right">
                    <li><a href="#">Link</a></li>
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
                        <ul class="dropdown-menu">
                            <li><a href="#">Action</a></li>
                            <li><a href="#">Another action</a></li>
                            <li><a href="#">Something else here</a></li>
                            <li role="separator" class="divider"></li>
                            <li><a href="#">Separated link</a></li>
                        </ul>
                    </li>
                </ul>
            </div><!-- /.navbar-collapse -->
        </div><!-- /.container-fluid -->
    </nav>

    <div id="Header-New">
        <img src="Header-New.png" alt="Header not Found!">
    </div>

</body>
</html>
</code>```

答:
You don't have jquery.min.js and bootstrap.min.js or bootstrap.js files connected in your html. Look at the basic template

Before closing tag  you need to add folowing code

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</code>```

Make sure that bootstrap.min.js file is in js folder in your project

Body:
I have this code snippet extracted from Bootstrap website. Everything works fine except when I click See Product, it won't show anything.

    <!DOCTYPE html>

    <title>Omicron.com</title>
    <link rel="stylesheet" type="text/css" href="css/bootstrap.css">
    <link rel="stylesheet" type="text/css" href="css/custom.css">
    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="css/bootstrap-theme.css">
    <link rel="stylesheet" type="text/css" href="css/bootstrap-theme.min.css">

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                    Toggle navigation

                </button>
                Omicron.Inc

Our Applications(current)

Link

                        See Products

Action

Another action

Something else here

Separated link

One more separated link

                <form class="navbar-form navbar-left">

                        <input type="text" class="form-control" placeholder="Search">

                    <button type="submit" class="btn btn-default">Submit</button>
                </form>

Link

                        Dropdown

Action

Another action

Something else here

Separated link

Body:
You don't have jquery.min.js and bootstrap.min.js or bootstrap.js files connected in your html. Look at the basic template

Before closing tag </body> you need to add folowing code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>

Make sure that bootstrap.min.js file is in js folder in your project


问:
Laravel Mix: compile Sass into .css and min.css
I've run my head against the wall here.

For my project, I would like Laravel Mix/webpack to compile an .scss-file into two files, a regular, un-minified (expanded or nested) .css-file, and a minified (compressed) .min.css-file, so I essentially have both files.

I've tried with:

```<code>mix.sass('src', 'output')
   .copy('output.css', 'output.min.css')
   .minify('output.min.css');
</code>```

However, this results in an error because the .css-file wasn't compiled.

I know Laravel Mix minifies when running npm run production but I'm interested in two files, not just the one production compiles to.

Is there any way to do this, without modifying the whole webpack config?

答:
I found an answer by messing with a few things, and came to the conclusion that I'm not going to use Laravel Mix's production-script for this. I couldn't find a way for Laravel Mix not to minify the regular CSS when running npm run production, however, production was needed for minify() to work, as it doesn't minify if the environment is development.

So I pulled in a package that minify on command. This is where minifier() comes to the rescue.

npm install --save-dev minifier

Then my webpack.mix.js looks like this:

let mix = require('laravel-mix');
let minifier = require('minifier');

mix.sass('src/sass/app.scss', 'public/css/', {
    outputStyle: 'nested'
});

mix.then(() => {
    minifier.minify('public/css/app.css')
});
```

The mix.then() is triggered when webpack finishes building, and .minify() will automagically create a new file called app.min.css.

Then when I run npm run dev, my Sass will be compiled in nested format, and it will also be minified. Not the most elegant solution but this is the best I could come up with.

And hey, if it's stupid but it works, it's not stupid. I mean, a CPU is literally a rock that we tricked into thinking¹.

Body:
I've run my head against the wall here.

For my project, I would like Laravel Mix/webpack to compile an .scss-file into two files, a regular, un-minified (expanded or nested) .css-file, and a minified (compressed) .min.css-file, so I essentially have both files.

I've tried with:

mix.sass('src', 'output')
   .copy('output.css', 'output.min.css')
   .minify('output.min.css');

However, this results in an error because the .css-file wasn't compiled.

I know Laravel Mix minifies when running npm run production but I'm interested in two files, not just the one production compiles to.

Is there any way to do this, without modifying the whole webpack config?

Body:
I found an answer by messing with a few things, and came to the conclusion that I'm not going to use Laravel Mix's production-script for this. I couldn't find a way for Laravel Mix not to minify the regular CSS when running npm run production, however, production was needed for minify() to work, as it doesn't minify if the environment is development.

So I pulled in a package that minify on command. This is where minifier() comes to the rescue.

npm install --save-dev minifier

Then my webpack.mix.js looks like this:

let mix = require('laravel-mix');
let minifier = require('minifier');

mix.sass('src/sass/app.scss', 'public/css/', {
    outputStyle: 'nested'
});

mix.then(() => {
    minifier.minify('public/css/app.css')
});

The mix.then() is triggered when webpack finishes building, and .minify() will automagically create a new file called app.min.css.

Then when I run npm run dev, my Sass will be compiled in nested format, and it will also be minified. Not the most elegant solution but this is the best I could come up with.

And hey, if it's stupid but it works, it's not stupid. I mean, a CPU is literally a rock that we tricked into thinking¹.


问:
node.js driver for mysql works in console but not in actual code
I have .js file with following code:

```<code>var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'databasename'});

function select(id,tablename){
connection.connect();
connection.query('select ' +tablename+'.property from databasename.'+tablename+' where id = '+id, function(err,result){
var string=JSON.stringify(result[0].property);
// alert(string); or console.log(string);
});
connection.end();
}

// function go(){select(3,"tablename");} or select(3,"tablename");
</code>```

where function.go() is called from button.onClick().
 And when I run it from console via "node filename.js" it works fine and shows correct data, but it doesn't work from button.onClick().

What am I doing wrong?

答:
i think you mix sync and async. you need your callback for the query</p>

```<code>var mysql = require('mysql');
var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'password',
    database: 'databasename'
});

function select(id, tablename, callback){
    connection.connect();
    connection.query(`SELECT ${tablename}.property from databasename.${tablename} where id = ?`, [id], callback);
    connection.end();
}

function go () {
    select(3, "tablename", function (err, result) {
        // mysql response
    });
}
</code>```

Body:
I have .js file with following code:

var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'databasename'});

function select(id,tablename){
connection.connect();
connection.query('select ' +tablename+'.property from databasename.'+tablename+' where id = '+id, function(err,result){
var string=JSON.stringify(result[0].property);
// alert(string); or console.log(string);
});
connection.end();
}

// function go(){select(3,"tablename");} or select(3,"tablename");

where function.go() is called from button.onClick().
 And when I run it from console via "node filename.js" it works fine and shows correct data, but it doesn't work from button.onClick().

What am I doing wrong?

Body:
i think you mix sync and async. you need your callback for the query

var mysql = require('mysql');
var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'password',
    database: 'databasename'
});

function select(id, tablename, callback){
    connection.connect();
    connection.query(`SELECT ${tablename}.property from databasename.${tablename} where id = ?`, [id], callback);
    connection.end();
}

function go () {
    select(3, "tablename", function (err, result) {
        // mysql response
    });
}


问:
Is it possible to debug application wireless or without connecting USB cable in XCODE?
how to connect device in xcode without cable. it is tedious to connect the cable and my USB is lil bit loose, so it disconnects from PC.</p>

答: Wireless debugging is possible now with XCode 9.x and iOS 11.x. Check my answer here for steps to connect device for wireless debugging.


问:
Storage issues in cloud when creating multiple instances
In a cloud hosting environment (amazon, rackspace,) you can create multiple instances. Let's say I have a database server (mysql,) and other persistent data.

If I create more instances, what happens to the data ? Ex.

1 Instance -> user table (in a db)

I make another 3 instances

4 Instances -> each one has it's one user table

Errors: if someone adds data to the table on instance 3 how does instance nr 4 see it ? If I merge the instances back to one, which instance data does it keep ?

Thank you

答:
I would suggest having one (or more) dedicated database servers that all the instances connect to. If you are using Amazon Web Services check out their RDS service ( http://aws.amazon.com/rds/ )

That way you don't need to worry about replication - if you do want each server running it's own db instance you'll have to look into replication - for MySQL this is a good guide: http://dev.mysql.com/doc/refman/5.0/en/replication.html

I would strongly recommend the former solution for the database. Replication is tricky to get right and can be a nightmare to maintain

If you are using static data eg images I would recommend using amazon's S3 service for uploading to ( http://aws.amazon.com/s3/ ) - that way all your servers are getting their data from a single point instead of having to replicate over servers, which is always going to end up a less scalable solution

ContentLicense: CC BY-SA 2.5


问:
elasticsearch xpack - Can’t change default password
I installed Xpack for elasticsearch, and tried to to change the password as it says here:
https://www.elastic.co/guide/en/x-pack/current/security-getting-started.html

Running this:

```<code>curl -XPUT -u elastic localhost:9200/_xpack/security/user/elastic/_password -H Content-Type: application/json -d {"password" : "elasticpassword"}
</code>```

is getting me:

```<code>{"error":{"root_cause":[{"type":"json_parse_exception","reason":"Unexpected character ('p' (code 112)): was expecting double-quote to start field name\n
at [Source: org.elasticsearch.transport.netty4.ByteBufStreamInput@4a142671; line: 1, column: 3]"}],"type":"json_parse_exception","reason":"Unexpected character ('p' (code 112)): was expecting double-quote to start field name\n
at [Source: org.elasticsearch.transport.netty4.ByteBufStreamInput@4a142671; line: 1, column: 3]"},"status":500}curl: (6) Could not resolve host: application
curl: (3) Bad URL, colon is first character
curl: (3) [globbing] unmatched close brace/bracket in column 16
</code>```

or, running this:

```<code>curl -XPUT -u elastic "localhost:9200/_xpack/security/user/elastic/_password" -H "Content-Type: application/json -d {"password" : "elasticpassword"}
</code>```

gets me this:

```<code>{"error":{"root_cause":[{"type":"not_x_content_exception","reason":"Compressor detection can only be called on some xcontent bytes or compressed xcontent bytes"}],"type":"not_x_content_exception","reason":"Compressor detection can only be called on some xcontent bytes or compressed xcontent bytes"},"status":500}
</code>```

I can't seem to get it, no matter what combination of " or ' I'm using. Please help!

Thanks

答:
This is general problem of Windows users. You can use Sense Chrome Plugin or Kibana Dev Tools instead.

```<code>curl -XPUT -u elastic localhost:9200/_xpack/security/user/elastic/_password -H "Content-Type: application/json" -d "{\"password\" : \"elasticpassword\"}"
</code>```

Please check the elastic developer response about this situation:
https://discuss.elastic.co/t/index-a-new-document/35281/8

Body:
I installed Xpack for elasticsearch, and tried to to change the password as it says here:
https://www.elastic.co/guide/en/x-pack/current/security-getting-started.html

Running this:

curl -XPUT -u elastic localhost:9200/_xpack/security/user/elastic/_password -H Content-Type: application/json -d {"password" : "elasticpassword"}

is getting me:

{"error":{"root_cause":[{"type":"json_parse_exception","reason":"Unexpected character ('p' (code 112)): was expecting double-quote to start field name\n
at [Source: org.elasticsearch.transport.netty4.ByteBufStreamInput@4a142671; line: 1, column: 3]"}],"type":"json_parse_exception","reason":"Unexpected character ('p' (code 112)): was expecting double-quote to start field name\n
at [Source: org.elasticsearch.transport.netty4.ByteBufStreamInput@4a142671; line: 1, column: 3]"},"status":500}curl: (6) Could not resolve host: application
curl: (3) Bad URL, colon is first character
curl: (3) [globbing] unmatched close brace/bracket in column 16

or, running this:

curl -XPUT -u elastic "localhost:9200/_xpack/security/user/elastic/_password" -H "Content-Type: application/json -d {"password" : "elasticpassword"}

gets me this:

{"error":{"root_cause":[{"type":"not_x_content_exception","reason":"Compressor detection can only be called on some xcontent bytes or compressed xcontent bytes"}],"type":"not_x_content_exception","reason":"Compressor detection can only be called on some xcontent bytes or compressed xcontent bytes"},"status":500}

I can't seem to get it, no matter what combination of " or ' I'm using. Please help!

Thanks

Body:
This is general problem of Windows users. You can use Sense Chrome Plugin or Kibana Dev Tools instead.

curl -XPUT -u elastic localhost:9200/_xpack/security/user/elastic/_password -H "Content-Type: application/json" -d "{\"password\" : \"elasticpassword\"}"

Please check the elastic developer response about this situation:
https://discuss.elastic.co/t/index-a-new-document/35281/8


问:
Passing a parameter programmatically and displaying in crystal report
I have a crystal report in which I set the datasource and parameter programmatically but it is not working. I'm not getting the output as required.

This is the output when i show all

But when I pass parameters to it, it shows nothing.
I checked in DataTable by applying debugging the data is Filtered but it is not showing in my Crystal Report Viewer

This is what I get when I passed parameters to it.

Here is my code:

```<code>private void button1_Click(object sender, EventArgs e)
{
    con.Open();
    DataTable table = new DataTable();
    DataSet DataSet2 = new DataSet();
    SqlCommand cmd = new SqlCommand("Select * from personal_data WHERE class = '" + textBox1.Text.ToString()+"'", con);

    table.Load(cmd.ExecuteReader());

    DataSet2.DataSetName = "dt";
    DataSet2.AcceptChanges();

    DataSet2.Tables.Add(table);
    ad.SelectCommand=cmd;
    ad.Fill(DataSet2,"personal_table");

    ParameterFields paramFields = new ParameterFields();
    // ParameterDiscreteValue paramDiscreteValue = new ParameterDiscreteValue();

    ParameterField paramField = new ParameterField();
    ParameterDiscreteValue paramDiscreteValue = new ParameterDiscreteValue();
    paramField.Name = @"class";
    paramDiscreteValue.Value = textBox1.Text.ToString();
    paramField.CurrentValues.Add(paramDiscreteValue);
    paramFields.Add(paramField);

    reportDocument.Load(@"C:\Users\Administrator\Documents\Visual Studio 2010\Projects\CrudStudent\Crud\CrystalReport1.rpt");
    crystalReportViewer1.ParameterFieldInfo = paramFields;
    reportDocument.SetDataSource(DataSet2);
    crystalReportViewer1.ReportSource = reportDocument;
    con.Close();
}
</code>```

答:
Passing a parameter look like this:

```<code>CRPT.SetParameterValue("parameterName", parameterValue);
</code>```

See this link for more details.

Body:
I have a crystal report in which I set the datasource and parameter programmatically but it is not working. I'm not getting the output as required.

This is the output when i show all

But when I pass parameters to it, it shows nothing.
I checked in DataTable by applying debugging the data is Filtered but it is not showing in my Crystal Report Viewer

This is what I get when I passed parameters to it.

Here is my code:

private void button1_Click(object sender, EventArgs e)
{
    con.Open();
    DataTable table = new DataTable();
    DataSet DataSet2 = new DataSet();
    SqlCommand cmd = new SqlCommand("Select * from personal_data WHERE class = '" + textBox1.Text.ToString()+"'", con);

    table.Load(cmd.ExecuteReader());

    DataSet2.DataSetName = "dt";
    DataSet2.AcceptChanges();

    DataSet2.Tables.Add(table);
    ad.SelectCommand=cmd;
    ad.Fill(DataSet2,"personal_table");

    ParameterFields paramFields = new ParameterFields();
    // ParameterDiscreteValue paramDiscreteValue = new ParameterDiscreteValue();

    ParameterField paramField = new ParameterField();
    ParameterDiscreteValue paramDiscreteValue = new ParameterDiscreteValue();
    paramField.Name = @"class";
    paramDiscreteValue.Value = textBox1.Text.ToString();
    paramField.CurrentValues.Add(paramDiscreteValue);
    paramFields.Add(paramField);

    reportDocument.Load(@"C:\Users\Administrator\Documents\Visual Studio 2010\Projects\CrudStudent\Crud\CrystalReport1.rpt");
    crystalReportViewer1.ParameterFieldInfo = paramFields;
    reportDocument.SetDataSource(DataSet2);
    crystalReportViewer1.ReportSource = reportDocument;
    con.Close();
}

Body:
Passing a parameter look like this:

CRPT.SetParameterValue("parameterName", parameterValue);

See this link for more details.


问:
add elements multiple values in XDocument C#
I want to add a section with tag name called properties, and have one item value called property with multiple value, like node name, value

org xml file is like this

```<code><testsuites>
    <testsuite>
        blah blah
    </testsuite>
</testsuites>
</code>```

After add, i want it show like this

```<code><testsuites>
    <testsuite>
        <properties>
        <property name="name" "value"="desirevalue"/>
        </properties>
        blah blah
    </testsuite>
</testsuites>
</code>```

The code that i wrote has some problems, it actually create two line of property, but i want them as one line. How should i update my code? Also seems last two line has problems. i get "object reference not set to an instance of an object" error

```<code>XDocument doc = XDocument.Load(fileOfReportInXML);
XElement root= new XElement("properties");
root.Add(new XElement("property", "name= node"));
root.Add(new XElement("property","value=desirevalue"));
doc.Element("testsuite").Add(root);
doc.Save(fileOfReportInXML);
</code>```

答:
Try following code:

```<code>//Load XML file
XDocument doc = XDocument.Load(fileOfReportInXML);
</code>```

Edit: Add element to the first element of your xdocument

```<code>doc.Root.Elements("testsuite").First().Add(new XElement("properties", new XElement("property", new XAttribute("name", "name"), new XAttribute("value", "desirevalue"))));
</code>```

if you want to add new elements to all your testsuite elements:

```<code>foreach (var element in doc.Root.Elements("testsuite"))
{
     //Skip adding element if element already exists
     if (element.HasElements && element.Element("properties") != null) continue;

     element.Add(new XElement("properties", new XElement("property", new XAttribute("name", "name"), new XAttribute("value", "desirevalue"))));
}
</code>```

Save the XML document

```<code>//Save XML file
doc.Save(fileOfReportInXML);
</code>```

Body:
I want to add a section with tag name called properties, and have one item value called property with multiple value, like node name, value

org xml file is like this

<testsuites>
    <testsuite>
        blah blah
    </testsuite>
</testsuites>

After add, i want it show like this

<testsuites>
    <testsuite>
        <properties>
        <property name="name" "value"="desirevalue"/>
        </properties>
        blah blah
    </testsuite>
</testsuites>

The code that i wrote has some problems, it actually create two line of property, but i want them as one line. How should i update my code? Also seems last two line has problems. i get "object reference not set to an instance of an object" error

XDocument doc = XDocument.Load(fileOfReportInXML);
XElement root= new XElement("properties");
root.Add(new XElement("property", "name= node"));
root.Add(new XElement("property","value=desirevalue"));
doc.Element("testsuite").Add(root);
doc.Save(fileOfReportInXML);

Body:
Try following code:

//Load XML file
XDocument doc = XDocument.Load(fileOfReportInXML);

Edit: Add element to the first element of your xdocument

doc.Root.Elements("testsuite").First().Add(new XElement("properties", new XElement("property", new XAttribute("name", "name"), new XAttribute("value", "desirevalue"))));

if you want to add new elements to all your testsuite elements:

foreach (var element in doc.Root.Elements("testsuite"))
{
     //Skip adding element if element already exists
     if (element.HasElements && element.Element("properties") != null) continue;

     element.Add(new XElement("properties", new XElement("property", new XAttribute("name", "name"), new XAttribute("value", "desirevalue"))));
}

Save the XML document

//Save XML file
doc.Save(fileOfReportInXML);


问:
Enable CORS via Web.config not working for .net WebApi
I am trying to get CORS working for my MVC Post action.

I have an MVC attribute:

```<code>using System;
using System.Configuration;
using System.Web.Mvc;
using System.Web.WebPages.Razor.Configuration;

namespace MyApp
{
    public class AllowCorsJsonAttribute : ActionFilterAttribute
    {
        private static String _allowHosts = null;
        public static String AllowHosts
        {
            get
            {
                if(_allowHosts == null)
                {
                    _allowHosts = ConfigurationManager.AppSettings["CorsAllowHost"] ?? "";
                }
                return _allowHosts;
            }
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
#if DEBUG
            if (filterContext.RequestContext.HttpContext.Request.IsLocal)
            {
                filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", AllowHosts);
                filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Headers", "*");
                filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Methods", "*");
                filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Credentials", "true");
            }
#endif
            base.OnActionExecuting(filterContext);
        }
    }
}
</code>```

To Enable CORS for my web api controllers I do this:

```<code>public static class WebApiConfig
{
    private static void EnableCrossSiteRequests(HttpConfiguration config)
    {
#if DEBUG
        var cors = new EnableCorsAttribute(
            origins: AllowCorsJsonAttribute.AllowHosts,
            headers: "*",
            methods: "*")
        {
            SupportsCredentials = true
        };
        config.EnableCors(cors);
#endif
    }

    public static void Register(HttpConfiguration config)
    {
        EnableCrossSiteRequests(config);
        ....
    }
</code>```

I am able to do GET/PUT/etc to my webAPI2 controllers alright. I am able to do Get requests to my MVC controller actions which have the [AllowCorsJson] attribute. However, I am unable to POST to an MVC action as the preflight OPTIONS check keeps failing. The options response has none of the CORS headers in it. It is like my Attribute is not even working for  POST methods.

This get request works when I have the attribute applied to it.

```<code>    [AllowCorsJson]
    public ActionResult GetExecuteModel(Int32 id)
    {
        var editorModel = GetExecutionModel(id);
        editorModel.UserList = null;
        return Json(editorModel, JsonRequestBehavior.AllowGet);
    }
</code>```

However POST'ing to this URL fails:

```<code>    [HttpPost]
    [AllowCorsJson]
    public ActionResult ExecuteSave(MyModel myModel)
    {
        if (!ModelState.IsValid)
        {
            Response.StatusCode = (Int32)HttpStatusCode.BadRequest;
            return Json(ModelState);
        }

        UpdateMyModel(myModel);

        return Json(null);
    }
</code>```

For some reason the the my Filter Attribute does not seem to fire when POST'ing to the ExecuteSave function. Why would this be?

Help appreciated.

答:
You can enable CORS in your webapi2 application oby using the following line of code in WebApiConfig.cs:

```<code> config.EnableCors(allowedApp);
</code>```

Also you need to install the following NUGET package to achieve this:

```<code> Install-Package Microsoft.AspNet.WebApi.Cors
</code>```

Body:
I am trying to get CORS working for my MVC Post action.

I have an MVC attribute:

using System;
using System.Configuration;
using System.Web.Mvc;
using System.Web.WebPages.Razor.Configuration;

namespace MyApp
{
    public class AllowCorsJsonAttribute : ActionFilterAttribute
    {
        private static String _allowHosts = null;
        public static String AllowHosts
        {
            get
            {
                if(_allowHosts == null)
                {
                    _allowHosts = ConfigurationManager.AppSettings["CorsAllowHost"] ?? "";
                }
                return _allowHosts;
            }
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
#if DEBUG
            if (filterContext.RequestContext.HttpContext.Request.IsLocal)
            {
                filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", AllowHosts);
                filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Headers", "*");
                filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Methods", "*");
                filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Credentials", "true");
            }
#endif
            base.OnActionExecuting(filterContext);
        }
    }
}

To Enable CORS for my web api controllers I do this:

public static class WebApiConfig
{
    private static void EnableCrossSiteRequests(HttpConfiguration config)
    {
#if DEBUG
        var cors = new EnableCorsAttribute(
            origins: AllowCorsJsonAttribute.AllowHosts,
            headers: "*",
            methods: "*")
        {
            SupportsCredentials = true
        };
        config.EnableCors(cors);
#endif
    }

    public static void Register(HttpConfiguration config)
    {
        EnableCrossSiteRequests(config);
        ....
    }

I am able to do GET/PUT/etc to my webAPI2 controllers alright. I am able to do Get requests to my MVC controller actions which have the [AllowCorsJson] attribute. However, I am unable to POST to an MVC action as the preflight OPTIONS check keeps failing. The options response has none of the CORS headers in it. It is like my Attribute is not even working for  POST methods.

This get request works when I have the attribute applied to it.

    [AllowCorsJson]
    public ActionResult GetExecuteModel(Int32 id)
    {
        var editorModel = GetExecutionModel(id);
        editorModel.UserList = null;
        return Json(editorModel, JsonRequestBehavior.AllowGet);
    }

However POST'ing to this URL fails:

    [HttpPost]
    [AllowCorsJson]
    public ActionResult ExecuteSave(MyModel myModel)
    {
        if (!ModelState.IsValid)
        {
            Response.StatusCode = (Int32)HttpStatusCode.BadRequest;
            return Json(ModelState);
        }

        UpdateMyModel(myModel);

        return Json(null);
    }

For some reason the the my Filter Attribute does not seem to fire when POST'ing to the ExecuteSave function. Why would this be?

Help appreciated.

Body:
You can enable CORS in your webapi2 application oby using the following line of code in WebApiConfig.cs:

 config.EnableCors(allowedApp);

Also you need to install the following NUGET package to achieve this:

 Install-Package Microsoft.AspNet.WebApi.Cors


问:
loop for multiple URLs
I am trying to scrape a web page with the following code:-

```<code>import requests
from bs4 import BeautifulSoup

page = requests.get("http://www.realcommercial.com.au/sold/property-offices-retail-showrooms+bulky+goods-land+development-hotel+leisure-medical+consulting-other-in-vic/list-1?includePropertiesWithin=includesurrounding&activeSort=list-date&autoSuggest=true")

soup = BeautifulSoup(page.content, 'html.parser')
links = soup.find_all('a', attrs ={'class' :'details-panel'})
hrefs = [link['href'] for link in links]

for urls in hrefs:
    pages = requests.get(urls)
    soup_2 =BeautifulSoup(pages.content, 'html.parser')

    Date = soup_2.find_all('li', attrs ={'class' :'sold-date'})
    Sold_Date = [Sold_Date.text.strip() for Sold_Date in Date]
    Address_1 = soup_2.find_all('p', attrs={'class' :'full-address'})
    Address = [Address.text.strip() for Address in Address_1]
</code>```

the above code is returning only the details from the first URL in the hrefs.

```<code>['Mon 05-Jun-17'] ['261 Keilor Road, Essendon, Vic 3040']
</code>```

I need the loop to run through each URL in hrefs & return similar details from each URL in hrefs.
Please suggest what should i add/edit in the above code.
Any help would be highly appreciated.

Thanks

答:
You are overwriting Address and Sold_Date objects on each iteration:

```<code># after assignment previous data will be lost
Sold_Date = [Sold_Date.text.strip() for Sold_Date in Date]
Address = [Address.text.strip() for Address in Address_1]
</code>```

Try to initialize empty lists outside of loop and extend them

```<code>import requests
from bs4 import BeautifulSoup

page = requests.get("http://www.realcommercial.com.au/sold/property-offices-retail-showrooms+bulky+goods-land+development-hotel+leisure-medical+consulting-other-in-vic/list-1?includePropertiesWithin=includesurrounding&activeSort=list-date&autoSuggest=true")

soup = BeautifulSoup(page.content, 'html.parser')
links = soup.find_all('a', attrs={'class': 'details-panel'})
hrefs = [link['href'] for link in links]

addresses = []
sold_dates = []
for urls in hrefs:
    pages = requests.get(urls)
    soup_2 = BeautifulSoup(pages.content, 'html.parser')

    dates_tags = soup_2.find_all('li', attrs={'class': 'sold-date'})
    sold_dates += [date_tag.text.strip() for date_tag in dates_tags]
    addresses_tags = soup_2.find_all('p', attrs={'class': 'full-address'})
    addresses += [address_tag.text.strip() for address_tag in addresses_tags]
</code>```

gives us

```<code>>>>sold_dates
[u'Tue 06-Jun-17',
 u'Tue 06-Jun-17',
 u'Tue 06-Jun-17',
 u'Tue 06-Jun-17',
 u'Tue 06-Jun-17',
 u'Tue 06-Jun-17',
 u'Tue 06-Jun-17',
 u'Mon 05-Jun-17',
 u'Mon 05-Jun-17',
 u'Mon 05-Jun-17']
>>>addresses
[u'141 Napier Street, Essendon, Vic 3040',
 u'5 Loupe Crescent, Leopold, Vic 3224',
 u'80 Ryrie Street, Geelong, Vic 3220',
 u'18 Boase Street, Brunswick, Vic 3056',
 u'130-186 Buckley Street, West Footscray, Vic 3012',
 u'223 Park Street, South Melbourne, Vic 3205',
 u'48-50 The Centreway, Lara, Vic 3212',
 u'14 Webster Street, Ballarat, Vic 3350',
 u'323 Nepean Highway, Frankston, Vic 3199',
 u'341 Buckley Street, Aberfeldie, Vic 3040']
</code>```

Title: loop for multiple URLs

Body:
I am trying to scrape a web page with the following code:-

import requests
from bs4 import BeautifulSoup

page = requests.get("http://www.realcommercial.com.au/sold/property-offices-retail-showrooms+bulky+goods-land+development-hotel+leisure-medical+consulting-other-in-vic/list-1?includePropertiesWithin=includesurrounding&activeSort=list-date&autoSuggest=true")

soup = BeautifulSoup(page.content, 'html.parser')
links = soup.find_all('a', attrs ={'class' :'details-panel'})
hrefs = [link['href'] for link in links]

for urls in hrefs:
    pages = requests.get(urls)
    soup_2 =BeautifulSoup(pages.content, 'html.parser')

    Date = soup_2.find_all('li', attrs ={'class' :'sold-date'})
    Sold_Date = [Sold_Date.text.strip() for Sold_Date in Date]
    Address_1 = soup_2.find_all('p', attrs={'class' :'full-address'})
    Address = [Address.text.strip() for Address in Address_1]

the above code is returning only the details from the first URL in the hrefs.

['Mon 05-Jun-17'] ['261 Keilor Road, Essendon, Vic 3040']

I need the loop to run through each URL in hrefs & return similar details from each URL in hrefs.
Please suggest what should i add/edit in the above code.
Any help would be highly appreciated.

Thanks

Body:
You are overwriting Address and Sold_Date objects on each iteration:

# after assignment previous data will be lost
Sold_Date = [Sold_Date.text.strip() for Sold_Date in Date]
Address = [Address.text.strip() for Address in Address_1]

Try to initialize empty lists outside of loop and extend them

import requests
from bs4 import BeautifulSoup

page = requests.get("http://www.realcommercial.com.au/sold/property-offices-retail-showrooms+bulky+goods-land+development-hotel+leisure-medical+consulting-other-in-vic/list-1?includePropertiesWithin=includesurrounding&activeSort=list-date&autoSuggest=true")

soup = BeautifulSoup(page.content, 'html.parser')
links = soup.find_all('a', attrs={'class': 'details-panel'})
hrefs = [link['href'] for link in links]

addresses = []
sold_dates = []
for urls in hrefs:
    pages = requests.get(urls)
    soup_2 = BeautifulSoup(pages.content, 'html.parser')

    dates_tags = soup_2.find_all('li', attrs={'class': 'sold-date'})
    sold_dates += [date_tag.text.strip() for date_tag in dates_tags]
    addresses_tags = soup_2.find_all('p', attrs={'class': 'full-address'})
    addresses += [address_tag.text.strip() for address_tag in addresses_tags]

gives us

>>>sold_dates
[u'Tue 06-Jun-17',
 u'Tue 06-Jun-17',
 u'Tue 06-Jun-17',
 u'Tue 06-Jun-17',
 u'Tue 06-Jun-17',
 u'Tue 06-Jun-17',
 u'Tue 06-Jun-17',
 u'Mon 05-Jun-17',
 u'Mon 05-Jun-17',
 u'Mon 05-Jun-17']
>>>addresses
[u'141 Napier Street, Essendon, Vic 3040',
 u'5 Loupe Crescent, Leopold, Vic 3224',
 u'80 Ryrie Street, Geelong, Vic 3220',
 u'18 Boase Street, Brunswick, Vic 3056',
 u'130-186 Buckley Street, West Footscray, Vic 3012',
 u'223 Park Street, South Melbourne, Vic 3205',
 u'48-50 The Centreway, Lara, Vic 3212',
 u'14 Webster Street, Ballarat, Vic 3350',
 u'323 Nepean Highway, Frankston, Vic 3199',
 u'341 Buckley Street, Aberfeldie, Vic 3040']


问:
How to Login Using Gmail account in Android
Google Authentication can verify my account if my account is added in my device.

But I want to login from my application login form where user will give his gmail account Id and password. I will test whether the gmail account is valid or not what the user has entered.

答:
```<code>**Dependency**
    **Need Internet Permission**

**Working Code   see Link on  play Store**
https://play.google.com/store/search?q=com.codecube.airbucks

    compile 'com.google.android.gms:play-services:8.3.0'

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <com.google.android.gms.common.SignInButton
            android:id="@+id/sign_in_button"
            android:layout_width="200dp"
            android:layout_marginTop="20dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal" />
        <Button
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:layout_gravity="center_horizontal"
            android:text="Logout"
            android:id="@+id/btn"/>
    </LinearLayout>

    package com.keshav.geofencing;

    import android.Manifest;
    import android.annotation.TargetApi;
    import android.app.ProgressDialog;
    import android.content.BroadcastReceiver;
    import android.content.Intent;
    import android.content.pm.PackageManager;
    import android.net.Uri;
    import android.os.Build;
    import android.os.Bundle;
    import android.support.v4.app.ActivityCompat;
    import android.support.v4.content.ContextCompat;
    import android.support.v4.content.LocalBroadcastManager;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.LinearLayout;
    import android.widget.TextView;

    import com.facebook.CallbackManager;
    import com.facebook.FacebookCallback;
    import com.facebook.FacebookException;
    import com.facebook.FacebookSdk;
    import com.facebook.GraphRequest;
    import com.facebook.GraphResponse;
    import com.facebook.login.LoginManager;
    import com.facebook.login.LoginResult;
    import com.google.android.gms.appindexing.Action;
    import com.google.android.gms.appindexing.AppIndex;
    import com.google.android.gms.auth.api.Auth;
    import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
    import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
    import com.google.android.gms.auth.api.signin.GoogleSignInResult;
    import com.google.android.gms.common.ConnectionResult;
    import com.google.android.gms.common.GoogleApiAvailability;
    import com.google.android.gms.common.api.GoogleApiClient;
    import com.google.android.gms.common.api.OptionalPendingResult;
    import com.google.android.gms.common.api.ResultCallback;
    import com.google.android.gms.common.api.Status;

    import org.json.JSONException;
    import org.json.JSONObject;

    import java.util.Arrays;

    import utilities.CommonMethod;
    import utilities.LoginPreferences;

    public class LoginWithGmail extends AppCompatActivity
            implements GoogleApiClient.OnConnectionFailedListener {

        private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
        private static final String TAG = "LoginActivity";
        private static final int RC_SIGN_IN = 9001;
        Button loginSub;
        LinearLayout signInButton;

        String gmailId;
        String gmailName;
        String gmailUserEmailId;
        Uri gmailUserPhoto;
        String savePassword;
        LinearLayout btnlogin;
        TextView btnsigning;
        ProgressDialog prgDialog;

        private CallbackManager callbackManager;

        private BroadcastReceiver mRegistrationBroadcastReceiver;
        private LinearLayout fbloginButton;
    //    private CallbackManager callbackManager;
        private ProgressDialog mProgressDialog;
        private GoogleApiClient mGoogleApiClient;

        EditText edtEmail;

        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_login1);

            checkPermission();

            GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build();

            mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .addApi(AppIndex.API).build();

            // Google Sign up Button
            signInButton = (LinearLayout) findViewById(R.id.sign_in_button);

            signInButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        int permissionCheck = ContextCompat.checkSelfPermission(LoginWithGmail.this, Manifest.permission.CAMERA);
                        if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                            //showing dialog to select image

                            Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
                            signInIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                            startActivityForResult(signInIntent, RC_SIGN_IN);
                            Log.e("permission", "granted");
                        } else {
                            ActivityCompat.requestPermissions(LoginWithGmail.this,
                                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                                            Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 1);
                        }
                    } else {
                        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
                        signInIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        startActivityForResult(signInIntent, RC_SIGN_IN);
                    }

                }
            });

        }

        public void checkPermission() {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                int permissionCheck = ContextCompat.checkSelfPermission(LoginWithGmail.this,
                        Manifest.permission.CAMERA);

                if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                    //showing dialog to select image
                    if (CommonMethod.isNetworkAvailable(LoginWithGmail.this)) {
                        Log.e("keshav", "Permission if part marsh");
                    } else {
                        CommonMethod.showAlert("Internet Connectivity Failure", LoginWithGmail.this);
                    }

                    Log.e("keshav", "permission granted");
                } else {
                    ActivityCompat.requestPermissions(LoginWithGmail.this,
                            new String[]{Manifest.permission.CAMERA,
                                    Manifest.permission.ACCESS_FINE_LOCATION,
                                    Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
                }
            }
        }

        @Override
        protected void onResume() {
            super.onResume();
    //        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
    //                new IntentFilter(QuickstartPreferences.REGISTRATION_COMPLETE));
        }

        @Override
        protected void onPause() {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
            super.onPause();
        }

        @Override
        public void onBackPressed() {
            super.onBackPressed();

        }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {

            if (requestCode == RC_SIGN_IN) {
                GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
                handleSignInResult(result);
            }
        }

        // TODO ADD ME

        @Override
        public void onStart() {
            super.onStart();

            OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
            if (opr.isDone()) {
                // If the user's cached credentials are valid, the OptionalPendingResult will be "done"
                // and the GoogleSignInResult will be available instantly.
                Log.e(TAG, "Got cached sign-in");
                GoogleSignInResult result = opr.get();
                handleSignInResult(result);
            } else {
                // If the user has not previously signed in on this device or the sign-in has expired,
                // this asynchronous branch will attempt to sign in the user silently.  Cross-device
                // single sign-on will occur in this branch.
                showProgressDialog();
                opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
                    @Override
                    public void onResult(GoogleSignInResult googleSignInResult) {
                        hideProgressDialog();
                        handleSignInResult(googleSignInResult);
                    }
                });
            }
        }

        // [START signOut]
        private void signOut() {
            Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
                    new ResultCallback<Status>() {
                        @Override
                        public void onResult(Status status) {
                            // [START_EXCLUDE]
    //                        updateUI(false);
                            // [END_EXCLUDE]
                        }
                    });
        }
        // [END signOut]

        // [START revokeAccess]
        private void revokeAccess() {
            Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
                    new ResultCallback<Status>() {
                        @Override
                        public void onResult(Status status) {
                            // [START_EXCLUDE]
    //                        updateUI(false);
                            // [END_EXCLUDE]
                        }
                    });
        }
        // [END revokeAccess]

        @Override
        public void onConnectionFailed(ConnectionResult connectionResult) {
            // An unresolvable error has occurred and Google APIs (including Sign-In) will not
            // be available.
            Log.e(TAG, "onConnectionFailed:" + connectionResult);
        }

        private void showProgressDialog() {
            if (mProgressDialog == null) {
                mProgressDialog = new ProgressDialog(this);
                mProgressDialog.setMessage("Loading...");
                mProgressDialog.setIndeterminate(true);
            }
            if (LoginWithGmail.this != null && mProgressDialog != null && !mProgressDialog.equals("null"))
                mProgressDialog.show();
        }

        private void hideProgressDialog() {
            if (mProgressDialog != null && mProgressDialog.isShowing()&& !mProgressDialog.equals("null")) {
                mProgressDialog.hide();
            }
        }

        // TODO ADD ME ENd

        private void handleSignInResult(GoogleSignInResult result) {
            Log.e("&&&s", "handleSignInResult:" + result.isSuccess());
            if (result.isSuccess()) {
                // Signed in successfully, show authenticated UI.
                GoogleSignInAccount acct = result.getSignInAccount();

                gmailId = acct.getId();
                gmailName = acct.getDisplayName();
                gmailUserEmailId = acct.getEmail();
                gmailUserPhoto = acct.getPhotoUrl();

                Log.e("gmailId", "is -->" + gmailId);
                Log.e("gmailName", "is -->" + gmailName);
                Log.e("gmailUserEmailId", "is -->" + gmailUserEmailId);
                Log.e("gmailUserPhoto", "is -->" + gmailUserPhoto);

                LoginPreferences.getActiveInstance(LoginWithGmail.this).setUserName(gmailName);
                LoginPreferences.getActiveInstance(LoginWithGmail.this).setProfileImage(""+gmailUserPhoto);

                Log.e("information", "using Gmail is > " + gmailId + " " + gmailName + "" + gmailUserEmailId + "" + gmailUserPhoto);

                if (CommonMethod.isNetworkAvailable(LoginWithGmail.this)) {
                    Log.e("SignUp gmail", "Hit API..........................");
                    Intent i=new Intent(LoginWithGmail.this,DrawerActivity.class);
                    LoginPreferences.getActiveInstance(LoginWithGmail.this).setIsLoggedIn(true);
                    startActivity(i);
                    finish();

                    // TODO Here Registered User in own Database call Volley Retrofit2 Api ....
                    new SignUpSocialFacebookAsyncTask().execute();
                } else {
                    CommonMethod.showAlert("Intenet Connectivity Failure", LoginWithGmail.this);
                }

            } else {

            }
            // TODO ADD ME KESHAV Google GMail Logout
            Auth.GoogleSignInApi.signOut(mGoogleApiClient);
        }

        @Override
        public void onStop() {
            super.onStop();

            // ATTENTION: This was auto-generated to implement the App Indexing API.
            // See https://g.co/AppIndexing/AndroidStudio for more information.
            Action viewAction = Action.newAction(
                    Action.TYPE_VIEW, // TODO: choose an action type.
                    "Login Page", // TODO: Define a title for the content shown.
                    // TODO: If you have web page content that matches this app activity's content,
                    // make sure this auto-generated web page URL is correct.
                    // Otherwise, set the URL to null.
                    Uri.parse("http://host/path"),
                    // TODO: Make sure this auto-generated app deep link URI is correct.
                    Uri.parse("android-app://com.keshav.geofencing/http/host/path")
            );
            AppIndex.AppIndexApi.end(mGoogleApiClient, viewAction);
            mGoogleApiClient.disconnect();
        }

        //Todo  add new method for permission
        @TargetApi(Build.VERSION_CODES.M)
        @Override
        public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
            if (requestCode == RC_SIGN_IN) {
                Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
                signInIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivityForResult(signInIntent, RC_SIGN_IN);

            }
        }

    }

    **Dependency**
    **Need Internet Permission**

**Working Code   see Link on  play Store**
https://play.google.com/store/search?q=com.codecube.airbucks

Please Like this post if it is helpful
</code>```


问:
Can we fix the direction of page if the body language changes?
i have a web form in which i change body language in master to arabic and english on selection of dropdown so the direction of elements changes from ltr to rtl ( if English to arabic) and vice versa. i have one page which inherits this master page and i dont want this page elements to change their directions when body language change.

This is how it looks when body language is english

And when convert to arabic it looks like this

I have used dir attribute (dir='ltr') on elements of this page but it still changes its direction when change language

HTML of This Page :

```<code>     <div id="#phone" style="direction:ltr" dir="ltr">

                      <div class="col-xs-12 col-sm-6 col-md-6 scrolling-list-container" dir="ltr">
                        <div class="boxpadding boxshadow title-bar-standalone">
                            <div class="col-xs-2 col-sm-1 col-md-1 pull-left"><i class="max_side_icon fa fa-bolt"></i></div>
                            <ul class="scrolling-list-holder">
                                <%= FillEntityLevel() %>
                            </ul>
                        </div>
                    </div>
                    <div class="col-xs-12 col-sm-6 col-md-6 scrolling-list-container" dir="ltr">
                        <div class="boxpadding boxshadow title-bar-standalone">
                            <div class="col-xs-2 col-sm-1 col-md-1 pull-left"><i class="max_side_icon fa fa-bolt"></i></div>
                            <ul class="scrolling-list-holder">
                                <%= FillServiceLevel() %>
                            </ul>
                        </div>
                    </div>

                       <div class="panel panel-default panel-osmm-1 panel-osmm-3" dir="ltr">
         <span>Progress</span>
                  <div class="row nopadding" dir="ltr">
                      <div class="col-md-12 nopadding" dir="ltr">

                          <div class="row" dir="ltr">

                              <div class="col-lg-6 nopadding" dir="ltr">
                                  <h3 style="text-align:center">Progress Chart</h3> <br />
                                           <div id="Chart1Progress" class="ProgressChart" style="stroke-width:0px; width:550px" dir="ltr">

                               </div>

                              </div>
                                  <div class="col-md-2  nopadding" dir="ltr">
                                       <h3>Late Services</h3>
                              <div id="Chart2" class="grow  LateServiceChart" style="width:300px; height:100%" dir="ltr">

                               </div>
                               </div>

                                      <div class="col-md-2 nopadding" dir="ltr">
                                      <h3>Ongoing Services</h3>

                                       <div id="Chart3" class="grow OngoingServices" style="width:300px; height:100%" dir="ltr">

                               </div>
                               </div>

                                      <div class="col-md-2 nopadding" dir="ltr">
                                      <h3>Complete Services</h3>

                                   <div id="Chart4" class="grow CompleteServices" style="  width:300px; height:100%" dir="ltr">

                               </div>
                               </div>

                              </div>

                          </div>

                      </div>
                  </div>

       <div class="col-xs-12 col-sm-6 col-md-6 " style="direction:ltr" dir="ltr">
        <div class="panel panel-default panel-osmm-1 panel-osmm-3" dir="ltr">
            <div class="panel-heading">
                <div class="col-xs-2 col-sm-2 col-md-1 pull-right"><i class="panel-heading-icon fa fa-book"></i></div>
                Status
            </div>
            <div class="panel-body">

              You are at Add Scenario :
                <br /><br />
                <div class="row">
                    <div class="col-md-12">
                            <div class="col-md-4 " style="text-align:center">
                            <div class="FlowChartmain">
<div class="FlowChartcircle grow" id="C1">
<img src="images/user.png" />
</div>
<div id="horizontal_line1"></div>
<div class="FlowChartcircle grow" id="C2">
<img src="images/user.png" />
</div>
<div class="line" id="horizontal_line2"></div>
<div class="FlowChartcircle grow"id="C3">
<img src="images/user.png" />
</div>

<div class="line" id="vertical_line1"></div>

    <div class="FlowChartcircle grow"id="C4">
<img src="images/user.png" />
    </div>
    <div id="horizontal_line3"></div>

    <div class="FlowChartcircle grow" id="C5">
<img src="images/user.png" />
    </div>
    <div class="line" id="horizontal_line4"></div>
    <div class="FlowChartcircle grow"id="C6">
<img src="images/user.png" />
    </div>

<div class="line" id="vertical_line2"></div>

    <div class="FlowChartcircle grow"id="C7">
<img src="images/user.png" />
    </div>
    <div id="horizontal_line5"></div>
    <div class="FlowChartcircle grow"id="C8">
<img src="images/user.png" />
    </div>
    <div id="horizontal_line6"></div>
    <div class="FlowChartcircle grow"id="C9">
<img src="images/user.png" />

    </div>
</div>

                     </div>

<%--                     <div class="col-md-4 grow" style="text-align:center">
                              <a href="OSMM_ScenarioSetting.aspx">

                       <img width="100px" src="images/1.png" />
                       <br/>
                       <span>Add Scenario</span>
                                  </a>

                     </div>--%>

                        <div class="col-md-4 pull-right">
              <span><b>Days Left</b></span><br />
         <div id="myclock" class="myclock timer"></div>

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

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

        <div class="col-xs-12 col-sm-6 col-md-6">
        <div class="panel panel-default panel-osmm-1 panel-osmm-3">
            <div class="panel-heading">
                <div class="col-xs-2 col-sm-2 col-md-1 pull-right"><i class="panel-heading-icon fa fa-pencil"></i></div>
             Description
            </div>
            <div class="panel-body">

مشروع إطار الإجادة الوطني يهدف إلى قياس جودة الأداء المؤسسي من خلال قياس 6 معايير أساسية ومعرفة مدى تطبيق الجهات الحكومية اللوائح والقوانين الصادرة من الخدمة المدنية:  دليل الخدمات  و الميثاق والتحول الإلكتروني للخدمات.

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

         <br />         <br />
         <br />
         <br />
         <br />

    <div class="col-xs-12 col-sm-6 col-md-6 ">
        <div class="panel panel-default panel-osmm-1 panel-osmm-3">
            <div class="panel-heading">
                <div class="col-xs-2 col-sm-2 col-md-1 pull-right"><i class="panel-heading-icon fa fa-pencil"></i></div>
                <%= Resources.Lang.ListDelayedServices %>
            </div>
            <div class="panel-body scrolling-list-container">

                    <%= FillServiceInfo(1) %>

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

    <div class="col-xs-12 col-sm-6 col-md-6">
        <div class="panel panel-default panel-osmm-1 panel-osmm-3">
            <div class="panel-heading">
                <div class="col-xs-2 col-sm-2 col-md-1 pull-right"><i class="panel-heading-icon fa fa-pencil"></i></div>
                <%= Resources.Lang.ListofOngoingServices %>
            </div>
            <div class="panel-body scrolling-list-container">

                    <%= FillServiceInfo(2) %>

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

                </div>

        <div class="panel panel-default panel-osmm-1" runat="server" visible="false">
            <div class="panel-heading" ">
                <div class="col-xs-3 col-sm-3 col-md-2 pull-left"><i class="panel-heading-icon fa fa-area-chart"></i></div>
                <span class="local-sm-push"><%= Resources.Lang.Agency_Level %></span>
            </div>
</code>```

答: putting the direction in the class should solve your problem.</p>

Body:
i have a web form in which i change body language in master to arabic and english on selection of dropdown so the direction of elements changes from ltr to rtl ( if English to arabic) and vice versa. i have one page which inherits this master page and i dont want this page elements to change their directions when body language change.

This is how it looks when body language is english

And when convert to arabic it looks like this

I have used dir attribute (dir='ltr') on elements of this page but it still changes its direction when change language

HTML of This Page :

                                <%= FillEntityLevel() %>

                                <%= FillServiceLevel() %>

         Progress

Progress Chart

Late Services

Ongoing Services

Complete Services

                Status

              You are at Add Scenario :

<%--

                       Add Scenario

--%>

              Days Left

             Description

مشروع إطار الإجادة الوطني يهدف إلى قياس جودة الأداء المؤسسي من خلال قياس 6 معايير أساسية ومعرفة مدى تطبيق الجهات الحكومية اللوائح والقوانين الصادرة من الخدمة المدنية:  دليل الخدمات  و الميثاق والتحول الإلكتروني للخدمات.

                <%= Resources.Lang.ListDelayedServices %>

                    <%= FillServiceInfo(1) %>

                <%= Resources.Lang.ListofOngoingServices %>

                    <%= FillServiceInfo(2) %>

                <%= Resources.Lang.Agency_Level %>


问:
Is there a standard C function for computing the string length up to some limit?
Consider a situation: I have a buffer of known length that presumably stores a null-terminated string and I need to know the length of the string.

The problem is if I use strlen() and the string turns out to be not null-terminated the program runs into undefined behavior while reading beyond the buffer end. So I'd like to have a function like the following:

```<code> size_t strlenUpTo( char* buffer, size_t limit )
 {
     size_t count = 0;
     while( count < limit && *buffer != 0 ) {
        count++;
        buffer++;
     }
     return count;
 }
</code>```

so that it returns the length of the string but never tries to read beyond the buffer end.

Is there such function already in C library or do I have to use my own?

答:
Use memchr(string, 0, limit), as in:

```<code>size_t strlenUpTo(char *s, size_t n)
{
    char *z = memchr(s, 0, n);
    return z ? z-s : n;
}
</code>```

Body:
Consider a situation: I have a buffer of known length that presumably stores a null-terminated string and I need to know the length of the string.

The problem is if I use strlen() and the string turns out to be not null-terminated the program runs into undefined behavior while reading beyond the buffer end. So I'd like to have a function like the following:

 size_t strlenUpTo( char* buffer, size_t limit )
 {
     size_t count = 0;
     while( count < limit && *buffer != 0 ) {
        count++;
        buffer++;
     }
     return count;
 }

so that it returns the length of the string but never tries to read beyond the buffer end.

Is there such function already in C library or do I have to use my own?

Body:
Use memchr(string, 0, limit), as in:

size_t strlenUpTo(char *s, size_t n)
{
    char *z = memchr(s, 0, n);
    return z ? z-s : n;
}


问:
App crashes because of "context" issue
I'm fairly new to android and having an issue grasping the concept of Contexts and all.

I have a small app that consists of 3 activities:

1- Main Activity

2- Login Activity

3- Splash Activity

I've created a number of classes that are part of MainActivity and run as part of it. One of the classes is a database helper. Database helper needs a context to use and what I do is, in MainActivity:

```<code>public static Context context;
</code>```

and in onResume I do:

```<code>@Override
public void onResume() {
    super.onResume();

    this.context = this;
}
</code>```

All activities work just fine, spalsh works, login works, everything works fine. I've defined everything in Manifest.

But randomly when I leave my app running in background for a while and do other stuff with my phone and open it up, sometimes it just crashes pointing to a function that gets "context" as an argument.

Is there anything I can do to fix this?

Thanks

答: Application crashed as you used only "this" keyword to assign a reference. "this" keyword points to current object. When application in background, "this" can refer to another object. So to avoid crash bind the keyword "this" with activity name like "MainActivity.this" where MainActivity is your current activity name.</p>

Title: App crashes because of "context" issue

Body:
I'm fairly new to android and having an issue grasping the concept of Contexts and all.

I have a small app that consists of 3 activities:

1- Main Activity

2- Login Activity

3- Splash Activity

I've created a number of classes that are part of MainActivity and run as part of it. One of the classes is a database helper. Database helper needs a context to use and what I do is, in MainActivity:

public static Context context;

and in onResume I do:

@Override
public void onResume() {
    super.onResume();

    this.context = this;
}

All activities work just fine, spalsh works, login works, everything works fine. I've defined everything in Manifest.

But randomly when I leave my app running in background for a while and do other stuff with my phone and open it up, sometimes it just crashes pointing to a function that gets "context" as an argument.

Is there anything I can do to fix this?

Thanks


问:
Using Materialize Gem for Rails and Submit Button on Form only works randomly
So I have a form that is working when I don't use Materialize to stylize it. It submits and the info is saved into the database, but the problem arises when I use materialize to stylize the button. It randomly saves the data into the database when it is using the materialize styling(e.g. like 7 times in a row and then it stops and will randomly start working again). Is there a known error with this gem or am I missing something?

```<code>gem 'materialize-sass'
</code>```

View

```<code><%= form_for(@user) do |f| %>
 <div class="action btn waves-effect waves-light actions">
<%= f.submit "Create my account" %>
</div>

 <% end %>
</code>```

答:
Check your styling. In your example button will always work when you click on button caption only.

```<code><button class="btn waves-effect waves-light" type="submit" name="action">Submit
<i class="material-icons right">send</i>
</code>```

Body:
So I have a form that is working when I don't use Materialize to stylize it. It submits and the info is saved into the database, but the problem arises when I use materialize to stylize the button. It randomly saves the data into the database when it is using the materialize styling(e.g. like 7 times in a row and then it stops and will randomly start working again). Is there a known error with this gem or am I missing something?

gem 'materialize-sass'

View

<%= form_for(@user) do |f| %>

<%= f.submit "Create my account" %>

 <% end %>

Body:
Check your styling. In your example button will always work when you click on button caption only.

<button class="btn waves-effect waves-light" type="submit" name="action">Submit
<i class="material-icons right">send</i>


问:
How can I start my MainActivity after Facebook Login to Android app?
I am trying to integrate Facebook login to my app through Firebase. When the user clicks on "Continue with Facebook" button, I see a blue progress bar and then the text on the button changes to "logout". I intent to open another Activity when the Login succeeds. I have used startActivity() method for that. However, nothing happens. Please help!

Below is the extract of onCreate() method of my Login Activity

```<code>     callbackManager = CallbackManager.Factory.create();
    // Register your callback
    LoginManager.getInstance().registerCallback(callbackManager,
            // If the login attempt is successful, then call onSuccess and pass the LoginResult
            new FacebookCallback<LoginResult>() {
                @Override
                public void onSuccess(LoginResult loginResult) {

                    // The HomeScreen.class should load, it is not happening.
                    startActivity(new Intent(getApplicationContext() ,HomeScreen.class));
                    // I get this Log on my screen, which is proof that this loop is executed
                    Log.w("TAG", "User ID: " +
                            loginResult.getAccessToken().getUserId() + "\n" +
                            "Auth Token: " + loginResult.getAccessToken().getToken());
                }
                // If the user cancels the login, then call onCancel
                @Override
                public void onCancel() {
                    Toast.makeText(getApplicationContext(),
                            "Canceled login through Facebook",Toast.LENGTH_LONG).show();
                }
                // If an error occurs, then call onError
                @Override
                public void onError(FacebookException exception) {
                    Toast.makeText(getApplicationContext(),
                            " Facebook Login failed!",Toast.LENGTH_LONG).show();
                    Log.w("FB failed", exception);
                }
            });
</code>```

I am allowing for Google login also through Firebase, for this I have written the onActivityResult method. It is this -

```<code>    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
    if (requestCode == RC_SIGN_IN) {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        if (result.isSuccess()) {
            // Google Sign In was successful, authenticate with Firebase
            GoogleSignInAccount account = result.getSignInAccount();
            firebaseAuthWithGoogle(account);

        } else {
            // Handle failed signin here
           Toast.makeText(getApplicationContext(),
                   "Google Sign In Failed, Please try with Facebook or Email!", Toast.LENGTH_LONG).show();
        }
    }
    callbackManager.onActivityResult(requestCode, resultCode, data);

}
</code>```

答:
If your are using fragment than add this to you fb login button

```<code>buttonLogin.setFragment(this);
</code>```

and in your onSuccess() method, try this

```<code>startActivity(new Intent(getActivity() ,HomeScreen.class));
</code>```

Body:
I am trying to integrate Facebook login to my app through Firebase. When the user clicks on "Continue with Facebook" button, I see a blue progress bar and then the text on the button changes to "logout". I intent to open another Activity when the Login succeeds. I have used startActivity() method for that. However, nothing happens. Please help!

Below is the extract of onCreate() method of my Login Activity

     callbackManager = CallbackManager.Factory.create();
    // Register your callback
    LoginManager.getInstance().registerCallback(callbackManager,
            // If the login attempt is successful, then call onSuccess and pass the LoginResult
            new FacebookCallback<LoginResult>() {
                @Override
                public void onSuccess(LoginResult loginResult) {

                    // The HomeScreen.class should load, it is not happening.
                    startActivity(new Intent(getApplicationContext() ,HomeScreen.class));
                    // I get this Log on my screen, which is proof that this loop is executed
                    Log.w("TAG", "User ID: " +
                            loginResult.getAccessToken().getUserId() + "\n" +
                            "Auth Token: " + loginResult.getAccessToken().getToken());
                }
                // If the user cancels the login, then call onCancel
                @Override
                public void onCancel() {
                    Toast.makeText(getApplicationContext(),
                            "Canceled login through Facebook",Toast.LENGTH_LONG).show();
                }
                // If an error occurs, then call onError
                @Override
                public void onError(FacebookException exception) {
                    Toast.makeText(getApplicationContext(),
                            " Facebook Login failed!",Toast.LENGTH_LONG).show();
                    Log.w("FB failed", exception);
                }
            });

I am allowing for Google login also through Firebase, for this I have written the onActivityResult method. It is this -

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
    if (requestCode == RC_SIGN_IN) {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        if (result.isSuccess()) {
            // Google Sign In was successful, authenticate with Firebase
            GoogleSignInAccount account = result.getSignInAccount();
            firebaseAuthWithGoogle(account);

        } else {
            // Handle failed signin here
           Toast.makeText(getApplicationContext(),
                   "Google Sign In Failed, Please try with Facebook or Email!", Toast.LENGTH_LONG).show();
        }
    }
    callbackManager.onActivityResult(requestCode, resultCode, data);

}

Body:
If your are using fragment than add this to you fb login button

buttonLogin.setFragment(this);

and in your onSuccess() method, try this

startActivity(new Intent(getActivity() ,HomeScreen.class));


问:
Can't subscribe data using one subscribe function in ionic 2
This is my get method.

```<code>    get(url: string, options?: RequestOptionsArgs): Promise<Observable<{}>> {
    return new Promise((resolve, reject) => {
      this._frotzOptions(url, options).then((data) => {
        if (data) {
          resolve(this.http.get(url, data));
        } else
          resolve(false);
      }).catch((err) => {
        reject(err);
      });
    });
  }
</code>```

_frotzOptions method.

```<code>     private _frotzOptions(urlo: string | Request, options: RequestOptionsArgs): Promise<{}> {
    if (!options) {
      options = {}
    }
    if (!options.headers) {
      options.headers = new Headers();
    }
    return new Promise((resolve, reject) => {
      this.storage.get('token').then(token => {
        options.headers.append('Content-Type', 'application/json');
        options.headers.append('Authorization', 'Bearer ' + token);
        if (token) {
          resolve(options);
        }
        else
          resolve(false);
      }).catch((err) => {
        reject(err);
      });
    });

  }
</code>```

home.ts

```<code>var subscription = Observable.fromPromise(this.ahttp.get(url));
subscription.subscribe((data) => {
  data.subscribe(rsp => {
    console.log("rsp", rsp);
  })
}, (err) => {
  console.log(err)
});
</code>```

When I need to use data which are resolving fro the get method, I have to use a subscribe within a subscribe! What is the best way to do this by using a subscribe! Any suggestions! Thank you!

答:
Using a new promise constructor over another promise/observable is an antipattern.
Convert your observable and just return it.

Your get function can be simplified to:

```<code> get(url: string, options?: RequestOptionsArgs): Promise<{}> {
    return this._frotzOptions(url, options).then((data) => {
        if (data) {
          return this.http.get(url, data).toPromise(); //use Observable toPromise function
        } else
          return false;
    }).catch((err) => {
         console.log(err); // handle error
   });
  }
</code>```

And your _frotzOptions function:

```<code>  private _frotzOptions(urlo: string | Request, options: RequestOptionsArgs): Promise<{}> {
    if (!options) {
      options = {}
    }
    if (!options.headers) {
      options.headers = new Headers();
    }
    return this.storage.get('token').then(token => {
        options.headers.append('Content-Type', 'application/json');
        options.headers.append('Authorization', 'Bearer ' + token);
        if (token) {
          return options;
        }
        else
          return false;
    });
  }
</code>```

This is called promise chaining

Body:
This is my get method.

    get(url: string, options?: RequestOptionsArgs): Promise<Observable<{}>> {
    return new Promise((resolve, reject) => {
      this._frotzOptions(url, options).then((data) => {
        if (data) {
          resolve(this.http.get(url, data));
        } else
          resolve(false);
      }).catch((err) => {
        reject(err);
      });
    });
  }

_frotzOptions method.

     private _frotzOptions(urlo: string | Request, options: RequestOptionsArgs): Promise<{}> {
    if (!options) {
      options = {}
    }
    if (!options.headers) {
      options.headers = new Headers();
    }
    return new Promise((resolve, reject) => {
      this.storage.get('token').then(token => {
        options.headers.append('Content-Type', 'application/json');
        options.headers.append('Authorization', 'Bearer ' + token);
        if (token) {
          resolve(options);
        }
        else
          resolve(false);
      }).catch((err) => {
        reject(err);
      });
    });

  }

home.ts

var subscription = Observable.fromPromise(this.ahttp.get(url));
subscription.subscribe((data) => {
  data.subscribe(rsp => {
    console.log("rsp", rsp);
  })
}, (err) => {
  console.log(err)
});

When I need to use data which are resolving fro the get method, I have to use a subscribe within a subscribe! What is the best way to do this by using a subscribe! Any suggestions! Thank you!

Body:
Using a new promise constructor over another promise/observable is an antipattern.
Convert your observable and just return it.

Your get function can be simplified to:

 get(url: string, options?: RequestOptionsArgs): Promise<{}> {
    return this._frotzOptions(url, options).then((data) => {
        if (data) {
          return this.http.get(url, data).toPromise(); //use Observable toPromise function
        } else
          return false;
    }).catch((err) => {
         console.log(err); // handle error
   });
  }

And your _frotzOptions function:

  private _frotzOptions(urlo: string | Request, options: RequestOptionsArgs): Promise<{}> {
    if (!options) {
      options = {}
    }
    if (!options.headers) {
      options.headers = new Headers();
    }
    return this.storage.get('token').then(token => {
        options.headers.append('Content-Type', 'application/json');
        options.headers.append('Authorization', 'Bearer ' + token);
        if (token) {
          return options;
        }
        else
          return false;
    });
  }

This is called promise chaining