问:
Files in folders not found in iOS app using C++
I'm trying to read files stored in assets folder and its subfolders using std::ifstream in an iOS app written mostly in C++ (The same code is also used in other, non-iOS projects), but they're not found. Example: there is a file assets/shaders/ortho2d.vert and I'm trying to load it like this:

```<code>std::ifstream vertFStream( vertFile ); // vertFile's contents is "assets/shaders/ortho2d.vert"
if (!vertFStream) {
    std::cerr << vertFile << " missing!" << std::endl;
    exit( 1 );
}
</code>```

I've added the assets folder to the XCode project as a blue folder and it shows up in Targets->Copy Bundle Resources.

答:
Try this:</p>

```<code>NSBundle *b = [NSBundle mainBundle];
NSString *dir = [b resourcePath];
NSArray *parts = [NSArray arrayWithObjects:
                  dir, @"assets", @"shaders", @"ortho2d.vert", (void *)nil];
NSString *path = [NSString pathWithComponents:parts];
const char *cpath = [path fileSystemRepresentation];
std::string vertFile(cpath);
std::ifstream vertFStream(vertFile);
</code>```

Body:
I'm trying to read files stored in assets folder and its subfolders using std::ifstream in an iOS app written mostly in C++ (The same code is also used in other, non-iOS projects), but they're not found. Example: there is a file assets/shaders/ortho2d.vert and I'm trying to load it like this:

std::ifstream vertFStream( vertFile ); // vertFile's contents is "assets/shaders/ortho2d.vert"
if (!vertFStream) {
    std::cerr << vertFile << " missing!" << std::endl;
    exit( 1 );
}

I've added the assets folder to the XCode project as a blue folder and it shows up in Targets->Copy Bundle Resources.

Body:
Try this:

NSBundle *b = [NSBundle mainBundle];
NSString *dir = [b resourcePath];
NSArray *parts = [NSArray arrayWithObjects:
                  dir, @"assets", @"shaders", @"ortho2d.vert", (void *)nil];
NSString *path = [NSString pathWithComponents:parts];
const char *cpath = [path fileSystemRepresentation];
std::string vertFile(cpath);
std::ifstream vertFStream(vertFile);


来源: stackexchange

问:
CSS transition out error
and sorry for my horrible english.
I have got a problem with CSS and transition.

I need to make a div 100px x 100px, it's just an example of course.

When I put cursor hover it, it should grow and be 500px x 500px.

And here, everything is fine and working.
The thing is, when i remove the cursor, I need that the div return back to 100x100px, but it won't have a transition, it just disappear and return 100x100px.
How can I fix this?

Here is the code i use.

```<code><html>
<head>
  <style>
    div.resize {
      width: 100px;
      height: 100px;
      background: rgb(80,80,80);
      }
      div.resize:hover {
      width: 500px;
      height: 500px;
      transition-duration: 1s;
      }
  </style>
</head>
  <body>
   <div class="resize"></div>
  </body>
</html>
</code>```

答:
Currently you are saying that there can only be an animation while hovering. You want the animation to reverse once you have left the element (you no longer hover), but that is not allowed, as the div without hover has no animation set.

Just put the transition-duration: 1s on the 'div.resize' instead of on the 'div.resize:hover' and it is fixed.

ContentLicense: CC BY-SA 3.0

Title: CSS transition out error


问:
How to ignore exceptions while testing "autoload" with PHPUnit?
Story:

So I am trying to implement autoloader for my application that will throw exception in case if file within namespace not found, and in test i am just checking is this class exists or not... well i am trying to check it.

My problem, that the exception i am throwing in autoloaded, not ignored in test... and i am getting error during testing. But isn't my exception are in try catch block should be ignored by PHPUnit?

```<code>spl_autoload_register( function ( $class_name ) {
    if ( strpos( $class_name, 'App' ) !== false ) {

        $class_file = strtolower( $class_name );
        $class_file = str_replace( '\\', '-', $class_file );

        $class_file  = str_replace( 'app-', '', $class_file );
        $class_file  = sprintf( 'class-%s.php', $class_file );
        $class_file  = dirname( __DIR__ ) . '/includes/' . $class_file;

        if ( file_exists( $class_file ) ) {
            include_once $class_file;
            if ( ! class_exists( $class_name ) ) {
                throw new Exception( sprintf( 'Can\'t load %s class.', $class_name ));
            }
        } else {
            // do not throw path of the file.
            throw new Exception( sprintf( 'Can\'t find %s class file.', $class_name ) );
        }
    }
});
</code>```

As you can see its quite simple code.

```<code>require dirname( __DIR__ ) . '/vendor/autoload.php';
use PHPUnit\Framework\TestCase;

class ExceptionsTest extends TestCase {

    /**
     * @dataProvider data_existing_namespace
     */
    public function test_existing_namespaces( $class_name, $class_exists ) {

        try {

            $object = new $class_name();
            if ( $class_exists === true ){
                $this->assertTrue(  class_exists( $class_name ) );
            } else {
                $this->assertFalse( class_exists( $class_name ) );
            }

        } catch( Exception $e ) {
            // do nothing.
        }
    }

    /**
     * Data provider for test_Namespace_Autoload
     */
    public function data_existing_namespace() {
        return [
            [ '\App', true ],
            [ '\App\Settings', false ],
        ];

    }
}
</code>```

but... I still getting this error, which I should (if I understand right) catch.

```<code>There was 1 error:

1) Tests\ExceptionTest::test_existing_namespaces with data set #1 ('\App\Settings', false)
Exception: Can't find App\Settings class file.
</code>```

What can I do to suppers this error and just use AssertFalse or AssertTrue ?

答:
You are only catching the PHPUnit\Framework\TestCase\Exception because your test is in this namespace and you just use Exception without any namespace or use statement.

You simply have to specify the full namespace to your exception f.e. \Exception or you can use a use statement like use Exception; on top of your file.

```<code>try {

    $object = new $class_name();
    if ( $class_exists === true ){
        $this->assertTrue(  class_exists( $class_name ) );
    } else {
        $this->assertFalse( class_exists( $class_name ) );
    }

// catch all exception possible \Excecption
// maybe use \My\Namespace\Exception or something
} catch( \Exception $e ) {
    // do nothing.
}
</code>```

PS:
I would recommend to use the PSR autoloader feature provided by composer to make vendor/autoload.php load your classes as well.
So you don't have to implement your own autoloader, and you are using only the one provided by composer. All you have to to is to implement the PSR0 or PSR4 style to name and structure your class files.

Have a look at the documentation here https://getcomposer.org/doc/04-schema.md#autoload

Body:
Story:

So I am trying to implement autoloader for my application that will throw exception in case if file within namespace not found, and in test i am just checking is this class exists or not... well i am trying to check it.

My problem, that the exception i am throwing in autoloaded, not ignored in test... and i am getting error during testing. But isn't my exception are in try catch block should be ignored by PHPUnit?

spl_autoload_register( function ( $class_name ) {
    if ( strpos( $class_name, 'App' ) !== false ) {

        $class_file = strtolower( $class_name );
        $class_file = str_replace( '\\', '-', $class_file );

        $class_file  = str_replace( 'app-', '', $class_file );
        $class_file  = sprintf( 'class-%s.php', $class_file );
        $class_file  = dirname( __DIR__ ) . '/includes/' . $class_file;

        if ( file_exists( $class_file ) ) {
            include_once $class_file;
            if ( ! class_exists( $class_name ) ) {
                throw new Exception( sprintf( 'Can\'t load %s class.', $class_name ));
            }
        } else {
            // do not throw path of the file.
            throw new Exception( sprintf( 'Can\'t find %s class file.', $class_name ) );
        }
    }
});

As you can see its quite simple code.

require dirname( __DIR__ ) . '/vendor/autoload.php';
use PHPUnit\Framework\TestCase;

class ExceptionsTest extends TestCase {

    /**
     * @dataProvider data_existing_namespace
     */
    public function test_existing_namespaces( $class_name, $class_exists ) {

        try {

            $object = new $class_name();
            if ( $class_exists === true ){
                $this->assertTrue(  class_exists( $class_name ) );
            } else {
                $this->assertFalse( class_exists( $class_name ) );
            }

        } catch( Exception $e ) {
            // do nothing.
        }
    }

    /**
     * Data provider for test_Namespace_Autoload
     */
    public function data_existing_namespace() {
        return [
            [ '\App', true ],
            [ '\App\Settings', false ],
        ];

    }
}

but... I still getting this error, which I should (if I understand right) catch.

There was 1 error:

1) Tests\ExceptionTest::test_existing_namespaces with data set #1 ('\App\Settings', false)
Exception: Can't find App\Settings class file.

What can I do to suppers this error and just use AssertFalse or AssertTrue ?

Body:
You are only catching the PHPUnit\Framework\TestCase\Exception because your test is in this namespace and you just use Exception without any namespace or use statement.

You simply have to specify the full namespace to your exception f.e. \Exception or you can use a use statement like use Exception; on top of your file.

try {

    $object = new $class_name();
    if ( $class_exists === true ){
        $this->assertTrue(  class_exists( $class_name ) );
    } else {
        $this->assertFalse( class_exists( $class_name ) );
    }

// catch all exception possible \Excecption
// maybe use \My\Namespace\Exception or something
} catch( \Exception $e ) {
    // do nothing.
}

PS:
I would recommend to use the PSR autoloader feature provided by composer to make vendor/autoload.php load your classes as well.
So you don't have to implement your own autoloader, and you are using only the one provided by composer. All you have to to is to implement the PSR0 or PSR4 style to name and structure your class files.

Have a look at the documentation here https://getcomposer.org/doc/04-schema.md#autoload


问:
jQuery PHP only works with 3 parameters
Heyho,

I have a problem with the following code. I took the example from here: http://phpflow.com/php/how-to-add-edit-and-delete-a-row-in-jquery-flexigrid-using-php-and-mysql/ and only removed the "age" option.
But after the removal, I am no longer able to add records to my database via the form. If I add the record manually (with phpMyAdmin) I am able to edit the records via the webpage.

Maybe someone could figure out where the mistake is...

This is my code:

index.php

```<code>    <!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Simple Bootgrid example with add,edit and delete using PHP,MySQL and AJAX</title>
<link rel="stylesheet" href="dist/bootstrap.min.css" type="text/css" media="all">
<link href="dist/jquery.bootgrid.css" rel="stylesheet" />
<script src="dist/jquery-1.11.1.min.js"></script>
<script src="dist/bootstrap.min.js"></script>
<script src="dist/jquery.bootgrid.min.js"></script>
</head>
<body>
    <div class="container">
      <div class="">
        <h1>Simple Bootgrid example with add,edit and delete using PHP,MySQL and AJAX</h1>
        <div class="col-sm-8">
        <div class="well clearfix">
            <div class="pull-right"><button type="button" class="btn btn-xs btn-primary" id="command-add" data-row-id="0">
            <span class="glyphicon glyphicon-plus"></span> Record</button></div></div>
        <table id="employee_grid" class="table table-condensed table-hover table-striped" width="60%" cellspacing="0" data-toggle="bootgrid">
            <thead>
                <tr>
                    <th data-column-id="id" data-type="numeric" data-identifier="true">Empid</th>
                    <th data-column-id="employee_name">Name</th>
                    <th data-column-id="employee_salary">Salary</th>
                    <th data-column-id="commands" data-formatter="commands" data-sortable="false">Commands</th>
                </tr>
            </thead>
        </table>
    </div>
      </div>
    </div>

<div id="add_model" class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h4 class="modal-title">Add Employee</h4>
            </div>
            <div class="modal-body">
                <form method="post" id="frm_add">
                <input type="hidden" value="add" name="action" id="action">
                  <div class="form-group">
                    <label for="name" class="control-label">Name:</label>
                    <input type="text" class="form-control" id="name" name="name"/>
                  </div>
                  <div class="form-group">
                    <label for="salary" class="control-label">Salary:</label>
                    <input type="text" class="form-control" id="salary" name="salary"/>
                  </div>

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" id="btn_add" class="btn btn-primary">Save</button>
            </div>
            </form>
        </div>
    </div>
</div>
<div id="edit_model" class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h4 class="modal-title">Edit Employee</h4>
            </div>
            <div class="modal-body">
                <form method="post" id="frm_edit">
                <input type="hidden" value="edit" name="action" id="action">
                <input type="hidden" value="0" name="edit_id" id="edit_id">
                  <div class="form-group">
                    <label for="name" class="control-label">Name:</label>
                    <input type="text" class="form-control" id="edit_name" name="edit_name"/>
                  </div>
                  <div class="form-group">
                    <label for="salary" class="control-label">Salary:</label>
                    <input type="text" class="form-control" id="edit_salary" name="edit_salary"/>
                  </div>

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" id="btn_edit" class="btn btn-primary">Save</button>
            </div>
            </form>
        </div>
    </div>
</div>
</body>
</html>
<script type="text/javascript">
$( document ).ready(function() {
    var grid = $("#employee_grid").bootgrid({
        ajax: true,
        rowSelect: true,
        post: function ()
        {
            /* To accumulate custom parameter with the request object */
            return {
                id: "b0df282a-0d67-40e5-8558-c9e93b7befed"
            };
        },

        url: "response.php",
        formatters: {
                "commands": function(column, row)
                {
                    return "<button type=\"button\" class=\"btn btn-xs btn-default command-edit\" data-row-id=\"" + row.id + "\"><span class=\"glyphicon glyphicon-edit\"></span></button> " +
                        "<button type=\"button\" class=\"btn btn-xs btn-default command-delete\" data-row-id=\"" + row.id + "\"><span class=\"glyphicon glyphicon-trash\"></span></button>";
                }
            }
   }).on("loaded.rs.jquery.bootgrid", function()
{
    /* Executes after data is loaded and rendered */
    grid.find(".command-edit").on("click", function(e)
    {
        //alert("You pressed edit on row: " + $(this).data("row-id"));
            var ele =$(this).parent();
            var g_id = $(this).parent().siblings(':first').html();
            var g_name = $(this).parent().siblings(':nth-of-type(2)').html();
console.log(g_id);
                    console.log(g_name);

        //console.log(grid.data());//
        $('#edit_model').modal('show');
                    if($(this).data("row-id") >0) {

                                // collect the data
                                $('#edit_id').val(ele.siblings(':first').html()); // in case we're changing the key
                                $('#edit_name').val(ele.siblings(':nth-of-type(2)').html());
                                $('#edit_salary').val(ele.siblings(':nth-of-type(3)').html());

                    } else {
                     alert('Now row selected! First select row, then click edit button');
                    }
    }).end().find(".command-delete").on("click", function(e)
    {

        var conf = confirm('Delete ' + $(this).data("row-id") + ' items?');
                    alert(conf);
                    if(conf){
                                $.post('response.php', { id: $(this).data("row-id"), action:'delete'}
                                    , function(){
                                        // when ajax returns (callback),
                                        $("#employee_grid").bootgrid('reload');
                                });
                                //$(this).parent('tr').remove();
                                //$("#employee_grid").bootgrid('remove', $(this).data("row-id"))
                    }
    });
});

function ajaxAction(action) {
                data = $("#frm_"+action).serializeArray();
                $.ajax({
                  type: "POST",
                  url: "response.php",
                  data: data,
                  dataType: "json",
                  success: function(response)
                  {
                    $('#'+action+'_model').modal('hide');
                    $("#employee_grid").bootgrid('reload');
                  }
                });
            }

            $( "#command-add" ).click(function() {
              $('#add_model').modal('show');
            });
            $( "#btn_add" ).click(function() {
              ajaxAction('add');
            });
            $( "#btn_edit" ).click(function() {
              ajaxAction('edit');
            });
});
</script>
</code>```

response.php

```<code><?php
    //include connection file
    include_once("connection.php");

    $db = new dbObj();
    $connString =  $db->getConnstring();

    $params = $_REQUEST;

    $action = isset($params['action']) != '' ? $params['action'] : '';
    $empCls = new Employee($connString);

    switch($action) {
     case 'add':
        $empCls->insertEmployee($params);
     break;
     case 'edit':
        $empCls->updateEmployee($params);
     break;
     case 'delete':
        $empCls->deleteEmployee($params);
     break;
     default:
     $empCls->getEmployees($params);
     return;
    }

    class Employee {
    protected $conn;
    protected $data = array();
    function __construct($connString) {
        $this->conn = $connString;
    }

    public function getEmployees($params) {

        $this->data = $this->getRecords($params);

        echo json_encode($this->data);
    }
    function insertEmployee($params) {
        $data = array();;
        $sql = "INSERT INTO `employee` (employee_name, employee_salary) VALUES('" . $params["name"] . "', '" . $params["salary"] . "' );  ";

        echo $result = mysqli_query($this->conn, $sql) or die("error to insert employee data");

    }

    function getRecords($params) {
        $rp = isset($params['rowCount']) ? $params['rowCount'] : 10;

        if (isset($params['current'])) { $page  = $params['current']; } else { $page=1; };
        $start_from = ($page-1) * $rp;

        $sql = $sqlRec = $sqlTot = $where = '';

        if( !empty($params['searchPhrase']) ) {
            $where .=" WHERE ";
            $where .=" ( employee_name LIKE '".$params['searchPhrase']."%' ";

            $where .=" OR employee_salary LIKE '".$params['searchPhrase']."%' )";
       }
       if( !empty($params['sort']) ) {
            $where .=" ORDER By ".key($params['sort']) .' '.current($params['sort'])." ";
        }
       // getting total number records without any search
        $sql = "SELECT * FROM `employee` ";
        $sqlTot .= $sql;
        $sqlRec .= $sql;

        //concatenate search sql if value exist
        if(isset($where) && $where != '') {

            $sqlTot .= $where;
            $sqlRec .= $where;
        }
        if ($rp!=-1)
        $sqlRec .= " LIMIT ". $start_from .",".$rp;

        $qtot = mysqli_query($this->conn, $sqlTot) or die("error to fetch tot employees data");
        $queryRecords = mysqli_query($this->conn, $sqlRec) or die("error to fetch employees data");

        while( $row = mysqli_fetch_assoc($queryRecords) ) {
            $data[] = $row;
        }

        $json_data = array(
            "current"            => intval($params['current']),
            "rowCount"            => 10,
            "total"    => intval($qtot->num_rows),
            "rows"            => $data   // total data array
            );

        return $json_data;
    }
    function updateEmployee($params) {
        $data = array();
        //print_R($_POST);die;
        $sql = "Update `employee` set employee_name = '" . $params["edit_name"] . "', employee_salary='" . $params["edit_salary"]."'  WHERE id='".$_POST["edit_id"]."'";

        echo $result = mysqli_query($this->conn, $sql) or die("error to update employee data");
    }

    function deleteEmployee($params) {
        $data = array();
        //print_R($_POST);die;
        $sql = "delete from `employee` WHERE id='".$params["id"]."'";

        echo $result = mysqli_query($this->conn, $sql) or die("error to delete employee data");
    }
}
?>
</code>```

There is also connection.php but the connection to my database works.
I guess that the response.php expects 3 parameters (name, salary and age) but only gets two...
Please don`t hesitate to ask for more details!

Thank you in advance,
Francis

答: Yes, you just had to delete the field from your database. It was likely marked as NOT NULL, and when you removed the field from the code, INSERT failed trying to insert a null employee_age :)

Title: jQuery PHP only works with 3 parameters

Body:
Heyho,

I have a problem with the following code. I took the example from here: http://phpflow.com/php/how-to-add-edit-and-delete-a-row-in-jquery-flexigrid-using-php-and-mysql/ and only removed the "age" option.
But after the removal, I am no longer able to add records to my database via the form. If I add the record manually (with phpMyAdmin) I am able to edit the records via the webpage.

Maybe someone could figure out where the mistake is...

This is my code:

index.php

    <!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Simple Bootgrid example with add,edit and delete using PHP,MySQL and AJAX</title>
<link rel="stylesheet" href="dist/bootstrap.min.css" type="text/css" media="all">
<link href="dist/jquery.bootgrid.css" rel="stylesheet" />

Simple Bootgrid example with add,edit and delete using PHP,MySQL and AJAX

<button type="button" class="btn btn-xs btn-primary" id="command-add" data-row-id="0">
             Record</button>

                    Empid
                    Name
                    Salary
                    Commands

                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Add Employee

                <form method="post" id="frm_add">
                <input type="hidden" value="add" name="action" id="action">

                    Name:
                    <input type="text" class="form-control" id="name" name="name"/>

                    Salary:
                    <input type="text" class="form-control" id="salary" name="salary"/>

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" id="btn_add" class="btn btn-primary">Save</button>

            </form>

                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Edit Employee

                <form method="post" id="frm_edit">
                <input type="hidden" value="edit" name="action" id="action">
                <input type="hidden" value="0" name="edit_id" id="edit_id">

                    Name:
                    <input type="text" class="form-control" id="edit_name" name="edit_name"/>

                    Salary:
                    <input type="text" class="form-control" id="edit_salary" name="edit_salary"/>

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" id="btn_edit" class="btn btn-primary">Save</button>

            </form>

response.php

<?php
    //include connection file
    include_once("connection.php");

    $db = new dbObj();
    $connString =  $db->getConnstring();

    $params = $_REQUEST;

    $action = isset($params['action']) != '' ? $params['action'] : '';
    $empCls = new Employee($connString);

    switch($action) {
     case 'add':
        $empCls->insertEmployee($params);
     break;
     case 'edit':
        $empCls->updateEmployee($params);
     break;
     case 'delete':
        $empCls->deleteEmployee($params);
     break;
     default:
     $empCls->getEmployees($params);
     return;
    }

    class Employee {
    protected $conn;
    protected $data = array();
    function __construct($connString) {
        $this->conn = $connString;
    }

    public function getEmployees($params) {

        $this->data = $this->getRecords($params);

        echo json_encode($this->data);
    }
    function insertEmployee($params) {
        $data = array();;
        $sql = "INSERT INTO `employee` (employee_name, employee_salary) VALUES('" . $params["name"] . "', '" . $params["salary"] . "' );  ";

        echo $result = mysqli_query($this->conn, $sql) or die("error to insert employee data");

    }

    function getRecords($params) {
        $rp = isset($params['rowCount']) ? $params['rowCount'] : 10;

        if (isset($params['current'])) { $page  = $params['current']; } else { $page=1; };
        $start_from = ($page-1) * $rp;

        $sql = $sqlRec = $sqlTot = $where = '';

        if( !empty($params['searchPhrase']) ) {
            $where .=" WHERE ";
            $where .=" ( employee_name LIKE '".$params['searchPhrase']."%' ";

            $where .=" OR employee_salary LIKE '".$params['searchPhrase']."%' )";
       }
       if( !empty($params['sort']) ) {
            $where .=" ORDER By ".key($params['sort']) .' '.current($params['sort'])." ";
        }
       // getting total number records without any search
        $sql = "SELECT * FROM `employee` ";
        $sqlTot .= $sql;
        $sqlRec .= $sql;

        //concatenate search sql if value exist
        if(isset($where) && $where != '') {

            $sqlTot .= $where;
            $sqlRec .= $where;
        }
        if ($rp!=-1)
        $sqlRec .= " LIMIT ". $start_from .",".$rp;

        $qtot = mysqli_query($this->conn, $sqlTot) or die("error to fetch tot employees data");
        $queryRecords = mysqli_query($this->conn, $sqlRec) or die("error to fetch employees data");

        while( $row = mysqli_fetch_assoc($queryRecords) ) {
            $data[] = $row;
        }

        $json_data = array(
            "current"            => intval($params['current']),
            "rowCount"            => 10,
            "total"    => intval($qtot->num_rows),
            "rows"            => $data   // total data array
            );

        return $json_data;
    }
    function updateEmployee($params) {
        $data = array();
        //print_R($_POST);die;
        $sql = "Update `employee` set employee_name = '" . $params["edit_name"] . "', employee_salary='" . $params["edit_salary"]."'  WHERE id='".$_POST["edit_id"]."'";

        echo $result = mysqli_query($this->conn, $sql) or die("error to update employee data");
    }

    function deleteEmployee($params) {
        $data = array();
        //print_R($_POST);die;
        $sql = "delete from `employee` WHERE id='".$params["id"]."'";

        echo $result = mysqli_query($this->conn, $sql) or die("error to delete employee data");
    }
}
?>

There is also connection.php but the connection to my database works.
I guess that the response.php expects 3 parameters (name, salary and age) but only gets two...
Please don`t hesitate to ask for more details!

Thank you in advance,
Francis


问:
Spring web mvc security took long time to finish loading page
i am creating a login page using spring web mvc with spring security. when i deploy the application in my local machine it is working as expected. the login page is loading without problem. But when i try to deploy the application in hosting provider, the login page took very long time to load before finally loaded successfully.

here is the message when i access the application

```<code>2017-04-02 18:16:30.482  INFO 28450 --- [p-nio-80-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 43 ms
</code>```

and here is the message when the login page finally loaded

```<code>2017-04-02 18:25:01.135  INFO 28450 --- [p-nio-80-exec-1] o.a.c.util.SessionIdGeneratorBase        : Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [510,546] milliseconds.
</code>```

i am using spring 1.4.5, build with maven and running the application with java -jar

here is my application.properties content

```<code># other
server.port=8082
spring.session.store-type=none
spring.jpa.properties.hibernate.jdbc.time_zone = UTC+7
</code>```

MvcConfig.java

```<code>import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("dashboard");
        registry.addViewController("/login").setViewName("login");
        registry.addViewController("/403").setViewName("403");
        registry.addViewController("/404").setViewName("404");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**")
                .addResourceLocations("/resources/")
                .addResourceLocations("/static/")
                .addResourceLocations("/static/**")
                .addResourceLocations("/resources/static/")
                .addResourceLocations("/resources/static/**")
                .addResourceLocations("/")
                .addResourceLocations("/**");
    }

}
</code>```

WebSecurityConfig.java

```<code>import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
@ComponentScan(basePackageClasses = CustomAccountDetailsService.class)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordencoder());

    @Bean(name = "passwordEncoder")
    public PasswordEncoder passwordencoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/layout/**").permitAll()
                .antMatchers("/calendar").hasAuthority("USER")
                .antMatchers("/customer").hasAuthority("ADMIN")
                .anyRequest().fullyAuthenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .failureUrl("/login?error")
                .defaultSuccessUrl("/")
                .permitAll()
                .and()
            .logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/login")
                .permitAll()
                .and()
            .exceptionHandling().accessDeniedPage("/403")
                .and().csrf();
    }

}
</code>```

hosting provider machine :
Ubuntu Server 16.04.2 LTS
RAM 4GB
HDD : 40GB SSD and 3TB

after the page successfully loaded, then the page is not taking long time anymore to load if i refresh it. but if i change the server.port in application.properties and restarting the application (Ctrl + C and java -jar again), the very same thing is happenned again.

i don't understand what makes the loading time in the hosting machine took very long if compared to my local machine.
any pointer for what should be done or check would be very helpful

答:
When SecureRandom initializes, it takes some bytes from the system random number generator. On Linux, Java takes those from /dev/random which blocks if the system does not have enough entropy (until the system gets that entropy). This may take a while.

The solution is to switch to /dev/urandom, which does not block.

One of the possible solutions is add the following to your java commandline:

```<code>-Djava.security.egd=file:/dev/./urandom
</code>```

Note that dot between /dev/ and /urandom: this is not a typo. This is required (or at least was required with some java versions): https://security.stackexchange.com/questions/14386/what-do-i-need-to-configure-to-make-sure-my-software-uses-dev-urandom

Body:
i am creating a login page using spring web mvc with spring security. when i deploy the application in my local machine it is working as expected. the login page is loading without problem. But when i try to deploy the application in hosting provider, the login page took very long time to load before finally loaded successfully.

here is the message when i access the application

2017-04-02 18:16:30.482  INFO 28450 --- [p-nio-80-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 43 ms

and here is the message when the login page finally loaded

2017-04-02 18:25:01.135  INFO 28450 --- [p-nio-80-exec-1] o.a.c.util.SessionIdGeneratorBase        : Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [510,546] milliseconds.

i am using spring 1.4.5, build with maven and running the application with java -jar

here is my application.properties content

# other
server.port=8082
spring.session.store-type=none
spring.jpa.properties.hibernate.jdbc.time_zone = UTC+7

MvcConfig.java

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("dashboard");
        registry.addViewController("/login").setViewName("login");
        registry.addViewController("/403").setViewName("403");
        registry.addViewController("/404").setViewName("404");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**")
                .addResourceLocations("/resources/")
                .addResourceLocations("/static/")
                .addResourceLocations("/static/**")
                .addResourceLocations("/resources/static/")
                .addResourceLocations("/resources/static/**")
                .addResourceLocations("/")
                .addResourceLocations("/**");
    }

}

WebSecurityConfig.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
@ComponentScan(basePackageClasses = CustomAccountDetailsService.class)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordencoder());

    @Bean(name = "passwordEncoder")
    public PasswordEncoder passwordencoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/layout/**").permitAll()
                .antMatchers("/calendar").hasAuthority("USER")
                .antMatchers("/customer").hasAuthority("ADMIN")
                .anyRequest().fullyAuthenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .failureUrl("/login?error")
                .defaultSuccessUrl("/")
                .permitAll()
                .and()
            .logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/login")
                .permitAll()
                .and()
            .exceptionHandling().accessDeniedPage("/403")
                .and().csrf();
    }

}

hosting provider machine :
Ubuntu Server 16.04.2 LTS
RAM 4GB
HDD : 40GB SSD and 3TB

after the page successfully loaded, then the page is not taking long time anymore to load if i refresh it. but if i change the server.port in application.properties and restarting the application (Ctrl + C and java -jar again), the very same thing is happenned again.

i don't understand what makes the loading time in the hosting machine took very long if compared to my local machine.
any pointer for what should be done or check would be very helpful

Body:
When SecureRandom initializes, it takes some bytes from the system random number generator. On Linux, Java takes those from /dev/random which blocks if the system does not have enough entropy (until the system gets that entropy). This may take a while.

The solution is to switch to /dev/urandom, which does not block.

One of the possible solutions is add the following to your java commandline:

-Djava.security.egd=file:/dev/./urandom

Note that dot between /dev/ and /urandom: this is not a typo. This is required (or at least was required with some java versions): https://security.stackexchange.com/questions/14386/what-do-i-need-to-configure-to-make-sure-my-software-uses-dev-urandom


问:
java.lang.NoClassDefFoundError: com/google/inject/Module using Guice
I am trying to use the DI mechanism provided by Google, but when I run my application, I am getting the following error:

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: com/google/inject/Module
at challenge.App.main(App.java:19)
Caused by: java.lang.ClassNotFoundException: com.google.inject.Module
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 1 more
</code>```

The pom.xml file looks like:

```<code>  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.6</source>
          <target>1.6</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.google.inject</groupId>
      <artifactId>guice</artifactId>
      <version>4.1.0</version>
      <classifier>no_aop</classifier>
    </dependency>
  </dependencies>
</code>```

And the code where I am using it looks like:

```<code>    Injector injector = Guice.createInjector(new DependenciesModule());
    IndexerController indexer = injector.getInstance(IndexerController.class);
</code>```

And I have imported com.google.inject.Guice and com.google.inject.Injector

I have been checking for several places but I cannot see any relevant solution for this problems, I would appreciate a lot any glue.

答:
This appears like the usual issue with Maven in that at runtime, the dependency classes (e.g. the Guice classes) are not available to the JVM.

The easiest solution is to use explicit classpath specification while running your app:

```<code>java -cp
/path/to/guice.jar:
/path/too/your-app.jar:
/path/to/other/classes/not/bundled/in/your-app.jar
main.MyClass
</code>```

(this is all on one line, split for better viewing).

The other solution is to use Maven Shade Plugin which facilitates the creation of the executable JAR which you can simply run as java -jar uber.jar.

Body:
I am trying to use the DI mechanism provided by Google, but when I run my application, I am getting the following error:

Exception in thread "main" java.lang.NoClassDefFoundError: com/google/inject/Module
at challenge.App.main(App.java:19)
Caused by: java.lang.ClassNotFoundException: com.google.inject.Module
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 1 more

The pom.xml file looks like:

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.6</source>
          <target>1.6</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.google.inject</groupId>
      <artifactId>guice</artifactId>
      <version>4.1.0</version>
      <classifier>no_aop</classifier>
    </dependency>
  </dependencies>

And the code where I am using it looks like:

    Injector injector = Guice.createInjector(new DependenciesModule());
    IndexerController indexer = injector.getInstance(IndexerController.class);

And I have imported com.google.inject.Guice and com.google.inject.Injector

I have been checking for several places but I cannot see any relevant solution for this problems, I would appreciate a lot any glue.

Body:
This appears like the usual issue with Maven in that at runtime, the dependency classes (e.g. the Guice classes) are not available to the JVM.

The easiest solution is to use explicit classpath specification while running your app:

java -cp
/path/to/guice.jar:
/path/too/your-app.jar:
/path/to/other/classes/not/bundled/in/your-app.jar
main.MyClass

(this is all on one line, split for better viewing).

The other solution is to use Maven Shade Plugin which facilitates the creation of the executable JAR which you can simply run as java -jar uber.jar.


问:
JAVA - WELD Decorator error
I try to make an Decorator in weld, but weld was return an error. I can't understand what's my error. I used the same example of weld "weld-se-numberguess" and i was created an decorator  extends game.

```<code> Set 18, 2015 3:41:02 PM org.jboss.weld.bootstrap.WeldStartup <clinit>
 INFO: WELD-000900: 2.2.16 (Final)
 Set 18, 2015 3:41:03 PM org.jboss.weld.bootstrap.WeldStartup startContainer
 INFO: WELD-000101: Transactional services not available. Injection of @Inject UserTransaction not available. Transactional observers will be invoked synchronously.
 Exception in thread "main" org.jboss.weld.exceptions.DefinitionException: WELD-001455: Decorator [class org.jboss.weld.environment.se.example.numberguess.GameDecorator] decorates [] with delegate type [Game] and delegate qualifiers [@Default] does not declare any decorated types.
    at org.jboss.weld.bootstrap.Validator.validateDecorator(Validator.java:570)
    at org.jboss.weld.bootstrap.ConcurrentValidator$3.doWork(ConcurrentValidator.java:96)
    at org.jboss.weld.bootstrap.ConcurrentValidator$3.doWork(ConcurrentValidator.java:94)
    at org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:60)
    at org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:53)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
</code>```

pom.xml

```<code><dependencies>
    <dependency>
        <groupId>org.jboss.weld.se</groupId>
        <artifactId>weld-se</artifactId>
    </dependency>

    <dependency>
        <groupId>javax.ejb</groupId>
        <artifactId>javax.ejb-api</artifactId>
        <version>3.2</version>
    </dependency>
    <dependency>
        <groupId>javax.enterprise</groupId>
        <artifactId>cdi-api</artifactId>
        <version>1.2</version>
    </dependency>
</dependencies>
</code>```

GameDecorator.java

```<code>@Decorator
public abstract class GameDecorator extends Game implements Serializable {

    @Delegate
    @Inject
    Game game;

    /**
     *
     */
    private static final long serialVersionUID = 9155583141751623258L;

    // public GameDecorator(@Delegate @Any Game game) {
    // }

    @Override
    public int getNumber() {
        return 98;
    }
}
</code>```

bean.xml

```<code><beans
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd" bean-discovery-mode="all">
           <decorators>
               <class>org.jboss.weld.environment.se.example.numberguess.GameDecorator</class>
           </decorators>
</beans>
</code>```

答:
It's an old question, but since I have just faced the same issue let me answer it.

It seems that there is a need for an interface to exist in the class hierarchy. Just try to extract an interface out of your Game class and make both your Game'ish class and the GameDecorator implement it.
Weld documentation says:

A decorator is a bean (possibly even an abstract class) that
  implements the type it decorates and is annotated @Decorator.

Title: JAVA - WELD Decorator error

Body:
I try to make an Decorator in weld, but weld was return an error. I can't understand what's my error. I used the same example of weld "weld-se-numberguess" and i was created an decorator  extends game.

 Set 18, 2015 3:41:02 PM org.jboss.weld.bootstrap.WeldStartup <clinit>
 INFO: WELD-000900: 2.2.16 (Final)
 Set 18, 2015 3:41:03 PM org.jboss.weld.bootstrap.WeldStartup startContainer
 INFO: WELD-000101: Transactional services not available. Injection of @Inject UserTransaction not available. Transactional observers will be invoked synchronously.
 Exception in thread "main" org.jboss.weld.exceptions.DefinitionException: WELD-001455: Decorator [class org.jboss.weld.environment.se.example.numberguess.GameDecorator] decorates [] with delegate type [Game] and delegate qualifiers [@Default] does not declare any decorated types.
    at org.jboss.weld.bootstrap.Validator.validateDecorator(Validator.java:570)
    at org.jboss.weld.bootstrap.ConcurrentValidator$3.doWork(ConcurrentValidator.java:96)
    at org.jboss.weld.bootstrap.ConcurrentValidator$3.doWork(ConcurrentValidator.java:94)
    at org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:60)
    at org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:53)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

pom.xml

<dependencies>
    <dependency>
        <groupId>org.jboss.weld.se</groupId>
        <artifactId>weld-se</artifactId>
    </dependency>

    <dependency>
        <groupId>javax.ejb</groupId>
        <artifactId>javax.ejb-api</artifactId>
        <version>3.2</version>
    </dependency>
    <dependency>
        <groupId>javax.enterprise</groupId>
        <artifactId>cdi-api</artifactId>
        <version>1.2</version>
    </dependency>
</dependencies>

GameDecorator.java

@Decorator
public abstract class GameDecorator extends Game implements Serializable {

    @Delegate
    @Inject
    Game game;

    /**
     *
     */
    private static final long serialVersionUID = 9155583141751623258L;

    // public GameDecorator(@Delegate @Any Game game) {
    // }

    @Override
    public int getNumber() {
        return 98;
    }
}

bean.xml

<beans
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd" bean-discovery-mode="all">
           <decorators>
               <class>org.jboss.weld.environment.se.example.numberguess.GameDecorator</class>
           </decorators>
</beans>


问:
MySQL does not seem to store databases anywhere
The MySQL command line works fine and connects well to PHP. However, the databases don't seem to be stored anywhere in the computer. I tried looking in C:\Program Files\MySQL\MySQL Server 5.7\ for the data folder, but there is none. I don't know if this is actually a problem or not but it is worrying me. Any help would be greatly appreciated.

答:
Get to your MySQL command line and run this query:

```<code>mysql> select @@datadir;
</code>```

That's the location on your computer where it stores databases. The location can vary based on your configuration, but the query above will always tell you where it is.

Body:
Get to your MySQL command line and run this query:

mysql> select @@datadir;

That's the location on your computer where it stores databases. The location can vary based on your configuration, but the query above will always tell you where it is.


问:
Simultaneous requests in JMeter
Assume I have two users in Thread Group and want them to fire two requests simultaneously. User 1 - HTTP Request A and User 2 - HTTP Request B.

Any ideas how to implement that ?

答:
To trigger the requests simultaneously, you need to place your each requests in different thread group as shown below.

Also, make sure that in the Test Plan, below option is unchecked.

Above settings will execute the request simultaneously. Below is the sample output.

Title: Simultaneous requests in JMeter


问:
How can a null pointer change its value?
I used something like this:

```<code>struct Node
{
    char name[50];
    Node *left,*right;
};

int main()
{
    char cmd[10];
    Node* p=NULL;

    scanf("%s",&cmd);

    if (p == NULL)
    {
        // do something

        // THIS NEVER GETS EXECUTED
        // WHYYYYY????
        //THIS IS STRANGE
    }
}
</code>```

So basically, the pointer p changes its value after I read into the cmd variable. I tried to commented out the scanf code, and then everything works. Very strange.

答:
You have a buffer overflow.

The memory looks like this:

```<code>+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|  |  |  |  |  |  |  |  |  |  |  |  |  |  |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
 ^                             ^
 cmd[10]                       p
</code>```

If scanf reads more than 10 bytes, it will overflow to p. Any non-zero value will fail the NULL check, even if it is not a valid pointer.

Body:
I used something like this:

struct Node
{
    char name[50];
    Node *left,*right;
};

int main()
{
    char cmd[10];
    Node* p=NULL;

    scanf("%s",&cmd);

    if (p == NULL)
    {
        // do something

        // THIS NEVER GETS EXECUTED
        // WHYYYYY????
        //THIS IS STRANGE
    }
}

So basically, the pointer p changes its value after I read into the cmd variable. I tried to commented out the scanf code, and then everything works. Very strange.

Body:
You have a buffer overflow.

The memory looks like this:

+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|  |  |  |  |  |  |  |  |  |  |  |  |  |  |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
 ^                             ^
 cmd[10]                       p

If scanf reads more than 10 bytes, it will overflow to p. Any non-zero value will fail the NULL check, even if it is not a valid pointer.


问:
Highcharts - How to show x-axis with incomplete data?
Not entirely sure how to best describe this issue in a title, so here goes.

I'm working on a chart that plots data over time, starting with a single date and adding one piece of data each day.

In the following screen shot, here's what I'm using for a x-axis:
categories: ['Mon Apr 3', 'Tue Apr 4', 'Wed Apr 5', 'Thu Apr 6', 'Fri Apr 7', 'Sat Apr 8', 'Sun Apr 9']

For my y-axis:
data: [4,0,0,0,0,0,0]

Which results in this graph:

The issue with it is technically only the Mon Apr 3 date has happened. The outcome I want is a single dot for Mon Apr 3 with the rest of the line uncharted.

When I adjust my axis as follows, highcharts hides the rest of the dates in my x-axis and centers the single point:
categories: ['Mon Apr 3', 'Tue Apr 4', 'Wed Apr 5', 'Thu Apr 6', 'Fri Apr 7', 'Sat Apr 8', 'Sun Apr 9']
data: [4]

Resulting in this:

Does anyone know of how to go about achieving the desired result? Again, just want this first data point of 4 to left align while keeping all of the other dates in the future.

答:
Technically 0 is a value. You could map the array to look like this instead:

```<code>categories: ['Mon Apr 3', 'Tue Apr 4', 'Wed Apr 5', 'Thu Apr 6', 'Fri Apr 7', 'Sat Apr 8', 'Sun Apr 9']

data: [4, null, null, null, null, null, null]
</code>```

Body:
Technically 0 is a value. You could map the array to look like this instead:

categories: ['Mon Apr 3', 'Tue Apr 4', 'Wed Apr 5', 'Thu Apr 6', 'Fri Apr 7', 'Sat Apr 8', 'Sun Apr 9']

data: [4, null, null, null, null, null, null]


问:
How to make a list of functions in python?
I tried to achieve something like this

```<code>list1 = [lambda x: x+0, lambda x: x+1]
</code>```

by doing this

```<code>list2 = [lambda x: x+n for n in range(2)]
</code>```

But it doesn't work! (Why not?)
How do I create a list of functions programmatically?

答:
n is reassigned by the for expression, so after the for expression is completed both will see value of n being 1.

More typical example of this problem can be visible without list expression:

```<code>list3 = []
for n in range(2):
    def f(x):
        return x + n
    list3.append(f)
</code>```

Here also all created function objects will refer to the same variable n and it will be assigned value 1 and both function objects will work as lambda x: x + 1.

You can deal with it by creating additional scope with a variable for each created function:

```<code>a = [(lambda n: lambda x: x+n)(n) for n in range(2)]
</code>```

Body:
I tried to achieve something like this

list1 = [lambda x: x+0, lambda x: x+1]

by doing this

list2 = [lambda x: x+n for n in range(2)]

But it doesn't work! (Why not?)
How do I create a list of functions programmatically?

Body:
n is reassigned by the for expression, so after the for expression is completed both will see value of n being 1.

More typical example of this problem can be visible without list expression:

list3 = []
for n in range(2):
    def f(x):
        return x + n
    list3.append(f)

Here also all created function objects will refer to the same variable n and it will be assigned value 1 and both function objects will work as lambda x: x + 1.

You can deal with it by creating additional scope with a variable for each created function:

a = [(lambda n: lambda x: x+n)(n) for n in range(2)]


问:
NoClassDefFoundError
I have an issue where NoClasDefFoundError is being thrown. It puzzles me since I am using interfaces, and no class definition should be available. I have read through some posts which point to Classpath, but I don't believe that to be the issue here (although I may be wrong). I am using NetBeans 6.9.1 IDE.

I have created a sample setup to reproduce the issue. Four projects: Interfaces, Objects, Locator and Consumer. Below you will find the implementations.

At runtime consumer coplains about missing SomeObject implementation, which it should not be aware of since it is accepting interface.

Exception in thread "main"
  java.lang.NoClassDefFoundError:
  objects/SomeObject

What am I missing?

```<code>package interfaces;
public interface ISomeInterface { }

package objects;
import interfaces.ISomeInterface;
public class SomeObject implements ISomeInterface{ }

package locator;
import interfaces.ISomeInterface;
import objects.SomeObject;
public class Locator { public static ISomeInterface LocateImplementation() { return new SomeObject(); }}

package consumer;
import interfaces.ISomeInterface;
import locator.Locator;
public class Main { public static void main(String[] args) { ISomeInterface object = Locator.LocateImplementation(); }}
</code>```

答:
Any Interface must be declared inside class </p>

```<code>public class Calbacks {
    public interface IBaseFragmentInterface {
        void NotifyMainActivity();
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: NoClassDefFoundError

Body:
I have an issue where NoClasDefFoundError is being thrown. It puzzles me since I am using interfaces, and no class definition should be available. I have read through some posts which point to Classpath, but I don't believe that to be the issue here (although I may be wrong). I am using NetBeans 6.9.1 IDE.

I have created a sample setup to reproduce the issue. Four projects: Interfaces, Objects, Locator and Consumer. Below you will find the implementations.

At runtime consumer coplains about missing SomeObject implementation, which it should not be aware of since it is accepting interface.

Exception in thread "main"
  java.lang.NoClassDefFoundError:
  objects/SomeObject

What am I missing?

package interfaces;
public interface ISomeInterface { }

package objects;
import interfaces.ISomeInterface;
public class SomeObject implements ISomeInterface{ }

package locator;
import interfaces.ISomeInterface;
import objects.SomeObject;
public class Locator { public static ISomeInterface LocateImplementation() { return new SomeObject(); }}

package consumer;
import interfaces.ISomeInterface;
import locator.Locator;
public class Main { public static void main(String[] args) { ISomeInterface object = Locator.LocateImplementation(); }}

Body:
Any Interface must be declared inside class

public class Calbacks {
    public interface IBaseFragmentInterface {
        void NotifyMainActivity();
    }
}


问:
How to input String in Switch case containing charAt()
I want to append each number to represent the each alphabets and charAt() will not allow me to use a string case statement. Pls any ideas on how i can go about this?. I have already appended from alphabets to numbers. But from numbers to Alphabets, Its been something else for me. I really need help on this.

```<code>String Sentence;
    Sentence = JOptionPane.showInputDialog(null, "Enter some String", "Message");
    StringBuilder build = new StringBuilder();

    for(int i=0; i<trim.length();i++)
    {
for (int i = 0; i < Sentence.length(); i++) {
    switch (Sentence.charAt(i)) {
        case '1':
            build.append("a");
            break;
        case '2':
            build.append("b");
            break;
        case '3':
            build.append("c");
            break;
        case '4':
            build.append("d");
            break;
        case '5':
            build.append("e");
            break;
        case '6':
            build.append("f");
            break;
        case '7':
            build.append("g");
            break;
        case '8':
            build.append("h");
            break;
        case '9':
            build.append("i");
            break;
        case (
            '1.0'):
            build.append("j");
            break;
        case "1.1":
            build.append("k");
            break;
        case "1.2":
            build.append("l");
            break;
        case "1.3":
            build.append("m");
            break;
        case "1.4":
            build.append("n");
            break;
        case "1.5":
            build.append("o");
            break;
        case "1.6":
            build.append("p");
            break;
        case "1.7":
            build.append("q");
            break;
        case "1.8":
            build.append("r");
            break;
        case "1.9":
            build.append("s");
            break;
        case "2.0":
            build.append("t");
            break;
        case "2.1":
            build.append("u");
            break;
        case "2.2":
            build.append("v");
            break;
        case "2.3":
            build.append("w");
            break;
        case "2.4":
            build.append("x");
            break;
        case "2.5":
            build.append("y");
            break;
        case "2.6":
            build.append("z");
            break;
        case '?':
            build.append(" ");
            break;
        case '*':
            build.append(",");
            break;
        case "'\'":
            build.append('.');
            break;
        default:

            break;
    }
</code>```

Seriously any help will be appreciated. Thanks

答:
To modify it quickly to working version - just convert your char to String and use it in switch:

```<code> switch ("" + Sentence.charAt(i)) {
    case "a": // "a" is a String now
...
</code>```

Body:
I want to append each number to represent the each alphabets and charAt() will not allow me to use a string case statement. Pls any ideas on how i can go about this?. I have already appended from alphabets to numbers. But from numbers to Alphabets, Its been something else for me. I really need help on this.

String Sentence;
    Sentence = JOptionPane.showInputDialog(null, "Enter some String", "Message");
    StringBuilder build = new StringBuilder();

    for(int i=0; i<trim.length();i++)
    {
for (int i = 0; i < Sentence.length(); i++) {
    switch (Sentence.charAt(i)) {
        case '1':
            build.append("a");
            break;
        case '2':
            build.append("b");
            break;
        case '3':
            build.append("c");
            break;
        case '4':
            build.append("d");
            break;
        case '5':
            build.append("e");
            break;
        case '6':
            build.append("f");
            break;
        case '7':
            build.append("g");
            break;
        case '8':
            build.append("h");
            break;
        case '9':
            build.append("i");
            break;
        case (
            '1.0'):
            build.append("j");
            break;
        case "1.1":
            build.append("k");
            break;
        case "1.2":
            build.append("l");
            break;
        case "1.3":
            build.append("m");
            break;
        case "1.4":
            build.append("n");
            break;
        case "1.5":
            build.append("o");
            break;
        case "1.6":
            build.append("p");
            break;
        case "1.7":
            build.append("q");
            break;
        case "1.8":
            build.append("r");
            break;
        case "1.9":
            build.append("s");
            break;
        case "2.0":
            build.append("t");
            break;
        case "2.1":
            build.append("u");
            break;
        case "2.2":
            build.append("v");
            break;
        case "2.3":
            build.append("w");
            break;
        case "2.4":
            build.append("x");
            break;
        case "2.5":
            build.append("y");
            break;
        case "2.6":
            build.append("z");
            break;
        case '?':
            build.append(" ");
            break;
        case '*':
            build.append(",");
            break;
        case "'\'":
            build.append('.');
            break;
        default:

            break;
    }

Seriously any help will be appreciated. Thanks

Body:
To modify it quickly to working version - just convert your char to String and use it in switch:

 switch ("" + Sentence.charAt(i)) {
    case "a": // "a" is a String now
...


答:
You can execute the following command to get location of data folder</p>

```<code>SHOW VARIABLES WHERE Variable_name LIKE '%dir'
</code>```

Title: MySQL does not seem to store databases anywhere

Body: The MySQL command line works fine and connects well to PHP. However, the databases don't seem to be stored anywhere in the computer. I tried looking in C:\Program Files\MySQL\MySQL Server 5.7\ for the data folder, but there is none. I don't know if this is actually a problem or not but it is worrying me. Any help would be greatly appreciated.

Body:
You can execute the following command to get location of data folder

SHOW VARIABLES WHERE Variable_name LIKE '%dir'


问:
How do I wait for a SwingWorker's doInBackground() method?
Say I have the following code:

```<code>import java.lang.InterruptedException;
import javax.swing.SwingWorker;

public class Test
{
    private JDialog window;

    public Test
    {
        // instantiate window
    }

    private class Task extends SwingWorker<Void, Void>
    {
        public Void doInBackground()
        {
            try { Thread.currentThread().sleep(5000); }
            catch(InterruptedException e) {}
            return null;
        }
    }

    public void doTask()
    {
        Task task = new Task();
        task.execute();
    }

    protected void process()
    {
        // update various GUI components here
    }

    public static void main(String args[])
    {
        Test t = new Test();
        t.doTask();
        System.out.println("done");
    }
}
</code>```

I need to wait until t.doTask() is done before printing out 'done', but I'm not sure exactly how.  I know I should probably use join() here, but I need a thread to call it on, and I don't know how to get doInBackground()'s thread from where I need to call join().  Thanks for any help.

EDIT:  Thanks for the responses.  Unfortunately, get() and the like don't quite solve the problem.  In my actual code, the SwingWorker also has an overridden process() function that updates a GUI window while the background thread is running.  get() does stop 'done' from being printed till after doInBackground, but then the GUI doesn't update.  I updated my sample code to reflect this, although now of course it won't compile.

Is there a way to get 'done' to print only once doInBackground is finished?  Are the GUI update code and the 'done' statement on the same thread?  Do I need to make a new thread?

答:
You can override the done() method, which is called when the doInBackground() is complete.  The done() method is called on EDT.  So something like:

```<code>@Override
protected void done() {
  try {
    super.get();

    System.out.println("done");
    //can call other gui update code here
  } catch (Throwable t) {
    //do something with the exception
  }
}
</code>```

Calling the get() method inside the done helps get back any exceptions that were thrown during the doInBackground, so I highly recommend it.  SwingWorker uses Callable and Future internally to manage the background thread, which you might want to read up on instead of trying the join/yield approach.

Body:
Say I have the following code:

import java.lang.InterruptedException;
import javax.swing.SwingWorker;

public class Test
{
    private JDialog window;

    public Test
    {
        // instantiate window
    }

    private class Task extends SwingWorker<Void, Void>
    {
        public Void doInBackground()
        {
            try { Thread.currentThread().sleep(5000); }
            catch(InterruptedException e) {}
            return null;
        }
    }

    public void doTask()
    {
        Task task = new Task();
        task.execute();
    }

    protected void process()
    {
        // update various GUI components here
    }

    public static void main(String args[])
    {
        Test t = new Test();
        t.doTask();
        System.out.println("done");
    }
}

I need to wait until t.doTask() is done before printing out 'done', but I'm not sure exactly how.  I know I should probably use join() here, but I need a thread to call it on, and I don't know how to get doInBackground()'s thread from where I need to call join().  Thanks for any help.

EDIT:  Thanks for the responses.  Unfortunately, get() and the like don't quite solve the problem.  In my actual code, the SwingWorker also has an overridden process() function that updates a GUI window while the background thread is running.  get() does stop 'done' from being printed till after doInBackground, but then the GUI doesn't update.  I updated my sample code to reflect this, although now of course it won't compile.

Is there a way to get 'done' to print only once doInBackground is finished?  Are the GUI update code and the 'done' statement on the same thread?  Do I need to make a new thread?

Body:
You can override the done() method, which is called when the doInBackground() is complete.  The done() method is called on EDT.  So something like:

@Override
protected void done() {
  try {
    super.get();

    System.out.println("done");
    //can call other gui update code here
  } catch (Throwable t) {
    //do something with the exception
  }
}

Calling the get() method inside the done helps get back any exceptions that were thrown during the doInBackground, so I highly recommend it.  SwingWorker uses Callable and Future internally to manage the background thread, which you might want to read up on instead of trying the join/yield approach.


问:
PHP calling out query with method
I am trying to call out method with query, but I can't get it working. I am probably calling it out wrong.

if (!empty($picturename) && !empty($productID)) {

 Product::set_main_pic($picturename, $productID);

}```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>public static function set_main_pic($picturename, $productID) {
        global $database;

        if(empty(($picturename) && empty($productID))) {
            return false;
        }

             $query = "UPDATE "
            . PX . self::$table_name
            . "SET main_picture = '" . $database->escape_value($picturename) . "' WHERE ID = " . $database->escape_value($productID);

            $database->query($query);

    }</code>```

答:
You must add  a space before SET be sure for self::$table_name</p>

```<code>$query = "UPDATE "
        . PX . self::$table_name
        . " SET main_picture = " . $database->escape_value($picturename) . " WHERE ID = " . $database->escape_value($productID)
</code>```

Title: PHP calling out query with method

Body:
I am trying to call out method with query, but I can't get it working. I am probably calling it out wrong.

if (!empty($picturename) && !empty($productID)) {

 Product::set_main_pic($picturename, $productID);

}

public static function set_main_pic($picturename, $productID) {
        global $database;

        if(empty(($picturename) && empty($productID))) {
            return false;
        }

             $query = "UPDATE "
            . PX . self::$table_name
            . "SET main_picture = '" . $database->escape_value($picturename) . "' WHERE ID = " . $database->escape_value($productID);

            $database->query($query);

    }

Body:
You must add  a space before SET be sure for self::$table_name

$query = "UPDATE "
        . PX . self::$table_name
        . " SET main_picture = " . $database->escape_value($picturename) . " WHERE ID = " . $database->escape_value($productID)


问:
Windows build and action “Goto was unexpected at this time”
Hoping for some assistance explaining and verifing this script I am getting an error "goto was unexpected at this time" </p>

<p>I attempting to created a script that gets the windows version number...  depending on the version number if its higher or equals then x it has to goto action 1 (FTRDWIN8) and when the version number is less then x it has to goto action 2 </p>

```<code>@echo off

::parsing the output of "ver" to getting windows version number
::excuting.

set strbuild=6.2

for /f "tokens=4-5 delims=. " %%i in ('ver') do set VERSION=%%i.%%j
if "%version%" geq "%strbuild%" goto FTRDWIN8
if "%version%" lss "%strbuild%" goto FTRDWINXPVI7

:FTRDWIN8
"C:\Windows\write.exe"
exit

:FTRDWINXPVI7
"C:\Windows\notepad.exe"
exit
</code>```

答:
If only compares strings or integers; any non numeric char forces string comparison on a char by char base and then 10.0 is less than 8.1

This slightly changed batch

```<code>@echo on
set strbuild=6.2

for /f "tokens=4-5 delims=. " %%i in ('ver') do set VERSION=%%i.%%j
if "%version%" geq "%strbuild%" goto FTRDWIN8
if "%version%" lss "%strbuild%" goto FTRDWINXPVI7

Goto :eof
:FTRDWIN8
"C:\Windows\write.exe"
Exit

:FTRDWINXPVI7
"C:\Windows\notepad.exe"
Exit
</code>```

has this transcript with echo on:

```<code>set strbuild=6.2
for /F "tokens=4-5 delims=. " %i in ('ver') do set VERSION=%i.%j
set VERSION=10.0
if "10.0 " GEQ "6.2" goto FTRDWIN8
if "10.0 " LSS "6.2" goto FTRDWINXPVI7
"C:\Windows\notepad.exe"
Goto :Eof
</code>```

Body:
Hoping for some assistance explaining and verifing this script I am getting an error "goto was unexpected at this time"

I attempting to created a script that gets the windows version number...  depending on the version number if its higher or equals then x it has to goto action 1 (FTRDWIN8) and when the version number is less then x it has to goto action 2

@echo off

::parsing the output of "ver" to getting windows version number
::excuting.

set strbuild=6.2

for /f "tokens=4-5 delims=. " %%i in ('ver') do set VERSION=%%i.%%j
if "%version%" geq "%strbuild%" goto FTRDWIN8
if "%version%" lss "%strbuild%" goto FTRDWINXPVI7

:FTRDWIN8
"C:\Windows\write.exe"
exit

:FTRDWINXPVI7
"C:\Windows\notepad.exe"
exit

Body:
If only compares strings or integers; any non numeric char forces string comparison on a char by char base and then 10.0 is less than 8.1

This slightly changed batch

@echo on
set strbuild=6.2

for /f "tokens=4-5 delims=. " %%i in ('ver') do set VERSION=%%i.%%j
if "%version%" geq "%strbuild%" goto FTRDWIN8
if "%version%" lss "%strbuild%" goto FTRDWINXPVI7

Goto :eof
:FTRDWIN8
"C:\Windows\write.exe"
Exit

:FTRDWINXPVI7
"C:\Windows\notepad.exe"
Exit

has this transcript with echo on:

set strbuild=6.2
for /F "tokens=4-5 delims=. " %i in ('ver') do set VERSION=%i.%j
set VERSION=10.0
if "10.0 " GEQ "6.2" goto FTRDWIN8
if "10.0 " LSS "6.2" goto FTRDWINXPVI7
"C:\Windows\notepad.exe"
Goto :Eof


问:
Easy way of representing multiple inputs in keras?
I am working on a CNN implementation in which there are multiple (72) inputs.

Each input is processed the same way, and then they are concatenated together.

Currently, I've written out each input and the process for the 72 which not only looks ugly, but takes up a lot of space (size vs. function).

Is it possible to define multiple outputs using some for loop structure?

I simple need to do this:

```<code>input = Input(shape(1,78,3))
conv_1_0 = Conv1D(filters = 32, kernel_size = (1,6) , padding = "same" , activation = "relu" , name = "conv_1d_1_0")(input)
</code>```

for 72 different inputs, but all the inputs have the same shape.

currently, I have

```<code>input0 = Input(shape(1,78,3))
input1 = Input(shape(1,78,3))
input2 = Input(shape(1,78,3))

conv_1_0 = Conv1D(filters = 32, kernel_size = (1,6) , padding = "same" , activation = "relu" , name = "conv_1d_1_0")(input0)
conv_1_1 = Conv1D(filters = 32, kernel_size = (1,6) , padding = "same" , activation = "relu" , name = "conv_1d_1_1")(input1)
conv_1_2 = Conv1D(filters = 32, kernel_size = (1,6) , padding = "same" , activation = "relu" , name = "conv_1d_1_1")(input2)
</code>```

..

Is it possible to do it in some for loop in keras?

答:
```<code>inputs_list = [Input(shape=(1,78,3)) for i in range(72)]
conv_1_list = [Conv1D(filters = 32, kernel_size = (1,6) , padding = "same" , activation = "relu" , name = "conv_1d_1_0")(input_tensor) for input_tensor in inputs_list]
</code>```

Does that work? :-)

Body:
I am working on a CNN implementation in which there are multiple (72) inputs.

Each input is processed the same way, and then they are concatenated together.

Currently, I've written out each input and the process for the 72 which not only looks ugly, but takes up a lot of space (size vs. function).

Is it possible to define multiple outputs using some for loop structure?

I simple need to do this:

input = Input(shape(1,78,3))
conv_1_0 = Conv1D(filters = 32, kernel_size = (1,6) , padding = "same" , activation = "relu" , name = "conv_1d_1_0")(input)

for 72 different inputs, but all the inputs have the same shape.

currently, I have

input0 = Input(shape(1,78,3))
input1 = Input(shape(1,78,3))
input2 = Input(shape(1,78,3))

conv_1_0 = Conv1D(filters = 32, kernel_size = (1,6) , padding = "same" , activation = "relu" , name = "conv_1d_1_0")(input0)
conv_1_1 = Conv1D(filters = 32, kernel_size = (1,6) , padding = "same" , activation = "relu" , name = "conv_1d_1_1")(input1)
conv_1_2 = Conv1D(filters = 32, kernel_size = (1,6) , padding = "same" , activation = "relu" , name = "conv_1d_1_1")(input2)

..

Is it possible to do it in some for loop in keras?

Body:
inputs_list = [Input(shape=(1,78,3)) for i in range(72)]
conv_1_list = [Conv1D(filters = 32, kernel_size = (1,6) , padding = "same" , activation = "relu" , name = "conv_1d_1_0")(input_tensor) for input_tensor in inputs_list]

Does that work? :-)


问:
Scala - xml transform throws away transformed elements with multiple attributes
Bit of a bizarre one, this, and I'm tempted to assume it may be a bug. Background - I have a whole load of XML that looks like this:

```<code><foo id="1">
 <bar id="0">
  <baz id="0" blah="blah" etc="etc">
   <buz id="0" />
  </baz>
  <buz id="0" blah="blah" etc="etc">
   ...
  </buz>
 </bar>
</foo>
<foo id="2">
 <bar id="0">
  <baz id="0" blah="blah" etc="etc">
   <buz id="0" />
  </baz>
  <buz id="0" blah="blah" etc="etc">
   ...
  </buz>
 </bar>
</foo>
....
</code>```

What I want to do is to transform this such that, for each foo element, I replace all the zero ids inside it with the id of foo.

To do this - firstly, I'm using Daniel's code along with an implicit conversion to provide 'Elem' with a mapAttributes method:

```<code>class ElemWithUsefulAttributes(elem : Elem) extends Elem(elem.prefix, elem.label, elem.attributes, elem.scope, elem.child : _*) {
def mapAttributes(f : GenAttr => GenAttr) = this.copy(attributes = mapMetaData(elem.attributes)(f))
}

implicit def Elem2ElemWithUsefulAttributes(elem : Elem) = new ElemWithUsefulAttributes(elem)
</code>```

Then I've got a 'replaceId' method:

```<code>def replaceId(attr : String, id : String)(in : GenAttr) = in match {
  case g@GenAttr(_,key,Text(v),_) if (key.equals(attr)) => g.copy(value=Text(id))
  case other => other
}
</code>```

Finally, I construct a couple of RewriteRules and corresponding RuleTransformers to deal with this:

```<code>class rw1(id : String) extends RewriteRule {
  override def transform(n : Node) : Seq[Node] = n match {
    case n2: Elem if (n2.label == "bar") => n2.mapAttributes(replaceId("id", id))
    case n2: Elem if (n2.label == "baz") => n2.mapAttributes(replaceId("id", id))
    case n2: Elem if (n2.label == "buz") => n2.mapAttributes(replaceId("id", id))
    case other => other
  }
}
class rt1(id : String) extends RuleTransformer(new rw1(id))
object rw2 extends RewriteRule {
  override def transform(n : Node) : Seq[Node] = n match {
    case n2@Elem(_, "foo", _, _, _*) => (new rw1(n2.attribute("id").get.toString))(n2)
    case other => other
  }
}
val rt2 = new RuleTransformer(rw2)
</code>```

After calling rt2(xml), I get output that looks like the following:

```<code><foo id="1">
 <bar id="1">
  <baz id="0" blah="blah" etc="etc">
   <buz id="1" />
  </baz>
  <buz id="0" blah="blah" etc="etc">
   ...
  </buz>
 </bar>
</foo>
<foo id="2">
 <bar id="2">
  <baz id="0" blah="blah" etc="etc">
   <buz id="2" />
  </baz>
  <buz id="0" blah="blah" etc="etc">
   ...
  </buz>
 </bar>
</foo>
....
</code>```

In other words, the attributes haven't been changed where there are multiple attributes. Naturally, one wants to suppose this is a problem with the mapAttributes code - however, if I dump out the results of the transform in the 'match' statement in rw1, I can clearly see it showing:

```<code>  <baz id="2" blah="blah" etc="etc">
   <buz id="2" />
  </baz>
</code>```

Further, if I alter a single baz, say, to remove the extra attributes then it works correctly and gets mapped. So it seems to be a strange combination of the multiple attributes and the transforms.

Can anybody make head or tail of this?

答:
The problem might be here:

```<code>case other => other
</code>```

Instead, try:

```<code>case elem: Elem => elem.copy(child = transform(elem.child))
case other => other
</code>```

I'm wondering if the library wasn't broken between 2.7 and 2.8, making transform not recurse automatically into each child. I have to look that up someday (though, of course, other eyes are welcome :).

Body:
Bit of a bizarre one, this, and I'm tempted to assume it may be a bug. Background - I have a whole load of XML that looks like this:

<foo id="1">
 <bar id="0">
  <baz id="0" blah="blah" etc="etc">
   <buz id="0" />
  </baz>
  <buz id="0" blah="blah" etc="etc">
   ...
  </buz>
 </bar>
</foo>
<foo id="2">
 <bar id="0">
  <baz id="0" blah="blah" etc="etc">
   <buz id="0" />
  </baz>
  <buz id="0" blah="blah" etc="etc">
   ...
  </buz>
 </bar>
</foo>
....

What I want to do is to transform this such that, for each foo element, I replace all the zero ids inside it with the id of foo.

To do this - firstly, I'm using Daniel's code along with an implicit conversion to provide 'Elem' with a mapAttributes method:

class ElemWithUsefulAttributes(elem : Elem) extends Elem(elem.prefix, elem.label, elem.attributes, elem.scope, elem.child : _*) {
def mapAttributes(f : GenAttr => GenAttr) = this.copy(attributes = mapMetaData(elem.attributes)(f))
}

implicit def Elem2ElemWithUsefulAttributes(elem : Elem) = new ElemWithUsefulAttributes(elem)

Then I've got a 'replaceId' method:

def replaceId(attr : String, id : String)(in : GenAttr) = in match {
  case g@GenAttr(_,key,Text(v),_) if (key.equals(attr)) => g.copy(value=Text(id))
  case other => other
}

Finally, I construct a couple of RewriteRules and corresponding RuleTransformers to deal with this:

class rw1(id : String) extends RewriteRule {
  override def transform(n : Node) : Seq[Node] = n match {
    case n2: Elem if (n2.label == "bar") => n2.mapAttributes(replaceId("id", id))
    case n2: Elem if (n2.label == "baz") => n2.mapAttributes(replaceId("id", id))
    case n2: Elem if (n2.label == "buz") => n2.mapAttributes(replaceId("id", id))
    case other => other
  }
}
class rt1(id : String) extends RuleTransformer(new rw1(id))
object rw2 extends RewriteRule {
  override def transform(n : Node) : Seq[Node] = n match {
    case n2@Elem(_, "foo", _, _, _*) => (new rw1(n2.attribute("id").get.toString))(n2)
    case other => other
  }
}
val rt2 = new RuleTransformer(rw2)

After calling rt2(xml), I get output that looks like the following:

<foo id="1">
 <bar id="1">
  <baz id="0" blah="blah" etc="etc">
   <buz id="1" />
  </baz>
  <buz id="0" blah="blah" etc="etc">
   ...
  </buz>
 </bar>
</foo>
<foo id="2">
 <bar id="2">
  <baz id="0" blah="blah" etc="etc">
   <buz id="2" />
  </baz>
  <buz id="0" blah="blah" etc="etc">
   ...
  </buz>
 </bar>
</foo>
....

In other words, the attributes haven't been changed where there are multiple attributes. Naturally, one wants to suppose this is a problem with the mapAttributes code - however, if I dump out the results of the transform in the 'match' statement in rw1, I can clearly see it showing:

  <baz id="2" blah="blah" etc="etc">
   <buz id="2" />
  </baz>

Further, if I alter a single baz, say, to remove the extra attributes then it works correctly and gets mapped. So it seems to be a strange combination of the multiple attributes and the transforms.

Can anybody make head or tail of this?

Body:
The problem might be here:

case other => other

Instead, try:

case elem: Elem => elem.copy(child = transform(elem.child))
case other => other

I'm wondering if the library wasn't broken between 2.7 and 2.8, making transform not recurse automatically into each child. I have to look that up someday (though, of course, other eyes are welcome :).


问:
Java weird compilation error with raw generic type parameter and Optionals
The following Java code doesn't compile (using javac 1.8.0_121)

```<code>import java.util.Optional;

class B<T> {}

public class Test {
    static B<Integer> f1(B<Object> a) { return null; }

    static B<Integer> f2() {
       Optional<B> opt = Optional.empty(); // note the raw type B
       return opt.map(Test::f1).get();
       // error: incompatible types: Object cannot be converted to B<Integer>
    }
}
</code>```

My question is: Why doesn't the code compile as above, and why does it compile if I change f1 to take a raw type:

```<code>static B<Integer> f1(B a) { return null; } // program compiles with raw B
</code>```

My guess is that opt.map is inferred as returning Optional<Object> (instead of Optional<B<Integer>>) but why? I have looked at other issues with generics and type erasure (JLS 4.8), but they all deal with the situation when a method is called on a raw type itself (e.g. this). Here, opt is not raw, it only takes a raw type parameter. Also, why does the second version (where parameter a is raw B instead of B<Object>) work?

Compilation Error Message

Error java: incompatible types: java.lang.Object cannot be converted to B<java.lang.Integer>

答:
Make the f1 use a ? extends Object, add a wildcard type to B.

```<code>import java.util.Optional;

class B<T> {}

public class Test {
   static B<Integer> f1(B<? extends Object> a) { return null; }

   static B<Integer> f2() {
       Optional<B<?>> opt = Optional.empty(); // note the raw type B
       return opt.map(x -> f1(x)).get();
    }
}
</code>```

Body:
The following Java code doesn't compile (using javac 1.8.0_121)

import java.util.Optional;

class B<T> {}

public class Test {
    static B<Integer> f1(B<Object> a) { return null; }

    static B<Integer> f2() {
       Optional opt = Optional.empty(); // note the raw type B
       return opt.map(Test::f1).get();
       // error: incompatible types: Object cannot be converted to B<Integer>
    }
}

My question is: Why doesn't the code compile as above, and why does it compile if I change f1 to take a raw type:

static B<Integer> f1(B a) { return null; } // program compiles with raw B

My guess is that opt.map is inferred as returning Optional<Object> (instead of Optional<B<Integer>>) but why? I have looked at other issues with generics and type erasure (JLS 4.8), but they all deal with the situation when a method is called on a raw type itself (e.g. this). Here, opt is not raw, it only takes a raw type parameter. Also, why does the second version (where parameter a is raw B instead of B<Object>) work?

Compilation Error Message

Error java: incompatible types: java.lang.Object cannot be converted to B<java.lang.Integer>

Body:
Make the f1 use a ? extends Object, add a wildcard type to B.

import java.util.Optional;

class B<T> {}

public class Test {
   static B<Integer> f1(B<? extends Object> a) { return null; }

   static B<Integer> f2() {
       Optional<B<?>> opt = Optional.empty(); // note the raw type B
       return opt.map(x -> f1(x)).get();
    }
}


问:
How to prevent game-client from sending fake player ID?
I am writing a game client/server. I use Artemis-odb and Netty to handle entities and networking. Each registered player is assigned an auto increment ID from the database. This ID is associated wth every client/server event.

I want to prevent the client from easy ID spoofing to stop account hijacking. In theory, what is the best practice to prevent this?

The game/client does not use UUID, but could if this is the best option.

Thank you!

答:
The player ID should be associated with the network connection context for that player (the socket if you're using TCP or the IP:PORT pair if UDP) on the server.

The client should never need send the ID back to the server since the server should know what the ID is.  As long as the server can associate incoming network packets with the player's context, there's no practical risk of spoofing, although I think the risk could be a bit higher with UDP.  But again a practical exploit would be unlikely as long as you include sequence numbers with the packets.

I know of no major network games that actually use full UUIDs as player identifiers in client-server protocols.


问:
Express.js req.body undefined
I have this as configuration of my Express server

```<code>app.use(app.router);
app.use(express.cookieParser());
app.use(express.session({ secret: "keyboard cat" }));
app.set('view engine', 'ejs');
app.set("view options", { layout: true });
//Handles post requests
app.use(express.bodyParser());
//Handles put requests
app.use(express.methodOverride());
</code>```

But still when I ask for req.body.something in my routes I get some error pointing out that body is undefined. Here is an example of a route that uses req.body :

```<code>app.post('/admin', function(req, res){
    console.log(req.body.name);
});
</code>```

I read that this problem is caused by the lack of app.use(express.bodyParser()); but as you can see I call it before the routes.

Any clue?

答:
```<code>// Require body-parser (to receive post data from clients)

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json

app.use(bodyParser.json())
</code>```

Title: Express.js req.body undefined

Body:
I have this as configuration of my Express server

app.use(app.router);
app.use(express.cookieParser());
app.use(express.session({ secret: "keyboard cat" }));
app.set('view engine', 'ejs');
app.set("view options", { layout: true });
//Handles post requests
app.use(express.bodyParser());
//Handles put requests
app.use(express.methodOverride());

But still when I ask for req.body.something in my routes I get some error pointing out that body is undefined. Here is an example of a route that uses req.body :

app.post('/admin', function(req, res){
    console.log(req.body.name);
});

I read that this problem is caused by the lack of app.use(express.bodyParser()); but as you can see I call it before the routes.

Any clue?